hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 | qsc_code_num_words_quality_signal int64 | qsc_code_num_chars_quality_signal float64 | qsc_code_mean_word_length_quality_signal float64 | qsc_code_frac_words_unique_quality_signal float64 | qsc_code_frac_chars_top_2grams_quality_signal float64 | qsc_code_frac_chars_top_3grams_quality_signal float64 | qsc_code_frac_chars_top_4grams_quality_signal float64 | qsc_code_frac_chars_dupe_5grams_quality_signal float64 | qsc_code_frac_chars_dupe_6grams_quality_signal float64 | qsc_code_frac_chars_dupe_7grams_quality_signal float64 | qsc_code_frac_chars_dupe_8grams_quality_signal float64 | qsc_code_frac_chars_dupe_9grams_quality_signal float64 | qsc_code_frac_chars_dupe_10grams_quality_signal float64 | qsc_code_frac_chars_replacement_symbols_quality_signal float64 | qsc_code_frac_chars_digital_quality_signal float64 | qsc_code_frac_chars_whitespace_quality_signal float64 | qsc_code_size_file_byte_quality_signal float64 | qsc_code_num_lines_quality_signal float64 | qsc_code_num_chars_line_max_quality_signal float64 | qsc_code_num_chars_line_mean_quality_signal float64 | qsc_code_frac_chars_alphabet_quality_signal float64 | qsc_code_frac_chars_comments_quality_signal float64 | qsc_code_cate_xml_start_quality_signal float64 | qsc_code_frac_lines_dupe_lines_quality_signal float64 | qsc_code_cate_autogen_quality_signal float64 | qsc_code_frac_lines_long_string_quality_signal float64 | qsc_code_frac_chars_string_length_quality_signal float64 | qsc_code_frac_chars_long_word_length_quality_signal float64 | qsc_code_frac_lines_string_concat_quality_signal float64 | qsc_code_cate_encoded_data_quality_signal float64 | qsc_code_frac_chars_hex_words_quality_signal float64 | qsc_code_frac_lines_prompt_comments_quality_signal float64 | qsc_code_frac_lines_assert_quality_signal float64 | qsc_codepython_cate_ast_quality_signal float64 | qsc_codepython_frac_lines_func_ratio_quality_signal float64 | qsc_codepython_cate_var_zero_quality_signal bool | qsc_codepython_frac_lines_pass_quality_signal float64 | qsc_codepython_frac_lines_import_quality_signal float64 | qsc_codepython_frac_lines_simplefunc_quality_signal float64 | qsc_codepython_score_lines_no_logic_quality_signal float64 | qsc_codepython_frac_lines_print_quality_signal float64 | qsc_code_num_words int64 | qsc_code_num_chars int64 | qsc_code_mean_word_length int64 | qsc_code_frac_words_unique null | qsc_code_frac_chars_top_2grams int64 | qsc_code_frac_chars_top_3grams int64 | qsc_code_frac_chars_top_4grams int64 | qsc_code_frac_chars_dupe_5grams int64 | qsc_code_frac_chars_dupe_6grams int64 | qsc_code_frac_chars_dupe_7grams int64 | qsc_code_frac_chars_dupe_8grams int64 | qsc_code_frac_chars_dupe_9grams int64 | qsc_code_frac_chars_dupe_10grams int64 | qsc_code_frac_chars_replacement_symbols int64 | qsc_code_frac_chars_digital int64 | qsc_code_frac_chars_whitespace int64 | qsc_code_size_file_byte int64 | qsc_code_num_lines int64 | qsc_code_num_chars_line_max int64 | qsc_code_num_chars_line_mean int64 | qsc_code_frac_chars_alphabet int64 | qsc_code_frac_chars_comments int64 | qsc_code_cate_xml_start int64 | qsc_code_frac_lines_dupe_lines int64 | qsc_code_cate_autogen int64 | qsc_code_frac_lines_long_string int64 | qsc_code_frac_chars_string_length int64 | qsc_code_frac_chars_long_word_length int64 | qsc_code_frac_lines_string_concat null | qsc_code_cate_encoded_data int64 | qsc_code_frac_chars_hex_words int64 | qsc_code_frac_lines_prompt_comments int64 | qsc_code_frac_lines_assert int64 | qsc_codepython_cate_ast int64 | qsc_codepython_frac_lines_func_ratio int64 | qsc_codepython_cate_var_zero int64 | qsc_codepython_frac_lines_pass int64 | qsc_codepython_frac_lines_import int64 | qsc_codepython_frac_lines_simplefunc int64 | qsc_codepython_score_lines_no_logic int64 | qsc_codepython_frac_lines_print int64 | effective string | hits int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
54a74660981b328f1918b126d52b142aa89751d0 | 142 | py | Python | config/api/consumer.py | codertheory/backend | 66017e4f484414b878d2a6e78fa623870aa38cfb | [
"MIT"
] | null | null | null | config/api/consumer.py | codertheory/backend | 66017e4f484414b878d2a6e78fa623870aa38cfb | [
"MIT"
] | null | null | null | config/api/consumer.py | codertheory/backend | 66017e4f484414b878d2a6e78fa623870aa38cfb | [
"MIT"
] | null | null | null | import channels_graphql_ws
from config.api import schema
class GraphQLConsumer(channels_graphql_ws.GraphqlWsConsumer):
schema = schema
| 17.75 | 61 | 0.830986 | 17 | 142 | 6.705882 | 0.647059 | 0.263158 | 0.298246 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.126761 | 142 | 7 | 62 | 20.285714 | 0.919355 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.5 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
54c83b0d494fce732af7deabd9a481a7d5a872d6 | 2,328 | py | Python | leetcode/tree/medium/max_level_sum_of_bt/tests/test_my_answer.py | BillionsRichard/pycharmWorkspace | 709e2681fc6d85ff52fb25717215a365f51073aa | [
"Apache-2.0"
] | null | null | null | leetcode/tree/medium/max_level_sum_of_bt/tests/test_my_answer.py | BillionsRichard/pycharmWorkspace | 709e2681fc6d85ff52fb25717215a365f51073aa | [
"Apache-2.0"
] | null | null | null | leetcode/tree/medium/max_level_sum_of_bt/tests/test_my_answer.py | BillionsRichard/pycharmWorkspace | 709e2681fc6d85ff52fb25717215a365f51073aa | [
"Apache-2.0"
] | null | null | null | # encoding: utf-8
"""
@version: v1.0
@author: Richard
@license: Apache Licence
@contact: billions.richard@qq.com
@site:
@software: PyCharm
@time: 2019/10/1 20:53
"""
from pprint import pprint as pp
from tree.medium.max_level_sum_of_bt.srcs.my_answer import TreeNode
from tree.medium.max_level_sum_of_bt.srcs.my_answer import Solution
import unittest
class TestMaxLevelSum(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_1(self):
r = TreeNode(1)
r.left = TreeNode(7)
r.right = TreeNode(0)
r.left.left = TreeNode(7)
r.left.right = TreeNode(-8)
s = Solution()
exp = 2
act = s.maxLevelSum(r)
self.assertEqual(exp, act)
def test_2(self):
r = TreeNode(1)
r.left = TreeNode(7)
r.right = TreeNode(0)
r.left.left = TreeNode(7)
r.left.right = TreeNode(-8)
r.right.left = TreeNode(7)
s = Solution()
exp = 2
act = s.maxLevelSum(r)
self.assertEqual(exp, act)
def test_3(self):
r = TreeNode(1)
r.left = TreeNode(7)
r.right = TreeNode(0)
r.left.left = TreeNode(7)
r.left.right = TreeNode(-8)
r.right.left = TreeNode(8)
print('level order traverse tree:', Solution.lvl_order_tree(r))
s = Solution()
exp = 2
act = s.maxLevelSum(r)
self.assertEqual(exp, act)
def test_4(self):
r = TreeNode(1)
r.left = TreeNode(7)
r.right = TreeNode(0)
r.left.left = TreeNode(7)
r.left.right = TreeNode(-8)
r.right.left = TreeNode(9)
print('level order traverse tree:', Solution.lvl_order_tree(r))
s = Solution()
exp = 3
act = s.maxLevelSum(r)
self.assertEqual(exp, act)
def test_5(self):
r = TreeNode(1)
r.left = TreeNode(7)
r.right = TreeNode(0)
r.left.left = TreeNode(7)
r.left.right = TreeNode(-8)
r.right.left = TreeNode(9)
r.right.left = TreeNode(9)
r.right.left.left = TreeNode(9)
print('level order traverse tree:', Solution.lvl_order_tree(r))
s = Solution()
exp = 4
act = s.maxLevelSum(r)
self.assertEqual(exp, act)
| 22.823529 | 71 | 0.562715 | 317 | 2,328 | 4.066246 | 0.217666 | 0.148953 | 0.110939 | 0.108611 | 0.799069 | 0.799069 | 0.799069 | 0.799069 | 0.747867 | 0.747867 | 0 | 0.034354 | 0.312285 | 2,328 | 101 | 72 | 23.049505 | 0.770768 | 0.070447 | 0 | 0.75 | 0 | 0 | 0.036229 | 0 | 0 | 0 | 0 | 0 | 0.073529 | 1 | 0.102941 | false | 0.029412 | 0.058824 | 0 | 0.176471 | 0.058824 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
49d7da577f2143e4daef8dfa7bc6af0655fb0a0b | 107 | py | Python | wagtail/documents/api/admin/views.py | brownaa/wagtail | c97bc56c6822eb1b6589d5c33e07f71acfc48845 | [
"BSD-3-Clause"
] | 8,851 | 2016-12-09T19:01:45.000Z | 2022-03-31T04:45:06.000Z | wagtail/documents/api/admin/views.py | brownaa/wagtail | c97bc56c6822eb1b6589d5c33e07f71acfc48845 | [
"BSD-3-Clause"
] | 5,197 | 2016-12-09T19:24:37.000Z | 2022-03-31T22:17:55.000Z | wagtail/documents/api/admin/views.py | brownaa/wagtail | c97bc56c6822eb1b6589d5c33e07f71acfc48845 | [
"BSD-3-Clause"
] | 2,548 | 2016-12-09T18:16:55.000Z | 2022-03-31T21:34:38.000Z | from ..v2.views import DocumentsAPIViewSet
class DocumentsAdminAPIViewSet(DocumentsAPIViewSet):
pass
| 17.833333 | 52 | 0.82243 | 9 | 107 | 9.777778 | 0.888889 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.010638 | 0.121495 | 107 | 5 | 53 | 21.4 | 0.925532 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.333333 | 0.333333 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 6 |
49e3b8d956cafeb7c6c41b8fdd6401561c5d0d65 | 41,773 | py | Python | src/encoded/tests/test_reports_batch_download.py | ENCODE-DCC/encoded | 77688076259af7441a9ffc3e3104f115c988d8e9 | [
"MIT"
] | 102 | 2015-05-20T01:17:43.000Z | 2022-03-07T06:03:55.000Z | src/encoded/tests/test_reports_batch_download.py | ENCODE-DCC/encoded | 77688076259af7441a9ffc3e3104f115c988d8e9 | [
"MIT"
] | 901 | 2015-01-07T23:11:57.000Z | 2022-03-18T13:56:12.000Z | src/encoded/tests/test_reports_batch_download.py | ENCODE-DCC/encoded | 77688076259af7441a9ffc3e3104f115c988d8e9 | [
"MIT"
] | 65 | 2015-02-06T23:00:26.000Z | 2022-01-22T07:58:44.000Z | import pytest
from encoded.tests.features.conftest import app, app_settings, index_workbook
pytestmark = [
pytest.mark.indexing,
pytest.mark.usefixtures('index_workbook'),
]
def test_reports_batch_download_view(index_workbook, testapp):
r = testapp.get('/batch_download/?type=Experiment&status=released')
lines = r.text.split('\n')
assert lines[0] == (
'"http://localhost/metadata/?type=Experiment&status=released"'
)
assert len(lines) >= 79
assert 'http://localhost/files/ENCFF002MXF/@@download/ENCFF002MXF.fastq.gz' in lines
def test_reports_batch_download_header_and_rows(index_workbook, testapp):
results = testapp.get('/batch_download/?type=Experiment')
assert results.headers['Content-Type'] == 'text/plain; charset=UTF-8'
assert results.headers['Content-Disposition'] == 'attachment; filename="files.txt"'
lines = results.text.strip().split('\n')
assert len(lines) > 0
assert '/metadata/?type=Experiment' in lines[0]
for line in lines[1:]:
assert '@@download' in line, f'{line} not download'
def test_reports_batch_download_view_file_plus(index_workbook, testapp):
r = testapp.get(
'/batch_download/?type=Experiment&files.file_type=bigBed+bed3%2B&format=json'
)
lines = r.text.split('\n')
assert lines[0] == (
'"http://localhost/metadata/?type=Experiment&files.file_type=bigBed+bed3%2B&format=json"'
)
assert 'http://localhost/files/ENCFF880XNW/@@download/ENCFF880XNW.bigBed' in lines
def test_reports_batch_download_contains_all_values(index_workbook, testapp):
from pkg_resources import resource_filename
r = testapp.get('/batch_download/?type=Experiment')
actual = r.text.strip().split('\n')
expected_path = resource_filename('encoded', 'tests/data/inserts/expected_batch_download.tsv')
# To write new expected_batch_download.tsv change 'r' to 'w' and f.write(r.text); return;
with open(expected_path, 'r') as f:
expected = [x.strip() for x in f.readlines()]
assert set(actual) == set(expected), f'{set(actual) - set(expected)} not expected'
def test_reports_batch_download_contains_all_values_file_size_inequality(index_workbook, testapp):
from pkg_resources import resource_filename
r = testapp.get('/batch_download/?type=Experiment&files.file_size=lte:99')
actual = r.text.strip().split('\n')
expected_path = resource_filename('encoded', 'tests/data/inserts/expected_batch_download_file_size_inequality.tsv')
# To write new expected_batch_download.tsv change 'r' to 'w' and f.write(r.text); return;
with open(expected_path, 'r') as f:
expected = [x.strip() for x in f.readlines()]
assert set(actual) == set(expected), f'{set(actual) - set(expected)} not expected'
def test_reports_batch_download_contains_all_annotation_values(index_workbook, testapp):
from pkg_resources import resource_filename
r = testapp.get('/batch_download/?type=Annotation')
actual = r.text.strip().split('\n')
expected_path = resource_filename('encoded', 'tests/data/inserts/expected_annotation_batch_download.tsv')
# To write new expected_batch_download.tsv change 'r' to 'w' and f.write(r.text); return;
with open(expected_path, 'r') as f:
expected = [x.strip() for x in f.readlines()]
assert set(actual) == set(expected), f'{set(actual) - set(expected)} not expected'
def test_reports_batch_download_contains_all_publication_data_values(index_workbook, testapp):
from pkg_resources import resource_filename
r = testapp.get('/batch_download/?type=PublicationData&@id=/publication-data/ENCSR727WCB/')
actual = r.text.strip().split('\n')
expected_path = resource_filename('encoded', 'tests/data/inserts/expected_publication_data_batch_download.tsv')
# To write new expected_batch_download.tsv change 'r' to 'w' and f.write(r.text); return;
with open(expected_path, 'r') as f:
expected = [x.strip() for x in f.readlines()]
assert set(actual) == set(expected), f'{set(actual) - set(expected)} not expected'
def test_reports_batch_download_and_metadata_contain_same_number_of_results(index_workbook, testapp):
batch_download_results = testapp.get('/batch_download/?type=Experiment').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=Experiment').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=Experiment&files.file_format=bigWig').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=Experiment&files.file_format=bigWig').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=Experiment&files.file_format=bigWig&files.file_format=tsv').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=Experiment&files.file_format=bigWig&files.file_format=tsv').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=Experiment&files.status=released').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=Experiment&files.status=released').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=Experiment&files.file_type=bed+narrowPeak').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=Experiment&files.file_type=bed+narrowPeak').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=Experiment&files.file_type!=bed+narrowPeak').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=Experiment&files.file_type!=bed+narrowPeak').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=Experiment&files.assay_term_name=ChIP-seq').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=Experiment&files.assay_term_name=ChIP-seq').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=Experiment&files.biological_replicates=2').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=Experiment&files.biological_replicates=2').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
def test_reports_annotation_batch_download_and_metadata_contain_same_number_of_results(index_workbook, testapp):
batch_download_results = testapp.get('/batch_download/?type=Annotation').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=Annotation').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=Annotation&files.file_format=bigWig').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=Annotation&files.file_format=bigWig').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=Annotation&files.file_format=bigWig&files.file_format=tsv').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=Annotation&files.file_format=bigWig&files.file_format=tsv').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=Annotation&files.status=released').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=Annotation&files.status=released').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=Annotation&files.file_type=bed+bed3%2B').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=Annotation&files.file_type=bed+bed3%2B').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=Annotation&files.file_type!=bed+bed3%2B').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=Annotation&files.file_type!=bed+bed3%2B').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=Annotation&annotation_type=candidate+Cis-Regulatory+Elements').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=Annotation&annotation_type=candidate+Cis-Regulatory+Elements').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=Annotation&files.lab.title=John+Stamatoyannopoulos%2C+UW').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=Annotation&files.lab.title=John+Stamatoyannopoulos%2C+UW').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
def test_reports_publication_data_batch_download_and_metadata_contain_same_number_of_results(index_workbook, testapp):
batch_download_results = testapp.get('/batch_download/?type=PublicationData').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=PublicationData').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=PublicationData&files.file_format=tsv').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=PublicationData&files.file_format=tsv').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=PublicationData&files.file_format=hic&files.file_format=tsv').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=PublicationData&files.file_format=hic&files.file_format=tsv').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=PublicationData&files.status=released').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=PublicationData&files.status=released').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=PublicationData&files.file_type=bed+narrowPeak').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=PublicationData&files.file_type=bed+narrowPeak').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=PublicationData&files.file_type!=bed+narrowPeak').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=PublicationData&files.file_type!=bed+narrowPeak').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=PublicationData&files.assay_term_name=ChIP-seq').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=PublicationData&files.assay_term_name=ChIP-seq').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=PublicationData&files.file_size=2433593').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=PublicationData&files.file_size=2433593').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
def test_reports_series_batch_download_and_metadata_contain_same_number_of_results(index_workbook, testapp):
batch_download_results = testapp.get('/batch_download/?type=ReferenceEpigenome').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=ReferenceEpigenome').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=ReferenceEpigenome&related_datasets.files.preferred_default=true').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=ReferenceEpigenome&related_datasets.files.preferred_default=true').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
batch_download_results = testapp.get('/batch_download/?type=ReferenceEpigenome&related_datasets.files.preferred_default=true&related_datasets.files.output_type=signal+of+all+reads').text.strip().split('\n')
metadata_results = testapp.get('/metadata/?type=ReferenceEpigenome&related_datasets.files.preferred_default=true&related_datasets.files.output_type=signal+of+all+reads').text.strip().split('\n')
assert len(batch_download_results) > 1
assert len(metadata_results) == len(batch_download_results)
def get_batch_download_and_metadata_results(testapp, query_string):
batch_download_results = testapp.get(
'/batch_download/' + query_string
).text.strip().split('\n')
metadata_results = testapp.get(
'/metadata/' + query_string
).text.strip().split('\n')
return batch_download_results, metadata_results
def test_reports_batch_download_and_metadata_specific_filters(index_workbook, testapp):
query_string = (
'?type=Experiment&status=released'
'&perturbed=false&assay_title=DNase-seq'
'&files.run_type=single-ended&files.file_type=fastq'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
# Two results plus header.
assert len(batch_download_results) == len(metadata_results) == 3
query_string = (
'?type=Experiment&status=released'
'&perturbed=false&assay_title=DNase-seq'
'&files.run_type=single-ended'
'&files.file_type=fastq&assembly=GRCh38'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
query_string = (
'?type=Experiment&status=released'
'&perturbed=false&assay_title=DNase-seq'
'&files.run_type=single-ended'
'&files.file_type=fastq&files.assembly=GRCh38'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
# Header only, zero files.
assert len(batch_download_results) == len(metadata_results) == 1
query_string = (
'?type=Experiment&files.no_file_available=true'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 1
query_string = (
'?type=Experiment&files.restricted=true'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 1
query_string = (
'?type=Experiment&files.no_file_available=*&target.label=H3K4me3&biosample_ontology.term_name=K562'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
query_string = (
'?type=Experiment&files.no_file_available=*&target.label=H3K4me3&assembly=mm10'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 8
query_string = (
'?type=Experiment&files.no_file_available=*&target.label=H3K4me3&files.assembly=mm10'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
query_string = (
'?type=Experiment&files.no_file_available=false'
'&target.label=H3K4me3&assembly!=mm10'
'&target.label=TCF4&files.read_length=50'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 3
query_string = (
'?type=Experiment&files.no_file_available=false'
'&target.label=H3K4me3&assembly!=mm10'
'&target.label=TCF4&files.file_type=bam'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 5
query_string = (
'?type=Experiment&files.no_file_available=false'
'&target.label=H3K4me3&assembly!=mm10'
'&target.label=TCF4&files.file_type=bam'
'&lab.title=Sherman+Weissman%2C+Yale'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
query_string = (
'?type=Experiment&files.no_file_available=false'
'&target.label=H3K4me3&assembly!=mm10'
'&target.label=TCF4&files.file_type=bam'
'&lab.title=Sherman+Weissman%2C+Yale&status!=released'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 1
query_string = (
'?type=Experiment&files.replicate.library=/libraries/ENCLB058ZZZ/'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 5
query_string = (
'?type=Experiment&files.replicate.library=/libraries/ENCLB058ZZZ/'
'&files.file_type=bigWig'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 3
query_string = (
'?type=Experiment&files.replicate.library=/libraries/ENCLB058ZZZ/'
'&files.file_type=bigWig&option=visualizable'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 3
query_string = (
'?type=Experiment&files.replicate.library=/libraries/ENCLB058ZZZ/'
'&files.file_type=bigWig&option=raw'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 1
query_string = (
'?type=Experiment&files.replicate.library=/libraries/ENCLB058ZZZ/'
'&files.file_type=fastq&files.read_length=50'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
query_string = (
'?type=Experiment&files.replicate.library=/libraries/ENCLB058ZZZ/'
'&files.file_type=fastq&files.read_length=50&option=raw'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
query_string = (
'?type=Experiment&files.replicate.library=/libraries/ENCLB058ZZZ/'
'&files.file_type=fastq&files.read_length=50&option=visualizable'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp,query_string
)
assert len(batch_download_results) == len(metadata_results) == 1
query_string = (
'?type=Experiment&files.replicate.library=/libraries/ENCLB058ZZZ/'
'&files.file_type=fastq&files.read_length=50&option=visualizable'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 1
query_string = (
'?type=Experiment&files.derived_from=*&files.file_type=bam'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 13
query_string = (
'?type=Experiment&files.derived_from=*&files.file_type=bam&files.file_type=fastq'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 14
query_string = (
'?type=Experiment&files.file_type=bam&files.file_type=fastq'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 72
query_string = (
'?type=Experiment&files.derived_from=*&files.file_type=bam'
'&files.file_type=fastq&files.file_type=bigWig'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 21
query_string = (
'?type=Experiment&files.derived_from=*&files.file_type=bam'
'&files.file_type=fastq&files.file_type=bigWig&files.read_length=76'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
query_string = (
'?type=Experiment&files.derived_from=*&files.file_type=bam'
'&files.file_type=fastq&files.file_type=bigWig&files.read_length=76'
'&audit.NOT_COMPLIANT.category=missing+documents'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
def test_reports_annotation_batch_download_and_metadata_specific_filters(index_workbook, testapp):
query_string = (
'?type=Annotation&files.file_type=bed+enhancer+predictions'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
query_string = (
'?type=Annotation&files.file_type=bed+enhancer+predictions&files.assembly=mm10'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
query_string = (
'?type=Annotation&files.file_type=bed+enhancer+predictions&files.assembly!=mm10'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 1
query_string = (
'?type=Annotation&files.file_type=bed+enhancer+predictions&files.biosample_ontology=*'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
query_string = (
'?type=Annotation&files.file_type=bed+enhancer+predictions'
'&files.biosample_ontology=/biosample-types/tissue_UBERON_0000948/'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
query_string = (
'?type=Annotation&files.file_type=bed+enhancer+predictions'
'&files.biosample_ontology!=/biosample-types/tissue_UBERON_0000948/'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 1
query_string = (
'?type=Annotation&files.file_size=1544154147'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
query_string = (
'?type=Annotation&files.file_size=1544154147&files.assembly!=mm10'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 1
query_string = (
'?type=Annotation&files.file_size=1544154147&files.assembly=mm10'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
def test_reports_publication_data_batch_download_and_metadata_specific_filters(index_workbook, testapp):
query_string = (
'?type=PublicationData&files.dataset=/experiments/ENCSR000ADH/'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
query_string = (
'?type=PublicationData&files.dataset!=/experiments/ENCSR000ADH/'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 6
query_string = (
'?type=PublicationData&files.file_type=tsv'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 3
query_string = (
'?type=PublicationData&files.file_type=tsv&files.md5sum=69031443b66578d55b5c4a039d55cceb'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
query_string = (
'?type=PublicationData&files.file_type=tsv&files.md5sum=69031443b66578d55b5c4a039d55cceb'
'&files.file_size=984865'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 2
query_string = (
'?type=PublicationData&files.file_type=tsv&files.md5sum=69031443b66578d55b5c4a039d55cceb'
'&files.file_size=3838'
)
batch_download_results, metadata_results = get_batch_download_and_metadata_results(
testapp, query_string
)
assert len(batch_download_results) == len(metadata_results) == 1
def test_reports_batch_download_init_batch_download_mixin(dummy_request):
from encoded.reports.batch_download import BatchDownloadMixin
bdm = BatchDownloadMixin()
assert isinstance(bdm, BatchDownloadMixin)
def test_reports_batch_download_init_batch_download(dummy_request):
from encoded.reports.batch_download import BatchDownload
dummy_request.environ['QUERY_STRING'] = (
'type=Experiment&files.file_type=bigWig&files.file_type=bam'
'&files.replicate.library.size_range=50-100'
'&files.status!=archived&files.biological_replicates=2'
)
bd = BatchDownload(dummy_request)
assert isinstance(bd, BatchDownload)
def test_reports_batch_download_should_add_json_elements_to_metadata_link(dummy_request):
from encoded.reports.batch_download import BatchDownload
dummy_request.environ['QUERY_STRING'] = (
'type=Experiment&files.file_type=bigWig&files.file_type=bam'
'&files.replicate.library.size_range=50-100'
'&files.status!=archived&files.biological_replicates=2'
)
bd = BatchDownload(dummy_request)
assert not bd._should_add_json_elements_to_metadata_link()
dummy_request.json = {'elements': ['/experiments/ENCSR123ABC/']}
bd = BatchDownload(dummy_request)
assert bd._should_add_json_elements_to_metadata_link()
dummy_request.json = {'elements': []}
bd = BatchDownload(dummy_request)
assert not bd._should_add_json_elements_to_metadata_link()
dummy_request.environ['QUERY_STRING'] = (
'type=Experiment&files.file_type=bigWig&files.file_type=bam'
'&files.replicate.library.size_range=50-100'
'&files.status!=archived&files.biological_replicates=2'
'&cart=xyz123'
)
dummy_request.json = {
'elements': [
'/experiments/ENCSR123ABC/',
'/experiments/ENCSRDEF567/'
]
}
bd = BatchDownload(dummy_request)
assert not bd._should_add_json_elements_to_metadata_link()
def test_reports_batch_download_maybe_add_json_elements_to_metadata_link(dummy_request):
from encoded.reports.batch_download import BatchDownload
dummy_request.environ['QUERY_STRING'] = (
'type=Experiment&files.file_type=bigWig&files.file_type=bam'
'&files.replicate.library.size_range=50-100'
'&files.status!=archived&files.biological_replicates=2'
)
bd = BatchDownload(dummy_request)
metadata_link = bd._maybe_add_json_elements_to_metadata_link('')
assert metadata_link == ''
dummy_request.json = {'elements': ['/experiments/ENCSR123ABC/']}
bd = BatchDownload(dummy_request)
metadata_link = bd._maybe_add_json_elements_to_metadata_link('')
assert metadata_link == (
' -X GET -H "Accept: text/tsv" -H '
'"Content-Type: application/json" '
'--data \'{"elements": ["/experiments/ENCSR123ABC/"]}\''
)
dummy_request.json = {'elements': []}
bd = BatchDownload(dummy_request)
metadata_link = bd._maybe_add_json_elements_to_metadata_link('')
assert metadata_link == ''
dummy_request.json = {
'elements': [
'/experiments/ENCSR123ABC/',
'/experiments/ENCSRDEF567/'
]
}
bd = BatchDownload(dummy_request)
metadata_link = bd._maybe_add_json_elements_to_metadata_link('')
assert metadata_link == (
' -X GET -H "Accept: text/tsv" -H '
'"Content-Type: application/json" '
'--data \'{"elements": ["/experiments/ENCSR123ABC/", "/experiments/ENCSRDEF567/"]}\''
)
dummy_request.environ['QUERY_STRING'] = (
'type=Experiment&files.file_type=bigWig&files.file_type=bam'
'&files.replicate.library.size_range=50-100'
'&files.status!=archived&files.biological_replicates=2'
'&cart=xyz123'
)
dummy_request.json = {
'elements': [
'/experiments/ENCSR123ABC/',
'/experiments/ENCSRDEF567/'
]
}
bd = BatchDownload(dummy_request)
metadata_link = bd._maybe_add_json_elements_to_metadata_link('')
assert metadata_link == ''
def test_reports_batch_download_get_metadata_link(dummy_request):
from encoded.reports.batch_download import BatchDownload
dummy_request.environ['QUERY_STRING'] = (
'type=Experiment&files.file_type=bigWig&files.file_type=bam'
'&files.replicate.library.size_range=50-100'
'&files.status!=archived&files.biological_replicates=2'
)
bd = BatchDownload(dummy_request)
metadata_link = bd._get_metadata_link()
assert metadata_link == (
'"http://localhost/metadata/?type=Experiment'
'&files.file_type=bigWig&files.file_type=bam'
'&files.replicate.library.size_range=50-100'
'&files.status%21=archived&files.biological_replicates=2"'
)
dummy_request.json = {
'elements': [
'/experiments/ENCSR123ABC/',
'/experiments/ENCSRDEF567/'
]
}
bd = BatchDownload(dummy_request)
metadata_link = bd._get_metadata_link()
assert metadata_link == (
'"http://localhost/metadata/?type=Experiment'
'&files.file_type=bigWig&files.file_type=bam'
'&files.replicate.library.size_range=50-100'
'&files.status%21=archived&files.biological_replicates=2"'
' -X GET -H "Accept: text/tsv" -H "Content-Type: application/json"'
' --data \'{"elements": ["/experiments/ENCSR123ABC/", "/experiments/ENCSRDEF567/"]}\''
)
def test_reports_batch_download_get_encoded_metadata_link_with_newline(dummy_request):
from encoded.reports.batch_download import BatchDownload
dummy_request.environ['QUERY_STRING'] = (
'type=Experiment&files.file_type=bigWig&files.file_type=bam'
'&files.replicate.library.size_range=50-100'
'&files.status!=archived&files.biological_replicates=2'
)
bd = BatchDownload(dummy_request)
metadata_link = bd._get_encoded_metadata_link_with_newline()
assert metadata_link == (
'"http://localhost/metadata/?type=Experiment'
'&files.file_type=bigWig&files.file_type=bam'
'&files.replicate.library.size_range=50-100'
'&files.status%21=archived&files.biological_replicates=2"'
'\n'
).encode('utf-8')
dummy_request.json = {
'elements': [
'/experiments/ENCSR123ABC/',
'/experiments/ENCSRDEF567/'
]
}
bd = BatchDownload(dummy_request)
metadata_link = bd._get_encoded_metadata_link_with_newline()
assert metadata_link == (
'"http://localhost/metadata/?type=Experiment'
'&files.file_type=bigWig&files.file_type=bam'
'&files.replicate.library.size_range=50-100'
'&files.status%21=archived&files.biological_replicates=2"'
' -X GET -H "Accept: text/tsv" -H "Content-Type: application/json"'
' --data \'{"elements": ["/experiments/ENCSR123ABC/", "/experiments/ENCSRDEF567/"]}\''
'\n'
).encode('utf-8')
def test_reports_batch_download_default_params(dummy_request):
from encoded.reports.batch_download import BatchDownload
dummy_request.environ['QUERY_STRING'] = (
'type=Experiment&files.file_type=bigWig&files.file_type=bam'
'&files.replicate.library.size_range=50-100'
'&files.status!=archived&files.biological_replicates=2'
)
bd = BatchDownload(dummy_request)
assert bd.DEFAULT_PARAMS == [
('limit', 'all'),
('field', 'files.@id'),
('field', 'files.href'),
('field', 'files.restricted'),
('field', 'files.no_file_available'),
('field', 'files.file_format'),
('field', 'files.file_format_type'),
('field', 'files.status'),
('field', 'files.assembly'),
]
def test_reports_batch_download_build_header(dummy_request):
from encoded.reports.batch_download import BatchDownload
dummy_request.environ['QUERY_STRING'] = (
'type=Experiment&files.file_type=bigWig&files.file_type=bam'
'&files.replicate.library.size_range=50-100'
'&files.status!=archived&files.biological_replicates=2'
)
bd = BatchDownload(dummy_request)
bd._build_header()
assert bd.header == ['File download URL']
def test_reports_batch_download_get_column_to_field_mapping(dummy_request):
from encoded.reports.batch_download import BatchDownload
dummy_request.environ['QUERY_STRING'] = (
'type=Experiment&files.file_type=bigWig&files.file_type=bam'
'&files.replicate.library.size_range=50-100'
'&files.status!=archived&files.biological_replicates=2'
)
bd = BatchDownload(dummy_request)
assert list(bd._get_column_to_fields_mapping().items()) == [
('File download URL', ['files.href'])
]
def test_reports_batch_download_build_params(dummy_request):
from encoded.reports.batch_download import BatchDownload
dummy_request.environ['QUERY_STRING'] = (
'type=Experiment&files.file_type=bigWig&files.file_type=bam'
'&files.replicate.library.size_range=50-100'
'&files.status!=archived&files.biological_replicates=2'
)
dummy_request.json = {'elements': ['/experiments/ENCSR123ABC/']}
bd = BatchDownload(dummy_request)
bd._build_params()
assert len(bd.param_list['field']) == 5, f'{len(bd.param_list["field"])} not expected'
assert len(bd.param_list['@id']) == 1
def test_reports_batch_download_build_query_string(dummy_request):
from encoded.reports.batch_download import BatchDownload
dummy_request.environ['QUERY_STRING'] = (
'type=Experiment&files.file_type=bigWig&files.file_type=bam'
)
bd = BatchDownload(dummy_request)
bd._initialize_report()
bd._build_params()
bd._build_query_string()
bd.query_string.deduplicate()
assert str(bd.query_string) == (
'type=Experiment&files.file_type=bigWig'
'&files.file_type=bam&limit=all&field=files.%40id'
'&field=files.href&field=files.restricted'
'&field=files.no_file_available&field=files.file_format'
'&field=files.file_format_type&field=files.status'
'&field=files.assembly&field=files.file_type'
)
dummy_request.environ['QUERY_STRING'] = (
'type=Experiment&files.file_type=bigWig&files.file_type=bam'
'&files.replicate.library.size_range=50-100'
'&files.status!=archived&files.biological_replicates=2'
)
bd = BatchDownload(dummy_request)
bd._initialize_report()
bd._build_params()
bd._build_query_string()
assert str(bd.query_string) == (
'type=Experiment&files.file_type=bigWig'
'&files.file_type=bam&files.replicate.library.size_range=50-100'
'&files.status%21=archived&files.biological_replicates=2'
'&limit=all&field=files.%40id&field=files.href&field=files.restricted'
'&field=files.no_file_available&field=files.file_format'
'&field=files.file_format_type&field=files.status&field=files.assembly'
'&field=files.href&field=files.file_type&field=files.file_type'
'&field=files.replicate.library.size_range&field=files.biological_replicates'
)
def test_reports_batch_download_generate(index_workbook, dummy_request):
from types import GeneratorType
from encoded.reports.batch_download import BatchDownload
from pyramid.response import Response
dummy_request.environ['QUERY_STRING'] = (
'type=Experiment'
)
bd = BatchDownload(dummy_request)
response = bd.generate()
assert isinstance(response, Response)
assert response.content_type == 'text/plain'
assert response.content_disposition == 'attachment; filename="files.txt"'
assert len(list(response.body)) >= 100
def test_reports_publication_data_batch_download_generate_rows(index_workbook, dummy_request):
from encoded.reports.batch_download import PublicationDataBatchDownload
dummy_request.environ['QUERY_STRING'] = (
'type=PublicationData'
'&@id=/publication-data/ENCSR727WCB/'
'&files.file_type=tsv'
)
pdbd = PublicationDataBatchDownload(dummy_request)
pdbd._initialize_report()
pdbd._build_params()
results = list(pdbd._generate_rows())
# One metadata link, two TSV.
assert len(results) == 3
def test_reports_publication_data_batch_download_generate_rows_no_files_in_publication_data(dummy_request, mocker):
from types import GeneratorType
from encoded.reports.batch_download import PublicationDataBatchDownload
dummy_request.environ['QUERY_STRING'] = (
'type=PublicationData'
)
pdbd = PublicationDataBatchDownload(dummy_request)
pdbd._initialize_report()
pdbd._build_params()
mocker.patch.object(pdbd, '_get_search_results_generator')
pdbd._get_search_results_generator.return_value = (
x for x in [{'files': []}]
)
row_generator = pdbd._generate_rows()
assert isinstance(row_generator, GeneratorType)
assert len(list(row_generator)) == 1
| 46.414444 | 210 | 0.726666 | 5,077 | 41,773 | 5.671853 | 0.052787 | 0.132727 | 0.114599 | 0.075879 | 0.943916 | 0.93315 | 0.91412 | 0.904292 | 0.894465 | 0.883838 | 0 | 0.015286 | 0.151198 | 41,773 | 899 | 211 | 46.466073 | 0.796853 | 0.01027 | 0 | 0.587642 | 0 | 0.007566 | 0.328455 | 0.282901 | 0 | 0 | 0 | 0 | 0.174023 | 1 | 0.03657 | false | 0 | 0.029004 | 0 | 0.066835 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
49e7703ca079c6b5b35390013b90cef8f4267114 | 177 | py | Python | catkin_ws/devel/lib/python2.7/dist-packages/map_msgs/srv/__init__.py | lies98/ROS_chasing_ball | 6e1f08ed51a5b5f0c7b0bdebfb1bef2d3fe61949 | [
"MIT"
] | 4 | 2020-05-10T13:23:49.000Z | 2020-06-08T12:13:34.000Z | catkin_ws/devel/lib/python2.7/dist-packages/map_msgs/srv/__init__.py | lies98/ROS_chasing_ball | 6e1f08ed51a5b5f0c7b0bdebfb1bef2d3fe61949 | [
"MIT"
] | 1 | 2021-07-08T10:26:06.000Z | 2021-07-08T10:31:11.000Z | catkin_ws/devel/lib/python2.7/dist-packages/map_msgs/srv/__init__.py | lies98/ROS_chasing_ball | 6e1f08ed51a5b5f0c7b0bdebfb1bef2d3fe61949 | [
"MIT"
] | 1 | 2020-05-28T11:05:36.000Z | 2020-05-28T11:05:36.000Z | from ._GetMapROI import *
from ._GetPointMap import *
from ._GetPointMapROI import *
from ._ProjectedMapsInfo import *
from ._SaveMap import *
from ._SetMapProjections import *
| 25.285714 | 33 | 0.79661 | 18 | 177 | 7.5 | 0.444444 | 0.37037 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.135593 | 177 | 6 | 34 | 29.5 | 0.882353 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
b702becf41f47446bc801cbee415352cc3c31a95 | 26 | py | Python | test_bed_adapter/services/__init__.py | ba-tno/python-test-bed-adapter | ac463257d11ed7c71755daad0743a8b6290db07b | [
"MIT"
] | null | null | null | test_bed_adapter/services/__init__.py | ba-tno/python-test-bed-adapter | ac463257d11ed7c71755daad0743a8b6290db07b | [
"MIT"
] | null | null | null | test_bed_adapter/services/__init__.py | ba-tno/python-test-bed-adapter | ac463257d11ed7c71755daad0743a8b6290db07b | [
"MIT"
] | null | null | null | from . import time_service | 26 | 26 | 0.846154 | 4 | 26 | 5.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.115385 | 26 | 1 | 26 | 26 | 0.913043 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
b71018251f481091e2fd34d3cf9e7f751279c1d5 | 6,050 | py | Python | autoscale.py | s3u/autoscale-mesos | cef5418fff0622d40e4dd4ad2031a6809fe87d65 | [
"MIT"
] | 8 | 2015-08-21T09:27:29.000Z | 2021-01-21T14:16:27.000Z | autoscale.py | s3u/autoscale-mesos | cef5418fff0622d40e4dd4ad2031a6809fe87d65 | [
"MIT"
] | null | null | null | autoscale.py | s3u/autoscale-mesos | cef5418fff0622d40e4dd4ad2031a6809fe87d65 | [
"MIT"
] | 3 | 2015-07-29T13:35:58.000Z | 2021-01-21T14:16:40.000Z | #!/usr/bin/env python
import logging
import sys
import boto.ec2.autoscale
import requests
logger = logging.getLogger(__name__)
class MesosReporter():
def __init__(self, mesos_url):
self.mesos_url = mesos_url.rstrip('/')
stats_url = '/'.join([self.mesos_url, '/stats.json'])
self.state = requests.get(stats_url).json()
@property
def state(self):
return self.state
class MesosDecider():
def __init__(self, thresholds):
self.thresholds = thresholds
def should_scale(self, cluster):
increment = 1
decrement = -1
cpus_free = cluster.state['cpus_total'] - cluster.state['cpus_used']
disk_free = cluster.state['disk_total'] - cluster.state['disk_used']
mem_free = cluster.state['mem_total'] - cluster.state['mem_used']
logger.info('State: %s', dict(cpus_free=cpus_free, disk_free=disk_free, mem_free=mem_free))
logger.info('Thresholds: %s', self.thresholds)
if (('cpus' in self.thresholds and cpus_free < self.thresholds['cpus']['lower']) or
('disk' in self.thresholds and disk_free < self.thresholds['disk']['lower']) or
('mem' in self.thresholds and mem_free < self.thresholds['mem']['lower'])):
scale_by = increment
elif (('cpus' in self.thresholds and cpus_free > self.thresholds['cpus']['upper']) or
('disk' in self.thresholds and disk_free > self.thresholds['disk']['upper']) or
('mem' in self.thresholds and mem_free > self.thresholds['mem']['upper'])):
scale_by = decrement
else:
scale_by = 0
logger.info('Should scale by %s', scale_by)
return scale_by
class AwsAsgScaler():
def __init__(self, region, asg_name, min_instances=1, max_instances=None,
aws_access_key_id=None, aws_secret_access_key=None):
self.region = region
self.asg_name = asg_name
self.min_instances = min_instances
self.max_instances = max_instances
self.aws_access_key_id = aws_access_key_id
self.aws_secret_access_key = aws_secret_access_key
def _get_connection(self):
if self.aws_access_key_id and self.aws_secret_access_key:
return boto.ec2.autoscale.connect_to_region(
self.region,
aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key)
else:
return boto.ec2.autoscale.connect_to_region(self.region)
def scale(self, delta):
c = self._get_connection()
current_count = c.get_all_groups(names=[self.asg_name])[0].desired_capacity
logger.info("Current scale: %s", current_count)
new_count = current_count + delta
if self.min_instances and new_count < self.min_instances:
new_count = self.min_instances
elif self.max_instances and new_count > self.max_instances:
new_count = self.max_instances
if new_count != current_count:
logger.info("Scaling to %s", new_count)
c.set_desired_capacity(self.asg_name, new_count)
class AwsAsgScaler():
def __init__(self, region, asg_name, min_instances=1, max_instances=None,
aws_access_key_id=None, aws_secret_access_key=None):
self.region = region
self.asg_name = asg_name
self.min_instances = min_instances
self.max_instances = max_instances
self.aws_access_key_id = aws_access_key_id
self.aws_secret_access_key = aws_secret_access_key
def _get_connection(self):
if self.aws_access_key_id and self.aws_secret_access_key:
return boto.ec2.autoscale.connect_to_region(
self.region,
aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key)
else:
return boto.ec2.autoscale.connect_to_region(self.region)
def scale(self, delta):
c = self._get_connection()
current_count = c.get_all_groups(names=[self.asg_name])[0].desired_capacity
logger.info("Current scale: %s", current_count)
new_count = current_count + delta
if self.min_instances and new_count < self.min_instances:
new_count = self.min_instances
elif self.max_instances and new_count > self.max_instances:
new_count = self.max_instances
if new_count != current_count:
logger.info("Scaling to %s", new_count)
c.set_desired_capacity(self.asg_name, new_count)
class OpenStackScaler():
def __init__(self, region, asg_name, min_instances=1, max_instances=None,
aws_access_key_id=None, aws_secret_access_key=None):
self.region = region
self.asg_name = asg_name
self.min_instances = min_instances
self.max_instances = max_instances
self.aws_access_key_id = aws_access_key_id
self.aws_secret_access_key = aws_secret_access_key
def _get_connection(self):
if self.aws_access_key_id and self.aws_secret_access_key:
return boto.ec2.autoscale.connect_to_region(
self.region,
aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key)
else:
return boto.ec2.autoscale.connect_to_region(self.region)
def scale(self, delta):
c = self._get_connection()
current_count = c.get_all_groups(names=[self.asg_name])[0].desired_capacity
logger.info("Current scale: %s", current_count)
new_count = current_count + delta
if self.min_instances and new_count < self.min_instances:
new_count = self.min_instances
elif self.max_instances and new_count > self.max_instances:
new_count = self.max_instances
if new_count != current_count:
logger.info("Scaling to %s", new_count)
c.set_desired_capacity(self.asg_name, new_count)
| 39.542484 | 99 | 0.659339 | 808 | 6,050 | 4.576733 | 0.10396 | 0.087615 | 0.05841 | 0.068145 | 0.796376 | 0.796376 | 0.796376 | 0.796376 | 0.796376 | 0.796376 | 0 | 0.003514 | 0.247438 | 6,050 | 152 | 100 | 39.802632 | 0.808698 | 0.003306 | 0 | 0.707317 | 0 | 0 | 0.045281 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.105691 | false | 0 | 0.03252 | 0.00813 | 0.243902 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
3fbbd96fb919f3142a057b3f25926824fd3781e9 | 79 | py | Python | Clarinet/utils/generatedata/__init__.py | rohans0509/Clarinet | 0a7a6a5e6a91f93956b6b5739cab1f030655cac8 | [
"MIT"
] | 1 | 2022-01-28T20:30:07.000Z | 2022-01-28T20:30:07.000Z | Clarinet/utils/generatedata/__init__.py | rohans0509/Clarinet | 0a7a6a5e6a91f93956b6b5739cab1f030655cac8 | [
"MIT"
] | null | null | null | Clarinet/utils/generatedata/__init__.py | rohans0509/Clarinet | 0a7a6a5e6a91f93956b6b5739cab1f030655cac8 | [
"MIT"
] | 2 | 2021-11-23T13:55:10.000Z | 2021-11-23T13:56:57.000Z | from .midiFolder2Text import *
from .queries import *
from .genAndEval import * | 26.333333 | 30 | 0.78481 | 9 | 79 | 6.888889 | 0.555556 | 0.322581 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.014706 | 0.139241 | 79 | 3 | 31 | 26.333333 | 0.897059 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
3feab8147ecd0f4addf9902dded43816117af047 | 106 | py | Python | abutils/plots/__init__.py | bnemoz/abutils | d5dfab90c885a5d948cc1cd8070100f0cdab1c7e | [
"MIT"
] | 4 | 2019-02-27T21:41:13.000Z | 2022-03-19T19:07:28.000Z | abutils/plots/__init__.py | bnemoz/abutils | d5dfab90c885a5d948cc1cd8070100f0cdab1c7e | [
"MIT"
] | 1 | 2018-10-11T22:01:19.000Z | 2018-10-11T22:01:19.000Z | abutils/plots/__init__.py | bnemoz/abutils | d5dfab90c885a5d948cc1cd8070100f0cdab1c7e | [
"MIT"
] | 5 | 2018-10-11T21:18:00.000Z | 2022-01-28T18:45:42.000Z | from __future__ import absolute_import
from .summary import *
from .lineage import *
from .base import *
| 17.666667 | 38 | 0.783019 | 14 | 106 | 5.571429 | 0.5 | 0.384615 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.160377 | 106 | 5 | 39 | 21.2 | 0.876404 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
b748fc8c7e140301c507fb8f6ef3d8dd0c2c5f97 | 41 | py | Python | dbl_archive_data_storage/__init__.py | ubsicap/dbl-archive-data-storage | 03786ed54024a55ae96b93948a656a3c01269894 | [
"MIT"
] | null | null | null | dbl_archive_data_storage/__init__.py | ubsicap/dbl-archive-data-storage | 03786ed54024a55ae96b93948a656a3c01269894 | [
"MIT"
] | 12 | 2018-12-11T17:49:01.000Z | 2019-02-21T18:26:22.000Z | dbl_archive_data_storage/__init__.py | ubsicap/dbl-archive-data-storage | 03786ed54024a55ae96b93948a656a3c01269894 | [
"MIT"
] | null | null | null | from .data_storage import DBLDataStorage
| 20.5 | 40 | 0.878049 | 5 | 41 | 7 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.097561 | 41 | 1 | 41 | 41 | 0.945946 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
b74cf2cfb848694d505888b0e8fc767392ce6e0b | 148 | py | Python | snekcord/objects/__init__.py | asleep-cult/snekcord | 04302b0c65bad01c00fb047df3040d3234773689 | [
"MIT"
] | 9 | 2021-07-26T00:25:51.000Z | 2022-02-23T16:00:10.000Z | snekcord/objects/__init__.py | asleep-cult/snekcord | 04302b0c65bad01c00fb047df3040d3234773689 | [
"MIT"
] | 37 | 2021-05-29T16:16:22.000Z | 2022-02-13T13:57:25.000Z | snekcord/objects/__init__.py | asleep-cult/snekcord | 04302b0c65bad01c00fb047df3040d3234773689 | [
"MIT"
] | 4 | 2021-06-02T16:45:41.000Z | 2022-02-10T14:57:16.000Z | from .base import *
from .channel import *
from .emoji import *
from .guild import *
from .message import *
from .role import *
from .user import *
| 18.5 | 22 | 0.716216 | 21 | 148 | 5.047619 | 0.428571 | 0.566038 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.189189 | 148 | 7 | 23 | 21.142857 | 0.883333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
b7631afca2e2203dfdd6ab74750a7de569f0db0e | 33 | py | Python | kikimr/public/sdk/python/client/s3list.py | yandex-cloud/ydb-python-sdk | 0df2dce2d77fc41ad3020072740f51dd91630177 | [
"Apache-2.0"
] | 19 | 2019-07-01T08:25:29.000Z | 2022-01-26T14:46:51.000Z | kikimr/public/sdk/python/client/s3list.py | yandex-cloud/ydb-python-sdk | 0df2dce2d77fc41ad3020072740f51dd91630177 | [
"Apache-2.0"
] | 5 | 2019-07-02T13:36:42.000Z | 2021-09-14T06:46:48.000Z | kikimr/public/sdk/python/client/s3list.py | yandex-cloud/ydb-python-sdk | 0df2dce2d77fc41ad3020072740f51dd91630177 | [
"Apache-2.0"
] | 10 | 2019-06-07T10:36:19.000Z | 2021-10-15T08:58:11.000Z | from ydb.s3list import * # noqa
| 16.5 | 32 | 0.69697 | 5 | 33 | 4.6 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.038462 | 0.212121 | 33 | 1 | 33 | 33 | 0.846154 | 0.121212 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
b777278e2e3afd1297374332e40a28d5318a1cf3 | 27 | py | Python | src/utils/__init__.py | karim-daw/pollination-app | ed87f3dbc2d93d25568707d6a6ad0ee35c5109b8 | [
"MIT"
] | null | null | null | src/utils/__init__.py | karim-daw/pollination-app | ed87f3dbc2d93d25568707d6a6ad0ee35c5109b8 | [
"MIT"
] | null | null | null | src/utils/__init__.py | karim-daw/pollination-app | ed87f3dbc2d93d25568707d6a6ad0ee35c5109b8 | [
"MIT"
] | null | null | null | from .folder_utils import * | 27 | 27 | 0.814815 | 4 | 27 | 5.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.111111 | 27 | 1 | 27 | 27 | 0.875 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
b788cdcf29832a766250484c2e7d130cef1b628d | 72 | py | Python | src/django-nonrel/tests/regressiontests/comment_tests/custom_comments/forms.py | adamjmcgrath/glancydesign | 826ede7c639879d5b79ee730eb5e91422768cb02 | [
"BSD-3-Clause"
] | 790 | 2015-01-03T02:13:39.000Z | 2020-05-10T19:53:57.000Z | tests/regressiontests/comment_tests/custom_comments/forms.py | mradziej/django | 5d38965743a369981c9a738a298f467f854a2919 | [
"BSD-3-Clause"
] | 1,361 | 2015-01-08T23:09:40.000Z | 2020-04-14T00:03:04.000Z | tests/regressiontests/comment_tests/custom_comments/forms.py | mradziej/django | 5d38965743a369981c9a738a298f467f854a2919 | [
"BSD-3-Clause"
] | 155 | 2015-01-08T22:59:31.000Z | 2020-04-08T08:01:53.000Z | from django import forms
class CustomCommentForm(forms.Form):
pass
| 14.4 | 36 | 0.777778 | 9 | 72 | 6.222222 | 0.888889 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | 72 | 4 | 37 | 18 | 0.933333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.333333 | 0.333333 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 6 |
b799afcf15d204f9779393354fa5382fd0cf70d8 | 169 | py | Python | erasure/__init__.py | ankitchiplunkar/erasure.py | 9b0e24883dbb3db8fe9cf2b4c4fb8cce583442a3 | [
"MIT"
] | 4 | 2019-12-17T02:27:44.000Z | 2021-05-07T12:26:03.000Z | erasure/__init__.py | ankitchiplunkar/erasure.py | 9b0e24883dbb3db8fe9cf2b4c4fb8cce583442a3 | [
"MIT"
] | 9 | 2019-12-12T18:47:19.000Z | 2019-12-29T21:49:59.000Z | erasure/__init__.py | ankitchiplunkar/erasure.py | 9b0e24883dbb3db8fe9cf2b4c4fb8cce583442a3 | [
"MIT"
] | null | null | null | from erasure.erasure_client import ErasureClient
from erasure.feed import Feed
from erasure.post import Post
from erasure.session import setup_logging
setup_logging()
| 21.125 | 48 | 0.852071 | 24 | 169 | 5.875 | 0.416667 | 0.312057 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.112426 | 169 | 7 | 49 | 24.142857 | 0.94 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.8 | 0 | 0.8 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
b7d9641f944921c63ec376bfc8e3e6cb08dc3bf9 | 378 | py | Python | rcnn/lib/python3.6/site-packages/tensorflow/keras/preprocessing/__init__.py | dreamingweaver/making_passportImage | 68f23411780ff82abe934dfae5fc04acb80f2c49 | [
"MIT"
] | 1 | 2019-01-12T13:17:32.000Z | 2019-01-12T13:17:32.000Z | rcnn/lib/python3.6/site-packages/tensorflow/keras/preprocessing/__init__.py | dreamingweaver/making_passportImage | 68f23411780ff82abe934dfae5fc04acb80f2c49 | [
"MIT"
] | null | null | null | rcnn/lib/python3.6/site-packages/tensorflow/keras/preprocessing/__init__.py | dreamingweaver/making_passportImage | 68f23411780ff82abe934dfae5fc04acb80f2c49 | [
"MIT"
] | null | null | null | # This file is MACHINE GENERATED! Do not edit.
# Generated by: tensorflow/python/tools/api/generator/create_python_api.py script.
"""Keras data preprocessing utils.
"""
from __future__ import print_function
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing import sequence
from tensorflow.keras.preprocessing import text
del print_function
| 29.076923 | 82 | 0.828042 | 50 | 378 | 6.1 | 0.6 | 0.137705 | 0.186885 | 0.314754 | 0.37377 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.10582 | 378 | 12 | 83 | 31.5 | 0.902367 | 0.417989 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.8 | 0 | 0.8 | 0.4 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
b7f837cc9c9d92ad5942d61a026dfca0fe332100 | 138 | py | Python | texttransformation/__init__.py | vamas/DupDetectorML | a0db6f24519f19a72f9bc7ac226d6a37734564ae | [
"CC0-1.0"
] | null | null | null | texttransformation/__init__.py | vamas/DupDetectorML | a0db6f24519f19a72f9bc7ac226d6a37734564ae | [
"CC0-1.0"
] | null | null | null | texttransformation/__init__.py | vamas/DupDetectorML | a0db6f24519f19a72f9bc7ac226d6a37734564ae | [
"CC0-1.0"
] | null | null | null | from .stringtransform import StringTransform
from .rowtexttransform import RowTextTransform
from .transformdataset import TransformDataset | 46 | 46 | 0.898551 | 12 | 138 | 10.333333 | 0.416667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.07971 | 138 | 3 | 47 | 46 | 0.976378 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
b7fccd2e2ff220e86df3de5672123cc9631d098d | 13,343 | py | Python | tests/components/broadlink/test_sensors.py | tizzen33/core | 2a1884a1f7a07848b8b63afd29f59c81f1ffaf62 | [
"Apache-2.0"
] | 7 | 2019-08-15T13:36:58.000Z | 2020-03-18T10:46:29.000Z | tests/components/broadlink/test_sensors.py | tizzen33/core | 2a1884a1f7a07848b8b63afd29f59c81f1ffaf62 | [
"Apache-2.0"
] | 87 | 2020-07-06T22:22:54.000Z | 2022-03-31T06:01:46.000Z | tests/components/broadlink/test_sensors.py | tizzen33/core | 2a1884a1f7a07848b8b63afd29f59c81f1ffaf62 | [
"Apache-2.0"
] | 7 | 2018-10-04T10:12:45.000Z | 2021-12-29T20:55:40.000Z | """Tests for Broadlink sensors."""
from datetime import timedelta
from homeassistant.components.broadlink.const import DOMAIN, SENSOR_DOMAIN
from homeassistant.components.broadlink.updater import BroadlinkSP4UpdateManager
from homeassistant.helpers.entity_registry import async_entries_for_device
from homeassistant.util import dt
from . import get_device
from tests.common import async_fire_time_changed, mock_device_registry, mock_registry
async def test_a1_sensor_setup(hass):
"""Test a successful e-Sensor setup."""
device = get_device("Bedroom")
mock_api = device.get_mock_api()
mock_api.check_sensors_raw.return_value = {
"temperature": 27.4,
"humidity": 59.3,
"air_quality": 3,
"light": 2,
"noise": 1,
}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_api.check_sensors_raw.call_count == 1
device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)}
)
entries = async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == SENSOR_DOMAIN]
assert len(sensors) == 5
sensors_and_states = {
(sensor.original_name, hass.states.get(sensor.entity_id).state)
for sensor in sensors
}
assert sensors_and_states == {
(f"{device.name} Temperature", "27.4"),
(f"{device.name} Humidity", "59.3"),
(f"{device.name} Air Quality", "3"),
(f"{device.name} Light", "2"),
(f"{device.name} Noise", "1"),
}
async def test_a1_sensor_update(hass):
"""Test a successful e-Sensor update."""
device = get_device("Bedroom")
mock_api = device.get_mock_api()
mock_api.check_sensors_raw.return_value = {
"temperature": 22.4,
"humidity": 47.3,
"air_quality": 3,
"light": 2,
"noise": 1,
}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)}
)
entries = async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == SENSOR_DOMAIN]
assert len(sensors) == 5
mock_setup.api.check_sensors_raw.return_value = {
"temperature": 22.5,
"humidity": 47.4,
"air_quality": 2,
"light": 3,
"noise": 2,
}
await hass.helpers.entity_component.async_update_entity(
next(iter(sensors)).entity_id
)
assert mock_setup.api.check_sensors_raw.call_count == 2
sensors_and_states = {
(sensor.original_name, hass.states.get(sensor.entity_id).state)
for sensor in sensors
}
assert sensors_and_states == {
(f"{device.name} Temperature", "22.5"),
(f"{device.name} Humidity", "47.4"),
(f"{device.name} Air Quality", "2"),
(f"{device.name} Light", "3"),
(f"{device.name} Noise", "2"),
}
async def test_rm_pro_sensor_setup(hass):
"""Test a successful RM pro sensor setup."""
device = get_device("Office")
mock_api = device.get_mock_api()
mock_api.check_sensors.return_value = {"temperature": 18.2}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_api.check_sensors.call_count == 1
device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)}
)
entries = async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == SENSOR_DOMAIN]
assert len(sensors) == 1
sensors_and_states = {
(sensor.original_name, hass.states.get(sensor.entity_id).state)
for sensor in sensors
}
assert sensors_and_states == {(f"{device.name} Temperature", "18.2")}
async def test_rm_pro_sensor_update(hass):
"""Test a successful RM pro sensor update."""
device = get_device("Office")
mock_api = device.get_mock_api()
mock_api.check_sensors.return_value = {"temperature": 25.7}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)}
)
entries = async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == SENSOR_DOMAIN]
assert len(sensors) == 1
mock_setup.api.check_sensors.return_value = {"temperature": 25.8}
await hass.helpers.entity_component.async_update_entity(
next(iter(sensors)).entity_id
)
assert mock_setup.api.check_sensors.call_count == 2
sensors_and_states = {
(sensor.original_name, hass.states.get(sensor.entity_id).state)
for sensor in sensors
}
assert sensors_and_states == {(f"{device.name} Temperature", "25.8")}
async def test_rm_pro_filter_crazy_temperature(hass):
"""Test we filter a crazy temperature variation.
Firmware issue. See https://github.com/home-assistant/core/issues/42100.
"""
device = get_device("Office")
mock_api = device.get_mock_api()
mock_api.check_sensors.return_value = {"temperature": 22.9}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)}
)
entries = async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == SENSOR_DOMAIN]
assert len(sensors) == 1
mock_setup.api.check_sensors.return_value = {"temperature": -7}
await hass.helpers.entity_component.async_update_entity(
next(iter(sensors)).entity_id
)
assert mock_setup.api.check_sensors.call_count == 2
sensors_and_states = {
(sensor.original_name, hass.states.get(sensor.entity_id).state)
for sensor in sensors
}
assert sensors_and_states == {(f"{device.name} Temperature", "22.9")}
async def test_rm_mini3_no_sensor(hass):
"""Test we do not set up sensors for RM mini 3."""
device = get_device("Entrance")
mock_api = device.get_mock_api()
mock_api.check_sensors.return_value = {"temperature": 0}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_api.check_sensors.call_count <= 1
device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)}
)
entries = async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == SENSOR_DOMAIN]
assert len(sensors) == 0
async def test_rm4_pro_hts2_sensor_setup(hass):
"""Test a successful RM4 pro sensor setup with HTS2 cable."""
device = get_device("Garage")
mock_api = device.get_mock_api()
mock_api.check_sensors.return_value = {"temperature": 22.5, "humidity": 43.7}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_api.check_sensors.call_count == 1
device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)}
)
entries = async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == SENSOR_DOMAIN]
assert len(sensors) == 2
sensors_and_states = {
(sensor.original_name, hass.states.get(sensor.entity_id).state)
for sensor in sensors
}
assert sensors_and_states == {
(f"{device.name} Temperature", "22.5"),
(f"{device.name} Humidity", "43.7"),
}
async def test_rm4_pro_hts2_sensor_update(hass):
"""Test a successful RM4 pro sensor update with HTS2 cable."""
device = get_device("Garage")
mock_api = device.get_mock_api()
mock_api.check_sensors.return_value = {"temperature": 16.7, "humidity": 34.1}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)}
)
entries = async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == SENSOR_DOMAIN]
assert len(sensors) == 2
mock_setup.api.check_sensors.return_value = {"temperature": 16.8, "humidity": 34.0}
await hass.helpers.entity_component.async_update_entity(
next(iter(sensors)).entity_id
)
assert mock_setup.api.check_sensors.call_count == 2
sensors_and_states = {
(sensor.original_name, hass.states.get(sensor.entity_id).state)
for sensor in sensors
}
assert sensors_and_states == {
(f"{device.name} Temperature", "16.8"),
(f"{device.name} Humidity", "34.0"),
}
async def test_rm4_pro_no_sensor(hass):
"""Test we do not set up sensors for RM4 pro without HTS2 cable."""
device = get_device("Garage")
mock_api = device.get_mock_api()
mock_api.check_sensors.return_value = {"temperature": 0, "humidity": 0}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_api.check_sensors.call_count <= 1
device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)}
)
entries = async_entries_for_device(entity_registry, device_entry.id)
sensors = {entry for entry in entries if entry.domain == SENSOR_DOMAIN}
assert len(sensors) == 0
async def test_scb1e_sensor_setup(hass):
"""Test a successful SCB1E sensor setup."""
device = get_device("Dining room")
mock_api = device.get_mock_api()
mock_api.get_state.return_value = {
"pwr": 1,
"indicator": 1,
"maxworktime": 0,
"power": 255.57,
"volt": 121.7,
"current": 2.1,
"overload": 0,
"totalconsum": 1.7,
"childlock": 0,
}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
assert mock_api.get_state.call_count == 1
device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)}
)
entries = async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == SENSOR_DOMAIN]
assert len(sensors) == 5
sensors_and_states = {
(sensor.original_name, hass.states.get(sensor.entity_id).state)
for sensor in sensors
}
assert sensors_and_states == {
(f"{device.name} Current power", "255.57"),
(f"{device.name} Voltage", "121.7"),
(f"{device.name} Current", "2.1"),
(f"{device.name} Overload", "0"),
(f"{device.name} Total consumption", "1.7"),
}
async def test_scb1e_sensor_update(hass):
"""Test a successful SCB1E sensor update."""
device = get_device("Dining room")
mock_api = device.get_mock_api()
mock_api.get_state.return_value = {
"pwr": 1,
"indicator": 1,
"maxworktime": 0,
"power": 255.6,
"volt": 121.7,
"current": 2.1,
"overload": 0,
"totalconsum": 1.7,
"childlock": 0,
}
device_registry = mock_device_registry(hass)
entity_registry = mock_registry(hass)
target_time = (
dt.utcnow() + BroadlinkSP4UpdateManager.SCAN_INTERVAL * 3 + timedelta(seconds=1)
)
mock_setup = await device.setup_entry(hass, mock_api=mock_api)
device_entry = device_registry.async_get_device(
{(DOMAIN, mock_setup.entry.unique_id)}
)
entries = async_entries_for_device(entity_registry, device_entry.id)
sensors = [entry for entry in entries if entry.domain == SENSOR_DOMAIN]
assert len(sensors) == 5
mock_setup.api.get_state.return_value = {
"pwr": 1,
"indicator": 1,
"maxworktime": 0,
"power": 291.8,
"volt": 121.6,
"current": 2.4,
"overload": 0,
"totalconsum": 0.5,
"childlock": 0,
}
async_fire_time_changed(hass, target_time)
await hass.async_block_till_done()
assert mock_setup.api.get_state.call_count == 2
sensors_and_states = {
(sensor.original_name, hass.states.get(sensor.entity_id).state)
for sensor in sensors
}
assert sensors_and_states == {
(f"{device.name} Current power", "291.8"),
(f"{device.name} Voltage", "121.6"),
(f"{device.name} Current", "2.4"),
(f"{device.name} Overload", "0"),
(f"{device.name} Total consumption", "0.5"),
}
| 33.609572 | 88 | 0.676684 | 1,782 | 13,343 | 4.787318 | 0.082492 | 0.050053 | 0.034814 | 0.036104 | 0.882663 | 0.853358 | 0.827218 | 0.801196 | 0.790998 | 0.790998 | 0 | 0.02162 | 0.206176 | 13,343 | 396 | 89 | 33.694444 | 0.783799 | 0.002098 | 0 | 0.624183 | 0 | 0 | 0.099448 | 0 | 0 | 0 | 0 | 0 | 0.101307 | 1 | 0 | false | 0 | 0.022876 | 0 | 0.022876 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
4d17c241c5a891fa979a88d2d9f2d9eeb1faffbf | 23,291 | py | Python | aphid/cogs/moderation.py | Jashooa/Aphid | 1b5df0dac8835956b2c7af86a1331c974614a90c | [
"MIT"
] | 1 | 2021-02-15T14:05:56.000Z | 2021-02-15T14:05:56.000Z | aphid/cogs/moderation.py | Jashooa/Aphid | 1b5df0dac8835956b2c7af86a1331c974614a90c | [
"MIT"
] | null | null | null | aphid/cogs/moderation.py | Jashooa/Aphid | 1b5df0dac8835956b2c7af86a1331c974614a90c | [
"MIT"
] | null | null | null | import datetime
import logging
import discord
from discord.ext import commands
from utils import checks, converters, formatting, time
from utils.paginator import Pages
log = logging.getLogger(__name__)
class Moderation:
"""Server moderation commands."""
def __init__(self, bot):
self.bot = bot
self.log_channel = 'mod-logs'
self.mute_role = 'Muted'
self.protected_roles = [
'Queen',
'Inquiline',
'Alate'
]
async def on_member_join(self, member):
if member.guild is None:
return
if member.guild.id != self.bot.guild_id:
return
query = 'SELECT * FROM mod_tempactions WHERE user_id = $1;'
record = await self.bot.pool.fetchrow(query, member.id)
if record is not None:
role = discord.utils.get(member.guild.roles, name=self.mute_role)
await member.add_roles(role, reason='Tempmute Reapplication')
async def log_action(self, guild: discord.Guild, action: str, member: discord.Member, moderator: discord.Member, issued: datetime.datetime, *, duration: time.ShortTime = None, reason: str = None):
query = 'INSERT INTO mod_cases (action, user_id, mod_id, issued, duration, reason) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id;'
duration = duration.delta if duration is not None else duration
record = await self.bot.pool.fetchrow(query, action, member.id, moderator.id, issued, duration, reason)
embed = discord.Embed()
if action == 'warn':
embed.colour = discord.Colour.gold()
elif action == 'mute' or action == 'tempmute':
embed.colour = discord.Colour.orange()
elif action == 'kick':
embed.colour = discord.Colour.dark_orange()
elif action == 'ban' or action == 'tempban':
embed.colour = discord.Colour.red()
elif action == 'unmute' or action == 'unban':
embed.colour = discord.Colour.blue()
embed.set_author(name=action.capitalize(), icon_url=member.avatar_url)
embed.description = f'{member.mention} {member}'
embed.add_field(name='Moderator', value=f'{moderator.mention} {moderator}', inline=False)
if duration is not None:
embed.add_field(name='Duration', value=time.human_timedelta(duration), inline=False)
embed.add_field(name='Reason', value=formatting.truncate(reason, 512) if reason is not None else 'None')
embed.set_footer(text=f'Case #{record["id"]} • ID: {member.id}')
embed.timestamp = issued
channel = discord.utils.get(guild.channels, name=self.log_channel)
await channel.send(embed=embed)
async def temp_action(self, action: str, member: discord.Member, duration: time.ShortTime):
timers = self.bot.get_cog('Timers')
if timers is None:
return
query = 'SELECT * FROM mod_tempactions WHERE user_id = $1 AND action = $2'
record = await self.bot.pool.fetchrow(query, member.id, action)
if record is None:
timer = await timers.create_timer(action, duration.datetime)
query = 'INSERT INTO mod_tempactions (user_id, action, timer_id) VALUES ($1, $2, $3);'
await self.bot.pool.execute(query, member.id, action, timer.id)
else:
await timers.update_timer(record['timer_id'], duration.datetime)
async def on_tempmute_timer_complete(self, timer):
query = 'SELECT * FROM mod_tempactions WHERE timer_id = ($1);'
record = await self.bot.pool.fetchrow(query, timer.id)
timers = self.bot.get_cog('Timers')
if timers is None:
return
await timers.remove_timer(timer.id)
if record is not None:
guild = self.bot.get_guild(self.bot.guild_id)
if guild is None:
return
member = guild.get_member(record['user_id'])
if member is None:
return
reason = 'Tempmute Expiration'
await self.log_action(guild, 'unmute', member, self.bot.user, datetime.datetime.utcnow(), reason=reason)
try:
await member.send(f'You have been unmuted in **{guild.name}**.\n**Reason:** {reason}')
except discord.errors.Forbidden:
pass
role = discord.utils.get(guild.roles, name=self.mute_role)
await member.remove_roles(role, reason=reason)
async def on_tempban_timer_complete(self, timer):
query = 'SELECT * FROM mod_tempactions WHERE timer_id = ($1);'
record = await self.bot.pool.fetchrow(query, timer.id)
timers = self.bot.get_cog('Timers')
if timers is None:
return
await timers.remove_timer(timer.id)
if record is not None:
guild = self.bot.get_guild(self.bot.guild_id)
if guild is None:
return
user = await self.bot.get_user_info(record['user_id'])
if user is None:
return
reason = 'Tempban Expiration'
await self.log_action(guild, 'unban', user, self.bot.user, datetime.datetime.utcnow(), reason=reason)
await guild.unban(user, reason=reason)
@commands.command()
@commands.has_any_role('Queen', 'Inquiline', 'Alate')
@commands.guild_only()
async def warn(self, ctx, member: discord.Member, *, reason: str = None):
"""Warn a member."""
try:
await ctx.message.delete()
except discord.errors.NotFound:
pass
if checks.has_any_role(member, *self.protected_roles):
return await ctx.send(f'That member has a protected role.')
if await self.bot.is_owner(member):
return
await self.log_action(ctx.guild, 'warn', member, ctx.author, datetime.datetime.utcnow(), reason=reason)
try:
await member.send(f'You have been warned in **{ctx.guild.name}**.\n**Reason:** {reason}')
except discord.errors.Forbidden:
pass
await ctx.send(f'{member.mention} has been warned.\n**Reason:** {reason}')
@commands.command()
@commands.bot_has_permissions(manage_roles=True)
@commands.has_any_role('Queen', 'Inquiline', 'Alate')
@commands.guild_only()
async def tempmute(self, ctx, member: discord.Member, duration: time.ShortTime, *, reason: str = None):
"""Temporarily mute a member."""
try:
await ctx.message.delete()
except discord.errors.NotFound:
pass
if checks.has_any_role(member, *self.protected_roles):
return await ctx.send(f'That member has a protected role.')
if await self.bot.is_owner(member):
return
await self.temp_action('tempmute', member, duration)
await self.log_action(ctx.guild, 'tempmute', member, ctx.author, datetime.datetime.utcnow(), duration=duration, reason=reason)
try:
await member.send(f'You have been temporarily muted in **{ctx.guild.name}** for {time.human_timedelta(duration.delta)}.\n**Reason:** {reason}')
except discord.errors.Forbidden:
pass
role = discord.utils.get(ctx.guild.roles, name=self.mute_role)
await member.add_roles(role, reason=reason)
await ctx.send(f'{member.mention} has been temporarily muted for {time.human_timedelta(duration.delta)}.\n**Reason:** {reason}')
@commands.command()
@commands.bot_has_permissions(manage_roles=True)
@commands.has_any_role('Queen', 'Inquiline', 'Alate')
@commands.guild_only()
async def mute(self, ctx, member: discord.Member, *, reason: str = None):
"""Mute a member."""
try:
await ctx.message.delete()
except discord.errors.NotFound:
pass
if checks.has_any_role(member, *self.protected_roles):
return await ctx.send(f'That member has a protected role.')
if await self.bot.is_owner(member):
return
query = 'SELECT timer_id FROM mod_tempactions WHERE user_id = $1 AND action = $2;'
record = await self.bot.pool.fetchrow(query, member.id, 'tempmute')
if record is not None:
timer_id = record['timer_id']
timers = self.bot.get_cog('Timers')
if timers is None:
return await ctx.send('Timers module is not loaded.')
else:
await timers.remove_timer(timer_id)
await self.log_action(ctx.guild, 'mute', member, ctx.author, datetime.datetime.utcnow(), reason=reason)
try:
await member.send(f'You have been muted in **{ctx.guild.name}**.\n**Reason:** {reason}')
except discord.errors.Forbidden:
pass
role = discord.utils.get(ctx.guild.roles, name=self.mute_role)
await member.add_roles(role, reason=reason)
await ctx.send(f'{member.mention} has been muted.\n**Reason:** {reason}')
@commands.command()
@commands.bot_has_permissions(manage_roles=True)
@commands.has_any_role('Queen', 'Inquiline', 'Alate')
@commands.guild_only()
async def unmute(self, ctx, member: discord.Member, *, reason: str = None):
"""Unmute a member."""
try:
await ctx.message.delete()
except discord.errors.NotFound:
pass
if checks.has_any_role(member, *self.protected_roles):
return await ctx.send(f'That member has a protected role.')
if await self.bot.is_owner(member):
return
query = 'SELECT timer_id FROM mod_tempactions WHERE user_id = $1 AND action = $2;'
record = await self.bot.pool.fetchrow(query, member.id, 'tempmute')
if record is not None:
timer_id = record['timer_id']
timers = self.bot.get_cog('Timers')
if timers is None:
return await ctx.send('Timers module is not loaded.')
else:
await timers.remove_timer(timer_id)
await self.log_action(ctx.guild, 'unmute', member, ctx.author, datetime.datetime.utcnow(), reason=reason)
try:
await member.send(f'You have been unmuted in **{ctx.guild.name}**.\n**Reason:** {reason}')
except discord.errors.Forbidden:
pass
role = discord.utils.get(ctx.guild.roles, name=self.mute_role)
await member.remove_roles(role, reason=reason)
await ctx.send(f'{member.mention} has been unmuted.\n**Reason:** {reason}')
@commands.command(description='Kick a user')
@commands.bot_has_permissions(kick_members=True)
@commands.has_any_role('Queen', 'Inquiline')
@commands.guild_only()
async def kick(self, ctx, member: discord.Member, *, reason: str = None):
"""Kick a member."""
try:
await ctx.message.delete()
except discord.errors.NotFound:
pass
if checks.has_any_role(member, *self.protected_roles):
return await ctx.send(f'That member has a protected role.')
if await self.bot.is_owner(member):
return
await self.log_action(ctx.guild, 'kick', member, ctx.author, datetime.datetime.utcnow(), reason=reason)
try:
await member.send(f'You have been kicked from **{ctx.guild.name}**.\n**Reason:** {reason}')
except discord.errors.Forbidden:
pass
await ctx.send(f'{member.mention} has been kicked.\n**Reason:** {reason}')
await member.kick(reason=reason)
@commands.command(description='Temporarily ban a user')
@commands.bot_has_permissions(kick_members=True)
@commands.has_any_role('Queen', 'Inquiline')
@commands.guild_only()
async def tempban(self, ctx, member: converters.UserConverter, duration: time.ShortTime, *, reason: str = None):
"""Temporarily ban a member."""
try:
await ctx.message.delete()
except discord.errors.NotFound:
pass
guild_member = ctx.guild.get_member(member.id)
if guild_member is not None and checks.has_any_role(guild_member, *self.protected_roles):
return await ctx.send(f'That member has a protected role.')
if await self.bot.is_owner(member):
return
await self.temp_action('tempban', member, duration)
await self.log_action(ctx.guild, 'tempban', member, ctx.author, datetime.datetime.utcnow(), duration=duration, reason=reason)
if guild_member is not None:
try:
await member.send(f'You have been temporarily banned from **{ctx.guild.name}** for {time.human_timedelta(duration.delta)}.\n**Reason:** {reason}')
except discord.errors.Forbidden:
pass
await ctx.send(f'{member.mention} has been temporarily banned for {time.human_timedelta(duration.delta)}.\n**Reason:** {reason}')
await ctx.guild.ban(member, reason=reason, delete_message_days=0)
@commands.command(description='Ban a user')
@commands.bot_has_permissions(ban_members=True)
@commands.has_any_role('Queen', 'Inquiline')
@commands.guild_only()
async def ban(self, ctx, member: converters.UserConverter, *, reason: str = None):
"""Ban a member."""
try:
await ctx.message.delete()
except discord.errors.NotFound:
pass
guild_member = ctx.guild.get_member(member.id)
if guild_member is not None and checks.has_any_role(guild_member, *self.protected_roles):
return await ctx.send(f'That member has a protected role.')
if await self.bot.is_owner(member):
return
query = 'SELECT timer_id FROM mod_tempactions WHERE user_id = $1 AND action = $2;'
record = await self.bot.pool.fetchrow(query, member.id, 'tempban')
if record is not None:
timer_id = record['timer_id']
timers = self.bot.get_cog('Timers')
if timers is None:
return await ctx.send('Timers module is not loaded.')
else:
await timers.remove_timer(timer_id)
await self.log_action(ctx.guild, 'ban', member, ctx.author, datetime.datetime.utcnow(), reason=reason)
if guild_member is not None:
try:
await member.send(f'You have been banned from **{ctx.guild.name}**.\n**Reason:** {reason}')
except discord.errors.Forbidden:
pass
await ctx.send(f'{member.mention} has been banned.\n**Reason:** {reason}')
await ctx.guild.ban(member, reason=reason, delete_message_days=0)
@commands.command(description='Unban a user')
@commands.bot_has_permissions(ban_members=True)
@commands.has_any_role('Queen', 'Inquiline')
@commands.guild_only()
async def unban(self, ctx, member: converters.UserConverter, *, reason: str = None):
"""Unban a member."""
try:
await ctx.message.delete()
except discord.errors.NotFound:
pass
guild_member = ctx.guild.get_member(member.id)
if guild_member is not None and checks.has_any_role(guild_member, *self.protected_roles):
return await ctx.send(f'That member has a protected role.')
if await self.bot.is_owner(member):
return
if await ctx.guild.get_ban(member) is None:
return await ctx.send(f'That member is not banned.')
query = "SELECT timer_id FROM mod_tempactions WHERE user_id = $1 AND action = $2;"
record = await self.bot.pool.fetchrow(query, member.id, 'tempban')
if record is not None:
timer_id = record['timer_id']
timers = self.bot.get_cog('Timers')
if timers is None:
return await ctx.send('Timers module is not loaded.')
else:
await timers.remove_timer(timer_id)
await self.log_action(ctx.guild, 'unban', member, ctx.author, datetime.datetime.utcnow(), reason=reason)
await ctx.guild.unban(member, reason=reason)
@commands.group(name='case', description='View a mod case', invoke_without_command=True)
@commands.bot_has_permissions(embed_links=True)
@commands.has_any_role('Queen', 'Inquiline', 'Alate')
@commands.guild_only()
async def case(self, ctx, case: int):
"""View a mod case."""
query = 'SELECT * FROM mod_cases WHERE id = $1;'
record = await self.bot.pool.fetchrow(query, case)
if record is None:
return await ctx.send(f'Case #{case} not found.')
action = record['action']
user_id = record['user_id']
mod_id = record['mod_id']
issued = record['issued']
duration = record['duration']
reason = record['reason']
member = ctx.guild.get_member(user_id) or await self.bot.get_user_info(user_id)
moderator = ctx.guild.get_member(mod_id)
embed = discord.Embed()
if action == 'warn':
embed.colour = discord.Colour.gold()
elif action == 'mute' or action == 'tempmute':
embed.colour = discord.Colour.orange()
elif action == 'kick':
embed.colour = discord.Colour.dark_orange()
elif action == 'ban' or action == 'tempban':
embed.colour = discord.Colour.red()
elif action == 'unmute' or action == 'unban':
embed.colour = discord.Colour.blue()
embed.set_author(name=f'{action.capitalize()}', icon_url=member.avatar_url)
embed.description = f'{member.mention} {member}'
embed.add_field(name='Moderator', value=f'{moderator.mention} {moderator}', inline=False)
if duration is not None:
embed.add_field(name='Duration', value=time.human_timedelta(duration), inline=False)
embed.add_field(name='Reason', value=formatting.truncate(reason, 512) if reason is not None else 'None')
embed.set_footer(text=f'Case #{record["id"]} • ID: {member.id}')
embed.timestamp = issued
await ctx.send(embed=embed)
@case.command(name='update', description='Update a mod case')
@commands.bot_has_permissions(embed_links=True)
@commands.has_any_role('Queen', 'Inquiline', 'Alate')
@commands.guild_only()
async def case_update(self, ctx, case: int, *, reason: str):
"""Update a mod case."""
query = 'UPDATE mod_cases SET reason = $1 WHERE id = $2 RETURNING *;'
record = await self.bot.pool.fetchrow(query, reason, case)
if record is None:
return await ctx.send(f'Case #{case} not found.')
action = record['action']
user_id = record['user_id']
mod_id = record['mod_id']
issued = record['issued']
duration = record['duration']
reason = record['reason']
member = ctx.guild.get_member(user_id) or await self.bot.get_user_info(user_id)
moderator = ctx.guild.get_member(mod_id)
embed = discord.Embed()
if action == 'warn':
embed.colour = discord.Colour.gold()
elif action == 'mute' or action == 'tempmute':
embed.colour = discord.Colour.orange()
elif action == 'kick':
embed.colour = discord.Colour.dark_orange()
elif action == 'ban' or action == 'tempban':
embed.colour = discord.Colour.red()
elif action == 'unmute' or action == 'unban':
embed.colour = discord.Colour.blue()
embed.set_author(name=f'{action.capitalize()} • Update', icon_url=member.avatar_url)
embed.description = f'{member.mention} {member}'
embed.add_field(name='Moderator', value=f'{moderator.mention} {moderator}', inline=False)
if duration is not None:
embed.add_field(name='Duration', value=time.human_timedelta(duration), inline=False)
embed.add_field(name='Reason', value=formatting.truncate(reason, 512) if reason is not None else 'None')
embed.set_footer(text=f'Case #{record["id"]} • ID: {member.id}')
embed.timestamp = issued
channel = discord.utils.get(ctx.guild.channels, name=self.log_channel)
await channel.send(embed=embed)
@case.command(name='pardon', description='Pardon a mod case')
# @commands.bot_has_permissions(ban_members=True, manage_roles=True, embed_links=True)
@commands.has_any_role('Queen', 'Inquiline')
@commands.guild_only()
async def case_pardon(self, ctx, case: int):
"""Pardon a mod case."""
query = 'DELETE FROM mod_cases WHERE id = $1 RETURNING *;'
record = await self.bot.pool.fetchrow(query, case)
if record is None:
return await ctx.send(f'Case #{case} not found.')
'''action = record['action']
user_id = record['user_id']
member = ctx.guild.get_member(user_id) or await self.bot.get_user_info(user_id)
if action == 'tempmute' or action == 'tempban':
query = 'SELECT timer_id FROM mod_tempactions WHERE user_id = $1 AND action = $2;'
record = await self.bot.pool.fetchrow(query, user_id, action)
if record is not None:
timer_id = record['timer_id']
timers = self.bot.get_cog('Timers')
if timers is None:
return await ctx.send('Timers module is not loaded.')
else:
await timers.remove_timer(timer_id)
if action == 'mute' or action == 'tempmute':
role = discord.utils.get(ctx.guild.roles, name=self.mute_role)
await member.remove_roles(role, reason='Pardon')
if action == 'ban' or action == 'tempban':
await ctx.guild.unban(member, reason='Pardon')'''
await ctx.send(f'Case #{case} has been pardoned.')
@commands.command(description='View all mod cases for a user')
@commands.bot_has_permissions(embed_links=True)
@commands.has_any_role('Queen', 'Inquiline', 'Alate')
@commands.guild_only()
async def cases(self, ctx, member: converters.UserConverter):
"""View all mod cases for a member."""
query = 'SELECT * FROM mod_cases WHERE user_id = $1 ORDER BY issued DESC;'
records = await self.bot.pool.fetch(query, member.id)
if len(records) == 0:
return await ctx.send("None found.")
entries = []
for record in records:
id = record['id']
action = record['action']
issued = time.human_timedelta(datetime.datetime.utcnow() - record['issued'], largest_only=True)
duration = record['duration']
duration = time.human_timedelta(duration) if duration is not None else None
reason = record['reason']
if duration is None:
entries.append(f'#{id} • *{action.capitalize()}* • {reason} • {issued} ago')
else:
entries.append(f'#{id} • *{action.capitalize()}* ({duration}) • {reason} • {issued} ago')
p = Pages(ctx, entries=entries)
p.embed.set_author(name=f'{member} Cases', icon_url=member.avatar_url)
p.embed.colour = discord.Colour.red()
await p.paginate()
def setup(bot):
bot.add_cog(Moderation(bot))
| 38.05719 | 200 | 0.619338 | 2,952 | 23,291 | 4.782182 | 0.064363 | 0.021818 | 0.022951 | 0.018418 | 0.843593 | 0.813062 | 0.780265 | 0.759793 | 0.722321 | 0.71042 | 0 | 0.002371 | 0.257524 | 23,291 | 611 | 201 | 38.119476 | 0.813393 | 0.004852 | 0 | 0.696386 | 0 | 0.014458 | 0.182134 | 0.023635 | 0 | 0 | 0 | 0 | 0 | 1 | 0.004819 | false | 0.038554 | 0.014458 | 0 | 0.103614 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
4d3596dfb941927800bc8d91161e4bf29887da66 | 30 | py | Python | sketchy/terminal/feature/__init__.py | mbhall88/sketchy | 5ed26d28f104710f6d425053eae41fd0e99f8760 | [
"MIT"
] | null | null | null | sketchy/terminal/feature/__init__.py | mbhall88/sketchy | 5ed26d28f104710f6d425053eae41fd0e99f8760 | [
"MIT"
] | null | null | null | sketchy/terminal/feature/__init__.py | mbhall88/sketchy | 5ed26d28f104710f6d425053eae41fd0e99f8760 | [
"MIT"
] | null | null | null | from .feature import feature
| 15 | 29 | 0.8 | 4 | 30 | 6 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | 30 | 1 | 30 | 30 | 0.96 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
4d69e741e5f3e0de349fa22a3686d7847e676c9a | 135 | py | Python | lcd/admin.py | bwackwat/local-climate-detail | 3be454e8bdbb6fa7bf83bf189b97346190eb66c8 | [
"MIT"
] | 1 | 2019-08-15T00:20:23.000Z | 2019-08-15T00:20:23.000Z | lcd/admin.py | bwackwat/local-climate-detail | 3be454e8bdbb6fa7bf83bf189b97346190eb66c8 | [
"MIT"
] | null | null | null | lcd/admin.py | bwackwat/local-climate-detail | 3be454e8bdbb6fa7bf83bf189b97346190eb66c8 | [
"MIT"
] | null | null | null | from django.contrib import admin
from lcd.models import *
admin.site.register(SensorLocation)
admin.site.register(ClimateData)
| 19.285714 | 36 | 0.785185 | 17 | 135 | 6.235294 | 0.647059 | 0.207547 | 0.320755 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.133333 | 135 | 6 | 37 | 22.5 | 0.905983 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.5 | 0 | 0.5 | 0 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 6 |
4d7b0b4bc85d9c965a72b21fa9f6e1bb6b4bbefb | 11,821 | py | Python | Version0.1/JSONFormatter.py | nfriedri/debie-backend-1 | 913644d582d64c4e73ca97f724d3fef75eba0e6f | [
"MIT"
] | 2 | 2021-04-11T15:45:22.000Z | 2021-09-08T17:51:18.000Z | Version0.1/JSONFormatter.py | nfriedri/debie-backend | 08a20d55749afa7e07ee9b0252dd98d3b6cef689 | [
"MIT"
] | null | null | null | Version0.1/JSONFormatter.py | nfriedri/debie-backend | 08a20d55749afa7e07ee9b0252dd98d3b6cef689 | [
"MIT"
] | 1 | 2021-04-23T10:17:39.000Z | 2021-04-23T10:17:39.000Z | import calculation
import vectors
import database_handler
import augmentation
import logging
fasttext = ''
# Parses JSON-input and calls methods for vector retrieval from above specified file
def get_json_vector_from_file(content):
logging.info("DB: Vector retrieval started")
logging.info("DB: Searching for following vectors:")
logging.info("DB:" + str(content))
raw_t1 = content['T1'].split(' ')
raw_t2 = content['T2'].split(' ')
raw_a1 = content['A1'].split(' ')
raw_a2 = content['A2'].split(' ')
logging.info("T1: " + str(len(raw_t1)) + " T2: " + str(len(raw_t2)) + " A1: " + str(len(raw_a1)) + " A2: " + str(
len(raw_a2)))
test_vectors1 = vectors.load_multiple_words(fasttext, raw_t1)
logging.info("vectors1 found")
test_vectors2 = vectors.load_multiple_words(fasttext, raw_t2)
logging.info("vectors2 found")
arg_vectors1 = vectors.load_multiple_words(fasttext, raw_a1)
logging.info("vectors3 found")
arg_vectors2 = vectors.load_multiple_words(fasttext, raw_a2)
logging.info("vectors4 found")
logging.info("Retrieved set sizes: " + str(len(test_vectors1)) + " " + str(len(test_vectors2)) + " " + str(
len(arg_vectors1)) + " " + str(len(arg_vectors2)))
return test_vectors1, test_vectors2, arg_vectors1, arg_vectors2
# Parses JSON-input and calls methods for vector retrieval from databases
def retrieve_vector_from_db(content):
logging.info("DB: Retrieval of single vector started")
logging.info("DB: Searching for following vector:")
logging.info("DB:" + str(content))
database = content['EmbeddingSpace']
raw_data = content['data'].rsplit()
vector = database_handler.get_vector_from_database(raw_data, database)
logging.info("DB: Found vector to word " + raw_data)
return vector
# Parses JSON-input for bias evaluation and calls methods for vector retrieval from databases
def retrieve_vectors_evaluation(content, database):
logging.info("DB: Retrieval of multiple vectors started")
logging.info("DB: Searching for following vectors:")
logging.info("DB:" + str(content))
raw_t1 = content['T1'].split(' ')
raw_t2 = content['T2'].split(' ')
raw_a1 = content['A1'].split(' ')
raw_a2 = content['A2'].split(' ')
if database is None:
database = 'fasttext'
if database == "fasttext" or database == "skipgram" or database == "cbow" or database == "glove":
test_vectors1 = database_handler.get_multiple_vectors_from_db(raw_t1, database)
logging.info("DB: First set added to memory")
test_vectors2 = database_handler.get_multiple_vectors_from_db(raw_t2, database)
logging.info("DB: Second set added to memory")
arg_vectors1 = database_handler.get_multiple_vectors_from_db(raw_a1, database)
logging.info("DB: Third set added to memory")
arg_vectors2 = database_handler.get_multiple_vectors_from_db(raw_a2, database)
logging.info("DB: Fourth set added to memory")
logging.info("DB: Found set sizes: " + str(len(test_vectors1)) + " " + str(len(test_vectors2)) + " " + str(
len(arg_vectors1)) + " " + str(len(test_vectors2)))
else:
file = "uploads\\files\\" + database
test_vectors1 = vectors.load_multiple_words(file, raw_t1)
logging.info("DB: First set added to memory")
test_vectors2 = vectors.load_multiple_words(file, raw_t2)
logging.info("DB: Second set added to memory")
arg_vectors1 = vectors.load_multiple_words(file, raw_a1)
logging.info("DB: Third set added to memory")
arg_vectors2 = vectors.load_multiple_words(file, raw_a2)
return test_vectors1, test_vectors2, arg_vectors1, arg_vectors2
# Parses JSON-input for debiasing and calls methods for vector retrieval from databases with optional augmentations
def retrieve_vectors_debiasing(content, database, augment_flag):
logging.info("DB: Retrieval of multiple vectors started")
logging.info("DB: Searching for following vectors:")
logging.info("DB:" + str(content))
raw_t1 = content['T1'].split(' ')
raw_t2 = content['T2'].split(' ')
raw_a1 = content['A1'].split(' ')
raw_a2 = content['A2'].split(' ')
if database is None:
database = 'fasttext'
if database == "uploadSpace":
file = "uploads\\files\\" + database
target_vectors1 = vectors.load_multiple_words(file, raw_t1)
logging.info("DB: First set added to memory")
target_vectors2 = vectors.load_multiple_words(file, raw_t2)
logging.info("DB: Second set added to memory")
attributes1 = vectors.load_multiple_words(file, raw_a1)
logging.info("DB: Third set added to memory")
attributes2 = vectors.load_multiple_words(file, raw_a2)
logging.info("DB: Fourth set added to memory")
if augment_flag == 'true':
raw_aug1 = content['AugT1'].split(' ')
raw_aug2 = content['AugT2'].split(' ')
raw_aug3 = content['AugA1'].split(' ')
raw_aug4 = content['AugA2'].split(' ')
augments_T1 = vectors.load_multiple_words(file, raw_aug1)
augments_T2 = vectors.load_multiple_words(file, raw_aug2)
augments_A1 = vectors.load_multiple_words(file, raw_aug3)
augments_A2 = vectors.load_multiple_words(file, raw_aug4)
logging.info("DB: Retrieved augmentations")
else:
aug_list_T1 = database_handler.get_multiple_augmentation_from_db(list(target_vectors1.keys()))
aug_list_T2 = database_handler.get_multiple_augmentation_from_db(list(target_vectors2.keys()))
aug_list_A1 = database_handler.get_multiple_augmentation_from_db(list(attributes1.keys()))
aug_list_A2 = database_handler.get_multiple_augmentation_from_db(list(attributes2.keys()))
augments_T1 = database_handler.get_multiple_vectors_from_db(aug_list_T1, database)
augments_T2 = database_handler.get_multiple_vectors_from_db(aug_list_T2, database)
augments_A1 = database_handler.get_multiple_vectors_from_db(aug_list_A1, database)
augments_A2 = database_handler.get_multiple_vectors_from_db(aug_list_A2, database)
logging.info("DB: Retrieved augmentations")
else:
target_vectors1 = database_handler.get_multiple_vectors_from_db(raw_t1, database)
logging.info("DB: First set added to memory")
target_vectors2 = database_handler.get_multiple_vectors_from_db(raw_t2, database)
logging.info("DB: Second set added to memory")
attributes1 = database_handler.get_multiple_vectors_from_db(raw_a1, database)
logging.info("DB: Third set added to memory")
attributes2 = database_handler.get_multiple_vectors_from_db(raw_a2, database)
logging.info("DB: Fourth set added to memory")
logging.info("DB: Found set sizes: " + str(len(target_vectors1)) + " " + str(len(target_vectors2)))
if augment_flag == 'true':
raw_aug1 = content['AugT1'].split(' ')
raw_aug2 = content['AugT2'].split(' ')
raw_aug3 = content['AugA1'].split(' ')
raw_aug4 = content['AugA2'].split(' ')
augments_T1 = database_handler.get_multiple_vectors_from_db(raw_aug1, database)
augments_T2 = database_handler.get_multiple_vectors_from_db(raw_aug2, database)
augments_A1 = database_handler.get_multiple_vectors_from_db(raw_aug3, database)
augments_A2 = database_handler.get_multiple_vectors_from_db(raw_aug4, database)
logging.info("DB: Retrieved augmentations")
else:
aug_list_T1 = database_handler.get_multiple_augmentation_from_db(list(target_vectors1.keys()))
aug_list_T2 = database_handler.get_multiple_augmentation_from_db(list(target_vectors2.keys()))
aug_list_A1 = database_handler.get_multiple_augmentation_from_db(list(attributes1.keys()))
aug_list_A2 = database_handler.get_multiple_augmentation_from_db(list(attributes2.keys()))
augments_T1 = database_handler.get_multiple_vectors_from_db(aug_list_T1, database)
augments_T2 = database_handler.get_multiple_vectors_from_db(aug_list_T2, database)
augments_A1 = database_handler.get_multiple_vectors_from_db(aug_list_A1, database)
augments_A2 = database_handler.get_multiple_vectors_from_db(aug_list_A2, database)
logging.info("DB: Retrieved augmentations")
return target_vectors1, target_vectors2, attributes1, attributes2, augments_T1, augments_T2, augments_A1, augments_A2
# Parses JSON-input for bias evaluation and calls methods for vector retrieval from the input JSON-file
def retrieve_vectors_from_json_evaluation(content):
logging.info("DB: Loading Vectors from JSON Input.")
target_dict1 = {}
target_dict2 = {}
attribute_dict1 = {}
attribute_dict2 = {}
for pair in content['T1']:
word = pair['word']
vec = pair['vec']
target_dict1[word] = vec.split(' ')
for pair in content['T2']:
word = pair['word']
vec = pair['vec']
target_dict2[word] = vec.split(' ')
for pair in content['A1']:
word = pair['word']
vec = pair['vec']
attribute_dict1[word] = vec.split(' ')
for pair in content['A2']:
word = pair['word']
vec = pair['vec']
attribute_dict2[word] = vec.split(' ')
logging.info("DB: Loaded JSON Input successfully.")
return target_dict1, target_dict2, attribute_dict1, attribute_dict2
# Parses JSON-input for debiasing and calls methods for vector retrieval from the input JSON-file
def retrieve_vectors_from_json_debiasing(content):
logging.info("DB: Loading Vectors from JSON Input.")
target_dict1 = {}
target_dict2 = {}
attribute_dict1 = {}
attribute_dict2 = {}
augmentation_dict1 = {}
augmentation_dict2 = {}
augmentation_dict3 = {}
augmentation_dict4 = {}
for pair in content['T1']:
word = pair['word']
vec = pair['vec']
target_dict1[word] = vec.split(' ')
for pair in content['T2']:
word = pair['word']
vec = pair['vec']
target_dict2[word] = vec.split(' ')
for pair in content['A1']:
word = pair['word']
vec = pair['vec']
attribute_dict1[word] = vec.split(' ')
for pair in content['A2']:
word = pair['word']
vec = pair['vec']
attribute_dict2[word] = vec.split(' ')
for pair in content['AugT1']:
word = pair['word']
vec = pair['vec']
augmentation_dict1[word] = vec.split(' ')
for pair in content['AugT2']:
word = pair['word']
vec = pair['vec']
augmentation_dict1[word] = vec.split(' ')
for pair in content['AugA1']:
word = pair['word']
vec = pair['vec']
augmentation_dict1[word] = vec.split(' ')
for pair in content['AugA2']:
word = pair['word']
vec = pair['vec']
augmentation_dict1[word] = vec.split(' ')
logging.info("DB: Loaded JSON Input successfully.")
return target_dict1, target_dict2, attribute_dict1, attribute_dict2, augmentation_dict1, augmentation_dict2, augmentation_dict3, augmentation_dict4
# Transformes dictionaries into JSON-format
def dict_to_json(vector_dict):
vector_dict_copy = calculation.create_duplicates(vector_dict)
string_dict = {}
for word in vector_dict_copy:
string_dict[word] = str(list(vector_dict_copy[word]))
return string_dict
# Transforms keys of a dictioanry into a string
def dict_keys_to_string(vector_dict):
vector_dict_copy = calculation.create_duplicates(vector_dict)
keys = ''
for word in vector_dict_copy.keys():
keys += str(word) + ' '
return keys
| 47.284 | 151 | 0.679976 | 1,505 | 11,821 | 5.071096 | 0.083056 | 0.063417 | 0.064727 | 0.095388 | 0.837919 | 0.830189 | 0.805556 | 0.767427 | 0.757993 | 0.747117 | 0 | 0.022836 | 0.207258 | 11,821 | 249 | 152 | 47.473896 | 0.791591 | 0.054649 | 0 | 0.623853 | 0 | 0 | 0.13362 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.036697 | false | 0 | 0.022936 | 0 | 0.09633 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
4ddd629d00e745f631888e53e62e3b120ba5cc05 | 41 | py | Python | lio/models/__init__.py | YivanZhang/lio | 07587a6d864e7876b2ae4cdc00e59ac1b82781bc | [
"MIT"
] | 8 | 2021-04-16T14:33:42.000Z | 2022-03-23T03:47:33.000Z | lio/models/__init__.py | YivanZhang/lio | 07587a6d864e7876b2ae4cdc00e59ac1b82781bc | [
"MIT"
] | 1 | 2021-08-20T18:33:24.000Z | 2021-08-21T14:54:00.000Z | lio/models/__init__.py | YivanZhang/lio | 07587a6d864e7876b2ae4cdc00e59ac1b82781bc | [
"MIT"
] | null | null | null | from . import mnist
from . import resnet
| 13.666667 | 20 | 0.756098 | 6 | 41 | 5.166667 | 0.666667 | 0.645161 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.195122 | 41 | 2 | 21 | 20.5 | 0.939394 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 6 |
1510f7d6b7b4c08915fd4ed6a96d15d88acc15ec | 1,226 | py | Python | simulation/heater_pwm/heater_pwm.py | solderdev/silvia | a1c5f255054849306b8383e0a98fb7322a7b625f | [
"MIT"
] | 1 | 2020-12-03T20:26:48.000Z | 2020-12-03T20:26:48.000Z | simulation/heater_pwm/heater_pwm.py | solderdev/silvia | a1c5f255054849306b8383e0a98fb7322a7b625f | [
"MIT"
] | null | null | null | simulation/heater_pwm/heater_pwm.py | solderdev/silvia | a1c5f255054849306b8383e0a98fb7322a7b625f | [
"MIT"
] | null | null | null | import numpy as np
# pwm = np.zeros((10, 10))
# percent = 25
#
# # fill array in each 10-percent field (tens) with 1s according to number of every 10%
# max_ones = int(percent/10)
# for tens in range(0, 10):
# for ones in range(0, max_ones):
# pwm[tens][ones] = 1
#
# # now handle remaining 0% to 9% on the first digit of the overall percent value
# max_tens = int(percent - int(percent/10)*10)
# for tens in range(0, max_tens):
# pwm[tens][max_ones] = 1
#
# for idx, val in enumerate(pwm):
# print(str(idx), val)
pwm = np.zeros(10)
percent = 25
# fill array in each 10-percent field (tens) with 1s according to number of every 10%
max_ones = int(percent/10)
for tens in range(0, 10):
for ones in range(0, max_ones):
pwm[tens] += 1
# now handle remaining 0% to 9% on the first digit of the overall percent value
max_tens = int(percent - int(percent/10)*10)
for tens in range(0, max_tens):
pwm[tens] += 1
for idx, val in enumerate(pwm):
print(str(idx), val)
for period in range(0, 100):
if period % 10 == 0:
print("/// ", int(period/10))
if pwm[int(period / 10)] > period % 10:
print(1)
else:
print(0) | 27.863636 | 88 | 0.608483 | 206 | 1,226 | 3.57767 | 0.23301 | 0.066486 | 0.075984 | 0.059701 | 0.816825 | 0.816825 | 0.816825 | 0.816825 | 0.816825 | 0.816825 | 0 | 0.071665 | 0.260196 | 1,226 | 44 | 89 | 27.863636 | 0.740904 | 0.523654 | 0 | 0.105263 | 0 | 0 | 0.007678 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.052632 | 0 | 0.052632 | 0.210526 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
12c216347a3db852bddad78bd6e7f21bcc83939b | 8,695 | py | Python | tests/pytests/unit/modules/test_mac_softwareupdate.py | tomdoherty/salt | f87d5d7abbf9777773c4d91fdafecb8b1a728e76 | [
"Apache-2.0"
] | 9,425 | 2015-01-01T05:59:24.000Z | 2022-03-31T20:44:05.000Z | tests/pytests/unit/modules/test_mac_softwareupdate.py | tomdoherty/salt | f87d5d7abbf9777773c4d91fdafecb8b1a728e76 | [
"Apache-2.0"
] | 33,507 | 2015-01-01T00:19:56.000Z | 2022-03-31T23:48:20.000Z | tests/pytests/unit/modules/test_mac_softwareupdate.py | tomdoherty/salt | f87d5d7abbf9777773c4d91fdafecb8b1a728e76 | [
"Apache-2.0"
] | 5,810 | 2015-01-01T19:11:45.000Z | 2022-03-31T02:37:20.000Z | import pytest
import salt.modules.mac_softwareupdate as mac_softwareupdate
from tests.support.mock import MagicMock, patch
MOJAVE_LIST_OUTPUT = """Software Update Tool
Finding available software
Software Update found the following new or updated software:
* Command Line Tools (macOS Mojave version 10.14) for Xcode-10.3
Command Line Tools (macOS Mojave version 10.14) for Xcode (10.3), 199140K [recommended]
* macOS 10.14.1 Update
macOS 10.14.1 Update (10.14.1), 199140K [recommended] [restart]
* BridgeOSUpdateCustomer
BridgeOSUpdateCustomer (10.14.4.1.1.1555388607), 328394K, [recommended] [shut down]
- iCal-1.0.2
iCal, (1.0.2), 6520K"""
CATALINA_LIST_OUTPUT = """Software Update Tool
Finding available software
Software Update found the following new or updated software:
* Label: Command Line Tools beta 5 for Xcode-11.0
Title: Command Line Tools beta 5 for Xcode, Version: 11.0, Size: 224804K, Recommended: YES,
* Label: macOS Catalina Developer Beta-6
Title: macOS Catalina Public Beta, Version: 5, Size: 3084292K, Recommended: YES, Action: restart,
* Label: BridgeOSUpdateCustomer
Title: BridgeOSUpdateCustomer, Version: 10.15.0.1.1.1560926689, Size: 390674K, Recommended: YES, Action: shut down,
- Label: iCal-1.0.2
Title: iCal, Version: 1.0.2, Size: 6520K,"""
@pytest.fixture
def configure_loader_modules():
return {mac_softwareupdate: {}}
def test_mojave_list_available():
with patch.dict(mac_softwareupdate.__grains__, {"osrelease_info": [10, 14, 6]}):
with patch(
"salt.utils.mac_utils.execute_return_result",
MagicMock(return_value=MOJAVE_LIST_OUTPUT),
):
result = mac_softwareupdate.list_available()
expected = {
"Command Line Tools (macOS Mojave version 10.14) for Xcode-10.3": "10.3",
"macOS 10.14.1 Update": "10.14.1",
"BridgeOSUpdateCustomer": "10.14.4.1.1.1555388607",
"iCal-1.0.2": "1.0.2",
}
assert result == expected
def test_mojave_list_available_trailing_ws():
"""Ensure the regex works with trailing whitespace in labels"""
with patch.dict(mac_softwareupdate.__grains__, {"osrelease_info": [10, 14, 6]}):
with patch(
"salt.utils.mac_utils.execute_return_result",
MagicMock(
return_value=(
"Software Update Tool\n\nFinding available software\nSoftware Update found"
" the following new or updated software:\n * macOS Mojave 10.14.6"
" Supplemental Update- \n macOS Mojave 10.14.6 Supplemental Update ( ),"
" 1581834K [recommended] [restart]"
)
),
):
result = mac_softwareupdate.list_available()
expected = {"macOS Mojave 10.14.6 Supplemental Update- ": ""}
assert result == expected
def test_mojave_list_recommended():
with patch.dict(mac_softwareupdate.__grains__, {"osrelease_info": [10, 14, 6]}):
with patch(
"salt.utils.mac_utils.execute_return_result",
MagicMock(return_value=MOJAVE_LIST_OUTPUT),
):
result = mac_softwareupdate.list_available(recommended=True)
expected = {
"Command Line Tools (macOS Mojave version 10.14) for Xcode-10.3": "10.3",
"macOS 10.14.1 Update": "10.14.1",
"BridgeOSUpdateCustomer": "10.14.4.1.1.1555388607",
}
assert result == expected
def test_mojave_list_restart():
with patch.dict(mac_softwareupdate.__grains__, {"osrelease_info": [10, 14, 6]}):
with patch(
"salt.utils.mac_utils.execute_return_result",
MagicMock(return_value=MOJAVE_LIST_OUTPUT),
):
result = mac_softwareupdate.list_available(restart=True)
expected = {"macOS 10.14.1 Update": "10.14.1"}
assert result == expected
def test_mojave_list_shut_down():
with patch.dict(mac_softwareupdate.__grains__, {"osrelease_info": [10, 14, 6]}):
with patch(
"salt.utils.mac_utils.execute_return_result",
MagicMock(return_value=MOJAVE_LIST_OUTPUT),
):
result = mac_softwareupdate.list_available(shut_down=True)
expected = {"BridgeOSUpdateCustomer": "10.14.4.1.1.1555388607"}
assert result == expected
def test_catalina_list_available():
with patch.dict(mac_softwareupdate.__grains__, {"osrelease_info": [10, 15]}):
with patch(
"salt.utils.mac_utils.execute_return_result",
MagicMock(return_value=CATALINA_LIST_OUTPUT),
):
result = mac_softwareupdate.list_available()
expected = {
"Command Line Tools beta 5 for Xcode-11.0": "11.0",
"macOS Catalina Developer Beta-6": "5",
"BridgeOSUpdateCustomer": "10.15.0.1.1.1560926689",
"iCal-1.0.2": "1.0.2",
}
assert result == expected
def test_catalina_list_recommended():
with patch.dict(mac_softwareupdate.__grains__, {"osrelease_info": [10, 15]}):
with patch(
"salt.utils.mac_utils.execute_return_result",
MagicMock(return_value=CATALINA_LIST_OUTPUT),
):
result = mac_softwareupdate.list_available(recommended=True)
expected = {
"Command Line Tools beta 5 for Xcode-11.0": "11.0",
"macOS Catalina Developer Beta-6": "5",
"BridgeOSUpdateCustomer": "10.15.0.1.1.1560926689",
}
assert result == expected
def test_catalina_list_restart():
with patch.dict(mac_softwareupdate.__grains__, {"osrelease_info": [10, 15]}):
with patch(
"salt.utils.mac_utils.execute_return_result",
MagicMock(return_value=CATALINA_LIST_OUTPUT),
):
result = mac_softwareupdate.list_available(restart=True)
expected = {"macOS Catalina Developer Beta-6": "5"}
assert result == expected
def test_catalina_list_shut_down():
with patch.dict(mac_softwareupdate.__grains__, {"osrelease_info": [10, 15]}):
with patch(
"salt.utils.mac_utils.execute_return_result",
MagicMock(return_value=CATALINA_LIST_OUTPUT),
):
result = mac_softwareupdate.list_available(shut_down=True)
expected = {"BridgeOSUpdateCustomer": "10.15.0.1.1.1560926689"}
assert result == expected
def test_bigsur_list_available():
with patch.dict(mac_softwareupdate.__grains__, {"osrelease_info": [11, 0]}):
with patch(
"salt.utils.mac_utils.execute_return_result",
MagicMock(return_value=CATALINA_LIST_OUTPUT),
):
result = mac_softwareupdate.list_available()
expected = {
"Command Line Tools beta 5 for Xcode-11.0": "11.0",
"macOS Catalina Developer Beta-6": "5",
"BridgeOSUpdateCustomer": "10.15.0.1.1.1560926689",
"iCal-1.0.2": "1.0.2",
}
assert result == expected
def test_bigsur_list_recommended():
with patch.dict(mac_softwareupdate.__grains__, {"osrelease_info": [11, 0]}):
with patch(
"salt.utils.mac_utils.execute_return_result",
MagicMock(return_value=CATALINA_LIST_OUTPUT),
):
result = mac_softwareupdate.list_available(recommended=True)
expected = {
"Command Line Tools beta 5 for Xcode-11.0": "11.0",
"macOS Catalina Developer Beta-6": "5",
"BridgeOSUpdateCustomer": "10.15.0.1.1.1560926689",
}
assert result == expected
def test_bigsur_list_restart():
with patch.dict(mac_softwareupdate.__grains__, {"osrelease_info": [11, 0]}):
with patch(
"salt.utils.mac_utils.execute_return_result",
MagicMock(return_value=CATALINA_LIST_OUTPUT),
):
result = mac_softwareupdate.list_available(restart=True)
expected = {"macOS Catalina Developer Beta-6": "5"}
assert result == expected
def test_bigsur_list_shut_down():
with patch.dict(mac_softwareupdate.__grains__, {"osrelease_info": [11, 0]}):
with patch(
"salt.utils.mac_utils.execute_return_result",
MagicMock(return_value=CATALINA_LIST_OUTPUT),
):
result = mac_softwareupdate.list_available(shut_down=True)
expected = {"BridgeOSUpdateCustomer": "10.15.0.1.1.1560926689"}
assert result == expected
| 40.630841 | 119 | 0.626682 | 1,002 | 8,695 | 5.202595 | 0.0998 | 0.094571 | 0.032419 | 0.0399 | 0.867063 | 0.854594 | 0.842893 | 0.799156 | 0.770382 | 0.764243 | 0 | 0.072688 | 0.26268 | 8,695 | 213 | 120 | 40.821596 | 0.740446 | 0.006555 | 0 | 0.698324 | 0 | 0.03352 | 0.367586 | 0.125 | 0 | 0 | 0 | 0 | 0.072626 | 1 | 0.078212 | false | 0 | 0.01676 | 0.005587 | 0.100559 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
12d11c3d6a3561e2a311f7031071dd0af80501cb | 104,020 | py | Python | hottbox/core/tests/test_structures.py | adamurban98/hottbox | 26580018ec6d38a1b08266c04ce4408c9e276130 | [
"Apache-2.0"
] | 167 | 2018-05-07T10:31:00.000Z | 2022-02-24T19:20:31.000Z | hottbox/core/tests/test_structures.py | adamurban98/hottbox | 26580018ec6d38a1b08266c04ce4408c9e276130 | [
"Apache-2.0"
] | 19 | 2018-05-10T13:26:39.000Z | 2020-01-31T12:49:27.000Z | hottbox/core/tests/test_structures.py | adamurban98/hottbox | 26580018ec6d38a1b08266c04ce4408c9e276130 | [
"Apache-2.0"
] | 24 | 2018-04-02T17:16:50.000Z | 2021-12-07T06:21:40.000Z | import pytest
import sys
import io
import numpy as np
from functools import reduce
from ..structures import Tensor, BaseTensorTD, TensorCPD, TensorTKD, TensorTT
from ..operations import unfold, kolda_unfold, mode_n_product
from .._meta import State
from ...errors import TensorModeError, TensorShapeError, TensorStateError, TensorTopologyError, ModeError, StateError
# TODO: find a better way to test the methods that only prints and for __repr__ and __str__
class TestTensor:
""" Tests for Tensor class """
def test_init(self):
""" Tests for Tensor object creation """
# ------ tests for basic properties of a tensor with default mode names
true_shape = (2, 4, 8)
true_size = reduce(lambda x, y: x * y, true_shape)
true_order = len(true_shape)
true_data = np.ones(true_size).reshape(true_shape)
true_default_mode_names = ['mode-0', 'mode-1', 'mode-2']
true_default_state = State(normal_shape=true_shape)
tensor = Tensor(array=true_data)
np.testing.assert_array_equal(tensor.data, true_data)
assert (tensor.frob_norm == 8.0)
assert (tensor.shape == true_shape)
assert (tensor.ft_shape == true_shape)
assert (tensor.order == true_order)
assert (tensor.size == true_size)
assert (tensor.mode_names == true_default_mode_names)
assert (tensor._state == true_default_state)
assert (tensor._data is not true_data) # check that is not a reference
# ------ tests for creating a Tensor object with custom mode names
true_custom_mode_names = ['time', 'frequency', 'channel']
tensor = Tensor(array=true_data, mode_names=true_custom_mode_names)
assert (tensor.mode_names == true_custom_mode_names)
# ------ tests for creating a Tensor object in custom state
I, J, K = 2, 4, 8
true_data = np.ones(I * J * K).reshape(I, J*K)
true_ft_shape = (I, J, K)
true_mode_order = ([0], [1, 2])
true_mode_names = ["mode-0", "mode-1_mode-2"]
custom_state = dict(normal_shape=true_ft_shape,
mode_order=true_mode_order,
rtype="T")
tensor = Tensor(array=true_data, custom_state=custom_state)
assert (tensor.ft_shape == true_ft_shape)
assert (tensor.mode_names == true_mode_names)
# ------ tests for creating a Tensor object with in custom state and with custom mode names
I, J, K = 2, 4, 8
true_data = np.ones(I * J * K).reshape(I, J * K)
true_ft_shape = (I, J, K)
true_mode_order = ([0], [1, 2])
custom_mode_names = ["time", "frequency", "channel"]
true_custom_mode_names = ["time", "frequency_channel"]
custom_state = dict(normal_shape=true_ft_shape,
mode_order=true_mode_order,
rtype="T")
tensor = Tensor(array=true_data, custom_state=custom_state, mode_names=custom_mode_names)
assert (tensor.ft_shape == true_ft_shape)
assert (tensor.mode_names == true_custom_mode_names)
def test_init_fail(self):
""" Tests for incorrect input data for the Tensor constructor """
# ------ the following tests should FAIL
correct_shape = (2, 4, 8)
size = reduce(lambda x, y: x * y, correct_shape)
order = len(correct_shape)
correct_data = np.ones(size).reshape(correct_shape)
# ------ tests that Tensor object can be created only from numpy array
# can not create from list
with pytest.raises(TypeError):
incorrect_data = [[1, 2, 3], [4, 5, 6]]
Tensor(array=incorrect_data)
# can not create from another Tensor
with pytest.raises(TypeError):
incorrect_data = Tensor(np.array([[1, 2, 3], [4, 5, 6]]))
Tensor(array=incorrect_data)
# ------ tests for custom mode names being incorrectly defined
# mode names are not of list type
with pytest.raises(ModeError):
incorrect_mode_names = {mode: "{}-mode".format(mode) for mode in range(order)}
Tensor(array=correct_data, mode_names=incorrect_mode_names)
# not enough mode names
with pytest.raises(ModeError):
incorrect_mode_names = ["{}-mode".format(mode) for mode in range(order - 1)]
Tensor(array=correct_data, mode_names=incorrect_mode_names)
# too many mode names
with pytest.raises(ModeError):
incorrect_mode_names = ["{}-mode".format(mode) for mode in range(order + 1)]
Tensor(array=correct_data, mode_names=incorrect_mode_names)
# all mode names should be strings
with pytest.raises(ModeError):
incorrect_mode_names = ["{}-mode".format(mode) for mode in range(order)]
incorrect_mode_names[0] = 0
Tensor(array=correct_data, mode_names=incorrect_mode_names)
# ------ tests for custom state being incorrectly defined
# custom state should be passed as a dict
with pytest.raises(StateError):
I, J, K = 2, 4, 8
correct_data = np.ones(I * J * K).reshape(I, J, K)
correct_normal_shape = (I, J, K)
correct_mode_order = ([0], [1], [2])
correct_rtype = "T"
incorrect_custom_state = [correct_normal_shape,
correct_mode_order,
correct_rtype]
Tensor(array=correct_data, custom_state=incorrect_custom_state)
# custom state not fully defined
with pytest.raises(StateError):
I, J, K = 2, 4, 8
correct_data = np.ones(I * J * K).reshape(I, J, K)
correct_normal_shape = (I, J, K)
correct_mode_order = ([0], [1], [2])
correct_rtype = "T"
incorrect_custom_state = dict(normal_shape=correct_normal_shape,
mode_order=correct_mode_order)
Tensor(array=correct_data, custom_state=incorrect_custom_state)
# normal shape of custom state should be a tuple
with pytest.raises(StateError):
I, J, K = 2, 4, 8
correct_data = np.ones(I * J * K).reshape(I, J, K)
incorrect_normal_shape = [I, J, K]
correct_mode_order = ([0], [1], [2])
correct_rtype = "T"
incorrect_custom_state = dict(normal_shape=incorrect_normal_shape,
mode_order=correct_mode_order,
rtype=correct_rtype)
Tensor(array=correct_data, custom_state=incorrect_custom_state)
# normal shape of custom state is inconsistent with the shape of provided data
with pytest.raises(StateError):
I, J, K = 2, 4, 8
correct_data = np.ones(I * J * K).reshape(I, J, K)
incorrect_normal_shape = (I+1, J, K)
correct_mode_order = ([0], [1], [2])
correct_rtype = "T"
incorrect_custom_state = dict(normal_shape=incorrect_normal_shape,
mode_order=correct_mode_order,
rtype=correct_rtype)
Tensor(array=correct_data, custom_state=incorrect_custom_state)
# mode order of custom state should be a !! TUPLE !! of lists
with pytest.raises(StateError):
I, J, K = 2, 4, 8
correct_data = np.ones(I * J * K).reshape(I, J, K)
correct_normal_shape = (I, J, K)
incorrect_mode_order = [[0], [1], [2]]
correct_rtype = "T"
incorrect_custom_state = dict(normal_shape=correct_normal_shape,
mode_order=incorrect_mode_order,
rtype=correct_rtype)
Tensor(array=correct_data, custom_state=incorrect_custom_state)
# mode order of custom state should be a tuple of !! LISTS !!
with pytest.raises(StateError):
I, J, K = 2, 4, 8
correct_data = np.ones(I * J * K).reshape(I, J, K)
correct_normal_shape = (I, J, K)
incorrect_mode_order = (0, 1, 2)
correct_rtype = "T"
incorrect_custom_state = dict(normal_shape=correct_normal_shape,
mode_order=incorrect_mode_order,
rtype=correct_rtype)
Tensor(array=correct_data, custom_state=incorrect_custom_state)
# number of list in mode order should correspond to the number of dimensions of provided data
with pytest.raises(StateError):
I, J, K = 2, 4, 8
correct_data = np.ones(I * J * K).reshape(I, J, K)
correct_normal_shape = (I, J, K)
incorrect_mode_order = ([0], [1, 2])
correct_rtype = "T"
incorrect_custom_state = dict(normal_shape=correct_normal_shape,
mode_order=incorrect_mode_order,
rtype=correct_rtype)
Tensor(array=correct_data, custom_state=incorrect_custom_state)
with pytest.raises(StateError):
I, J, K = 2, 4, 8
correct_data = np.ones(I * J * K).reshape(I, J*K)
correct_normal_shape = (I, J, K)
incorrect_mode_order = ([0], [1], [2])
correct_rtype = "T"
incorrect_custom_state = dict(normal_shape=correct_normal_shape,
mode_order=incorrect_mode_order,
rtype=correct_rtype)
Tensor(array=correct_data, custom_state=incorrect_custom_state)
# length of mode order of custom state is inconsistent with the normal shape
with pytest.raises(StateError):
I, J, K = 2, 4, 8
correct_data = np.ones(I * J * K).reshape(I, J, K)
correct_normal_shape = (I, J, K)
incorrect_mode_order = ([0], [1], [2, 3])
correct_rtype = "T"
incorrect_custom_state = dict(normal_shape=correct_normal_shape,
mode_order=incorrect_mode_order,
rtype=correct_rtype)
Tensor(array=correct_data, custom_state=incorrect_custom_state)
# length of normal shape of custom state is inconsistent with the length of provided mode names
with pytest.raises(ModeError):
I, J, K = 2, 4, 8
correct_data = np.ones(I * J * K).reshape(I, J, K)
correct_normal_shape = (I, J, K)
correct_mode_order = ([0], [1], [2])
correct_rtype = "T"
correct_custom_state = dict(normal_shape=correct_normal_shape,
mode_order=correct_mode_order,
rtype=correct_rtype)
incorrect_mode_names = ["frequency", "time"]
Tensor(array=correct_data, custom_state=correct_custom_state, mode_names=incorrect_mode_names)
def test_equal(self):
""" Test for tensors being equal """
shape = (2, 2, 2)
size = reduce(lambda x, y: x * y, shape)
data_1 = np.ones(size).reshape(shape)
data_2 = np.ones(size).reshape(shape)
data_3 = np.arange(size).reshape(shape)
init_names = ["country", "year", "month"]
new_mode_names = {i: "{}".format(init_names[i]) for i in range(len(shape))}
new_mode_index = {i: ["index" for _ in range(shape[i])] for i in range(len(shape))}
tensor_1 = Tensor(data_1)
tensor_2 = Tensor(data_2)
assert tensor_1 == tensor_2
tensor_1 = Tensor(array=data_1, mode_names=init_names)
tensor_2 = Tensor(array=data_2, mode_names=init_names)
assert tensor_1 == tensor_2
tensor_1 = Tensor(array=data_1).set_mode_index(mode_index=new_mode_index)
tensor_2 = Tensor(array=data_2).set_mode_index(mode_index=new_mode_index)
assert tensor_1 == tensor_2
tensor_1 = Tensor(array=data_1, mode_names=init_names)
tensor_2 = Tensor(array=data_2)
assert tensor_1 != tensor_2
tensor_2.set_mode_names(mode_names=new_mode_names)
assert tensor_1 == tensor_2
tensor_1 = Tensor(array=data_1)
tensor_2 = Tensor(array=data_3)
assert tensor_1 != tensor_2
tensor_1 = Tensor(array=data_1)
tensor_2 = Tensor(array=data_2).unfold(mode=0, inplace=True)
assert tensor_1 != tensor_2
tensor_1 = Tensor(array=data_1, mode_names=init_names)
tensor_2 = Tensor(array=data_2)
assert tensor_1 != tensor_2
tensor_1 = Tensor(array=data_1).set_mode_index(mode_index=new_mode_index)
tensor_2 = Tensor(array=data_2)
assert tensor_1 != tensor_2
assert tensor_1 != data_1
def test_addition(self):
""" Test for summation of two tensors """
shape = (2, 2, 2)
size = reduce(lambda x, y: x * y, shape)
data_1 = np.ones(size).reshape(shape)
data_2 = np.arange(size).reshape(shape)
data_res = data_1 + data_2
tensor_1 = Tensor(array=data_1)
tensor_2 = Tensor(array=data_2)
tensor_res = Tensor(array=data_res)
tensor = tensor_1 + tensor_2
assert tensor_res == tensor
tensor_1 = Tensor(array=data_1, mode_names=["country", "year", "month"])
tensor_2 = Tensor(array=data_2)
tensor_res = Tensor(array=data_res)
tensor = tensor_1 + tensor_2
assert tensor_res == tensor
#---- Tests that should fail
with pytest.raises(TypeError):
assert Tensor(data_1) + data_1
with pytest.raises(TensorStateError):
tensor_1 = Tensor(array=data_1)
tensor_2 = Tensor(array=data_2).unfold(mode=0, inplace=True)
assert tensor_1 + tensor_2
with pytest.raises(TensorModeError):
mode_index = {0: ["idx1", "idx2"]}
tensor_1 = Tensor(array=data_1)
tensor_2 = Tensor(array=data_2).set_mode_index(mode_index=mode_index)
assert tensor_1 + tensor_2
with pytest.raises(TensorShapeError):
data_2 = np.arange(2*2).reshape(2,2)
tensor_1 = Tensor(array=data_1)
tensor_2 = Tensor(array=data_2)
assert tensor_1 + tensor_2
def test_repr(self):
array = np.arange(2*3*4).reshape(2,3,4)
tensor = Tensor(array=array)
captured_output = io.StringIO() # Create StringIO object
sys.stdout = captured_output # and redirect stdout.
print(repr(tensor))
assert captured_output.getvalue() != '' # to check that something was actually printed
def test_show_state(self):
""" Tests for `show_state` method """
array = np.arange(2 * 3 * 4).reshape(2, 3, 4)
tensor = Tensor(array=array)
captured_output = io.StringIO() # Create StringIO object
sys.stdout = captured_output # and redirect stdout.
tensor.show_state()
assert captured_output.getvalue() != '' # to check that something was actually printed
def test_copy(self):
""" Tests for creation a copy of a Tensor object """
data = np.arange(24).reshape(2, 3, 4)
mode_index = {0: ["idx1", "idx2"],
1: ["idx1", "idx2", "idx3"],
2: ["idx1", "idx2", "idx3", "idx4"],}
tensor = Tensor(data, mode_names=['pixel_x', 'pixel_y', 'color']).set_mode_index(mode_index=mode_index)
tensor_copy = tensor.copy()
assert tensor_copy == tensor
assert (tensor_copy is not tensor)
assert (tensor_copy._data is not tensor._data)
assert (tensor_copy._modes is not tensor._modes)
assert (tensor_copy._state is not tensor._state)
def test_reset_meta(self):
""" Tests for `reset_meta` method """
shape = (2, 2, 2)
size = reduce(lambda x, y: x * y, shape)
data = np.ones(size).reshape(shape)
init_names = ["country", "year", "month"]
mode_index = {i: ["index" for _ in range(shape[i])] for i in range(len(shape))}
tensor = Tensor(array=data, mode_names=init_names).set_mode_index(mode_index=mode_index)
tensor.reset_meta()
tensor_true_result = Tensor(array=data)
assert tensor == tensor_true_result
def test_set_mode_names(self):
""" Tests for renaming modes """
true_shape = (2, 4, 8)
true_size = reduce(lambda x, y: x * y, true_shape)
true_order = len(true_shape)
true_data = np.ones(true_size).reshape(true_shape)
true_new_mode_names = {0: 'pixel-x',
1: 'pixel-y',
2: 'color'
}
tensor = Tensor(array=true_data)
tensor.set_mode_names(true_new_mode_names)
assert tensor.mode_names == list(true_new_mode_names.values())
# ------ tests that should FAIL for new mode names being incorrectly defined for renaming
with pytest.raises(ModeError):
# too many mode names
incorrect_new_mode_names = {mode: "{}-mode".format(mode) for mode in range(true_order + 1)}
tensor.set_mode_names(mode_names=incorrect_new_mode_names)
with pytest.raises(ModeError):
# incorrect type of keys (not integers)
incorrect_new_mode_names = {"{}-mode".format(mode): mode for mode in range(true_order)}
tensor.set_mode_names(mode_names=incorrect_new_mode_names)
with pytest.raises(ModeError):
# key value exceeds the order of a tensor
incorrect_new_mode_names = {mode: "{}-mode".format(mode) for mode in range(true_order - 2, true_order + 1)}
tensor.set_mode_names(mode_names=incorrect_new_mode_names)
with pytest.raises(ModeError):
# key value is set to be negative
incorrect_new_mode_names = {mode: "{}-mode".format(mode) for mode in range(-1, true_order - 1)}
tensor.set_mode_names(mode_names=incorrect_new_mode_names)
def test_reset_mode_name(self):
""" Tests for `reset_mode_name` method """
shape = (2, 2, 2)
size = reduce(lambda x, y: x * y, shape)
data = np.ones(size).reshape(shape)
init_names = ["country", "year", "month"]
mode_index = {i: ["index" for _ in range(shape[i])] for i in range(len(shape))}
tensor = Tensor(array=data, mode_names=init_names).set_mode_index(mode_index=mode_index)
tensor.reset_mode_name()
tensor_true_result = Tensor(array=data).set_mode_index(mode_index=mode_index)
assert tensor == tensor_true_result
tensor = Tensor(array=data, mode_names=init_names)
tensor.reset_mode_name(mode=0)
init_names[0] = "mode-0"
tensor_true_result = Tensor(array=data, mode_names=init_names)
assert tensor == tensor_true_result
def test_set_mode_index(self):
""" Tests for `set_mode_index` method """
shape = (2, 2, 2)
true_order = len(shape)
size = reduce(lambda x, y: x * y, shape)
data = np.ones(size).reshape(shape)
tensor = Tensor(array=data)
# ------ tests that should FAIL for new mode index being incorrectly defined for renaming
with pytest.raises(ModeError):
# too many lists of indices provided
mode_index = {i: ["index"] for i in range(len(shape)+1)}
tensor.set_mode_index(mode_index=mode_index)
with pytest.raises(ModeError):
# incorrect type of keys (not integers)
mode_index = {"index-name": mode for mode in range(true_order)}
tensor.set_mode_index(mode_index=mode_index)
with pytest.raises(ModeError):
# key value exceeds the order of a tensor
wrong_key = true_order + 1
mode_index = {wrong_key : ["idx"]}
tensor.set_mode_index(mode_index=mode_index)
with pytest.raises(ModeError):
# key value exceeds the order of a tensor
wrong_key = -1
mode_index = {wrong_key : ["idx"]}
tensor.set_mode_index(mode_index=mode_index)
with pytest.raises(ModeError):
# not enough indices for the length of the mode
mode_index = {0: ["idx"]}
tensor.set_mode_index(mode_index=mode_index)
def test_reset_mode_index(self):
""" Tests for `reset_mode_index` method """
shape = (2, 2, 2)
size = reduce(lambda x, y: x * y, shape)
data = np.ones(size).reshape(shape)
init_names = ["country", "year", "month"]
mode_index = {i: ["index" for _ in range(shape[i])] for i in range(len(shape))}
tensor = Tensor(array=data, mode_names=init_names).set_mode_index(mode_index=mode_index)
tensor.reset_mode_index()
tensor_true_result = Tensor(array=data, mode_names=init_names)
assert tensor == tensor_true_result
def test_describe(self):
""" Tests for describe function of a Tensor object """
array = np.arange(2 * 3 * 4).reshape(2, 3, 4)
tensor = Tensor(array=array)
captured_output = io.StringIO() # Create StringIO object
sys.stdout = captured_output # and redirect stdout.
tensor.describe()
assert captured_output.getvalue() != '' # to check that something was actually printed
def test_unfold_fold(self):
""" Tests for folding and unfolding of a Tensor object """
shape = (2, 3, 4)
size = reduce(lambda x, y: x * y, shape)
orig_data = np.arange(size).reshape(shape)
unfolded_data = [unfold(tensor=orig_data, mode=mode) for mode in range(len(shape))]
kolda_unfolded_data = [kolda_unfold(tensor=orig_data, mode=mode) for mode in range(len(shape))]
orig_mode_names = ['time', 'frequency', 'person']
unfolded_mode_names = [
['time', 'frequency_person'],
['frequency', 'time_person'],
['person', 'time_frequency']
]
orig_state = State(normal_shape=shape)
unfolded_state = [
State(normal_shape=shape, rtype="T", mode_order=([0], [1, 2])),
State(normal_shape=shape, rtype="T", mode_order=([1], [0, 2])),
State(normal_shape=shape, rtype="T", mode_order=([2], [0, 1])),
]
unfolded_state_kolda = [
State(normal_shape=shape, rtype="K", mode_order=([0], [1, 2])),
State(normal_shape=shape, rtype="K", mode_order=([1], [0, 2])),
State(normal_shape=shape, rtype="K", mode_order=([2], [0, 1])),
]
tensor = Tensor(array=orig_data, mode_names=orig_mode_names)
# --------- tests for unfolding and folding INPLACE=TRUE
for mode in range(len(shape)):
tensor.unfold(mode=mode, inplace=True)
assert tensor._state == unfolded_state[mode]
np.testing.assert_array_equal(tensor.data, unfolded_data[mode])
assert (tensor.mode_names == unfolded_mode_names[mode])
tensor.fold(inplace=True)
assert tensor._state == orig_state
np.testing.assert_array_equal(tensor.data, orig_data)
assert (tensor.mode_names == orig_mode_names)
# --------- tests for kolda unfolding and folding INPLACE=TRUE
for mode in range(len(shape)):
tensor.unfold(mode=mode, rtype="K", inplace=True)
assert tensor._state == unfolded_state_kolda[mode]
np.testing.assert_array_equal(tensor.data, kolda_unfolded_data[mode])
assert (tensor.mode_names == unfolded_mode_names[mode])
tensor.fold(inplace=True)
assert tensor._state == orig_state
np.testing.assert_array_equal(tensor.data, orig_data)
assert (tensor.mode_names == orig_mode_names)
# --------- tests for unfolding and folding INPLACE=FALSE
for mode in range(len(shape)):
tensor_unfolded = tensor.unfold(mode=mode, inplace=False)
tensor_folded = tensor_unfolded.fold(inplace=False)
assert tensor_unfolded is not tensor
assert tensor_folded is not tensor_unfolded
assert tensor._state == orig_state
assert (tensor.mode_names == orig_mode_names)
np.testing.assert_array_equal(tensor.data, orig_data)
assert tensor_unfolded._state == unfolded_state[mode]
assert (tensor_unfolded.mode_names == unfolded_mode_names[mode])
np.testing.assert_array_equal(tensor_unfolded.data, unfolded_data[mode])
assert tensor_folded._state == orig_state
assert (tensor_folded.mode_names == orig_mode_names)
np.testing.assert_array_equal(tensor_folded.data, orig_data)
# --------- tests that should fail
with pytest.raises(ValueError):
# Unknown convention for unfolding
Tensor(array=orig_data).unfold(mode=0, rtype="dummy", inplace=True)
# Tests for checking normal state of a tensor
with pytest.raises(TensorStateError):
# Should not unfold several times in a row
Tensor(array=orig_data).unfold(mode=0, inplace=True).unfold(mode=0, inplace=True)
with pytest.raises(TensorStateError):
# Should not fold if it wasn't unfolded before
Tensor(array=orig_data).fold(inplace=True)
def test_vectorise(self):
""" Tests for `vectorise` method """
shape = (2, 3, 4)
size = reduce(lambda x, y: x * y, shape)
orig_data = np.arange(size).reshape(shape)
orig_mode_names = ['time', 'frequency', 'person']
vectorised_mode_names = ['time_frequency_person']
orig_state = State(normal_shape=shape)
vectorised_state = State(normal_shape=shape, rtype="T", mode_order=([0, 1, 2], ))
vectorised_state_kolda = State(normal_shape=shape, rtype="K", mode_order=([0, 1, 2], ))
tensor = Tensor(array=orig_data, mode_names=orig_mode_names)
# --------- tests for vectorising and folding INPLACE=TRUE
tensor.vectorise(inplace=True)
assert tensor._state == vectorised_state
assert (tensor.mode_names == vectorised_mode_names)
tensor.fold(inplace=True)
assert tensor._state == orig_state
np.testing.assert_array_equal(tensor.data, orig_data)
assert (tensor.mode_names == orig_mode_names)
tensor.vectorise(rtype="K", inplace=True)
assert tensor._state == vectorised_state_kolda
assert (tensor.mode_names == vectorised_mode_names)
tensor.fold(inplace=True)
assert tensor._state == orig_state
np.testing.assert_array_equal(tensor.data, orig_data)
assert (tensor.mode_names == orig_mode_names)
# --------- tests for vectorising and folding INPLACE=FALSE
tensor_vectorised = tensor.vectorise(inplace=False)
tensor_folded = tensor_vectorised.fold(inplace=False)
assert tensor_vectorised is not tensor
assert tensor_folded is not tensor_vectorised
assert tensor._state == orig_state
assert (tensor.mode_names == orig_mode_names)
np.testing.assert_array_equal(tensor.data, orig_data)
assert tensor_vectorised._state == vectorised_state
assert (tensor_vectorised.mode_names == vectorised_mode_names)
assert tensor_folded._state == orig_state
assert (tensor_folded.mode_names == orig_mode_names)
np.testing.assert_array_equal(tensor_folded.data, orig_data)
# --------- tests that should fail
with pytest.raises(ValueError):
# Unknown convention for vectorisation
Tensor(array=orig_data).vectorise(rtype="dummy", inplace=True)
# Tests for checking normal state of a tensor
with pytest.raises(TensorStateError):
# Should vectorise a tensor only if it was in normal state
Tensor(array=orig_data).unfold(mode=0, inplace=True).vectorise(inplace=True)
def test_mode_n_product(self):
""" Tests for mode-n product on an object of Tensor class """
I, J, K = 5, 6, 7
I_new, J_new, K_new = 2, 3, 4
array_3d = np.arange(I * J * K).reshape((I, J, K))
A = np.arange(I_new * I).reshape(I_new, I)
B = np.arange(J_new * J).reshape(J_new, J)
C = np.arange(K_new * K).reshape(K_new, K)
res_0 = mode_n_product(tensor=array_3d, matrix=A, mode=0)
res_1 = mode_n_product(tensor=res_0, matrix=B, mode=1)
res_1 = mode_n_product(tensor=res_1, matrix=C, mode=2)
tensor = Tensor(array=array_3d)
tensor.mode_n_product(A, 0)
np.testing.assert_array_equal(tensor.data, res_0)
# ------ test for chaining methods
tensor = Tensor(array=array_3d)
tensor.mode_n_product(A, 0).mode_n_product(B, 1).mode_n_product(C, 2)
np.testing.assert_array_equal(tensor.data, res_1)
# ------ test that chaining order doesn't matter
tensor = Tensor(array=array_3d)
tensor.mode_n_product(C, 2).mode_n_product(B, 1).mode_n_product(A, 0)
np.testing.assert_array_equal(tensor.data, res_1)
# ------ test for inplace=False
orig_dim = (5, 6, 7)
new_dim = [2, 3, 4]
size = reduce(lambda x, y: x * y, orig_dim)
array_3d = np.arange(size).reshape(orig_dim)
tensor = Tensor(array_3d)
matrix_list = [np.arange(new_dim[i] * orig_dim[i]).reshape(new_dim[i], orig_dim[i]) for i in range(len(new_dim))]
for mode in range(tensor.order):
true_res = mode_n_product(tensor=array_3d, matrix=matrix_list[mode], mode=mode)
tensor_res = tensor.mode_n_product(matrix_list[mode], mode, inplace=False)
assert (tensor_res is not tensor)
assert (tensor_res.ft_shape is not tensor.ft_shape)
np.testing.assert_array_equal(tensor_res.data, true_res)
# check that the original tensor object has not been modified
np.testing.assert_array_equal(tensor.data, array_3d)
# check that mode_n_product can be performed only on a tensor in normal state
with pytest.raises(TensorStateError):
tensor = Tensor(array=array_3d).unfold(mode=0, inplace=True)
matrix = np.arange(2)
tensor.mode_n_product(matrix, mode=0)
# ------ test for changing mode_names correctly
orig_dim = (5, 6, 7)
new_dim = [2, 3, 4]
size = reduce(lambda x, y: x * y, orig_dim)
array_3d = np.arange(size).reshape(orig_dim)
orig_names = ['country', 'model', 'year']
# check that names have not been changed when multiply with numpy array
for i, mode in enumerate(new_dim):
tensor = Tensor(array=array_3d, mode_names=orig_names)
matrix = np.arange(mode * orig_dim[i]).reshape(mode, orig_dim[i])
tensor.mode_n_product(matrix, mode=i)
assert (tensor.mode_names == orig_names)
# check that names have not been changed when multiply with matrix as a Tensor object with default names
for mode in range(len(new_dim)):
tensor = Tensor(array=array_3d, mode_names=orig_names)
matrix = Tensor(np.arange(new_dim[mode] * orig_dim[mode]).reshape(new_dim[mode], orig_dim[mode]))
tensor.mode_n_product(matrix, mode=mode)
assert (tensor.mode_names == orig_names)
# check that name of the correct mode has been changed when multiplied with numpy array and specifying new_name
new_name = 'age'
for mode in range(len(new_dim)):
tensor = Tensor(array=array_3d, mode_names=orig_names)
matrix = np.arange(new_dim[mode] * orig_dim[mode]).reshape(new_dim[mode], orig_dim[mode])
tensor.mode_n_product(matrix, mode=mode, new_name=new_name)
new_true_names = orig_names.copy()
new_true_names[mode] = new_name
assert (tensor.mode_names == new_true_names)
# check that name of the correct mode has been changed when multiplied with a matrix as a Tensor object
new_matrix_name = {0: 'age'}
for mode in range(len(new_dim)):
tensor = Tensor(array=array_3d, mode_names=orig_names)
matrix = Tensor(np.arange(new_dim[mode] * orig_dim[mode]).reshape(new_dim[mode], orig_dim[mode]))
matrix.set_mode_names(mode_names=new_matrix_name)
tensor.mode_n_product(matrix, mode=mode)
new_true_names = orig_names.copy()
new_true_names[mode] = new_matrix_name[0]
assert (tensor.mode_names == new_true_names)
# check that you cannot use matrix of Tensor class and specify new name at the same time
with pytest.raises(ModeError):
mode = 1
tensor = Tensor(array=array_3d, mode_names=orig_names)
matrix = Tensor(np.arange(new_dim[mode] * orig_dim[mode]).reshape(new_dim[mode], orig_dim[mode]))
new_name = 'age'
tensor.mode_n_product(matrix, mode=mode, new_name=new_name)
# check that new_name should be of string type
with pytest.raises(ModeError):
mode = 1
tensor = Tensor(array=array_3d, mode_names=orig_names)
matrix = np.arange(new_dim[mode] * orig_dim[mode]).reshape(new_dim[mode], orig_dim[mode])
new_name = 5
tensor.mode_n_product(matrix, mode=mode, new_name=new_name)
def test_access(self):
tensor = np.random.uniform(size=(4,4,3,4))
tt = Tensor(array=tensor)
# testing single access of subtensors
assert np.array_equal(tt.access(0,0), tensor[0,:,:,:])
assert np.array_equal(tt.access(3,1), tensor[:,3,:,:])
assert np.array_equal(tt.access(1,2), tensor[:,:,1,:])
assert np.array_equal(tt.access(2,3), tensor[:,:,:,2])
# testing multiple array access
assert np.array_equal(tt.access(3, [0,1]), tensor[3,3,:,:])
assert np.array_equal(tt.access(0, [1,3]), tensor[:,0,:,0])
# multiple array access corresponding to indices
assert np.array_equal(tt.access([1,2], [0,2]), tensor[1,:,2,:])
assert np.array_equal(tt.access([2,3], [1,3]), tensor[:,2,:,3])
def test_write_subtensor(self):
tensor = np.random.uniform(size=(4,4,3,4))
tt = Tensor(array=tensor)
# testing single access of subtensors
wr = np.random.uniform(size=(tensor[0,:,:,:].shape))
tt.write_subtensor(0,0,wr)
assert np.array_equal(wr, tt.data[0,:,:,:])
# testing multiple array access
wr = np.random.uniform(size=(tensor[3,3,:,:].shape))
tt.write_subtensor(3,[0,1],wr)
assert np.array_equal(wr, tt.data[3,3,:,:])
class TestBaseTensorTD:
""" Tests for the BaseTensorTD as an interface"""
def test_init(self):
tensor_interface = BaseTensorTD()
with pytest.raises(NotImplementedError):
tensor_interface._validate_init_data()
with pytest.raises(NotImplementedError):
tensor_interface.copy()
with pytest.raises(NotImplementedError):
tensor_interface.modes
with pytest.raises(NotImplementedError):
tensor_interface.order
with pytest.raises(NotImplementedError):
tensor_interface.rank
with pytest.raises(NotImplementedError):
tensor_interface.size
with pytest.raises(NotImplementedError):
tensor_interface.frob_norm
with pytest.raises(NotImplementedError):
tensor_interface.unfold()
with pytest.raises(NotImplementedError):
tensor_interface.fold()
with pytest.raises(NotImplementedError):
tensor_interface.mode_n_product()
with pytest.raises(NotImplementedError):
tensor_interface.reconstruct()
class TestTensorCPD:
""" Tests for the TensorCPD class """
def test_init(self):
""" Tests for the TensorCPD constructor """
ft_shape = (3, 4, 5) # define shape of the tensor in full form
R = 2 # define Kryskal rank of a tensor in CP form
core_values = np.ones(R)
true_orig_fmat_list = [np.arange(orig_dim * R).reshape(orig_dim, R) for orig_dim in ft_shape]
fmat_list = [fmat.copy() for fmat in true_orig_fmat_list]
true_mode_names = ["mode-0", "mode-1", "mode-2"]
tensor_cpd = TensorCPD(fmat=fmat_list, core_values=core_values)
assert isinstance(tensor_cpd.fmat, list)
assert tensor_cpd.order == len(fmat_list)
assert isinstance(tensor_cpd.rank, tuple)
assert tensor_cpd.rank == (R,)
assert isinstance(tensor_cpd._core_values, np.ndarray)
np.testing.assert_array_equal(tensor_cpd._core_values, core_values)
assert tensor_cpd._core_values is not core_values
assert tensor_cpd.mode_names == true_mode_names
assert tensor_cpd.ft_shape == ft_shape
# ------ tests for factor matrices
for mode, fmat in enumerate(tensor_cpd.fmat):
# check that values are the same but there are not references
np.testing.assert_array_equal(fmat, fmat_list[mode])
assert fmat is not fmat_list[mode]
# check that changes to the matrices have no affect on the TensorCPD
# (double check for not being references)
fmat_list[mode] = fmat_list[mode] * 2
np.testing.assert_array_equal(fmat, true_orig_fmat_list[mode])
assert fmat is not true_orig_fmat_list[mode]
# ------ tests for core
true_core = np.array([[[1., 0.],
[0., 0.]],
[[0., 0.],
[0., 1.]]]
)
assert isinstance(tensor_cpd.core, Tensor)
np.testing.assert_array_equal(tensor_cpd.core.data, true_core)
def test_init_fail(self):
""" Tests for incorrect input data for the TensorCPD constructor """
# ------ the following tests should FAIL
ft_shape = (3, 4, 5) # define shape of the tensor in full form
R = 2 # define Kryskal rank of a tensor in CP form
correct_core_values = np.ones(R)
correct_fmat = [np.arange(orig_dim * R).reshape(orig_dim, R) for orig_dim in ft_shape]
# core_values should be in form of numpy array
with pytest.raises(TypeError):
incorrect_core_values = list(correct_core_values)
TensorCPD(fmat=correct_fmat, core_values=incorrect_core_values)
# factor matrices should be passed as a list
with pytest.raises(TypeError):
incorrect_fmat = tuple(correct_fmat)
TensorCPD(fmat=incorrect_fmat, core_values=correct_core_values)
# all factor matrices should be in form of numpy array
with pytest.raises(TypeError):
incorrect_fmat = [fmat.copy() for fmat in correct_fmat]
incorrect_fmat[0] = list(incorrect_fmat[0])
TensorCPD(fmat=incorrect_fmat, core_values=correct_core_values)
# all factor matrices should be a 2-dimensional numpy array
with pytest.raises(TensorTopologyError):
incorrect_fmat = [fmat.copy() for fmat in correct_fmat]
incorrect_fmat[0] = np.ones([2, 2, 2])
TensorCPD(fmat=incorrect_fmat, core_values=correct_core_values)
# too many (or not enough) `core_values` for `fmat`
with pytest.raises(TensorTopologyError):
incorrect_core_values = np.ones(correct_core_values.size + 1)
TensorCPD(fmat=correct_fmat, core_values=incorrect_core_values)
# dimension all factor matrices should have the same number of columns
with pytest.raises(TensorTopologyError):
incorrect_fmat = [fmat.copy() for fmat in correct_fmat]
incorrect_fmat[0] = incorrect_fmat[0].T
TensorCPD(fmat=incorrect_fmat, core_values=correct_core_values)
def test_equal(self):
""" Test for tensors in kruskal form being equal """
ft_shape_1 = (3, 4, 5)
R_1 = 2
mode_names_1 = ["frequency", "time", "channel"]
new_mode_names = {i: "{}".format(mode_names_1[i]) for i in range(len(ft_shape_1))}
new_mode_index = {i: ["index" for _ in range(ft_shape_1[i])] for i in range(len(ft_shape_1))}
ft_shape_2 = ft_shape_1
R_2 = R_1
mode_names_2 = [name for name in mode_names_1]
t_cpd_1 = TensorCPD(fmat=[np.arange(i * R_1).reshape(i, R_1) for i in ft_shape_1], core_values=np.ones(R_1))
t_cpd_2 = TensorCPD(fmat=[np.arange(i * R_2).reshape(i, R_2) for i in ft_shape_2], core_values=np.ones(R_2))
assert t_cpd_1 == t_cpd_2
t_cpd_1.set_mode_names(mode_names=new_mode_names)
t_cpd_2.set_mode_names(mode_names=new_mode_names)
assert t_cpd_1 == t_cpd_2
t_cpd_1.set_mode_index(mode_index=new_mode_index)
t_cpd_2.set_mode_index(mode_index=new_mode_index)
assert t_cpd_1 == t_cpd_2
t_cpd_1 = TensorCPD(fmat=[np.arange(i * R_1).reshape(i, R_1) for i in ft_shape_1], core_values=np.ones(R_1), mode_names=mode_names_1)
t_cpd_2 = TensorCPD(fmat=[np.arange(i * R_2).reshape(i, R_2) for i in ft_shape_2], core_values=np.ones(R_2), mode_names=mode_names_2)
assert t_cpd_1 == t_cpd_2
# --------------------- Not equal because of Kruskal Rank
ft_shape_2 = ft_shape_1
R_2 = R_1 + 1
t_cpd_1 = TensorCPD(fmat=[np.arange(i * R_1).reshape(i, R_1) for i in ft_shape_1], core_values=np.ones(R_1))
t_cpd_2 = TensorCPD(fmat=[np.arange(i * R_2).reshape(i, R_2) for i in ft_shape_2], core_values=np.ones(R_2))
assert t_cpd_1 != t_cpd_2
# --------------------- Not equal because of ft_shape
ft_shape_2 = tuple(i+1 for i in ft_shape_1)
R_2 = R_1
t_cpd_1 = TensorCPD(fmat=[np.arange(i * R_1).reshape(i, R_1) for i in ft_shape_1], core_values=np.ones(R_1))
t_cpd_2 = TensorCPD(fmat=[np.arange(i * R_2).reshape(i, R_2) for i in ft_shape_2], core_values=np.ones(R_2))
assert t_cpd_1 != t_cpd_2
# --------------------- Not equal because of core values
ft_shape_2 = ft_shape_1
R_2 = R_1
t_cpd_1 = TensorCPD(fmat=[np.arange(i * R_1).reshape(i, R_1) for i in ft_shape_1], core_values=np.ones(R_1))
t_cpd_2 = TensorCPD(fmat=[np.arange(i * R_2).reshape(i, R_2) for i in ft_shape_2], core_values=np.zeros(R_2))
assert t_cpd_1 != t_cpd_2
# --------------------- Not equal because of fmat values
ft_shape_2 = ft_shape_1
R_2 = R_1
t_cpd_1 = TensorCPD(fmat=[np.arange(i * R_1).reshape(i, R_1) for i in ft_shape_1], core_values=np.ones(R_1))
t_cpd_2 = TensorCPD(fmat=[np.ones(i * R_2).reshape(i, R_2) for i in ft_shape_2], core_values=np.ones(R_2))
assert t_cpd_1 != t_cpd_2
# --------------------- Not equal because of mode names
ft_shape_2 = ft_shape_1
R_2 = R_1
mode_names_2 = ["modified-{}".format(name) for name in mode_names_1]
t_cpd_1 = TensorCPD(fmat=[np.ones(i * R_1).reshape(i, R_1) for i in ft_shape_1], core_values=np.ones(R_1), mode_names=mode_names_1)
t_cpd_2 = TensorCPD(fmat=[np.ones(i * R_2).reshape(i, R_2) for i in ft_shape_2], core_values=np.ones(R_2), mode_names=mode_names_2)
assert t_cpd_1 != t_cpd_2
t_cpd_2.set_mode_names(mode_names=new_mode_names)
assert t_cpd_1 == t_cpd_2
# --------------------- Not equal to the because of mode index
ft_shape_2 = ft_shape_1
R_2 = R_1
t_cpd_1 = TensorCPD(fmat=[np.ones(i * R_1).reshape(i, R_1) for i in ft_shape_1], core_values=np.ones(R_1))
t_cpd_2 = TensorCPD(fmat=[np.ones(i * R_2).reshape(i, R_2) for i in ft_shape_2], core_values=np.ones(R_2))
t_cpd_1.set_mode_index(mode_index=new_mode_index)
assert t_cpd_1 != t_cpd_2
# --------------------- Not equal to the because it is an instance of another class
ft_shape_2 = ft_shape_1
R_2 = R_1
t_cpd_1 = TensorCPD(fmat=[np.ones(i * R_1).reshape(i, R_1) for i in ft_shape_1], core_values=np.ones(R_1))
t_cpd_2 = TensorCPD(fmat=[np.ones(i * R_2).reshape(i, R_2) for i in ft_shape_2], core_values=np.ones(R_2))
tensor_full = t_cpd_1.reconstruct()
assert t_cpd_1 != tensor_full
tensor_full = t_cpd_2.reconstruct()
assert t_cpd_1 != tensor_full
def test_addition(self):
""" Test for summation of tensors in kruskal form """
ft_shape = (4, 5, 6)
R_1 = 2
R_2 = 3
mode_names = ["frequency", "time", "channel"]
new_mode_index = {i: ["index" for _ in range(ft_shape[i])] for i in range(len(ft_shape))}
core_values_1 = np.ones(R_1)
core_values_2 = np.ones(R_2) * 2
core_values_res = np.concatenate((core_values_1, core_values_2))
fmat_1 = [np.arange(i * R_1).reshape(i, R_1) for i in ft_shape]
fmat_2 = [np.ones(i * R_2).reshape(i, R_2) for i in ft_shape]
fmat_res = [np.concatenate((fmat_1[i], fmat_2[i]), axis=1) for i in range(len(ft_shape))]
t_cpd_1 = TensorCPD(fmat=fmat_1, core_values=core_values_1)
t_cpd_2 = TensorCPD(fmat=fmat_2, core_values=core_values_2)
t_cpd_res = TensorCPD(fmat=fmat_res, core_values=core_values_res)
t_cpd_sum = t_cpd_1 + t_cpd_2
assert t_cpd_sum == t_cpd_res
t_cpd_1 = TensorCPD(fmat=fmat_1, core_values=core_values_1, mode_names=mode_names)
t_cpd_2 = TensorCPD(fmat=fmat_2, core_values=core_values_2)
t_cpd_res = TensorCPD(fmat=fmat_res, core_values=core_values_res)
t_cpd_sum = t_cpd_1 + t_cpd_2
assert t_cpd_sum == t_cpd_res
#---- Tests that should fail
with pytest.raises(TypeError):
# wrong data type
assert TensorCPD(fmat=fmat_1, core_values=core_values_1) + np.ones(R_2)
with pytest.raises(TensorTopologyError):
# wrong topology which is determined by the ft_shape or number of dimensions
ft_shape_new = ft_shape + (6,)
fmat_2_new = [np.ones(i * R_2).reshape(i, R_2) for i in ft_shape_new]
t_cpd_1 = TensorCPD(fmat=fmat_1, core_values=core_values_1)
t_cpd_2 = TensorCPD(fmat=fmat_2_new, core_values=core_values_2)
assert t_cpd_1 + t_cpd_2
with pytest.raises(ModeError):
# wrong mode index
t_cpd_1 = TensorCPD(fmat=fmat_1, core_values=core_values_1)
t_cpd_2 = TensorCPD(fmat=fmat_2, core_values=core_values_2).set_mode_index(mode_index=new_mode_index)
assert t_cpd_1 + t_cpd_2
def test_repr(self):
ft_shape = (3, 4, 5)
R = 2
core_values = np.ones(R)
fmat = [np.arange(orig_dim * R).reshape(orig_dim, R) for orig_dim in ft_shape]
tensor_cpd = TensorCPD(core_values=core_values, fmat=fmat)
captured_output = io.StringIO() # Create StringIO object
sys.stdout = captured_output # and redirect stdout.
print(repr(tensor_cpd))
assert captured_output.getvalue() != '' # to check that something was actually printed
def test_copy(self):
""" Tests for creation a copy of TensorCPD object """
ft_shape = (3, 4, 5) # define shape of the tensor in full form
R = 2 # define Kryskal rank of a tensor in CP form
core_values = np.ones(R)
fmat_list = [np.arange(orig_dim * R).reshape(orig_dim, R) for orig_dim in ft_shape]
tensor_cpd = TensorCPD(fmat=fmat_list, core_values=core_values)
tensor_cpd_copy = tensor_cpd.copy()
# tests that the values are the same but not a reference
assert tensor_cpd_copy is not tensor_cpd
np.testing.assert_array_equal(tensor_cpd_copy._core_values, core_values)
np.testing.assert_array_equal(tensor_cpd_copy._core_values, tensor_cpd._core_values)
assert tensor_cpd_copy._core_values is not tensor_cpd._core_values
assert tensor_cpd_copy.core is not tensor_cpd.core
assert isinstance(tensor_cpd_copy.core, Tensor)
np.testing.assert_array_equal(tensor_cpd_copy.core.data, tensor_cpd.core.data)
assert tensor_cpd_copy.core.data is not tensor_cpd.core.data
for mode in range(tensor_cpd.order):
np.testing.assert_array_equal(tensor_cpd_copy.fmat[mode], fmat_list[mode])
np.testing.assert_array_equal(tensor_cpd_copy.fmat[mode], tensor_cpd.fmat[mode])
assert tensor_cpd_copy.fmat[mode] is not tensor_cpd.fmat[mode]
def test_reconstruct(self):
""" Tests for reconstruction TensorCPD object into the full form (Tensor) """
true_default_mode_names = ['mode-0', 'mode-1', 'mode-2']
true_data = np.array([[[225., 555., 885., 1215.],
[555., 1425., 2295., 3165.],
[885., 2295., 3705., 5115.]],
[[555., 1425., 2295., 3165.],
[1425., 4131., 6837., 9543.],
[2295., 6837., 11379., 15921.]]]
)
ft_shape = true_data.shape # define shape of the tensor in full form
R = 6 # define Kryskal rank of a tensor in CP form
core_values = np.ones(R)
fmat_list = [np.arange(orig_dim * R).reshape(orig_dim, R) for orig_dim in ft_shape]
tensor_cpd = TensorCPD(fmat=fmat_list, core_values=core_values)
# ------ basic tests on getting correct results after reconstruction
tensor_rec = tensor_cpd.reconstruct()
assert isinstance(tensor_rec, Tensor)
np.testing.assert_array_equal(tensor_rec.data, true_data)
assert (tensor_rec.ft_shape == ft_shape)
assert (tensor_rec.mode_names == true_default_mode_names)
# ------ tests for consecutive reconstructions: results should be the same but different objects
tensor_rec_1 = tensor_cpd.reconstruct()
tensor_rec_2 = tensor_cpd.reconstruct()
np.testing.assert_array_equal(tensor_rec_1.data, true_data)
np.testing.assert_array_equal(tensor_rec_1.data, tensor_rec_2.data)
assert tensor_rec_1 is not tensor_rec_2
# ------ tests for chaining methods
new_mode_names = {0: 'frequency',
1: 'time',
2: 'channel'
}
mode = 0
new_dim_size = 7
matrix = np.arange(new_dim_size * ft_shape[mode]).reshape(new_dim_size, ft_shape[mode])
tensor_rec = tensor_cpd.reconstruct().set_mode_names(mode_names=new_mode_names)
for i, mode_name in enumerate(tensor_rec.mode_names):
assert (mode_name == new_mode_names[i])
new_name = 'age'
tensor_rec = tensor_cpd.reconstruct().mode_n_product(matrix, mode=mode, new_name=new_name)
new_shape = [i for i in ft_shape]
new_shape[mode] = new_dim_size
new_shape = tuple(new_shape)
new_mode_names = true_default_mode_names
new_mode_names[mode] = new_name
assert (tensor_rec.shape == new_shape)
assert (tensor_rec.mode_names == new_mode_names)
def test_reconstruct_with_meta(self):
""" Tests for keeping meta data about modes """
ft_shape = (2, 3, 4) # define shape of the tensor in full form
R = 2 # define Kryskal rank of a tensor in CP form
core_values = np.ones(R)
fmat_list = [np.arange(orig_dim * R).reshape(orig_dim, R) for orig_dim in ft_shape]
mode_names = ["country", "year", "month"]
mode_index ={0: ['UK', 'RUS'],
1: [2005, 2015, 2010],
2: ['Jan', 'Feb', 'Mar', 'Apr']}
tensor_cpd = TensorCPD(fmat=fmat_list, core_values=core_values, mode_names=mode_names)
tensor_cpd.set_mode_index(mode_index=mode_index)
tensor = tensor_cpd.reconstruct(keep_meta=2)
assert tensor.modes == tensor_cpd.modes
tensor = tensor_cpd.reconstruct(keep_meta=1)
assert all([tensor.modes[i].name == tensor_cpd.modes[i].name for i in range(tensor.order)])
assert all([tensor.modes[i].index is None for i in range(tensor.order)])
tensor = tensor_cpd.reconstruct(keep_meta=0)
tensor_cpd.reset_mode_name()
tensor_cpd.reset_mode_index()
assert tensor.modes == tensor_cpd.modes
def test_set_mode_names(self):
""" Tests for `set_mode_names` method """
ft_shape = (3, 4, 5) # define shape of the tensor in full form
true_order = len(ft_shape)
R = 2 # define Kryskal rank of a tensor in CP form
core_values = np.ones(R)
fmat_list = [np.arange(orig_dim * R).reshape(orig_dim, R) for orig_dim in ft_shape]
init_names = ["country", "year", "month"]
mode_names = {i: name for i, name in enumerate(init_names)}
tensor_cpd = TensorCPD(fmat=fmat_list, core_values=core_values)
tensor_cpd.set_mode_names(mode_names)
tensor_cpd_true = TensorCPD(fmat=fmat_list, core_values=core_values, mode_names=init_names)
assert all([tensor_cpd.modes[i].name == tensor_cpd_true.modes[i].name for i in range(tensor_cpd.order)])
# ------ tests that should FAIL for new mode names being incorrectly defined for renaming
with pytest.raises(ModeError):
# too many mode names
incorrect_new_mode_names = {mode: "{}-mode".format(mode) for mode in range(true_order + 1)}
tensor_cpd.set_mode_names(mode_names=incorrect_new_mode_names)
with pytest.raises(ModeError):
# incorrect type of keys (not integers)
incorrect_new_mode_names = {"{}-mode".format(mode): mode for mode in range(true_order)}
tensor_cpd.set_mode_names(mode_names=incorrect_new_mode_names)
with pytest.raises(ModeError):
# key value exceeds the order of a tensor
incorrect_new_mode_names = {mode: "{}-mode".format(mode) for mode in range(true_order - 2, true_order + 1)}
tensor_cpd.set_mode_names(mode_names=incorrect_new_mode_names)
with pytest.raises(ModeError):
# key value is set to be negative
incorrect_new_mode_names = {mode: "{}-mode".format(mode) for mode in range(-1, true_order - 1)}
tensor_cpd.set_mode_names(mode_names=incorrect_new_mode_names)
def test_reset_mode_name(self):
""" Tests for `reset_mode_name` method """
ft_shape = (3, 4, 5) # define shape of the tensor in full form
R = 2 # define Kryskal rank of a tensor in CP form
core_values = np.ones(R)
fmat_list = [np.arange(orig_dim * R).reshape(orig_dim, R) for orig_dim in ft_shape]
init_names = ["country", "year", "month"]
tensor_cpd = TensorCPD(fmat=fmat_list, core_values=core_values, mode_names=init_names)
tensor_cpd.reset_mode_name()
tensor_cpd_true = TensorCPD(fmat=fmat_list, core_values=core_values)
assert all([tensor_cpd.modes[i].name == tensor_cpd_true.modes[i].name for i in range(tensor_cpd.order)])
tensor_cpd = TensorCPD(fmat=fmat_list, core_values=core_values, mode_names=init_names)
tensor_cpd.reset_mode_name(mode=0)
init_names = ["mode-0", "year", "month"]
tensor_cpd_true = TensorCPD(fmat=fmat_list, core_values=core_values, mode_names=init_names)
assert all([tensor_cpd.modes[i].name == tensor_cpd_true.modes[i].name for i in range(tensor_cpd.order)])
def test_set_mode_index(self):
""" Tests for `set_mode_index` method """
ft_shape = (2, 3, 4) # define shape of the tensor in full form
true_order = len(ft_shape)
R = 2 # define Kryskal rank of a tensor in CP form
core_values = np.ones(R)
fmat_list = [np.arange(orig_dim * R).reshape(orig_dim, R) for orig_dim in ft_shape]
tensor_cpd = TensorCPD(fmat=fmat_list, core_values=core_values)
mode_index = {0: ["idx1", "idx2"],
1: ["idx1", "idx2", "idx3"],
2: ["idx1", "idx2", "idx3", "idx4"]}
tensor_cpd.set_mode_index(mode_index=mode_index)
assert all([tensor_cpd.modes[i].index == mode_index[i] for i in range(tensor_cpd.order)])
# ------ tests that should FAIL for new mode index being incorrectly defined for renaming
with pytest.raises(ModeError):
# too many lists of indices provided
mode_index = {i: ["index"] for i in range(len(ft_shape) + 1)}
tensor_cpd.set_mode_index(mode_index=mode_index)
with pytest.raises(ModeError):
# incorrect type of keys (not integers)
mode_index = {"index".format(mode): mode for mode in range(true_order)}
tensor_cpd.set_mode_index(mode_index=mode_index)
with pytest.raises(ModeError):
# key value exceeds the order of a tensor
wrong_key = true_order + 1
mode_index = {wrong_key: ["idx"]}
tensor_cpd.set_mode_index(mode_index=mode_index)
with pytest.raises(ModeError):
# key value exceeds the order of a tensor
wrong_key = -1
mode_index = {wrong_key: ["idx"]}
tensor_cpd.set_mode_index(mode_index=mode_index)
with pytest.raises(ModeError):
# not enough indices for the length of the mode
mode_index = {0: ["idx"]}
tensor_cpd.set_mode_index(mode_index=mode_index)
def test_reset_mode_index(self):
""" Tests for `reset_mode_index` method """
ft_shape = (2, 3, 4) # define shape of the tensor in full form
R = 2 # define Kryskal rank of a tensor in CP form
core_values = np.ones(R)
fmat_list = [np.arange(orig_dim * R).reshape(orig_dim, R) for orig_dim in ft_shape]
tensor_cpd = TensorCPD(fmat=fmat_list, core_values=core_values)
mode_index = {0: ["idx1", "idx2"],
1: ["idx1", "idx2", "idx3"],
2: ["idx1", "idx2", "idx3", "idx4"]}
tensor_cpd.set_mode_index(mode_index=mode_index)
tensor_cpd.reset_mode_index()
tensor_cpd_2 = TensorCPD(fmat=fmat_list, core_values=core_values)
assert all([tensor_cpd.modes[i].index == tensor_cpd_2.modes[i].index for i in range(tensor_cpd.order)])
tensor_cpd = TensorCPD(fmat=fmat_list, core_values=core_values)
mode_index = {0: ["idx1", "idx2"]}
tensor_cpd.set_mode_index(mode_index=mode_index)
tensor_cpd.reset_mode_index(mode=0)
tensor_cpd_2 = TensorCPD(fmat=fmat_list, core_values=core_values)
assert all([tensor_cpd.modes[i].index == tensor_cpd_2.modes[i].index for i in range(tensor_cpd.order)])
class TestTensorTKD:
""" Tests for the TensorTKD class """
def test_init(self):
""" Tests for the TensorTKD constructor """
ft_shape = (5, 6, 7) # define shape of the tensor in full form
ml_rank = (2, 3, 4) # define multi-linear rank of a tensor in Tucker form
core_size = reduce(lambda x, y: x * y, ml_rank)
core_values = np.arange(core_size).reshape(ml_rank)
true_orig_fmat_list = [np.arange(ft_shape[mode] * ml_rank[mode]).reshape(ft_shape[mode], ml_rank[mode]) for mode in range(len(ft_shape))]
fmat_list = [fmat.copy() for fmat in true_orig_fmat_list]
tensor_tkd = TensorTKD(fmat=fmat_list, core_values=core_values)
assert isinstance(tensor_tkd.fmat, list)
assert tensor_tkd.order == len(fmat_list)
assert isinstance(tensor_tkd.rank, tuple)
assert (tensor_tkd.rank == ml_rank)
assert isinstance(tensor_tkd._core_values, np.ndarray)
np.testing.assert_array_equal(tensor_tkd._core_values, core_values)
assert tensor_tkd._core_values is not core_values
# ------ tests for factor matrices
for mode, fmat in enumerate(tensor_tkd.fmat):
# check that values are the same but there are not references
np.testing.assert_array_equal(fmat, fmat_list[mode])
assert fmat is not fmat_list[mode]
# check that changes to the matrices have no affect on the TensorCPD
# (double check for not being references)
fmat_list[mode] = fmat_list[mode] * 2
np.testing.assert_array_equal(fmat, true_orig_fmat_list[mode])
assert fmat is not true_orig_fmat_list[mode]
# ------ tests for core
assert isinstance(tensor_tkd.core, Tensor)
np.testing.assert_array_equal(tensor_tkd.core.data, core_values)
def test_init_fail(self):
""" Tests for incorrect input data for the TensorTKD constructor """
# ------ the following tests should FAIL
ft_shape = (5, 6, 7) # define shape of the tensor in full form
ml_rank = (2, 3, 4) # define multi-linear rank of a tensor in Tucker form
correct_core_values = np.ones(ml_rank)
correct_fmat = [np.ones([ft_shape[mode], ml_rank[mode]]) for mode in range(len(ft_shape))]
# core_values should be in form of numpy array
with pytest.raises(TypeError):
incorrect_core_values = list(correct_core_values)
TensorTKD(fmat=correct_fmat, core_values=incorrect_core_values)
# factor matrices should be passed as a list
with pytest.raises(TypeError):
incorrect_fmat = tuple(correct_fmat)
TensorTKD(fmat=incorrect_fmat, core_values=correct_core_values)
# all factor matrices should be in form of numpy array
with pytest.raises(TypeError):
incorrect_fmat = [fmat.copy() for fmat in correct_fmat]
mode = 0
incorrect_fmat[mode] = list(incorrect_fmat[mode])
TensorTKD(fmat=incorrect_fmat, core_values=correct_core_values)
# all factor matrices should be a 2-dimensional numpy array
with pytest.raises(TensorTopologyError):
incorrect_fmat = [fmat.copy() for fmat in correct_fmat]
mode = 0
incorrect_fmat[mode] = np.ones([ft_shape[mode], ml_rank[mode], 2])
TensorTKD(fmat=incorrect_fmat, core_values=correct_core_values)
# Not enough factor matrices for the specified core tensor
with pytest.raises(TensorTopologyError):
incorrect_core_values = np.ones(correct_core_values.shape + (2,))
TensorTKD(fmat=correct_fmat, core_values=incorrect_core_values)
# number of columns of some factor matrices does not match the size of the corresponding mode of the core
with pytest.raises(TensorTopologyError):
incorrect_fmat = [fmat.copy() for fmat in correct_fmat]
incorrect_fmat[0] = incorrect_fmat[0].T
TensorTKD(fmat=incorrect_fmat, core_values=correct_core_values)
def test_equal(self):
""" Test for tensors in tucker form being equal """
create_fmat = lambda func, shape, R: [func(shape[i] * R[i]).reshape(shape[i], R[i]) for i in range(len(shape))]
ft_shape = (5, 6, 7)
ft_shape_new = tuple(i + 1 for i in ft_shape)
ml_rank = (2, 3, 4)
ml_rank_new = tuple(i + 1 for i in ml_rank)
core_size = reduce(lambda x, y: x * y, ml_rank)
core_size_new = reduce(lambda x, y: x * y, ml_rank_new)
mode_names_1 = ["frequency", "time", "channel"]
mode_names_2 = [name for name in mode_names_1]
new_mode_names = {i: "{}".format(mode_names_1[i]) for i in range(len(ft_shape))}
new_mode_index = {i: ["index" for _ in range(ft_shape[i])] for i in range(len(ft_shape))}
core_values_1 = np.arange(core_size).reshape(ml_rank)
fmat_1 = create_fmat(np.arange, ft_shape, ml_rank)
core_values_2 = core_values_1.copy()
fmat_2 = [fmat.copy() for fmat in fmat_1]
tensor_tkd_1 = TensorTKD(fmat=fmat_1, core_values=core_values_1)
tensor_tkd_2 = TensorTKD(fmat=fmat_2, core_values=core_values_2)
assert tensor_tkd_1 == tensor_tkd_2
tensor_tkd_1.set_mode_names(mode_names=new_mode_names)
tensor_tkd_2.set_mode_names(mode_names=new_mode_names)
assert tensor_tkd_1 == tensor_tkd_2
tensor_tkd_1.set_mode_index(mode_index=new_mode_index)
tensor_tkd_2.set_mode_index(mode_index=new_mode_index)
assert tensor_tkd_1 == tensor_tkd_2
tensor_tkd_1 = TensorTKD(fmat=fmat_1, core_values=core_values_1, mode_names=mode_names_1)
tensor_tkd_2 = TensorTKD(fmat=fmat_2, core_values=core_values_2, mode_names=mode_names_2)
assert tensor_tkd_1 == tensor_tkd_2
# --------------------- Not equal because of multi-linear Rank
core_values_2 = np.arange(core_size_new).reshape(ml_rank_new)
fmat_2 = create_fmat(np.arange, ft_shape, ml_rank_new)
tensor_tkd_1 = TensorTKD(fmat=fmat_1, core_values=core_values_1)
tensor_tkd_2 = TensorTKD(fmat=fmat_2, core_values=core_values_2)
assert tensor_tkd_1 != tensor_tkd_2
# --------------------- Not equal because of ft_shape
core_values_2 = core_values_1.copy()
fmat_2 = create_fmat(np.arange, ft_shape_new, ml_rank)
tensor_tkd_1 = TensorTKD(fmat=fmat_1, core_values=core_values_1)
tensor_tkd_2 = TensorTKD(fmat=fmat_2, core_values=core_values_2)
assert tensor_tkd_1 != tensor_tkd_2
# --------------------- Not equal because of core values
core_values_2 = core_values_1.copy() * 2
fmat_2 = [fmat.copy() for fmat in fmat_1]
tensor_tkd_1 = TensorTKD(fmat=fmat_1, core_values=core_values_1)
tensor_tkd_2 = TensorTKD(fmat=fmat_2, core_values=core_values_2)
assert tensor_tkd_1 != tensor_tkd_2
# --------------------- Not equal because of fmat values
core_values_2 = core_values_1.copy()
fmat_2 = [fmat.copy() * 2 for fmat in fmat_1]
tensor_tkd_1 = TensorTKD(fmat=fmat_1, core_values=core_values_1)
tensor_tkd_2 = TensorTKD(fmat=fmat_2, core_values=core_values_2)
assert tensor_tkd_1 != tensor_tkd_2
# --------------------- Not equal because of mode names
mode_names_2 = ["modified-{}".format(name) for name in mode_names_1]
core_values_2 = core_values_1.copy()
fmat_2 = [fmat.copy() for fmat in fmat_1]
tensor_tkd_1 = TensorTKD(fmat=fmat_1, core_values=core_values_1, mode_names=mode_names_1)
tensor_tkd_2 = TensorTKD(fmat=fmat_2, core_values=core_values_2, mode_names=mode_names_2)
assert tensor_tkd_1 != tensor_tkd_2
tensor_tkd_2.set_mode_names(mode_names=new_mode_names)
assert tensor_tkd_1 == tensor_tkd_2
# --------------------- Not equal to the because of mode index
core_values_2 = core_values_1.copy()
fmat_2 = [fmat.copy() for fmat in fmat_1]
tensor_tkd_1 = TensorTKD(fmat=fmat_1, core_values=core_values_1)
tensor_tkd_2 = TensorTKD(fmat=fmat_2, core_values=core_values_2)
tensor_tkd_1.set_mode_index(mode_index=new_mode_index)
assert tensor_tkd_1 != tensor_tkd_2
# --------------------- Not equal to the because it is an instance of another class
core_values_2 = core_values_1.copy()
fmat_2 = [fmat.copy() for fmat in fmat_1]
tensor_tkd_1 = TensorTKD(fmat=fmat_1, core_values=core_values_1)
tensor_tkd_2 = TensorTKD(fmat=fmat_2, core_values=core_values_2)
tensor_full = tensor_tkd_2.reconstruct()
assert tensor_tkd_1 != tensor_full
def test_addition(self):
""" Test for summation of tensors in tucker form """
create_fmat = lambda func, shape, R: [func(shape[i] * R[i]).reshape(shape[i], R[i]) for i in range(len(shape))]
ft_shape = (4, 5, 6)
ml_rank_1 = (2, 2, 2)
ml_rank_2 = (3, 3, 3)
core_size_1 = reduce(lambda x, y: x * y, ml_rank_1)
mode_names = ["frequency", "time", "channel"]
new_mode_index = {i: ["index" for _ in range(ft_shape[i])] for i in range(len(ft_shape))}
core_values_1 = np.arange(core_size_1).reshape(ml_rank_1)
core_values_2 = np.ones(ml_rank_2) * 2
core_values_res = np.array([[[0., 1., 0., 0., 0.],
[2., 3., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]],
[[4., 5., 0., 0., 0.],
[6., 7., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]],
[[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 2., 2., 2.],
[0., 0., 2., 2., 2.],
[0., 0., 2., 2., 2.]],
[[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 2., 2., 2.],
[0., 0., 2., 2., 2.],
[0., 0., 2., 2., 2.]],
[[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 2., 2., 2.],
[0., 0., 2., 2., 2.],
[0., 0., 2., 2., 2.]]])
fmat_1 = create_fmat(np.arange, ft_shape, ml_rank_1)
fmat_2 = create_fmat(np.ones, ft_shape, ml_rank_2)
fmat_res = [np.concatenate((fmat_1[i], fmat_2[i]), axis=1) for i in range(len(ft_shape))]
tensor_tkd_1 = TensorTKD(fmat=fmat_1, core_values=core_values_1)
tensor_tkd_2 = TensorTKD(fmat=fmat_2, core_values=core_values_2)
tensor_tkd_res = TensorTKD(fmat=fmat_res, core_values=core_values_res)
tensor_tkd_sum = tensor_tkd_1 + tensor_tkd_2
assert tensor_tkd_sum == tensor_tkd_res
tensor_tkd_1 = TensorTKD(fmat=fmat_1, core_values=core_values_1, mode_names=mode_names)
tensor_tkd_2 = TensorTKD(fmat=fmat_2, core_values=core_values_2)
tensor_tkd_res = TensorTKD(fmat=fmat_res, core_values=core_values_res)
tensor_tkd_sum = tensor_tkd_1 + tensor_tkd_2
assert tensor_tkd_sum == tensor_tkd_res
# ---- Tests that should fail
with pytest.raises(TypeError):
# wrong data type
assert TensorTKD(fmat=fmat_1, core_values=core_values_1) + np.ones(ml_rank_1)
with pytest.raises(TensorTopologyError):
# wrong topology which is determined by the ft_shape or number of dimensions
ft_shape_new = tuple(i + 1 for i in ft_shape)
fmat_2_new = create_fmat(np.ones, ft_shape_new, ml_rank_2)
tensor_tkd_1 = TensorTKD(fmat=fmat_1, core_values=core_values_1)
tensor_tkd_2 = TensorTKD(fmat=fmat_2_new, core_values=core_values_2)
assert tensor_tkd_1 + tensor_tkd_2
with pytest.raises(ModeError):
# wrong mode index
tensor_tkd_1 = TensorTKD(fmat=fmat_1, core_values=core_values_1)
tensor_tkd_2 = TensorTKD(fmat=fmat_2, core_values=core_values_2).set_mode_index(mode_index=new_mode_index)
assert tensor_tkd_1 + tensor_tkd_2
def test_repr(self):
shape = (5, 6, 7)
rank = (2, 3, 4)
core_size = reduce(lambda x, y: x * y, rank)
core_values = np.arange(core_size).reshape(rank)
fmat = [np.arange(shape[mode] * rank[mode]).reshape(shape[mode], rank[mode]) for mode in range(len(shape))]
tensor_tkd = TensorTKD(fmat=fmat, core_values=core_values)
captured_output = io.StringIO() # Create StringIO object
sys.stdout = captured_output # and redirect stdout.
print(repr(tensor_tkd))
assert captured_output.getvalue() != '' # to check that something was actually printed
def test_copy(self):
""" Tests for creation a copy of TensorTKD object """
ft_shape = (2, 3, 4) # define shape of the tensor in full form
ml_rank = (5, 6, 7) # define multi-linear rank of a tensor in Tucker form
core_values = np.ones(ml_rank)
fmat = [np.arange(ft_shape[mode] * ml_rank[mode]).reshape(ft_shape[mode], ml_rank[mode]) for mode in range(len(ft_shape))]
tensor_tkd = TensorTKD(fmat=fmat, core_values=core_values)
tensor_tkd_copy = tensor_tkd.copy()
# tests that the values are the same but not a reference
assert tensor_tkd_copy is not tensor_tkd
np.testing.assert_array_equal(tensor_tkd_copy._core_values, core_values)
np.testing.assert_array_equal(tensor_tkd_copy._core_values, tensor_tkd._core_values)
assert tensor_tkd_copy._core_values is not tensor_tkd._core_values
assert tensor_tkd_copy.core is not tensor_tkd.core
assert isinstance(tensor_tkd_copy.core, Tensor)
np.testing.assert_array_equal(tensor_tkd_copy.core.data, tensor_tkd.core.data)
assert tensor_tkd_copy.core.data is not tensor_tkd.core.data
for mode in range(tensor_tkd.order):
np.testing.assert_array_equal(tensor_tkd_copy.fmat[mode], fmat[mode])
np.testing.assert_array_equal(tensor_tkd_copy.fmat[mode], tensor_tkd.fmat[mode])
assert tensor_tkd_copy.fmat[mode] is not tensor_tkd.fmat[mode]
def test_reconstruct(self):
""" Tests for reconstruction TensorTKD object into the full form (Tensor) """
ft_shape = (2, 3, 4) # define shape of the tensor in full form
ml_rank = (5, 6, 7) # define multi-linear rank of a tensor in Tucker form
core_size = reduce(lambda x, y: x * y, ml_rank)
core_values = np.arange(core_size).reshape(ml_rank)
fmat = [np.arange(ft_shape[mode] * ml_rank[mode]).reshape(ft_shape[mode], ml_rank[mode]) for mode
in range(len(ft_shape))]
true_default_mode_names = ['mode-0', 'mode-1', 'mode-2']
true_data = np.array([[[491400, 1628200, 2765000, 3901800],
[1609020, 5330080, 9051140, 12772200],
[2726640, 9031960, 15337280, 21642600]],
[[1389150, 4596200, 7803250, 11010300],
[4507020, 14906780, 25306540, 35706300],
[7624890, 25217360, 42809830, 60402300]]]
)
tensor_tkd = TensorTKD(fmat=fmat, core_values=core_values)
# ------ basic tests on getting correct results after reconstruction
tensor_rec = tensor_tkd.reconstruct()
assert isinstance(tensor_rec, Tensor)
np.testing.assert_array_equal(tensor_rec.data, true_data)
assert (tensor_rec.ft_shape == ft_shape)
assert (tensor_rec.mode_names == true_default_mode_names)
# ------ tests for consecutive reconstructions: results should be the same but different objects
tensor_rec_1 = tensor_tkd.reconstruct()
tensor_rec_2 = tensor_tkd.reconstruct()
np.testing.assert_array_equal(tensor_rec_1.data, true_data)
np.testing.assert_array_equal(tensor_rec_1.data, tensor_rec_2.data)
assert tensor_rec_1 is not tensor_rec_2
# ------ tests for chaining methods
new_mode_names = {0: 'frequency',
1: 'time',
2: 'channel'
}
mode = 0
new_dim_size = 7
matrix = np.arange(new_dim_size * ft_shape[mode]).reshape(new_dim_size, ft_shape[mode])
tensor_rec = tensor_tkd.reconstruct().set_mode_names(mode_names=new_mode_names)
for i, mode_name in enumerate(tensor_rec.mode_names):
assert (mode_name == new_mode_names[i])
new_name = 'age'
tensor_rec = tensor_tkd.reconstruct().mode_n_product(matrix, mode=mode, new_name=new_name)
new_shape = [i for i in ft_shape]
new_shape[mode] = new_dim_size
new_shape = tuple(new_shape)
new_mode_names = true_default_mode_names
new_mode_names[mode] = new_name
assert (tensor_rec.shape == new_shape)
assert (tensor_rec.mode_names == new_mode_names)
def test_reconstruct_with_meta(self):
""" Tests for keeping meta data about modes """
ft_shape = (2, 3, 4) # define shape of the tensor in full form
ml_rank = (5, 6, 7) # define multi-linear rank of a tensor in Tucker form
core_size = reduce(lambda x, y: x * y, ml_rank)
core_values = np.arange(core_size).reshape(ml_rank)
fmat_list = [np.arange(ft_shape[mode] * ml_rank[mode]).reshape(ft_shape[mode], ml_rank[mode]) for mode
in range(len(ft_shape))]
mode_names = ["country", "year", "month"]
mode_index ={0: ['UK', 'RUS'],
1: [2005, 2015, 2010],
2: ['Jan', 'Feb', 'Mar', 'Apr']}
tensor_tkd = TensorTKD(fmat=fmat_list, core_values=core_values, mode_names=mode_names)
tensor_tkd.set_mode_index(mode_index=mode_index)
tensor = tensor_tkd.reconstruct(keep_meta=2)
assert tensor.modes == tensor_tkd.modes
tensor = tensor_tkd.reconstruct(keep_meta=1)
assert all([tensor.modes[i].name == tensor_tkd.modes[i].name for i in range(tensor.order)])
assert all([tensor.modes[i].index is None for i in range(tensor.order)])
tensor = tensor_tkd.reconstruct(keep_meta=0)
tensor_tkd.reset_mode_name()
tensor_tkd.reset_mode_index()
assert tensor.modes == tensor_tkd.modes
def test_set_mode_names(self):
""" Tests for `set_mode_names` method """
ft_shape = (5, 6, 7) # define shape of the tensor in full form
ml_rank = (2, 3, 4) # define multi-linear rank of a tensor in Tucker form
core_size = reduce(lambda x, y: x * y, ml_rank)
core_values = np.arange(core_size).reshape(ml_rank)
true_orig_fmat_list = [np.arange(ft_shape[mode] * ml_rank[mode]).reshape(ft_shape[mode], ml_rank[mode]) for mode
in range(len(ft_shape))]
fmat_list = [fmat.copy() for fmat in true_orig_fmat_list]
init_names = ["country", "year", "month"]
mode_names = {i: name for i, name in enumerate(init_names)}
tensor_tkd = TensorTKD(fmat=fmat_list, core_values=core_values)
tensor_tkd.set_mode_names(mode_names)
tensor_tkd_true = TensorTKD(fmat=fmat_list, core_values=core_values, mode_names=init_names)
assert all([tensor_tkd.modes[i].name == tensor_tkd_true.modes[i].name for i in range(tensor_tkd.order)])
def test_reset_mode_name(self):
""" Tests for `reset_mode_name` method """
ft_shape = (5, 6, 7) # define shape of the tensor in full form
ml_rank = (2, 3, 4) # define multi-linear rank of a tensor in Tucker form
core_size = reduce(lambda x, y: x * y, ml_rank)
core_values = np.arange(core_size).reshape(ml_rank)
true_orig_fmat_list = [np.arange(ft_shape[mode] * ml_rank[mode]).reshape(ft_shape[mode], ml_rank[mode]) for mode
in range(len(ft_shape))]
fmat_list = [fmat.copy() for fmat in true_orig_fmat_list]
init_names = ["country", "year", "month"]
tensor_tkd = TensorTKD(fmat=fmat_list, core_values=core_values, mode_names=init_names)
tensor_tkd.reset_mode_name()
tensor_tkd_true = TensorTKD(fmat=fmat_list, core_values=core_values)
assert all([tensor_tkd.modes[i].name == tensor_tkd_true.modes[i].name for i in range(tensor_tkd.order)])
tensor_tkd = TensorTKD(fmat=fmat_list, core_values=core_values, mode_names=init_names)
tensor_tkd.reset_mode_name(mode=0)
init_names = ["mode-0", "year", "month"]
tensor_tkd_true = TensorTKD(fmat=fmat_list, core_values=core_values, mode_names=init_names)
assert all([tensor_tkd.modes[i].name == tensor_tkd_true.modes[i].name for i in range(tensor_tkd.order)])
def test_set_mode_index(self):
""" Tests for `set_mode_index` method """
ft_shape = (2, 3, 4) # define shape of the tensor in full form
ml_rank = (2, 3, 4) # define multi-linear rank of a tensor in Tucker form
core_size = reduce(lambda x, y: x * y, ml_rank)
core_values = np.arange(core_size).reshape(ml_rank)
true_orig_fmat_list = [np.arange(ft_shape[mode] * ml_rank[mode]).reshape(ft_shape[mode], ml_rank[mode]) for mode
in range(len(ft_shape))]
fmat_list = [fmat.copy() for fmat in true_orig_fmat_list]
tensor_tkd = TensorTKD(fmat=fmat_list, core_values=core_values)
mode_index = {0: ["idx1", "idx2"],
1: ["idx1", "idx2", "idx3"],
2: ["idx1", "idx2", "idx3", "idx4"]}
tensor_tkd.set_mode_index(mode_index=mode_index)
assert all([tensor_tkd.modes[i].index == mode_index[i] for i in range(tensor_tkd.order)])
def test_reset_mode_index(self):
""" Tests for `reset_mode_index` method """
ft_shape = (2, 3, 4) # define shape of the tensor in full form
ml_rank = (2, 3, 4) # define multi-linear rank of a tensor in Tucker form
core_size = reduce(lambda x, y: x * y, ml_rank)
core_values = np.arange(core_size).reshape(ml_rank)
true_orig_fmat_list = [np.arange(ft_shape[mode] * ml_rank[mode]).reshape(ft_shape[mode], ml_rank[mode]) for mode
in range(len(ft_shape))]
fmat_list = [fmat.copy() for fmat in true_orig_fmat_list]
tensor_tkd = TensorTKD(fmat=fmat_list, core_values=core_values)
mode_index = {0: ["idx1", "idx2"],
1: ["idx1", "idx2", "idx3"],
2: ["idx1", "idx2", "idx3", "idx4"]}
tensor_tkd.set_mode_index(mode_index=mode_index)
tensor_tkd.reset_mode_index()
tensor_tkd_2 = TensorTKD(fmat=fmat_list, core_values=core_values)
assert all([tensor_tkd.modes[i].index == tensor_tkd_2.modes[i].index for i in range(tensor_tkd.order)])
tensor_tkd = TensorTKD(fmat=fmat_list, core_values=core_values)
mode_index = {0: ["idx1", "idx2"]}
tensor_tkd.set_mode_index(mode_index=mode_index)
tensor_tkd.reset_mode_index(mode=0)
tensor_tkd_2 = TensorTKD(fmat=fmat_list, core_values=core_values)
assert all([tensor_tkd.modes[i].index == tensor_tkd_2.modes[i].index for i in range(tensor_tkd.order)])
class TestTensorTT:
""" Tests for the TensorTT class """
def test_init(self):
""" Tests for the TensorTT constructor """
r1, r2 = 2, 3
I, J, K = 4, 5, 6
core_1 = np.arange(I * r1).reshape(I, r1)
core_2 = np.arange(r1 * J * r2).reshape(r1, J, r2)
core_3 = np.arange(r2 * K).reshape(r2, K)
core_values = [core_1, core_2, core_3]
true_orig_core_values = [core.copy() for core in core_values]
true_tt_rank = (r1, r2)
true_ft_shape = (I, J, K)
true_order = len(true_ft_shape)
true_default_mode_names_2d = ['mode-0', 'mode-1']
true_default_mode_names_3d = ['mode-0', 'mode-1', 'mode-2']
tensor_tt = TensorTT(core_values=core_values)
# ------ tests for types of data being correct
assert isinstance(tensor_tt._core_values, list)
assert isinstance(tensor_tt.ft_shape, tuple)
assert isinstance(tensor_tt.cores, list)
assert isinstance(tensor_tt.rank, tuple)
for i, core in enumerate(tensor_tt.cores):
assert isinstance(core, Tensor)
assert isinstance(tensor_tt.core(i), Tensor)
assert isinstance(tensor_tt._core_values[i], np.ndarray)
# ------ tests for data being correct
assert (tensor_tt.rank == true_tt_rank)
assert (tensor_tt.order == true_order)
# check that values are the same but they are not a references
assert (tensor_tt.ft_shape == true_ft_shape)
assert tensor_tt.ft_shape is not true_ft_shape
for i, core in enumerate(tensor_tt.cores):
np.testing.assert_array_equal(core.data, core_values[i])
np.testing.assert_array_equal(tensor_tt._core_values[i], core_values[i])
assert core.data is not core_values[i]
assert tensor_tt._core_values[i] is not core_values[i]
assert (core.order == 2) or (core.order == 3) # cores should be either matrices or 3d arrays
if core.order == 2:
assert core.mode_names == true_default_mode_names_2d
if core.order == 3:
assert core.mode_names == true_default_mode_names_3d
# double check for not being references
for i, core in enumerate(tensor_tt.cores):
core_values[i] = core_values[i] * 2
np.testing.assert_array_equal(core.data, true_orig_core_values[i])
np.testing.assert_array_equal(tensor_tt._core_values[i], true_orig_core_values[i])
with pytest.raises(IndexError):
order = tensor_tt.order
tensor_tt.core(i=order)
with pytest.raises(IndexError):
order = tensor_tt.order
tensor_tt.core(i=(-order))
def test_init_fail(self):
""" Tests for incorrect input data for the TensorTT constructor """
# ------ the following tests should FAIL
r1, r2 = 2, 3
I, J, K = 4, 5, 6
correct_core_1 = np.arange(I * r1).reshape(I, r1)
correct_core_2 = np.arange(r1 * J * r2).reshape(r1, J, r2)
correct_core_3 = np.arange(r2 * K).reshape(r2, K)
correct_core_values = [correct_core_1, correct_core_2, correct_core_3]
correct_ft_shape = (I, J, K)
# core_values should be a list of numpy arrays
with pytest.raises(TypeError):
incorrect_core_values = np.arange(5)
TensorTT(core_values=incorrect_core_values)
# all elements in core_values should be numpy arrays
with pytest.raises(TypeError):
incorrect_core_values = [[1], [2], [3]]
TensorTT(core_values=incorrect_core_values)
# not enough elements in core_values for the specified ft_shape
with pytest.raises(TensorTopologyError):
incorrect_core_values = [correct_core_1, correct_core_2]
TensorTT(core_values=incorrect_core_values)
# first and last element of core_values should be 2-dimensional arrays
with pytest.raises(TensorTopologyError):
shape = (2, 2, 2)
incorrect_core_values = [np.ones(shape) for _ in range(len(correct_ft_shape))]
TensorTT(core_values=incorrect_core_values)
# All but first and last element of core_values should be 3-dimensional arrays
with pytest.raises(TensorTopologyError):
shape = (2, 2)
incorrect_core_values = [np.ones(shape) for _ in range(len(correct_ft_shape))]
TensorTT(core_values=incorrect_core_values)
# Last dimension of core_values[i] should be the same as the first dimension of core_values[i+1]
with pytest.raises(TensorTopologyError):
incorrect_core_values = [np.ones((2, 3)), np.ones((3, 4, 5)), np.ones((6, 8))]
TensorTT(core_values=incorrect_core_values)
def test_equal(self):
""" Test for tensors in tensor train form being equal """
r1, r2 = 2, 3
I, J, K = 4, 5, 6
ft_shape = (I, J, K)
core_1 = np.arange(I * r1).reshape(I, r1)
core_2 = np.arange(r1 * J * r2).reshape(r1, J, r2)
core_3 = np.arange(r2 * K).reshape(r2, K)
mode_names_1 = ["frequency", "time", "channel"]
mode_names_2 = [name for name in mode_names_1]
new_mode_names = {i: "{}".format(mode_names_1[i]) for i in range(len(ft_shape))}
new_mode_index = {i: ["index" for _ in range(ft_shape[i])] for i in range(len(ft_shape))}
core_values_1 = [core_1, core_2, core_3]
core_values_2 = [core.copy() for core in core_values_1]
tensor_tt_1 = TensorTT(core_values=core_values_1)
tensor_tt_2 = TensorTT(core_values=core_values_2)
assert tensor_tt_1 == tensor_tt_2
tensor_tt_1.set_mode_names(mode_names=new_mode_names)
tensor_tt_2.set_mode_names(mode_names=new_mode_names)
assert tensor_tt_1 == tensor_tt_2
tensor_tt_1.set_mode_index(mode_index=new_mode_index)
tensor_tt_2.set_mode_index(mode_index=new_mode_index)
assert tensor_tt_1 == tensor_tt_2
tensor_tt_1 = TensorTT(core_values=core_values_1, mode_names=mode_names_1)
tensor_tt_2 = TensorTT(core_values=core_values_2, mode_names=mode_names_2)
assert tensor_tt_1 == tensor_tt_2
# --------------------- Not equal because of core values
core_values_2 = [core.copy() * 2 for core in core_values_1]
tensor_tt_1 = TensorTT(core_values=core_values_1)
tensor_tt_2 = TensorTT(core_values=core_values_2)
assert tensor_tt_1 != tensor_tt_2
# --------------------- Not equal because of mode names
mode_names_2 = ["modified-{}".format(name) for name in mode_names_1]
core_values_2 = [core.copy() for core in core_values_1]
tensor_tt_1 = TensorTT(core_values=core_values_1, mode_names=mode_names_1)
tensor_tt_2 = TensorTT(core_values=core_values_2, mode_names=mode_names_2)
assert tensor_tt_1 != tensor_tt_2
tensor_tt_2.set_mode_names(mode_names=new_mode_names)
assert tensor_tt_1 == tensor_tt_2
# --------------------- Not equal to the because of mode index
core_values_2 = [core.copy() for core in core_values_1]
tensor_tt_1 = TensorTT(core_values=core_values_1)
tensor_tt_2 = TensorTT(core_values=core_values_2)
tensor_tt_2.set_mode_index(mode_index=new_mode_index)
assert tensor_tt_1 != tensor_tt_2
# --------------------- Not equal because of TT-Rank
core_values_2 = [core.copy() for core in core_values_1]
r1, J, r2 = core_values_2[1].shape
core_values_2[0] = np.arange(I * (r1+1)).reshape(I, (r1+1))
core_values_2[1] = np.arange((r1+1) * J * r2).reshape((r1+1), J, r2)
tensor_tt_1 = TensorTT(core_values=core_values_1)
tensor_tt_2 = TensorTT(core_values=core_values_2)
assert tensor_tt_1 != tensor_tt_2
# --------------------- Not equal because of ft_shape
core_values_2 = [core.copy() for core in core_values_1]
r1, J, r2 = core_values_2[1].shape
core_values_2[1] = np.arange(r1 * (J+1) * r2).reshape(r1, (J+1), r2)
tensor_tt_1 = TensorTT(core_values=core_values_1)
tensor_tt_2 = TensorTT(core_values=core_values_2)
assert tensor_tt_1 != tensor_tt_2
# --------------------- Not equal to the because it is an instance of another class
core_values_2 = [core.copy() for core in core_values_1]
tensor_tt_1 = TensorTT(core_values=core_values_1)
tensor_tt_2 = TensorTT(core_values=core_values_2)
tensor_full = tensor_tt_2.reconstruct()
assert tensor_tt_1 != tensor_full
def test_repr(self):
r1, r2 = 2, 3
I, J, K = 4, 5, 6
core_1 = np.arange(I * r1).reshape(I, r1)
core_2 = np.arange(r1 * J * r2).reshape(r1, J, r2)
core_3 = np.arange(r2 * K).reshape(r2, K)
core_values = [core_1, core_2, core_3]
tensor_tt = TensorTT(core_values=core_values)
captured_output = io.StringIO() # Create StringIO object
sys.stdout = captured_output # and redirect stdout.
print(repr(tensor_tt))
assert captured_output.getvalue() != '' # to check that something was actually printed
def test_copy(self):
""" Tests for creation a copy of TensorTT object """
r1, r2 = 2, 3
I, J, K = 4, 5, 6
core_1 = np.arange(I * r1).reshape(I, r1)
core_2 = np.arange(r1 * J * r2).reshape(r1, J, r2)
core_3 = np.arange(r2 * K).reshape(r2, K)
core_values = [core_1, core_2, core_3]
ft_shape = (I, J, K)
tensor_tt = TensorTT(core_values=core_values)
tensor_tt_copy = tensor_tt.copy()
# tests that the values are the same but not a reference
assert tensor_tt_copy is not tensor_tt
assert tensor_tt_copy.ft_shape is not tensor_tt.ft_shape
assert tensor_tt_copy.ft_shape == tensor_tt.ft_shape
assert tensor_tt_copy.rank == tensor_tt.rank
assert tensor_tt_copy.order == tensor_tt.order
assert tensor_tt_copy._core_values is not tensor_tt._core_values
for i in range(tensor_tt_copy.order):
assert tensor_tt_copy._core_values[i] is not tensor_tt._core_values[i]
np.testing.assert_array_equal(tensor_tt_copy._core_values[i], core_values[i])
np.testing.assert_array_equal(tensor_tt_copy._core_values[i], tensor_tt._core_values[i])
assert tensor_tt_copy.core(i) is not tensor_tt.core(i)
np.testing.assert_array_equal(tensor_tt_copy.core(i).data, tensor_tt.core(i).data)
assert tensor_tt_copy.cores is not tensor_tt.cores
def test_reconstruct(self):
""" Tests for reconstruction TensorTT object into the full form (Tensor) """
r1, r2 = 2, 3
I, J, K = 4, 5, 6
core_1 = np.arange(I * r1).reshape(I, r1)
core_2 = np.arange(r1 * J * r2).reshape(r1, J, r2)
core_3 = np.arange(r2 * K).reshape(r2, K)
core_values = [core_1, core_2, core_3]
ft_shape = (I, J, K)
true_data = np.array([[[ 300, 348, 396, 444, 492, 540],
[ 354, 411, 468, 525, 582, 639],
[ 408, 474, 540, 606, 672, 738],
[ 462, 537, 612, 687, 762, 837],
[ 516, 600, 684, 768, 852, 936]],
[[ 960, 1110, 1260, 1410, 1560, 1710],
[1230, 1425, 1620, 1815, 2010, 2205],
[1500, 1740, 1980, 2220, 2460, 2700],
[1770, 2055, 2340, 2625, 2910, 3195],
[2040, 2370, 2700, 3030, 3360, 3690]],
[[1620, 1872, 2124, 2376, 2628, 2880],
[2106, 2439, 2772, 3105, 3438, 3771],
[2592, 3006, 3420, 3834, 4248, 4662],
[3078, 3573, 4068, 4563, 5058, 5553],
[3564, 4140, 4716, 5292, 5868, 6444]],
[[2280, 2634, 2988, 3342, 3696, 4050],
[2982, 3453, 3924, 4395, 4866, 5337],
[3684, 4272, 4860, 5448, 6036, 6624],
[4386, 5091, 5796, 6501, 7206, 7911],
[5088, 5910, 6732, 7554, 8376, 9198]]])
true_default_mode_names = ['mode-0', 'mode-1', 'mode-2']
tensor_tt = TensorTT(core_values=core_values)
# ------ basic tests on getting correct results after reconstruction
tensor_rec = tensor_tt.reconstruct()
assert isinstance(tensor_rec, Tensor)
np.testing.assert_array_equal(tensor_rec.data, true_data)
assert (tensor_rec.ft_shape == ft_shape)
assert (tensor_rec.mode_names == true_default_mode_names)
# ------ tests for consecutive reconstructions: results should be the same but different objects
tensor_rec_1 = tensor_tt.reconstruct()
tensor_rec_2 = tensor_tt.reconstruct()
np.testing.assert_array_equal(tensor_rec_1.data, true_data)
np.testing.assert_array_equal(tensor_rec_1.data, tensor_rec_2.data)
assert tensor_rec_1 is not tensor_rec_2
# ------ tests for chaining methods
new_mode_names = {0: 'frequency',
1: 'time',
2: 'channel'
}
mode = 0
new_dim_size = 7
matrix = np.arange(new_dim_size * ft_shape[mode]).reshape(new_dim_size, ft_shape[mode])
tensor_rec = tensor_tt.reconstruct().set_mode_names(mode_names=new_mode_names)
for i, mode_name in enumerate(tensor_rec.mode_names):
assert (mode_name == new_mode_names[i])
new_name = 'age'
tensor_rec = tensor_tt.reconstruct().mode_n_product(matrix, mode=mode, new_name=new_name)
new_shape = [i for i in ft_shape]
new_shape[mode] = new_dim_size
new_shape = tuple(new_shape)
new_mode_names = true_default_mode_names
new_mode_names[mode] = new_name
assert (tensor_rec.shape == new_shape)
assert (tensor_rec.mode_names == new_mode_names)
# ------ tests for the 4th order Tensor
true_default_mode_names = ['mode-0', 'mode-1', 'mode-2', 'mode-3']
r1, r2, r3 = 2, 3, 4
I, J, K, L = 5, 6, 7, 8
core_1 = np.arange(I * r1).reshape(I, r1)
core_2 = np.arange(r1 * J * r2).reshape(r1, J, r2)
core_3 = np.arange(r2 * K * r3).reshape(r2, K, r3)
core_4 = np.arange(r3 * L).reshape(r3, L)
core_values = [core_1, core_2, core_3, core_4]
ft_shape = (I, J, K, L)
tensor_tt = TensorTT(core_values=core_values)
tensor_rec = tensor_tt.reconstruct()
assert (tensor_rec.shape == ft_shape)
assert (tensor_rec.mode_names == true_default_mode_names)
# ------ tests for the 5th order Tensor
true_default_mode_names = ['mode-0', 'mode-1', 'mode-2', 'mode-3', 'mode-4']
r1, r2, r3, r4 = 2, 3, 4, 5
I, J, K, L, M = 5, 6, 7, 8, 9
core_1 = np.arange(I * r1).reshape(I, r1)
core_2 = np.arange(r1 * J * r2).reshape(r1, J, r2)
core_3 = np.arange(r2 * K * r3).reshape(r2, K, r3)
core_4 = np.arange(r3 * L * r4).reshape(r3, L, r4)
core_5 = np.arange(r4 * M).reshape(r4, M)
core_values = [core_1, core_2, core_3, core_4, core_5]
ft_shape = (I, J, K, L, M)
tensor_tt = TensorTT(core_values=core_values)
tensor_rec = tensor_tt.reconstruct()
assert (tensor_rec.shape == ft_shape)
assert (tensor_rec.mode_names == true_default_mode_names)
def test_reconstruct_with_meta(self):
""" Tests for keeping meta data about modes """
r1, r2 = 2, 3
I, J, K = 2, 3, 4
core_1 = np.arange(I * r1).reshape(I, r1)
core_2 = np.arange(r1 * J * r2).reshape(r1, J, r2)
core_3 = np.arange(r2 * K).reshape(r2, K)
core_values = [core_1, core_2, core_3]
ft_shape = (I, J, K)
mode_names = ["country", "year", "month"]
mode_index ={0: ['UK', 'RUS'],
1: [2005, 2015, 2010],
2: ['Jan', 'Feb', 'Mar', 'Apr']}
tensor_tt = TensorTT(core_values=core_values, mode_names=mode_names)
tensor_tt.set_mode_index(mode_index=mode_index)
tensor = tensor_tt.reconstruct(keep_meta=2)
assert tensor.modes == tensor_tt.modes
tensor = tensor_tt.reconstruct(keep_meta=1)
assert all([tensor.modes[i].name == tensor_tt.modes[i].name for i in range(tensor.order)])
assert all([tensor.modes[i].index is None for i in range(tensor.order)])
tensor = tensor_tt.reconstruct(keep_meta=0)
tensor_tt.reset_mode_name()
tensor_tt.reset_mode_index()
assert tensor.modes == tensor_tt.modes
def test_set_mode_names(self):
""" Tests for `set_mode_names` method """
r1, r2 = 2, 3
I, J, K = 2, 3, 4
core_1 = np.arange(I * r1).reshape(I, r1)
core_2 = np.arange(r1 * J * r2).reshape(r1, J, r2)
core_3 = np.arange(r2 * K).reshape(r2, K)
core_values = [core_1, core_2, core_3]
ft_shape = (I, J, K)
init_names = ["country", "year", "month"]
mode_names = {i: name for i, name in enumerate(init_names)}
tensor_tkd = TensorTT(core_values=core_values)
tensor_tkd.set_mode_names(mode_names)
tensor_tkd_true = TensorTT(core_values=core_values, mode_names=init_names)
assert all([tensor_tkd.modes[i].name == tensor_tkd_true.modes[i].name for i in range(tensor_tkd.order)])
def test_reset_mode_name(self):
""" Tests for `reset_mode_name` method """
r1, r2 = 2, 3
I, J, K = 2, 3, 4
core_1 = np.arange(I * r1).reshape(I, r1)
core_2 = np.arange(r1 * J * r2).reshape(r1, J, r2)
core_3 = np.arange(r2 * K).reshape(r2, K)
core_values = [core_1, core_2, core_3]
ft_shape = (I, J, K)
init_names = ["country", "year", "month"]
tensor_tt = TensorTT(core_values=core_values, mode_names=init_names)
tensor_tt.reset_mode_name()
tensor_tkd_true = TensorTT(core_values=core_values)
assert all([tensor_tt.modes[i].name == tensor_tkd_true.modes[i].name for i in range(tensor_tt.order)])
tensor_tt = TensorTT(core_values=core_values, mode_names=init_names)
tensor_tt.reset_mode_name(mode=0)
init_names = ["mode-0", "year", "month"]
tensor_tt_true = TensorTT(core_values=core_values, mode_names=init_names)
assert all([tensor_tt.modes[i].name == tensor_tt_true.modes[i].name for i in range(tensor_tt.order)])
def test_set_mode_index(self):
""" Tests for `set_mode_index` method """
r1, r2 = 2, 3
I, J, K = 2, 3, 4
core_1 = np.arange(I * r1).reshape(I, r1)
core_2 = np.arange(r1 * J * r2).reshape(r1, J, r2)
core_3 = np.arange(r2 * K).reshape(r2, K)
core_values = [core_1, core_2, core_3]
ft_shape = (I, J, K)
tensor_tt = TensorTT(core_values=core_values)
mode_index = {0: ["idx1", "idx2"],
1: ["idx1", "idx2", "idx3"],
2: ["idx1", "idx2", "idx3", "idx4"]}
tensor_tt.set_mode_index(mode_index=mode_index)
assert all([tensor_tt.modes[i].index == mode_index[i] for i in range(tensor_tt.order)])
def test_reset_mode_index(self):
""" Tests for `reset_mode_index` method """
r1, r2 = 2, 3
I, J, K = 2, 3, 4
core_1 = np.arange(I * r1).reshape(I, r1)
core_2 = np.arange(r1 * J * r2).reshape(r1, J, r2)
core_3 = np.arange(r2 * K).reshape(r2, K)
core_values = [core_1, core_2, core_3]
ft_shape = (I, J, K)
tensor_tt = TensorTT(core_values=core_values)
mode_index = {0: ["idx1", "idx2"],
1: ["idx1", "idx2", "idx3"],
2: ["idx1", "idx2", "idx3", "idx4"]}
tensor_tt.set_mode_index(mode_index=mode_index)
tensor_tt.reset_mode_index()
tensor_tt_2 = TensorTT(core_values=core_values)
assert all([tensor_tt.modes[i].index == tensor_tt_2.modes[i].index for i in range(tensor_tt.order)])
tensor_tt = TensorTT(core_values=core_values)
mode_index = {0: ["idx1", "idx2"]}
tensor_tt.set_mode_index(mode_index=mode_index)
tensor_tt.reset_mode_index(mode=0)
tensor_tt_2 = TensorTT(core_values=core_values)
assert all([tensor_tt.modes[i].index == tensor_tt_2.modes[i].index for i in range(tensor_tt.order)])
| 48.471575 | 145 | 0.618323 | 14,834 | 104,020 | 4.060334 | 0.034515 | 0.068901 | 0.028822 | 0.03719 | 0.88481 | 0.854693 | 0.809948 | 0.779964 | 0.748551 | 0.715977 | 0 | 0.03303 | 0.270621 | 104,020 | 2,145 | 146 | 48.494172 | 0.760841 | 0.120121 | 0 | 0.675357 | 0 | 0 | 0.016186 | 0.000231 | 0 | 0 | 0 | 0.000466 | 0.187461 | 1 | 0.03352 | false | 0 | 0.005587 | 0 | 0.04221 | 0.002483 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
42431073b1ce1ec5092f33639eb0ac737fb18147 | 200 | py | Python | profiles_api/admin.py | erickoziel/profiles-rest-api | 0bef2a4f718e5ca88001c38d05c2a05670bfb76d | [
"MIT"
] | null | null | null | profiles_api/admin.py | erickoziel/profiles-rest-api | 0bef2a4f718e5ca88001c38d05c2a05670bfb76d | [
"MIT"
] | 7 | 2020-06-06T01:25:27.000Z | 2022-02-10T13:57:56.000Z | profiles_api/admin.py | erickoziel/profiles-rest-api | 0bef2a4f718e5ca88001c38d05c2a05670bfb76d | [
"MIT"
] | null | null | null | from django.contrib import admin
from profiles_api import models
admin.site.register(models.UserProfile)
admin.site.register(models.ProfileFeedItem)
admin.site.register(models.SentimentMessageItem)
| 25 | 48 | 0.855 | 25 | 200 | 6.8 | 0.52 | 0.158824 | 0.3 | 0.405882 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.065 | 200 | 7 | 49 | 28.571429 | 0.909091 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.4 | 0 | 0.4 | 0 | 1 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 6 |
424b6b81f8121e55c11545e696249e64f5aaaa58 | 2,697 | py | Python | xerlok_api/voice.py | JarbasAI/XerlokAPI | 4d377e64c4f4740c41859efeefb53c23307b3b16 | [
"MIT"
] | 1 | 2017-11-14T08:06:05.000Z | 2017-11-14T08:06:05.000Z | xerlok_api/voice.py | JarbasAI/XerlokAPI | 4d377e64c4f4740c41859efeefb53c23307b3b16 | [
"MIT"
] | null | null | null | xerlok_api/voice.py | JarbasAI/XerlokAPI | 4d377e64c4f4740c41859efeefb53c23307b3b16 | [
"MIT"
] | null | null | null | import requests
from requests.exceptions import ConnectionError
class XerlokVoice(object):
GENDER_URL = "http://159.203.78.247:5680/gender_recognition/"
SPEAKER_URL = "http://159.203.78.247:5679/speaker_recognition/"
EMOTION_URL = "http://159.203.78.247:5681/emotion_recognition/"
def __init__(self, api):
self.api = api
self.headers = {"Authorization": str(self.api)}
def recognize_emotion(self, wav_file):
filepath = wav_file
with open(filepath) as fh:
mydata = fh.read()
try:
response = requests.put(
XerlokVoice.EMOTION_URL + "recognize",
data=mydata,
headers=self.headers
)
except ConnectionError:
raise ConnectionError("The Emotion Analysis service is "
"unavailable.")
try:
return response.json()
except:
return response.text
def recognize_gender(self, wav_file):
filepath = wav_file
with open(filepath) as fh:
mydata = fh.read()
try:
response = requests.put(
XerlokVoice.GENDER_URL + "recognize",
data=mydata,
headers=self.headers
)
except ConnectionError:
raise ConnectionError("The Gender Analysis service is "
"unavailable.")
try:
return response.json()
except:
return response.text
def recognize_speaker(self, wav_file):
filepath = wav_file
with open(filepath) as fh:
mydata = fh.read()
try:
response = requests.put(
XerlokVoice.SPEAKER_URL + "recognize",
data=mydata,
headers=self.headers
)
except ConnectionError:
raise ConnectionError("The Speaker Recognition service is "
"unavailable.")
try:
return response.json()
except:
return response.text
def train_speaker(self, user, wav_file):
filepath = wav_file
with open(filepath) as fh:
mydata = fh.read()
try:
response = requests.put(
XerlokVoice.SPEAKER_URL + "train/" + user,
data=mydata,
headers=self.headers
)
except ConnectionError:
raise ConnectionError("The Speaker Recognition service is "
"unavailable.")
try:
return response.json()
except:
return response.text | 31.729412 | 71 | 0.529848 | 247 | 2,697 | 5.680162 | 0.218623 | 0.039914 | 0.042766 | 0.051319 | 0.779758 | 0.779758 | 0.741269 | 0.741269 | 0.741269 | 0.741269 | 0 | 0.027306 | 0.388951 | 2,697 | 85 | 72 | 31.729412 | 0.824029 | 0 | 0 | 0.701299 | 0 | 0 | 0.136027 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.064935 | false | 0 | 0.025974 | 0 | 0.246753 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
429e95f5ea64e6723851570567b41f94d106eb84 | 14,342 | py | Python | tests/shapes/test_connector.py | mistrymj/python-pptx | c1c72823de4adcf401711d806433ea6cecf65058 | [
"MIT"
] | null | null | null | tests/shapes/test_connector.py | mistrymj/python-pptx | c1c72823de4adcf401711d806433ea6cecf65058 | [
"MIT"
] | 1 | 2022-03-12T01:02:27.000Z | 2022-03-12T01:02:27.000Z | tests/shapes/test_connector.py | Blocp/python-pptx | 470ad045e46e8f611a54fa96f5cc5faa735ca607 | [
"MIT"
] | null | null | null | # encoding: utf-8
"""
Unit test suite for pptx.shapes.connector module.
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
import pytest
from pptx.shapes.base import BaseShape
from pptx.shapes.connector import Connector
from pptx.util import Emu
from ..unitutil.cxml import element, xml
from ..unitutil.mock import instance_mock, method_mock
class DescribeConnector(object):
def it_knows_its_begin_point_x_location(self, begin_x_get_fixture):
connector, expected_value = begin_x_get_fixture
begin_x = connector.begin_x
assert isinstance(begin_x, Emu)
assert connector.begin_x == expected_value
def it_can_change_its_begin_point_x_location(self, begin_x_set_fixture):
connector, new_x, expected_xml = begin_x_set_fixture
connector.begin_x = new_x
assert connector._element.xml == expected_xml
def it_knows_its_begin_point_y_location(self, begin_y_get_fixture):
connector, expected_value = begin_y_get_fixture
begin_y = connector.begin_y
assert isinstance(begin_y, Emu)
assert connector.begin_y == expected_value
def it_can_change_its_begin_point_y_location(self, begin_y_set_fixture):
connector, new_y, expected_xml = begin_y_set_fixture
connector.begin_y = new_y
assert connector._element.xml == expected_xml
def it_knows_its_end_point_x_location(self, end_x_get_fixture):
connector, expected_value = end_x_get_fixture
end_x = connector.end_x
assert isinstance(end_x, Emu)
assert connector.end_x == expected_value
def it_can_change_its_end_point_x_location(self, end_x_set_fixture):
connector, new_x, expected_xml = end_x_set_fixture
connector.end_x = new_x
assert connector._element.xml == expected_xml
def it_knows_its_end_point_y_location(self, end_y_get_fixture):
connector, expected_value = end_y_get_fixture
end_y = connector.end_y
assert isinstance(end_y, Emu)
assert connector.end_y == expected_value
def it_can_change_its_end_point_y_location(self, end_y_set_fixture):
connector, new_y, expected_xml = end_y_set_fixture
connector.end_y = new_y
assert connector._element.xml == expected_xml
def it_can_connect_its_begin_point_to_a_shape(self, begin_conn_fixture):
connector, shape, cxn_idx = begin_conn_fixture
connector.begin_connect(shape, cxn_idx)
connector._connect_begin_to.assert_called_once_with(
connector, shape, cxn_idx
)
connector._move_begin_to_cxn.assert_called_once_with(
connector, shape, cxn_idx
)
def it_connects_its_begin_point_to_help(self, connect_begin_fixture):
connector, shape, cxn_idx, expected_xml = connect_begin_fixture
connector._connect_begin_to(shape, cxn_idx)
assert connector._element.xml == expected_xml
def it_moves_its_begin_point_to_help(self, move_begin_fixture):
connector, shape, cxn_idx, expected_xml = move_begin_fixture
connector._move_begin_to_cxn(shape, cxn_idx)
assert connector._element.xml == expected_xml
def it_can_connect_its_end_point_to_a_shape(self, end_conn_fixture):
connector, shape, cxn_idx = end_conn_fixture
connector.end_connect(shape, cxn_idx)
connector._connect_end_to.assert_called_once_with(
connector, shape, cxn_idx
)
connector._move_end_to_cxn.assert_called_once_with(
connector, shape, cxn_idx
)
def it_connects_its_end_point_to_help(self, connect_end_fixture):
connector, shape, cxn_idx, expected_xml = connect_end_fixture
connector._connect_end_to(shape, cxn_idx)
assert connector._element.xml == expected_xml
def it_moves_its_end_point_to_help(self, move_end_fixture):
connector, shape, cxn_idx, expected_xml = move_end_fixture
connector._move_end_to_cxn(shape, cxn_idx)
assert connector._element.xml == expected_xml
# fixtures -------------------------------------------------------
@pytest.fixture
def begin_conn_fixture(self, _connect_begin_to_, _move_begin_to_cxn_):
connector = Connector(None, None)
shape, cxn_idx = 42, 24
return connector, shape, cxn_idx
@pytest.fixture(params=[
(42, 24, False, 42),
(24, 42, True, 66),
])
def begin_x_get_fixture(self, request):
x, cx, flipH, expected_value = request.param
cxnSp = element(
'p:cxnSp/p:spPr/a:xfrm{flipH=%d}/(a:off{x=%d,y=6},a:ext{cx=%d,cy'
'=32})' % (flipH, x, cx)
)
connector = Connector(cxnSp, None)
return connector, expected_value
@pytest.fixture(params=[
('a:xfrm/(a:off{x=10,y=1},a:ext{cx=10,cy=1})', 5,
'a:xfrm/(a:off{x=5,y=1},a:ext{cx=15,cy=1})'),
('a:xfrm/(a:off{x=10,y=1},a:ext{cx=10,cy=1})', 15,
'a:xfrm/(a:off{x=15,y=1},a:ext{cx=5,cy=1})'),
('a:xfrm/(a:off{x=10,y=1},a:ext{cx=10,cy=1})', 25,
'a:xfrm{flipH=1}/(a:off{x=20,y=1},a:ext{cx=5,cy=1})'),
('a:xfrm{flipH=1}/(a:off{x=10,y=1},a:ext{cx=10,cy=1})', 25,
'a:xfrm{flipH=1}/(a:off{x=10,y=1},a:ext{cx=15,cy=1})'),
('a:xfrm{flipH=1}/(a:off{x=10,y=1},a:ext{cx=10,cy=1})', 15,
'a:xfrm{flipH=1}/(a:off{x=10,y=1},a:ext{cx=5,cy=1})'),
('a:xfrm{flipH=1}/(a:off{x=10,y=1},a:ext{cx=10,cy=1})', 5,
'a:xfrm/(a:off{x=5,y=1},a:ext{cx=5,cy=1})'),
])
def begin_x_set_fixture(self, request):
xfrm_cxml, new_x, expected_cxml = request.param
tmpl = 'p:cxnSp/p:spPr/%s'
cxnSp = element(tmpl % xfrm_cxml)
expected_xml = xml(tmpl % expected_cxml)
connector = Connector(cxnSp, None)
return connector, new_x, expected_xml
@pytest.fixture(params=[
(40, 60, False, 40),
(50, 42, True, 92),
])
def begin_y_get_fixture(self, request):
y, cy, flipV, expected_value = request.param
cxnSp = element(
'p:cxnSp/p:spPr/a:xfrm{flipV=%d}/(a:off{x=6,y=%d},a:ext{cx=32,cy'
'=%d})' % (flipV, y, cy)
)
connector = Connector(cxnSp, None)
return connector, expected_value
@pytest.fixture(params=[
('a:xfrm/(a:off{x=1,y=10},a:ext{cx=1,cy=10})', 5,
'a:xfrm/(a:off{x=1,y=5},a:ext{cx=1,cy=15})'),
('a:xfrm/(a:off{x=1,y=10},a:ext{cx=1,cy=10})', 15,
'a:xfrm/(a:off{x=1,y=15},a:ext{cx=1,cy=5})'),
('a:xfrm/(a:off{x=1,y=10},a:ext{cx=1,cy=10})', 25,
'a:xfrm{flipV=1}/(a:off{x=1,y=20},a:ext{cx=1,cy=5})'),
('a:xfrm{flipV=1}/(a:off{x=1,y=10},a:ext{cx=1,cy=10})', 30,
'a:xfrm{flipV=1}/(a:off{x=1,y=10},a:ext{cx=1,cy=20})'),
('a:xfrm{flipV=1}/(a:off{x=1,y=10},a:ext{cx=1,cy=10})', 15,
'a:xfrm{flipV=1}/(a:off{x=1,y=10},a:ext{cx=1,cy=5})'),
('a:xfrm{flipV=1}/(a:off{x=1,y=10},a:ext{cx=1,cy=10})', 5,
'a:xfrm/(a:off{x=1,y=5},a:ext{cx=1,cy=5})'),
])
def begin_y_set_fixture(self, request):
xfrm_cxml, new_y, expected_cxml = request.param
tmpl = 'p:cxnSp/p:spPr/%s'
cxnSp = element(tmpl % xfrm_cxml)
expected_xml = xml(tmpl % expected_cxml)
connector = Connector(cxnSp, None)
return connector, new_y, expected_xml
@pytest.fixture(params=[
('p:cxnSp{a:b=c}/p:nvCxnSpPr/p:cNvCxnSpPr',
'p:cxnSp{a:b=c}/p:nvCxnSpPr/p:cNvCxnSpPr/a:stCxn{id=42,idx=3}'),
('p:cxnSp/p:nvCxnSpPr/p:cNvCxnSpPr/a:stCxn{id=66,idx=6}',
'p:cxnSp/p:nvCxnSpPr/p:cNvCxnSpPr/a:stCxn{id=42,idx=3}'),
])
def connect_begin_fixture(self, request, shape_):
cxnSp_cxml, expected_cxml = request.param
cxnSp = element(cxnSp_cxml)
connector = Connector(cxnSp, None)
shape_.id, cxn_idx = 42, 3
expected_xml = xml(expected_cxml)
return connector, shape_, cxn_idx, expected_xml
@pytest.fixture(params=[
('p:cxnSp{a:b=c}/p:nvCxnSpPr/p:cNvCxnSpPr',
'p:cxnSp{a:b=c}/p:nvCxnSpPr/p:cNvCxnSpPr/a:endCxn{id=24,idx=2}'),
('p:cxnSp/p:nvCxnSpPr/p:cNvCxnSpPr/a:endCxn{id=66,idx=6}',
'p:cxnSp/p:nvCxnSpPr/p:cNvCxnSpPr/a:endCxn{id=24,idx=2}'),
])
def connect_end_fixture(self, request, shape_):
cxnSp_cxml, expected_cxml = request.param
cxnSp = element(cxnSp_cxml)
connector = Connector(cxnSp, None)
shape_.id, cxn_idx = 24, 2
expected_xml = xml(expected_cxml)
return connector, shape_, cxn_idx, expected_xml
@pytest.fixture
def end_conn_fixture(self, _connect_end_to_, _move_end_to_cxn_):
connector = Connector(None, None)
shape, cxn_idx = 42, 24
return connector, shape, cxn_idx
@pytest.fixture(params=[
(21, 32, False, 53),
(43, 54, True, 43),
])
def end_x_get_fixture(self, request):
x, cx, flipH, expected_value = request.param
cxnSp = element(
'p:cxnSp/p:spPr/a:xfrm{flipH=%d}/(a:off{x=%d,y=6},a:ext{cx=%d,cy'
'=60})' % (flipH, x, cx)
)
connector = Connector(cxnSp, None)
return connector, expected_value
@pytest.fixture(params=[
('a:xfrm/(a:off{x=10,y=1},a:ext{cx=10,cy=1})', 32,
'a:xfrm/(a:off{x=10,y=1},a:ext{cx=22,cy=1})'),
('a:xfrm/(a:off{x=10,y=1},a:ext{cx=10,cy=1})', 15,
'a:xfrm/(a:off{x=10,y=1},a:ext{cx=5,cy=1})'),
('a:xfrm/(a:off{x=10,y=1},a:ext{cx=10,cy=1})', 5,
'a:xfrm{flipH=1}/(a:off{x=5,y=1},a:ext{cx=5,cy=1})'),
('a:xfrm{flipH=1}/(a:off{x=10,y=1},a:ext{cx=10,cy=1})', 5,
'a:xfrm{flipH=1}/(a:off{x=5,y=1},a:ext{cx=15,cy=1})'),
('a:xfrm{flipH=1}/(a:off{x=10,y=1},a:ext{cx=10,cy=1})', 15,
'a:xfrm{flipH=1}/(a:off{x=15,y=1},a:ext{cx=5,cy=1})'),
('a:xfrm{flipH=1}/(a:off{x=10,y=1},a:ext{cx=10,cy=1})', 28,
'a:xfrm/(a:off{x=20,y=1},a:ext{cx=8,cy=1})'),
])
def end_x_set_fixture(self, request):
xfrm_cxml, new_x, expected_cxml = request.param
tmpl = 'p:cxnSp/p:spPr/%s'
cxnSp = element(tmpl % xfrm_cxml)
expected_xml = xml(tmpl % expected_cxml)
connector = Connector(cxnSp, None)
return connector, new_x, expected_xml
@pytest.fixture(params=[
(31, 42, False, 73),
(53, 14, True, 53),
])
def end_y_get_fixture(self, request):
y, cy, flipV, expected_value = request.param
cxnSp = element(
'p:cxnSp/p:spPr/a:xfrm{flipV=%d}/(a:off{x=6,y=%d},a:ext{cx=32,cy'
'=%d})' % (flipV, y, cy)
)
connector = Connector(cxnSp, None)
return connector, expected_value
@pytest.fixture(params=[
('a:xfrm/(a:off{x=1,y=10},a:ext{cx=1,cy=10})', 28,
'a:xfrm/(a:off{x=1,y=10},a:ext{cx=1,cy=18})'),
('a:xfrm/(a:off{x=1,y=10},a:ext{cx=1,cy=10})', 13,
'a:xfrm/(a:off{x=1,y=10},a:ext{cx=1,cy=3})'),
('a:xfrm/(a:off{x=1,y=10},a:ext{cx=1,cy=10})', 4,
'a:xfrm{flipV=1}/(a:off{x=1,y=4},a:ext{cx=1,cy=6})'),
('a:xfrm{flipV=1}/(a:off{x=1,y=10},a:ext{cx=1,cy=10})', 6,
'a:xfrm{flipV=1}/(a:off{x=1,y=6},a:ext{cx=1,cy=14})'),
('a:xfrm{flipV=1}/(a:off{x=1,y=10},a:ext{cx=1,cy=10})', 12,
'a:xfrm{flipV=1}/(a:off{x=1,y=12},a:ext{cx=1,cy=8})'),
('a:xfrm{flipV=1}/(a:off{x=1,y=10},a:ext{cx=1,cy=10})', 27,
'a:xfrm/(a:off{x=1,y=20},a:ext{cx=1,cy=7})'),
])
def end_y_set_fixture(self, request):
xfrm_cxml, new_y, expected_cxml = request.param
tmpl = 'p:cxnSp/p:spPr/%s'
cxnSp = element(tmpl % xfrm_cxml)
expected_xml = xml(tmpl % expected_cxml)
connector = Connector(cxnSp, None)
return connector, new_y, expected_xml
@pytest.fixture(params=[
(0, 'p:cxnSp/p:spPr/a:xfrm/(a:off{x=25,y=15},a:ext{cx=74,cy=123})'),
(1, 'p:cxnSp/p:spPr/a:xfrm/(a:off{x=10,y=33},a:ext{cx=89,cy=105})'),
(2, 'p:cxnSp/p:spPr/a:xfrm/(a:off{x=25,y=51},a:ext{cx=74,cy=87})'),
(3, 'p:cxnSp/p:spPr/a:xfrm/(a:off{x=40,y=33},a:ext{cx=59,cy=105})'),
])
def move_begin_fixture(self, request, shape_):
cxn_idx, expected_cxml = request.param
cxnSp = element(
'p:cxnSp/p:spPr/a:xfrm/(a:off{x=66,y=99},a:ext{cx=33,cy=39})'
)
connector = Connector(cxnSp, None)
shape_.left, shape_.top, shape_.width, shape_.height = 10, 15, 30, 36
expected_xml = xml(expected_cxml)
return connector, shape_, cxn_idx, expected_xml
@pytest.fixture(params=[
(0, 'p:cxnSp/p:spPr/a:xfrm/(a:off{x=10,y=15},a:ext{cx=50,cy=10})'),
(1, 'p:cxnSp/p:spPr/a:xfrm/(a:off{x=10,y=15},a:ext{cx=40,cy=19})'),
(2, 'p:cxnSp/p:spPr/a:xfrm/(a:off{x=10,y=15},a:ext{cx=50,cy=28})'),
(3, 'p:cxnSp/p:spPr/a:xfrm/(a:off{x=10,y=15},a:ext{cx=60,cy=19})'),
])
def move_end_fixture(self, request, shape_):
cxn_idx, expected_cxml = request.param
cxnSp = element(
'p:cxnSp/p:spPr/a:xfrm/(a:off{x=10,y=15},a:ext{cx=10,cy=5})'
)
connector = Connector(cxnSp, None)
shape_.left, shape_.top, shape_.width, shape_.height = 50, 25, 20, 18
expected_xml = xml(expected_cxml)
return connector, shape_, cxn_idx, expected_xml
# fixture components ---------------------------------------------
@pytest.fixture
def _connect_begin_to_(self, request):
return method_mock(
request, Connector, '_connect_begin_to', autospec=True
)
@pytest.fixture
def _connect_end_to_(self, request):
return method_mock(
request, Connector, '_connect_end_to', autospec=True
)
@pytest.fixture
def _move_begin_to_cxn_(self, request):
return method_mock(
request, Connector, '_move_begin_to_cxn', autospec=True
)
@pytest.fixture
def _move_end_to_cxn_(self, request):
return method_mock(
request, Connector, '_move_end_to_cxn', autospec=True
)
@pytest.fixture
def shape_(self, request):
return instance_mock(request, BaseShape)
| 40.514124 | 77 | 0.599916 | 2,341 | 14,342 | 3.473302 | 0.064075 | 0.038126 | 0.038126 | 0.037634 | 0.838273 | 0.802484 | 0.748616 | 0.739884 | 0.676424 | 0.628336 | 0 | 0.047358 | 0.224097 | 14,342 | 353 | 78 | 40.628895 | 0.683321 | 0.013666 | 0 | 0.428571 | 0 | 0.225914 | 0.256013 | 0.245119 | 0 | 0 | 0 | 0 | 0.066445 | 1 | 0.109635 | false | 0 | 0.026578 | 0.016611 | 0.202658 | 0.003322 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
42a05aea90f730feb01f04643b2c71fd84f22672 | 151 | py | Python | elseifs.py | chidanandpujar/Python_scripts | 0ee70e07ef4ab4d8c04955466ea9b305bdac0a53 | [
"Unlicense"
] | null | null | null | elseifs.py | chidanandpujar/Python_scripts | 0ee70e07ef4ab4d8c04955466ea9b305bdac0a53 | [
"Unlicense"
] | null | null | null | elseifs.py | chidanandpujar/Python_scripts | 0ee70e07ef4ab4d8c04955466ea9b305bdac0a53 | [
"Unlicense"
] | null | null | null | num=int(input("Enter number:"))
if (num > 0):
print(num,"is positive")
elif (num < 0):
print(num,"is negative")
else:
print(num,"is zero")
| 18.875 | 31 | 0.596026 | 24 | 151 | 3.75 | 0.583333 | 0.266667 | 0.333333 | 0.266667 | 0.311111 | 0 | 0 | 0 | 0 | 0 | 0 | 0.016393 | 0.192053 | 151 | 7 | 32 | 21.571429 | 0.721311 | 0 | 0 | 0 | 0 | 0 | 0.278146 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.428571 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 6 |
c4002acaaf8c8798171dd6f3307f8c7a19f14aae | 61 | py | Python | securetea/lib/antivirus/tools/__init__.py | neerajv18/SecureTea-Project | e999cbe7c8e497c69b76b4c886de0d063169ea03 | [
"MIT"
] | 257 | 2018-03-28T12:43:20.000Z | 2022-03-29T07:07:23.000Z | securetea/lib/antivirus/tools/__init__.py | neerajv18/SecureTea-Project | e999cbe7c8e497c69b76b4c886de0d063169ea03 | [
"MIT"
] | 155 | 2018-03-31T14:57:46.000Z | 2022-03-17T18:12:41.000Z | securetea/lib/antivirus/tools/__init__.py | neerajv18/SecureTea-Project | e999cbe7c8e497c69b76b4c886de0d063169ea03 | [
"MIT"
] | 132 | 2018-03-27T06:25:20.000Z | 2022-03-28T11:32:45.000Z | """Summary."""
from . import file_gather
from . import utils
| 15.25 | 25 | 0.704918 | 8 | 61 | 5.25 | 0.75 | 0.47619 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.147541 | 61 | 3 | 26 | 20.333333 | 0.807692 | 0.131148 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
c44a358a66e9c3060a1c662962653b6a3c448f1e | 23 | py | Python | smap_nepse/prediction/__init__.py | Anyesh/Stock-Market-Analysis-and-Prediction | 3d400c34e1be0c731218cb4d02225ec02900520b | [
"MIT"
] | 11 | 2016-06-13T16:02:54.000Z | 2021-12-09T03:58:31.000Z | smap_nepse/prediction/__init__.py | Anyesh/Stock-Market-Analysis-and-Prediction | 3d400c34e1be0c731218cb4d02225ec02900520b | [
"MIT"
] | 4 | 2016-06-12T08:29:15.000Z | 2020-09-08T17:15:58.000Z | smap_nepse/prediction/__init__.py | Anyesh/Stock-Market-Analysis-and-Prediction | 3d400c34e1be0c731218cb4d02225ec02900520b | [
"MIT"
] | 11 | 2016-06-02T07:59:06.000Z | 2019-10-17T18:15:22.000Z | from .train import ann
| 11.5 | 22 | 0.782609 | 4 | 23 | 4.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.173913 | 23 | 1 | 23 | 23 | 0.947368 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
c452c622b7bcd4f331c6c852e03e3764de6a3120 | 32,656 | py | Python | tests/app/submitter/test_convert_payload_0_0_3.py | petechd/eq-questionnaire-runner | 1c5b182a7f8bc878cfdd767ae080410fa679abd6 | [
"MIT"
] | null | null | null | tests/app/submitter/test_convert_payload_0_0_3.py | petechd/eq-questionnaire-runner | 1c5b182a7f8bc878cfdd767ae080410fa679abd6 | [
"MIT"
] | null | null | null | tests/app/submitter/test_convert_payload_0_0_3.py | petechd/eq-questionnaire-runner | 1c5b182a7f8bc878cfdd767ae080410fa679abd6 | [
"MIT"
] | null | null | null | from app.data_models.answer import Answer
from app.data_models.answer_store import AnswerStore
from app.data_models.list_store import ListStore
from app.questionnaire.questionnaire_schema import QuestionnaireSchema
from app.questionnaire.routing_path import RoutingPath
from app.submitter.converter import convert_answers
from app.utilities.json import json_dumps, json_loads
from app.utilities.schema import load_schema_from_name
from tests.app.submitter.schema import make_schema
def test_convert_answers_to_payload_0_0_3(fake_questionnaire_store):
full_routing_path = [
RoutingPath(["about you", "where you live"], section_id="household-section")
]
fake_questionnaire_store.answer_store = AnswerStore(
[
Answer("name", "Joe Bloggs", None).to_dict(),
Answer("address", "62 Somewhere", None).to_dict(),
]
)
questionnaire = {
"survey_id": "021",
"data_version": "0.0.3",
"sections": [
{
"id": "household-section",
"groups": [
{
"id": "personal details",
"blocks": [
{
"id": "about you",
"type": "Question",
"question": {
"id": "crisps-question",
"answers": [{"id": "name", "type": "TextField"}],
},
}
],
},
{
"id": "household",
"blocks": [
{
"id": "where you live",
"type": "Question",
"question": {
"id": "crisps-question",
"answers": [{"id": "address", "type": "TextField"}],
},
}
],
},
],
}
],
}
# When
answer_object = convert_answers(
QuestionnaireSchema(questionnaire), fake_questionnaire_store, full_routing_path
)
# Then
assert len(answer_object["data"]["answers"]) == 2
assert answer_object["data"]["answers"][0].value == "Joe Bloggs"
assert answer_object["data"]["answers"][1].value, "62 Somewhere"
def test_convert_payload_0_0_3_multiple_answers(fake_questionnaire_store):
full_routing_path = [RoutingPath(["crisps"], section_id="section-1")]
answers = AnswerStore(
[Answer("crisps-answer", ["Ready salted", "Sweet chilli"]).to_dict()]
)
fake_questionnaire_store.answer_store = answers
questionnaire = make_schema(
"0.0.3",
"section-1",
"favourite-food",
"crisps",
{
"id": "crisps-question",
"answers": [
{
"id": "crisps-answer",
"type": "Checkbox",
"options": [
{"label": "Ready salted", "value": "Ready salted"},
{"label": "Sweet chilli", "value": "Sweet chilli"},
{"label": "Cheese and onion", "value": "Cheese and onion"},
],
}
],
},
)
# When
answer_object = convert_answers(
QuestionnaireSchema(questionnaire), fake_questionnaire_store, full_routing_path
)
# Then
assert len(answer_object["data"]["answers"]) == 1
assert answer_object["data"]["answers"][0].value == ["Ready salted", "Sweet chilli"]
def test_radio_answer(fake_questionnaire_store):
full_routing_path = [RoutingPath(["radio-block"], section_id="section-1")]
answers = AnswerStore([Answer("radio-answer", "Coffee").to_dict()])
fake_questionnaire_store.answer_store = answers
questionnaire = make_schema(
"0.0.3",
"section-1",
"radio-group",
"radio-block",
{
"id": "radio-question",
"answers": [
{
"type": "Radio",
"id": "radio-answer",
"options": [
{"label": "Coffee", "value": "Coffee"},
{"label": "Tea", "value": "Tea"},
],
}
],
},
)
answer_object = convert_answers(
QuestionnaireSchema(questionnaire), fake_questionnaire_store, full_routing_path
)
assert len(answer_object["data"]["answers"]) == 1
assert answer_object["data"]["answers"][0].value == "Coffee"
def test_number_answer(fake_questionnaire_store):
full_routing_path = [RoutingPath(["number-block"], section_id="section-1")]
answers = AnswerStore([Answer("number-answer", 1.755).to_dict()])
fake_questionnaire_store.answer_store = answers
questionnaire = make_schema(
"0.0.3",
"section-1",
"number-group",
"number-block",
{
"id": "number-question",
"answers": [{"id": "number-answer", "type": "Number"}],
},
)
answer_object = convert_answers(
QuestionnaireSchema(questionnaire), fake_questionnaire_store, full_routing_path
)
assert len(answer_object["data"]["answers"]) == 1
assert answer_object["data"]["answers"][0].value == 1.755
def test_percentage_answer(fake_questionnaire_store):
full_routing_path = [RoutingPath(["percentage-block"], section_id="section-1")]
answers = AnswerStore([Answer("percentage-answer", 99).to_dict()])
fake_questionnaire_store.answer_store = answers
questionnaire = make_schema(
"0.0.3",
"section-1",
"percentage-group",
"percentage-block",
{
"id": "percentage-question",
"answers": [{"id": "percentage-answer", "type": "Percentage"}],
},
)
answer_object = convert_answers(
QuestionnaireSchema(questionnaire), fake_questionnaire_store, full_routing_path
)
assert len(answer_object["data"]["answers"]) == 1
assert answer_object["data"]["answers"][0].value == 99
def test_textarea_answer(fake_questionnaire_store):
full_routing_path = [RoutingPath(["textarea-block"], section_id="section-1")]
answers = AnswerStore(
[Answer("textarea-answer", "This is an example text!").to_dict()]
)
fake_questionnaire_store.answer_store = answers
questionnaire = make_schema(
"0.0.3",
"section-1",
"textarea-group",
"textarea-block",
{
"id": "textarea-question",
"answers": [{"id": "textarea-answer", "type": "TextArea"}],
},
)
answer_object = convert_answers(
QuestionnaireSchema(questionnaire), fake_questionnaire_store, full_routing_path
)
assert len(answer_object["data"]["answers"]) == 1
assert answer_object["data"]["answers"][0].value == "This is an example text!"
def test_currency_answer(fake_questionnaire_store):
full_routing_path = [RoutingPath(["currency-block"], section_id="section-1")]
answers = AnswerStore([Answer("currency-answer", 100).to_dict()])
fake_questionnaire_store.answer_store = answers
questionnaire = make_schema(
"0.0.3",
"section-1",
"currency-group",
"currency-block",
{
"id": "currency-question",
"answers": [{"id": "currency-answer", "type": "Currency"}],
},
)
answer_object = convert_answers(
QuestionnaireSchema(questionnaire), fake_questionnaire_store, full_routing_path
)
assert len(answer_object["data"]["answers"]) == 1
assert answer_object["data"]["answers"][0].value == 100
def test_dropdown_answer(fake_questionnaire_store):
full_routing_path = [RoutingPath(["dropdown-block"], section_id="section-1")]
answers = AnswerStore([Answer("dropdown-answer", "Rugby is better!").to_dict()])
fake_questionnaire_store.answer_store = answers
questionnaire = make_schema(
"0.0.3",
"section-1",
"dropdown-group",
"dropdown-block",
{
"id": "dropdown-question",
"answers": [
{
"id": "dropdown-answer",
"type": "Dropdown",
"options": [
{"label": "Liverpool", "value": "Liverpool"},
{"label": "Chelsea", "value": "Chelsea"},
{"label": "Rugby is better!", "value": "Rugby is better!"},
],
}
],
},
)
answer_object = convert_answers(
QuestionnaireSchema(questionnaire), fake_questionnaire_store, full_routing_path
)
# Then
assert len(answer_object["data"]["answers"]) == 1
assert answer_object["data"]["answers"][0].value == "Rugby is better!"
def test_date_answer(fake_questionnaire_store):
full_routing_path = [RoutingPath(["date-block"], section_id="section-1")]
answers = AnswerStore(
[
Answer("single-date-answer", "01-01-1990").to_dict(),
Answer("month-year-answer", "01-1990").to_dict(),
]
)
fake_questionnaire_store.answer_store = answers
questionnaire = make_schema(
"0.0.3",
"section-1",
"date-group",
"date-block",
{
"id": "single-date-question",
"answers": [{"id": "single-date-answer", "type": "Date"}],
},
)
answer_object = convert_answers(
QuestionnaireSchema(questionnaire), fake_questionnaire_store, full_routing_path
)
assert len(answer_object["data"]["answers"]) == 1
assert answer_object["data"]["answers"][0].value == "01-01-1990"
def test_month_year_date_answer(fake_questionnaire_store):
full_routing_path = [RoutingPath(["date-block"], section_id="section-1")]
answers = AnswerStore(
[
Answer("single-date-answer", "01-01-1990").to_dict(),
Answer("month-year-answer", "01-1990").to_dict(),
]
)
fake_questionnaire_store.answer_store = answers
questionnaire = make_schema(
"0.0.3",
"section-1",
"date-group",
"date-block",
{
"id": "month-year-question",
"answers": [{"id": "month-year-answer", "type": "MonthYearDate"}],
},
)
answer_object = convert_answers(
QuestionnaireSchema(questionnaire), fake_questionnaire_store, full_routing_path
)
assert len(answer_object["data"]["answers"]) == 1
assert answer_object["data"]["answers"][0].value == "01-1990"
def test_unit_answer(fake_questionnaire_store):
full_routing_path = [RoutingPath(["unit-block"], section_id="section-1")]
answers = AnswerStore([Answer("unit-answer", 10).to_dict()])
fake_questionnaire_store.answer_store = answers
questionnaire = make_schema(
"0.0.3",
"section-1",
"unit-group",
"unit-block",
{"id": "unit-question", "answers": [{"id": "unit-answer", "type": "Unit"}]},
)
answer_object = convert_answers(
QuestionnaireSchema(questionnaire), fake_questionnaire_store, full_routing_path
)
assert len(answer_object["data"]["answers"]) == 1
assert answer_object["data"]["answers"][0].value == 10
def test_primary_person_list_item_conversion(fake_questionnaire_store):
routing_path = [
RoutingPath(
["primary-person-list-collector", "list-collector"], section_id="section-1"
)
]
answer_objects = [
{"answer_id": "you-live-here", "value": "Yes"},
{"answer_id": "first-name", "value": "1", "list_item_id": "xJlKBy"},
{"answer_id": "last-name", "value": "1", "list_item_id": "xJlKBy"},
{"answer_id": "first-name", "value": "2", "list_item_id": "RfAGDc"},
{"answer_id": "last-name", "value": "2", "list_item_id": "RfAGDc"},
{"answer_id": "anyone-else", "value": "No"},
]
answers = AnswerStore(answer_objects)
list_store = ListStore(
existing_items=[
{
"name": "people",
"items": ["xJlKBy", "RfAGDc"],
"primary_person": "xJlKBy",
}
]
)
fake_questionnaire_store.answer_store = answers
fake_questionnaire_store.list_store = list_store
schema = load_schema_from_name("test_list_collector_primary_person")
output = convert_answers(schema, fake_questionnaire_store, routing_path)
data_dict = json_loads(json_dumps(output["data"]["answers"]))
assert sorted(answer_objects, key=lambda x: x["answer_id"]) == sorted(
data_dict, key=lambda x: x["answer_id"]
)
def test_list_item_conversion(fake_questionnaire_store):
routing_path = [
RoutingPath(
["list-collector", "next-interstitial", "another-list-collector-block"],
section_id="section-1",
)
]
answer_objects = [
{"answer_id": "first-name", "value": "1", "list_item_id": "xJlKBy"},
{"answer_id": "last-name", "value": "1", "list_item_id": "xJlKBy"},
{"answer_id": "first-name", "value": "2", "list_item_id": "RfAGDc"},
{"answer_id": "last-name", "value": "2", "list_item_id": "RfAGDc"},
{"answer_id": "anyone-else", "value": "No"},
{"answer_id": "another-anyone-else", "value": "No"},
{"answer_id": "extraneous-answer", "value": "Bad", "list_item_id": "123"},
]
answers = AnswerStore(answer_objects)
list_store = ListStore(
existing_items=[{"name": "people", "items": ["xJlKBy", "RfAGDc"]}]
)
fake_questionnaire_store.answer_store = answers
fake_questionnaire_store.list_store = list_store
schema = load_schema_from_name("test_list_collector")
output = convert_answers(schema, fake_questionnaire_store, routing_path)
del answer_objects[-1]
data_dict = json_loads(json_dumps(output["data"]["answers"]))
assert sorted(answer_objects, key=lambda x: x["answer_id"]) == sorted(
data_dict, key=lambda x: x["answer_id"]
)
def test_list_item_conversion_empty_list(fake_questionnaire_store):
"""Test that the list store is populated with an empty list for lists which
do not have answers yet."""
routing_path = [
RoutingPath(
["list-collector", "next-interstitial", "another-list-collector-block"],
section_id="section-1",
)
]
answer_objects = [
{"answer_id": "last-name", "value": "2", "list_item_id": "RfAGDc"},
{"answer_id": "anyone-else", "value": "No"},
{"answer_id": "another-anyone-else", "value": "No"},
{"answer_id": "extraneous-answer", "value": "Bad", "list_item_id": "123"},
]
fake_questionnaire_store.answer_store = AnswerStore(answer_objects)
fake_questionnaire_store.list_store = ListStore()
schema = load_schema_from_name("test_list_collector")
output = convert_answers(schema, fake_questionnaire_store, routing_path)
# Answers not on the routing path
del answer_objects[0]
del answer_objects[-1]
data_dict = json_loads(json_dumps(output["data"]["answers"]))
assert sorted(answer_objects, key=lambda x: x["answer_id"]) == sorted(
data_dict, key=lambda x: x["answer_id"]
)
def test_default_answers_not_present_when_not_answered(fake_questionnaire_store):
"""Test that default values aren't submitted downstream when an answer with
a default value is not present in the answer store."""
schema = load_schema_from_name("test_default")
answer_objects = [{"answer_id": "number-question-two", "value": "12"}]
fake_questionnaire_store.answer_store = AnswerStore(answer_objects)
fake_questionnaire_store.list_store = ListStore()
routing_path = [
RoutingPath(
["number-question-one", "number-question-two"], section_id="default-section"
)
]
output = convert_answers(schema, fake_questionnaire_store, routing_path)
data = json_loads(json_dumps(output["data"]["answers"]))
answer_ids = {answer["answer_id"] for answer in data}
assert "answer-one" not in answer_ids
def test_list_structure_in_payload_is_as_expected(fake_questionnaire_store):
routing_path = [
RoutingPath(
["primary-person-list-collector", "list-collector"], section_id="section-1"
)
]
answer_objects = [
{"answer_id": "you-live-here", "value": "Yes"},
{"answer_id": "first-name", "value": "1", "list_item_id": "xJlKBy"},
{"answer_id": "last-name", "value": "1", "list_item_id": "xJlKBy"},
{"answer_id": "first-name", "value": "2", "list_item_id": "RfAGDc"},
{"answer_id": "last-name", "value": "2", "list_item_id": "RfAGDc"},
{"answer_id": "anyone-else", "value": "No"},
]
answers = AnswerStore(answer_objects)
list_store = ListStore(
existing_items=[
{
"name": "people",
"items": ["xJlKBy", "RfAGDc"],
"primary_person": "xJlKBy",
}
]
)
fake_questionnaire_store.answer_store = answers
fake_questionnaire_store.list_store = list_store
schema = load_schema_from_name("test_list_collector_primary_person")
output = convert_answers(schema, fake_questionnaire_store, routing_path)
data_dict = json_loads(json_dumps(output["data"]["lists"]))
assert data_dict[0]["name"] == "people"
assert "xJlKBy" in data_dict[0]["items"]
assert data_dict[0]["primary_person"] == "xJlKBy"
def test_primary_person_not_in_payload_when_not_answered(fake_questionnaire_store):
routing_path = [
RoutingPath(
["list-collector", "next-interstitial", "another-list-collector-block"],
section_id="section-1",
)
]
answer_objects = [
{"answer_id": "first-name", "value": "1", "list_item_id": "xJlKBy"},
{"answer_id": "last-name", "value": "1", "list_item_id": "xJlKBy"},
{"answer_id": "first-name", "value": "2", "list_item_id": "RfAGDc"},
{"answer_id": "last-name", "value": "2", "list_item_id": "RfAGDc"},
{"answer_id": "anyone-else", "value": "No"},
{"answer_id": "another-anyone-else", "value": "No"},
{"answer_id": "extraneous-answer", "value": "Bad", "list_item_id": "123"},
]
answers = AnswerStore(answer_objects)
list_store = ListStore(
existing_items=[{"name": "people", "items": ["xJlKBy", "RfAGDc"]}]
)
fake_questionnaire_store.answer_store = answers
fake_questionnaire_store.list_store = list_store
schema = load_schema_from_name("test_list_collector")
output = convert_answers(schema, fake_questionnaire_store, routing_path)
data_dict = json_loads(json_dumps(output["data"]["lists"]))
assert "primary_person" not in data_dict[0]
def test_relationships_in_payload(fake_questionnaire_store):
routing_path = [
RoutingPath(
["list-collector", "relationships"],
section_id="section",
)
]
answer_objects = [
{"answer_id": "first-name", "value": "1", "list_item_id": "person1"},
{"answer_id": "last-name", "value": "1", "list_item_id": "person1"},
{"answer_id": "first-name", "value": "2", "list_item_id": "person2"},
{"answer_id": "last-name", "value": "2", "list_item_id": "person2"},
{"answer_id": "first-name", "value": "3", "list_item_id": "person3"},
{"answer_id": "last-name", "value": "3", "list_item_id": "person3"},
{"answer_id": "anyone-else", "value": "No"},
{
"answer_id": "relationship-answer",
"value": [
{
"list_item_id": "person1",
"to_list_item_id": "person2",
"relationship": "Husband or Wife",
},
{
"list_item_id": "person1",
"to_list_item_id": "person3",
"relationship": "Son or daughter",
},
],
},
]
answers = AnswerStore(answer_objects)
list_store = ListStore(
existing_items=[
{
"name": "people",
"items": [
"person1",
"person2",
"person3",
],
}
]
)
fake_questionnaire_store.answer_store = answers
fake_questionnaire_store.list_store = list_store
schema = load_schema_from_name("test_relationships")
output = convert_answers(schema, fake_questionnaire_store, routing_path)
data = json_loads(json_dumps(output["data"]["answers"]))
answers = {answer["answer_id"]: answer for answer in data}
expected_relationships_answer = [
{
"list_item_id": "person1",
"relationship": "Husband or Wife",
"to_list_item_id": "person2",
},
{
"list_item_id": "person1",
"relationship": "Son or daughter",
"to_list_item_id": "person3",
},
]
relationships_answer = answers["relationship-answer"]
assert expected_relationships_answer == relationships_answer["value"]
def test_no_relationships_in_payload(fake_questionnaire_store):
routing_path = [
RoutingPath(
["list-collector", "relationships"],
section_id="section",
)
]
answer_objects = [
{"answer_id": "first-name", "value": "1", "list_item_id": "person1"},
{"answer_id": "last-name", "value": "1", "list_item_id": "person1"},
{"answer_id": "first-name", "value": "2", "list_item_id": "person2"},
{"answer_id": "last-name", "value": "2", "list_item_id": "person2"},
{"answer_id": "first-name", "value": "3", "list_item_id": "person3"},
{"answer_id": "last-name", "value": "3", "list_item_id": "person3"},
{"answer_id": "anyone-else", "value": "No"},
]
answers = AnswerStore(answer_objects)
list_store = ListStore(
existing_items=[
{
"name": "people",
"items": [
"person1",
"person2",
"person3",
],
}
]
)
fake_questionnaire_store.answer_store = answers
fake_questionnaire_store.list_store = list_store
schema = load_schema_from_name("test_relationships_unrelated")
output = convert_answers(schema, fake_questionnaire_store, routing_path)
data = json_loads(json_dumps(output["data"]["answers"]))
answers = {answer["answer_id"]: answer for answer in data}
assert "relationship-answer" not in answers
def test_unrelated_block_answers_in_payload(fake_questionnaire_store):
routing_path = [
RoutingPath(
["list-collector", "relationships"],
section_id="section",
)
]
answer_objects = [
{"answer_id": "first-name", "value": "1", "list_item_id": "person1"},
{"answer_id": "last-name", "value": "1", "list_item_id": "person1"},
{"answer_id": "first-name", "value": "2", "list_item_id": "person2"},
{"answer_id": "last-name", "value": "2", "list_item_id": "person2"},
{"answer_id": "first-name", "value": "3", "list_item_id": "person3"},
{"answer_id": "last-name", "value": "3", "list_item_id": "person3"},
{"answer_id": "first-name", "value": "4", "list_item_id": "person4"},
{"answer_id": "last-name", "value": "4", "list_item_id": "person4"},
{"answer_id": "first-name", "value": "5", "list_item_id": "person5"},
{"answer_id": "last-name", "value": "5", "list_item_id": "person5"},
{"answer_id": "anyone-else", "value": "No"},
{
"answer_id": "relationship-answer",
"value": [
{
"list_item_id": "person1",
"to_list_item_id": "person2",
"relationship": "Unrelated",
},
{
"list_item_id": "person1",
"to_list_item_id": "person3",
"relationship": "Unrelated",
},
{
"list_item_id": "person1",
"to_list_item_id": "person4",
"relationship": "Unrelated",
},
],
},
{
"answer_id": "related-to-anyone-else-answer",
"value": "Yes",
"list_item_id": "person1",
},
]
answers = AnswerStore(answer_objects)
list_store = ListStore(
existing_items=[
{
"name": "people",
"items": [
"person1",
"person2",
"person3",
"person4",
"person5",
],
}
]
)
fake_questionnaire_store.answer_store = answers
fake_questionnaire_store.list_store = list_store
schema = load_schema_from_name("test_relationships_unrelated")
output = convert_answers(schema, fake_questionnaire_store, routing_path)
data = json_loads(json_dumps(output["data"]["answers"]))
answers = {
(answer["answer_id"], answer.get("list_item_id")): answer for answer in data
}
expected_relationships_answer = [
{
"list_item_id": "person1",
"relationship": "Unrelated",
"to_list_item_id": "person2",
},
{
"list_item_id": "person1",
"relationship": "Unrelated",
"to_list_item_id": "person3",
},
{
"list_item_id": "person1",
"relationship": "Unrelated",
"to_list_item_id": "person4",
},
]
assert ("related-to-anyone-else-answer", "person1") in answers
relationships_answer = answers[("relationship-answer", None)]
assert expected_relationships_answer == relationships_answer["value"]
def test_unrelated_block_answers_not_on_path_not_in_payload(fake_questionnaire_store):
routing_path = [
RoutingPath(
["list-collector", "relationships"],
section_id="section",
)
]
answer_objects = [
{"answer_id": "first-name", "value": "1", "list_item_id": "person1"},
{"answer_id": "last-name", "value": "1", "list_item_id": "person1"},
{"answer_id": "first-name", "value": "2", "list_item_id": "person2"},
{"answer_id": "last-name", "value": "2", "list_item_id": "person2"},
{"answer_id": "first-name", "value": "3", "list_item_id": "person3"},
{"answer_id": "last-name", "value": "3", "list_item_id": "person3"},
{"answer_id": "first-name", "value": "4", "list_item_id": "person4"},
{"answer_id": "last-name", "value": "4", "list_item_id": "person4"},
{"answer_id": "first-name", "value": "5", "list_item_id": "person5"},
{"answer_id": "last-name", "value": "5", "list_item_id": "person5"},
{"answer_id": "anyone-else", "value": "No"},
{
"answer_id": "relationship-answer",
"value": [
{
"list_item_id": "person1",
"to_list_item_id": "person2",
"relationship": "Unrelated",
},
{
"list_item_id": "person1",
"to_list_item_id": "person3",
"relationship": "Related",
},
],
},
{
"answer_id": "related-to-anyone-else-answer",
"value": "No",
"list_item_id": "person1",
},
]
answers = AnswerStore(answer_objects)
list_store = ListStore(
existing_items=[
{
"name": "people",
"items": [
"person1",
"person2",
"person3",
"person4",
"person5",
],
}
]
)
fake_questionnaire_store.answer_store = answers
fake_questionnaire_store.list_store = list_store
schema = load_schema_from_name("test_relationships_unrelated")
output = convert_answers(schema, fake_questionnaire_store, routing_path)
data = json_loads(json_dumps(output["data"]["answers"]))
answers = {
(answer["answer_id"], answer.get("list_item_id")): answer for answer in data
}
assert ("related-to-anyone-else-answer", "person1") not in answers
def test_relationship_answers_not_on_path_in_payload(fake_questionnaire_store):
routing_path = [
RoutingPath(
["list-collector", "relationships"],
section_id="section",
)
]
answer_objects = [
{"answer_id": "first-name", "value": "1", "list_item_id": "person1"},
{"answer_id": "last-name", "value": "1", "list_item_id": "person1"},
{"answer_id": "first-name", "value": "2", "list_item_id": "person2"},
{"answer_id": "last-name", "value": "2", "list_item_id": "person2"},
{"answer_id": "first-name", "value": "3", "list_item_id": "person3"},
{"answer_id": "last-name", "value": "3", "list_item_id": "person3"},
{"answer_id": "first-name", "value": "4", "list_item_id": "person4"},
{"answer_id": "last-name", "value": "4", "list_item_id": "person4"},
{"answer_id": "first-name", "value": "5", "list_item_id": "person5"},
{"answer_id": "last-name", "value": "5", "list_item_id": "person5"},
{"answer_id": "anyone-else", "value": "No"},
{
"answer_id": "relationship-answer",
"value": [
{
"list_item_id": "person1",
"to_list_item_id": "person2",
"relationship": "Unrelated",
},
{
"list_item_id": "person1",
"to_list_item_id": "person3",
"relationship": "Unrelated",
},
{
"list_item_id": "person1",
"to_list_item_id": "person4",
"relationship": "Unrelated",
},
{
"list_item_id": "person1",
"to_list_item_id": "person5",
"relationship": "Unrelated",
},
],
},
{
"answer_id": "related-to-anyone-else-answer",
"value": "No",
"list_item_id": "person1",
},
]
answers = AnswerStore(answer_objects)
list_store = ListStore(
existing_items=[
{
"name": "people",
"items": [
"person1",
"person2",
"person3",
"person4",
"person5",
],
}
]
)
fake_questionnaire_store.answer_store = answers
fake_questionnaire_store.list_store = list_store
schema = load_schema_from_name("test_relationships_unrelated")
output = convert_answers(schema, fake_questionnaire_store, routing_path)
data = json_loads(json_dumps(output["data"]["answers"]))
answers = {
(answer["answer_id"], answer.get("list_item_id")): answer for answer in data
}
expected_relationships_answer = [
{
"list_item_id": "person1",
"relationship": "Unrelated",
"to_list_item_id": "person2",
},
{
"list_item_id": "person1",
"relationship": "Unrelated",
"to_list_item_id": "person3",
},
{
"list_item_id": "person1",
"relationship": "Unrelated",
"to_list_item_id": "person4",
},
{
"list_item_id": "person1",
"relationship": "Unrelated",
"to_list_item_id": "person5",
},
]
assert ("related-to-anyone-else-answer", "person1") in answers
relationships_answer = answers[("relationship-answer", None)]
assert expected_relationships_answer == relationships_answer["value"]
| 33.631308 | 88 | 0.552609 | 3,247 | 32,656 | 5.2587 | 0.058824 | 0.052006 | 0.06325 | 0.032855 | 0.838184 | 0.815813 | 0.812767 | 0.795256 | 0.74899 | 0.743777 | 0 | 0.014964 | 0.296025 | 32,656 | 970 | 89 | 33.665979 | 0.727783 | 0.008574 | 0 | 0.582707 | 0 | 0 | 0.27241 | 0.015331 | 0 | 0 | 0 | 0 | 0.047619 | 1 | 0.027569 | false | 0 | 0.011278 | 0 | 0.038847 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
c47ce8d46d335a55c5945407eb08191575f60ecb | 41 | py | Python | neutpy/physics/__init__.py | gt-frc/neutpy | 4ae03fba5bdf34bd83ac0d88c5d6e53f3c708785 | [
"MIT"
] | null | null | null | neutpy/physics/__init__.py | gt-frc/neutpy | 4ae03fba5bdf34bd83ac0d88c5d6e53f3c708785 | [
"MIT"
] | 10 | 2020-08-05T21:29:02.000Z | 2020-10-17T02:08:11.000Z | neutpy/physics/__init__.py | gt-frc/neutpy | 4ae03fba5bdf34bd83ac0d88c5d6e53f3c708785 | [
"MIT"
] | 1 | 2021-12-03T11:46:15.000Z | 2021-12-03T11:46:15.000Z | #!/usr/bin/python
from .physics import * | 13.666667 | 22 | 0.707317 | 6 | 41 | 4.833333 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.121951 | 41 | 3 | 22 | 13.666667 | 0.805556 | 0.390244 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
6707dec41060531445e578ccf5f9087f3e49f942 | 22 | py | Python | preview/__init__.py | nickmcdonald/ies-generator | 122df628afd2b0135a4910c8c76d45cb7ec93ef2 | [
"MIT"
] | 31 | 2018-08-19T07:15:14.000Z | 2022-02-20T05:30:14.000Z | preview/__init__.py | nickmcdonald/ies-generator | 122df628afd2b0135a4910c8c76d45cb7ec93ef2 | [
"MIT"
] | 10 | 2018-09-02T20:50:13.000Z | 2022-02-24T17:55:25.000Z | preview/__init__.py | nickmcdonald/ies-generator | 122df628afd2b0135a4910c8c76d45cb7ec93ef2 | [
"MIT"
] | 4 | 2020-12-18T18:11:54.000Z | 2022-02-20T05:30:18.000Z | from .preview import * | 22 | 22 | 0.772727 | 3 | 22 | 5.666667 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.136364 | 22 | 1 | 22 | 22 | 0.894737 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
6758aa7bf51752e00163ef8d44a762ba15455aa9 | 15,166 | py | Python | test/test_markdown_autolinks.py | scop/pymarkdown | 562ba8f7857d99ba09e86e42de5a37ec6d9b2c30 | [
"MIT"
] | null | null | null | test/test_markdown_autolinks.py | scop/pymarkdown | 562ba8f7857d99ba09e86e42de5a37ec6d9b2c30 | [
"MIT"
] | null | null | null | test/test_markdown_autolinks.py | scop/pymarkdown | 562ba8f7857d99ba09e86e42de5a37ec6d9b2c30 | [
"MIT"
] | null | null | null | """
https://github.github.com/gfm/#autolinks
"""
import pytest
from .utils import act_and_assert
@pytest.mark.gfm
def test_autolinks_602():
"""
Test case 602: (part 1) Here are some valid autolinks:
"""
# Arrange
source_markdown = """<http://foo.bar.baz>"""
expected_tokens = [
"[para(1,1):]",
"[uri-autolink(1,1):http://foo.bar.baz]",
"[end-para:::True]",
]
expected_gfm = """<p><a href="http://foo.bar.baz">http://foo.bar.baz</a></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_603():
"""
Test case 603: (part 2) Here are some valid autolinks:
"""
# Arrange
source_markdown = """<http://foo.bar.baz/test?q=hello&id=22&boolean>"""
expected_tokens = [
"[para(1,1):]",
"[uri-autolink(1,1):http://foo.bar.baz/test?q=hello&id=22&boolean]",
"[end-para:::True]",
]
expected_gfm = """<p><a href="http://foo.bar.baz/test?q=hello&id=22&boolean">http://foo.bar.baz/test?q=hello&id=22&boolean</a></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_604():
"""
Test case 604: (part 3) Here are some valid autolinks:
"""
# Arrange
source_markdown = """<irc://foo.bar:2233/baz>"""
expected_tokens = [
"[para(1,1):]",
"[uri-autolink(1,1):irc://foo.bar:2233/baz]",
"[end-para:::True]",
]
expected_gfm = (
"""<p><a href="irc://foo.bar:2233/baz">irc://foo.bar:2233/baz</a></p>"""
)
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_604a():
"""
Test case 604a: variations
"""
# Arrange
source_markdown = """<irc:foo.bar>"""
expected_tokens = [
"[para(1,1):]",
"[uri-autolink(1,1):irc:foo.bar]",
"[end-para:::True]",
]
expected_gfm = """<p><a href="irc:foo.bar">irc:foo.bar</a></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_604b():
"""
Test case 604b: variations
"""
# Arrange
source_markdown = """<my+weird-custom.scheme1:foo.bar>"""
expected_tokens = [
"[para(1,1):]",
"[uri-autolink(1,1):my+weird-custom.scheme1:foo.bar]",
"[end-para:::True]",
]
expected_gfm = """<p><a href="my+weird-custom.scheme1:foo.bar">my+weird-custom.scheme1:foo.bar</a></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_605():
"""
Test case 605: Uppercase is also fine
"""
# Arrange
source_markdown = """<MAILTO:FOO@BAR.BAZ>"""
expected_tokens = [
"[para(1,1):]",
"[uri-autolink(1,1):MAILTO:FOO@BAR.BAZ]",
"[end-para:::True]",
]
expected_gfm = """<p><a href="MAILTO:FOO@BAR.BAZ">MAILTO:FOO@BAR.BAZ</a></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_606():
"""
Test case 606: (part 1) Note that many strings that count as absolute URIs for purposes of this spec are not valid URIs, because their schemes are not registered or because of other problems with their syntax:
"""
# Arrange
source_markdown = """<a+b+c:d>"""
expected_tokens = [
"[para(1,1):]",
"[uri-autolink(1,1):a+b+c:d]",
"[end-para:::True]",
]
expected_gfm = """<p><a href="a+b+c:d">a+b+c:d</a></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_607():
"""
Test case 607: (part 2) Note that many strings that count as absolute URIs for purposes of this spec are not valid URIs, because their schemes are not registered or because of other problems with their syntax:
"""
# Arrange
source_markdown = """<made-up-scheme://foo,bar>"""
expected_tokens = [
"[para(1,1):]",
"[uri-autolink(1,1):made-up-scheme://foo,bar]",
"[end-para:::True]",
]
expected_gfm = (
"""<p><a href="made-up-scheme://foo,bar">made-up-scheme://foo,bar</a></p>"""
)
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_608():
"""
Test case 608: (part 3) Note that many strings that count as absolute URIs for purposes of this spec are not valid URIs, because their schemes are not registered or because of other problems with their syntax:
"""
# Arrange
source_markdown = """<http://../>"""
expected_tokens = [
"[para(1,1):]",
"[uri-autolink(1,1):http://../]",
"[end-para:::True]",
]
expected_gfm = """<p><a href="http://../">http://../</a></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_609():
"""
Test case 609: (part 4) Note that many strings that count as absolute URIs for purposes of this spec are not valid URIs, because their schemes are not registered or because of other problems with their syntax:
"""
# Arrange
source_markdown = """<localhost:5001/foo>"""
expected_tokens = [
"[para(1,1):]",
"[uri-autolink(1,1):localhost:5001/foo]",
"[end-para:::True]",
]
expected_gfm = """<p><a href="localhost:5001/foo">localhost:5001/foo</a></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_610():
"""
Test case 610: Spaces are not allowed in autolinks:
"""
# Arrange
source_markdown = """<http://foo.bar/baz bim>"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):\a<\a<\ahttp://foo.bar/baz bim\a>\a>\a:]",
"[end-para:::True]",
]
expected_gfm = """<p><http://foo.bar/baz bim></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_611():
"""
Test case 611: Backslash-escapes do not work inside autolinks:
"""
# Arrange
source_markdown = """<http://example.com/\\[\\>"""
expected_tokens = [
"[para(1,1):]",
"[uri-autolink(1,1):http://example.com/\\[\\]",
"[end-para:::True]",
]
expected_gfm = (
"""<p><a href="http://example.com/%5C%5B%5C">http://example.com/\\[\\</a></p>"""
)
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_611a():
"""
Test case 611a: Backslash-escapes do not work inside autolinks:
"""
# Arrange
source_markdown = """<http://example.com/\u2122\u20AC>"""
expected_tokens = [
"[para(1,1):]",
"[uri-autolink(1,1):http://example.com/™€]",
"[end-para:::True]",
]
expected_gfm = """<p><a href="http://example.com/%E2%84%A2%E2%82%AC">http://example.com/™€</a></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_611b():
"""
Test case 611b: Backslash-escapes do not work inside autolinks:
"""
# Arrange
source_markdown = """<http://abcdefjhijklmnopqrstuvwxyz!"#$%&'()*+,-./0123456789:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`{}|~ABC>"""
expected_tokens = [
"[para(1,1):]",
"[uri-autolink(1,1):http://abcdefjhijklmnopqrstuvwxyz!\"#$%&'()*+,-./0123456789:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`{}|~ABC]",
"[end-para:::True]",
]
expected_gfm = """<p><a href="http://abcdefjhijklmnopqrstuvwxyz!%22#$%25&'()*+,-./0123456789:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60%7B%7D%7C~ABC">http://abcdefjhijklmnopqrstuvwxyz!"#$%&'()*+,-./0123456789:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`{}|~ABC</a></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_612():
"""
Test case 612: (part 1) Examples of email autolinks:
"""
# Arrange
source_markdown = """<foo@bar.example.com>"""
expected_tokens = [
"[para(1,1):]",
"[email-autolink(1,1):foo@bar.example.com]",
"[end-para:::True]",
]
expected_gfm = (
"""<p><a href="mailto:foo@bar.example.com">foo@bar.example.com</a></p>"""
)
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_613():
"""
Test case 613: (part 2) Examples of email autolinks:
"""
# Arrange
source_markdown = """<foo+special@Bar.baz-bar0.com>"""
expected_tokens = [
"[para(1,1):]",
"[email-autolink(1,1):foo+special@Bar.baz-bar0.com]",
"[end-para:::True]",
]
expected_gfm = """<p><a href="mailto:foo+special@Bar.baz-bar0.com">foo+special@Bar.baz-bar0.com</a></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_613a():
"""
Test case 613a: variations
"""
# Arrange
source_markdown = """<l@f>"""
expected_tokens = ["[para(1,1):]", "[email-autolink(1,1):l@f]", "[end-para:::True]"]
expected_gfm = """<p><a href="mailto:l@f">l@f</a></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_614():
"""
Test case 614: Backslash-escapes do not work inside email autolinks:
"""
# Arrange
source_markdown = """<foo\\+@bar.example.com>"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):\a<\a<\afoo\\\b+@bar.example.com\a>\a>\a:]",
"[end-para:::True]",
]
expected_gfm = """<p><foo+@bar.example.com></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_615():
"""
Test case 615: (part 1) These are not autolinks:
"""
# Arrange
source_markdown = """<>"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):\a<\a<\a\a>\a>\a:]",
"[end-para:::True]",
]
expected_gfm = """<p><></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_616():
"""
Test case 616: (part 2) These are not autolinks:
"""
# Arrange
source_markdown = """< http://foo.bar >"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):\a<\a<\a http://foo.bar \a>\a>\a:]",
"[end-para:::True]",
]
expected_gfm = """<p>< http://foo.bar ></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_617():
"""
Test case 617: (part 3) These are not autolinks:
"""
# Arrange
source_markdown = """<m:abc>"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):\a<\a<\am:abc\a>\a>\a:]",
"[end-para:::True]",
]
expected_gfm = """<p><m:abc></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_618():
"""
Test case 618: (part 4) These are not autolinks:
"""
# Arrange
source_markdown = """<foo.bar.baz>"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):\a<\a<\afoo.bar.baz\a>\a>\a:]",
"[end-para:::True]",
]
expected_gfm = """<p><foo.bar.baz></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_619():
"""
Test case 619: (part 5) These are not autolinks:
"""
# Arrange
source_markdown = """http://example.com"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):http://example.com:]",
"[end-para:::True]",
]
expected_gfm = """<p>http://example.com</p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_620():
"""
Test case 620: (part 6) These are not autolinks:
"""
# Arrange
source_markdown = """foo@bar.example.com"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):foo@bar.example.com:]",
"[end-para:::True]",
]
expected_gfm = """<p>foo@bar.example.com</p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_620a():
"""
Test case 620a: variation (not enough in scheme)
"""
# Arrange
source_markdown = """<f:foo.bar>"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):\a<\a<\af:foo.bar\a>\a>\a:]",
"[end-para:::True]",
]
expected_gfm = """<p><f:foo.bar></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_620b():
"""
Test case 620b: variation (too much in scheme)
"""
# Arrange
source_markdown = """<f012345678901234567890123456789f0:foo.bar>"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):\a<\a<\af012345678901234567890123456789f0:foo.bar\a>\a>\a:]",
"[end-para:::True]",
]
expected_gfm = """<p><f012345678901234567890123456789f0:foo.bar></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_620c():
"""
Test case 620c: variation (illegal char in scheme)
"""
# Arrange
source_markdown = """<my_scheme:foo.bar>"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):\a<\a<\amy:]",
"[text(1,4):_:]",
"[text(1,5):scheme:foo.bar\a>\a>\a:]",
"[end-para:::True]",
]
expected_gfm = """<p><my_scheme:foo.bar></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_620d():
"""
Test case 620d: variation (no domain part)
"""
# Arrange
source_markdown = """<no_domain@>"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):\a<\a<\ano:]",
"[text(1,4):_:]",
"[text(1,5):domain@\a>\a>\a:]",
"[end-para:::True]",
]
expected_gfm = """<p><no_domain@></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
@pytest.mark.gfm
def test_autolinks_620e():
"""
Test case 620e: variation (no mailbox part)
"""
# Arrange
source_markdown = """<@no.mailbox>"""
expected_tokens = [
"[para(1,1):]",
"[text(1,1):\a<\a<\a@no.mailbox\a>\a>\a:]",
"[end-para:::True]",
]
expected_gfm = """<p><@no.mailbox></p>"""
# Act & Assert
act_and_assert(source_markdown, expected_gfm, expected_tokens)
| 26.795053 | 285 | 0.584795 | 2,015 | 15,166 | 4.254591 | 0.090819 | 0.094716 | 0.041992 | 0.054123 | 0.841012 | 0.796571 | 0.76356 | 0.753995 | 0.722034 | 0.691707 | 0 | 0.043832 | 0.21324 | 15,166 | 565 | 286 | 26.842478 | 0.674154 | 0.181261 | 0 | 0.5 | 0 | 0.081081 | 0.359762 | 0.147813 | 0 | 0 | 0 | 0 | 0.101351 | 1 | 0.097973 | false | 0 | 0.006757 | 0 | 0.10473 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
67703b0c78a4b2a46190ea9a931c516c68abc93b | 51 | py | Python | genetic-tuner/lib/__init__.py | windstrip/Genetic-Algorithm-PID-Controller-Tuner | 7e4c4febcc6e4d7c116d570a0d6a5f975a237007 | [
"Apache-2.0"
] | 39 | 2015-02-14T01:39:30.000Z | 2022-03-13T21:57:56.000Z | genetic-tuner/lib/__init__.py | windstrip/Genetic-Algorithm-PID-Controller-Tuner | 7e4c4febcc6e4d7c116d570a0d6a5f975a237007 | [
"Apache-2.0"
] | null | null | null | genetic-tuner/lib/__init__.py | windstrip/Genetic-Algorithm-PID-Controller-Tuner | 7e4c4febcc6e4d7c116d570a0d6a5f975a237007 | [
"Apache-2.0"
] | 18 | 2015-06-18T18:16:52.000Z | 2022-01-28T13:19:23.000Z | from chromosome import Chromosome
import listtools
| 17 | 33 | 0.882353 | 6 | 51 | 7.5 | 0.666667 | 0.711111 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.117647 | 51 | 2 | 34 | 25.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
67a7c374543bd4cba6ea99a4dbb012a847bccea4 | 71 | py | Python | sandbox/B.py | hybridx/WebScraper | f588a8285e696f7c0cef7b4f9bf1606bc4ce4d90 | [
"MIT"
] | 6 | 2018-05-25T10:16:00.000Z | 2022-03-12T07:17:37.000Z | sandbox/B.py | hybridx/WebScraper | f588a8285e696f7c0cef7b4f9bf1606bc4ce4d90 | [
"MIT"
] | null | null | null | sandbox/B.py | hybridx/WebScraper | f588a8285e696f7c0cef7b4f9bf1606bc4ce4d90 | [
"MIT"
] | 3 | 2018-09-28T10:17:25.000Z | 2019-03-20T22:50:07.000Z | import connections
print(connections.TestdbStudentsCollection.find())
| 17.75 | 50 | 0.859155 | 6 | 71 | 10.166667 | 0.833333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.056338 | 71 | 3 | 51 | 23.666667 | 0.910448 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.5 | 0 | 0.5 | 0.5 | 1 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 0 | 6 |
67bdf4923487d0ad7f2ce902e4c392052edecf84 | 983 | py | Python | tests/diffusion/conftest.py | Gabinou/NHPPy | 1068b1548d008771a58d5479d8333703c54abbed | [
"MIT"
] | 51 | 2019-02-01T19:43:37.000Z | 2022-03-16T09:07:03.000Z | tests/diffusion/conftest.py | noisyoscillator/stochastic | 168659c36fd16a33f69b1f21654a7661286dc9d0 | [
"MIT"
] | 2 | 2019-02-23T18:54:22.000Z | 2019-11-09T01:30:32.000Z | tests/diffusion/conftest.py | noisyoscillator/stochastic | 168659c36fd16a33f69b1f21654a7661286dc9d0 | [
"MIT"
] | 35 | 2019-02-08T02:00:31.000Z | 2022-03-01T23:17:00.000Z | """Diffusion process testing."""
# flake8: noqa
import pytest
# Floating point arithmetic comparison threshold
@pytest.fixture(params=[10**-10])
def threshold(request):
return request.param
# Common
@pytest.fixture(params=[1])
def t(request):
return request.param
@pytest.fixture(params=[16])
def n(request):
return request.param
@pytest.fixture(params=[True, False])
def zero(request):
return request.param
@pytest.fixture(params=[1])
def initial(request):
return request.param
# OrnsteinUhlenbeckProcess
@pytest.fixture(params=[1])
def speed(request):
return request.param
@pytest.fixture(params=[1])
def mean(request):
return request.param
@pytest.fixture(params=[1])
def vol(request):
return request.param
# CEVProcess
@pytest.fixture(params=[1])
def mu(request):
return request.param
@pytest.fixture(params=[1])
def sigma(request):
return request.param
@pytest.fixture(params=[1])
def gamma(request):
return request.param
| 18.54717 | 48 | 0.725331 | 127 | 983 | 5.614173 | 0.283465 | 0.200561 | 0.293128 | 0.385694 | 0.556802 | 0.460028 | 0.460028 | 0.336606 | 0.336606 | 0 | 0 | 0.017626 | 0.134283 | 983 | 52 | 49 | 18.903846 | 0.820212 | 0.132248 | 0 | 0.558824 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.323529 | false | 0 | 0.029412 | 0.323529 | 0.676471 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 6 |
db07f41b10b3217c88169ad2485db5cdc56ee923 | 42 | py | Python | gpviz/styles/__init__.py | thomaspinder/GPViz | 9196424e89c1a18d4c3f1837e4c37b3df4888b53 | [
"Apache-2.0"
] | 1 | 2022-03-26T05:35:05.000Z | 2022-03-26T05:35:05.000Z | gpviz/styles/__init__.py | thomaspinder/GPViz | 9196424e89c1a18d4c3f1837e4c37b3df4888b53 | [
"Apache-2.0"
] | 5 | 2021-05-10T12:07:34.000Z | 2021-06-16T09:50:31.000Z | gpviz/styles/__init__.py | thomaspinder/GPViz | 9196424e89c1a18d4c3f1837e4c37b3df4888b53 | [
"Apache-2.0"
] | 2 | 2021-06-17T11:48:05.000Z | 2021-06-22T06:08:49.000Z | from .colours import get_colours, get_cmap | 42 | 42 | 0.857143 | 7 | 42 | 4.857143 | 0.714286 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.095238 | 42 | 1 | 42 | 42 | 0.894737 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
e1f5ba6600590f89470a3015987307956f92be7d | 26 | py | Python | osu/utils/__init__.py | byWambo/osu-API-Wrapper | abd564f101cb43e34eb382f7a971faba413780d5 | [
"MIT"
] | 3 | 2019-01-14T22:03:14.000Z | 2020-08-18T17:18:53.000Z | osu/utils/__init__.py | byWambo/osu-API-Wrapper | abd564f101cb43e34eb382f7a971faba413780d5 | [
"MIT"
] | 2 | 2019-01-29T23:23:10.000Z | 2019-03-31T09:29:03.000Z | osu/utils/__init__.py | byWambo/osu-API-Wrapper | abd564f101cb43e34eb382f7a971faba413780d5 | [
"MIT"
] | 2 | 2019-02-07T22:12:39.000Z | 2019-03-27T22:35:37.000Z | from . import modes, mods
| 13 | 25 | 0.730769 | 4 | 26 | 4.75 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.192308 | 26 | 1 | 26 | 26 | 0.904762 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
c026ea4dfb5afd614266c2ec910c3252489160cf | 36,190 | py | Python | sat.py | rjhd2/sotc_graphics | e9d2b259fb09d6a7bc9262d33de25b1a113fb9b1 | [
"BSD-3-Clause"
] | null | null | null | sat.py | rjhd2/sotc_graphics | e9d2b259fb09d6a7bc9262d33de25b1a113fb9b1 | [
"BSD-3-Clause"
] | null | null | null | sat.py | rjhd2/sotc_graphics | e9d2b259fb09d6a7bc9262d33de25b1a113fb9b1 | [
"BSD-3-Clause"
] | 1 | 2020-10-01T05:15:03.000Z | 2020-10-01T05:15:03.000Z | #!/usr/bin/env python
#************************************************************************
#
# Plot figures and output numbers for surface temperature (SAT) section.
# For BAMS SotC 2016
#
#************************************************************************
# SVN Info
# $Rev:: 31 $: Revision of last commit
# $Author:: rdunn $: Author of last commit
# $Date:: 2021-09-06 09:52:46 +0100 (Mon, 06 Sep #$: Date of last commit
#************************************************************************
# START
#************************************************************************
import os
import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import iris
import utils # RJHD utilities
import settings
DATALOC = "{}/{}/data/SAT/".format(settings.ROOTLOC, settings.YEAR)
IS_timeseries_root = "global-tempDatasets-{}".format(settings.YEAR)
LEGEND_LOC = 'upper left'
LW = 3
BBOX = (0.05, 0.9)
YLIM = [-1.4, 1.4]
# Colin to provide 1981-2010 HadCRUT4 timeseries with uncertainty bounds
# Map files from HadOBS (use N+S averaged),
# Ahira for MLOST
# /project/earthobs/GLOBAL_SURFACE_TEMPERATURE/GISTEMP/GISS_1200_blend_1x1.pp fof GISS
#************************************************************************
def read_global_t(filename):
# Ahira's global temperature files (observed)
indata = np.genfromtxt(filename, delimiter=',', dtype=(float), skip_header=1)
indata = np.ma.masked_where(indata == -99.9, indata)
hadley = utils.Timeseries("Hadley", indata[:, 0], indata[:, 1]) # for completeness in 2016
noaa = utils.Timeseries("NOAA/NCEI", indata[:, 0], indata[:, 2])
nasa = utils.Timeseries("NASA/GISS", indata[:, 0], indata[:, 3])
# jma = utils.Timeseries("JMA", indata[:, 0], indata[:, 4])
jma = utils.Timeseries("JMA", [0], [0])
try:
berkeley = utils.Timeseries("Berkeley", indata[:, 0], indata[:, 5])
return hadley, noaa, nasa, jma, berkeley
except IndexError:
return hadley, noaa, nasa, jma # read_global_t
#************************************************************************
def read_nasa_giss(filename):
"""
Read the NASA GISS data and returns a cube of the year.
:param str filename: filename to read
:returns: cube of 1 year of temperature anomalies
"""
all_giss = np.genfromtxt(filename, dtype=(float), skip_header=2)
# 2 degree, but just in case
# read from i, j columns to get the size of the array
longitudes = np.zeros(np.max(all_giss[:, 0]).astype(int))
latitudes = np.zeros(np.max(all_giss[:, 1]).astype(int))
# set up a masked data array
data = np.ma.zeros((np.max(all_giss[:, 1]).astype(int), np.max(all_giss[:, 0]).astype(int)))
data.mask = np.ones(data.shape)
# spin through each line
for line in all_giss:
# use the indexing provided
j = line[0].astype(int)
i = line[1].astype(int)
data[i-1, j-1] = line[4]
# and read in the coordinates too
if i == 1:
longitudes[j-1] = line[2]
if j == 1:
latitudes[i-1] = line[3]
# mask the missing data
data = np.ma.masked_where(data > 1000, data)
cube = utils.make_iris_cube_2d(data, latitudes, longitudes, "temperature", "C")
return cube # read_nasa_giss
#************************************************************************
def read_noaa_mlost(filename, year):
"""
Read the NOAA MLOST data and returns a cube of the year.
:param str filename: filename to read
:param int year: year to extract
:returns: cube of 1 year of temperature anomalies
"""
all_mlost = np.genfromtxt(filename, dtype=(float))
DELTA = 5
# read from i, j columns to get the size of the array
longitudes = np.arange(-180 + (DELTA/2.), 180 + (DELTA/2.), DELTA)
latitudes = np.arange(-90 + (DELTA/2.), 90 + (DELTA/2.), DELTA)
# set up a masked data array
data = np.ma.zeros((len(latitudes), len(longitudes)))
data.mask = np.ones(data.shape)
# spin through each line
for line in all_mlost:
if line[0] == year:
lat_loc, = np.where(latitudes == line[1])
lon_loc, = np.where(longitudes == line[2])
data[lat_loc, lon_loc] = line[3]
data.mask[lat_loc, lon_loc] = False
cube = utils.make_iris_cube_2d(data, latitudes, longitudes, "temperature", "C")
return cube # read_noaa_mlost
#************************************************************************
def read_hadcrut_crutem(filename, adjust_clim=False):
"""
Read data from HadCRUT, HadSST and CRUTEM
:param str filename: infile to read
:param bool adjust_clim: adjust climatology if required
:returns: Timeseries object with upper and lower bounds.
"""
#******************************************
def apply_clim(data, upper, lower, start):
'''Calculate and apply climatology'''
offset = np.mean(data[start:start+30])
return data-offset, upper-offset, lower-offset # apply_clim
#******************************************
# Colin's global temperature files (observed)
indata = np.genfromtxt(filename, dtype=(float), delimiter=",", skip_header=3)
indata = np.ma.masked_where(indata == -99.9, indata)
years = indata[:, 0]
mean = indata[:, 1]
# order can be different for different datasets.
if "CRUTEM" in filename or "crutem" in filename:
lower = indata[:, -2]
upper = indata[:, -1]
name = "CRUTEM"
elif "HadSST" in filename or "hadsst" in filename:
lower = indata[:, -2]
upper = indata[:, -1]
name = "HadSST4"
elif "hadcrut4" in filename:
lower = indata[:, -2]
upper = indata[:, -1]
name = "HadCRUT4"
if adjust_clim:
# these curves are 1961-1990
# need to adjust to 1981-2010
locs, = np.where(years == 1981)
mean, upper, lower = apply_clim(mean, upper, lower, locs) # does 30 years from start point
if years[-1] >= dt.datetime.now().year:
while years[-1] != dt.datetime.now().year - 1:
years = years[:-1]
mean = mean[:-1]
upper = upper[:-1]
lower = lower[:-1]
hadcrut = utils.Timeseries(name, years, mean)
hadcrut.upper = upper
hadcrut.lower = lower
return hadcrut # read_hadcrut_crutem
#************************************************************************
def read_hadcrut5_crutem5(filename, adjust_clim=False):
"""
Read data from HadCRUT5 and CRUTEM5
:param str filename: infile to read
:returns: Timeseries object with upper and lower bounds.
"""
# Colin's global temperature files (observed)
indata = np.genfromtxt(filename, dtype=(float), delimiter=",", skip_header=1)
indata = np.ma.masked_where(indata == -99.9, indata)
years = indata[:, 0]
mean = indata[:, 1]
# order can be different for different datasets.
if "CRUTEM" in filename or "crutem" in filename:
name = "CRUTEM5"
elif "HadCRUT" in filename:
name = "HadCRUT5"
lower = indata[:, 2]
upper = indata[:, 3]
# remove any years after the one for the report
if years[-1] > int(settings.YEAR):
while years[-1] != dt.datetime.now().year - 1:
years = years[:-1]
mean = mean[:-1]
upper = upper[:-1]
lower = lower[:-1]
hadcrut = utils.Timeseries(name, years, mean)
hadcrut.upper = upper
hadcrut.lower = lower
return hadcrut # read_hadcrut5_crutem5
#************************************************************************
def read_hadsst4(filename, adjust_clim=False):
"""
Read data from HadSST4
:param str filename: infile to read
:returns: Timeseries object with upper and lower bounds.
"""
# Colin's global temperature files (observed)
indata = np.genfromtxt(filename, dtype=(float), delimiter=",", skip_header=1)
indata = np.ma.masked_where(indata == -99.9, indata)
name = "HadSST4"
years = indata[:, 0]
mean = indata[:, 1]
# scale from 1sigma to 95% range
lower = indata[:, 1]-(1.96*indata[:, 2])
upper = indata[:, 1]+(1.96*indata[:, 2])
# remove any years after the one for the report
if years[-1] > int(settings.YEAR):
while years[-1] != dt.datetime.now().year - 1:
years = years[:-1]
mean = mean[:-1]
upper = upper[:-1]
lower = lower[:-1]
hadsst = utils.Timeseries(name, years, mean)
hadsst.upper = upper
hadsst.lower = lower
return hadsst # read_hadsst4
#************************************************************************
def run_all_plots():
if False:
# old multipanel timeseries
COLOURS = settings.COLOURS["temperature"]
fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, figsize=(8, 19), sharex=True)
# ERA5
era5_globe, era5_ocean, era5_land, era5tropics = utils.era5_ts_read(settings.REANALYSISLOC, "sat", annual=True)
land_era5_clim, land_era5_anoms = utils.calculate_climatology_and_anomalies_1d(era5_land, 1981, 2010)
ocean_era5_clim, ocean_era5_anoms = utils.calculate_climatology_and_anomalies_1d(era5_ocean, 1981, 2010)
global_era5_clim, global_era5_anoms = utils.calculate_climatology_and_anomalies_1d(era5_globe, 1981, 2010)
#*******************
# in situ L+O (JMA field is empty)
noaa, nasa, jma = read_global_t(DATALOC + "{}_LO.csv".format(IS_timeseries_root))
# hadcrut = read_hadcrut_crutem(DATALOC+"hadcrut4.1981-2010.csv")
p0 = ax1.plot(noaa.times, noaa.data, c=COLOURS[noaa.name], ls='-', label=noaa.name, lw=LW)
p1 = ax1.plot(nasa.times, nasa.data, c=COLOURS[nasa.name], ls='-', label=nasa.name, lw=LW)
# p2 = ax1.plot(jma.times, jma.data, c=COLOURS[jma.name], ls='-', label=jma.name, lw=LW)
# p3 = ax1.plot(hadcrut.times, hadcrut.data, c=COLOURS[hadcrut.name], ls='-', label=hadcrut.name, lw=LW)
# ax1.fill_between(hadcrut.times, hadcrut.lower, hadcrut.upper, \
# where=hadcrut.upper > hadcrut.lower, color='0.5', alpha=0.7)
p4 = ax1.fill(np.NaN, np.NaN, '0.5', alpha=0.7)
ax1.axhline(0, c='0.5', ls='--')
# ax1.legend([p0[0], p1[0], (p3[0], p4[0])], [noaa.name, nasa.name, hadcrut.name], \
# loc=LEGEND_LOC, ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, \
# labelspacing=0.1, columnspacing=0.5, bbox_to_anchor=BBOX)
ax1.text(0.02, 0.9, "(a) In Situ Land and Ocean", transform=ax1.transAxes, fontsize=settings.FONTSIZE)
utils.thicken_panel_border(ax1)
# ax1.yaxis.set_ticks_position('left')
#*******************
# reanalysis L+O
merra = utils.read_merra(os.path.join(settings.REANALYSISLOC, "MERRA2", "MERRA-2_SfcAnom{}.dat".format(settings.YEAR)), "temperature", "LO")
jra_actuals, jra_anoms = utils.read_jra55(os.path.join(settings.REANALYSISLOC, "JRA-55", "JRA-55_tmp2m_global_ts.txt"), "temperature")
twenty_cr_actuals = utils.read_20cr(os.path.join(settings.REANALYSISLOC, "20CR", "global.2mt.skt.txt"), "temperature")
dummy, twenty_cr_anoms = utils.calculate_climatology_and_anomalies_1d(twenty_cr_actuals, 1981, 2010)
twenty_cr_anoms.zorder=-1
# 2018 no MERRA
utils.plot_ts_panel(ax2, [jra_anoms, global_era5_anoms, twenty_cr_anoms], "-", "temperature", loc=LEGEND_LOC, bbox=BBOX)
ax2.text(0.02, 0.9, "(b) Reanalysis Land and Ocean", transform=ax2.transAxes, fontsize=settings.FONTSIZE)
#*******************
# in situ L
noaa, nasa, jma = read_global_t(DATALOC +"{}_L.csv".format(IS_timeseries_root))
# crutem = read_hadcrut_crutem(DATALOC + "crutem4_new_logo.1981-2010.csv")
p0 = ax3.plot(noaa.times, noaa.data, ls='-', c=COLOURS[noaa.name], label=noaa.name, lw=LW)
p1 = ax3.plot(nasa.times, nasa.data, ls='-', c=COLOURS[nasa.name], label=nasa.name, lw=LW)
# p2 = ax3.plot(jma.times, jma.data, ls='-', c=COLOURS[jma.name], label=jma.name, lw=LW)
# p3 = ax3.plot(berkeley.times, berkeley.data, ls = '-', c = COLOURS[berkeley.name], label = berkeley.name, lw = LW)
# p4 = ax3.plot(crutem.times, crutem.data, ls='-', c=COLOURS[crutem.name], label=crutem.name, lw=LW)
# ax3.fill_between(crutem.times, crutem.lower, crutem.upper, \
# where=crutem.upper > crutem.lower, color='0.5', alpha=0.7)
p5 = ax3.fill(np.NaN, np.NaN, '0.5', alpha=0.7)
ax3.axhline(0, c='0.5', ls='--')
# ax3.legend([p0[0], p1[0], (p4[0], p5[0])], [noaa.name, nasa.name, crutem.name], \
# loc=LEGEND_LOC, ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, \
# labelspacing=0.1, columnspacing=0.5, bbox_to_anchor=BBOX)
ax3.text(0.02, 0.9, "(c) In Situ Land only", transform=ax3.transAxes, fontsize=settings.FONTSIZE)
utils.thicken_panel_border(ax3)
# ax3.yaxis.set_ticks_position('left')
#*******************
# reanalysis L
merra = utils.read_merra(os.path.join(settings.REANALYSISLOC, "MERRA2", "MERRA-2_SfcAnom{}.dat".format(settings.YEAR)), "temperature", "L")
jra_actual, jra_anoms = utils.read_jra55(os.path.join(settings.REANALYSISLOC, "JRA-55", "JRA-55_tmp2m_globalland_ts.txt"), "temperature")
twenty_cr_actuals = utils.read_20cr(os.path.join(settings.REANALYSISLOC, "20CR", "air2mland.txt"), "temperature")
dummy, twenty_cr_anoms = utils.calculate_climatology_and_anomalies_1d(twenty_cr_actuals, 1981, 2010)
twenty_cr_anoms.zorder=-1
# 2018 - No MERRA
utils.plot_ts_panel(ax4, [jra_anoms, land_era5_anoms, twenty_cr_anoms], "-", "temperature", loc=LEGEND_LOC, bbox=BBOX)
ax4.text(0.02, 0.9, "(d) Reanalysis Land only", transform=ax4.transAxes, fontsize=settings.FONTSIZE)
#*******************
# in situ O
noaa, nasa, jma = read_global_t(DATALOC + "{}_O.csv".format(IS_timeseries_root))
# hadsst = read_hadcrut_crutem(DATALOC+"hadsst3_new_logo.1981-2010.csv")
p0 = ax5.plot(noaa.times, noaa.data, ls='-', c=COLOURS[noaa.name], label=noaa.name, lw=LW)
p1 = ax5.plot(nasa.times, nasa.data, ls='-', c=COLOURS[nasa.name], label=nasa.name, lw=LW)
# p2 = ax5.plot(jma.times, jma.data, ls='-', c=COLOURS[jma.name], label=jma.name, lw=LW)
# p3 = ax5.plot(hadsst.times, hadsst.data, ls='-', c=COLOURS[hadsst.name], label=hadsst.name, lw=LW)
# ax5.fill_between(hadsst.times, hadsst.lower, hadsst.upper, \
# where=hadsst.upper > hadsst.lower, color='0.5', alpha=0.7)
p4 = ax5.fill(np.NaN, np.NaN, '0.5', alpha=0.7)
ax5.axhline(0, c='0.5', ls='--')
# ax5.legend([p0[0], p1[0], (p3[0], p4[0])], [noaa.name, nasa.name, hadsst.name], \
# loc=LEGEND_LOC, ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, \
# labelspacing=0.1, columnspacing=0.5, bbox_to_anchor=BBOX)
ax5.text(0.02, 0.9, "(e) In Situ Ocean only", transform=ax5.transAxes, fontsize=settings.FONTSIZE)
utils.thicken_panel_border(ax5)
# ax5.yaxis.set_ticks_position('left')
#*******************
# reanalysis O
merra = utils.read_merra(os.path.join(settings.REANALYSISLOC, "MERRA2", "MERRA-2_SfcAnom{}.dat".format(settings.YEAR)), "temperature", "O")
jra_actual, jra_anoms = utils.read_jra55(os.path.join(settings.REANALYSISLOC, "JRA-55", "JRA-55_tmp2m_globalocean_ts.txt"), "temperature")
twenty_cr_actuals = utils.read_20cr(os.path.join(settings.REANALYSISLOC, "20CR", "airsktocean.txt"), "temperature")
dummy, twenty_cr_anoms = utils.calculate_climatology_and_anomalies_1d(twenty_cr_actuals, 1981, 2010)
twenty_cr_anoms.zorder=-1
# 2018 no MERRA
utils.plot_ts_panel(ax6, [jra_anoms, ocean_era5_anoms, twenty_cr_anoms], "-", "temperature", loc=LEGEND_LOC, bbox=BBOX)
ax6.text(0.02, 0.9, "(f) Reanalysis Ocean only", transform=ax6.transAxes, fontsize=settings.FONTSIZE)
#*******************
# prettify
fig.text(0.03, 0.5, "Anomalies ("+r'$^{\circ}$'+"C)", va='center', rotation='vertical', fontsize=settings.FONTSIZE)
plt.xlim([1900, int(settings.YEAR)+4])
minorLocator = MultipleLocator(5)
for ax in [ax1, ax2, ax3, ax4, ax5, ax6]:
ax.set_ylim(YLIM)
for tick in ax.yaxis.get_major_ticks():
tick.label.set_fontsize(settings.FONTSIZE)
ax.xaxis.set_minor_locator(minorLocator)
for tick in ax6.xaxis.get_major_ticks():
tick.label.set_fontsize(settings.FONTSIZE)
fig.subplots_adjust(right=0.96, top=0.995, bottom=0.02, hspace=0.001)
plt.savefig(settings.IMAGELOC+"SAT_ts{}".format(settings.OUTFMT))
plt.close()
#************************************************************************
if True:
# new multipanel timeseries
COLOURS = settings.COLOURS["temperature"]
fig = plt.figure(figsize=(8, 19))
# manually set up the 12 axes
w1 = 0.53
w2 = 0.86-w1
h = 0.16
c = 0.12+w1
ax1 = plt.axes([c-w1, 0.99-h, w1, h])
ax2 = plt.axes([c, 0.99-h, w2, h])
ax3 = plt.axes([c-w1, 0.99-(2*h), w1, h], sharex=ax1)
ax4 = plt.axes([c, 0.99-(2*h), w2, h], sharex=ax2)
ax5 = plt.axes([c-w1, 0.99-(3*h), w1, h], sharex=ax1)
ax6 = plt.axes([c, 0.99-(3*h), w2, h], sharex=ax2)
ax7 = plt.axes([c-w1, 0.99-(4*h), w1, h], sharex=ax1)
ax8 = plt.axes([c, 0.99-(4*h), w2, h], sharex=ax2)
ax9 = plt.axes([c-w1, 0.99-(5*h), w1, h], sharex=ax1)
ax10= plt.axes([c, 0.99-(5*h), w2, h], sharex=ax2)
ax11 = plt.axes([c-w1, 0.99-(6*h), w1, h], sharex=ax1)
ax12= plt.axes([c, 0.99-(6*h), w2, h], sharex=ax2)
# ERA5
era5_globe, era5_ocean, era5_land, era5tropics = utils.era5_ts_read(settings.REANALYSISLOC, "sat", annual=True)
land_era5_clim, land_era5_anoms = utils.calculate_climatology_and_anomalies_1d(era5_land, 1981, 2010)
ocean_era5_clim, ocean_era5_anoms = utils.calculate_climatology_and_anomalies_1d(era5_ocean, 1981, 2010)
global_era5_clim, global_era5_anoms = utils.calculate_climatology_and_anomalies_1d(era5_globe, 1981, 2010)
#*******************
# in situ L+O
hadcrut, noaa, nasa, jma = read_global_t(DATALOC + "{}_LO.csv".format(IS_timeseries_root))
hadcrut = read_hadcrut5_crutem5(DATALOC+"HadCRUT.5.0.1.0.summary_series.global.annual.1981-2010.csv")
for ax in [ax1, ax2]:
p0 = ax.plot(noaa.times, noaa.data, c=COLOURS[noaa.name], ls='-', label=noaa.name, lw=LW)
p1 = ax.plot(nasa.times, nasa.data, c=COLOURS[nasa.name], ls='-', label=nasa.name, lw=LW)
p2 = ax.plot(jma.times, jma.data, c=COLOURS[jma.name], ls='-', label=jma.name, lw=LW)
p3 = ax.plot(hadcrut.times, hadcrut.data, c=COLOURS[hadcrut.name], ls='-', label=hadcrut.name, lw=LW)
ax.fill_between(hadcrut.times, hadcrut.lower, hadcrut.upper, \
where=hadcrut.upper > hadcrut.lower, color='0.5')
p4 = ax.fill(np.NaN, np.NaN, '0.5')
ax.axhline(0, c='0.5', ls='--')
utils.thicken_panel_border(ax)
ax1.legend([p0[0], p1[0], (p4[0], p3[0])], [noaa.name, nasa.name, hadcrut.name], \
loc=LEGEND_LOC, ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, \
labelspacing=0.1, columnspacing=0.5, bbox_to_anchor=BBOX)
ax1.text(0.02, 0.9, "(a) In Situ Land and Ocean", transform=ax1.transAxes, fontsize=settings.FONTSIZE)
#*******************
# reanalysis L+O
merra = utils.read_merra(os.path.join(settings.REANALYSISLOC, "MERRA2", "MERRA-2_SfcAnom{}.dat".format(settings.YEAR)), "temperature", "LO")
jra_actuals, jra_anoms = utils.read_jra55(os.path.join(settings.REANALYSISLOC, "JRA-55", "JRA-55_tmp2m_global_ts.txt"), "temperature")
twenty_cr_actuals = utils.read_20cr(os.path.join(settings.REANALYSISLOC, "20CR", "global.2mt.skt.txt"), "temperature")
dummy, twenty_cr_anoms = utils.calculate_climatology_and_anomalies_1d(twenty_cr_actuals, 1981, 2010)
twenty_cr_anoms.zorder=-1
# 2019 no MERRA
# utils.plot_ts_panel(ax3, [jra_anoms, global_era5_anoms, twenty_cr_anoms], "-", "temperature", loc=LEGEND_LOC, bbox=BBOX)
# utils.plot_ts_panel(ax4, [jra_anoms, global_era5_anoms, twenty_cr_anoms], "-", "temperature", loc="")
# 2020 no MERRA, 20CR
utils.plot_ts_panel(ax3, [jra_anoms, global_era5_anoms], "-", "temperature", loc=LEGEND_LOC, bbox=BBOX)
utils.plot_ts_panel(ax4, [jra_anoms, global_era5_anoms], "-", "temperature", loc="")
ax3.text(0.02, 0.9, "(b) Reanalysis Land and Ocean", transform=ax3.transAxes, fontsize=settings.FONTSIZE)
#*******************
# in situ L
crutem, noaa, nasa, jma = read_global_t(DATALOC +"{}_L.csv".format(IS_timeseries_root))
crutem = read_hadcrut5_crutem5(DATALOC + "CRUTEM.5.0.1.0.summary_series.global.annual.1981-2010.csv")
for ax in [ax5, ax6]:
p0 = ax.plot(noaa.times, noaa.data, ls='-', c=COLOURS[noaa.name], label=noaa.name, lw=LW)
p1 = ax.plot(nasa.times, nasa.data, ls='-', c=COLOURS[nasa.name], label=nasa.name, lw=LW)
p2 = ax.plot(jma.times, jma.data, ls='-', c=COLOURS[jma.name], label=jma.name, lw=LW)
# p3 = ax.plot(berkeley.times, berkeley.data, ls = '-', c = COLOURS[berkeley.name], label = berkeley.name, lw = LW)
p4 = ax.plot(crutem.times, crutem.data, ls='-', c=COLOURS[crutem.name], label=crutem.name, lw=LW)
ax.fill_between(crutem.times, crutem.lower, crutem.upper, \
where=crutem.upper > crutem.lower, color='0.5')
p5 = ax.fill(np.NaN, np.NaN, '0.5')
ax.axhline(0, c='0.5', ls='--')
utils.thicken_panel_border(ax)
ax5.legend([p0[0], p1[0], (p5[0], p4[0])], [noaa.name, nasa.name, crutem.name], \
loc=LEGEND_LOC, ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, \
labelspacing=0.1, columnspacing=0.5, bbox_to_anchor=BBOX)
ax5.text(0.02, 0.9, "(c) In Situ Land only", transform=ax5.transAxes, fontsize=settings.FONTSIZE)
#*******************
# reanalysis L
merra = utils.read_merra(os.path.join(settings.REANALYSISLOC, "MERRA2", "MERRA-2_SfcAnom{}.dat".format(settings.YEAR)), "temperature", "L")
jra_actual, jra_anoms = utils.read_jra55(os.path.join(settings.REANALYSISLOC, "JRA-55", "JRA-55_tmp2m_globalland_ts.txt"), "temperature")
twenty_cr_actuals = utils.read_20cr(os.path.join(settings.REANALYSISLOC, "20CR", "air2mland.txt"), "temperature")
dummy, twenty_cr_anoms = utils.calculate_climatology_and_anomalies_1d(twenty_cr_actuals, 1981, 2010)
twenty_cr_anoms.zorder=-1
# 2019 - No MERRA
# utils.plot_ts_panel(ax7, [jra_anoms, land_era5_anoms, twenty_cr_anoms], "-", "temperature", loc=LEGEND_LOC, bbox=BBOX)
# utils.plot_ts_panel(ax8, [jra_anoms, land_era5_anoms, twenty_cr_anoms], "-", "temperature", loc="")
# 2020 - No MERRA, no 20CR
utils.plot_ts_panel(ax7, [jra_anoms, land_era5_anoms], "-", "temperature", loc=LEGEND_LOC, bbox=BBOX)
utils.plot_ts_panel(ax8, [jra_anoms, land_era5_anoms], "-", "temperature", loc="")
ax7.text(0.02, 0.9, "(d) Reanalysis Land only", transform=ax7.transAxes, fontsize=settings.FONTSIZE)
#*******************
# in situ O
hadsst, noaa, nasa, jma = read_global_t(DATALOC + "{}_O.csv".format(IS_timeseries_root))
hadsst = read_hadsst4(DATALOC+"HadSST.4.0.1.0_annual_GLOBE_1981_2010.csv")
for ax in [ax9, ax10]:
p0 = ax.plot(noaa.times, noaa.data, ls='-', c=COLOURS[noaa.name], label=noaa.name, lw=LW)
p1 = ax.plot(nasa.times, nasa.data, ls='-', c=COLOURS[nasa.name], label=nasa.name, lw=LW)
# p2 = ax9plot(jma.times, jma.data, ls='-', c=COLOURS[jma.name], label=jma.name, lw=LW)
p3 = ax.plot(hadsst.times, hadsst.data, ls='-', c=COLOURS[hadsst.name], label=hadsst.name, lw=LW)
ax.fill_between(hadsst.times, hadsst.lower, hadsst.upper, \
where=hadsst.upper > hadsst.lower, color='0.5')
p4 = ax.fill(np.NaN, np.NaN, '0.5')
ax.axhline(0, c='0.5', ls='--')
utils.thicken_panel_border(ax)
ax9.legend([p0[0], p1[0], (p4[0], p3[0])], [noaa.name, nasa.name, hadsst.name], \
loc=LEGEND_LOC, ncol=2, frameon=False, prop={'size':settings.LEGEND_FONTSIZE}, \
labelspacing=0.1, columnspacing=0.5, bbox_to_anchor=BBOX)
ax9.text(0.02, 0.9, "(e) In Situ Ocean only", transform=ax9.transAxes, fontsize=settings.FONTSIZE)
#*******************
# reanalysis O
merra = utils.read_merra(os.path.join(settings.REANALYSISLOC, "MERRA2", "MERRA-2_SfcAnom{}.dat".format(settings.YEAR)), "temperature", "O")
jra_actual, jra_anoms = utils.read_jra55(os.path.join(settings.REANALYSISLOC, "JRA-55", "JRA-55_tmp2m_globalocean_ts.txt"), "temperature")
twenty_cr_actuals = utils.read_20cr(os.path.join(settings.REANALYSISLOC, "20CR", "airsktocean.txt"), "temperature")
dummy, twenty_cr_anoms = utils.calculate_climatology_and_anomalies_1d(twenty_cr_actuals, 1981, 2010)
twenty_cr_anoms.zorder=-1
# 2019 no MERRA
# utils.plot_ts_panel(ax11, [jra_anoms, ocean_era5_anoms, twenty_cr_anoms], "-", "temperature", loc=LEGEND_LOC, bbox=BBOX)
# utils.plot_ts_panel(ax12, [jra_anoms, ocean_era5_anoms, twenty_cr_anoms], "-", "temperature", loc="")
# 2019 no MERRA, no 20CR
utils.plot_ts_panel(ax11, [jra_anoms, ocean_era5_anoms], "-", "temperature", loc=LEGEND_LOC, bbox=BBOX)
utils.plot_ts_panel(ax12, [jra_anoms, ocean_era5_anoms], "-", "temperature", loc="")
ax11.text(0.02, 0.9, "(f) Reanalysis Ocean only", transform=ax11.transAxes, fontsize=settings.FONTSIZE)
#*******************
# prettify
fig.text(0.03, 0.5, "Anomalies ("+r'$^{\circ}$'+"C)", va='center', rotation='vertical', fontsize=settings.FONTSIZE)
ax1.set_xlim([1900, 2000])
ax2.set_xlim([2000, int(settings.YEAR)+2])
minorLocator = MultipleLocator(5)
majorLocator = MultipleLocator(50)
for ax in [ax1, ax3, ax5, ax7, ax9, ax11]:
ax.xaxis.set_major_locator(majorLocator)
for tick in ax.yaxis.get_major_ticks():
tick.label.set_fontsize(settings.FONTSIZE)
ax.xaxis.set_minor_locator(minorLocator)
ax.yaxis.set_ticks_position('left')
ax.set_ylim(YLIM)
for ax in fig.axes:
for tick in ax.xaxis.get_major_ticks():
tick.label.set_fontsize(0)
for ax in [ax11, ax12]:
for tick in ax.xaxis.get_major_ticks():
tick.label.set_fontsize(settings.FONTSIZE)
minorLocator = MultipleLocator(1)
majorLocator = MultipleLocator(10)
for ax in [ax2, ax4, ax6, ax8, ax10, ax12]:
ax.xaxis.set_major_locator(majorLocator)
ax.set_ylim(YLIM)
# ax.set_yticks([])
ax.yaxis.set_ticks_position('right')
ax.yaxis.set_ticklabels([])
ax.xaxis.set_minor_locator(minorLocator)
fig.subplots_adjust(right=0.96, top=0.995, bottom=0.02, hspace=0.001)
plt.savefig(settings.IMAGELOC+"SAT_ts{}".format(settings.OUTFMT))
plt.close()
#************************************************************************
# ERA5 Anomaly figure
if True:
# Read in ERA anomalies
cube_list = iris.load(os.path.join(settings.REANALYSISLOC, "ERA5", "SFCTEMP", "era5_2t_{}_gridded_ano.nc".format(settings.YEAR)))
for cube in cube_list:
if cube.var_name == "T2M":
break
cube.coord('latitude').guess_bounds()
cube.coord('longitude').guess_bounds()
bounds = [-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100]
utils.plot_smooth_map_iris(settings.IMAGELOC + "SAT_{}_anoms_era5".format(settings.YEAR), cube, settings.COLOURMAP_DICT["temperature"], bounds, "Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", title="ERA5")
#************************************************************************
# MERRA2 Anomaly figure
if True:
cube_list = iris.load(os.path.join(settings.REANALYSISLOC, "MERRA2", "MERRA-2_SfcAnom_{}.nc".format(settings.YEAR)))
for cube in cube_list:
if cube.var_name == "t2ma":
break
cube.coord('latitude').guess_bounds()
cube.coord('longitude').guess_bounds()
bounds = [-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100]
utils.plot_smooth_map_iris(settings.IMAGELOC + "SAT_{}_anoms_merra".format(settings.YEAR), cube[0], \
settings.COLOURMAP_DICT["temperature"], bounds, \
"Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", title="MERRA-2")
#************************************************************************
# HadCRUT5 Anomaly figure
if True:
# cube_list = iris.load(DATALOC + "HadCRUT.4.6.0.0.median.nc")
cube_list = iris.load(DATALOC + "HadCRUT.5.0.1.0.analysis.anomalies.ensemble_mean.nc")
for cube in cube_list:
if cube.var_name == "tas_mean":
break
# restrict to 1851 to last full year
date_constraint = utils.periodConstraint(cube, dt.datetime(1850, 1, 1), dt.datetime(int(settings.YEAR)+1, 1, 1))
cube = cube.extract(date_constraint)
# convert to 1981-2010 climatology.
clim_constraint = utils.periodConstraint(cube, dt.datetime(1981, 1, 1), dt.datetime(2011, 1, 1))
clim_cube = cube.extract(clim_constraint)
clim_data = clim_cube.data.reshape(-1, 12, clim_cube.data.shape[-2], clim_cube.data.shape[-1])
# more than 15 years present
climatology = np.ma.mean(clim_data, axis=0)
nyears = np.ma.count(clim_data, axis=0)
climatology = np.ma.masked_where(nyears <= 15, climatology) # Kate keeps GT 15.
# extract final year
final_year_constraint = utils.periodConstraint(cube, dt.datetime(int(settings.YEAR), 1, 1), dt.datetime(int(settings.YEAR)+1, 1, 1))
final_year_cube = cube.extract(final_year_constraint)
final_year_cube.data = final_year_cube.data - climatology
# more than 6 months present
annual_cube = final_year_cube.collapsed(['time'], iris.analysis.MEAN)
nmonths = np.ma.count(final_year_cube.data, axis=0)
annual_cube.data = np.ma.masked_where(nmonths <= 6, annual_cube.data)
bounds = [-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100]
utils.plot_smooth_map_iris(settings.IMAGELOC + "SAT_{}_anoms_hadcrut5".format(settings.YEAR), annual_cube, \
settings.COLOURMAP_DICT["temperature"], bounds, \
"Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", title="HadCRUT 5.0")
#************************************************************************
# NOAA data Anomaly figure - incl plate 2.1
if True:
cube = read_noaa_mlost(DATALOC + "mlost-box.ytd.12.1981-2010bp.txt", int(settings.YEAR))
bounds = [-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100]
utils.plot_smooth_map_iris(settings.IMAGELOC + "p2.1_SAT_{}_anoms_noaa".format(settings.YEAR), cube, \
settings.COLOURMAP_DICT["temperature"], bounds, \
"Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", \
figtext="(a) Surface Temperature", \
save_netcdf_filename="{}MLOST_for_NOAA_{}.nc".format(DATALOC, dt.datetime.strftime(dt.datetime.now(), "%d-%b-%Y")))
utils.plot_smooth_map_iris(settings.IMAGELOC + "SAT_{}_anoms_noaa".format(settings.YEAR), cube, \
settings.COLOURMAP_DICT["temperature"], bounds, \
"Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", title="NOAAGlobalTemp")
#************************************************************************
# JRA55 data Anomaly figure
if True:
cube_list = iris.load(os.path.join(settings.REANALYSISLOC, "ERA5", "SFCTEMP", "jra55_2t_{}_gridded_ano.nc".format(settings.YEAR, settings.YEAR)))
for cube in cube_list:
if cube.var_name == "T2M":
break
cube.coord('latitude').guess_bounds()
cube.coord('longitude').guess_bounds()
bounds = [-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100]
utils.plot_smooth_map_iris(settings.IMAGELOC + "SAT_{}_anoms_jra55".format(settings.YEAR), cube, \
settings.COLOURMAP_DICT["temperature"], bounds, \
"Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", title="JRA-55")
#************************************************************************
# NASA GISS Anomaly figure
if True:
doNASAIris = False # if netcdf file or text
if doNASAIris:
cube = iris.load(DATALOC + "gistemp1200_GHCNv4_ERSSTv5.nc")[0]
# convert to 1981-2010 climatology.
clim_constraint = utils.periodConstraint(cube, dt.datetime(1981, 1, 1), dt.datetime(2011, 1, 1))
clim_cube = cube.extract(clim_constraint)
clim_data = clim_cube.data.reshape(-1, 12, clim_cube.data.shape[-2], clim_cube.data.shape[-1])
# more than 15 years present
climatology = np.ma.mean(clim_data, axis=0)
nyears = np.ma.count(clim_data, axis=0)
climatology = np.ma.masked_where(nyears <= 15, climatology) # Kate keeps GT 15.
# extract final year
final_year_constraint = utils.periodConstraint(cube, dt.datetime(int(settings.YEAR), 1, 1), \
dt.datetime(int(settings.YEAR)+1, 1, 1))
final_year_cube = cube.extract(final_year_constraint)
final_year_cube.data = final_year_cube.data - climatology
# more than 6 months present
annual_cube = final_year_cube.collapsed(['time'], iris.analysis.MEAN)
nmonths = np.ma.count(final_year_cube.data, axis=0)
annual_cube.data = np.ma.masked_where(nmonths <= 6, annual_cube.data)
else:
annual_cube = read_nasa_giss(DATALOC + "nasa-gridded-{}-anomalies.txt".format(settings.YEAR))
bounds = [-100, -4, -2, -1, -0.5, 0, 0.5, 1, 2, 4, 100]
utils.plot_smooth_map_iris(settings.IMAGELOC + "SAT_{}_anoms_nasa".format(settings.YEAR), annual_cube, \
settings.COLOURMAP_DICT["temperature"], bounds, \
"Anomalies from 1981-2010 ("+r'$^{\circ}$'+"C)", title="NASA GISS")
return # run_all_plots
#************************************************************************
if __name__ == "__main__":
run_all_plots()
#************************************************************************
# END
#************************************************************************
| 44.679012 | 214 | 0.580271 | 4,691 | 36,190 | 4.334683 | 0.098913 | 0.003738 | 0.010229 | 0.01859 | 0.811301 | 0.786958 | 0.756467 | 0.725583 | 0.710632 | 0.694207 | 0 | 0.050047 | 0.228129 | 36,190 | 809 | 215 | 44.73424 | 0.677884 | 0.236585 | 0 | 0.481572 | 0 | 0.004914 | 0.095949 | 0.027665 | 0 | 0 | 0 | 0 | 0 | 1 | 0.019656 | false | 0 | 0.019656 | 0 | 0.061425 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
c049a7e52ddf80af741b44d35ed4f7320b282eb3 | 61,038 | py | Python | tests/test_utils.py | fossabot/easy_sast | 1aa7dbbf340e3340fa2f70ec5bafb798294bfa7a | [
"BSD-3-Clause"
] | null | null | null | tests/test_utils.py | fossabot/easy_sast | 1aa7dbbf340e3340fa2f70ec5bafb798294bfa7a | [
"BSD-3-Clause"
] | null | null | null | tests/test_utils.py | fossabot/easy_sast | 1aa7dbbf340e3340fa2f70ec5bafb798294bfa7a | [
"BSD-3-Clause"
] | 1 | 2021-01-20T20:59:52.000Z | 2021-01-20T20:59:52.000Z | #!/usr/bin/env python3
# pylint: disable=too-many-public-methods, too-many-lines
"""
Unit tests for utils.py
"""
# built-ins
import logging
import secrets
from pathlib import Path
from unittest import TestCase
from unittest.mock import patch
# third party
from defusedxml import ElementTree
from requests.exceptions import HTTPError, Timeout, RequestException, TooManyRedirects
# custom
from tests import constants as test_constants
from veracode import constants as veracode_constants
from veracode import utils
from veracode.api import ResultsAPI, UploadAPI
# Setup a logger
logging.getLogger()
FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
logging.basicConfig(level="DEBUG", format=FORMAT)
logging.raiseExceptions = True
LOG = logging.getLogger(__name__)
class TestVeracodeUtils(TestCase):
"""
Test utils.py
"""
## validate tests
# validate decorator on a Results API function
@patch("veracode.utils.validate_api")
@patch("veracode.utils.is_valid_attribute")
def test_validate_decorator(self, mock_is_valid_attribute, mock_validate_api):
"""
Test the validate decorator
"""
# Prereqs to test the validate decorator with a valid ResultsAPI
@utils.validate
def test_results_function(
*, results_api: ResultsAPI, variable: int # pylint: disable=unused-argument
) -> None:
pass
results_api = ResultsAPI(app_id=test_constants.VALID_RESULTS_API["app_id"])
# Prereqs to test the validate decorator with a valid UploadAPI
@utils.validate
def test_upload_function(
*, upload_api: UploadAPI, variable: int # pylint: disable=unused-argument
) -> None:
pass
upload_api = UploadAPI(app_id=test_constants.VALID_UPLOAD_API["app_id"])
# Test the validate decorator with a valid ResultsAPI
for is_valid_attribute_return_value in [True, False]:
for validate_api_side_effect in [None, KeyError, ValueError]:
mock_is_valid_attribute.return_value = is_valid_attribute_return_value
mock_validate_api.side_effect = validate_api_side_effect
if validate_api_side_effect == KeyError:
self.assertRaises(
KeyError,
test_results_function,
results_api=results_api,
variable=123,
)
elif validate_api_side_effect == ValueError:
self.assertRaises(
ValueError,
test_results_function,
results_api=results_api,
variable=123,
)
elif not is_valid_attribute_return_value:
self.assertRaises(
ValueError,
test_results_function,
results_api=results_api,
variable=123,
)
else:
self.assertIsNone(
test_results_function(results_api=results_api, variable=123)
)
# Test the validate decorator with a valid ResultsAPI
for is_valid_attribute_return_value in [True, False]:
for validate_api_side_effect in [None, KeyError, ValueError]:
mock_is_valid_attribute.return_value = is_valid_attribute_return_value
mock_validate_api.side_effect = validate_api_side_effect
if validate_api_side_effect == KeyError:
self.assertRaises(
KeyError,
test_upload_function,
upload_api=upload_api,
variable=123,
)
elif validate_api_side_effect == ValueError:
self.assertRaises(
ValueError,
test_upload_function,
upload_api=upload_api,
variable=123,
)
elif not is_valid_attribute_return_value:
self.assertRaises(
ValueError,
test_upload_function,
upload_api=upload_api,
variable=123,
)
else:
self.assertIsNone(
test_upload_function(upload_api=upload_api, variable=123)
)
## parse_xml tests
def test_parse_xml(self):
"""
Test the parse_xml function
"""
# Fail when attempting to call the parse_xml function, given that the
# argument causes an exception to be raised
self.assertRaises(
ElementTree.ParseError,
utils.parse_xml,
content=test_constants.XML_API_INVALID_RESPONSE_XML_ERROR["bytes"],
)
# Succeed when calling the parse_xml function with valid arguments
output = utils.parse_xml(
content=test_constants.XML_API_VALID_RESPONSE_XML_ERROR["bytes"]
)
self.assertEqual(
[output.tag, output.attrib],
[
test_constants.XML_API_VALID_RESPONSE_XML_ERROR["Element"].tag,
test_constants.XML_API_VALID_RESPONSE_XML_ERROR["Element"].attrib,
],
)
## element_contains_error tests
def test_element_contains_error(self):
"""
Test the element_contains_error function
"""
# Succeed when calling the element_contains_error function, given an
# argument which contains an error
self.assertTrue(
utils.element_contains_error(
parsed_xml=test_constants.XML_API_VALID_RESPONSE_XML_ERROR["Element"]
)
)
# Return False when calling the element_contains_error function, given
# an argument which doesn't contain an error
self.assertFalse(
utils.element_contains_error(
parsed_xml=test_constants.VALID_UPLOAD_API_CREATEBUILD_RESPONSE_XML[
"Element"
]
)
)
## http_request tests
# http_request get 200
@patch("requests.get")
@patch("veracode.utils.parse_xml")
@patch("veracode.utils.element_contains_error")
def test_http_request_get_200(
self, mock_element_contains_error, mock_parse_xml, mock_get
):
"""
Test the http_request function with a get verb and 200 response
"""
# Succeed when calling the http_request function with valid arguments,
# a verb="get", and a mocked 200 response
mock_element_contains_error.return_value = False
mock_get.return_value.content = (
test_constants.VALID_RESULTS_API_GETAPPBUILDS_RESPONSE_XML_NO_BUILDS[
"bytes"
]
)
mock_get.return_value.status_code = 200
mock_get.return_value.raise_for_status.side_effect = HTTPError()
mock_parse_xml.return_value = (
test_constants.VALID_RESULTS_API_GETAPPBUILDS_RESPONSE_XML_NO_BUILDS[
"Element"
]
)
endpoint = "getappbuilds.do"
url = (
test_constants.VALID_RESULTS_API["base_url"]
+ test_constants.VALID_RESULTS_API["version"][endpoint]
+ "/"
+ endpoint
)
response = utils.http_request(verb="get", url=url)
self.assertEqual(
[response.tag, response.attrib],
[
test_constants.VALID_RESULTS_API_GETAPPBUILDS_RESPONSE_XML_NO_BUILDS[
"Element"
].tag,
test_constants.VALID_RESULTS_API_GETAPPBUILDS_RESPONSE_XML_NO_BUILDS[
"Element"
].attrib,
],
)
# http_request get httperror
@patch("requests.get")
@patch("veracode.utils.parse_xml")
@patch("veracode.utils.element_contains_error")
def test_http_request_get_httperror(
self, mock_element_contains_error, mock_parse_xml, mock_get
):
"""
Test the http_request function with a get verb and experience a
variety of HTTPError failures based on the status_code
"""
# These two should not be relevant, but keeping in case the test
# follows an unexpected path
mock_element_contains_error.return_value = False
mock_parse_xml.return_value = (
test_constants.VALID_RESULTS_API_GETAPPBUILDS_RESPONSE_XML_NO_BUILDS[
"Element"
]
)
# Fail when attempting to call the http_request function with valid
# arguments, a verb="get", and a mocked failure response from the
# list above
endpoint = "getappbuilds.do"
url = (
test_constants.VALID_RESULTS_API["base_url"]
+ test_constants.VALID_RESULTS_API["version"][endpoint]
+ "/"
+ endpoint
)
for failure_code in [403, 404, 500]:
mock_get.return_value.status_code = failure_code
mock_get.return_value.raise_for_status.side_effect = HTTPError()
self.assertRaises(
HTTPError,
utils.http_request,
verb="get",
url=url,
)
# http_request get connectionerror
@patch("requests.get")
@patch("veracode.utils.parse_xml")
@patch("veracode.utils.element_contains_error")
def test_http_request_get_connectionerror(
self, mock_element_contains_error, mock_parse_xml, mock_get
):
"""
Test the http_request function with a get verb and experience a
ConnectionError
"""
# These two should not be relevant, but keeping in case the test
# follows an unexpected path
mock_element_contains_error.return_value = False
mock_parse_xml.return_value = (
test_constants.VALID_RESULTS_API_GETAPPBUILDS_RESPONSE_XML_NO_BUILDS[
"Element"
]
)
# Fail when attempting to call the http_request function with valid
# arguments, a verb="get", and a mocked ConnectionError
endpoint = "getappbuilds.do"
url = (
test_constants.VALID_RESULTS_API["base_url"]
+ test_constants.VALID_RESULTS_API["version"][endpoint]
+ "/"
+ endpoint
)
mock_get.side_effect = ConnectionError()
self.assertRaises(
ConnectionError,
utils.http_request,
verb="get",
url=url,
)
# http_request get requestexception
@patch("requests.get")
@patch("veracode.utils.parse_xml")
@patch("veracode.utils.element_contains_error")
def test_http_request_get_requestexception(
self, mock_element_contains_error, mock_parse_xml, mock_get
):
"""
Test the http_request function with a get verb and experience a
RequestException
"""
# These two should not be relevant, but keeping in case the test
# follows an unexpected path
mock_element_contains_error.return_value = False
mock_parse_xml.return_value = (
test_constants.VALID_RESULTS_API_GETAPPBUILDS_RESPONSE_XML_NO_BUILDS[
"Element"
]
)
# Fail when attempting to call the http_request function with valid
# arguments, a verb="get", and a mocked RequestException
endpoint = "getappbuilds.do"
url = (
test_constants.VALID_RESULTS_API["base_url"]
+ test_constants.VALID_RESULTS_API["version"][endpoint]
+ "/"
+ endpoint
)
mock_get.side_effect = RequestException()
self.assertRaises(
RequestException,
utils.http_request,
verb="get",
url=url,
)
# http_request get timeout
@patch("requests.get")
@patch("veracode.utils.parse_xml")
@patch("veracode.utils.element_contains_error")
def test_http_request_get_timeout(
self, mock_element_contains_error, mock_parse_xml, mock_get
):
"""
Test the http_request function with a get verb and experience a
Timeout
"""
# These two should not be relevant, but keeping in case the test
# follows an unexpected path
mock_element_contains_error.return_value = False
mock_parse_xml.return_value = (
test_constants.VALID_RESULTS_API_GETAPPBUILDS_RESPONSE_XML_NO_BUILDS[
"Element"
]
)
# Fail when attempting to call the http_request function with valid
# arguments, a verb="get", and a mocked Timeout
endpoint = "getappbuilds.do"
url = (
test_constants.VALID_RESULTS_API["base_url"]
+ test_constants.VALID_RESULTS_API["version"][endpoint]
+ "/"
+ endpoint
)
mock_get.side_effect = Timeout()
self.assertRaises(
Timeout,
utils.http_request,
verb="get",
url=url,
)
# http_request get toomanyredirects
@patch("requests.get")
@patch("veracode.utils.parse_xml")
@patch("veracode.utils.element_contains_error")
def test_http_request_get_toomanyredirects(
self, mock_element_contains_error, mock_parse_xml, mock_get
):
"""
Test the http_request function with a get verb and experience a
TooManyRedirects
"""
# These two should not be relevant, but keeping in case the test
# follows an unexpected path
mock_element_contains_error.return_value = False
mock_parse_xml.return_value = (
test_constants.VALID_RESULTS_API_GETAPPBUILDS_RESPONSE_XML_NO_BUILDS[
"Element"
]
)
# Fail when attempting to call the http_request function with valid
# arguments, a verb="get", and a mocked TooManyRedirects
endpoint = "getappbuilds.do"
url = (
test_constants.VALID_RESULTS_API["base_url"]
+ test_constants.VALID_RESULTS_API["version"][endpoint]
+ "/"
+ endpoint
)
mock_get.side_effect = TooManyRedirects()
self.assertRaises(
TooManyRedirects,
utils.http_request,
verb="get",
url=url,
)
# http_request get error body response
@patch("requests.get")
@patch("veracode.utils.parse_xml")
@patch("veracode.utils.element_contains_error")
def test_http_request_get_error_body_response(
self, mock_element_contains_error, mock_parse_xml, mock_get
):
"""
Test the http_request function with a get verb and experience an error
in the response body
"""
# Fail when attempting to call the http_request function with valid
# arguments, a verb="get", and a mocked element_contains_error of True
mock_get.return_value.status_code = 200
mock_get.return_value.raise_for_status.side_effect = HTTPError()
mock_get.return_value.content = test_constants.VERACODE_ERROR_RESPONSE_XML[
"bytes"
]
mock_parse_xml.return_value = test_constants.VERACODE_ERROR_RESPONSE_XML[
"Element"
]
mock_element_contains_error.return_value = True
endpoint = "getappbuilds.do"
url = (
test_constants.VALID_RESULTS_API["base_url"]
+ test_constants.VALID_RESULTS_API["version"][endpoint]
+ "/"
+ endpoint
)
response = utils.http_request(verb="get", url=url)
self.assertEqual(
[response.tag, response.attrib],
[
test_constants.VERACODE_ERROR_RESPONSE_XML["Element"].tag,
test_constants.VERACODE_ERROR_RESPONSE_XML["Element"].attrib,
],
)
# http_request post 200
@patch("requests.post")
@patch("veracode.utils.parse_xml")
@patch("veracode.utils.element_contains_error")
def test_http_request_post_200(
self, mock_element_contains_error, mock_parse_xml, mock_post
):
"""
Test the http_request function with a post verb and 200 response
"""
# Succeed when calling the http_request function with valid arguments,
# a verb="post", and a mocked 200 response
mock_element_contains_error.return_value = False
mock_post.return_value.content = (
test_constants.VALID_UPLOAD_API_UPLOADLARGEFILE_RESPONSE_XML["bytes"]
)
mock_post.return_value.status_code = 200
mock_post.return_value.raise_for_status.side_effect = HTTPError()
mock_parse_xml.return_value = (
test_constants.VALID_UPLOAD_API_UPLOADLARGEFILE_RESPONSE_XML["Element"]
)
app_id = test_constants.VALID_UPLOAD_API["app_id"]
filename = test_constants.VALID_FILE["name"]
data = test_constants.VALID_FILE["bytes"]
params = {"app_id": app_id, "filename": filename}
headers = {"Content-Type": "binary/octet-stream"}
endpoint = "uploadlargefile.do"
url = (
test_constants.VALID_UPLOAD_API["base_url"]
+ test_constants.VALID_UPLOAD_API["version"][endpoint]
+ "/"
+ endpoint
)
response = utils.http_request(
verb="post",
url=url,
data=data,
params=params,
headers=headers,
)
self.assertEqual(
[response.tag, response.attrib],
[
test_constants.VALID_UPLOAD_API_UPLOADLARGEFILE_RESPONSE_XML[
"Element"
].tag,
test_constants.VALID_UPLOAD_API_UPLOADLARGEFILE_RESPONSE_XML[
"Element"
].attrib,
],
)
# http_request post httperror
@patch("requests.post")
@patch("veracode.utils.parse_xml")
@patch("veracode.utils.element_contains_error")
def test_http_request_post_httperror(
self, mock_element_contains_error, mock_parse_xml, mock_post
):
"""
Test the http_request function with a post verb and experience a
variety of HTTPError failures based on the status_code
"""
# These two should not be relevant, but keeping in case the test
# follows an unexpected path
mock_element_contains_error.return_value = False
mock_parse_xml.return_value = (
test_constants.VALID_UPLOAD_API_UPLOADLARGEFILE_RESPONSE_XML["Element"]
)
# Fail when attempting to call the http_request function with valid
# arguments, a verb="post", and a mocked failure response from the
# list above
app_id = test_constants.VALID_UPLOAD_API["app_id"]
filename = test_constants.VALID_FILE["name"]
data = test_constants.VALID_FILE["bytes"]
params = {"app_id": app_id, "filename": filename}
headers = {"Content-Type": "binary/octet-stream"}
endpoint = "uploadlargefile.do"
url = (
test_constants.VALID_UPLOAD_API["base_url"]
+ test_constants.VALID_UPLOAD_API["version"][endpoint]
+ "/"
+ endpoint
)
for failure_code in [403, 404, 500]:
mock_post.return_value.status_code = failure_code
mock_post.return_value.raise_for_status.side_effect = HTTPError()
self.assertRaises(
HTTPError,
utils.http_request,
verb="post",
url=url,
data=data,
params=params,
headers=headers,
)
# http_request post connectionerror
@patch("requests.post")
@patch("veracode.utils.parse_xml")
@patch("veracode.utils.element_contains_error")
def test_http_request_post_connectionerror(
self, mock_element_contains_error, mock_parse_xml, mock_post
):
"""
Test the http_request function with a post verb and experience a
ConnectionError
"""
# These two should not be relevant, but keeping in case the test
# follows an unexpected path
mock_element_contains_error.return_value = False
mock_parse_xml.return_value = (
test_constants.VALID_UPLOAD_API_UPLOADLARGEFILE_RESPONSE_XML["Element"]
)
# Fail when attempting to call the http_request function with valid
# arguments, a verb="post", and a mocked ConnectionError
app_id = test_constants.VALID_UPLOAD_API["app_id"]
filename = test_constants.VALID_FILE["name"]
data = test_constants.VALID_FILE["bytes"]
params = {"app_id": app_id, "filename": filename}
headers = {"Content-Type": "binary/octet-stream"}
endpoint = "uploadlargefile.do"
url = (
test_constants.VALID_UPLOAD_API["base_url"]
+ test_constants.VALID_UPLOAD_API["version"][endpoint]
+ "/"
+ endpoint
)
mock_post.side_effect = ConnectionError()
self.assertRaises(
ConnectionError,
utils.http_request,
verb="post",
url=url,
data=data,
params=params,
headers=headers,
)
# http_request post requestexception
@patch("requests.post")
@patch("veracode.utils.parse_xml")
@patch("veracode.utils.element_contains_error")
def test_http_request_post_requestexception(
self, mock_element_contains_error, mock_parse_xml, mock_post
):
"""
Test the http_request function with a post verb and experience a
RequestException
"""
# These two should not be relevant, but keeping in case the test
# follows an unexpected path
mock_element_contains_error.return_value = False
mock_parse_xml.return_value = (
test_constants.VALID_UPLOAD_API_UPLOADLARGEFILE_RESPONSE_XML["Element"]
)
# Fail when attempting to call the http_request function with valid
# arguments, a verb="post", and a mocked RequestException
app_id = test_constants.VALID_UPLOAD_API["app_id"]
filename = test_constants.VALID_FILE["name"]
data = test_constants.VALID_FILE["bytes"]
params = {"app_id": app_id, "filename": filename}
headers = {"Content-Type": "binary/octet-stream"}
endpoint = "uploadlargefile.do"
url = (
test_constants.VALID_UPLOAD_API["base_url"]
+ test_constants.VALID_UPLOAD_API["version"][endpoint]
+ "/"
+ endpoint
)
mock_post.side_effect = RequestException()
self.assertRaises(
RequestException,
utils.http_request,
verb="post",
url=url,
data=data,
params=params,
headers=headers,
)
# http_request post timeout
@patch("requests.post")
@patch("veracode.utils.parse_xml")
@patch("veracode.utils.element_contains_error")
def test_http_request_post_timeout(
self, mock_element_contains_error, mock_parse_xml, mock_post
):
"""
Test the http_request function with a post verb and experience a
Timeout
"""
# These two should not be relevant, but keeping in case the test
# follows an unexpected path
mock_element_contains_error.return_value = False
mock_parse_xml.return_value = (
test_constants.VALID_UPLOAD_API_UPLOADLARGEFILE_RESPONSE_XML["Element"]
)
# Fail when attempting to call the http_request function with valid
# arguments, a verb="post", and a mocked Timeout
app_id = test_constants.VALID_UPLOAD_API["app_id"]
filename = test_constants.VALID_FILE["name"]
data = test_constants.VALID_FILE["bytes"]
params = {"app_id": app_id, "filename": filename}
headers = {"Content-Type": "binary/octet-stream"}
endpoint = "uploadlargefile.do"
url = (
test_constants.VALID_UPLOAD_API["base_url"]
+ test_constants.VALID_UPLOAD_API["version"][endpoint]
+ "/"
+ endpoint
)
mock_post.side_effect = Timeout()
self.assertRaises(
Timeout,
utils.http_request,
verb="post",
url=url,
data=data,
params=params,
headers=headers,
)
# http_request post toomanyredirects
@patch("requests.post")
@patch("veracode.utils.parse_xml")
@patch("veracode.utils.element_contains_error")
def test_http_request_post_toomanyredirects(
self, mock_element_contains_error, mock_parse_xml, mock_post
):
"""
Test the http_request function with a post verb and experience a
TooManyRedirects
"""
# These two should not be relevant, but keeping in case the test
# follows an unexpected path
mock_element_contains_error.return_value = False
mock_parse_xml.return_value = (
test_constants.VALID_UPLOAD_API_UPLOADLARGEFILE_RESPONSE_XML["Element"]
)
# Fail when attempting to call the http_request function with valid
# arguments, a verb="post", and a mocked TooManyRedirects
app_id = test_constants.VALID_UPLOAD_API["app_id"]
filename = test_constants.VALID_FILE["name"]
data = test_constants.VALID_FILE["bytes"]
params = {"app_id": app_id, "filename": filename}
headers = {"Content-Type": "binary/octet-stream"}
endpoint = "uploadlargefile.do"
url = (
test_constants.VALID_UPLOAD_API["base_url"]
+ test_constants.VALID_UPLOAD_API["version"][endpoint]
+ "/"
+ endpoint
)
mock_post.side_effect = TooManyRedirects()
self.assertRaises(
TooManyRedirects,
utils.http_request,
verb="post",
url=url,
data=data,
params=params,
headers=headers,
)
# http_request post error body response
@patch("requests.post")
@patch("veracode.utils.parse_xml")
@patch("veracode.utils.element_contains_error")
def test_http_request_post_error_body_response(
self, mock_element_contains_error, mock_parse_xml, mock_post
):
"""
Test the http_request function with a post verb and experience an error
in the response body
"""
# Fail when attempting to call the http_request function with valid
# arguments, a verb="post", and a mocked element_contains_error of True
app_id = test_constants.VALID_UPLOAD_API["app_id"]
filename = test_constants.VALID_FILE["name"]
data = test_constants.VALID_FILE["bytes"]
params = {"app_id": app_id, "filename": filename}
headers = {"Content-Type": "binary/octet-stream"}
endpoint = "uploadlargefile.do"
url = (
test_constants.VALID_UPLOAD_API["base_url"]
+ test_constants.VALID_UPLOAD_API["version"][endpoint]
+ "/"
+ endpoint
)
mock_post.return_value.status_code = 200
mock_post.return_value.raise_for_status.side_effect = HTTPError()
mock_post.return_value.content = test_constants.VERACODE_ERROR_RESPONSE_XML[
"bytes"
]
mock_parse_xml.return_value = test_constants.VERACODE_ERROR_RESPONSE_XML[
"Element"
]
mock_element_contains_error.return_value = True
response = utils.http_request(
verb="post",
url=url,
data=data,
params=params,
headers=headers,
)
self.assertEqual(
[response.tag, response.attrib],
[
test_constants.VERACODE_ERROR_RESPONSE_XML["Element"].tag,
test_constants.VERACODE_ERROR_RESPONSE_XML["Element"].attrib,
],
)
# http_request unsupported verb valueerror
def test_http_request_unsupported_verb_valueerror(self):
"""
Test the http_request function with a list of unsupported verbs
"""
# Fail when attempting to call the http_request function with an invalid verb
# as an argument
endpoint = "uploadlargefile.do"
url = (
test_constants.VALID_UPLOAD_API["base_url"]
+ test_constants.VALID_UPLOAD_API["version"][endpoint]
+ "/"
+ endpoint
)
for verb in ["put", "patch", "delete", "options", "head", "connect", "trace"]:
self.assertRaises(
ValueError,
utils.http_request,
verb=verb,
url=url,
)
## is_valid_attribute tests
# base_url validation
@patch("veracode.utils.protocol_is_insecure")
@patch("veracode.utils.is_valid_netloc")
def test_is_valid_attribute_base_url(
self, mock_is_valid_netloc, mock_protocol_is_insecure
):
"""
Test the base_url validation in is_valid_attribute
"""
# Fail when calling the is_valid_attribute function with valid
# arguments and a mocked protocol_is_insecure of True
mock_is_valid_netloc.return_value = True
mock_protocol_is_insecure.return_value = True
self.assertFalse(
utils.is_valid_attribute(
key="base_url", value=test_constants.VALID_RESULTS_API["base_url"]
)
)
# Succeed when calling the is_valid_attribute function with valid
# arguments and a mocked protocol_is_insecure of False
mock_is_valid_netloc.return_value = True
mock_protocol_is_insecure.return_value = False
self.assertTrue(
utils.is_valid_attribute(
key="base_url", value=test_constants.VALID_RESULTS_API["base_url"]
)
)
# Fail when calling the is_valid_attribute function with an invalid
# argument that contains an empty netloc on the base_url
mock_is_valid_netloc.return_value = True
mock_protocol_is_insecure.return_value = False
self.assertFalse(
utils.is_valid_attribute(
key="base_url",
value=test_constants.INVALID_RESULTS_API_MISSING_DOMAIN["base_url"],
)
)
# Succeed when calling the is_valid_attribute function with a valid
# argument, and an in_valid_netloc patched to always return True
mock_is_valid_netloc.return_value = True
mock_protocol_is_insecure.return_value = False
self.assertTrue(
utils.is_valid_attribute(
key="base_url",
value=test_constants.VALID_RESULTS_API["base_url"],
)
)
# Fail when calling the is_valid_attribute function with a valid
# argument, and an in_valid_netloc patched to always return False
mock_is_valid_netloc.return_value = False
mock_protocol_is_insecure.return_value = False
self.assertFalse(
utils.is_valid_attribute(
key="base_url",
value=test_constants.VALID_RESULTS_API["base_url"],
)
)
# Succeed when calling the is_valid_attribute function with a missing
# port (and thus valid) in the base_url
mock_is_valid_netloc.return_value = True
mock_protocol_is_insecure.return_value = False
self.assertTrue(
utils.is_valid_attribute(
key="base_url",
value=test_constants.VALID_RESULTS_API["base_url"],
)
)
# Succeed when calling the is_valid_attribute function with a valid
# port in the base_url
mock_is_valid_netloc.return_value = True
mock_protocol_is_insecure.return_value = False
self.assertTrue(
utils.is_valid_attribute(
key="base_url",
value=test_constants.VALID_RESULTS_API_WITH_PORT_IN_URL["base_url"],
)
)
# Fail when calling the is_valid_attribute function with an invalid
# port in the base_url
mock_is_valid_netloc.return_value = True
mock_protocol_is_insecure.return_value = False
self.assertRaises(
ValueError,
utils.is_valid_attribute,
key="base_url",
value=test_constants.INVALID_RESULTS_API_INVALID_PORT["base_url"],
)
# Fail when attempting to call the is_valid_attribute function with an
# improperly formatted base_url dual to the double colon
mock_is_valid_netloc.return_value = True
mock_protocol_is_insecure.return_value = False
self.assertRaises(
ValueError,
utils.is_valid_attribute,
key="base_url",
value="https://example.com::443/testing/",
)
# Fail when calling the is_valid_attribute function with an empty path
# in the base_url
mock_is_valid_netloc.return_value = True
mock_protocol_is_insecure.return_value = False
self.assertFalse(
utils.is_valid_attribute(key="base_url", value="https://example.com/")
)
# Fail when calling the is_valid_attribute function with a base_url
# that doesn't end with /
mock_is_valid_netloc.return_value = True
mock_protocol_is_insecure.return_value = False
self.assertFalse(
utils.is_valid_attribute(key="base_url", value="https://example.com/thing")
)
# version validation
def test_is_valid_attribute_version(self):
"""
Test the version validation in is_valid_attribute
"""
# Succeed when calling the is_valid_attribute function with a version
# that maps a string to a string
self.assertTrue(
utils.is_valid_attribute(key="version", value={"test.do": "1.2"})
)
# Fail when calling the is_valid_attribute function with a version that
# maps a string to a float
self.assertFalse(
utils.is_valid_attribute(key="version", value={"test.do": 1.1})
)
# Fail when calling the is_valid_attribute function with a version that
# maps a float to a string
self.assertFalse(
utils.is_valid_attribute(key="version", value={3.141: "2.718"})
)
# Fail when calling the is_valid_attribute function with a version that
# is a string
self.assertFalse(utils.is_valid_attribute(key="version", value="failure"))
# endpoint validation
def test_is_valid_attribute_endpoint(self):
"""
Test the endpoint validation in is_valid_attribute
"""
# Succeed when calling the is_valid_attribute function with an endpoint
# that is a valid string
self.assertTrue(
utils.is_valid_attribute(
key="endpoint",
value="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",
)
)
# Fail when calling the is_valid_attribute function with an endpoint
# that is an empty string
self.assertFalse(utils.is_valid_attribute(key="endpoint", value=""))
# Fail when calling the is_valid_attribute function with an endpoint
# that is an invalid string
self.assertFalse(utils.is_valid_attribute(key="endpoint", value=";$"))
# Fail when calling the is_valid_attribute function with an endpoint
# that is an int
self.assertFalse(utils.is_valid_attribute(key="endpoint", value=7))
# app_id validation
def test_is_valid_attribute_app_id(self):
"""
Test the app_id validation in is_valid_attribute
"""
# Succeed when calling the is_valid_attribute function with an app_id
# that is whole number represented as a string
self.assertTrue(utils.is_valid_attribute(key="app_id", value="54321"))
# Fail when calling the is_valid_attribute function with an app_id that
# is an int
self.assertFalse(utils.is_valid_attribute(key="app_id", value=54321))
# Fail when calling the is_valid_attribute function with an app_id that
# is a string but not a whole number
self.assertFalse(utils.is_valid_attribute(key="app_id", value="success"))
# Fail when calling the is_valid_attribute function with an app_id that
# is a float
self.assertFalse(utils.is_valid_attribute(key="app_id", value=543.21))
# build_dir validation
def test_is_valid_attribute_build_dir(self):
"""
Test the build_dir validation in is_valid_attribute
"""
# Succeed when calling the is_valid_attribute function with a build_dir
# that is a Path object
self.assertTrue(
utils.is_valid_attribute(key="build_dir", value=Path("./path.pdb"))
)
# Fail when calling the is_valid_attribute function with a build_dir
# that is a string
self.assertFalse(utils.is_valid_attribute(key="build_dir", value="./path.pdb"))
# build_id validation
def test_is_valid_attribute_build_id(self):
"""
Test the build_id validation in is_valid_attribute
"""
# Succeed when calling the is_valid_attribute function with a build_id
# that is a valid string
self.assertTrue(
utils.is_valid_attribute(
key="build_id",
value="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",
)
)
# Fail when calling the is_valid_attribute function with a build_id
# that is an empty string
self.assertFalse(utils.is_valid_attribute(key="build_id", value=""))
# Succeed when calling the is_valid_attribute function with a build_id
# that is an invalid string
self.assertFalse(utils.is_valid_attribute(key="build_id", value=";$"))
# Fail when calling the is_valid_attribute function with a build_id
# that is an int
self.assertFalse(utils.is_valid_attribute(key="build_id", value=7))
# sandbox_id validation
def test_is_valid_attribute_sandbox_id(self):
"""
Test the sandbox_id validation in is_valid_attribute
"""
# Succeed when calling the is_valid_attribute function with a
# sandbox_id that is whole number represented as a string
self.assertTrue(utils.is_valid_attribute(key="sandbox_id", value="54321"))
# Succeed when calling the is_valid_attribute function with a
# sandbox_id that is None (the default)
self.assertTrue(utils.is_valid_attribute(key="sandbox_id", value=None))
# Fail when calling the is_valid_attribute function with a sandbox_id
# that is an int
self.assertFalse(utils.is_valid_attribute(key="sandbox_id", value=54321))
# Fail when calling the is_valid_attribute function with a sandbox_id
# that is a string but not a whole number
self.assertFalse(utils.is_valid_attribute(key="sandbox_id", value="success"))
# Fail when calling the is_valid_attribute function with a sandbox_id
# that is a float
self.assertFalse(utils.is_valid_attribute(key="sandbox_id", value=543.21))
# scan_all_nonfatal_top_level_modules validation
def test_is_valid_attribute_scan_all_nonfatal_top_level_modules(self):
"""
Test the scan_all_nonfatal_top_level_modules validation in
is_valid_attribute
"""
# Succeed when calling the is_valid_attribute function with a
# scan_all_nonfatal_top_level_modules that is a bool
self.assertTrue(
utils.is_valid_attribute(
key="scan_all_nonfatal_top_level_modules", value=False
)
)
# Fail when calling the is_valid_attribute function with a
# scan_all_nonfatal_top_level_modules that is a string
self.assertFalse(
utils.is_valid_attribute(
key="scan_all_nonfatal_top_level_modules", value="string"
)
)
# Succeed when calling the is_valid_attribute function with a
# scan_all_nonfatal_top_level_modules that is an int
self.assertFalse(
utils.is_valid_attribute(key="scan_all_nonfatal_top_level_modules", value=1)
)
# auto_scan validation
def test_is_valid_attribute_auto_scan(self):
"""
Test the auto_scan validation in is_valid_attribute
"""
# Succeed when calling the is_valid_attribute function with an auto_scan
# that is a bool
self.assertTrue(utils.is_valid_attribute(key="auto_scan", value=False))
# Fail when calling the is_valid_attribute function with an auto_scan
# that is a string
self.assertFalse(utils.is_valid_attribute(key="auto_scan", value="string"))
# Succeed when calling the is_valid_attribute function with an auto_scan
# that is an int
self.assertFalse(utils.is_valid_attribute(key="auto_scan", value=1))
# sandbox_name validation
def test_is_valid_attribute_sandbox_name(self):
"""
Test the sandbox_name validation in is_valid_attribute
"""
# Succeed when calling the is_valid_attribute function with a
# sandbox_name that is a valid string
self.assertTrue(
utils.is_valid_attribute(
key="sandbox_name",
value=r"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()_+=-[]|}{;:,./? ",
)
)
# Fail when calling the is_valid_attribute function with a sandbox_name
# that is an empty string
self.assertFalse(utils.is_valid_attribute(key="sandbox_name", value=""))
# Fail when calling the is_valid_attribute function with a sandbox_name
# that is an invalid string
self.assertFalse(utils.is_valid_attribute(key="sandbox_name", value=r"a\b\c"))
# Fail when calling the is_valid_attribute function with a sandbox_name
# that is an int
self.assertFalse(utils.is_valid_attribute(key="sandbox_name", value=7))
# Fail when calling the is_valid_attribute function with a sandbox_name
# that contains invalid characters
self.assertFalse(utils.is_valid_attribute(key="sandbox_name", value="<test>"))
# api_key_id validation
def test_is_valid_attribute_api_key_id(self):
"""
Test the api_key_id validation in is_valid_attribute
"""
# Succeed when calling the is_valid_attribute function with an
# api_key_id that is 32 characters of hex
self.assertTrue(
utils.is_valid_attribute(key="api_key_id", value=secrets.token_hex(16))
)
# Fail when calling the is_valid_attribute function with an api_key_id
# that is a 32 digit int
self.assertFalse(
utils.is_valid_attribute(
key="api_key_id", value=12345678901234567890123456789012
)
)
# Fail when calling the is_valid_attribute function with an api_key_id
# that is a 32 character string but contains non-hex characters
self.assertFalse(
utils.is_valid_attribute(
key="api_key_id", value="a" * 15 + "z" + "b" * 15 + "g"
)
)
# api_key_secret validation
def test_is_valid_attribute_api_key_secret(self):
"""
Test the api_key_secret validation in is_valid_attribute
"""
# Succeed when calling the is_valid_attribute function with an
# api_key_secret that is 128 characters of hex
self.assertTrue(
utils.is_valid_attribute(key="api_key_secret", value=secrets.token_hex(64))
)
# Fail when calling the is_valid_attribute function with an
# api_key_secret that is 127 characters of hex
self.assertFalse(
utils.is_valid_attribute(
key="api_key_secret", value=secrets.token_hex(63) + "0"
)
)
# Fail when calling the is_valid_attribute function with an
# api_key_secret that is a 128 character string which contains non-hex
# characters
self.assertFalse(
utils.is_valid_attribute(
key="api_key_secret", value=secrets.token_hex(63) + "zz"
)
)
# ignore_compliance_status validation
def test_is_valid_attribute_ignore_compliance_status(self):
"""
Test the ignore_compliance_status validation in is_valid_attribute
"""
# Succeed when calling the is_valid_attribute function with an
# ignore_compliance_status that is a bool
self.assertTrue(
utils.is_valid_attribute(key="ignore_compliance_status", value=False)
)
# Fail when calling the is_valid_attribute function with an
# ignore_compliance_status that is a string
self.assertFalse(
utils.is_valid_attribute(key="ignore_compliance_status", value="string")
)
# Succeed when calling the is_valid_attribute function with an
# ignore_compliance_status that is an int
self.assertFalse(
utils.is_valid_attribute(key="ignore_compliance_status", value=1)
)
# loglevel validation
def test_is_valid_attribute_loglevel(self):
"""
Test the loglevel validation in is_valid_attribute
"""
# Succeed when calling the is_valid_attribute function with a loglevel
# that is an allowed log level, appropriately formatted
for log_level in veracode_constants.ALLOWED_LOG_LEVELS:
self.assertTrue(utils.is_valid_attribute(key="loglevel", value=log_level))
# Fail when calling the is_valid_attribute function with a loglevel
# that is a lowercase version of an allowed log level
for log_level in veracode_constants.ALLOWED_LOG_LEVELS:
self.assertFalse(
utils.is_valid_attribute(key="loglevel", value=log_level.casefold())
)
# Fail when calling the is_valid_attribute function with a loglevel
# that is an int
self.assertFalse(utils.is_valid_attribute(key="loglevel", value=20))
# Fail when calling the is_valid_attribute function with a loglevel
# that is both an int and a non-existant log level
self.assertFalse(utils.is_valid_attribute(key="loglevel", value=1020384))
# workflow validation
def test_is_valid_attribute_workflow(self):
"""
Test the workflow validation in is_valid_attribute
"""
# Succeed when calling the is_valid_attribute function with a workflow
# that is a list of allowed workflows
self.assertTrue(
utils.is_valid_attribute(
key="workflow", value=list(veracode_constants.SUPPORTED_WORKFLOWS)
)
)
# Fail when calling the is_valid_attribute function with a workflow
# that is a set of allowed workflows
self.assertFalse(
utils.is_valid_attribute(
key="workflow", value=veracode_constants.SUPPORTED_WORKFLOWS
)
)
# Fail when calling the is_valid_attribute function with a workflow
# that is a list that contains an unsupported workflow mixed in with
# supported workflows
invalid_workflow = (
list(veracode_constants.SUPPORTED_WORKFLOWS)
+ ["unsupported_workflow"]
+ list(veracode_constants.SUPPORTED_WORKFLOWS)
)
self.assertFalse(
utils.is_valid_attribute(key="workflow", value=invalid_workflow)
)
# verb validation
def test_is_valid_attribute_verb(self):
"""
Test the verb validation in is_valid_attribute
"""
# Succeed when calling the is_valid_attribute function with a verb that
# is an allowed verb, appropriately formatted
for verb in veracode_constants.SUPPORTED_VERBS:
self.assertTrue(utils.is_valid_attribute(key="verb", value=verb))
# Fail when calling the is_valid_attribute function with a verb that
# is not an allowed verb
self.assertFalse(utils.is_valid_attribute(key="verb", value=123.2))
# Fail when calling the is_valid_attribute function with a verb that
# is not an allowed verb
for verb in ["put", "patch", "delete", "options", "head", "connect", "trace"]:
self.assertFalse(utils.is_valid_attribute(key="verb", value=verb))
# catch-all validation
def test_is_valid_attribute_catch_all(self):
"""
Test the catch-all validation in is_valid_attribute
"""
# Succeed when calling the is_valid_attribute function with a key that
# is not handled
self.assertTrue(
utils.is_valid_attribute(key="ajfoanweofkwmeofmow", value="alksmfo")
)
## configure_environment tests
def test_configure_environment(self):
"""
Test the configure_environment function
"""
invalid_api_key_id = secrets.token_hex(15) + "zZ"
invalid_api_key_secret = secrets.token_hex(63) + "zZ"
# Succeed when calling the configure_environment function with a valid
# api_key_id and api_key_secret, and no pre-existing environment
# variables
values = {}
with patch.dict("os.environ", values=values, clear=True):
self.assertIsNone(
utils.configure_environment(
api_key_id=test_constants.VALID_RESULTS_API["api_key_id"],
api_key_secret=test_constants.VALID_RESULTS_API["api_key_secret"],
)
)
# Succeed when calling the configure_environment function with a valid
# api_key_id and api_key_secret, even though the VERACODE_API_KEY_ID
# and VERACODE_API_KEY_SECRET environment variables are currently set,
# and do not match the provided values
values = {
"VERACODE_API_KEY_ID": invalid_api_key_id,
"VERACODE_API_KEY_SECRET": invalid_api_key_secret,
}
with patch.dict("os.environ", values=values, clear=True):
self.assertIsNone(
utils.configure_environment(
api_key_id=test_constants.VALID_RESULTS_API["api_key_id"],
api_key_secret=test_constants.VALID_RESULTS_API["api_key_secret"],
)
)
# Succeed when calling the configure_environment function with a valid
# api_key_id and api_key_secret, even though the VERACODE_API_KEY_ID
# and VERACODE_API_KEY_SECRET environment variables are currently set,
# and match the provided values
values = {
"VERACODE_API_KEY_ID": test_constants.VALID_RESULTS_API["api_key_id"],
"VERACODE_API_KEY_SECRET": test_constants.VALID_RESULTS_API[
"api_key_secret"
],
}
with patch.dict("os.environ", values=values, clear=True):
self.assertIsNone(
utils.configure_environment(
api_key_id=test_constants.VALID_RESULTS_API["api_key_id"],
api_key_secret=test_constants.VALID_RESULTS_API["api_key_secret"],
)
)
# Fail when calling the configure_environment function with an invalid
# api_key_id and a valid api_key_secret due to the validate decorator
self.assertRaises(
ValueError,
utils.configure_environment,
api_key_id=invalid_api_key_id,
api_key_secret=test_constants.VALID_RESULTS_API["api_key_secret"],
)
# Fail when calling the configure_environment function with a valid
# api_key_id and an invalid api_key_secret due to the validate
# decorator
self.assertRaises(
ValueError,
utils.configure_environment,
api_key_id=test_constants.VALID_RESULTS_API["api_key_id"],
api_key_secret=invalid_api_key_secret,
)
# Fail when calling the configure_environment function with an invalid
# api_key_id and an invalid api_key_secret due to the validate
# decorator
self.assertRaises(
ValueError,
utils.configure_environment,
api_key_id=invalid_api_key_id,
api_key_secret=invalid_api_key_secret,
)
## validate_api tests
def test_validate_api(self):
"""
Test the validate_api function
"""
# Succeed when calling the validate_api function, given a
# properly configured ResultsAPI object
results_api = ResultsAPI(app_id=test_constants.VALID_RESULTS_API["app_id"])
self.assertIsNone(utils.validate_api(api=results_api))
# Succeed when calling the validate_api function, given a
# properly configured UploadAPI object
upload_api = UploadAPI(app_id=test_constants.VALID_UPLOAD_API["app_id"])
self.assertIsNone(utils.validate_api(api=upload_api))
# Fail when attempting to call the validate_api function, given
# an improperly configured results_api due to an invalid property
results_api._app_id = test_constants.INVALID_RESULTS_API_INCORRECT_APP_ID[ # pylint: disable=protected-access
"app_id"
]
self.assertRaises(
ValueError,
utils.validate_api,
api=results_api,
)
# Fail when attempting to call the validate_api function, given
# an improperly configured upload_api due to an invalid property
upload_api._base_url = test_constants.INVALID_UPLOAD_API_MISSING_DOMAIN[ # pylint: disable=protected-access
"base_url"
]
self.assertRaises(
ValueError,
utils.validate_api,
api=upload_api,
)
## protocol_is_insecure tests
def test_protocol_is_insecure(self):
"""
Test the protocol_is_insecure function
"""
# protocol_is_insecure must be passed the protocol
self.assertRaises(TypeError, utils.protocol_is_insecure)
# http is insecure
output = utils.protocol_is_insecure(protocol="http")
self.assertTrue(output)
# https is secure
output = utils.protocol_is_insecure(protocol="https")
self.assertFalse(output)
## is_null tests
def test_is_null(self):
"""
Test the is_null function
"""
# is_null must be passed a value
self.assertRaises(TypeError, utils.is_null)
# Python's null equivalent is None
output = utils.is_null(value=None)
self.assertTrue(output)
# An empty string is not null
output = utils.is_null(value="")
self.assertFalse(output)
# A tuple is not null
output = utils.is_null(value=(1, "2"))
self.assertFalse(output)
# A dict is not null
output = utils.is_null(value={"a": {"Test": 123}})
self.assertFalse(output)
# An int is not null
output = utils.is_null(value=12321)
self.assertFalse(output)
# A string is not null
output = utils.is_null(value="thisisonlyatest")
self.assertFalse(output)
# A list is not null
output = utils.is_null(value=["a", "b", "c"])
self.assertFalse(output)
# A set is not null
output = utils.is_null(value={"1", 2})
self.assertFalse(output)
## is_valid_netloc tests
def test_is_valid_netloc(self):
"""
Test the is_valid_netloc function
"""
# Succeed when calling the is_valid_netloc function with a legal
# netloc, containing no subdomains
self.assertTrue(utils.is_valid_netloc(netloc="example.com"))
# Succeed when calling the is_valid_netloc function with a legal
# netloc, containing numerous subdomains
self.assertTrue(
utils.is_valid_netloc(netloc="i.love.to.use.subdomains.example.com")
)
# Succeed when calling the is_valid_netloc function with a legal netloc
# due to a 63 character (max valid length) subdomain
self.assertTrue(utils.is_valid_netloc(netloc="a" * 63 + ".example.com"))
# Succeed when calling the is_valid_netloc function with a valid
# port in the netloc
self.assertTrue(utils.is_valid_netloc(netloc="example.com:7"))
self.assertTrue(utils.is_valid_netloc(netloc="example.com:32"))
self.assertTrue(utils.is_valid_netloc(netloc="example.com:443"))
self.assertTrue(utils.is_valid_netloc(netloc="example.com:1234"))
self.assertTrue(utils.is_valid_netloc(netloc="example.com:54321"))
self.assertTrue(utils.is_valid_netloc(netloc="example.com:61423"))
self.assertTrue(utils.is_valid_netloc(netloc="example.com:65243"))
self.assertTrue(utils.is_valid_netloc(netloc="example.com:65512"))
self.assertTrue(utils.is_valid_netloc(netloc="example.com:65535"))
# Fail when calling the is_valid_netloc function with a legal netloc,
# containing no subdomains, but a user/pass specified in the url
self.assertFalse(utils.is_valid_netloc(netloc="user:pass@example.com"))
# Fail when attempting to call the is_valid_netloc function with an
# illegal netloc based on the characters used
self.assertFalse(utils.is_valid_netloc(netloc="$$"))
# Fail when attempting to call the is_valid_netloc function with an
# illegal netloc due to a 64 character (invalid) subdomain
self.assertFalse(utils.is_valid_netloc(netloc="a" * 64 + ".example.com"))
# Fail when attempting to call the is_valid_netloc function with a
# non-string value
self.assertFalse(utils.is_valid_netloc(netloc=12321))
# Fail when calling the is_valid_netloc function with an invalid port
# in the netloc
self.assertFalse(utils.is_valid_netloc(netloc="example.com:65536"))
# Fail when calling the is_valid_netloc function with an IPv4 address
# as the netloc, as it is not currently supported
self.assertFalse(utils.is_valid_netloc(netloc="192.0.2.1"))
self.assertFalse(utils.is_valid_netloc(netloc="192.0.2.1:443"))
self.assertFalse(utils.is_valid_netloc(netloc="user:pass@192.0.2.1"))
self.assertFalse(utils.is_valid_netloc(netloc="user:pass@192.0.2.1:443"))
# Fail when calling the is_valid_netloc function with a compressed IPv6
# address as the netloc, as it is not currently supported
self.assertFalse(utils.is_valid_netloc(netloc="2001:db8::1"))
self.assertFalse(utils.is_valid_netloc(netloc="2001:db8::1:443"))
self.assertFalse(utils.is_valid_netloc(netloc="user:pass@2001:db8::1"))
self.assertFalse(utils.is_valid_netloc(netloc="user:pass@2001:db8::1:443"))
self.assertFalse(utils.is_valid_netloc(netloc="[2001:db8::1]"))
self.assertFalse(utils.is_valid_netloc(netloc="[2001:db8::1]:443"))
self.assertFalse(utils.is_valid_netloc(netloc="user:pass@[2001:db8::1]"))
self.assertFalse(utils.is_valid_netloc(netloc="user:pass@[2001:db8::1]:443"))
# Fail when calling the is_valid_netloc function with an IPv6 address
# as the netloc, as it is not currently supported
self.assertFalse(utils.is_valid_netloc(netloc="2001:db8:0:0:0:0:0:1"))
self.assertFalse(utils.is_valid_netloc(netloc="2001:db8:0:0:0:0:0:1:443"))
self.assertFalse(utils.is_valid_netloc(netloc="user:pass@2001:db8:0:0:0:0:0:1"))
self.assertFalse(
utils.is_valid_netloc(netloc="user:pass@2001:db8:0:0:0:0:0:1:443")
)
self.assertFalse(utils.is_valid_netloc(netloc="[2001:db8:0:0:0:0:0:1]"))
self.assertFalse(utils.is_valid_netloc(netloc="[2001:db8:0:0:0:0:0:1]:443"))
self.assertFalse(
utils.is_valid_netloc(netloc="user:pass@[2001:db8:0:0:0:0:0:1]")
)
self.assertFalse(
utils.is_valid_netloc(netloc="user:pass@[2001:db8:0:0:0:0:0:1]:443")
)
| 38.558433 | 118 | 0.633769 | 7,193 | 61,038 | 5.095371 | 0.049354 | 0.045838 | 0.076396 | 0.031868 | 0.877821 | 0.866143 | 0.848135 | 0.819923 | 0.801888 | 0.754877 | 0 | 0.011422 | 0.29 | 61,038 | 1,582 | 119 | 38.582807 | 0.834299 | 0.274501 | 0 | 0.607477 | 0 | 0.002077 | 0.108584 | 0.042012 | 0.001038 | 0 | 0 | 0 | 0.156802 | 1 | 0.043614 | false | 0.013499 | 0.011423 | 0 | 0.056075 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
fbf2a6e95ef60b59625d9e6b5ed6494b48635b53 | 21,861 | py | Python | training/train.py | xhchrn/open_lth | 6b3d04a12a2f868ce851bd09b330ea57957c1de6 | [
"MIT"
] | null | null | null | training/train.py | xhchrn/open_lth | 6b3d04a12a2f868ce851bd09b330ea57957c1de6 | [
"MIT"
] | null | null | null | training/train.py | xhchrn/open_lth | 6b3d04a12a2f868ce851bd09b330ea57957c1de6 | [
"MIT"
] | null | null | null | # Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import typing
import warnings
import torch
from datasets.base import DataLoader
import datasets.registry
from foundations import hparams
from foundations import paths
from foundations.step import Step
from models.base import Model, DataParallel, DistributedDataParallel
import models.registry
from platforms.platform import get_platform
from training.checkpointing import restore_checkpoint
from training import optimizers
from training import standard_callbacks
from training.metric_logger import MetricLogger
try:
import apex
NO_APEX = False
except ImportError:
NO_APEX = True
def train(
training_hparams: hparams.TrainingHparams,
model: Model,
train_loader: DataLoader,
output_location: str,
callbacks: typing.List[typing.Callable] = [],
start_step: Step = None,
end_step: Step = None,
suffix: str = ''
):
"""The main training loop for this framework.
Args:
* training_hparams: The training hyperparameters whose schema is specified in hparams.py.
* model: The model to train. Must be a models.base.Model
* train_loader: The training data. Must be a datasets.base.DataLoader
* output_location: The string path where all outputs should be stored.
* callbacks: A list of functions that are called before each training step and once more
after the last training step. Each function takes five arguments: the current step,
the output location, the model, the optimizer, and the logger.
Callbacks are used for running the test set, saving the logger, saving the state of the
model, etc. The provide hooks into the training loop for customization so that the
training loop itself can remain simple.
* start_step: The step at which the training data and learning rate schedule should begin.
Defaults to step 0.
* end_step: The step at which training should cease. Otherwise, training will go for the
full `training_hparams.training_steps` steps.
"""
# Create the output location if it doesn't already exist.
if not get_platform().exists(output_location) and get_platform().is_primary_process:
get_platform().makedirs(output_location)
# Get the optimizer and learning rate schedule.
model.to(get_platform().torch_device)
optimizer = optimizers.get_optimizer(training_hparams, model)
if training_hparams.optimizer_name != 'bop':
step_optimizer = optimizer
fc_optimizer = None
else:
step_optimizer = optimizer[0]
fc_optimizer = optimizer[1]
lr_schedule = optimizers.get_lr_schedule(training_hparams,
optimizer if training_hparams.optimizer_name != 'bop' else fc_optimizer,
train_loader.iterations_per_epoch
)
# Adapt for FP16.
if training_hparams.apex_fp16:
if NO_APEX: raise ImportError('Must install nvidia apex to use this model.')
model, step_optimizer = apex.amp.initialize(model, step_optimizer, loss_scale='dynamic', verbosity=0)
# Handle parallelism if applicable.
if get_platform().is_distributed:
model = DistributedDataParallel(model, device_ids=[get_platform().rank])
elif get_platform().is_parallel:
model = DataParallel(model)
# Get the random seed for the data order.
data_order_seed = training_hparams.data_order_seed
# Restore the model from a saved checkpoint if the checkpoint exists.
cp_step, cp_logger = restore_checkpoint(output_location, model, step_optimizer, train_loader.iterations_per_epoch, suffix)
start_step = cp_step or start_step or Step.zero(train_loader.iterations_per_epoch)
logger = cp_logger or MetricLogger()
with warnings.catch_warnings(): # Filter unnecessary warning.
warnings.filterwarnings("ignore", category=UserWarning)
for _ in range(start_step.iteration): lr_schedule.step()
# Determine when to end training.
end_step = end_step or Step.from_str(training_hparams.training_steps, train_loader.iterations_per_epoch)
if end_step <= start_step: return
# The training loop.
for ep in range(start_step.ep, end_step.ep + 1):
# Ensure the data order is different for each epoch.
train_loader.shuffle(None if data_order_seed is None else (data_order_seed + ep))
for it, (examples, labels) in enumerate(train_loader):
# Advance the data loader until the start epoch and iteration.
if ep == start_step.ep and it < start_step.it: continue
# Run the callbacks.
step = Step.from_epoch(ep, it, train_loader.iterations_per_epoch)
for callback in callbacks: callback(output_location, step, model, step_optimizer, logger)
# Exit at the end step.
if ep == end_step.ep and it == end_step.it: return
# Otherwise, train.
examples = examples.to(device=get_platform().torch_device)
labels = labels.to(device=get_platform().torch_device)
step_optimizer.zero_grad()
if fc_optimizer:
fc_optimizer.zero_grad()
model.train()
loss = model.loss_criterion(model(examples), labels)
if training_hparams.apex_fp16:
with apex.amp.scale_loss(loss, step_optimizer) as scaled_loss:
scaled_loss.backward()
else:
loss.backward()
# Step forward. Ignore extraneous warnings that the lr_schedule generates.
step_optimizer.step()
if fc_optimizer:
fc_optimizer.step()
with warnings.catch_warnings(): # Filter unnecessary warning.
warnings.filterwarnings("ignore", category=UserWarning)
lr_schedule.step()
if training_hparams.optimizer_name == 'bop' and (ep + 1 - start_step.ep) % training_hparams.ar_decay_freq == 0:
step_optimizer.decay_ar(training_hparams.ar_decay_ratio)
get_platform().barrier()
def accumulate(
training_hparams: hparams.TrainingHparams,
model: Model,
train_loader: DataLoader,
data_order_seed: int = None,
suffix: str = ''
):
"""Accumulate the gradient for one training epoch.
Args:
* training_hparams: The training hyperparameters whose schema is specified in hparams.py.
* model: The model to train. Must be a models.base.Model
* train_loader: The training data. Must be a datasets.base.DataLoader
* data_order_seed: The RNG seed for data shuffling.
"""
# Adapt for FP16.
if training_hparams.apex_fp16:
if NO_APEX: raise ImportError('Must install nvidia apex to use this model.')
model = apex.amp.initialize(model, loss_scale='dynamic', verbosity=0)
# Handle parallelism if applicable.
if get_platform().is_distributed:
model = DistributedDataParallel(model, device_ids=[get_platform().rank])
elif get_platform().is_parallel:
model = DataParallel(model)
train_loader.shuffle(data_order_seed)
for it, (examples, labels) in enumerate(train_loader):
examples = examples.to(device=get_platform().torch_device)
labels = labels.to(device=get_platform().torch_device)
model.eval()
loss = model.loss_criterion(model(examples), labels)
if training_hparams.apex_fp16:
with apex.amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
else:
loss.backward()
get_platform().barrier()
def grasp(
training_hparams: hparams.TrainingHparams,
model: Model,
parameter_list: list,
train_loader: DataLoader,
data_order_seed: int = None,
suffix: str = ''
):
"""For the implementation of GraSP.
Args:
* training_hparams: The training hyperparameters whose schema is specified in hparams.py.
* model: The model to train. Must be a models.base.Model
* train_loader: The training data. Must be a datasets.base.DataLoader
* data_order_seed: The RNG seed for data shuffling.
"""
# Adapt for FP16.
if training_hparams.apex_fp16:
if NO_APEX: raise ImportError('Must install nvidia apex to use this model.')
model = apex.amp.initialize(model, loss_scale='dynamic', verbosity=0)
# Handle parallelism if applicable.
if get_platform().is_distributed:
model = DistributedDataParallel(model, device_ids=[get_platform().rank])
elif get_platform().is_parallel:
model = DataParallel(model)
train_loader.shuffle(data_order_seed)
# First gradient without computational graph
stopped_grads = 0
for it, (examples, labels) in enumerate(train_loader):
examples = examples.to(device=get_platform().torch_device)
labels = labels.to(device=get_platform().torch_device)
model.eval()
output = model(examples) / 200.0 # temp = 200
loss = model.loss_criterion(output, labels)
# if training_hparams.apex_fp16:
# with apex.amp.scale_loss(loss, optimizer) as scaled_loss:
# scaled_loss.backward()
# else:
# loss.backward()
grads = torch.autograd.grad(loss, parameter_list, create_graph=False)
flatten_grads = torch.cat([g.reshape(-1) for g in grads if g is not None])
stopped_grads += flatten_grads
train_loader.shuffle(None if data_order_seed is None else (data_order_seed + 1))
# Second gradient vector with computational graph
for it, (examples, labels) in enumerate(train_loader):
examples = examples.to(device=get_platform().torch_device)
labels = labels.to(device=get_platform().torch_device)
model.eval()
output = model(examples) / 200.0 # temp = 200
loss = model.loss_criterion(output, labels)
# if training_hparams.apex_fp16:
# with apex.amp.scale_loss(loss, optimizer) as scaled_loss:
# scaled_loss.backward()
# else:
# loss.backward()
grads = torch.autograd.grad(loss, parameter_list, create_graph=True)
flatten_grads = torch.cat([g.reshape(-1) for g in grads if g is not None])
gnorm = (stopped_grads * flatten_grads).sum()
gnorm.backward()
get_platform().barrier()
def distill(
training_hparams: hparams.TrainingHparams,
distill_hparams: hparams.DistillHparams,
student: Model,
teacher: Model,
train_loader: DataLoader,
output_location: str,
callbacks: typing.List[typing.Callable] = [],
start_step: Step = None,
end_step: Step = None
):
"""The main training loop for this framework.
Args:
* training_hparams: The training hyperparameters whose schema is specified in hparams.py.
* distll_hparams: The knowledge distillation hyperparameters whose schema is specified in hparams.py.
* student: The student model to train. Must be a models.base.Model
* teacher: The teacher model to distill the knowledge. Must be a models.base.Model
* train_loader: The training data. Must be a datasets.base.DataLoader
* output_location: The string path where all outputs should be stored.
* callbacks: A list of functions that are called before each training step and once more
after the last training step. Each function takes five arguments: the current step,
the output location, the model, the optimizer, and the logger.
Callbacks are used for running the test set, saving the logger, saving the state of the
model, etc. The provide hooks into the training loop for customization so that the
training loop itself can remain simple.
* start_step: The step at which the training data and learning rate schedule should begin.
Defaults to step 0.
* end_step: The step at which training should cease. Otherwise, training will go for the
full `training_hparams.training_steps` steps.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
# Create the output location if it doesn't already exist.
if not get_platform().exists(output_location) and get_platform().is_primary_process:
get_platform().makedirs(output_location)
# Get the optimizer and learning rate schedule.
student.to(get_platform().torch_device)
teacher.to(get_platform().torch_device)
optimizer = optimizers.get_optimizer(training_hparams, student)
step_optimizer = optimizer
lr_schedule = optimizers.get_lr_schedule(training_hparams, optimizer, train_loader.iterations_per_epoch)
ce_loss_fct = nn.KLDivLoss(reduction="batchmean")
if distill_hparams.alpha_mse > 0.0:
mse_loss_fct = nn.MSELoss(reduction='sum')
if distill_hparams.alpha_cos > 0.0:
cos_loss_fct = nn.CosineEmbeddingLoss(reduction='mean')
# Adapt for FP16.
if training_hparams.apex_fp16:
if NO_APEX: raise ImportError('Must install nvidia apex to use this model.')
(student, teacher), step_optimizer = apex.amp.initialize(
[student, teacher], optimizer, loss_scale='dynamic', verbosity=0
)
# Handle parallelism if applicable.
if get_platform().is_distributed:
student = DistributedDataParallel(student, device_ids=[get_platform().rank])
teacher = DistributedDataParallel(teacher, device_ids=[get_platform().rank])
elif get_platform().is_parallel:
student = DataParallel(student)
teacher = DataParallel(teacher)
# Get the random seed for the data order.
data_order_seed = training_hparams.data_order_seed
# Restore the model from a saved checkpoint if the checkpoint exists.
cp_step, cp_logger = restore_checkpoint(output_location, student, optimizer, train_loader.iterations_per_epoch)
start_step = cp_step or start_step or Step.zero(train_loader.iterations_per_epoch)
logger = cp_logger or MetricLogger()
with warnings.catch_warnings(): # Filter unnecessary warning.
warnings.filterwarnings("ignore", category=UserWarning)
for _ in range(start_step.iteration): lr_schedule.step()
# Determine when to end training.
end_step = end_step or Step.from_str(training_hparams.training_steps, train_loader.iterations_per_epoch)
if end_step <= start_step: return
# The training loop.
for ep in range(start_step.ep, end_step.ep + 1):
# Ensure the data order is different for each epoch.
train_loader.shuffle(None if data_order_seed is None else (data_order_seed + ep))
for it, (examples, labels) in enumerate(train_loader):
# Advance the data loader until the start epoch and iteration.
if ep == start_step.ep and it < start_step.it: continue
# Run the callbacks.
step = Step.from_epoch(ep, it, train_loader.iterations_per_epoch)
for callback in callbacks: callback(output_location, step, student, optimizer, logger)
# Exit at the end step.
if ep == end_step.ep and it == end_step.it: return
# Otherwise, train.
examples = examples.to(device=get_platform().torch_device)
labels = labels.to(device=get_platform().torch_device)
loss = 0.0
step_optimizer.zero_grad()
student.train()
teacher.eval()
student_outputs = student(examples)
with torch.no_grad():
teacher_outputs = teacher(examples)
s_logits = student_outputs
t_logits = teacher_outputs
# KL Divergence loss for the knowledge distillation
loss_ce = ce_loss_fct(
F.log_softmax(s_logits / distill_hparams.temperature, dim=-1),
F.softmax(t_logits / distill_hparams.temperature, dim=-1),
) * distill_hparams.temperature**2
loss += distill_hparams.alpha_ce * loss_ce
if distill_hparams.alpha_cls > 0.0:
loss_cls = student.loss_criterion(student_outputs, labels)
loss += distill_hparams.alpha_cls * loss_cls
if distill_hparams.alpha_mse > 0.0:
loss_mse = mse_loss_fct(s_logits, t_logits) / s_logits.size(0)
loss += distill_hparams.alpha_mse * loss_mse
if training_hparams.apex_fp16:
with apex.amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
else:
loss.backward()
# Step forward. Ignore extraneous warnings that the lr_schedule generates.
step_optimizer.step()
with warnings.catch_warnings(): # Filter unnecessary warning.
warnings.filterwarnings("ignore", category=UserWarning)
lr_schedule.step()
get_platform().barrier()
def standard_train(
model: Model,
output_location: str,
dataset_hparams: hparams.DatasetHparams,
training_hparams: hparams.TrainingHparams,
start_step: Step = None,
verbose: bool = True,
evaluate_every_epoch: bool = True,
suffix: str = ''
):
"""Train using the standard callbacks according to the provided hparams."""
# If the model file for the end of training already exists in this location, do not train.
iterations_per_epoch = datasets.registry.iterations_per_epoch(dataset_hparams)
train_end_step = Step.from_str(training_hparams.training_steps, iterations_per_epoch)
if (models.registry.exists(output_location, train_end_step) and
get_platform().exists(paths.logger(output_location))): return
train_loader = datasets.registry.get(dataset_hparams, train=True)
test_loader = datasets.registry.get(dataset_hparams, train=False)
callbacks = standard_callbacks.standard_callbacks(
training_hparams, train_loader, test_loader, start_step=start_step,
verbose=verbose, evaluate_every_epoch=evaluate_every_epoch, suffix=suffix)
train(training_hparams, model, train_loader, output_location, callbacks, start_step=start_step, suffix=suffix)
def accumulate_gradient(
training_hparams: hparams.TrainingHparams,
model: Model,
dataset_hparams: hparams.DatasetHparams,
data_order_seed: int = None,
verbose: bool = True,
suffix: str = ''
):
"""Train using the standard callbacks according to the provided hparams."""
# If the model file for the end of training already exists in this location, do not train.
iterations_per_epoch = datasets.registry.iterations_per_epoch(dataset_hparams)
# train_end_step = Step.from_str(training_hparams.training_steps, iterations_per_epoch)
# if (models.registry.exists(output_location, train_end_step) and
# get_platform().exists(paths.logger(output_location))): return
train_loader = datasets.registry.get(dataset_hparams, train=True)
test_loader = datasets.registry.get(dataset_hparams, train=False)
# callbacks = standard_callbacks.standard_callbacks(
# training_hparams, train_loader, test_loader, start_step=start_step,
# verbose=verbose, evaluate_every_epoch=evaluate_every_epoch, suffix=suffix)
accumulate(training_hparams, model, train_loader, data_order_seed, suffix=suffix)
def run_grasp(
training_hparams: hparams.TrainingHparams,
model: Model,
parameter_list: list,
dataset_hparams: hparams.DatasetHparams,
data_order_seed: int = None,
verbose: bool = True,
suffix: str = ''
):
"""Train using the standard callbacks according to the provided hparams."""
# If the model file for the end of training already exists in this location, do not train.
iterations_per_epoch = datasets.registry.iterations_per_epoch(dataset_hparams)
# train_end_step = Step.from_str(training_hparams.training_steps, iterations_per_epoch)
# if (models.registry.exists(output_location, train_end_step) and
# get_platform().exists(paths.logger(output_location))): return
train_loader = datasets.registry.get(dataset_hparams, train=True)
test_loader = datasets.registry.get(dataset_hparams, train=False)
# callbacks = standard_callbacks.standard_callbacks(
# training_hparams, train_loader, test_loader, start_step=start_step,
# verbose=verbose, evaluate_every_epoch=evaluate_every_epoch, suffix=suffix)
grasp(training_hparams, model, parameter_list, train_loader, data_order_seed, suffix=suffix)
def distill_train(
student: Model,
teacher: Model,
output_location: str,
dataset_hparams: hparams.DatasetHparams,
training_hparams: hparams.TrainingHparams,
distill_hparams: hparams.DistillHparams,
start_step: Step = None,
verbose: bool = True,
evaluate_every_epoch: bool = True,
suffix: str = ""
):
"""Train using the standard callbacks according to the provided hparams."""
# If the model file for the end of training already exists in this location, do not train.
iterations_per_epoch = datasets.registry.iterations_per_epoch(dataset_hparams)
train_end_step = Step.from_str(training_hparams.training_steps, iterations_per_epoch)
if (models.registry.exists(output_location, train_end_step) and
get_platform().exists(paths.logger(output_location))): return
train_loader = datasets.registry.get(dataset_hparams, train=True)
test_loader = datasets.registry.get(dataset_hparams, train=False)
callbacks = standard_callbacks.standard_callbacks(
training_hparams, train_loader, test_loader, start_step=start_step,
verbose=verbose, evaluate_every_epoch=evaluate_every_epoch, suffix=suffix)
distill(training_hparams, distill_hparams, student, teacher,
train_loader, output_location, callbacks, start_step=start_step)
| 41.719466 | 126 | 0.703719 | 2,778 | 21,861 | 5.331533 | 0.107631 | 0.048613 | 0.026737 | 0.01931 | 0.838228 | 0.822227 | 0.797988 | 0.794477 | 0.778746 | 0.755722 | 0 | 0.004091 | 0.217328 | 21,861 | 523 | 127 | 41.799235 | 0.861543 | 0.293674 | 0 | 0.678689 | 0 | 0 | 0.016443 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.02623 | false | 0 | 0.078689 | 0 | 0.104918 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
222c8ccf2b919a9adeb50ec01729cc72db5bd784 | 13,056 | py | Python | ws2812/effect.py | xil-se/esp8266 | eef6630d43052e994aed5a2b58364c56d896d448 | [
"MIT"
] | 2 | 2015-07-14T12:15:07.000Z | 2015-12-29T16:23:34.000Z | ws2812/effect.py | xil-se/esp8266 | eef6630d43052e994aed5a2b58364c56d896d448 | [
"MIT"
] | null | null | null | ws2812/effect.py | xil-se/esp8266 | eef6630d43052e994aed5a2b58364c56d896d448 | [
"MIT"
] | null | null | null | import socket
import time
import math
import serial
from colorsys import *
'''
This code is ugly and I know it.
- Konrad Beckmann
'''
W = 144
H = 8
BPP = 3
class Glyphs():
a = ([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00],
[ 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x36, 0x36, 0x7F, 0x36, 0x7F, 0x36, 0x36, 0x00],
[ 0x0C, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x0C, 0x00],
[ 0x00, 0x63, 0x33, 0x18, 0x0C, 0x66, 0x63, 0x00],
[ 0x1C, 0x36, 0x1C, 0x6E, 0x3B, 0x33, 0x6E, 0x00],
[ 0x06, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x18, 0x0C, 0x06, 0x06, 0x06, 0x0C, 0x18, 0x00],
[ 0x06, 0x0C, 0x18, 0x18, 0x18, 0x0C, 0x06, 0x00],
[ 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00],
[ 0x00, 0x0C, 0x0C, 0x3F, 0x0C, 0x0C, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x06],
[ 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x00],
[ 0x60, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x01, 0x00],
[ 0x3E, 0x63, 0x73, 0x7B, 0x6F, 0x67, 0x3E, 0x00],
[ 0x0C, 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x3F, 0x00],
[ 0x1E, 0x33, 0x30, 0x1C, 0x06, 0x33, 0x3F, 0x00],
[ 0x1E, 0x33, 0x30, 0x1C, 0x30, 0x33, 0x1E, 0x00],
[ 0x38, 0x3C, 0x36, 0x33, 0x7F, 0x30, 0x78, 0x00],
[ 0x3F, 0x03, 0x1F, 0x30, 0x30, 0x33, 0x1E, 0x00],
[ 0x1C, 0x06, 0x03, 0x1F, 0x33, 0x33, 0x1E, 0x00],
[ 0x3F, 0x33, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x00],
[ 0x1E, 0x33, 0x33, 0x1E, 0x33, 0x33, 0x1E, 0x00],
[ 0x1E, 0x33, 0x33, 0x3E, 0x30, 0x18, 0x0E, 0x00],
[ 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x00],
[ 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x06],
[ 0x18, 0x0C, 0x06, 0x03, 0x06, 0x0C, 0x18, 0x00],
[ 0x00, 0x00, 0x3F, 0x00, 0x00, 0x3F, 0x00, 0x00],
[ 0x06, 0x0C, 0x18, 0x30, 0x18, 0x0C, 0x06, 0x00],
[ 0x1E, 0x33, 0x30, 0x18, 0x0C, 0x00, 0x0C, 0x00],
[ 0x3E, 0x63, 0x7B, 0x7B, 0x7B, 0x03, 0x1E, 0x00],
[ 0x0C, 0x1E, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x00],
[ 0x3F, 0x66, 0x66, 0x3E, 0x66, 0x66, 0x3F, 0x00],
[ 0x3C, 0x66, 0x03, 0x03, 0x03, 0x66, 0x3C, 0x00],
[ 0x1F, 0x36, 0x66, 0x66, 0x66, 0x36, 0x1F, 0x00],
[ 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x46, 0x7F, 0x00],
[ 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x06, 0x0F, 0x00],
[ 0x3C, 0x66, 0x03, 0x03, 0x73, 0x66, 0x7C, 0x00],
[ 0x33, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x33, 0x00],
[ 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00],
[ 0x78, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E, 0x00],
[ 0x67, 0x66, 0x36, 0x1E, 0x36, 0x66, 0x67, 0x00],
[ 0x0F, 0x06, 0x06, 0x06, 0x46, 0x66, 0x7F, 0x00],
[ 0x63, 0x77, 0x7F, 0x7F, 0x6B, 0x63, 0x63, 0x00],
[ 0x63, 0x67, 0x6F, 0x7B, 0x73, 0x63, 0x63, 0x00],
[ 0x1C, 0x36, 0x63, 0x63, 0x63, 0x36, 0x1C, 0x00],
[ 0x3F, 0x66, 0x66, 0x3E, 0x06, 0x06, 0x0F, 0x00],
[ 0x1E, 0x33, 0x33, 0x33, 0x3B, 0x1E, 0x38, 0x00],
[ 0x3F, 0x66, 0x66, 0x3E, 0x36, 0x66, 0x67, 0x00],
[ 0x1E, 0x33, 0x07, 0x0E, 0x38, 0x33, 0x1E, 0x00],
[ 0x3F, 0x2D, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00],
[ 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x3F, 0x00],
[ 0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00],
[ 0x63, 0x63, 0x63, 0x6B, 0x7F, 0x77, 0x63, 0x00],
[ 0x63, 0x63, 0x36, 0x1C, 0x1C, 0x36, 0x63, 0x00],
[ 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x0C, 0x1E, 0x00],
[ 0x7F, 0x63, 0x31, 0x18, 0x4C, 0x66, 0x7F, 0x00],
[ 0x1E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x1E, 0x00],
[ 0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x40, 0x00],
[ 0x1E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1E, 0x00],
[ 0x08, 0x1C, 0x36, 0x63, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF],
[ 0x0C, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x1E, 0x30, 0x3E, 0x33, 0x6E, 0x00],
[ 0x07, 0x06, 0x06, 0x3E, 0x66, 0x66, 0x3B, 0x00],
[ 0x00, 0x00, 0x1E, 0x33, 0x03, 0x33, 0x1E, 0x00],
[ 0x38, 0x30, 0x30, 0x3e, 0x33, 0x33, 0x6E, 0x00],
[ 0x00, 0x00, 0x1E, 0x33, 0x3f, 0x03, 0x1E, 0x00],
[ 0x1C, 0x36, 0x06, 0x0f, 0x06, 0x06, 0x0F, 0x00],
[ 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x1F],
[ 0x07, 0x06, 0x36, 0x6E, 0x66, 0x66, 0x67, 0x00],
[ 0x0C, 0x00, 0x0E, 0x0C, 0x0C, 0x0C, 0x1E, 0x00],
[ 0x30, 0x00, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E],
[ 0x07, 0x06, 0x66, 0x36, 0x1E, 0x36, 0x67, 0x00],
[ 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00],
[ 0x00, 0x00, 0x33, 0x7F, 0x7F, 0x6B, 0x63, 0x00],
[ 0x00, 0x00, 0x1F, 0x33, 0x33, 0x33, 0x33, 0x00],
[ 0x00, 0x00, 0x1E, 0x33, 0x33, 0x33, 0x1E, 0x00],
[ 0x00, 0x00, 0x3B, 0x66, 0x66, 0x3E, 0x06, 0x0F],
[ 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x78],
[ 0x00, 0x00, 0x3B, 0x6E, 0x66, 0x06, 0x0F, 0x00],
[ 0x00, 0x00, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x00],
[ 0x08, 0x0C, 0x3E, 0x0C, 0x0C, 0x2C, 0x18, 0x00],
[ 0x00, 0x00, 0x33, 0x33, 0x33, 0x33, 0x6E, 0x00],
[ 0x00, 0x00, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00],
[ 0x00, 0x00, 0x63, 0x6B, 0x7F, 0x7F, 0x36, 0x00],
[ 0x00, 0x00, 0x63, 0x36, 0x1C, 0x36, 0x63, 0x00],
[ 0x00, 0x00, 0x33, 0x33, 0x33, 0x3E, 0x30, 0x1F],
[ 0x00, 0x00, 0x3F, 0x19, 0x0C, 0x26, 0x3F, 0x00],
[ 0x38, 0x0C, 0x0C, 0x07, 0x0C, 0x0C, 0x38, 0x00],
[ 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00],
[ 0x07, 0x0C, 0x0C, 0x38, 0x0C, 0x0C, 0x07, 0x00],
[ 0x6E, 0x3B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
[ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
def render(self, code):
c = self.a[code]
out = []
for x in range(0,8):
tmp = []
for y in range(0,8):
set = c[x] & 1 << y;
if set:
tmp.append(1)
else:
tmp.append(0)
out.append(tmp)
return out
class Foo():
def __init__(self):
self.i = 0
self.glyphs = Glyphs()
def clamp(self, x, a, b):
return max(min(x, b), a)
def setpixel(self, buf, x, y, rgb):
if x < 0 or x > 143: return
if y < 0 or y > 7: return
oldx=x
if y % 2 == 1: x = W - 1 - x
try:
buf[x*BPP + W*BPP*y] = int(rgb[1])
buf[x*BPP + W*BPP*y + 1] = int(rgb[0])
buf[x*BPP + W*BPP*y + 2] = int(rgb[2])
except:
print oldx, y, rgb
def lissajous(self, A, a, B, b, x0, y0, delta, t):
x = x0 + A * math.sin(a * t + delta)
y = y0 + B * math.sin(b * t)
return (x, y)
def render_lissajous(self, buf, u, v, A, a, B, b, x0, y0, delta, t, intensity):
(x, y) = self.lissajous(A + v, a, B + v, b, u, 4, self.i / 10.0, self.i / 10.0 + t/100.0)
(r, g, b) = hsv_to_rgb(t / 100.0, 1.0, 1.0)
r = int(r*64 * intensity)
g = int(g*64 * intensity)
b = int(b*64 * intensity)
if y >= 0 and y < H:
self.setpixel(buf, self.clamp(int(x + 70), 0, W - 1), self.clamp(int(y), 0, 7), (r, g, b))
def render_curves(self, buf):
i = self.i
u1 = 40 * math.sin(i / 10.0 + math.pi)
u2 = 40 * math.sin(i / 10.0)
v1 = 2.5 * math.sin(i / 10.0 + 3 * math.pi / 2)
v2 = 2.5 * math.sin(i / 10.0 + math.pi / 2)
i1 = v1 / 6 + 1
i2 = v2 / 6 + 1
if v1 < 0:
for t in range(0, 300):
self.render_lissajous(buf, u1, v1, 20, 6, 4, 6, u1, 4, 0, t, i1)
for t in range(0, 300):
self.render_lissajous(buf, u2, v2, 20, 3, 4, 6, u2, 4, 0, t, i2)
else:
for t in range(0, 300):
self.render_lissajous(buf, u2, v2, 20, 3, 4, 6, u2, 4, 0, t, i2)
for t in range(0, 300):
self.render_lissajous(buf, u1, v1, 20, 6, 4, 6, u1, 4, 0, t, i1)
def render_background(self, buf):
for y in range(0, H):
for x in range(0, W):
self.setpixel(buf, x, y, self.funky(x, y))
def funky(self, x, y):
x = (x + int(30 * math.sin((self.i+y) / 3.0))) % W
h = math.fmod((x + 30 * (1.0 + math.sin(self.i / 5.0))) / W, 1.0)
rgb = hsv_to_rgb(h, 1.0, 1.0)
v = (math.sin(self.i / 3.0) + 1.0) + 1.5
r = rgb[0] * 2.0 * v
g = rgb[1] * 2.0 * v
b = rgb[2] * 2.0 * v
return (int(r), int(g), int(b))
def render_text(self, data, offset_x, offset_y, text):
a = -1
for c in text:
a = a + 1
foo = self.glyphs.render(ord(c))
i = -1
for y in foo:
i = i + 1
j = -1
for x in y:
j = j + 1
if x > 0:
#rgb = (255, 255, 255)
rgb = (16, 16, 0)
self.setpixel(data, j + a * 8 + offset_x, i + offset_y, rgb)
def udp(self):
UDP_IP = "192.168.5.10"
UDP_PORT = 8888
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
xxx = 0
while True:
self.i = (self.i + 1)
data = bytearray(W * H * BPP)
self.render_background(data)
#self.render_curves(data)
#self.render_text(data, xxx, 0, " >_ xil.se abcdefghijklmnopqrstuvwxyz")
text = str(int(round(time.time() * 1000)))
self.render_text(data, xxx, 0, text)
sock.sendto("\x01" + bytes(data[0:1458]), (UDP_IP, UDP_PORT))
sock.sendto("\x02" + bytes(data[1458:1458*2]), (UDP_IP, UDP_PORT))
sock.sendto("\x03" + bytes(data[1458*2:]), (UDP_IP, UDP_PORT))
# time.sleep(0.1)
def main(self):
print("FOO!")
ser = serial.Serial('/dev/ttyUSB0', timeout=0.5)
ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
ser.write("dofile(\"uart.lua\")\n")
time.sleep(2)
#ser.baudrate = 115200
ser.baudrate = 9600
xxx = 0
while True:
print("frame")
self.i = (self.i + 1)
data = bytearray(W * H * BPP)
#self.render_background(data)
#self.render_curves(data)
#self.render_text(data, xxx, 0, " >_ xil.se abcdefghijklmnopqrstuvwxyz")
#text = str(int(round(time.time() * 1000)))
#self.render_text(data, xxx, 0, text)
self.render_text(data, 0, 0, "A")
ser.write(data)
time.sleep(0.01)
ser.close()
if __name__ == "__main__":
while True:
try:
Foo().udp()
#Foo().main()
#main()
except KeyboardInterrupt:
break
except Exception as e:
print e
pass
| 40.672897 | 102 | 0.509344 | 1,867 | 13,056 | 3.534547 | 0.113016 | 0.434005 | 0.587362 | 0.724958 | 0.48371 | 0.406728 | 0.31626 | 0.287619 | 0.283376 | 0.271253 | 0 | 0.356124 | 0.328968 | 13,056 | 320 | 103 | 40.8 | 0.397101 | 0.034314 | 0 | 0.206767 | 0 | 0 | 0.005189 | 0 | 0 | 0 | 0.327 | 0 | 0 | 0 | null | null | 0.003759 | 0.018797 | null | null | 0.015038 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
227bc2784805a4847a0bb9e6e5ddcdb10709bcf4 | 302 | py | Python | arch_params/__init__.py | zhjpqq/scaledensenet | 5ae56786c7f628b8320b76d559ecaa6fa1d2ac0e | [
"MIT"
] | 5 | 2019-08-27T20:15:05.000Z | 2021-01-18T08:21:37.000Z | arch_params/__init__.py | zhjpqq/scaledensenet | 5ae56786c7f628b8320b76d559ecaa6fa1d2ac0e | [
"MIT"
] | null | null | null | arch_params/__init__.py | zhjpqq/scaledensenet | 5ae56786c7f628b8320b76d559ecaa6fa1d2ac0e | [
"MIT"
] | 2 | 2020-03-12T04:41:49.000Z | 2020-10-11T08:32:34.000Z |
from .res_dense_fish_mobile_hrnet import *
from .github_imagenet_archs import *
from .scalenet_imagenet_archs import *
from .scalenet_cifar_archs import *
from .msnet_imagenet_archs import *
from .vivo_cifar10_archs import *
from .srnet_imagenet_archs import *
from .actres_cifar_archs import * | 18.875 | 42 | 0.817881 | 42 | 302 | 5.452381 | 0.404762 | 0.305677 | 0.393013 | 0.401747 | 0.270742 | 0 | 0 | 0 | 0 | 0 | 0 | 0.007605 | 0.129139 | 302 | 16 | 43 | 18.875 | 0.863118 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
3f050895795755c99d8c87e00c9c757b4a2b6986 | 635 | py | Python | src/infi/rpc/base/utils.py | Infinidat/infi.rpc | 8d7e7357193582a7cfd59afd0d1dfb745738a6ce | [
"BSD-3-Clause"
] | 2 | 2017-04-29T16:35:45.000Z | 2017-04-29T16:40:16.000Z | src/infi/rpc/base/utils.py | Infinidat/infi.rpc | 8d7e7357193582a7cfd59afd0d1dfb745738a6ce | [
"BSD-3-Clause"
] | null | null | null | src/infi/rpc/base/utils.py | Infinidat/infi.rpc | 8d7e7357193582a7cfd59afd0d1dfb745738a6ce | [
"BSD-3-Clause"
] | null | null | null | from logbook import Logger
logger = Logger('infi.rpc')
class SelfLoggerMixin(object):
def log_debug(self, format, *args, **kwargs):
self.get_logger().debug("{} {}".format(self, format), *args, **kwargs)
def log_error(self, format, *args, **kwargs):
self.get_logger().error("{} {}".format(self, format), *args, **kwargs)
def log_exception(self, format, *args, **kwargs):
self.get_logger().exception("{} {}".format(self, format), *args, **kwargs)
def get_logger(self):
return logger
def format_request(method, args, kwargs):
return "{}(*{}, **{})".format(method, args, kwargs)
| 28.863636 | 82 | 0.625197 | 76 | 635 | 5.118421 | 0.289474 | 0.205656 | 0.215938 | 0.308483 | 0.493573 | 0.493573 | 0.419023 | 0 | 0 | 0 | 0 | 0 | 0.176378 | 635 | 21 | 83 | 30.238095 | 0.743786 | 0 | 0 | 0 | 0 | 0 | 0.056693 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.384615 | false | 0 | 0.076923 | 0.153846 | 0.692308 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 6 |
3f16edda9156c0643d2bb59d52c0cb605da264e4 | 2,067 | py | Python | tests/common/test_import.py | jungtaekkim/bayeso | d11c9ff8037cf7fd3f9b41362eaab120f1224c71 | [
"MIT"
] | 76 | 2018-01-18T03:03:14.000Z | 2022-02-07T06:41:41.000Z | tests/common/test_import.py | POSTECH-CVLab/bayeso | d11c9ff8037cf7fd3f9b41362eaab120f1224c71 | [
"MIT"
] | 20 | 2018-06-29T16:48:03.000Z | 2021-04-19T00:30:57.000Z | tests/common/test_import.py | POSTECH-CVLab/bayeso | d11c9ff8037cf7fd3f9b41362eaab120f1224c71 | [
"MIT"
] | 4 | 2020-01-07T06:24:17.000Z | 2021-06-11T06:21:42.000Z | #
# author: Jungtaek Kim (jtkim@postech.ac.kr)
# last updated: August 6, 2021
#
"""test_import"""
def test_import_bayeso():
import bayeso
def test_import_bo():
import bayeso.bo
def test_import_bo_bo_w_gp():
import bayeso.bo.bo_w_gp
def test_import_bo_bo_w_tp():
import bayeso.bo.bo_w_tp
def test_import_bo_bo_w_trees():
import bayeso.bo.bo_w_trees
def test_import_covariance():
import bayeso.covariance
def test_import_acquisition():
import bayeso.acquisition
def test_import_constants():
import bayeso.constants
def test_import_gp():
import bayeso.gp
def test_import_gp_gp():
import bayeso.gp.gp
def test_import_gp_gp_kernel():
import bayeso.gp.gp_kernel
def test_import_gp_gp_likelihood():
import bayeso.gp.gp_likelihood
def test_import_tp():
import bayeso.tp
def test_import_tp_tp():
import bayeso.tp.tp
def test_import_tp_tp_kernel():
import bayeso.tp.tp_kernel
def test_import_tp_tp_likelihood():
import bayeso.tp.tp_likelihood
def test_import_trees():
import bayeso.trees
def test_import_trees_trees_common():
import bayeso.trees.trees_common
def test_import_trees_trees_generic_trees():
import bayeso.trees.trees_generic_trees
def test_import_trees_trees_random_forest():
import bayeso.trees.trees_random_forest
def test_import_utils():
import bayeso.utils
def test_import_utils_utils_bo():
import bayeso.utils.utils_bo
def test_import_utils_utils_gp():
import bayeso.utils.utils_gp
def test_import_utils_utils_common():
import bayeso.utils.utils_common
def test_import_utils_utils_covariance():
import bayeso.utils.utils_covariance
def test_import_utils_utils_plotting():
import bayeso.utils.utils_plotting
def test_import_utils_utils_logger():
import bayeso.utils.utils_logger
def test_import_wrappers():
import bayeso.wrappers
def test_import_wrappers_wrappers_bo_function():
import bayeso.wrappers.wrappers_bo_function
def test_import_wrappers_wrappers_bo_class():
import bayeso.wrappers.wrappers_bo_class
| 21.53125 | 48 | 0.786647 | 313 | 2,067 | 4.776358 | 0.115016 | 0.207358 | 0.26087 | 0.084281 | 0.370569 | 0.165886 | 0 | 0 | 0 | 0 | 0 | 0.002804 | 0.137397 | 2,067 | 95 | 49 | 21.757895 | 0.83567 | 0.040639 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.5 | true | 0 | 1 | 0 | 1.5 | 0 | 0 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
3f308f5eec2db7f433069c27b449b9eafec01b53 | 156 | py | Python | monopyly/utility/__init__.py | YSabarad/monopyly | 0460f2452c83846b6b9e3b234be411e12a86d69c | [
"MIT"
] | 4 | 2015-11-04T21:18:40.000Z | 2020-12-26T21:15:23.000Z | monopyly/utility/__init__.py | YSabarad/monopyly | 0460f2452c83846b6b9e3b234be411e12a86d69c | [
"MIT"
] | 2 | 2021-08-09T18:19:58.000Z | 2021-08-10T14:44:54.000Z | monopyly/utility/__init__.py | YSabarad/monopyly | 0460f2452c83846b6b9e3b234be411e12a86d69c | [
"MIT"
] | 6 | 2015-08-01T17:54:17.000Z | 2022-02-28T00:00:21.000Z | from .logger import Logger
from .console_log_handler import ConsoleLogHandler
from .file_log_handler import FileLogHandler
from .ai_loader import load_ais
| 26 | 50 | 0.865385 | 22 | 156 | 5.863636 | 0.590909 | 0.155039 | 0.248062 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.108974 | 156 | 5 | 51 | 31.2 | 0.928058 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
3f3519189080233e58b8db4e7c7229912a4b1273 | 34 | py | Python | pySPIRALTAP/__init__.py | MaximeMaW/pySPIRALTAP | e83d70cc3dab3a567377fe105d29f0878f5539ee | [
"MIT"
] | 5 | 2017-06-10T20:25:19.000Z | 2019-04-12T10:38:34.000Z | pySPIRALTAP/__init__.py | MaximeMaW/pySPIRALTAP | e83d70cc3dab3a567377fe105d29f0878f5539ee | [
"MIT"
] | null | null | null | pySPIRALTAP/__init__.py | MaximeMaW/pySPIRALTAP | e83d70cc3dab3a567377fe105d29f0878f5539ee | [
"MIT"
] | 4 | 2017-04-14T21:24:04.000Z | 2019-11-13T07:03:19.000Z | from pySPIRALTAP import SPIRALTAP
| 17 | 33 | 0.882353 | 4 | 34 | 7.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.117647 | 34 | 1 | 34 | 34 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
3f59de8b07ff28444a9fa59cc8832ddbb9487e71 | 375 | py | Python | src/tsgettoolbox/ulmo/twc/kbdi/__init__.py | timcera/tsgettoolbox | 828306aefaa097a74abd8e71605bd19eeda29058 | [
"BSD-3-Clause"
] | 4 | 2017-11-21T20:22:47.000Z | 2021-09-27T13:27:05.000Z | src/tsgettoolbox/ulmo/twc/kbdi/__init__.py | timcera/tsgettoolbox | 828306aefaa097a74abd8e71605bd19eeda29058 | [
"BSD-3-Clause"
] | 21 | 2016-04-28T16:52:18.000Z | 2021-12-16T17:00:27.000Z | src/tsgettoolbox/ulmo/twc/kbdi/__init__.py | timcera/tsgettoolbox | 828306aefaa097a74abd8e71605bd19eeda29058 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
"""
ulmo.twc.kbdi.core
~~~~~~~~~~~~~~~~~~~~~
This module provides direct access to `Texas Weather Connection`_ -
`Daily Keetch-Byram Drought Index (KBDI)`_ dataset.
.. _Texas Weather Connection: http://twc.tamu.edu/
.. _Daily Keetch-Byram Drought Index (KBDI): http://twc.tamu.edu/drought/kbdi
"""
from .core import get_data
| 28.846154 | 81 | 0.632 | 47 | 375 | 4.93617 | 0.617021 | 0.103448 | 0.189655 | 0.198276 | 0.275862 | 0.275862 | 0 | 0 | 0 | 0 | 0 | 0.003247 | 0.178667 | 375 | 12 | 82 | 31.25 | 0.75 | 0.837333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
58ab078ba5c3ac6491ecdbdc0262477ccfa8b4d4 | 77 | py | Python | tests/test_cli_config_manager.py | ryohare/python-cli-config-manager | 55759115bd2fd8ab63307bc7f147d7b923b2f86f | [
"BSD-2-Clause"
] | null | null | null | tests/test_cli_config_manager.py | ryohare/python-cli-config-manager | 55759115bd2fd8ab63307bc7f147d7b923b2f86f | [
"BSD-2-Clause"
] | null | null | null | tests/test_cli_config_manager.py | ryohare/python-cli-config-manager | 55759115bd2fd8ab63307bc7f147d7b923b2f86f | [
"BSD-2-Clause"
] | null | null | null |
from cli_config_manager import Config
def test_main():
Config("test")
| 11 | 37 | 0.727273 | 11 | 77 | 4.818182 | 0.727273 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.181818 | 77 | 6 | 38 | 12.833333 | 0.84127 | 0 | 0 | 0 | 0 | 0 | 0.052632 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | true | 0 | 0.333333 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
58e7ff9cc80693bd0cafcb12bf6d227ef265bebf | 196 | py | Python | lg_media/src/lg_media/__init__.py | carlosvquezada/lg_ros_nodes | 7560e99272d06ef5c80a5444131dad72c078a718 | [
"Apache-2.0"
] | null | null | null | lg_media/src/lg_media/__init__.py | carlosvquezada/lg_ros_nodes | 7560e99272d06ef5c80a5444131dad72c078a718 | [
"Apache-2.0"
] | null | null | null | lg_media/src/lg_media/__init__.py | carlosvquezada/lg_ros_nodes | 7560e99272d06ef5c80a5444131dad72c078a718 | [
"Apache-2.0"
] | null | null | null | from mplayer_pool import MplayerPool
from mplayer_pool import ManagedMplayer
from director_media_bridge import DirectorMediaBridge
from mplayer_pool import DEFAULT_ARGS, SRV_QUERY, ROS_NODE_NAME
| 32.666667 | 63 | 0.892857 | 27 | 196 | 6.148148 | 0.62963 | 0.198795 | 0.271084 | 0.379518 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.096939 | 196 | 5 | 64 | 39.2 | 0.937853 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 6 |
58ed54ba36faa0da9cc53c60452bcd93446685ea | 11,283 | py | Python | example/blog/tests/test_permissions.py | timgates42/django-admin2 | 08867d7e139623711099f2e6bf5f7b6b8211278d | [
"BSD-3-Clause"
] | 330 | 2016-06-07T23:08:19.000Z | 2022-03-23T23:36:41.000Z | example/blog/tests/test_permissions.py | timgates42/django-admin2 | 08867d7e139623711099f2e6bf5f7b6b8211278d | [
"BSD-3-Clause"
] | 48 | 2016-06-08T03:04:31.000Z | 2021-10-21T13:27:57.000Z | example/blog/tests/test_permissions.py | timgates42/django-admin2 | 08867d7e139623711099f2e6bf5f7b6b8211278d | [
"BSD-3-Clause"
] | 47 | 2016-06-08T03:06:34.000Z | 2022-03-10T07:53:29.000Z | from blog.models import Post
from django.contrib.auth.models import User, Permission
from django.shortcuts import get_object_or_404
from django.template import Template, Context
from django.test import TestCase
from django.test.client import RequestFactory
from django.urls import reverse
from djadmin2.permissions import TemplatePermissionChecker
from djadmin2.site import djadmin2_site
from djadmin2.types import ModelAdmin2
class TemplatePermissionTest(TestCase):
def setUp(self):
self.factory = RequestFactory()
self.user = User(
username='admin',
is_staff=True)
self.user.set_password('admin')
self.user.save()
def render(self, template, context):
template = Template(template)
context = Context(context)
return template.render(context)
def test_permission_wrapper(self):
model_admin = ModelAdmin2(Post, djadmin2_site)
request = self.factory.get(reverse('admin2:blog_post_index'))
request.user = self.user
permissions = TemplatePermissionChecker(request, model_admin)
context = {
'permissions': permissions,
}
result = self.render(
'{{ permissions.has_unvalid_permission }}',
context)
self.assertEqual(result, '')
result = self.render('{{ permissions.has_add_permission }}', context)
self.assertEqual(result, 'False')
post_add_permission = Permission.objects.get(
content_type__app_label='blog',
content_type__model='post',
codename='add_post')
self.user.user_permissions.add(post_add_permission)
# invalidate the users permission cache
self.user = get_object_or_404(User, pk=self.user.id)
request.user = self.user
result = self.render('{{ permissions.has_add_permission }}', context)
self.assertEqual(result, 'True')
def test_admin_traversal_by_name(self):
post_add_permission = Permission.objects.get(
content_type__app_label='blog',
content_type__model='post',
codename='add_post')
self.user.user_permissions.add(post_add_permission)
model_admin = ModelAdmin2(Post, djadmin2_site)
request = self.factory.get(reverse('admin2:blog_post_index'))
request.user = self.user
permissions = TemplatePermissionChecker(request, model_admin)
context = {
'permissions': permissions,
}
result = self.render('{{ permissions.has_add_permission }}', context)
self.assertEqual(result, 'True')
result = self.render(
'{{ permissions.blog_post.has_add_permission }}', context)
self.assertEqual(result, 'True')
result = self.render(
'{{ permissions.blog_post.has_change_permission }}', context)
self.assertEqual(result, 'False')
result = self.render(
'{{ permissions.auth_user.has_delete_permission }}', context)
self.assertEqual(result, 'False')
result = self.render(
'{{ permissions.unknown_app.has_add_permission }}',
context)
self.assertEqual(result, '')
result = self.render(
'{{ permissions.blog_post.has_unvalid_permission }}',
context)
self.assertEqual(result, '')
def test_admin_binding(self):
user_admin = djadmin2_site.get_admin_by_name('auth_user')
post_admin = djadmin2_site.get_admin_by_name('blog_post')
request = self.factory.get(reverse('admin2:auth_user_index'))
request.user = self.user
permissions = TemplatePermissionChecker(request, user_admin)
post = Post.objects.create(title='Hello', body='world')
context = {
'post': post,
'post_admin': post_admin,
'permissions': permissions,
}
result = self.render(
'{% load admin2_tags %}'
'{{ permissions|for_admin:post_admin }}',
context)
self.assertEqual(result, '')
result = self.render(
'{% load admin2_tags %}'
'{{ permissions.has_add_permission }}'
'{% with permissions|for_admin:post_admin as permissions %}'
'{{ permissions.has_add_permission }}'
'{% endwith %}',
context)
self.assertEqual(result, 'FalseFalse')
post_add_permission = Permission.objects.get(
content_type__app_label='blog',
content_type__model='post',
codename='add_post')
self.user.user_permissions.add(post_add_permission)
# invalidate the users permission cache
self.user = get_object_or_404(User, pk=self.user.id)
request.user = self.user
result = self.render(
'{% load admin2_tags %}'
'{{ permissions.has_add_permission }}'
'{% with permissions|for_admin:post_admin as permissions %}'
'{{ permissions.has_add_permission }}'
'{% endwith %}'
'{{ permissions.blog_post.has_add_permission }}',
context)
self.assertEqual(result, 'FalseTrueTrue')
# giving a string (the name of the admin) also works
result = self.render(
'{% load admin2_tags %}'
'{% with permissions|for_admin:"blog_post" as permissions %}'
'{{ permissions.has_add_permission }}'
'{% endwith %}',
context)
self.assertEqual(result, 'True')
# testing invalid admin names
result = self.render(
'{% load admin2_tags %}'
'{% with permissions|for_admin:"invalid_admin_name" as permissions %}'
'{{ permissions.has_add_permission }}'
'{% endwith %}',
context)
self.assertEqual(result, '')
def test_view_binding(self):
user_admin = djadmin2_site.get_admin_by_name('auth_user')
post_admin = djadmin2_site.get_admin_by_name('blog_post')
request = self.factory.get(reverse('admin2:auth_user_index'))
request.user = self.user
permissions = TemplatePermissionChecker(request, user_admin)
context = {
'post_admin': post_admin,
'post_add_view': post_admin.create_view,
'permissions': permissions,
}
result = self.render(
'{% load admin2_tags %}'
'{{ permissions|for_view:"add" }}',
context)
self.assertEqual(result, 'False')
# view classes are not supported yet
result = self.render(
'{% load admin2_tags %}'
'{{ permissions|for_view:post_add_view }}',
context)
self.assertEqual(result, '')
result = self.render(
'{% load admin2_tags %}'
# user add permission
'{{ permissions.has_add_permission }}'
'{% with permissions|for_admin:"blog_post"|for_view:"add" as post_add_perm %}'
# post add permission
'{{ post_add_perm }}'
'{% endwith %}',
context)
self.assertEqual(result, 'FalseFalse')
post_add_permission = Permission.objects.get(
content_type__app_label='blog',
content_type__model='post',
codename='add_post')
self.user.user_permissions.add(post_add_permission)
user_change_permission = Permission.objects.get(
content_type__app_label='auth',
content_type__model='user',
codename='change_user')
self.user.user_permissions.add(user_change_permission)
# invalidate the users permission cache
self.user = get_object_or_404(User, pk=self.user.id)
request.user = self.user
result = self.render(
'{% load admin2_tags %}'
# user add permission
'{{ permissions.has_add_permission }}'
'{% with permissions|for_admin:"blog_post"|for_view:"add" as post_add_perm %}'
# post add permission
'{{ post_add_perm }}'
'{% endwith %}'
# user change permission
'{{ permissions|for_view:"change" }}',
context)
self.assertEqual(result, 'FalseTrueTrue')
# giving a string (the name of the view) also works
result = self.render(
'{% load admin2_tags %}'
'{% with permissions|for_view:"change" as user_change_perm %}'
'1{{ user_change_perm }}'
'2{{ user_change_perm|for_view:"add" }}'
# this shouldn't return True or False but '' since the
# previously bound change view doesn't belong to the newly
# bound blog_post admin
'3{{ user_change_perm|for_admin:"blog_post" }}'
'4{{ user_change_perm|for_admin:"blog_post"|for_view:"add" }}'
'{% endwith %}',
context)
self.assertEqual(result, '1True2False34True')
def test_object_level_permission(self):
model_admin = ModelAdmin2(Post, djadmin2_site)
request = self.factory.get(reverse('admin2:blog_post_index'))
request.user = self.user
permissions = TemplatePermissionChecker(request, model_admin)
post = Post.objects.create(title='Hello', body='world')
context = {
'post': post,
'permissions': permissions,
}
result = self.render(
'{% load admin2_tags %}'
'{{ permissions.has_unvalid_permission|for_object:post }}',
context)
self.assertEqual(result, '')
result = self.render(
'{% load admin2_tags %}'
'{{ permissions.has_add_permission|for_object:post }}',
context)
self.assertEqual(result, 'False')
post_add_permission = Permission.objects.get(
content_type__app_label='blog',
content_type__model='post',
codename='add_post')
self.user.user_permissions.add(post_add_permission)
# invalidate the users permission cache
self.user = get_object_or_404(User, pk=self.user.id)
request.user = self.user
# object level permission are not supported by default. So this will
# return ``False``.
result = self.render(
'{% load admin2_tags %}'
'{{ permissions.has_add_permission }}'
'{{ permissions.has_add_permission|for_object:post }}',
context)
self.assertEqual(result, 'TrueFalse')
# binding an object and then checking for a specific view also works
result = self.render(
'{% load admin2_tags %}'
'{{ permissions.has_add_permission }}'
'{% with permissions|for_object:post as permissions %}'
'{{ permissions.has_add_permission }}'
'{% endwith %}',
context)
self.assertEqual(result, 'TrueFalse')
class ViewPermissionTest(TestCase):
def test_view_permission_was_created(self):
permissions = Permission.objects.filter(
content_type__app_label='blog',
content_type__model='post')
self.assertEqual(len(permissions.filter(codename='view_post')), 1)
| 37.61 | 90 | 0.604006 | 1,161 | 11,283 | 5.61671 | 0.116279 | 0.065787 | 0.056433 | 0.098758 | 0.775341 | 0.755406 | 0.752645 | 0.73133 | 0.719828 | 0.677197 | 0 | 0.007199 | 0.285917 | 11,283 | 299 | 91 | 37.735786 | 0.80216 | 0.062218 | 0 | 0.732218 | 0 | 0 | 0.26238 | 0.141275 | 0 | 0 | 0 | 0 | 0.100418 | 1 | 0.033473 | false | 0.004184 | 0.041841 | 0 | 0.087866 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
451377d758fad8c8a2b29209e743960eaaf9e2c4 | 9,896 | py | Python | solvers/neighborhoods/MoveNode.py | powertomato/heuOpt_2017_G1 | ee97f18cfd7ef6c9548708a539b1cf2ac4acfdc9 | [
"MIT"
] | null | null | null | solvers/neighborhoods/MoveNode.py | powertomato/heuOpt_2017_G1 | ee97f18cfd7ef6c9548708a539b1cf2ac4acfdc9 | [
"MIT"
] | null | null | null | solvers/neighborhoods/MoveNode.py | powertomato/heuOpt_2017_G1 | ee97f18cfd7ef6c9548708a539b1cf2ac4acfdc9 | [
"MIT"
] | null | null | null |
from solvers.neighborhoods.Neighborhood import Neighborhood
import math
import itertools, random
import copy
from collections import Counter
class MoveNodeCandidate(object):
def __init__(self, graph, nodeIdx, target):
self.nodeIdx = nodeIdx
self.target = target
self.graph = graph
def _calcIndexAfterMove(self, idx):
if idx == self.nodeIdx:
return self.target
if self.target > self.nodeIdx:
if idx > self.nodeIdx and idx <= self.target:
return idx - 1
else:
if idx < self.nodeIdx and idx >= self.target:
return idx + 1
return idx
def numCrossings(self):
numNewCrossings = 0
numResolvedCrossings = 0
movenode = self.graph.getNodeByIndex(self.nodeIdx)
for edge in movenode.edges:
edgeId = edge.id
e1Idx = ( self._calcIndexAfterMove(self.graph.nodeIdToIndex[edge.node1]),
self._calcIndexAfterMove(self.graph.nodeIdToIndex[edge.node2]) )
if (e1Idx[0] > e1Idx[1]):
e1Idx = (e1Idx[1], e1Idx[0])
page = edge.pageId
for edgeId2 in edge.perPageCrossedEdges[page]:
edge2 = self.graph.edgeList[edgeId2]
e2Idx = ( self._calcIndexAfterMove(self.graph.nodeIdToIndex[edge2.node1]),
self._calcIndexAfterMove(self.graph.nodeIdToIndex[edge2.node2]) )
#edges not crossing
if (e2Idx[0] > e2Idx[1]):
e2Idx = (e2Idx[1], e2Idx[0])
if e1Idx[0]>e2Idx[0]:
if not (e2Idx[0] < e1Idx[0] < e2Idx[1] < e1Idx[1]):
numResolvedCrossings+=1
else:
if not (e1Idx[0] < e2Idx[0] < e1Idx[1] < e2Idx[1]):
numResolvedCrossings+=1
if self.nodeIdx < self.target:
noderange = range(self.nodeIdx+1, self.target+1)
else:
noderange = range(self.target, self.nodeIdx)
for nodeIdx in noderange:
node = self.graph.getNodeByIndex(nodeIdx)
for edge in movenode.edges:
e1Idx = ( self._calcIndexAfterMove(self.graph.nodeIdToIndex[edge.node1]),
self._calcIndexAfterMove(self.graph.nodeIdToIndex[edge.node2]) )
if (e1Idx[0] > e1Idx[1]):
e1Idx = (e1Idx[1], e1Idx[0])
page = edge.pageId
for edge2 in node.edges:
if page != edge2.pageId:
continue
if edge2.id in edge.perPageCrossedEdges[page]:
continue
e2Idx = ( self._calcIndexAfterMove(self.graph.nodeIdToIndex[edge2.node1]),
self._calcIndexAfterMove(self.graph.nodeIdToIndex[edge2.node2]) )
#edges crossing
if (e2Idx[0] > e2Idx[1]):
e2Idx = (e2Idx[1], e2Idx[0])
if e1Idx[0]>e2Idx[0]:
if e2Idx[0] < e1Idx[0] < e2Idx[1] < e1Idx[1]:
numNewCrossings+=1
else:
if e1Idx[0] < e2Idx[0] < e1Idx[1] < e2Idx[1]:
numNewCrossings+=1
return self.graph.numCrossings() - numResolvedCrossings + numNewCrossings
def graphUpdate(self):
#print("movenode %d %d" % (self.nodeIdx, self.target))
if self.nodeIdx < self.target:
noderange = range(self.nodeIdx+1, self.target+1)
indexShift = -1
else:
noderange = range(self.target, self.nodeIdx)
indexShift = 1
for i in noderange:
node = self.graph.getNodeByIndex(i)
self.graph.nodeIdToIndex[node.id] = i+indexShift
node = self.graph.getNodeByIndex(self.nodeIdx)
self.graph.nodeIdToIndex[node.id] = self.target
if self.nodeIdx < self.target:
a = self.graph.nodes
i = self.nodeIdx
t = self.target
self.graph.nodes = a[0:i] + a[i+1:t+1] + [a[i]] + a[t+1:]
else:
a = self.graph.nodes
i = self.nodeIdx
t = self.target
self.graph.nodes = a[0:t] + [a[i]] + a[t:i] + a[i+1:]
for edge in self.graph.edgeList:
edge.resetCrossings()
for edge in self.graph.edgeList:
self.graph.initCrossingsForEdge(edge)
return self.graph
movenode = self.graph.getNodeByIndex(self.nodeIdx)
for edge in movenode.edges:
edgeId = edge.id
e1Idx = ( self._calcIndexAfterMove(self.graph.nodeIdToIndex[edge.node1]),
self._calcIndexAfterMove(self.graph.nodeIdToIndex[edge.node2]) )
if (e1Idx[0] > e1Idx[1]):
e1Idx = (e1Idx[1], e1Idx[0])
page = edge.pageId
toremove = set()
for edgeId2 in edge.perPageCrossedEdges[page]:
edge2 = self.graph.edgeList[edgeId2]
e2Idx = ( self._calcIndexAfterMove(self.graph.nodeIdToIndex[edge2.node1]),
self._calcIndexAfterMove(self.graph.nodeIdToIndex[edge2.node2]) )
#edges not crossing
if (e2Idx[0] > e2Idx[1]):
e2Idx = (e2Idx[1], e2Idx[0])
if e1Idx[0]>e2Idx[0]:
if not (e2Idx[0] < e1Idx[0] < e2Idx[1] < e1Idx[1]):
toremove.add(edgeId2)
edge2.perPageCrossedEdges[page].remove(edgeId)
else:
if not (e1Idx[0] < e2Idx[0] < e1Idx[1] < e2Idx[1]):
toremove.add(edgeId2)
edge2.perPageCrossedEdges[page].remove(edgeId)
edge.perPageCrossedEdges[page].difference_update(toremove)
if self.nodeIdx < self.target:
noderange = range(self.nodeIdx+1, self.target+1)
else:
noderange = range(self.target, self.nodeIdx)
for nodeIdx in noderange:
node = self.graph.getNodeByIndex(nodeIdx)
for edge in movenode.edges:
edgeId = edge.id
e1Idx = ( self._calcIndexAfterMove(self.graph.nodeIdToIndex[edge.node1]),
self._calcIndexAfterMove(self.graph.nodeIdToIndex[edge.node2]) )
if (e1Idx[0] > e1Idx[1]):
e1Idx = (e1Idx[1], e1Idx[0])
page = edge.pageId
for edge2 in node.edges:
edgeId2 = edge2.id
if page != edge2.pageId:
continue
e2Idx = ( self._calcIndexAfterMove(self.graph.nodeIdToIndex[edge2.node1]),
self._calcIndexAfterMove(self.graph.nodeIdToIndex[edge2.node2]) )
#edges not crossing
if (e2Idx[0] > e2Idx[1]):
e2Idx = (e2Idx[1], e2Idx[0])
if e1Idx[0]>e2Idx[0]:
if e2Idx[0] < e1Idx[0] < e2Idx[1] < e1Idx[1]:
edge.perPageCrossedEdges[page].add(edgeId2)
edge2.perPageCrossedEdges[page].add(edgeId)
else:
if e1Idx[0] < e2Idx[0] < e1Idx[1] < e2Idx[1]:
edge.perPageCrossedEdges[page].add(edgeId2)
edge2.perPageCrossedEdges[page].add(edgeId)
if self.nodeIdx < self.target:
noderange = range(self.nodeIdx+1, self.target+1)
indexShift = -1
else:
noderange = range(self.target, self.nodeIdx)
indexShift = 1
for i in noderange:
node = self.graph.getNodeByIndex(i)
self.graph.nodeIdToIndex[node.id] = i+indexShift
node = self.graph.getNodeByIndex(self.nodeIdx)
self.graph.nodeIdToIndex[node.id] = self.target
if self.nodeIdx < self.target:
a = self.graph.nodes
i = self.nodeIdx
t = self.target
self.graph.nodes = a[0:i] + a[i+1:t+1] + [a[i]] + a[t+1:]
else:
a = self.graph.nodes
i = self.nodeIdx
t = self.target
self.graph.nodes = a[0:t] + [a[i]] + a[t:i] + a[i+1:]
return self.graph
class MoveNode(Neighborhood):
def __init__(self, strategy, evaluator):
super(MoveNode, self).__init__(strategy, evaluator)
def generateRandom(self, x):
while True:
n1 = random.randint(0, len(x.nodes)-1)
n2 = -1
while n1==n2 or n2==-1:
n2 = random.randint(0, len(x.nodes)-1)
yield MoveNodeCandidate(x, n1, n2)
def generateSingle(self, x):
for n1 in range(len(x.nodes)):
for n2 in range(len(x.nodes)):
if n1==n2:
continue
yield MoveNodeCandidate(x, n1, n2)
| 40.391837 | 96 | 0.473626 | 945 | 9,896 | 4.928042 | 0.091005 | 0.088898 | 0.094481 | 0.106506 | 0.797294 | 0.769809 | 0.758643 | 0.746189 | 0.746189 | 0.72128 | 0 | 0.045326 | 0.427041 | 9,896 | 244 | 97 | 40.557377 | 0.776014 | 0.012328 | 0 | 0.772487 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.037037 | false | 0 | 0.026455 | 0 | 0.111111 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
453070ee3e5961cbd856eda052151e6deee1c7ff | 90 | py | Python | anaconda-mode/0.1.1/service_factory/providers/__init__.py | dzhwinter/spacemacs-stable | c8de148787278af0a83021701a19e44ba0c0b16a | [
"Vim"
] | 42 | 2015-08-24T13:46:03.000Z | 2022-03-22T01:51:17.000Z | anaconda-mode/0.1.1/service_factory/providers/__init__.py | dzhwinter/spacemacs-stable | c8de148787278af0a83021701a19e44ba0c0b16a | [
"Vim"
] | null | null | null | anaconda-mode/0.1.1/service_factory/providers/__init__.py | dzhwinter/spacemacs-stable | c8de148787278af0a83021701a19e44ba0c0b16a | [
"Vim"
] | 3 | 2015-08-24T13:20:18.000Z | 2019-08-06T10:46:22.000Z | from __future__ import (
absolute_import, unicode_literals, division, print_function)
| 30 | 64 | 0.811111 | 10 | 90 | 6.6 | 0.9 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.133333 | 90 | 2 | 65 | 45 | 0.846154 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0.5 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | 6 |
18a4467510b3849aabbbea69ef876afc8ac67011 | 213 | py | Python | django_project/pages/views.py | bekzodbuyukov/postgresql-experience | ae89fd84ffde43952f32fc97feaebda4d0045d3a | [
"MIT"
] | 1 | 2021-06-23T07:08:39.000Z | 2021-06-23T07:08:39.000Z | django_project/pages/views.py | bekzodbuyukov/postgresql-experience | ae89fd84ffde43952f32fc97feaebda4d0045d3a | [
"MIT"
] | null | null | null | django_project/pages/views.py | bekzodbuyukov/postgresql-experience | ae89fd84ffde43952f32fc97feaebda4d0045d3a | [
"MIT"
] | null | null | null | from django.http.response import HttpResponse
from django.shortcuts import render
# Create your views here.
def show_home_page(request):
return HttpResponse('<h3>PostgreSQL-experience app is working!</h3>')
| 26.625 | 73 | 0.788732 | 29 | 213 | 5.724138 | 0.827586 | 0.120482 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.010695 | 0.122066 | 213 | 7 | 74 | 30.428571 | 0.877005 | 0.107981 | 0 | 0 | 0 | 0 | 0.244681 | 0.132979 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0.5 | 0.25 | 1 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 6 |
7a03a46dbf648555ccd1852ab390f93e82ce9f7e | 29 | py | Python | venv/Lib/site-packages/tools37/algebra/__init__.py | GabrielAmare/Darts | 182748d821b8c1838071f3b28724d0d9b095dcf9 | [
"MIT"
] | null | null | null | venv/Lib/site-packages/tools37/algebra/__init__.py | GabrielAmare/Darts | 182748d821b8c1838071f3b28724d0d9b095dcf9 | [
"MIT"
] | null | null | null | venv/Lib/site-packages/tools37/algebra/__init__.py | GabrielAmare/Darts | 182748d821b8c1838071f3b28724d0d9b095dcf9 | [
"MIT"
] | null | null | null | from .Polynom import Polynom
| 14.5 | 28 | 0.827586 | 4 | 29 | 6 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.137931 | 29 | 1 | 29 | 29 | 0.96 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
e162f13342691bf627051ff2ce77edce2660afc0 | 16,846 | py | Python | src/rsactftool/attacks/single_key/pastctfprimes.py | borari/RsaCtfTool | 8a6b661d066fe81c02bdb9ad4d4f57fc7d2f7184 | [
"Beerware"
] | null | null | null | src/rsactftool/attacks/single_key/pastctfprimes.py | borari/RsaCtfTool | 8a6b661d066fe81c02bdb9ad4d4f57fc7d2f7184 | [
"Beerware"
] | null | null | null | src/rsactftool/attacks/single_key/pastctfprimes.py | borari/RsaCtfTool | 8a6b661d066fe81c02bdb9ad4d4f57fc7d2f7184 | [
"Beerware"
] | 1 | 2022-03-29T04:18:25.000Z | 2022-03-29T04:18:25.000Z | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
from rsactftool.lib.keys_wrapper import PrivateKey
def attack(attack_rsa_obj, publickey, cipher=[]):
""" Search for previously used primes in CTFs
"""
primes = [
108082147276398906822234149167480016132157014049560913761488880190018027488520386318253742675423286348552334110023434741671427911613197684395221211646299519273129194692306445874938199068586137486874290442314459278649345469626426790676801658394799404284116771456479272808343825651929906737811050557836671896732124546721747709022607151231423494815945385193624295868730390462068156825588342737037490320356361648437686599733,
108082147276398906822234149167480016132157014049560913761488880190018027488520386318253742675423286348552334110023434741671427911613197684395221211646299519273129194692306445874938199068586137486874290442314459278649345469626426790676801658394799404284116771456479272808343825651929906737811050557836671896732124546721747709022607151231423494815945385193624295868730390462068156825588342737037490320356361648437686598461,
108082147276398906822234149167480016132157014049560913761488880190018027488520386318253742675423286348552334110023434741671427911613197684395221211646299519273129194692306445874938199068586137486874290442314459278649345469626426790676801658394799404284116771456479272808343825651929906737811050557836671896732124546721747709022607151231423494815945385193624295868730390462068156825588342737037490320356361648437686597791,
108082147276398906822234149167480016132157014049560913761488880190018027488520386318253742675423286348552334110023434741671427911613197684395221211646299519273129194692306445874938199068586137486874290442314459278649345469626426790676801658394799404284116771456479272808343825651929906737811050557836671896732124546721747709022607151231423494815945385193624295868730390462068156825588342737037490320356361648437686600843,
6703903965361517118576511528025622717463828698514771456694902115718276634989944955753407851598489976727952425488221391817052769267904281935379659980013749,
13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903820008890319855427587165500997237443558735689450602365103,
4101860217206195486319508931988944464741665503169699281154625914180099350459859416508157842908810493659777848990372055112637980426665995893689191266676993,
4101860217206195486319508931988944464741665503169699281154625914180099350459859416508157842908810493659777848990372055112637980426665995893689191266677141,
4101860217206195486319508931988944464741665503169699281154625914180099350459859416508157842908810493659777848990372055112637980426665995893689191266677279,
4165938907260954640804986514555496835723686162893011508104816859692320046868363019435944953520658898678455053432699809898947934756189120526030787871227407,
4165938907260954640804986514555496835723686162893011508104816859692320046868363019435944953520658898678455053432699809898947934756189120526030787871227587,
4165938907260954640804986514555496835723686162893011508104816859692320046868363019435944953520658898678455053432699809898947934756189120526030787871227863,
12643740637395110652894262209502063899047520218436247735878188180335985789877601396069401620713231058940443043891453952791936466967524033214476598572706213,
12217494205780318874865198006759446969679921137474855298485716817925925911890415286181103665676748660959871257808447814451048738105000263500773868071134927,
12753003603072550531018654801465540625925587065270735249200707034221342553612566510512289220382168917762612389041102258111324579759414416978278947259367203,
11512221259968944711215688757058402596735146070663731484166937019905962795560024445608131301476308525203431567566930188520189544071868201113560261699518477,
120154561482812169366431552175315487829790853533514455083187141150401404579723989466386713554692826031183462112641793395815695957964420754471645865010199918851008631038679685035857813488382170765657628252079464574576993595350214255290554756868269962991079417299897885957935578968328491235168443836989742332343,
164184701914508585475304431352949988726937945291,
123722643358410276082662590855480232574295213977,
1367950959033448694251101693351971454646908585982174247214456588106744480223502924899594970200721567086593256490339820357729417073968911473368284373028327,
1873061312526431600198418914726418187289872964131683141580934527253790685014095254664971230592314176869517383698550622907346640404434127554775124138006963,
72432241732033981541049204016745025006867436329489703868293535625696723664804764149457845005290546241606890061226796845022216057745054630401792003744462109,
90126444730029710403645054775061222054869762216009860614264509250054875494146740846632769652653539286830798492363476860052054761040294014518933023714223427,
279125332373073513017147096164124452877,
295214597363242917440342570226980714417,
25478326064937419292200172136399497719081842914528228316455906211693118321971399936004729134841162974144246271486439695786036588117424611881955950996219646807378822278285638261582099108339438949573034101215141156156408742843820048066830863814362379885720395082318462850002901605689761876319151147352730090957556940842144299887394678743607766937828094478336401159449035878306853716216548374273462386508307367713112073004011383418967894930554067582453248981022011922883374442736848045920676341361871231787163441467533076890081721882179369168787287724769642665399992556052144845878600126283968890273067575342061776244939,
783420406144696097385833069281677113,
783756020423148789078921701951691559,
31834349,
48670331,
19193025210159847056853811703017693,
17357677172158834256725194757225793,
279125332373073513017147096164124452877,
295214597363242917440342570226980714417,
42727,
58757,
123722643358410276082662590855480232574295213977,
164184701914508585475304431352949988726937945291,
800644567978575682363895000391634967,
83024947846700869393771322159348359271173,
37024794671302122535260220812153587643,
272573531366295567443756143024197333707,
21563957808398119329545349513312897291720371794644161565433575994922624494866014735925135594671402533520230648695949559828278766299067426136066601816643711,
22708406967509416561081471369947020796745437757938294005271339336356008357234294069698063747451399564794968797317330497407167861251551902204973484175503837,
144299940222848685214153733110344660304144248927927225494186904499495592842937728938865184611511914233674465357703431948804720019559293726714685845430627084912877192848598444717376108179511822902563959186098293320939635766298482099885173238182915991321932102606591240368970651488289284872552548559190434607447,
144245059483864997316184517203073096336312163518349447278779492969760750146161606776371569522895088103056082865212093431805166968588430946389831338526998726900084424430828957236538023320369476765118148928194401317313951462365588911048597017242401293395926609382786042879520305147467629849523719036035657146109,
26440615366395242196516853423447,
32581479300404876772405716877547,
27038194053540661979045656526063,
31267675316206058850450140119274819751417791661635697504813240447984629079490652100735044733540913861142747523203435425061407513320468637503374655392825781473928382075249940537540518803447705157748005302692062548318810509906583495199574613016294007136437402473510780242916703476437678742060227320715065951829792345046885904400712909744723822283218325063910405248903702979799406800950896480067506026510838938457917561846489922757260048427449921729671259609502925944554834113384775414185570194511576885758113751887157223120097006977944365867967544959413407725601588176723859982645734322192561519871486442323167074933639,
43068974121995373755259728623203756276151708711206529799133972499770311973917522370590279232720654505974288964559409201661353918115651149664716192367955840217357608436100090406769463686865453605648714294729259644629396177958653095754824288389624580579733807505133514369658203797575477437151706954894720485223,
698962359293224388508528504293868295849536117911029511500535686265628116126035273937376653818042771965856143346411321978169984196703587737297011635332863244713959616825373265069482088742784543259349452001104153825865595450998374567435519147735270488504450983670922877905525006233437224249682098320961706073951,
4911154640312831735300579932662636306005188439240020352879,
5858530077012370931106950309549472688326371985155604622439,
1451135465007329936687682012556458198263354033267,
1283383279909541494981671251013593566543423047599,
289260226283275563579648656678444936057,
288180072604771133716023733756993741403,
32158763574926282399690427421751598974822750157866002942864427634852437380540017586451493854661729909380518733649186624385206737336324813109500237603304026009112696565510846849987937423619262973393969175056759821652138869783215378169757835283584660846583208812725733839059137580944002686113912792569631796916069732431775599320458346937859589815497525828622622652165709271152246464728489927670696601016248559515951932154686633599100945314921834227324381958751184684979824241375253606863601895383658582486045363570755445629865194046700806542078378801136397577730247660070033517187439537339428288763342861366560261446073,
32158763574926282399690427421751598974822750157866002942864427634852437380540017586451493854661729909380518733649186624385206737336324813109500237603304026009112696565510846849987937423619262973393969175056759821652138869783215378169757835283584660846583208812725733839059137580944002686113912792569631796916069732431775599320458346937859589815497525828622622652165709271152246464728489927670696601016248559515951932154686633599100945314921834227324381958751184684979824241375253606863601895383658582486045363570755445629865194046700806542078378801136397577730247660070033517187439537339428288763342861366560261414507,
30555909537318327326226067108345484260972616392831008890345613182167918843881096961410781393695029449357707848545288220880122374798556583885387343041975279297622137379354808942799947266338126600859247945486391385249259848502175234010967289831554894776077704571261457595823825245669052206379832284446373088109050246642453540203667448240894956074979263603360448779126929364191229791046048600648158120404404766763070327940029813826415327745664993191485439444296109763969948631755535163926384703087422857642736153852582820056661551903549876616627900530084158172809851351898663554970528201875223815554349604138636668040631,
28796899277235049975421947378568428888005019408631005870725337759187744546493409470582705210790627097597656481534493716225301660663533212040068163723937803169735485217437722947354732420098585958967033073629288721874028940705969141716032409906092583043329293532612601200186754187377338924379443611709918885185638934712580040042904995838353611699081350712817357237035507539201368300463060034856220488010509411264244138417348439340955309300128758040513940379009974696105387107481999359705587790254117489020540714253505694682552102843028243384677060490696214834957049391213864664165843655260698241682369402177091178720927,
28349223152666012309896421767725787316124897111416473420803849019741154117582482568645254183215552986563114855665416593397403745371086355268654763921803558654340155902194948080056226592560917521612824589013349044205989541259468856602228462903448721105774109966325479530181197156476502473067978072053273437369680433495259118953717909524799086692640103084287064091489681162498108275295255082627807077949841602061428289272700263987438087045434043977981316071156426134695316796020506076336851840708593720052204359360366058549157961154869248835793804817253083037277453771408544063058190126149127240681909811943783388977967,
28349223152666012309896421767725787316124897111416473420803849019741154117582482568645254183215552986563114855665416593397403745371086355268654763921803558654340155902194948080056226592560917521612824589013349044205989541259468856602228462903448721105774109966325479530181197156476502473067978072053273437369680433495259118953717909524799086692640103084287064091489681162498101607280822202773532998098050880803631144514377948079277690787622279940743498439084904702494445241729763146426258407468147831250550239995285695193105630324823153678214290802694619958991541957383815098042054239547145549933872335482492225099839,
2758599203,
199050626189790903113151725251371951406311367304411013359159100762029303668345459282823483508119186508070350039475140948570888009866572148405365532164833126992414461936781273087675274788769905198546175946505790118332257676994622928414648644875376193656132263418075334807302665038501361680530751104620475935886499714767992159620130246904875540624651891646715835632182355428589610236128648209568297096024509697960196858754170641081387466229916585122877955908862176165344465889280850859817985096316883025515924332365977538735425288433292357532172467247159245727072344354499113900733623716569924461327947462469348798798400461045817375922057805611166274339541877392159201774893120311667898551312256530117094221191204981071357303328506659872809131929265966688409379037586014938643190675726674943253875287765020503118408406103824607730713529079962656130622218633922911733000466212212532871890933508287965723844399784165195088175666883742686183165151553009638524764735387233844317375317153437534933611361683136151569588355535831475925641431859231311079029505004457816932257031352498323214304125608733640306746900473758755832661915903475867854937735150255829715879232213599597863424779218670961633567259935246911742292942052832671549,
24333562944687516822197571192658754203291290861678417217447438854540594847087766562404339574537862439116548079253289466115128767870577648533973566286797593441730003379848043825634065823911136780045362090360846493427099473619203426216220826743478974241107765471416754913629766068614128278553165309459614540881272639715963742807416312087758332567870818068056326342400589601117982695439948496482753836668023789721452705706258642830333890588979897355741176673670662543132574318628603066958811749579934075668455748590286427527491514861437629540690813171672435522560204943058263324060332232490301430308879676240097644556943,
25699922293123622238012005113928758274338093880738911843144609876290300384447243164527369410936522534026502861166228851341858617366580840945546916656960397913459416157594030359887797479829819533476376181670391998963549074371737295746623468123112547424135047636878302121269250886314724602949616886176008642837449632045010113812032294774060357611189602487961064611234002464905006798590256478016955856378120527444702590839053848988168714049387256070864726124290373739801554166928887083826045058481026363141572007235867367607974662051368481037707609970666363610931674810380477197023311110704572295255843715262143691203301,
26641239846781539174997613915486416003684568556746576609279663468469031683562139918289710191916575980269872103186803161203776420494840845869372424906386190919487401478921545410628828040240934885968480468559124463233908052442280478139872489261920279274813374296134128578293855845928227225795788061940296913771355415137193729864318300987109915105382195425114525826138321815629366884757211418011082865207792823895128910178064295532964692290697547400111032047363746813247658976480566291220338236760240639947583180060309174234225896967104503916386813098322083010876516252218060276731781117933746509243898480864478441202823,
136417036410264428599995771571898945930186573023163480671956484856375945728848790966971207515506078266840020356163911542099310863126768355608704677724047001480085295885211298435966986319962418547256435839380570361886915753122740558506761054514911316828252552919954185397609637064869903969124281568548845615791,
11232077261967644077277312997808249915855709514498625183789998098688209996914964867050110603375257386497746294969159136128904120786273278056895662599793297,
]
for prime in primes:
if publickey.n % prime == 0:
publickey.q = prime
publickey.p = publickey.n // publickey.q
priv_key = PrivateKey(
int(publickey.p), int(publickey.q), int(publickey.e), int(publickey.n)
)
return (priv_key, None)
return (None, None)
| 181.139785 | 1,233 | 0.943369 | 142 | 16,846 | 111.880282 | 0.753521 | 0.003021 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.969877 | 0.048201 | 16,846 | 92 | 1,234 | 183.108696 | 0.020955 | 0.005343 | 0 | 0.094118 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0.011765 | false | 0 | 0.023529 | 0 | 0.058824 | 0 | 0 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
e1cef13f2a61568e9f9f1d7a8d84f3a893c7676f | 40 | py | Python | backend/metric/ulca-utility-service/src/routes/__init__.py | agupta54/ulca | c1f570ac254ce2ac73f40c49716458f4f7cbaee2 | [
"MIT"
] | 3 | 2022-01-12T06:51:51.000Z | 2022-02-23T18:54:33.000Z | backend/metric/ulca-utility-service/src/routes/__init__.py | agupta54/ulca | c1f570ac254ce2ac73f40c49716458f4f7cbaee2 | [
"MIT"
] | 6 | 2021-08-31T19:21:26.000Z | 2022-01-03T05:53:42.000Z | backend/metric/ulca-utility-service/src/routes/__init__.py | agupta54/ulca | c1f570ac254ce2ac73f40c49716458f4f7cbaee2 | [
"MIT"
] | 8 | 2021-08-12T08:07:49.000Z | 2022-01-25T04:40:51.000Z | from .notifier import NOTIFIER_BLUEPRINT | 40 | 40 | 0.9 | 5 | 40 | 7 | 0.8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.075 | 40 | 1 | 40 | 40 | 0.945946 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
bed2976428de537d66154c00696d86904d25f12b | 40 | py | Python | tests/test_tokenize/__init__.py | bigdata-ustc/CangJie | a3264082fa0432d257b5c4722b14c55f9092a411 | [
"MIT"
] | 2 | 2020-03-04T02:27:29.000Z | 2020-05-22T04:07:24.000Z | tests/test_tokenize/__init__.py | bigdata-ustc/CangJie | a3264082fa0432d257b5c4722b14c55f9092a411 | [
"MIT"
] | null | null | null | tests/test_tokenize/__init__.py | bigdata-ustc/CangJie | a3264082fa0432d257b5c4722b14c55f9092a411 | [
"MIT"
] | 1 | 2022-03-12T00:31:59.000Z | 2022-03-12T00:31:59.000Z | # coding: utf-8
# 2020/1/3 @ tongshiwei
| 13.333333 | 23 | 0.65 | 7 | 40 | 3.714286 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.212121 | 0.175 | 40 | 2 | 24 | 20 | 0.575758 | 0.875 | 0 | null | 0 | null | 0 | 0 | null | 0 | 0 | 0 | null | 1 | null | true | 0 | 0 | null | null | null | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
833b9552c36f270221c17a9d424329b062036f14 | 148 | py | Python | cpo/tests/test_zzz.py | worc3131/CPO | de738f18188566327c407bd34f0683d827b5d5d5 | [
"MIT"
] | null | null | null | cpo/tests/test_zzz.py | worc3131/CPO | de738f18188566327c407bd34f0683d827b5d5d5 | [
"MIT"
] | null | null | null | cpo/tests/test_zzz.py | worc3131/CPO | de738f18188566327c407bd34f0683d827b5d5d5 | [
"MIT"
] | null | null | null |
import time
from cpo import *
def test_zzz():
# run at the end of all the tests
# used to track down hanging threads etc.
DEBUGGER()
| 14.8 | 45 | 0.662162 | 24 | 148 | 4.041667 | 0.916667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.277027 | 148 | 9 | 46 | 16.444444 | 0.906542 | 0.47973 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | true | 0 | 0.5 | 0 | 0.75 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
55cb3a62607f56521076152f3906e193b1f21955 | 86,581 | py | Python | test_autoastro/unit/profiles/mass_profiles/test_total_mass_profiles.py | woodyZootopia/PyAutoAstro | 6500b9746b3e73c3f3129fcbaa3a0419bb400915 | [
"MIT"
] | null | null | null | test_autoastro/unit/profiles/mass_profiles/test_total_mass_profiles.py | woodyZootopia/PyAutoAstro | 6500b9746b3e73c3f3129fcbaa3a0419bb400915 | [
"MIT"
] | null | null | null | test_autoastro/unit/profiles/mass_profiles/test_total_mass_profiles.py | woodyZootopia/PyAutoAstro | 6500b9746b3e73c3f3129fcbaa3a0419bb400915 | [
"MIT"
] | null | null | null | import autofit as af
import autoarray as aa
from autoarray.structures import grids
import autoastro as aast
import numpy as np
import pytest
import os
@pytest.fixture(autouse=True)
def reset_config():
"""
Use configuration from the default path. You may want to change this to set a specific path.
"""
af.conf.instance = af.conf.default
grid = aa.grid_irregular.manual_1d([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [2.0, 4.0]])
class TestPointMass:
def test__constructor_and_units(self):
point_mass = aast.mp.PointMass(centre=(1.0, 2.0), einstein_radius=2.0)
assert point_mass.centre == (1.0, 2.0)
assert isinstance(point_mass.centre[0], aast.dim.Length)
assert isinstance(point_mass.centre[1], aast.dim.Length)
assert point_mass.centre[0].unit == "arcsec"
assert point_mass.centre[1].unit == "arcsec"
assert point_mass.einstein_radius == 2.0
assert isinstance(point_mass.einstein_radius, aast.dim.Length)
assert point_mass.einstein_radius.unit_length == "arcsec"
# def test__converence__correct_values(self):
#
# grid = aa.grid_irregular.manual_1d([[0.0, -1.0], [0.0, 0.0], [0.0, 1.0]])
#
# point_mass = aast.mp.PointMass(centre=(0.0, 0.0), einstein_radius=1.0)
#
# convergence = point_mass.convergence_from_grid(
# grid=grid)
#
# assert convergence == pytest.approx(np.array([0.0, np.pi, 0.0]), 1e-3)
#
# point_mass = aast.mp.PointMass(centre=(0.0, 0.8), einstein_radius=2.0)
#
# convergence = point_mass.convergence_from_grid(
# grid=grid)
#
# assert convergence == pytest.approx(np.array([0.0, 0.0, 4.0*np.pi]), 1e-3)
#
# grid = aa.grid.uniform(shape_2d=(5,5), pixel_scales=1.0, sub_size=2)
#
# point_mass = aast.mp.PointMass(centre=(1.0, -1.0), einstein_radius=1.0)
#
# convergence = point_mass.convergence_from_grid(
# grid=grid)
#
# assert convergence[14] == 0.0
# assert convergence[24] == np.pi
def test__deflections__correct_values(self):
# The radial coordinate at (1.0, 1.0) is sqrt(2)
# This is decomposed into (y,x) angles of sin(45) = cos(45) = sqrt(2) / 2.0
# Thus, for an EinR of 1.0, the deflection angle is (1.0 / sqrt(2)) * (sqrt(2) / 2.0)
point_mass = aast.mp.PointMass(centre=(0.0, 0.0), einstein_radius=1.0)
deflections = point_mass.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 1.0]])
)
assert deflections[0, 0] == pytest.approx(0.5, 1e-3)
assert deflections[0, 1] == pytest.approx(0.5, 1e-3)
point_mass = aast.mp.PointMass(centre=(0.0, 0.0), einstein_radius=2.0)
deflections = point_mass.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 1.0]])
)
assert deflections[0, 0] == pytest.approx(2.0, 1e-3)
assert deflections[0, 1] == pytest.approx(2.0, 1e-3)
point_mass = aast.mp.PointMass(centre=(0.0, 0.0), einstein_radius=1.0)
deflections = point_mass.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[2.0, 2.0]])
)
assert deflections[0, 0] == pytest.approx(0.25, 1e-3)
assert deflections[0, 1] == pytest.approx(0.25, 1e-3)
point_mass = aast.mp.PointMass(centre=(0.0, 0.0), einstein_radius=1.0)
deflections = point_mass.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[2.0, 1.0]])
)
assert deflections[0, 0] == pytest.approx(0.4, 1e-3)
assert deflections[0, 1] == pytest.approx(0.2, 1e-3)
point_mass = aast.mp.PointMass(centre=(0.0, 0.0), einstein_radius=2.0)
deflections = point_mass.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[4.0, 9.0]])
)
assert deflections[0, 0] == pytest.approx(16.0 / 97.0, 1e-3)
assert deflections[0, 1] == pytest.approx(36.0 / 97.0, 1e-3)
point_mass = aast.mp.PointMass(centre=(1.0, 2.0), einstein_radius=1.0)
deflections = point_mass.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[2.0, 3.0]])
)
assert deflections[0, 0] == pytest.approx(0.5, 1e-3)
assert deflections[0, 1] == pytest.approx(0.5, 1e-3)
def test__deflections__change_geometry(self):
point_mass_0 = aast.mp.PointMass(centre=(0.0, 0.0))
point_mass_1 = aast.mp.PointMass(centre=(1.0, 1.0))
deflections_0 = point_mass_0.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 1.0]])
)
deflections_1 = point_mass_1.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 0.0]])
)
assert deflections_0[0, 0] == pytest.approx(-deflections_1[0, 0], 1e-5)
assert deflections_0[0, 1] == pytest.approx(-deflections_1[0, 1], 1e-5)
point_mass_0 = aast.mp.PointMass(centre=(0.0, 0.0))
point_mass_1 = aast.mp.PointMass(centre=(0.0, 0.0))
deflections_0 = point_mass_0.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 0.0]])
)
deflections_1 = point_mass_1.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
)
assert deflections_0[0, 0] == pytest.approx(deflections_1[0, 1], 1e-5)
assert deflections_0[0, 1] == pytest.approx(deflections_1[0, 0], 1e-5)
def test__multiple_coordinates_in__multiple_coordinates_out(self):
point_mass = aast.mp.PointMass(centre=(1.0, 2.0), einstein_radius=1.0)
deflections = point_mass.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[2.0, 3.0], [2.0, 3.0], [2.0, 3.0]])
)
assert deflections[0, 0] == pytest.approx(0.5, 1e-3)
assert deflections[0, 1] == pytest.approx(0.5, 1e-3)
assert deflections[1, 0] == pytest.approx(0.5, 1e-3)
assert deflections[1, 1] == pytest.approx(0.5, 1e-3)
assert deflections[2, 0] == pytest.approx(0.5, 1e-3)
assert deflections[2, 1] == pytest.approx(0.5, 1e-3)
point_mass = aast.mp.PointMass(centre=(0.0, 0.0), einstein_radius=1.0)
deflections = point_mass.deflections_from_grid(
grid=aa.grid_irregular.manual_1d(
[[1.0, 1.0], [2.0, 2.0], [1.0, 1.0], [2.0, 2.0]]
)
)
assert deflections[0, 0] == pytest.approx(0.5, 1e-3)
assert deflections[0, 1] == pytest.approx(0.5, 1e-3)
assert deflections[1, 0] == pytest.approx(0.25, 1e-3)
assert deflections[1, 1] == pytest.approx(0.25, 1e-3)
assert deflections[2, 0] == pytest.approx(0.5, 1e-3)
assert deflections[2, 1] == pytest.approx(0.5, 1e-3)
assert deflections[3, 0] == pytest.approx(0.25, 1e-3)
assert deflections[3, 1] == pytest.approx(0.25, 1e-3)
def test__deflections_of_profile__dont_use_interpolate_and_cache_decorators(self):
point_mass = aast.mp.PointMass(centre=(-0.3, 0.2), einstein_radius=1.0)
mask = np.array(
[
[True, True, True, True, True],
[True, False, False, False, True],
[True, False, True, False, True],
[True, False, False, False, True],
[True, True, True, True, True],
]
)
mask = aa.mask.manual(mask, pixel_scales=(1.0, 1.0), sub_size=1)
grid = aa.masked.grid.from_mask(mask=mask)
regular_with_interp = grid.new_grid_with_interpolator(
pixel_scale_interpolation_grid=0.5
)
interp_deflections = point_mass.deflections_from_grid(grid=regular_with_interp)
interpolator = grids.Interpolator.from_mask_grid_and_pixel_scale_interpolation_grids(
mask=mask, grid=grid, pixel_scale_interpolation_grid=0.5
)
interp_deflections_values = point_mass.deflections_from_grid(
grid=interpolator.interp_grid
)
interp_deflections_manual_y = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 0]
)
interp_deflections_manual_x = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 1]
)
assert (interp_deflections_manual_y != interp_deflections[:, 0]).all()
assert (interp_deflections_manual_x != interp_deflections[:, 1]).all()
def test__output_are_autoarrays(self):
grid = aa.grid.uniform(shape_2d=(2, 2), pixel_scales=1.0, sub_size=1)
point_mass = aast.mp.PointMass()
deflections = point_mass.deflections_from_grid(grid=grid)
assert deflections.shape_2d == (2, 2)
class TestBrokenPowerLaw:
def test__convergence_correct_values(self):
broken_power_law = aast.mp.SphericalBrokenPowerLaw(
centre=(0, 0),
einstein_radius=1.0,
inner_slope=1.5,
outer_slope=2.5,
break_radius=0.1,
)
assert broken_power_law.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.5, 1.0]])
) == pytest.approx(0.0355237, 1e-4)
assert broken_power_law.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.5, 1.0], [0.5, 1.0]])
) == pytest.approx([0.0355237, 0.0355237], 1e-4)
broken_power_law = aast.mp.EllipticalBrokenPowerLaw(
centre=(0, 0),
axis_ratio=0.8,
phi=30.0,
einstein_radius=1.0,
inner_slope=1.5,
outer_slope=2.5,
break_radius=0.1,
)
assert broken_power_law.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.5, 1.0]])
) == pytest.approx(0.05006035, 1e-4)
broken_power_law = aast.mp.EllipticalBrokenPowerLaw(
centre=(0, 0),
axis_ratio=0.7,
phi=160.0,
einstein_radius=1.0,
inner_slope=1.8,
outer_slope=2.2,
break_radius=0.1,
)
assert broken_power_law.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.5, 1.0]])
) == pytest.approx(0.034768, 1e-4)
broken_power_law = aast.mp.EllipticalBrokenPowerLaw(
centre=(0, 0),
axis_ratio=0.7,
phi=250.0,
einstein_radius=1.0,
inner_slope=1.8,
outer_slope=2.2,
break_radius=0.1,
)
assert broken_power_law.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.5, 1.0]])
) == pytest.approx(0.03622852, 1e-4)
broken_power_law = aast.mp.EllipticalBrokenPowerLaw(
centre=(0, 0),
axis_ratio=0.7,
phi=310.0,
einstein_radius=1.0,
inner_slope=1.8,
outer_slope=2.2,
break_radius=0.1,
)
assert broken_power_law.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.5, 1.0]])
) == pytest.approx(0.026469, 1e-4)
def test__deflections__correct_values(self):
broken_power_law = aast.mp.SphericalBrokenPowerLaw(
centre=(0, 0),
einstein_radius=1.0,
inner_slope=1.5,
outer_slope=2.5,
break_radius=0.1,
)
deflections = broken_power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.5, 1.0]])
)
assert deflections[0, 0] == pytest.approx(0.404076, 1e-3)
assert deflections[0, 1] == pytest.approx(0.808152, 1e-3)
deflections = broken_power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.5, 1.0], [0.5, 1.0]])
)
assert deflections[0, 0] == pytest.approx(0.404076, 1e-3)
assert deflections[0, 1] == pytest.approx(0.808152, 1e-3)
assert deflections[1, 0] == pytest.approx(0.404076, 1e-3)
assert deflections[1, 1] == pytest.approx(0.808152, 1e-3)
broken_power_law = aast.mp.EllipticalBrokenPowerLaw(
centre=(0, 0),
axis_ratio=0.8,
phi=30.0,
einstein_radius=1.0,
inner_slope=1.5,
outer_slope=2.5,
break_radius=0.1,
)
deflections = broken_power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.5, 1.0]])
)
assert deflections[0, 0] == pytest.approx(0.40392, 1e-3)
assert deflections[0, 1] == pytest.approx(0.811619, 1e-3)
broken_power_law = aast.mp.EllipticalBrokenPowerLaw(
centre=(0, 0),
axis_ratio=0.8,
phi=110.0,
einstein_radius=1.0,
inner_slope=1.5,
outer_slope=2.5,
break_radius=0.1,
)
deflections = broken_power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.5, 1.0]])
)
assert deflections[0, 0] == pytest.approx(0.4005338, 1e-3)
assert deflections[0, 1] == pytest.approx(0.8067221, 1e-3)
broken_power_law = aast.mp.EllipticalBrokenPowerLaw(
centre=(0, 0),
axis_ratio=0.8,
phi=220.0,
einstein_radius=1.0,
inner_slope=1.5,
outer_slope=2.5,
break_radius=0.1,
)
deflections = broken_power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.5, 1.0]])
)
assert deflections[0, 0] == pytest.approx(0.399651, 1e-3)
assert deflections[0, 1] == pytest.approx(0.813372, 1e-3)
broken_power_law = aast.mp.EllipticalBrokenPowerLaw(
centre=(0, 0),
axis_ratio=0.6,
phi=300.0,
einstein_radius=1.0,
inner_slope=1.5,
outer_slope=2.5,
break_radius=0.1,
)
deflections = broken_power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.5, 1.0]])
)
assert deflections[0, 0] == pytest.approx(0.402629, 1e-3)
assert deflections[0, 1] == pytest.approx(0.798795, 1e-3)
def test__convergence__change_geometry(self):
broken_power_law_0 = aast.mp.SphericalBrokenPowerLaw(centre=(0.0, 0.0))
broken_power_law_1 = aast.mp.SphericalBrokenPowerLaw(centre=(1.0, 1.0))
assert broken_power_law_0.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 1.0]])
) == broken_power_law_1.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 0.0]])
)
broken_power_law_0 = aast.mp.SphericalBrokenPowerLaw(centre=(0.0, 0.0))
broken_power_law_1 = aast.mp.SphericalBrokenPowerLaw(centre=(0.0, 0.0))
assert broken_power_law_0.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 0.0]])
) == broken_power_law_1.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
)
broken_power_law_0 = aast.mp.EllipticalBrokenPowerLaw(
centre=(0.0, 0.0), axis_ratio=0.8, phi=0.0
)
broken_power_law_1 = aast.mp.EllipticalBrokenPowerLaw(
centre=(0.0, 0.0), axis_ratio=0.8, phi=90.0
)
assert broken_power_law_0.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 0.0]])
) == broken_power_law_1.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
)
def test__deflections__change_geometry(self):
broken_power_law_0 = aast.mp.SphericalBrokenPowerLaw(centre=(0.0, 0.0))
broken_power_law_1 = aast.mp.SphericalBrokenPowerLaw(centre=(1.0, 1.0))
deflections_0 = broken_power_law_0.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 1.0]])
)
deflections_1 = broken_power_law_1.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 0.0]])
)
assert deflections_0[0, 0] == pytest.approx(-deflections_1[0, 0], 1e-5)
assert deflections_0[0, 1] == pytest.approx(-deflections_1[0, 1], 1e-5)
broken_power_law_0 = aast.mp.SphericalBrokenPowerLaw(centre=(0.0, 0.0))
broken_power_law_1 = aast.mp.SphericalBrokenPowerLaw(centre=(0.0, 0.0))
deflections_0 = broken_power_law_0.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 0.0]])
)
deflections_1 = broken_power_law_1.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
)
assert deflections_0[0, 0] == pytest.approx(deflections_1[0, 1], 1e-5)
assert deflections_0[0, 1] == pytest.approx(deflections_1[0, 0], 1e-5)
broken_power_law_0 = aast.mp.EllipticalBrokenPowerLaw(
centre=(0.0, 0.0), axis_ratio=0.8, phi=0.0
)
broken_power_law_1 = aast.mp.EllipticalBrokenPowerLaw(
centre=(0.0, 0.0), axis_ratio=0.8, phi=90.0
)
deflections_0 = broken_power_law_0.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 0.0]])
)
deflections_1 = broken_power_law_1.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
)
assert deflections_0[0, 0] == pytest.approx(deflections_1[0, 1], 1e-5)
assert deflections_0[0, 1] == pytest.approx(deflections_1[0, 0], 1e-5)
def test__deflections__compare_to_power_law(self):
broken_power_law = aast.mp.SphericalBrokenPowerLaw(
centre=(0, 0),
einstein_radius=2.0,
inner_slope=1.999,
outer_slope=2.0001,
break_radius=0.0001,
)
deflections = broken_power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.5, 1.0]])
)
# Use of ratio avoids normalization definition difference effects
broken_yx_ratio = deflections[0, 0] / deflections[0, 1]
power_law = aast.mp.SphericalPowerLaw(
centre=(0, 0), einstein_radius=2.0, slope=2.0
)
deflections = power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.5, 1.0]])
)
power_law_yx_ratio = deflections[0, 0] / deflections[0, 1]
assert broken_yx_ratio == pytest.approx(power_law_yx_ratio, 1.0e-4)
broken_power_law = aast.mp.SphericalBrokenPowerLaw(
centre=(0, 0),
einstein_radius=2.0,
inner_slope=2.399,
outer_slope=2.4001,
break_radius=0.0001,
)
deflections = broken_power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.5, 1.0]])
)
# Use of ratio avoids normalization difference effects
broken_yx_ratio = deflections[0, 0] / deflections[0, 1]
power_law = aast.mp.SphericalPowerLaw(
centre=(0, 0), einstein_radius=2.0, slope=2.4
)
deflections = power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.5, 1.0]])
)
power_law_yx_ratio = deflections[0, 0] / deflections[0, 1]
assert broken_yx_ratio == pytest.approx(power_law_yx_ratio, 1.0e-4)
def test__deflections_of_both_profiles__dont_use_interpolate_and_cache_decorators(
self
):
broken_power_law = aast.mp.SphericalBrokenPowerLaw(
centre=(0, 0),
einstein_radius=2.0,
inner_slope=2.399,
outer_slope=2.4001,
break_radius=0.0001,
)
mask = np.array(
[
[True, True, True, True, True],
[True, False, False, False, True],
[True, False, True, False, True],
[True, False, False, False, True],
[True, True, True, True, True],
]
)
mask = aa.mask.manual(mask, pixel_scales=(1.0, 1.0), sub_size=1)
grid = aa.masked.grid.from_mask(mask=mask)
true_deflections = broken_power_law.deflections_from_grid(grid=grid)
regular_with_interp = grid.new_grid_with_interpolator(
pixel_scale_interpolation_grid=0.5
)
interp_deflections = broken_power_law.deflections_from_grid(
grid=regular_with_interp
)
assert np.max(true_deflections[:, 0] - interp_deflections[:, 0]) < 0.1
assert np.max(true_deflections[:, 1] - interp_deflections[:, 1]) < 0.1
interpolator = grids.Interpolator.from_mask_grid_and_pixel_scale_interpolation_grids(
mask=mask, grid=grid, pixel_scale_interpolation_grid=0.5
)
interp_deflections_values = broken_power_law.deflections_from_grid(
grid=interpolator.interp_grid
)
interp_deflections_manual_y = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 0]
)
interp_deflections_manual_x = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 1]
)
assert (interp_deflections_manual_y != interp_deflections[:, 0]).all()
assert (interp_deflections_manual_x != interp_deflections[:, 1]).all()
broken_power_law = aast.mp.EllipticalBrokenPowerLaw(
centre=(0, 0),
einstein_radius=2.0,
inner_slope=2.399,
outer_slope=2.4001,
break_radius=0.0001,
)
mask = np.array(
[
[True, True, True, True, True],
[True, False, False, False, True],
[True, False, True, False, True],
[True, False, False, False, True],
[True, True, True, True, True],
]
)
mask = aa.mask.manual(mask, pixel_scales=(1.0, 1.0), sub_size=1)
grid = aa.masked.grid.from_mask(mask=mask)
true_deflections = broken_power_law.deflections_from_grid(grid=grid)
regular_with_interp = grid.new_grid_with_interpolator(
pixel_scale_interpolation_grid=0.5
)
interp_deflections = broken_power_law.deflections_from_grid(
grid=regular_with_interp
)
assert np.max(true_deflections[:, 0] - interp_deflections[:, 0]) < 0.1
assert np.max(true_deflections[:, 1] - interp_deflections[:, 1]) < 0.1
interpolator = grids.Interpolator.from_mask_grid_and_pixel_scale_interpolation_grids(
mask=mask, grid=grid, pixel_scale_interpolation_grid=0.5
)
interp_deflections_values = broken_power_law.deflections_from_grid(
grid=interpolator.interp_grid
)
interp_deflections_manual_y = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 0]
)
interp_deflections_manual_x = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 1]
)
assert (interp_deflections_manual_y != interp_deflections[:, 0]).all()
assert (interp_deflections_manual_x != interp_deflections[:, 1]).all()
def test__output_are_autoarrays(self):
grid = aa.grid.uniform(shape_2d=(2, 2), pixel_scales=1.0, sub_size=1)
cored_power_law = aast.mp.EllipticalBrokenPowerLaw()
convergence = cored_power_law.convergence_from_grid(grid=grid)
assert convergence.shape_2d == (2, 2)
deflections = cored_power_law.deflections_from_grid(grid=grid)
assert deflections.shape_2d == (2, 2)
cored_power_law = aast.mp.SphericalBrokenPowerLaw()
convergence = cored_power_law.convergence_from_grid(grid=grid)
assert convergence.shape_2d == (2, 2)
deflections = cored_power_law.deflections_from_grid(grid=grid)
assert deflections.shape_2d == (2, 2)
class TestCoredPowerLaw:
def test__constructor_and_units(self):
cored_power_law = aast.mp.EllipticalCoredPowerLaw(
centre=(1.0, 2.0),
axis_ratio=0.5,
phi=45.0,
einstein_radius=1.0,
slope=2.2,
core_radius=0.1,
)
assert cored_power_law.centre == (1.0, 2.0)
assert isinstance(cored_power_law.centre[0], aast.dim.Length)
assert isinstance(cored_power_law.centre[1], aast.dim.Length)
assert cored_power_law.centre[0].unit == "arcsec"
assert cored_power_law.centre[1].unit == "arcsec"
assert cored_power_law.axis_ratio == 0.5
assert isinstance(cored_power_law.axis_ratio, float)
assert cored_power_law.phi == 45.0
assert isinstance(cored_power_law.phi, float)
assert cored_power_law.einstein_radius == 1.0
assert isinstance(cored_power_law.einstein_radius, aast.dim.Length)
assert cored_power_law.einstein_radius.unit_length == "arcsec"
assert cored_power_law.slope == 2.2
assert isinstance(cored_power_law.slope, float)
assert cored_power_law.core_radius == 0.1
assert isinstance(cored_power_law.core_radius, aast.dim.Length)
assert cored_power_law.core_radius.unit_length == "arcsec"
assert cored_power_law.einstein_radius_rescaled == pytest.approx(
0.53333333, 1.0e-4
)
cored_power_law = aast.mp.SphericalCoredPowerLaw(
centre=(1.0, 2.0), einstein_radius=1.0, slope=2.2, core_radius=0.1
)
assert cored_power_law.centre == (1.0, 2.0)
assert isinstance(cored_power_law.centre[0], aast.dim.Length)
assert isinstance(cored_power_law.centre[1], aast.dim.Length)
assert cored_power_law.centre[0].unit == "arcsec"
assert cored_power_law.centre[1].unit == "arcsec"
assert cored_power_law.axis_ratio == 1.0
assert isinstance(cored_power_law.axis_ratio, float)
assert cored_power_law.phi == 0.0
assert isinstance(cored_power_law.phi, float)
assert cored_power_law.einstein_radius == 1.0
assert isinstance(cored_power_law.einstein_radius, aast.dim.Length)
assert cored_power_law.einstein_radius.unit_length == "arcsec"
assert cored_power_law.slope == 2.2
assert isinstance(cored_power_law.slope, float)
assert cored_power_law.core_radius == 0.1
assert isinstance(cored_power_law.core_radius, aast.dim.Length)
assert cored_power_law.core_radius.unit_length == "arcsec"
assert cored_power_law.einstein_radius_rescaled == pytest.approx(0.4, 1.0e-4)
def test__convergence_correct_values(self):
cored_power_law = aast.mp.SphericalCoredPowerLaw(
centre=(1, 1), einstein_radius=1.0, slope=2.2, core_radius=0.1
)
assert cored_power_law.convergence_func(grid_radius=1.0) == pytest.approx(
0.39762, 1e-4
)
cored_power_law = aast.mp.EllipticalCoredPowerLaw(
centre=(0.0, 0.0),
axis_ratio=0.5,
phi=0.0,
einstein_radius=1.0,
slope=2.3,
core_radius=0.2,
)
assert cored_power_law.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
) == pytest.approx(0.45492, 1e-3)
cored_power_law = aast.mp.EllipticalCoredPowerLaw(
centre=(0.0, 0.0),
axis_ratio=0.5,
phi=0.0,
einstein_radius=2.0,
slope=1.7,
core_radius=0.2,
)
assert cored_power_law.convergence_from_grid(
grid=aa.coordinates([[(0.0, 1.0)]])
)[0][0] == pytest.approx(1.3887, 1e-3)
def test__potential_correct_values(self):
power_law = aast.mp.SphericalCoredPowerLaw(
centre=(-0.7, 0.5), einstein_radius=1.0, slope=1.8, core_radius=0.2
)
assert power_law.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1875, 0.1625]])
) == pytest.approx(0.54913, 1e-3)
power_law = aast.mp.SphericalCoredPowerLaw(
centre=(0.2, -0.2), einstein_radius=0.5, slope=2.4, core_radius=0.5
)
assert power_law.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1875, 0.1625]])
) == pytest.approx(0.01820, 1e-3)
cored_power_law = aast.mp.EllipticalCoredPowerLaw(
centre=(0.2, -0.2),
axis_ratio=0.6,
phi=120.0,
einstein_radius=0.5,
slope=2.4,
core_radius=0.5,
)
assert cored_power_law.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1625, 0.1625]])
) == pytest.approx(0.02319, 1e-3)
cored_power_law = aast.mp.EllipticalCoredPowerLaw(
centre=(-0.7, 0.5),
axis_ratio=0.7,
phi=60.0,
einstein_radius=1.3,
slope=1.8,
core_radius=0.2,
)
assert cored_power_law.potential_from_grid(
grid=aa.coordinates([[(0.1625, 0.1625)]])
)[0][0] == pytest.approx(0.71185, 1e-3)
def test__deflections__correct_values(self):
power_law = aast.mp.SphericalCoredPowerLaw(
centre=(-0.7, 0.5), einstein_radius=1.0, slope=1.8, core_radius=0.2
)
deflections = power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1875, 0.1625]])
)
assert deflections[0, 0] == pytest.approx(0.80677, 1e-3)
assert deflections[0, 1] == pytest.approx(-0.30680, 1e-3)
power_law = aast.mp.SphericalCoredPowerLaw(
centre=(0.2, -0.2), einstein_radius=0.5, slope=2.4, core_radius=0.5
)
deflections = power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1875, 0.1625]])
)
assert deflections[0, 0] == pytest.approx(-0.00321, 1e-3)
assert deflections[0, 1] == pytest.approx(0.09316, 1e-3)
cored_power_law = aast.mp.EllipticalCoredPowerLaw(
centre=(-0.7, 0.5),
axis_ratio=0.7,
phi=60.0,
einstein_radius=1.3,
slope=1.8,
core_radius=0.2,
)
deflections = cored_power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1625, 0.1625]])
)
assert deflections[0, 0] == pytest.approx(0.9869, 1e-3)
assert deflections[0, 1] == pytest.approx(-0.54882, 1e-3)
cored_power_law = aast.mp.EllipticalCoredPowerLaw(
centre=(0.2, -0.2),
axis_ratio=0.6,
phi=120.0,
einstein_radius=0.5,
slope=2.4,
core_radius=0.5,
)
deflections = cored_power_law.deflections_from_grid(
grid=aa.coordinates([[(0.1625, 0.1625)]])
)
assert deflections[0][0][0] == pytest.approx(0.01111, 1e-3)
assert deflections[0][0][1] == pytest.approx(0.11403, 1e-3)
def test__convergence__change_geometry(self):
cored_power_law_0 = aast.mp.SphericalCoredPowerLaw(centre=(0.0, 0.0))
cored_power_law_1 = aast.mp.SphericalCoredPowerLaw(centre=(1.0, 1.0))
assert cored_power_law_0.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 1.0]])
) == cored_power_law_1.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 0.0]])
)
cored_power_law_0 = aast.mp.SphericalCoredPowerLaw(centre=(0.0, 0.0))
cored_power_law_1 = aast.mp.SphericalCoredPowerLaw(centre=(0.0, 0.0))
assert cored_power_law_0.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 0.0]])
) == cored_power_law_1.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
)
cored_power_law_0 = aast.mp.EllipticalCoredPowerLaw(
centre=(0.0, 0.0), axis_ratio=0.8, phi=0.0
)
cored_power_law_1 = aast.mp.EllipticalCoredPowerLaw(
centre=(0.0, 0.0), axis_ratio=0.8, phi=90.0
)
assert cored_power_law_0.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 0.0]])
) == cored_power_law_1.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
)
def test__potential__change_geometry(self):
cored_power_law_0 = aast.mp.SphericalCoredPowerLaw(centre=(0.0, 0.0))
cored_power_law_1 = aast.mp.SphericalCoredPowerLaw(centre=(1.0, 1.0))
assert cored_power_law_0.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 1.0]])
) == cored_power_law_1.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 0.0]])
)
cored_power_law_0 = aast.mp.SphericalCoredPowerLaw(centre=(0.0, 0.0))
cored_power_law_1 = aast.mp.SphericalCoredPowerLaw(centre=(0.0, 0.0))
assert cored_power_law_0.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 0.0]])
) == cored_power_law_1.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
)
cored_power_law_0 = aast.mp.EllipticalCoredPowerLaw(
centre=(0.0, 0.0), axis_ratio=0.8, phi=0.0
)
cored_power_law_1 = aast.mp.EllipticalCoredPowerLaw(
centre=(0.0, 0.0), axis_ratio=0.8, phi=90.0
)
assert cored_power_law_0.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 0.0]])
) == cored_power_law_1.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
)
def test__deflections__change_geometry(self):
cored_power_law_0 = aast.mp.SphericalCoredPowerLaw(centre=(0.0, 0.0))
cored_power_law_1 = aast.mp.SphericalCoredPowerLaw(centre=(1.0, 1.0))
deflections_0 = cored_power_law_0.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 1.0]])
)
deflections_1 = cored_power_law_1.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 0.0]])
)
assert deflections_0[0, 0] == pytest.approx(-deflections_1[0, 0], 1e-5)
assert deflections_0[0, 1] == pytest.approx(-deflections_1[0, 1], 1e-5)
cored_power_law_0 = aast.mp.SphericalCoredPowerLaw(centre=(0.0, 0.0))
cored_power_law_1 = aast.mp.SphericalCoredPowerLaw(centre=(0.0, 0.0))
deflections_0 = cored_power_law_0.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 0.0]])
)
deflections_1 = cored_power_law_1.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
)
assert deflections_0[0, 0] == pytest.approx(deflections_1[0, 1], 1e-5)
assert deflections_0[0, 1] == pytest.approx(deflections_1[0, 0], 1e-5)
cored_power_law_0 = aast.mp.EllipticalCoredPowerLaw(
centre=(0.0, 0.0), axis_ratio=0.8, phi=0.0
)
cored_power_law_1 = aast.mp.EllipticalCoredPowerLaw(
centre=(0.0, 0.0), axis_ratio=0.8, phi=90.0
)
deflections_0 = cored_power_law_0.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 0.0]])
)
deflections_1 = cored_power_law_1.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
)
assert deflections_0[0, 0] == pytest.approx(deflections_1[0, 1], 1e-5)
assert deflections_0[0, 1] == pytest.approx(deflections_1[0, 0], 1e-5)
def test__multiple_coordinates_in__multiple_quantities_out(self):
cored_power_law = aast.mp.EllipticalCoredPowerLaw(
centre=(0.0, 0.0),
axis_ratio=0.5,
phi=0.0,
einstein_radius=1.0,
slope=2.3,
core_radius=0.2,
)
assert cored_power_law.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0], [0.0, 1.0]])
)[0] == pytest.approx(0.45492, 1e-3)
assert cored_power_law.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0], [0.0, 1.0]])
)[1] == pytest.approx(0.45492, 1e-3)
cored_power_law = aast.mp.EllipticalCoredPowerLaw(
centre=(0.2, -0.2),
axis_ratio=0.6,
phi=120.0,
einstein_radius=0.5,
slope=2.4,
core_radius=0.5,
)
assert cored_power_law.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1625, 0.1625], [0.1625, 0.1625]])
)[0] == pytest.approx(0.02319, 1e-3)
assert cored_power_law.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1625, 0.1625], [0.1625, 0.1625]])
)[1] == pytest.approx(0.02319, 1e-3)
cored_power_law = aast.mp.EllipticalCoredPowerLaw(
centre=(-0.7, 0.5),
axis_ratio=0.7,
phi=60.0,
einstein_radius=1.3,
slope=1.8,
core_radius=0.2,
)
deflections = cored_power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1625, 0.1625], [0.1625, 0.1625]])
)
assert deflections[0, 0] == pytest.approx(0.9869, 1e-3)
assert deflections[0, 1] == pytest.approx(-0.54882, 1e-3)
assert deflections[1, 0] == pytest.approx(0.9869, 1e-3)
assert deflections[1, 1] == pytest.approx(-0.54882, 1e-3)
def test__spherical_and_elliptical_match(self):
elliptical = aast.mp.EllipticalCoredPowerLaw(
centre=(1.1, 1.1),
axis_ratio=1.0,
phi=0.0,
einstein_radius=3.0,
slope=2.2,
core_radius=0.1,
)
spherical = aast.mp.SphericalCoredPowerLaw(
centre=(1.1, 1.1), einstein_radius=3.0, slope=2.2, core_radius=0.1
)
assert elliptical.convergence_from_grid(grid=grid) == pytest.approx(
spherical.convergence_from_grid(grid=grid), 1e-4
)
assert elliptical.potential_from_grid(grid=grid) == pytest.approx(
spherical.potential_from_grid(grid=grid), 1e-4
)
assert elliptical.deflections_from_grid(grid=grid) == pytest.approx(
spherical.deflections_from_grid(grid=grid), 1e-4
)
def test__deflections_of_elliptical_profile__use_interpolate_and_cache_decorators(
self
):
cored_power_law = aast.mp.EllipticalCoredPowerLaw(
centre=(-0.7, 0.5),
axis_ratio=0.7,
phi=60.0,
einstein_radius=1.3,
slope=1.8,
core_radius=0.2,
)
mask = np.array(
[
[True, True, True, True, True],
[True, False, False, False, True],
[True, False, True, False, True],
[True, False, False, False, True],
[True, True, True, True, True],
]
)
mask = aa.mask.manual(mask, pixel_scales=(1.0, 1.0), sub_size=1)
grid = aa.masked.grid.from_mask(mask=mask)
true_deflections = cored_power_law.deflections_from_grid(grid=grid)
regular_with_interp = grid.new_grid_with_interpolator(
pixel_scale_interpolation_grid=0.5
)
interp_deflections = cored_power_law.deflections_from_grid(
grid=regular_with_interp
)
assert np.max(true_deflections[:, 0] - interp_deflections[:, 0]) < 0.1
assert np.max(true_deflections[:, 1] - interp_deflections[:, 1]) < 0.1
interpolator = grids.Interpolator.from_mask_grid_and_pixel_scale_interpolation_grids(
mask=mask, grid=grid, pixel_scale_interpolation_grid=0.5
)
interp_deflections_values = cored_power_law.deflections_from_grid(
grid=interpolator.interp_grid
)
interp_deflections_manual_y = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 0]
)
interp_deflections_manual_x = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 1]
)
assert (interp_deflections_manual_y == interp_deflections[:, 0]).all()
assert (interp_deflections_manual_x == interp_deflections[:, 1]).all()
def test__deflections_of_spherical_profile__dont_use_interpolate_and_cache_decorators(
self
):
cored_power_law = aast.mp.SphericalCoredPowerLaw(
centre=(-0.7, 0.5), einstein_radius=1.3, slope=1.8, core_radius=0.2
)
mask = np.array(
[
[True, True, True, True, True],
[True, False, False, False, True],
[True, False, True, False, True],
[True, False, False, False, True],
[True, True, True, True, True],
]
)
mask = aa.mask.manual(mask, pixel_scales=(1.0, 1.0), sub_size=1)
grid = aa.masked.grid.from_mask(mask=mask)
true_deflections = cored_power_law.deflections_from_grid(grid=grid)
regular_with_interp = grid.new_grid_with_interpolator(
pixel_scale_interpolation_grid=0.5
)
interp_deflections = cored_power_law.deflections_from_grid(
grid=regular_with_interp
)
assert np.max(true_deflections[:, 0] - interp_deflections[:, 0]) < 0.1
assert np.max(true_deflections[:, 1] - interp_deflections[:, 1]) < 0.1
interpolator = grids.Interpolator.from_mask_grid_and_pixel_scale_interpolation_grids(
mask=mask, grid=grid, pixel_scale_interpolation_grid=0.5
)
interp_deflections_values = cored_power_law.deflections_from_grid(
grid=interpolator.interp_grid
)
interp_deflections_manual_y = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 0]
)
interp_deflections_manual_x = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 1]
)
assert (interp_deflections_manual_y != interp_deflections[:, 0]).all()
assert (interp_deflections_manual_x != interp_deflections[:, 1]).all()
def test__summarize_in_units(self):
test_path = "{}/../../test_files/config/summary".format(
os.path.dirname(os.path.realpath(__file__))
)
af.conf.instance = af.conf.Config(config_path=test_path)
cored_power_law = aast.mp.SphericalCoredPowerLaw(
centre=(0.0, 0.0), einstein_radius=1.0, core_radius=0.0, slope=2.0
)
summary_text = cored_power_law.summarize_in_units(
radii=[aast.dim.Length(10.0), aast.dim.Length(500.0)],
prefix="pl_",
unit_length="arcsec",
unit_mass="angular",
whitespace=50,
)
i = 0
assert summary_text[i] == "Mass Profile = SphericalCoredPowerLaw\n"
i += 1
assert (
summary_text[i]
== "pl_einstein_radius 1.00 arcsec"
)
i += 1
assert (
summary_text[i]
== "pl_einstein_mass 3.1308e+00 angular"
)
i += 1
assert (
summary_text[i]
== "pl_mass_within_10.00_arcsec 3.1416e+01 angular"
)
i += 1
assert (
summary_text[i]
== "pl_mass_within_500.00_arcsec 1.5708e+03 angular"
)
i += 1
def test__output_are_autoarrays(self):
grid = aa.grid.uniform(shape_2d=(2, 2), pixel_scales=1.0, sub_size=1)
cored_power_law = aast.mp.EllipticalCoredPowerLaw()
convergence = cored_power_law.convergence_from_grid(grid=grid)
assert convergence.shape_2d == (2, 2)
potential = cored_power_law.potential_from_grid(grid=grid)
assert potential.shape_2d == (2, 2)
deflections = cored_power_law.deflections_from_grid(grid=grid)
assert deflections.shape_2d == (2, 2)
cored_power_law = aast.mp.SphericalCoredPowerLaw()
convergence = cored_power_law.convergence_from_grid(grid=grid)
assert convergence.shape_2d == (2, 2)
potential = cored_power_law.potential_from_grid(grid=grid)
assert potential.shape_2d == (2, 2)
deflections = cored_power_law.deflections_from_grid(grid=grid)
assert deflections.shape_2d == (2, 2)
class TestPowerLaw:
def test__constructor_and_units(self):
power_law = aast.mp.EllipticalPowerLaw(
centre=(1.0, 2.0), axis_ratio=0.5, phi=45.0, einstein_radius=1.0, slope=2.0
)
assert power_law.centre == (1.0, 2.0)
assert isinstance(power_law.centre[0], aast.dim.Length)
assert isinstance(power_law.centre[1], aast.dim.Length)
assert power_law.centre[0].unit == "arcsec"
assert power_law.centre[1].unit == "arcsec"
assert power_law.axis_ratio == 0.5
assert isinstance(power_law.axis_ratio, float)
assert power_law.phi == 45.0
assert isinstance(power_law.phi, float)
assert power_law.einstein_radius == 1.0
assert isinstance(power_law.einstein_radius, aast.dim.Length)
assert power_law.einstein_radius.unit_length == "arcsec"
assert power_law.slope == 2.0
assert isinstance(power_law.slope, float)
assert power_law.core_radius == 0.0
assert isinstance(power_law.core_radius, aast.dim.Length)
assert power_law.core_radius.unit_length == "arcsec"
assert power_law.einstein_radius_rescaled == pytest.approx(0.6666666666, 1.0e-4)
power_law = aast.mp.SphericalPowerLaw(
centre=(1.0, 2.0), einstein_radius=1.0, slope=2.0
)
assert power_law.centre == (1.0, 2.0)
assert isinstance(power_law.centre[0], aast.dim.Length)
assert isinstance(power_law.centre[1], aast.dim.Length)
assert power_law.centre[0].unit == "arcsec"
assert power_law.centre[1].unit == "arcsec"
assert power_law.axis_ratio == 1.0
assert isinstance(power_law.axis_ratio, float)
assert power_law.phi == 0.0
assert isinstance(power_law.phi, float)
assert power_law.einstein_radius == 1.0
assert isinstance(power_law.einstein_radius, aast.dim.Length)
assert power_law.einstein_radius.unit_length == "arcsec"
assert power_law.slope == 2.0
assert isinstance(power_law.slope, float)
assert power_law.core_radius == 0.0
assert isinstance(power_law.core_radius, aast.dim.Length)
assert power_law.core_radius.unit_length == "arcsec"
assert power_law.einstein_radius_rescaled == pytest.approx(0.5, 1.0e-4)
def test__convergence_correct_values(self):
isothermal = aast.mp.SphericalPowerLaw(
centre=(0.0, 0.0), einstein_radius=1.0, slope=2.0
)
assert isothermal.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 0.0]])
) == pytest.approx(0.5, 1e-3)
isothermal = aast.mp.SphericalPowerLaw(
centre=(0.0, 0.0), einstein_radius=2.0, slope=2.2
)
assert isothermal.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[2.0, 0.0]])
) == pytest.approx(0.4, 1e-3)
power_law = aast.mp.SphericalPowerLaw(
centre=(0.0, 0.0), einstein_radius=2.0, slope=2.2
)
assert power_law.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[2.0, 0.0]])
) == pytest.approx(0.4, 1e-3)
power_law = aast.mp.EllipticalPowerLaw(
centre=(0.0, 0.0), axis_ratio=0.5, phi=0.0, einstein_radius=1.0, slope=2.3
)
assert power_law.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
) == pytest.approx(0.466666, 1e-3)
power_law = aast.mp.EllipticalPowerLaw(
centre=(0.0, 0.0), axis_ratio=0.5, phi=0.0, einstein_radius=2.0, slope=1.7
)
assert power_law.convergence_from_grid(grid=aa.coordinates([[(0.0, 1.0)]]))[0][
0
] == pytest.approx(1.4079, 1e-3)
def test__potential_correct_values(self):
power_law = aast.mp.SphericalPowerLaw(
centre=(-0.7, 0.5), einstein_radius=1.3, slope=2.3
)
assert power_law.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1625, 0.1625]])
) == pytest.approx(1.90421, 1e-3)
power_law = aast.mp.SphericalPowerLaw(
centre=(-0.7, 0.5), einstein_radius=1.3, slope=1.8
)
assert power_law.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1625, 0.1625]])
) == pytest.approx(0.93758, 1e-3)
power_law = aast.mp.EllipticalPowerLaw(
centre=(-0.7, 0.5), axis_ratio=0.7, phi=60.0, einstein_radius=1.3, slope=2.2
)
assert power_law.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1625, 0.1625]])
) == pytest.approx(1.53341, 1e-3)
power_law = aast.mp.EllipticalPowerLaw(
centre=(-0.7, 0.5), axis_ratio=0.7, phi=60.0, einstein_radius=1.3, slope=1.8
)
assert power_law.potential_from_grid(grid=aa.coordinates([[(0.1625, 0.1625)]]))[
0
][0] == pytest.approx(0.96723, 1e-3)
def test__deflections__correct_values(self):
power_law = aast.mp.SphericalPowerLaw(
centre=(0.2, 0.2), einstein_radius=1.0, slope=2.0
)
deflections = power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1875, 0.1625]])
)
assert deflections[0, 0] == pytest.approx(-0.31622, 1e-3)
assert deflections[0, 1] == pytest.approx(-0.94868, 1e-3)
power_law = aast.mp.SphericalPowerLaw(
centre=(0.2, 0.2), einstein_radius=1.0, slope=2.5
)
deflections = power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1875, 0.1625]])
)
assert deflections[0, 0] == pytest.approx(-1.59054, 1e-3)
assert deflections[0, 1] == pytest.approx(-4.77162, 1e-3)
power_law = aast.mp.SphericalPowerLaw(
centre=(0.2, 0.2), einstein_radius=1.0, slope=1.5
)
deflections = power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1875, 0.1625]])
)
assert deflections[0, 0] == pytest.approx(-0.06287, 1e-3)
assert deflections[0, 1] == pytest.approx(-0.18861, 1e-3)
power_law = aast.mp.EllipticalPowerLaw(
centre=(0, 0), axis_ratio=0.5, phi=0.0, einstein_radius=1.0, slope=2.0
)
deflections = power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1625, 0.1625]])
)
assert deflections[0, 0] == pytest.approx(0.79421, 1e-3)
assert deflections[0, 1] == pytest.approx(0.50734, 1e-3)
power_law = aast.mp.EllipticalPowerLaw(
centre=(0, 0), axis_ratio=0.5, phi=0.0, einstein_radius=1.0, slope=2.5
)
deflections = power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1625, 0.1625]])
)
assert deflections[0, 0] == pytest.approx(1.29641, 1e-3)
assert deflections[0, 1] == pytest.approx(0.99629, 1e-3)
power_law = aast.mp.EllipticalPowerLaw(
centre=(0, 0), axis_ratio=0.5, phi=0.0, einstein_radius=1.0, slope=1.5
)
deflections = power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1625, 0.1625]])
)
assert deflections[0, 0] == pytest.approx(0.48036, 1e-3)
assert deflections[0, 1] == pytest.approx(0.26729, 1e-3)
power_law = aast.mp.EllipticalPowerLaw(
centre=(-0.7, 0.5), axis_ratio=0.7, phi=60.0, einstein_radius=1.3, slope=1.9
)
deflections = power_law.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1625, 0.1625]])
)
# assert deflections[0, 0] == pytest.approx(1.12841, 1e-3)
# assert deflections[0, 1] == pytest.approx(-0.60205, 1e-3)
power_law = aast.mp.EllipticalPowerLaw(
centre=(-0.7, 0.5),
axis_ratio=0.7,
phi=150.0,
einstein_radius=1.3,
slope=2.2,
)
deflections = power_law.deflections_from_grid(
grid=aa.coordinates([[(0.1625, 0.1625)]])
)
assert deflections[0][0][0] == pytest.approx(1.25995, 1e-3)
assert deflections[0][0][1] == pytest.approx(-0.35096, 1e-3)
def test__compare_to_cored_power_law(self):
power_law = aast.mp.EllipticalPowerLaw(
centre=(0.0, 0.0), axis_ratio=0.5, phi=45.0, einstein_radius=1.0, slope=2.3
)
cored_power_law = aast.mp.EllipticalCoredPowerLaw(
centre=(0.0, 0.0),
axis_ratio=0.5,
phi=45.0,
einstein_radius=1.0,
slope=2.3,
core_radius=0.0,
)
assert power_law.potential_from_grid(grid=grid) == pytest.approx(
cored_power_law.potential_from_grid(grid=grid), 1e-3
)
assert power_law.potential_from_grid(grid=grid) == pytest.approx(
cored_power_law.potential_from_grid(grid=grid), 1e-3
)
assert power_law.deflections_from_grid(grid=grid) == pytest.approx(
cored_power_law.deflections_from_grid(grid=grid), 1e-3
)
assert power_law.deflections_from_grid(grid=grid) == pytest.approx(
cored_power_law.deflections_from_grid(grid=grid), 1e-3
)
def test__spherical_and_elliptical_match(self):
elliptical = aast.mp.EllipticalPowerLaw(
centre=(1.1, 1.1),
axis_ratio=0.9999,
phi=0.0,
einstein_radius=3.0,
slope=2.4,
)
spherical = aast.mp.SphericalPowerLaw(
centre=(1.1, 1.1), einstein_radius=3.0, slope=2.4
)
assert elliptical.convergence_from_grid(grid=grid) == pytest.approx(
spherical.convergence_from_grid(grid=grid), 1e-4
)
assert elliptical.potential_from_grid(grid=grid) == pytest.approx(
spherical.potential_from_grid(grid=grid), 1e-4
)
assert elliptical.deflections_from_grid(grid=grid) == pytest.approx(
spherical.deflections_from_grid(grid=grid), 1e-4
)
def test__deflections_of_elliptical_profile__dont_use_interpolate_and_cache_decorators(
self
):
power_law = aast.mp.EllipticalPowerLaw(
centre=(-0.7, 0.5), axis_ratio=0.7, phi=60.0, einstein_radius=1.3, slope=1.8
)
mask = np.array(
[
[True, True, True, True, True],
[True, False, False, False, True],
[True, False, True, False, True],
[True, False, False, False, True],
[True, True, True, True, True],
]
)
mask = aa.mask.manual(mask, pixel_scales=(1.0, 1.0), sub_size=1)
grid = aa.masked.grid.from_mask(mask=mask)
regular_with_interp = grid.new_grid_with_interpolator(
pixel_scale_interpolation_grid=0.5
)
interp_deflections = power_law.deflections_from_grid(grid=regular_with_interp)
interpolator = grids.Interpolator.from_mask_grid_and_pixel_scale_interpolation_grids(
mask=mask, grid=grid, pixel_scale_interpolation_grid=0.5
)
interp_deflections_values = power_law.deflections_from_grid(
grid=interpolator.interp_grid
)
interp_deflections_manual_y = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 0]
)
interp_deflections_manual_x = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 1]
)
assert (interp_deflections_manual_y != interp_deflections[:, 0]).all()
assert (interp_deflections_manual_x != interp_deflections[:, 1]).all()
def test__deflections_of_spherical_profile__dont_use_interpolate_and_cache_decorators(
self
):
power_law = aast.mp.SphericalPowerLaw(
centre=(-0.7, 0.5), einstein_radius=1.3, slope=1.8
)
mask = np.array(
[
[True, True, True, True, True],
[True, False, False, False, True],
[True, False, True, False, True],
[True, False, False, False, True],
[True, True, True, True, True],
]
)
mask = aa.mask.manual(mask, pixel_scales=(1.0, 1.0), sub_size=1)
grid = aa.masked.grid.from_mask(mask=mask)
regular_with_interp = grid.new_grid_with_interpolator(
pixel_scale_interpolation_grid=0.5
)
interp_deflections = power_law.deflections_from_grid(grid=regular_with_interp)
interpolator = grids.Interpolator.from_mask_grid_and_pixel_scale_interpolation_grids(
mask=mask, grid=grid, pixel_scale_interpolation_grid=0.5
)
interp_deflections_values = power_law.deflections_from_grid(
grid=interpolator.interp_grid
)
interp_deflections_manual_y = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 0]
)
interp_deflections_manual_x = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 1]
)
assert (interp_deflections_manual_y != interp_deflections[:, 0]).all()
assert (interp_deflections_manual_x != interp_deflections[:, 1]).all()
def test__output_are_autoarrays(self):
grid = aa.grid.uniform(shape_2d=(2, 2), pixel_scales=1.0, sub_size=1)
power_law = aast.mp.EllipticalPowerLaw()
convergence = power_law.convergence_from_grid(grid=grid)
assert convergence.shape_2d == (2, 2)
potential = power_law.potential_from_grid(grid=grid)
assert potential.shape_2d == (2, 2)
deflections = power_law.deflections_from_grid(grid=grid)
assert deflections.shape_2d == (2, 2)
power_law = aast.mp.SphericalPowerLaw()
convergence = power_law.convergence_from_grid(grid=grid)
assert convergence.shape_2d == (2, 2)
potential = power_law.potential_from_grid(grid=grid)
assert potential.shape_2d == (2, 2)
deflections = power_law.deflections_from_grid(grid=grid)
assert deflections.shape_2d == (2, 2)
class TestCoredIsothermal:
def test__constructor_and_units(self):
cored_isothermal = aast.mp.EllipticalCoredIsothermal(
centre=(1.0, 2.0),
axis_ratio=0.5,
phi=45.0,
einstein_radius=1.0,
core_radius=0.1,
)
assert cored_isothermal.centre == (1.0, 2.0)
assert isinstance(cored_isothermal.centre[0], aast.dim.Length)
assert isinstance(cored_isothermal.centre[1], aast.dim.Length)
assert cored_isothermal.centre[0].unit == "arcsec"
assert cored_isothermal.centre[1].unit == "arcsec"
assert cored_isothermal.axis_ratio == 0.5
assert isinstance(cored_isothermal.axis_ratio, float)
assert cored_isothermal.phi == 45.0
assert isinstance(cored_isothermal.phi, float)
assert cored_isothermal.einstein_radius == 1.0
assert isinstance(cored_isothermal.einstein_radius, aast.dim.Length)
assert cored_isothermal.einstein_radius.unit_length == "arcsec"
assert cored_isothermal.slope == 2.0
assert isinstance(cored_isothermal.slope, float)
assert cored_isothermal.core_radius == 0.1
assert isinstance(cored_isothermal.core_radius, aast.dim.Length)
assert cored_isothermal.core_radius.unit_length == "arcsec"
assert cored_isothermal.einstein_radius_rescaled == pytest.approx(
0.6666666666, 1.0e-4
)
cored_isothermal = aast.mp.SphericalCoredIsothermal(
centre=(1.0, 2.0), einstein_radius=1.0, core_radius=0.1
)
assert cored_isothermal.centre == (1.0, 2.0)
assert isinstance(cored_isothermal.centre[0], aast.dim.Length)
assert isinstance(cored_isothermal.centre[1], aast.dim.Length)
assert cored_isothermal.centre[0].unit == "arcsec"
assert cored_isothermal.centre[1].unit == "arcsec"
assert cored_isothermal.axis_ratio == 1.0
assert isinstance(cored_isothermal.axis_ratio, float)
assert cored_isothermal.phi == 0.0
assert isinstance(cored_isothermal.phi, float)
assert cored_isothermal.einstein_radius == 1.0
assert isinstance(cored_isothermal.einstein_radius, aast.dim.Length)
assert cored_isothermal.einstein_radius.unit_length == "arcsec"
assert cored_isothermal.slope == 2.0
assert isinstance(cored_isothermal.slope, float)
assert cored_isothermal.core_radius == 0.1
assert isinstance(cored_isothermal.core_radius, aast.dim.Length)
assert cored_isothermal.core_radius.unit_length == "arcsec"
assert cored_isothermal.einstein_radius_rescaled == pytest.approx(0.5, 1.0e-4)
def test__convergence_correct_values(self):
cored_isothermal = aast.mp.SphericalCoredIsothermal(
centre=(1, 1), einstein_radius=1.0, core_radius=0.1
)
assert cored_isothermal.convergence_func(grid_radius=1.0) == pytest.approx(
0.49752, 1e-4
)
cored_isothermal = aast.mp.SphericalCoredIsothermal(
centre=(1, 1), einstein_radius=1.0, core_radius=0.1
)
assert cored_isothermal.convergence_func(grid_radius=1.0) == pytest.approx(
0.49752, 1e-4
)
cored_isothermal = aast.mp.SphericalCoredIsothermal(
centre=(0.0, 0.0), einstein_radius=1.0, core_radius=0.2
)
assert cored_isothermal.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 0.0]])
) == pytest.approx(0.49029, 1e-3)
cored_isothermal = aast.mp.SphericalCoredIsothermal(
centre=(0.0, 0.0), einstein_radius=2.0, core_radius=0.2
)
assert cored_isothermal.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[1.0, 0.0]])
) == pytest.approx(2.0 * 0.49029, 1e-3)
cored_isothermal = aast.mp.SphericalCoredIsothermal(
centre=(0.0, 0.0), einstein_radius=1.0, core_radius=0.2
)
assert cored_isothermal.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
) == pytest.approx(0.49029, 1e-3)
# axis ratio changes only einstein_rescaled, so wwe can use the above value and times by 1.0/1.5.
cored_isothermal = aast.mp.EllipticalCoredIsothermal(
centre=(0.0, 0.0),
axis_ratio=0.5,
phi=0.0,
einstein_radius=1.0,
core_radius=0.2,
)
assert cored_isothermal.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
) == pytest.approx(0.49029 * 1.33333, 1e-3)
cored_isothermal = aast.mp.EllipticalCoredIsothermal(
centre=(0.0, 0.0),
axis_ratio=1.0,
phi=0.0,
einstein_radius=2.0,
core_radius=0.2,
)
assert cored_isothermal.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
) == pytest.approx(2.0 * 0.49029, 1e-3)
# for axis_ratio = 1.0, the factor is 1/2
# for axis_ratio = 0.5, the factor is 1/(1.5)
# So the change in the value is 0.5 / (1/1.5) = 1.0 / 0.75
# axis ratio changes only einstein_rescaled, so wwe can use the above value and times by 1.0/1.5.
cored_isothermal = aast.mp.EllipticalCoredIsothermal(
centre=(0.0, 0.0),
axis_ratio=0.5,
phi=0.0,
einstein_radius=1.0,
core_radius=0.2,
)
assert cored_isothermal.convergence_from_grid(
grid=aa.coordinates([[(0.0, 1.0)]])
)[0][0] == pytest.approx((1.0 / 0.75) * 0.49029, 1e-3)
def test__potential__correct_values(self):
isothermal_core = aast.mp.SphericalCoredIsothermal(
centre=(-0.7, 0.5), einstein_radius=1.3, core_radius=0.2
)
assert isothermal_core.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1875, 0.1625]])
) == pytest.approx(0.72231, 1e-3)
isothermal_core = aast.mp.SphericalCoredIsothermal(
centre=(0.2, -0.2), einstein_radius=0.5, core_radius=0.5
)
assert isothermal_core.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1875, 0.1625]])
) == pytest.approx(0.03103, 1e-3)
cored_isothermal = aast.mp.EllipticalCoredIsothermal(
centre=(-0.7, 0.5),
axis_ratio=0.7,
phi=60.0,
einstein_radius=1.3,
core_radius=0.2,
)
assert cored_isothermal.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1625, 0.1625]])
) == pytest.approx(0.74354, 1e-3)
cored_isothermal = aast.mp.EllipticalCoredIsothermal(
centre=(0.2, -0.2),
axis_ratio=0.6,
phi=120.0,
einstein_radius=0.5,
core_radius=0.5,
)
assert cored_isothermal.potential_from_grid(
grid=aa.coordinates([[(0.1625, 0.1625)]])
)[0][0] == pytest.approx(0.04024, 1e-3)
def test__deflections__correct_values(self):
isothermal_core = aast.mp.SphericalCoredIsothermal(
centre=(-0.7, 0.5), einstein_radius=1.3, core_radius=0.2
)
deflections = isothermal_core.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1875, 0.1625]])
)
assert deflections[0, 0] == pytest.approx(0.98582, 1e-3)
assert deflections[0, 1] == pytest.approx(-0.37489, 1e-3)
isothermal_core = aast.mp.SphericalCoredIsothermal(
centre=(0.2, -0.2), einstein_radius=0.5, core_radius=0.5
)
deflections = isothermal_core.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1875, 0.1625]])
)
assert deflections[0, 0] == pytest.approx(-0.00559, 1e-3)
assert deflections[0, 1] == pytest.approx(0.16216, 1e-3)
cored_isothermal = aast.mp.EllipticalCoredIsothermal(
centre=(-0.7, 0.5),
axis_ratio=0.7,
phi=60.0,
einstein_radius=1.3,
core_radius=0.2,
)
deflections = cored_isothermal.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1625, 0.1625]])
)
assert deflections[0, 0] == pytest.approx(0.95429, 1e-3)
assert deflections[0, 1] == pytest.approx(-0.52047, 1e-3)
cored_isothermal = aast.mp.EllipticalCoredIsothermal(
centre=(0.2, -0.2),
axis_ratio=0.6,
phi=120.0,
einstein_radius=0.5,
core_radius=0.5,
)
deflections = cored_isothermal.deflections_from_grid(
grid=aa.coordinates([[(0.1625, 0.1625)]])
)
assert deflections[0][0][0] == pytest.approx(0.02097, 1e-3)
assert deflections[0][0][1] == pytest.approx(0.20500, 1e-3)
def test__compare_to_cored_power_law(self):
power_law = aast.mp.EllipticalCoredIsothermal(
centre=(0.0, 0.0),
axis_ratio=0.5,
phi=45.0,
einstein_radius=1.0,
core_radius=0.1,
)
cored_power_law = aast.mp.EllipticalCoredPowerLaw(
centre=(0.0, 0.0),
axis_ratio=0.5,
phi=45.0,
einstein_radius=1.0,
slope=2.0,
core_radius=0.1,
)
assert power_law.potential_from_grid(grid=grid) == pytest.approx(
cored_power_law.potential_from_grid(grid=grid), 1e-3
)
assert power_law.potential_from_grid(grid=grid) == pytest.approx(
cored_power_law.potential_from_grid(grid=grid), 1e-3
)
assert power_law.deflections_from_grid(grid=grid) == pytest.approx(
cored_power_law.deflections_from_grid(grid=grid), 1e-3
)
assert power_law.deflections_from_grid(grid=grid) == pytest.approx(
cored_power_law.deflections_from_grid(grid=grid), 1e-3
)
def test__spherical_and_elliptical_match(self):
elliptical = aast.mp.EllipticalCoredIsothermal(
centre=(1.1, 1.1),
axis_ratio=0.9999,
phi=0.0,
einstein_radius=3.0,
core_radius=1.0,
)
spherical = aast.mp.SphericalCoredIsothermal(
centre=(1.1, 1.1), einstein_radius=3.0, core_radius=1.0
)
assert elliptical.convergence_from_grid(grid=grid) == pytest.approx(
spherical.convergence_from_grid(grid=grid), 1e-4
)
assert elliptical.potential_from_grid(grid=grid) == pytest.approx(
spherical.potential_from_grid(grid=grid), 1e-4
)
assert elliptical.deflections_from_grid(grid=grid) == pytest.approx(
spherical.deflections_from_grid(grid=grid), 1e-4
)
def test__deflections_of_elliptical_profile__use_interpolate_and_cache_decorators(
self
):
cored_isothermal = aast.mp.EllipticalCoredIsothermal(
centre=(-0.7, 0.5),
axis_ratio=0.7,
phi=60.0,
einstein_radius=1.3,
core_radius=0.2,
)
mask = np.array(
[
[True, True, True, True, True],
[True, False, False, False, True],
[True, False, True, False, True],
[True, False, False, False, True],
[True, True, True, True, True],
]
)
mask = aa.mask.manual(mask, pixel_scales=(1.0, 1.0), sub_size=1)
grid = aa.masked.grid.from_mask(mask=mask)
regular_with_interp = grid.new_grid_with_interpolator(
pixel_scale_interpolation_grid=0.5
)
interp_deflections = cored_isothermal.deflections_from_grid(
grid=regular_with_interp
)
interpolator = grids.Interpolator.from_mask_grid_and_pixel_scale_interpolation_grids(
mask=mask, grid=grid, pixel_scale_interpolation_grid=0.5
)
interp_deflections_values = cored_isothermal.deflections_from_grid(
grid=interpolator.interp_grid
)
interp_deflections_manual_y = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 0]
)
interp_deflections_manual_x = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 1]
)
assert (interp_deflections_manual_y == interp_deflections[:, 0]).all()
assert (interp_deflections_manual_x == interp_deflections[:, 1]).all()
def test__deflections_of_spherical_profile__dont_use_interpolate_and_cache_decorators(
self
):
cored_isothermal = aast.mp.SphericalCoredIsothermal(
centre=(-0.7, 0.5), einstein_radius=1.3, core_radius=0.2
)
mask = np.array(
[
[True, True, True, True, True],
[True, False, False, False, True],
[True, False, True, False, True],
[True, False, False, False, True],
[True, True, True, True, True],
]
)
mask = aa.mask.manual(mask, pixel_scales=(1.0, 1.0), sub_size=1)
grid = aa.masked.grid.from_mask(mask=mask)
regular_with_interp = grid.new_grid_with_interpolator(
pixel_scale_interpolation_grid=0.5
)
interp_deflections = cored_isothermal.deflections_from_grid(
grid=regular_with_interp
)
interpolator = grids.Interpolator.from_mask_grid_and_pixel_scale_interpolation_grids(
mask=mask, grid=grid, pixel_scale_interpolation_grid=0.5
)
interp_deflections_values = cored_isothermal.deflections_from_grid(
grid=interpolator.interp_grid
)
interp_deflections_manual_y = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 0]
)
interp_deflections_manual_x = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 1]
)
assert (interp_deflections_manual_y != interp_deflections[:, 0]).all()
assert (interp_deflections_manual_x != interp_deflections[:, 1]).all()
def test__output_are_autoarrays(self):
grid = aa.grid.uniform(shape_2d=(2, 2), pixel_scales=1.0, sub_size=1)
cored_isothermal = aast.mp.EllipticalCoredIsothermal()
convergence = cored_isothermal.convergence_from_grid(grid=grid)
assert convergence.shape_2d == (2, 2)
potential = cored_isothermal.potential_from_grid(grid=grid)
assert potential.shape_2d == (2, 2)
deflections = cored_isothermal.deflections_from_grid(grid=grid)
assert deflections.shape_2d == (2, 2)
cored_isothermal = aast.mp.SphericalCoredIsothermal()
convergence = cored_isothermal.convergence_from_grid(grid=grid)
assert convergence.shape_2d == (2, 2)
potential = cored_isothermal.potential_from_grid(grid=grid)
assert potential.shape_2d == (2, 2)
deflections = cored_isothermal.deflections_from_grid(grid=grid)
assert deflections.shape_2d == (2, 2)
class TestIsothermal:
def test__constructor_and_units(self):
isothermal = aast.mp.EllipticalIsothermal(
centre=(1.0, 2.0), axis_ratio=0.5, phi=45.0, einstein_radius=1.0
)
assert isothermal.centre == (1.0, 2.0)
assert isinstance(isothermal.centre[0], aast.dim.Length)
assert isinstance(isothermal.centre[1], aast.dim.Length)
assert isothermal.centre[0].unit == "arcsec"
assert isothermal.centre[1].unit == "arcsec"
assert isothermal.axis_ratio == 0.5
assert isinstance(isothermal.axis_ratio, float)
assert isothermal.phi == 45.0
assert isinstance(isothermal.phi, float)
assert isothermal.einstein_radius == 1.0
assert isinstance(isothermal.einstein_radius, aast.dim.Length)
assert isothermal.einstein_radius.unit_length == "arcsec"
assert isothermal.slope == 2.0
assert isinstance(isothermal.slope, float)
assert isothermal.core_radius == 0.0
assert isinstance(isothermal.core_radius, aast.dim.Length)
assert isothermal.core_radius.unit_length == "arcsec"
assert isothermal.einstein_radius_rescaled == pytest.approx(
0.6666666666, 1.0e-4
)
isothermal = aast.mp.SphericalIsothermal(centre=(1.0, 2.0), einstein_radius=1.0)
assert isothermal.centre == (1.0, 2.0)
assert isinstance(isothermal.centre[0], aast.dim.Length)
assert isinstance(isothermal.centre[1], aast.dim.Length)
assert isothermal.centre[0].unit == "arcsec"
assert isothermal.centre[1].unit == "arcsec"
assert isothermal.axis_ratio == 1.0
assert isinstance(isothermal.axis_ratio, float)
assert isothermal.phi == 0.0
assert isinstance(isothermal.phi, float)
assert isothermal.einstein_radius == 1.0
assert isinstance(isothermal.einstein_radius, aast.dim.Length)
assert isothermal.einstein_radius.unit_length == "arcsec"
assert isothermal.slope == 2.0
assert isinstance(isothermal.slope, float)
assert isothermal.core_radius == 0.0
assert isinstance(isothermal.core_radius, aast.dim.Length)
assert isothermal.core_radius.unit_length == "arcsec"
assert isothermal.einstein_radius_rescaled == pytest.approx(0.5, 1.0e-4)
def test__convergence__correct_values(self):
# eta = 1.0
# kappa = 0.5 * 1.0 ** 1.0
isothermal = aast.mp.SphericalIsothermal(centre=(0.0, 0.0), einstein_radius=2.0)
assert isothermal.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
) == pytest.approx(0.5 * 2.0, 1e-3)
isothermal = aast.mp.EllipticalIsothermal(
centre=(0.0, 0.0), axis_ratio=1.0, phi=0.0, einstein_radius=1.0
)
assert isothermal.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
) == pytest.approx(0.5, 1e-3)
isothermal = aast.mp.EllipticalIsothermal(
centre=(0.0, 0.0), axis_ratio=1.0, phi=0.0, einstein_radius=2.0
)
assert isothermal.convergence_from_grid(
grid=aa.grid_irregular.manual_1d([[0.0, 1.0]])
) == pytest.approx(0.5 * 2.0, 1e-3)
isothermal = aast.mp.EllipticalIsothermal(
centre=(0.0, 0.0), axis_ratio=0.5, phi=0.0, einstein_radius=1.0
)
assert isothermal.convergence_from_grid(grid=aa.coordinates([[(0.0, 1.0)]]))[0][
0
] == pytest.approx(0.66666, 1e-3)
def test__potential__correct_values(self):
isothermal = aast.mp.SphericalIsothermal(
centre=(-0.7, 0.5), einstein_radius=1.3
)
assert isothermal.potential_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1875, 0.1625]])
) == pytest.approx(1.23435, 1e-3)
isothermal = aast.mp.EllipticalIsothermal(
centre=(-0.7, 0.5), axis_ratio=0.7, phi=60.0, einstein_radius=1.3
)
assert isothermal.potential_from_grid(
grid=aa.coordinates([[(0.1625, 0.1625)]])
)[0][0] == pytest.approx(1.19268, 1e-3)
def test__deflections__correct_values(self):
isothermal = aast.mp.SphericalIsothermal(
centre=(-0.7, 0.5), einstein_radius=1.3
)
deflections = isothermal.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1875, 0.1625]])
)
assert deflections[0, 0] == pytest.approx(1.21510, 1e-4)
assert deflections[0, 1] == pytest.approx(-0.46208, 1e-4)
isothermal = aast.mp.SphericalIsothermal(
centre=(-0.1, 0.1), einstein_radius=5.0
)
deflections = isothermal.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1875, 0.1625]])
)
assert deflections[0, 0] == pytest.approx(4.88588, 1e-4)
assert deflections[0, 1] == pytest.approx(1.06214, 1e-4)
isothermal = aast.mp.EllipticalIsothermal(
centre=(0, 0), axis_ratio=0.5, phi=0.0, einstein_radius=1.0
)
deflections = isothermal.deflections_from_grid(
grid=aa.grid_irregular.manual_1d([[0.1625, 0.1625]])
)
assert deflections[0, 0] == pytest.approx(0.79421, 1e-3)
assert deflections[0, 1] == pytest.approx(0.50734, 1e-3)
isothermal = aast.mp.EllipticalIsothermal(
centre=(0, 0), axis_ratio=0.5, phi=0.0, einstein_radius=1.0
)
deflections = isothermal.deflections_from_grid(
grid=aa.coordinates([[(0.1625, 0.1625)]])
)
assert deflections[0][0][0] == pytest.approx(0.79421, 1e-3)
assert deflections[0][0][1] == pytest.approx(0.50734, 1e-3)
def test__compare_to_cored_power_law(self):
isothermal = aast.mp.EllipticalIsothermal(
centre=(0.0, 0.0), axis_ratio=0.5, phi=45.0, einstein_radius=1.0
)
cored_power_law = aast.mp.EllipticalCoredPowerLaw(
centre=(0.0, 0.0),
axis_ratio=0.5,
phi=45.0,
einstein_radius=1.0,
core_radius=0.0,
)
assert isothermal.potential_from_grid(grid=grid) == pytest.approx(
cored_power_law.potential_from_grid(grid=grid), 1e-3
)
assert isothermal.potential_from_grid(grid=grid) == pytest.approx(
cored_power_law.potential_from_grid(grid=grid), 1e-3
)
assert isothermal.deflections_from_grid(grid=grid) == pytest.approx(
cored_power_law.deflections_from_grid(grid=grid), 1e-3
)
assert isothermal.deflections_from_grid(grid=grid) == pytest.approx(
cored_power_law.deflections_from_grid(grid=grid), 1e-3
)
def test__spherical_and_elliptical_match(self):
elliptical = aast.mp.EllipticalIsothermal(
centre=(1.1, 1.1), axis_ratio=0.9999, phi=0.0, einstein_radius=3.0
)
spherical = aast.mp.SphericalIsothermal(centre=(1.1, 1.1), einstein_radius=3.0)
assert elliptical.convergence_from_grid(grid=grid) == pytest.approx(
spherical.convergence_from_grid(grid=grid), 1e-4
)
assert elliptical.potential_from_grid(grid=grid) == pytest.approx(
spherical.potential_from_grid(grid=grid), 1e-4
)
assert elliptical.deflections_from_grid(grid=grid) == pytest.approx(
spherical.deflections_from_grid(grid=grid), 1e-4
)
def test__radius_of_critical_curve(self):
sis = aast.mp.SphericalIsothermal(centre=(0.0, 0.0), einstein_radius=2.0)
assert sis.average_convergence_of_1_radius_in_units(
unit_length="arcsec"
) == pytest.approx(2.0, 1e-4)
sie = aast.mp.EllipticalIsothermal(
centre=(0.0, 0.0), einstein_radius=1.0, axis_ratio=0.8, phi=0.0
)
assert sie.average_convergence_of_1_radius_in_units(
unit_length="arcsec"
) == pytest.approx(1.0, 1e-4)
sie = aast.mp.EllipticalIsothermal(
centre=(0.0, 0.0), einstein_radius=3.0, axis_ratio=0.5, phi=0.0
)
assert sie.average_convergence_of_1_radius_in_units(
unit_length="arcsec"
) == pytest.approx(3.0, 1e-4)
sie = aast.mp.EllipticalIsothermal(
centre=(0.0, 0.0), einstein_radius=8.0, axis_ratio=0.2, phi=0.0
)
assert sie.average_convergence_of_1_radius_in_units(
unit_length="arcsec"
) == pytest.approx(8.0, 1e-4)
def test__deflections_of_elliptical_profile__dont_use_interpolate_and_cache_decorators(
self
):
isothermal = aast.mp.EllipticalIsothermal(
centre=(-0.7, 0.5), axis_ratio=0.7, phi=60.0, einstein_radius=1.3
)
mask = np.array(
[
[True, True, True, True, True],
[True, False, False, False, True],
[True, False, True, False, True],
[True, False, False, False, True],
[True, True, True, True, True],
]
)
mask = aa.mask.manual(mask, pixel_scales=(1.0, 1.0), sub_size=1)
grid = aa.masked.grid.from_mask(mask=mask)
regular_with_interp = grid.new_grid_with_interpolator(
pixel_scale_interpolation_grid=0.5
)
interp_deflections = isothermal.deflections_from_grid(grid=regular_with_interp)
interpolator = grids.Interpolator.from_mask_grid_and_pixel_scale_interpolation_grids(
mask=mask, grid=grid, pixel_scale_interpolation_grid=0.5
)
interp_deflections_values = isothermal.deflections_from_grid(
grid=interpolator.interp_grid
)
interp_deflections_manual_y = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 0]
)
interp_deflections_manual_x = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 1]
)
assert (interp_deflections_manual_y != interp_deflections[:, 0]).all()
assert (interp_deflections_manual_x != interp_deflections[:, 1]).all()
def test__deflections_of_spherical_profile__dont_use_interpolate_and_cache_decorators(
self
):
isothermal = aast.mp.SphericalIsothermal(
centre=(-0.7, 0.5), einstein_radius=1.3
)
mask = np.array(
[
[True, True, True, True, True],
[True, False, False, False, True],
[True, False, True, False, True],
[True, False, False, False, True],
[True, True, True, True, True],
]
)
mask = aa.mask.manual(mask, pixel_scales=(1.0, 1.0), sub_size=1)
grid = aa.masked.grid.from_mask(mask=mask)
regular_with_interp = grid.new_grid_with_interpolator(
pixel_scale_interpolation_grid=0.5
)
interp_deflections = isothermal.deflections_from_grid(grid=regular_with_interp)
interpolator = grids.Interpolator.from_mask_grid_and_pixel_scale_interpolation_grids(
mask=mask, grid=grid, pixel_scale_interpolation_grid=0.5
)
interp_deflections_values = isothermal.deflections_from_grid(
grid=interpolator.interp_grid
)
interp_deflections_manual_y = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 0]
)
interp_deflections_manual_x = interpolator.interpolated_values_from_values(
values=interp_deflections_values[:, 1]
)
assert (interp_deflections_manual_y != interp_deflections[:, 0]).all()
assert (interp_deflections_manual_x != interp_deflections[:, 1]).all()
def test__output_are_autoarrays(self):
grid = aa.grid.uniform(shape_2d=(2, 2), pixel_scales=1.0, sub_size=1)
isothermal = aast.mp.EllipticalIsothermal()
convergence = isothermal.convergence_from_grid(grid=grid)
assert convergence.shape_2d == (2, 2)
potential = isothermal.potential_from_grid(grid=grid)
assert potential.shape_2d == (2, 2)
deflections = isothermal.deflections_from_grid(grid=grid)
assert deflections.shape_2d == (2, 2)
isothermal = aast.mp.SphericalIsothermal()
convergence = isothermal.convergence_from_grid(grid=grid)
assert convergence.shape_2d == (2, 2)
potential = isothermal.potential_from_grid(grid=grid)
assert potential.shape_2d == (2, 2)
deflections = isothermal.deflections_from_grid(grid=grid)
assert deflections.shape_2d == (2, 2)
| 38.040861 | 105 | 0.616313 | 11,361 | 86,581 | 4.448816 | 0.028343 | 0.017727 | 0.052233 | 0.031577 | 0.965752 | 0.954178 | 0.941001 | 0.932335 | 0.919356 | 0.892112 | 0 | 0.07005 | 0.263972 | 86,581 | 2,275 | 106 | 38.057582 | 0.72308 | 0.020282 | 0 | 0.684909 | 0 | 0 | 0.006937 | 0.001333 | 0 | 0 | 0 | 0 | 0.219458 | 1 | 0.030404 | false | 0 | 0.00387 | 0 | 0.03759 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
3662f593bf720d98cb251055a54f8eb65bb3ed3f | 98 | py | Python | lifelines/compat.py | TylerLiuAIrobotics/lifelines | a4ce565b17ebdaf5c0049750b7b3f94b41d6b404 | [
"MIT"
] | null | null | null | lifelines/compat.py | TylerLiuAIrobotics/lifelines | a4ce565b17ebdaf5c0049750b7b3f94b41d6b404 | [
"MIT"
] | null | null | null | lifelines/compat.py | TylerLiuAIrobotics/lifelines | a4ce565b17ebdaf5c0049750b7b3f94b41d6b404 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] >= 3
| 16.333333 | 30 | 0.602041 | 17 | 98 | 3.352941 | 0.705882 | 0.350877 | 0.491228 | 0.526316 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.0875 | 0.183673 | 98 | 5 | 31 | 19.6 | 0.625 | 0.214286 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.333333 | 0 | 0.333333 | 0 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 6 |
3672dcf3de510f7bbb3cd18706b022a10a347458 | 2,162 | py | Python | tests/cfpq_tensor_product_test.py | e90r/formal_languages_course | 5a7f2e962a720e6279f268d8f5f96c8fe2c613e0 | [
"Apache-2.0"
] | null | null | null | tests/cfpq_tensor_product_test.py | e90r/formal_languages_course | 5a7f2e962a720e6279f268d8f5f96c8fe2c613e0 | [
"Apache-2.0"
] | 1 | 2020-12-02T15:06:21.000Z | 2020-12-02T15:06:21.000Z | tests/cfpq_tensor_product_test.py | e90r/formal_languages_course | 5a7f2e962a720e6279f268d8f5f96c8fe2c613e0 | [
"Apache-2.0"
] | null | null | null | import os
from src.BMGraph import BMGraph
from src.GrammarAlgos import GrammarAlgos
def test_cfpq_tensor_1():
test_path = os.path.join(os.getcwd(), 'tests/data/cfpq/test1')
graph = BMGraph.from_edges_file(
os.path.join(test_path, 'graph.txt'))
grammar = GrammarAlgos.from_grammar_file(
os.path.join(test_path, 'grammar.txt'))
adj_matrix = GrammarAlgos.cfpq_tensor_product(grammar, graph)
expected = {(0, 2), (0, 3), (1, 2), (1, 3), (2, 2), (2, 3)}
actual = set(BMGraph.get_reachable_vertices(adj_matrix))
assert expected == actual
def test_cfpq_tensor_2():
test_path = os.path.join(os.getcwd(), 'tests/data/cfpq/test2')
graph = BMGraph.from_edges_file(
os.path.join(test_path, 'graph.txt'))
grammar = GrammarAlgos.from_grammar_file(
os.path.join(test_path, 'grammar.txt'))
adj_matrix = GrammarAlgos.cfpq_tensor_product(grammar, graph)
expected = {(0, 1), (3, 3)}
actual = set(BMGraph.get_reachable_vertices(adj_matrix))
assert expected == actual
def test_cfpq_tensor_3():
test_path = os.path.join(os.getcwd(), 'tests/data/cfpq/test3')
graph = BMGraph.from_edges_file(
os.path.join(test_path, 'graph.txt'))
grammar = GrammarAlgos.from_grammar_file(
os.path.join(test_path, 'grammar.txt'))
adj_matrix = GrammarAlgos.cfpq_tensor_product(grammar, graph)
expected = {(0, 0), (1, 1), (0, 2), (3, 3), (2, 2)}
actual = set(BMGraph.get_reachable_vertices(adj_matrix))
assert expected == actual
def test_cfpq_tensor_4():
test_path = os.path.join(os.getcwd(), 'tests/data/cfpq/test4')
graph = BMGraph.from_edges_file(
os.path.join(test_path, 'graph.txt'))
grammar = GrammarAlgos.from_grammar_file(
os.path.join(test_path, 'grammar.txt'))
adj_matrix = GrammarAlgos.cfpq_tensor_product(grammar, graph)
expected = {(0, 1), (4, 4), (2, 4), (1, 2),
(0, 4), (3, 4), (0, 0), (4, 3),
(1, 1), (0, 3), (1, 4), (2, 3),
(0, 2), (3, 3), (2, 2), (1, 3)}
actual = set(BMGraph.get_reachable_vertices(adj_matrix))
assert expected == actual
| 30.450704 | 66 | 0.641073 | 310 | 2,162 | 4.264516 | 0.125806 | 0.072617 | 0.090772 | 0.08472 | 0.886536 | 0.886536 | 0.877458 | 0.877458 | 0.877458 | 0.877458 | 0 | 0.038194 | 0.20074 | 2,162 | 70 | 67 | 30.885714 | 0.726852 | 0 | 0 | 0.608696 | 0 | 0 | 0.075856 | 0.038853 | 0 | 0 | 0 | 0 | 0.086957 | 1 | 0.086957 | false | 0 | 0.065217 | 0 | 0.152174 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
7fe9293a5a6694539fb12230201f048f7f57331e | 24,399 | py | Python | pirates/leveleditor/worldData/interior_shanty_store_tattoo.py | Willy5s/Pirates-Online-Rewritten | 7434cf98d9b7c837d57c181e5dabd02ddf98acb7 | [
"BSD-3-Clause"
] | 81 | 2018-04-08T18:14:24.000Z | 2022-01-11T07:22:15.000Z | pirates/leveleditor/worldData/interior_shanty_store_tattoo.py | Willy5s/Pirates-Online-Rewritten | 7434cf98d9b7c837d57c181e5dabd02ddf98acb7 | [
"BSD-3-Clause"
] | 4 | 2018-09-13T20:41:22.000Z | 2022-01-08T06:57:00.000Z | pirates/leveleditor/worldData/interior_shanty_store_tattoo.py | Willy5s/Pirates-Online-Rewritten | 7434cf98d9b7c837d57c181e5dabd02ddf98acb7 | [
"BSD-3-Clause"
] | 26 | 2018-05-26T12:49:27.000Z | 2021-09-11T09:11:59.000Z | from pandac.PandaModules import Point3, VBase3, Vec4, Vec3
objectStruct = {'AmbientColors': {},'DirectionalColors': {},'FogColors': {},'FogRanges': {},'Objects': {'1156268617.43dzlu0t': {'Type': 'Building Interior','Name': '','Instanced': True,'Objects': {'1172095480.47kmuller': {'Type': 'Interior_furnishings','DisableCollision': False,'Hpr': VBase3(-89.577, 0.0, 0.0),'Pos': Point3(0.226, 6.857, -0.113),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/shop_tatoo_bottles'}},'1172095536.58kmuller': {'Type': 'Interior_furnishings','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(33.403, 15.797, 2.83),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/shop_tatoo_heater'}},'1172095575.85kmuller': {'Type': 'Interior_furnishings','DisableCollision': False,'Hpr': VBase3(88.92, 0.0, 0.0),'Pos': Point3(28.445, 17.078, 0.0),'Scale': VBase3(1.193, 1.193, 1.193),'Visual': {'Model': 'models/props/interior_wall_shanty'}},'1172095643.89kmuller': {'Type': 'Interior_furnishings','DisableCollision': False,'Hpr': VBase3(-179.224, 0.0, 0.0),'Pos': Point3(-1.676, -9.894, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/interior_wall_shanty'}},'1172095696.85kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(79.291, 0.0, 0.0),'Pos': Point3(-17.493, -9.578, 12.07),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.699999988079071, 0.699999988079071, 0.699999988079071, 1.0),'Model': 'models/props/bed_shanty'}},'1172095827.0kmuller': {'Type': 'Interior_furnishings','DisableCollision': True,'Hpr': VBase3(48.849, 0.0, 0.0),'Pos': Point3(-0.119, 15.236, 0.0),'Scale': VBase3(1.161, 1.161, 1.161),'Visual': {'Model': 'models/props/stove_potbelly'}},'1172100105.43kmuller': {'Type': 'Prop_Groups','DisableCollision': False,'Hpr': VBase3(-110.888, 0.0, 0.0),'Pos': Point3(-17.132, 11.691, 12.07),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/prop_group01'}},'1172100325.91kmuller': {'Type': 'Interior_furnishings','DisableCollision': False,'Hpr': VBase3(0.0, 0.0, 0.0),'Pos': Point3(18.712, 17.255, 7.915),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/shop_tatoo_sample'}},'1172100435.43kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(33.552, 15.923, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/table_shanty'}},'1172100612.43kmuller': {'Type': 'Interior_furnishings','DisableCollision': False,'Hpr': VBase3(88.92, 0.0, 0.0),'Pos': Point3(-0.732, 18.009, 0.0),'Scale': VBase3(1.193, 1.193, 1.193),'Visual': {'Model': 'models/props/interior_wall_shanty'}},'1172100647.41kmuller': {'Type': 'Interior_furnishings','DisableCollision': False,'Hpr': VBase3(88.92, 0.0, 0.0),'Pos': Point3(-30.212, 18.669, 0.0),'Scale': VBase3(1.193, 1.193, 1.193),'Visual': {'Model': 'models/props/interior_wall_shanty'}},'1172100717.96kmuller': {'Type': 'Furniture','DisableCollision': True,'Hpr': VBase3(90.427, 0.0, 0.0),'Pos': Point3(-0.208, -1.491, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/cabinet_shanty'}},'1172100724.71kmuller': {'Type': 'Furniture','DisableCollision': True,'Hpr': VBase3(90.427, 0.0, 0.0),'Pos': Point3(-0.28, -12.692, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/cabinet_shanty'}},'1172100752.18kmuller': {'Type': 'Furniture','DisableCollision': True,'Hpr': VBase3(90.427, 0.0, 0.0),'Pos': Point3(0.261, -7.068, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/cabinet_shanty_low'}},'1172100806.77kmuller': {'Type': 'Interior_furnishings','DisableCollision': False,'Hpr': VBase3(-179.224, 0.0, 0.0),'Pos': Point3(-1.951, 14.79, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/interior_wall_shanty'}},'1172100908.93kmuller': {'Type': 'Crate','DisableCollision': True,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(4.454, -25.456, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.5, 0.5, 0.5, 1.0),'Model': 'models/props/crate_04'}},'1172100935.39kmuller': {'Type': 'Crate','DisableCollision': True,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-0.392, -24.673, -0.138),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.5899999737739563, 0.5899999737739563, 0.49000000953674316, 1.0),'Model': 'models/props/crate'}},'1172100965.11kmuller': {'Type': 'Crate','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-0.109, -28.673, 0.008),'Scale': VBase3(0.826, 0.826, 0.826),'Visual': {'Model': 'models/props/crates_group_2'}},'1172101104.39kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(-93.038, 0.0, 0.0),'Pos': Point3(41.038, 7.173, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.8500000238418579, 0.7900000214576721, 0.8299999833106995, 1.0),'Model': 'models/props/bench_shanty_2'}},'1172101251.99kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(0.0, 0.0, 0.0),'Pos': Point3(9.296, 16.134, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/table_bar_square'}},'1172101295.69kmuller': {'Type': 'Interior_furnishings','DisableCollision': True,'Hpr': VBase3(-42.123, 0.0, 0.0),'Pos': Point3(39.832, 14.988, 0.0),'Scale': VBase3(1.161, 1.161, 1.161),'Visual': {'Model': 'models/props/stove_potbelly'}},'1172101331.02kmuller': {'Type': 'Interior_furnishings','DisableCollision': False,'Hpr': VBase3(0.0, 0.0, 0.0),'Pos': Point3(8.895, 16.991, 2.812),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/shop_tatoo_heater'}},'1172101372.05kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(51.097, 0.0, 0.0),'Pos': Point3(8.509, 6.955, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/table_shanty'}},'1172101830.61kmuller': {'Type': 'Interior_furnishings','DisableCollision': False,'Hpr': VBase3(-89.706, 0.0, 0.0),'Pos': Point3(-0.408, -7.368, 2.793),'Scale': VBase3(0.854, 0.854, 0.854),'Visual': {'Model': 'models/props/shop_doctor_bottles'}},'1172101986.27kmuller': {'Type': 'Trunks','DisableCollision': True,'Hpr': VBase3(59.828, 0.0, 0.0),'Pos': Point3(0.012, -0.555, 2.633),'Scale': VBase3(0.741, 0.741, 0.741),'Visual': {'Model': 'models/props/Trunk_rounded'}},'1172102034.1kmuller': {'Type': 'Sack','DisableCollision': True,'Hpr': VBase3(87.338, 0.0, 0.0),'Pos': Point3(0.003, -2.377, 5.367),'Scale': VBase3(0.421, 0.421, 0.421),'Visual': {'Model': 'models/props/Sack'}},'1172102087.46kmuller': {'Type': 'Sack','DisableCollision': True,'Hpr': VBase3(8.582, -1.616, 72.763),'Pos': Point3(-0.716, -0.468, 6.521),'Scale': VBase3(0.421, 0.421, 0.421),'Visual': {'Model': 'models/props/Sack'}},'1172102089.18kmuller': {'Type': 'Sack','DisableCollision': True,'Hpr': VBase3(87.338, 0.166, 0.0),'Pos': Point3(-0.214, -2.332, 5.924),'Scale': VBase3(0.421, 0.421, 0.421),'Visual': {'Model': 'models/props/Sack'}},'1172102242.03kmuller': {'Type': 'Jugs_and_Jars','DisableCollision': False,'Hpr': VBase3(0.0, 0.0, 0.0),'Pos': Point3(0.528, -11.84, 5.539),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/jar'}},'1172102341.66kmuller': {'Type': 'Mortar_Pestle','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(0.037, -11.177, 5.538),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/mortar_pestle_stone'}},'1172102400.72kmuller': {'Type': 'Crate','DisableCollision': True,'Hpr': VBase3(11.4, 0.0, 0.0),'Pos': Point3(0.131, -13.728, 2.652),'Scale': VBase3(0.618, 0.618, 0.618),'Visual': {'Model': 'models/props/crate'}},'1172102479.08kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(44.574, 0.0, 0.0),'Pos': Point3(6.573, 8.272, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/stool_shanty'}},'1172102495.93kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(-37.021, 0.0, 0.0),'Pos': Point3(9.836, 4.828, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/chair_shanty'}},'1172102515.35kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(41.055, 0.0, 0.0),'Pos': Point3(34.623, 13.175, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/chair_shanty'}},'1172102612.1kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(-93.038, 0.0, 0.0),'Pos': Point3(31.282, -22.309, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.5899999737739563, 0.5899999737739563, 0.49000000953674316, 1.0),'Model': 'models/props/bench_shanty_2'}},'1172102617.41kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(-93.038, 0.0, 0.0),'Pos': Point3(40.422, -21.949, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.5899999737739563, 0.5899999737739563, 0.49000000953674316, 1.0),'Model': 'models/props/bench_shanty_2'}},'1172102641.11kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(36.057, -22.476, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.5899999737739563, 0.5899999737739563, 0.49000000953674316, 1.0),'Model': 'models/props/table_shanty_2'}},'1172102706.86kmuller': {'Type': 'Prop_Groups','DisableCollision': True,'Hpr': VBase3(95.423, 0.0, 0.0),'Pos': Point3(-1.637, 15.937, 12.07),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/prop_group_A'}},'1172102778.21kmuller': {'Type': 'Interior_furnishings','DisableCollision': False,'Hpr': VBase3(90.677, 0.0, 0.0),'Pos': Point3(-1.766, -6.996, 6.21),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/shop_tatoo_sample'}},'1174687513.07dzlu': {'Type': 'Light - Dynamic','Attenuation': '0.005','ConeAngle': '120.0000','DropOff': '4.0909','FlickRate': '0.5000','Flickering': False,'Hpr': VBase3(49.414, -58.284, 67.394),'Intensity': '1.0606','LightType': 'SPOT','Pos': Point3(34.058, -13.448, 45.656),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.92, 0.75, 1.0, 1.0),'Model': 'models/props/light_tool_bulb'}},'1176415428.42dzlu': {'Type': 'Light - Dynamic','Attenuation': '0.005','ConeAngle': '41.5663','DropOff': '2.7273','FlickRate': '0.5000','Flickering': False,'Hpr': VBase3(131.493, -18.013, 2.34),'Intensity': '0.5904','LightType': 'SPOT','Pos': Point3(43.578, 10.551, 12.912),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.8700000047683716, 1.0, 1.0, 1.0),'Model': 'models/props/light_tool_bulb'}},'1176415733.23dzlu': {'Type': 'Light - Dynamic','Attenuation': '0.005','ConeAngle': '60.0000','DropOff': '2.7273','FlickRate': '0.5000','Flickering': False,'Hpr': VBase3(45.566, -41.007, -172.421),'Intensity': '0.3373','LightType': 'SPOT','Pos': Point3(46.089, -30.101, 23.147),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.8700000047683716, 1.0, 1.0, 1.0),'Model': 'models/props/light_tool_bulb'}},'1179420638.48dzlu': {'Type': 'Light - Dynamic','Attenuation': '0.005','ConeAngle': '60.0000','DropOff': '0.0000','FlickRate': '0.5000','Flickering': False,'Hpr': Point3(0.0, 0.0, 0.0),'Intensity': '0.0964','LightType': 'AMBIENT','Pos': Point3(24.836, -8.851, 3.003),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (1, 1, 1, 1),'Model': 'models/props/light_tool_bulb'}},'1185469537.64kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': VBase3(-43.289, 0.0, 0.0),'Pos': Point3(39.649, 13.494, -0.936),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}},'1185469632.86kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': VBase3(47.737, 0.0, 0.0),'Pos': Point3(1.056, 14.646, -0.739),'Scale': VBase3(1.0, 1.0, 1.145),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}},'1185469711.62kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-0.532, -7.078, -0.178),'Scale': VBase3(1.0, 3.257, 1.785),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}},'1185469766.65kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': VBase3(167.335, 0.0, 0.0),'Pos': Point3(-20.358, -3.953, 11.493),'Scale': VBase3(0.673, 1.0, 0.828),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}},'1185469903.48kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': VBase3(-31.844, 0.0, 0.0),'Pos': Point3(-12.313, 9.966, 11.696),'Scale': VBase3(0.609, 1.0, 1.0),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}},'1185469967.01kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Holiday': '','Hpr': VBase3(24.122, 0.0, 0.0),'Pos': Point3(-6.893, 9.783, 11.68),'Scale': VBase3(0.678, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}},'1201118003.08dxschafe': {'Type': 'Door Locator Node','Name': 'door_locator','Hpr': VBase3(90.0, 0.0, 0.0),'Pos': Point3(41.986, -7.423, 0.079),'Scale': VBase3(1.0, 1.0, 1.0)},'1257881464.18caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(90.143, 0.0, 0.0),'Pos': Point3(2.953, -11.139, 1.586),'Scale': VBase3(0.654, 0.654, 0.654),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}},'1257881500.56caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(90.143, 0.0, 0.0),'Pos': Point3(1.08, -1.435, 8.507),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}},'1257881576.28caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-54.62, 0.0, 0.0),'Pos': Point3(-1.988, 13.39, 7.619),'Scale': VBase3(1.84, 1.84, 1.84),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoStocking03_winter09'}},'1257881635.74caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-20.018, 0.0, 0.0),'Pos': Point3(0.535, 18.009, 7.033),'Scale': VBase3(1.051, 1.051, 1.051),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoStocking02_winter09'}},'1257881724.96caoconno': {'Type': 'Bucket','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(28.222, 0.0, 0.0),'Pos': Point3(2.016, -11.174, -0.057),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/bucket'}},'1257881781.23caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(35.295, -15.277, 15.364),'Pos': Point3(2.091, -10.12, 2.409),'Scale': VBase3(1.0, 1.0, 1.27),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257881827.31caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(0.0, 0.0, 7.019),'Pos': Point3(3.071, -11.107, 2.46),'Scale': VBase3(1.0, 1.0, 1.27),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257881839.73caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-32.225, -3.757, 20.733),'Pos': Point3(3.065, -11.632, 2.374),'Scale': VBase3(1.0, 1.0, 1.27),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257881852.21caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-94.918, -16.48, 23.195),'Pos': Point3(2.432, -12.365, 2.27),'Scale': VBase3(1.0, 1.0, 1.27),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257881891.09caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(36.575, 12.178, 26.755),'Pos': Point3(3.165, -10.612, 2.418),'Scale': VBase3(1.0, 1.0, 1.27),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257881932.09caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(63.196, 7.284, 25.248),'Pos': Point3(2.68, -10.088, 2.446),'Scale': VBase3(1.0, 1.0, 1.27),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257882030.93caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(90.143, 0.0, 0.0),'Pos': Point3(1.006, -12.787, 8.507),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}},'1259722417.42caoconno': {'Type': 'Collision Barrier','DisableCollision': False,'Holiday': '','Hpr': VBase3(-28.089, 0.0, 0.0),'Pos': Point3(-6.211, 8.457, 12.067),'Scale': VBase3(0.504, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}}},'Visual': {'Model': 'models/buildings/interior_shanty_store'}}},'Node Links': [],'Layers': {'Collisions': ['1184008208.59kmuller', '1184016064.62kmuller', '1184013852.84kmuller', '1185822696.06kmuller', '1184006140.32kmuller', '1184002350.98kmuller', '1184007573.29kmuller', '1184021176.59kmuller', '1184005963.59kmuller', '1188324241.31akelts', '1184006537.34kmuller', '1184006605.81kmuller', '1187139568.33kmuller', '1188324186.98akelts', '1184006730.66kmuller', '1184007538.51kmuller', '1184006188.41kmuller', '1184021084.27kmuller', '1185824396.94kmuller', '1185824250.16kmuller', '1185823630.52kmuller', '1185823760.23kmuller', '1185824497.83kmuller', '1185824751.45kmuller', '1187739103.34akelts', '1188323993.34akelts', '1184016538.29kmuller', '1185822200.97kmuller', '1184016225.99kmuller', '1195241421.34akelts', '1195242796.08akelts', '1184020642.13kmuller', '1195237994.63akelts', '1184020756.88kmuller', '1184020833.4kmuller', '1185820992.97kmuller', '1185821053.83kmuller', '1184015068.54kmuller', '1184014935.82kmuller', '1185821432.88kmuller', '1185821701.86kmuller', '1195240137.55akelts', '1195241539.38akelts', '1195238422.3akelts', '1195238473.22akelts', '1185821453.17kmuller', '1184021269.96kmuller', '1185821310.89kmuller', '1185821165.59kmuller', '1185821199.36kmuller', '1185822035.98kmuller', '1184015806.59kmuller', '1185822059.48kmuller', '1185920461.76kmuller', '1194984449.66akelts', '1185824206.22kmuller', '1184003446.23kmuller', '1184003254.85kmuller', '1184003218.74kmuller', '1184002700.44kmuller', '1186705073.11kmuller', '1187658531.86akelts', '1186705214.3kmuller', '1185824927.28kmuller', '1184014204.54kmuller', '1184014152.84kmuller']},'ObjectIds': {'1156268617.43dzlu0t': '["Objects"]["1156268617.43dzlu0t"]','1172095480.47kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172095480.47kmuller"]','1172095536.58kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172095536.58kmuller"]','1172095575.85kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172095575.85kmuller"]','1172095643.89kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172095643.89kmuller"]','1172095696.85kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172095696.85kmuller"]','1172095827.0kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172095827.0kmuller"]','1172100105.43kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172100105.43kmuller"]','1172100325.91kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172100325.91kmuller"]','1172100435.43kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172100435.43kmuller"]','1172100612.43kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172100612.43kmuller"]','1172100647.41kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172100647.41kmuller"]','1172100717.96kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172100717.96kmuller"]','1172100724.71kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172100724.71kmuller"]','1172100752.18kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172100752.18kmuller"]','1172100806.77kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172100806.77kmuller"]','1172100908.93kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172100908.93kmuller"]','1172100935.39kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172100935.39kmuller"]','1172100965.11kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172100965.11kmuller"]','1172101104.39kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172101104.39kmuller"]','1172101251.99kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172101251.99kmuller"]','1172101295.69kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172101295.69kmuller"]','1172101331.02kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172101331.02kmuller"]','1172101372.05kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172101372.05kmuller"]','1172101830.61kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172101830.61kmuller"]','1172101986.27kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172101986.27kmuller"]','1172102034.1kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172102034.1kmuller"]','1172102087.46kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172102087.46kmuller"]','1172102089.18kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172102089.18kmuller"]','1172102242.03kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172102242.03kmuller"]','1172102341.66kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172102341.66kmuller"]','1172102400.72kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172102400.72kmuller"]','1172102479.08kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172102479.08kmuller"]','1172102495.93kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172102495.93kmuller"]','1172102515.35kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172102515.35kmuller"]','1172102612.1kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172102612.1kmuller"]','1172102617.41kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172102617.41kmuller"]','1172102641.11kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172102641.11kmuller"]','1172102706.86kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172102706.86kmuller"]','1172102778.21kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1172102778.21kmuller"]','1174687513.07dzlu': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1174687513.07dzlu"]','1176415428.42dzlu': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1176415428.42dzlu"]','1176415733.23dzlu': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1176415733.23dzlu"]','1179420638.48dzlu': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1179420638.48dzlu"]','1185469537.64kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1185469537.64kmuller"]','1185469632.86kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1185469632.86kmuller"]','1185469711.62kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1185469711.62kmuller"]','1185469766.65kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1185469766.65kmuller"]','1185469903.48kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1185469903.48kmuller"]','1185469967.01kmuller': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1185469967.01kmuller"]','1201118003.08dxschafe': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1201118003.08dxschafe"]','1257881464.18caoconno': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1257881464.18caoconno"]','1257881500.56caoconno': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1257881500.56caoconno"]','1257881576.28caoconno': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1257881576.28caoconno"]','1257881635.74caoconno': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1257881635.74caoconno"]','1257881724.96caoconno': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1257881724.96caoconno"]','1257881781.23caoconno': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1257881781.23caoconno"]','1257881827.31caoconno': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1257881827.31caoconno"]','1257881839.73caoconno': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1257881839.73caoconno"]','1257881852.21caoconno': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1257881852.21caoconno"]','1257881891.09caoconno': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1257881891.09caoconno"]','1257881932.09caoconno': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1257881932.09caoconno"]','1257882030.93caoconno': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1257882030.93caoconno"]','1259722417.42caoconno': '["Objects"]["1156268617.43dzlu0t"]["Objects"]["1259722417.42caoconno"]'}}
extraInfo = {'camPos': Point3(0, -14, 0),'camHpr': VBase3(0, 0, 0),'focalLength': 0.792142391205,'skyState': -1,'fog': 0} | 8,133 | 24,218 | 0.688348 | 3,280 | 24,399 | 5.067988 | 0.194817 | 0.025387 | 0.024183 | 0.020935 | 0.500391 | 0.44264 | 0.413584 | 0.364856 | 0.326175 | 0.303916 | 0 | 0.278725 | 0.047584 | 24,399 | 3 | 24,219 | 8,133 | 0.436612 | 0 | 0 | 0 | 0 | 0 | 0.596107 | 0.280246 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.333333 | 0 | 0.333333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 6 |
7fec8aa103acf557f52c81f432b1861b71739e35 | 45 | py | Python | src/coolc/__init__.py | matcom-compilers-2019/cool-compiler-alexander-leonardo-marcos | 874b3155769612fb8dc1dd823c9a024c66169a02 | [
"MIT"
] | null | null | null | src/coolc/__init__.py | matcom-compilers-2019/cool-compiler-alexander-leonardo-marcos | 874b3155769612fb8dc1dd823c9a024c66169a02 | [
"MIT"
] | null | null | null | src/coolc/__init__.py | matcom-compilers-2019/cool-compiler-alexander-leonardo-marcos | 874b3155769612fb8dc1dd823c9a024c66169a02 | [
"MIT"
] | null | null | null | from . import ply
from .coolc import Compiler | 22.5 | 27 | 0.8 | 7 | 45 | 5.142857 | 0.714286 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.155556 | 45 | 2 | 27 | 22.5 | 0.947368 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
3d0424df95366352c229724b67769b8a72567b9f | 26 | py | Python | mbutil/mbutil/__init__.py | N129BZ/VFRSectionalCharts | 5274a2d493e8b0059ca0cacf5999ca6885cf93f7 | [
"MIT"
] | 449 | 2015-01-01T12:55:46.000Z | 2022-03-25T21:28:52.000Z | mbutil/mbutil/__init__.py | N129BZ/VFRSectionalCharts | 5274a2d493e8b0059ca0cacf5999ca6885cf93f7 | [
"MIT"
] | 48 | 2015-02-20T23:17:11.000Z | 2022-03-27T13:42:37.000Z | mbutil/mbutil/__init__.py | N129BZ/VFRSectionalCharts | 5274a2d493e8b0059ca0cacf5999ca6885cf93f7 | [
"MIT"
] | 135 | 2015-01-04T11:37:30.000Z | 2022-03-25T21:28:54.000Z | from mbutil.util import *
| 13 | 25 | 0.769231 | 4 | 26 | 5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.153846 | 26 | 1 | 26 | 26 | 0.909091 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
3d3416c6b2ca116ef6ea525cbf86be3686b0e7a1 | 296 | py | Python | server/lib/python/cartodb_services/cartodb_services/mapbox/__init__.py | CartoDB/dataservices-api | d0f28cc002ef11df9f371d5d1fd2d0901c245f97 | [
"BSD-3-Clause"
] | 22 | 2016-03-11T17:33:31.000Z | 2021-02-22T04:00:43.000Z | server/lib/python/cartodb_services/cartodb_services/mapbox/__init__.py | CartoDB/dataservices-api | d0f28cc002ef11df9f371d5d1fd2d0901c245f97 | [
"BSD-3-Clause"
] | 338 | 2016-02-16T16:13:13.000Z | 2022-03-30T15:50:17.000Z | server/lib/python/cartodb_services/cartodb_services/mapbox/__init__.py | CartoDB/dataservices-api | d0f28cc002ef11df9f371d5d1fd2d0901c245f97 | [
"BSD-3-Clause"
] | 14 | 2016-09-22T15:29:33.000Z | 2021-02-08T03:46:40.000Z | from cartodb_services.mapbox.routing import MapboxRouting, MapboxRoutingResponse
from cartodb_services.mapbox.geocoder import MapboxGeocoder
from cartodb_services.mapbox.bulk_geocoder import MapboxBulkGeocoder
from cartodb_services.mapbox.isolines import MapboxIsolines, MapboxIsochronesResponse
| 59.2 | 85 | 0.905405 | 31 | 296 | 8.483871 | 0.483871 | 0.1673 | 0.288973 | 0.380228 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.060811 | 296 | 4 | 86 | 74 | 0.946043 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
3d583f398bc16f21dd4cbecbefb6c44039a032a7 | 53 | py | Python | python/utils/PlayerDataImporter.py | hillnet/Supersonic | 3f3c94eff1d82b85614850d567777c2d6a32bc0e | [
"BSD-2-Clause"
] | null | null | null | python/utils/PlayerDataImporter.py | hillnet/Supersonic | 3f3c94eff1d82b85614850d567777c2d6a32bc0e | [
"BSD-2-Clause"
] | null | null | null | python/utils/PlayerDataImporter.py | hillnet/Supersonic | 3f3c94eff1d82b85614850d567777c2d6a32bc0e | [
"BSD-2-Clause"
] | null | null | null | def import_settings(player):
print("hi")
pass | 17.666667 | 28 | 0.660377 | 7 | 53 | 4.857143 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.207547 | 53 | 3 | 29 | 17.666667 | 0.809524 | 0 | 0 | 0 | 0 | 0 | 0.037037 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | false | 0.333333 | 0.333333 | 0 | 0.666667 | 0.333333 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | 1 | 0 | 0 | 6 |
184373f2837aac41261753d813fcf8769b3ee208 | 35 | py | Python | imp/data/__init__.py | philskillz-coder/uno-discord-bot | 02a3fce3df73d75d31795590dbdb93aaa1d7f268 | [
"MIT"
] | null | null | null | imp/data/__init__.py | philskillz-coder/uno-discord-bot | 02a3fce3df73d75d31795590dbdb93aaa1d7f268 | [
"MIT"
] | null | null | null | imp/data/__init__.py | philskillz-coder/uno-discord-bot | 02a3fce3df73d75d31795590dbdb93aaa1d7f268 | [
"MIT"
] | null | null | null | from imp.data.config import Config
| 17.5 | 34 | 0.828571 | 6 | 35 | 4.833333 | 0.833333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.114286 | 35 | 1 | 35 | 35 | 0.935484 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
a101cb6d99c4c4dce3bc9ed530fc487d4e8559bd | 40 | py | Python | src/flow/callbacks/__init__.py | JonasFrey96/RPOSE | 7da77499ab777ce7ee37b731541982870da8d40b | [
"BSD-3-Clause"
] | null | null | null | src/flow/callbacks/__init__.py | JonasFrey96/RPOSE | 7da77499ab777ce7ee37b731541982870da8d40b | [
"BSD-3-Clause"
] | null | null | null | src/flow/callbacks/__init__.py | JonasFrey96/RPOSE | 7da77499ab777ce7ee37b731541982870da8d40b | [
"BSD-3-Clause"
] | null | null | null | from .time_callback import TimeCallback
| 20 | 39 | 0.875 | 5 | 40 | 6.8 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | 40 | 1 | 40 | 40 | 0.944444 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
a12e7e4b394ce2300cdcd5cd7df2377ad7efc753 | 21,785 | py | Python | service_test.py | igushev/notes_fase | 0d161948bec1780caeec08603e2564e96e8ca45d | [
"MIT"
] | 4 | 2019-05-20T09:57:11.000Z | 2019-09-29T03:55:21.000Z | service_test.py | igushev/notes_fase | 0d161948bec1780caeec08603e2564e96e8ca45d | [
"MIT"
] | null | null | null | service_test.py | igushev/notes_fase | 0d161948bec1780caeec08603e2564e96e8ca45d | [
"MIT"
] | null | null | null | import copy
import datetime
import unittest
from fase_lib import fase
from fase_lib.base_util import datetime_util
from fase_lib.server_util import resource_manager
from fase_lib.fase_model import fase_model
from fase_lib.fase_server import fase_database
from fase_lib.fase_server import fase_resource
from fase_lib.fase_server import fase_server
from fase_lib.fase_server import fase_sign_in_test_util
import database as notes_database
import model as notes_model
import service as notes_service
fase.Service.RegisterService(notes_service.NotesService)
class NotesTest(unittest.TestCase):
def setUp(self):
super(NotesTest, self).setUp()
resource_manager.ResourceManager.Set(
resource_manager.ResourceManager(fase_resource.GetResourceDir()), overwrite=True)
fase_server.FaseServer.Set(fase_server.FaseServer(), overwrite=True)
def Start(self):
fase_database.FaseDatabaseInterface.Set(
fase_database.MockFaseDatabase(
service_prog_list=[],
screen_prog_list=[],
user_list=[
fase.User(user_id='321',
phone_number='+13216549870',
first_name='Edward',
last_name='Igushev',
datetime_added=datetime.datetime.utcnow())]),
overwrite=True)
datetime_now = datetime.datetime.utcnow()
self.note_1 = notes_model.Note(note_id='321_1',
user_id='321',
header='Note 1 Header',
text='Note 1 text',
datetime=datetime_now+datetime.timedelta(days=1),
favourite=False)
self.note_2 = notes_model.Note(note_id='321_2',
user_id='321',
header='Note 2 Header',
text='Note 2 text',
datetime=datetime_now-datetime.timedelta(days=1),
favourite=True)
self.note_3 = notes_model.Note(note_id='321_3',
user_id='321',
header='Note 3 Header',
text='Note 3 text',
datetime=datetime_now,
favourite=False)
notes_database.NotesDatabaseInterface.Set(
notes_database.MockNotesDatabase([self.note_1, self.note_2, self.note_3]),
overwrite=True)
# Create Service
self.device = fase_model.Device(device_type='Python', device_id='DeviceID')
response = fase_server.FaseServer.Get().GetService(self.device)
version_info = response.version_info
session_info = response.session_info
screen_info = response.screen_info
screen = response.screen
# Check present of main elements.
screen.GetElement(id_='notes_frame')
return version_info, session_info, screen_info, screen
def AssertNotes(self, expected_notes, screen):
notes_frame = screen.GetElement(id_='notes_frame')
for expected_note, (actual_note_frame_id, actual_note_frame) in zip(expected_notes, notes_frame.GetIdElementList()):
if expected_note.note_id:
self.assertEqual('note_frame_%s' % expected_note.note_id, actual_note_frame_id)
# Actual variable removed from output.
self.assertFalse(actual_note_frame.HasStringVariable(id_='frame_note_id'))
actual_note_header_frame = actual_note_frame.GetFrame(id_='note_header_frame')
self.assertEqual(expected_note.header, actual_note_header_frame.GetLabel(id_='note_header_label').GetText())
self.assertEqual('images/favourite_2/favourite_orange_1_00.png' if expected_note.favourite else
'images/favourite_2/favourite_frame_black_1_00.png',
actual_note_header_frame.GetImage(id_='note_header_image').GetFilename())
self.assertEqual(expected_note.text, actual_note_frame.GetLabel(id_='note_frame_label').GetText())
if expected_note.datetime:
expected_datetime_text = datetime_util.GetDatetimeDiffStr(expected_note.datetime, datetime.datetime.utcnow())
actual_note_deails_frame = actual_note_frame.GetFrame(id_='note_deails_frame')
self.assertEqual(expected_datetime_text,
actual_note_deails_frame.GetLabel(id_='note_deails_frame_datetime_text').GetText())
def AddNote(self, version_info, session_info, screen_info, note):
# Click on New button.
response = fase_server.FaseServer.Get().ElementCallback(
fase_model.ElementCallback(id_list=[fase.MAIN_BUTTON_ID], method=fase.ON_CLICK_METHOD, device=self.device),
version_info, session_info, screen_info)
version_info = response.screen_info
session_info = response.session_info
screen_info = response.screen_info
screen = response.screen
# Check present of main elements.
screen.GetElement(id_='note_frame')
# Enter note.
elements_update=fase_model.ElementsUpdate([['note_frame', 'header_text'],
['note_frame', 'text_text']], [note.header,
note.text])
screen_update = fase_model.ScreenUpdate(elements_update=elements_update, device=self.device)
fase_server.FaseServer.Get().ScreenUpdate(screen_update, version_info, session_info, screen_info)
# Click on Save button.
response = fase_server.FaseServer.Get().ElementCallback(
fase_model.ElementCallback(id_list=[fase.NEXT_STEP_BUTTON_ID], method=fase.ON_CLICK_METHOD, device=self.device),
version_info, session_info, screen_info)
version_info = response.screen_info
session_info = response.session_info
screen_info = response.screen_info
screen = response.screen
# Check present of main elements.
screen.GetElement(id_='notes_frame')
return version_info, session_info, screen_info, screen
def SelectNote(self, version_info, session_info, screen_info, note):
# Click on the Note.
response = fase_server.FaseServer.Get().ElementCallback(
fase_model.ElementCallback(
id_list=['notes_frame', 'note_frame_%s' % note.note_id], method=fase.ON_CLICK_METHOD, device=self.device),
version_info, session_info, screen_info)
version_info = response.version_info
session_info = response.session_info
screen_info = response.screen_info
screen = response.screen
# Check present of main elements and content.
screen.GetElement(id_='note_frame')
self.assertEqual(note.header, screen.GetElement(id_='note_frame').GetElement(id_='header_text').GetText())
self.assertEqual(note.text, screen.GetElement(id_='note_frame').GetElement(id_='text_text').GetText())
return version_info, session_info, screen_info, screen
def EditNote(self, version_info, session_info, screen_info, note, note_edited):
version_info, session_info, screen_info, _ = self.SelectNote(version_info, session_info, screen_info, note)
# Edit Note.
elements_update=fase_model.ElementsUpdate([['note_frame', 'header_text'],
['note_frame', 'text_text']], [note_edited.header,
note_edited.text])
screen_update = fase_model.ScreenUpdate(elements_update=elements_update, device=self.device)
fase_server.FaseServer.Get().ScreenUpdate(screen_update, version_info, session_info, screen_info)
# Click on Save button.
response = fase_server.FaseServer.Get().ElementCallback(
fase_model.ElementCallback(id_list=[fase.NEXT_STEP_BUTTON_ID], method=fase.ON_CLICK_METHOD, device=self.device),
version_info, session_info, screen_info)
version_info = response.version_info
session_info = response.session_info
screen_info = response.screen_info
screen = response.screen
# Check present of main elements.
screen.GetElement(id_='notes_frame')
return version_info, session_info, screen_info, screen
def DeleteNote(self, version_info, session_info, screen_info, note):
version_info, session_info, screen_info, _ = self.SelectNote(version_info, session_info, screen_info, note)
# Click on Delete image.
response = fase_server.FaseServer.Get().ElementCallback(
fase_model.ElementCallback(id_list=['note_frame', 'delete_image'], method=fase.ON_CLICK_METHOD,
device=self.device),
version_info, session_info, screen_info)
version_info = response.version_info
session_info = response.session_info
screen_info = response.screen_info
screen = response.screen
# Check present of main elements.
screen.GetElement(id_=fase.ALERT_ID)
# Click on Yes.
response = fase_server.FaseServer.Get().ElementCallback(
fase_model.ElementCallback(id_list=[fase.ALERT_ID, 'ok_id'], method=fase.ON_CLICK_METHOD, device=self.device),
version_info, session_info, screen_info)
version_info = response.version_info
session_info = response.session_info
screen_info = response.screen_info
screen = response.screen
# Check present of main elements.
screen.GetElement(id_='notes_frame')
return version_info, session_info, screen_info, screen
def ReverseFavouriteNote(self, version_info, session_info, screen_info, note):
version_info, session_info, screen_info, _ = self.SelectNote(version_info, session_info, screen_info, note)
# Click on Favourite image.
response = fase_server.FaseServer.Get().ElementCallback(
fase_model.ElementCallback(id_list=['note_frame', 'favourite_image'], method=fase.ON_CLICK_METHOD,
device=self.device),
version_info, session_info, screen_info)
version_info = response.version_info
session_info = response.session_info
screen_info = response.screen_info
# Click on Save button.
response = fase_server.FaseServer.Get().ElementCallback(
fase_model.ElementCallback(id_list=[fase.NEXT_STEP_BUTTON_ID], method=fase.ON_CLICK_METHOD, device=self.device),
version_info, session_info, screen_info)
version_info = response.version_info
session_info = response.session_info
screen_info = response.screen_info
screen = response.screen
# Check present of main elements.
screen.GetElement(id_='notes_frame')
return version_info, session_info, screen_info, screen
def testNotes_Start_SignIn_Navigation(self):
version_info, session_info, screen_info, screen = self.Start()
self.AssertNotes([], screen)
# Sign In.
version_info, session_info, screen_info, screen = (
fase_sign_in_test_util.SignInProcedure(
version_info, session_info, screen_info,
sign_in_id_list=[fase.NAVIGATION_ID, 'sign_in_button'], sign_in=True, phone_number='+13216549870'))
self.AssertNotes([self.note_1, self.note_2, self.note_3], screen)
# Click on Notes button.
response = fase_server.FaseServer.Get().ElementCallback(
fase_model.ElementCallback(id_list=[fase.NAVIGATION_ID, 'notes_button'], method=fase.ON_CLICK_METHOD,
device=self.device),
version_info, session_info, screen_info)
screen_info = response.screen_info
screen = response.screen
self.AssertNotes([self.note_1, self.note_2, self.note_3], screen)
# Click on Favourites button.
response = fase_server.FaseServer.Get().ElementCallback(
fase_model.ElementCallback(id_list=[fase.NAVIGATION_ID, 'favourites_button'], method=fase.ON_CLICK_METHOD,
device=self.device),
version_info, session_info, screen_info)
screen_info = response.screen_info
screen = response.screen
self.AssertNotes([self.note_2], screen)
# Click on Recent button.
response = fase_server.FaseServer.Get().ElementCallback(
fase_model.ElementCallback(id_list=[fase.NAVIGATION_ID, 'recent_button'], method=fase.ON_CLICK_METHOD,
device=self.device),
version_info, session_info, screen_info)
screen_info = response.screen_info
screen = response.screen
self.AssertNotes([self.note_1, self.note_3, self.note_2], screen)
# Click on Notes button again.
response = fase_server.FaseServer.Get().ElementCallback(
fase_model.ElementCallback(id_list=[fase.NAVIGATION_ID, 'notes_button'], method=fase.ON_CLICK_METHOD,
device=self.device),
version_info, session_info, screen_info)
screen_info = response.screen_info
screen = response.screen
self.AssertNotes([self.note_1, self.note_2, self.note_3], screen)
def testNotes_Start_AddNote_SignIn(self):
version_info, session_info, screen_info, screen = self.Start()
self.AssertNotes([], screen)
# Create a Note.
note_4 = notes_model.Note(note_id=None,
user_id=None,
header='Note 4 Header',
text='Note 4 text',
datetime=None,
favourite=False)
# Add Note.
version_info, session_info, screen_info, screen = self.AddNote(version_info, session_info, screen_info, note_4)
self.AssertNotes([note_4], screen)
# Sign In.
version_info, session_info, screen_info, screen = (
fase_sign_in_test_util.SignInProcedure(
version_info, session_info, screen_info,
sign_in_id_list=[fase.NAVIGATION_ID, 'sign_in_button'], sign_in=True, phone_number='+13216549870'))
self.AssertNotes([self.note_1, self.note_2, self.note_3, note_4], screen)
def testNotes_Start_AddNote_SignUn(self):
version_info, session_info, screen_info, screen = self.Start()
self.AssertNotes([], screen)
# Create a Note.
note_4 = notes_model.Note(note_id=None,
user_id=None,
header='Note 4 Header',
text='Note 4 text',
datetime=None,
favourite=False)
# Add Note.
version_info, session_info, screen_info, screen = self.AddNote(version_info, session_info, screen_info, note_4)
self.AssertNotes([note_4], screen)
# Sign In.
version_info, session_info, screen_info, screen = (
fase_sign_in_test_util.SignInProcedure(
version_info, session_info, screen_info,
sign_in_id_list=[fase.NAVIGATION_ID, 'sign_in_button'], sign_in=False,
phone_number='+19876543210', first_name='Edward Junior', last_name='Igushev'))
self.AssertNotes([note_4], screen)
def testNotes_Signin_SignOut(self):
version_info, session_info, screen_info, screen = self.Start()
self.AssertNotes([], screen)
# Sign In.
version_info, session_info, screen_info, screen = (
fase_sign_in_test_util.SignInProcedure(
version_info, session_info, screen_info,
sign_in_id_list=[fase.NAVIGATION_ID, 'sign_in_button'], sign_in=True, phone_number='+13216549870'))
self.AssertNotes([self.note_1, self.note_2, self.note_3], screen)
# Sign Out.
fase_sign_in_test_util.SignOutProcedure(version_info, session_info, screen_info,
sign_out_id_list=[fase.NAVIGATION_ID, 'sign_out_button'])
self.AssertNotes([], screen)
def testNotes_Start_SignIn_AddNote(self):
version_info, session_info, screen_info, screen = self.Start()
self.AssertNotes([], screen)
# Sign In.
version_info, session_info, screen_info, screen = (
fase_sign_in_test_util.SignInProcedure(
version_info, session_info, screen_info,
sign_in_id_list=[fase.NAVIGATION_ID, 'sign_in_button'], sign_in=True, phone_number='+13216549870'))
self.AssertNotes([self.note_1, self.note_2, self.note_3], screen)
# Create a Note.
note_4 = notes_model.Note(note_id=None,
user_id=None,
header='Note 4 Header',
text='Note 4 text',
datetime=None,
favourite=False)
# Add Note.
version_info, session_info, screen_info, screen = self.AddNote(version_info, session_info, screen_info, note_4)
self.AssertNotes([self.note_1, self.note_2, self.note_3, note_4], screen)
def testNotes_Start_SignIn_EditNote(self):
version_info, session_info, screen_info, screen = self.Start()
self.AssertNotes([], screen)
# Sign In.
version_info, session_info, screen_info, screen = (
fase_sign_in_test_util.SignInProcedure(
version_info, session_info, screen_info,
sign_in_id_list=[fase.NAVIGATION_ID, 'sign_in_button'], sign_in=True, phone_number='+13216549870'))
self.AssertNotes([self.note_1, self.note_2, self.note_3], screen)
# Copy and edit Note.
note_2_edited = copy.copy(self.note_2)
note_2_edited.header = 'Note 2 Header edited'
note_2_edited.text = 'Note 2 text edited'
note_2_edited.datetime = datetime.datetime.utcnow() # Should be updated by the Service.
# Edit Note.
version_info, session_info, screen_info, screen = (
self.EditNote(version_info, session_info, screen_info, self.note_2, note_2_edited))
self.AssertNotes([self.note_1, note_2_edited, self.note_3], screen)
def testNotes_Start_SignIn_DeleteNote(self):
version_info, session_info, screen_info, screen = self.Start()
self.AssertNotes([], screen)
# Sign In.
version_info, session_info, screen_info, screen = (
fase_sign_in_test_util.SignInProcedure(
version_info, session_info, screen_info,
sign_in_id_list=[fase.NAVIGATION_ID, 'sign_in_button'], sign_in=True, phone_number='+13216549870'))
self.AssertNotes([self.note_1, self.note_2, self.note_3], screen)
# Delete Note.
version_info, session_info, screen_info, screen = (
self.DeleteNote(version_info, session_info, screen_info, self.note_2))
self.AssertNotes([self.note_1, self.note_3], screen)
def testNotes_Start_SignIn_ReverseFavouriteNote(self):
version_info, session_info, screen_info, screen = self.Start()
self.AssertNotes([], screen)
# Sign In.
version_info, session_info, screen_info, screen = (
fase_sign_in_test_util.SignInProcedure(
version_info, session_info, screen_info,
sign_in_id_list=[fase.NAVIGATION_ID, 'sign_in_button'], sign_in=True, phone_number='+13216549870'))
self.AssertNotes([self.note_1, self.note_2, self.note_3], screen)
# Copy and edit Note.
note_3_edited = copy.copy(self.note_3)
note_3_edited.favourite = True
note_3_edited.datetime = datetime.datetime.utcnow() # Should be updated by the Service.
# Reverse Favourite for Note.
version_info, session_info, screen_info, screen = (
self.ReverseFavouriteNote(version_info, session_info, screen_info, self.note_3))
self.AssertNotes([self.note_1, self.note_2, note_3_edited], screen)
def testNotes_Start_SignIn_EditNote_Cancel(self):
version_info, session_info, screen_info, screen = self.Start()
self.AssertNotes([], screen)
# Sign In.
version_info, session_info, screen_info, screen = (
fase_sign_in_test_util.SignInProcedure(
version_info, session_info, screen_info,
sign_in_id_list=[fase.NAVIGATION_ID, 'sign_in_button'], sign_in=True, phone_number='+13216549870'))
self.AssertNotes([self.note_1, self.note_2, self.note_3], screen)
# Copy and edit Note.
note_2_edited = copy.copy(self.note_2)
note_2_edited.header = 'Note 2 Header edited'
note_2_edited.text = 'Note 2 text edited'
version_info, session_info, screen_info, screen = self.SelectNote(
version_info, session_info, screen_info, self.note_2)
# Edit Note.
elements_update=fase_model.ElementsUpdate([['note_frame', 'header_text'],
['note_frame', 'text_text']], [note_2_edited.header,
note_2_edited.text])
screen_update = fase_model.ScreenUpdate(elements_update=elements_update, device=self.device)
fase_server.FaseServer.Get().ScreenUpdate(screen_update, version_info, session_info, screen_info)
# Click on Cancel button.
response = fase_server.FaseServer.Get().ElementCallback(
fase_model.ElementCallback(id_list=[fase.PREV_STEP_BUTTON_ID], method=fase.ON_CLICK_METHOD, device=self.device),
version_info, session_info, screen_info)
version_info = response.version_info
session_info = response.session_info
screen_info = response.screen_info
screen = response.screen
# Check present of main elements.
screen.GetElement(id_='notes_frame')
self.AssertNotes([self.note_1, self.note_2, self.note_3], screen)
def testNotes_EmptyHeader(self):
version_info, session_info, screen_info, screen = self.Start()
self.AssertNotes([], screen)
# Create a Note.
note = notes_model.Note(note_id=None,
user_id=None,
header='',
text='',
datetime=None,
favourite=False)
# Add Note.
version_info, session_info, screen_info, screen = self.AddNote(version_info, session_info, screen_info, note)
self.AssertNotes([note], screen)
if __name__ == '__main__':
unittest.main()
| 46.449893 | 120 | 0.677117 | 2,652 | 21,785 | 5.226998 | 0.062971 | 0.099553 | 0.092916 | 0.133314 | 0.812581 | 0.78423 | 0.769586 | 0.746718 | 0.721036 | 0.689078 | 0 | 0.014582 | 0.228735 | 21,785 | 468 | 121 | 46.549145 | 0.810439 | 0.048336 | 0 | 0.638728 | 0 | 0 | 0.057259 | 0.005997 | 0 | 0 | 0 | 0 | 0.118497 | 1 | 0.052023 | false | 0 | 0.040462 | 0 | 0.112717 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
a134b75ac04946bbddb1d39688fbe8fbf47e44e8 | 5,786 | py | Python | src/unitair/gates/gates.py | qcware/qcware-unitair | 43a241ec147716a85713d1a57c14286c19732aeb | [
"Apache-2.0"
] | null | null | null | src/unitair/gates/gates.py | qcware/qcware-unitair | 43a241ec147716a85713d1a57c14286c19732aeb | [
"Apache-2.0"
] | null | null | null | src/unitair/gates/gates.py | qcware/qcware-unitair | 43a241ec147716a85713d1a57c14286c19732aeb | [
"Apache-2.0"
] | null | null | null | import torch
from typing import Union, Optional
from .gate_construction import parameterized_gate, constant_gate
@parameterized_gate(strictly_complex=True)
def exp_x(
angle: Union[torch.Tensor, float],
dtype: torch.dtype = torch.complex64
):
"""Get the operator e^(-i angle X).
PyTorch device is inherited from the device of `angle`. If `angle` is
a float, CPU is used.
Args:
angle: Tensor with size (batch_length,) or just ().
dtype: Data type for the gate. Required to be complex.
Returns: Tensor with size (batch_length, 2, 2, 2) or (2, 2, 2) if there
is no batch dimension. The (2, 2, 2) is such that the first dimension
means the real and imaginary parts and the last two dimension are
the matrices of the real an imaginary parts of the gates.
"""
angle = angle.to(dtype=dtype)
cos = torch.cos(angle)
i_sin = torch.sin(angle) * 1.j
return [
[[cos, -i_sin],
[-i_sin, cos]],
]
@parameterized_gate(strictly_complex=True)
def exp_y(
angle: Union[torch.Tensor, float],
dtype: torch.dtype = torch.complex64
):
"""Get the operator e^(-i angle Y).
PyTorch device is inherited from the device of `angle`. If `angle` is
a float, CPU is used.
Args:
angle: Tensor with size (batch_length,) or just ().
dtype: Data type for the gate. Required to be complex.
Returns: Tensor with size (batch_length, 2, 2, 2) or (2, 2, 2) if there
is no batch dimension. The (2, 2, 2) is such that the first dimension
means the real and imaginary parts and the last two dimension are
the matrices of the real an imaginary parts of the gates.
"""
angle = angle.to(dtype=dtype)
cos = torch.cos(angle)
sin = torch.sin(angle)
return [
[[cos, -sin],
[sin, cos]],
]
@parameterized_gate(strictly_complex=True)
def exp_z(
angle: Union[torch.Tensor, float],
dtype: torch.dtype = torch.complex64
):
"""Get the operator e^(-i angle Z).
PyTorch device is inherited from the device of `angle`. If `angle` is
a float, CPU is used.
Args:
angle: Tensor with size (batch_length,) or just ().
dtype: Data type for the gate. Required to be complex.
Returns: Tensor with size (batch_length, 2, 2, 2) or (2, 2, 2) if there
is no batch dimension. The (2, 2, 2) is such that the first dimension
means the real and imaginary parts and the last two dimension are
the matrices of the real an imaginary parts of the gates.
"""
angle = angle.to(dtype=dtype)
cos = torch.cos(angle)
i_sin = torch.sin(angle) * 1.j
zero = torch.zeros(angle.size(), device=angle.device)
return [
[[cos - i_sin, zero],
[zero, cos + i_sin]],
]
@constant_gate(strictly_complex=True)
def hadamard(
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None
):
"""Get the Hadamard gate.
Args:
device: If the torch device is not specified, CPU is used.
dtype: torch.dtype for the result.
When not specified, torch.complex64 is used.
"""
val = 2. ** (-.5) + 0.j
return [
[val, val],
[val, -val]
]
@constant_gate(strictly_complex=True)
def pauli_x(
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None
):
"""Get the Pauli X gate.
Args:
device: If the torch device is not specified, CPU is used.
dtype: torch.dtype for the result.
When not specified, torch.complex64 is used.
"""
return [
[0. + 0.j, 1. + 0.j],
[1. + 0.j, 0. + 0.j]
]
@constant_gate(strictly_complex=True)
def pauli_y(
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None
):
"""Get the Pauli Y gate.
Args:
device: If the torch device is not specified, CPU is used.
dtype: torch.dtype for the result.
When not specified, torch.complex64 is used.
"""
return [
[0., -1.j],
[1.j, 0.]
]
@constant_gate(strictly_complex=True)
def pauli_z(
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None
):
"""Get the Pauli Z gate.
Args:
device: If the torch device is not specified, CPU is used.
dtype: torch.dtype for the result.
When not specified, torch.complex64 is used.
"""
return [
[1. + 0.j, 0.j],
[0.j, -1. + 0.j]
]
@constant_gate(strictly_complex=True)
def cnot(
device: Optional[torch.device] = None,
dtype: Optional[torch.device] = None
):
"""Get the CNOT gate.
Args:
device: If the torch device is not specified, CPU is used.
dtype: torch.dtype for the result.
When not specified, torch.complex64 is used.
"""
return [
[1. + 0.j, 0. + 0.j, 0. + 0.j, 0. + 0.j],
[0. + 0.j, 1. + 0.j, 0. + 0.j, 0. + 0.j],
[0. + 0.j, 0. + 0.j, 0. + 0.j, 1. + 0.j],
[0. + 0.j, 0. + 0.j, 1. + 0.j, 0. + 0.j]
]
# `cx` is an alias for `cnot`.
cx = cnot
@constant_gate(strictly_complex=True)
def cz(
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None
):
"""Get the controlled-Z gate.
Args:
device: If the torch device is not specified, CPU is used.
dtype: torch.dtype for the result.
When not specified, torch.complex64 is used.
"""
return [
[1. + 0.j, 0. + 0.j, 0. + 0.j, 0. + 0.j],
[0. + 0.j, 1. + 0.j, 0. + 0.j, 0. + 0.j],
[0. + 0.j, 0. + 0.j, 1. + 0.j, 0. + 0.j],
[0. + 0.j, 0. + 0.j, 0. + 0.j, -1. + 0.j]
]
| 26.911628 | 77 | 0.580885 | 858 | 5,786 | 3.871795 | 0.106061 | 0.024684 | 0.024383 | 0.030102 | 0.902769 | 0.901866 | 0.880494 | 0.842866 | 0.805238 | 0.77634 | 0 | 0.032337 | 0.294504 | 5,786 | 214 | 78 | 27.037383 | 0.78148 | 0.470964 | 0 | 0.56 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.09 | false | 0 | 0.03 | 0 | 0.21 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
a13c45d866388c39508a230399911a39a425e76c | 45 | py | Python | mmelemental/models/forcefield/nonbonded/__init__.py | ccbiozhaw/mmelemental | 2e3215b3d2291cbc0f346efb05e8ad056516b15d | [
"BSD-3-Clause"
] | null | null | null | mmelemental/models/forcefield/nonbonded/__init__.py | ccbiozhaw/mmelemental | 2e3215b3d2291cbc0f346efb05e8ad056516b15d | [
"BSD-3-Clause"
] | null | null | null | mmelemental/models/forcefield/nonbonded/__init__.py | ccbiozhaw/mmelemental | 2e3215b3d2291cbc0f346efb05e8ad056516b15d | [
"BSD-3-Clause"
] | null | null | null | from .base import *
from . import potentials
| 15 | 24 | 0.755556 | 6 | 45 | 5.666667 | 0.666667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.177778 | 45 | 2 | 25 | 22.5 | 0.918919 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
a1c2deec7a47732b66396689f5083392f90ea25b | 116 | py | Python | hello.py | wexler/train | d19d5cf347a6da448a819a6c588cbdf30fa360e1 | [
"MIT"
] | null | null | null | hello.py | wexler/train | d19d5cf347a6da448a819a6c588cbdf30fa360e1 | [
"MIT"
] | null | null | null | hello.py | wexler/train | d19d5cf347a6da448a819a6c588cbdf30fa360e1 | [
"MIT"
] | null | null | null | # This program prints Hello, world!
print('Hello, world!')
print("This is a change")
print('working n branches!')
| 16.571429 | 35 | 0.698276 | 17 | 116 | 4.764706 | 0.705882 | 0.246914 | 0.37037 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.146552 | 116 | 6 | 36 | 19.333333 | 0.818182 | 0.284483 | 0 | 0 | 0 | 0 | 0.6 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 6 |
a1d02a60999233756ffd50c41630baa2db48d1e5 | 66 | py | Python | carpenpi/__init__.py | ethanwhite/web-free-data-science | 8794245e8f42be7245dba51bd6d16161e711d30c | [
"MIT"
] | null | null | null | carpenpi/__init__.py | ethanwhite/web-free-data-science | 8794245e8f42be7245dba51bd6d16161e711d30c | [
"MIT"
] | null | null | null | carpenpi/__init__.py | ethanwhite/web-free-data-science | 8794245e8f42be7245dba51bd6d16161e711d30c | [
"MIT"
] | null | null | null | from . import main
from . import urls
from . import downloadfiles
| 16.5 | 27 | 0.772727 | 9 | 66 | 5.666667 | 0.555556 | 0.588235 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.181818 | 66 | 3 | 28 | 22 | 0.944444 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
a1df451bcdfe7c77439348bb8f9233b9ad73f4f5 | 293 | py | Python | src/python/WMCore/WMBS/Oracle/Workflow/GetDeletableWorkflows.py | khurtado/WMCore | f74e252412e49189a92962945a94f93bec81cd1e | [
"Apache-2.0"
] | 21 | 2015-11-19T16:18:45.000Z | 2021-12-02T18:20:39.000Z | src/python/WMCore/WMBS/Oracle/Workflow/GetDeletableWorkflows.py | khurtado/WMCore | f74e252412e49189a92962945a94f93bec81cd1e | [
"Apache-2.0"
] | 5,671 | 2015-01-06T14:38:52.000Z | 2022-03-31T22:11:14.000Z | src/python/WMCore/WMBS/Oracle/Workflow/GetDeletableWorkflows.py | khurtado/WMCore | f74e252412e49189a92962945a94f93bec81cd1e | [
"Apache-2.0"
] | 67 | 2015-01-21T15:55:38.000Z | 2022-02-03T19:53:13.000Z | #!/usr/bin/env python
"""
_GetDeletableWorkflows_
Oracle implementation of Workflow.GetDeletableWorkflows
"""
from WMCore.WMBS.MySQL.Workflow.GetDeletableWorkflows import GetDeletableWorkflows as MySQLGetDeletableWorkflows
class GetDeletableWorkflows(MySQLGetDeletableWorkflows):
pass
| 22.538462 | 112 | 0.846416 | 24 | 293 | 10.25 | 0.75 | 0.235772 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.088737 | 293 | 12 | 113 | 24.416667 | 0.921348 | 0.34471 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.333333 | 0.333333 | 0 | 0.666667 | 0 | 1 | 0 | 1 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 6 |
a1e4f4a2677a44205235bc3642ca82a3492b29f4 | 85 | py | Python | projects/permissions/media_file_permissions.py | SuviVappula/kaavapino | 0e3687c94afff10527c9bee9627fc30bd2dfab4f | [
"MIT"
] | 3 | 2019-02-07T14:47:00.000Z | 2022-02-15T14:09:38.000Z | projects/permissions/media_file_permissions.py | SuviVappula/kaavapino | 0e3687c94afff10527c9bee9627fc30bd2dfab4f | [
"MIT"
] | 74 | 2017-12-13T09:18:04.000Z | 2022-03-11T23:29:59.000Z | projects/permissions/media_file_permissions.py | SuviVappula/kaavapino | 0e3687c94afff10527c9bee9627fc30bd2dfab4f | [
"MIT"
] | 8 | 2017-12-13T09:31:20.000Z | 2022-02-15T13:10:34.000Z | def has_project_attribute_file_permissions(attribute_file, request):
return True
| 28.333333 | 68 | 0.847059 | 11 | 85 | 6.090909 | 0.818182 | 0.38806 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.105882 | 85 | 2 | 69 | 42.5 | 0.881579 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.5 | false | 0 | 0 | 0.5 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 6 |
b802d6cec439a4a5ef2414ac38beaed13410db9d | 2,961 | py | Python | data/data_utils/computed_fields/flags.py | mattsolo1/gnomadjs-1 | e924407e598ba1902619b2634b639a9f33ff791d | [
"MIT"
] | 15 | 2017-11-22T14:48:04.000Z | 2020-10-05T18:22:24.000Z | data/data_utils/computed_fields/flags.py | mattsolo1/gnomadjs-1 | e924407e598ba1902619b2634b639a9f33ff791d | [
"MIT"
] | 94 | 2020-10-21T17:37:57.000Z | 2022-03-29T14:59:46.000Z | data/data_utils/computed_fields/flags.py | mattsolo1/gnomadjs-1 | e924407e598ba1902619b2634b639a9f33ff791d | [
"MIT"
] | 7 | 2019-01-29T09:08:10.000Z | 2020-02-25T16:22:57.000Z | import hail as hl
def get_expr_for_consequence_lc_lof_flag(transcript_consequence):
"""Flag a transcript consequence if it has an LOFTEE annotation other than HC"""
return hl.or_else((transcript_consequence.lof != "") & (transcript_consequence.lof != "HC"), False)
def get_expr_for_variant_lc_lof_flag(sorted_transcript_consequences):
"""Flag a variant if it has some transcript consequences with LOFTEE annotations and none are marked HC"""
return hl.bind(
lambda lof_annotations: (lof_annotations.size() > 0) & lof_annotations.all(lambda csq: csq.lof != "HC"),
sorted_transcript_consequences.filter(lambda csq: csq.lof != ""),
)
def get_expr_for_genes_with_lc_lof_flag(sorted_transcript_consequences):
"""
From a variant's sorted transcript consequences, get the set of gene IDs where the variant has at least one
LoF consequence in that gene and all the variant's LoF consequences in that gene are not marked HC.
"""
return hl.bind(
lambda lof_consequences: hl.set(lof_consequences.map(lambda csq: csq.gene_id)).filter(
lambda gene_id: hl.bind(
lambda lof_consequences_in_gene: (lof_consequences_in_gene.size() > 0)
& (lof_consequences_in_gene.all(lambda csq: csq.lof != "HC")),
lof_consequences.filter(lambda csq: csq.gene_id == gene_id),
)
),
sorted_transcript_consequences.filter(lambda csq: csq.lof != ""),
)
def get_expr_for_consequence_loftee_flag_flag(transcript_consequence):
"""Flag a transcript consequence if it has a LOFTEE annotation with flags"""
return hl.or_else((transcript_consequence.lof != "") & (transcript_consequence.lof_flags != ""), False)
def get_expr_for_variant_loftee_flag_flag(sorted_transcript_consequences):
"""Flag a variant if it has some transcript consequences with LOFTEE annotations and all have flags"""
return hl.bind(
lambda lof_annotations: (lof_annotations.size() > 0) & lof_annotations.all(lambda csq: csq.lof_flags != ""),
sorted_transcript_consequences.filter(lambda csq: csq.lof != ""),
)
def get_expr_for_genes_with_loftee_flag_flag(sorted_transcript_consequences):
"""
From a variant's sorted transcript consequences, get the set of gene IDs where the variant has at least one
LoF consequence in that gene and all the variant's LoF consequences in that gene are flagged by LOFTEE.
"""
return hl.bind(
lambda lof_consequences: hl.set(lof_consequences.map(lambda csq: csq.gene_id)).filter(
lambda gene_id: hl.bind(
lambda lof_consequences_in_gene: (lof_consequences_in_gene.size() > 0)
& (lof_consequences_in_gene.all(lambda csq: csq.lof_flags != "")),
lof_consequences.filter(lambda csq: csq.gene_id == gene_id),
)
),
sorted_transcript_consequences.filter(lambda csq: csq.lof != ""),
)
| 47.758065 | 116 | 0.703479 | 404 | 2,961 | 4.90099 | 0.160891 | 0.106061 | 0.072727 | 0.060606 | 0.935354 | 0.917677 | 0.870202 | 0.862121 | 0.862121 | 0.862121 | 0 | 0.001694 | 0.202634 | 2,961 | 61 | 117 | 48.540984 | 0.836934 | 0.257683 | 0 | 0.486486 | 0 | 0 | 0.002805 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.162162 | false | 0 | 0.027027 | 0 | 0.351351 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
b8159a09c2f27a21fd881f6c5f367b5824bebf01 | 74 | py | Python | network/utils/__init__.py | ml4ai/tomcat-network-latency-test | be920be19e4e104a99f8fb4464173a3eb2540f89 | [
"MIT"
] | 1 | 2022-01-23T19:29:57.000Z | 2022-01-23T19:29:57.000Z | network/utils/__init__.py | ml4ai/tomcat-network-latency-test | be920be19e4e104a99f8fb4464173a3eb2540f89 | [
"MIT"
] | 34 | 2022-01-18T18:26:15.000Z | 2022-03-31T19:21:28.000Z | network/utils/__init__.py | ml4ai/tomcat-network-latency-test | be920be19e4e104a99f8fb4464173a3eb2540f89 | [
"MIT"
] | 2 | 2022-01-27T05:31:33.000Z | 2022-03-29T20:57:23.000Z | from .config_network import HEADER
from .read_message import read_message
| 24.666667 | 38 | 0.864865 | 11 | 74 | 5.545455 | 0.636364 | 0.360656 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.108108 | 74 | 2 | 39 | 37 | 0.924242 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
62acccd3f6d838f7d2dd12c92ca7cc5894b3d24a | 35,688 | py | Python | reconcile/test/test_terraform_vpc_peerings_build_desired_state.py | bhushanthakur93/qontract-reconcile | fd8eea9f92d353224113955d08e3592864e37df8 | [
"Apache-2.0"
] | null | null | null | reconcile/test/test_terraform_vpc_peerings_build_desired_state.py | bhushanthakur93/qontract-reconcile | fd8eea9f92d353224113955d08e3592864e37df8 | [
"Apache-2.0"
] | null | null | null | reconcile/test/test_terraform_vpc_peerings_build_desired_state.py | bhushanthakur93/qontract-reconcile | fd8eea9f92d353224113955d08e3592864e37df8 | [
"Apache-2.0"
] | null | null | null | import pytest
import testslide
from reconcile.utils import aws_api
import reconcile.terraform_vpc_peerings as sut
from reconcile.utils import ocm
from reconcile.test.test_terraform_vpc_peerings import (
MockOCM,
MockAWSAPI,
build_cluster,
build_accepter_connection,
build_requester_connection,
)
def test_c2c_all_clusters(mocker):
"""
happy path
"""
accepter_cluster = build_cluster(
name="accepter_cluster",
vpc="accepter_vpc",
network_mgmt_accounts=["acc"],
peering_connections=[
build_accepter_connection(name="peername", cluster="requester_cluster")
],
)
requester_cluster = build_cluster(
name="requester_cluster",
vpc="requester_vpc",
network_mgmt_accounts=["acc"],
peering_connections=[
build_requester_connection(name="peername", peer_cluster=accepter_cluster)
],
)
ocm_map = {
"requester_cluster": MockOCM()
.register("requester_cluster", "acc", "terraform", "r")
.register("accepter_cluster", "acc", "terraform", "a")
.auto_speced_mock(mocker)
}
awsapi = (
MockAWSAPI()
.register(
vpc="accepter_vpc",
vpc_id="accepter_vpc_id",
route_tables=["accepter_rt_id"],
)
.register(
vpc="requester_vpc",
vpc_id="requester_vpc_id",
route_tables=["requester_rt_id"],
)
.auto_speced_mock(mocker)
)
result, error = sut.build_desired_state_all_clusters(
[requester_cluster], ocm_map, awsapi
)
expected = [
{
"connection_provider": "cluster-vpc-requester",
"connection_name": "peername",
"requester": {
"cidr_block": "requester_vpc",
"region": "region",
"vpc_id": "requester_vpc_id",
"route_table_ids": ["requester_rt_id"],
"account": {
"name": "acc",
"uid": "acc",
"terraformUsername": "terraform",
"automationToken": {},
"assume_role": "arn::::r",
"assume_region": "region",
"assume_cidr": "requester_vpc",
},
"peer_owner_id": "a",
},
"accepter": {
"cidr_block": "accepter_vpc",
"region": "region",
"vpc_id": "accepter_vpc_id",
"route_table_ids": ["accepter_rt_id"],
"account": {
"name": "acc",
"uid": "acc",
"terraformUsername": "terraform",
"automationToken": {},
"assume_role": "arn::::a",
"assume_region": "region",
"assume_cidr": "accepter_vpc",
},
},
"deleted": False,
}
]
assert expected == result
assert not error
def test_c2c_one_cluster_failing_recoverable(mocker):
"""
in this scenario, the handling of a single cluster fails with known
exceptions
"""
build_desired_state_single_cluster = mocker.patch.object(
sut, "build_desired_state_single_cluster"
)
build_desired_state_single_cluster.side_effect = sut.BadTerraformPeeringState(
"something bad"
)
result, error = sut.build_desired_state_all_clusters([{"name": "cluster"}], {}, {})
assert not result
assert error
def test_c2c_one_cluster_failing_weird(mocker):
"""
in this scenario, the handling of a single cluster fails with unexpected
exceptions
"""
build_desired_state_single_cluster = mocker.patch.object(
sut, "build_desired_state_single_cluster"
)
SOMETHING_UNEXPECTED = "nobody expects the spanish inquisition"
build_desired_state_single_cluster.side_effect = ValueError(SOMETHING_UNEXPECTED)
with pytest.raises(ValueError) as ex:
sut.build_desired_state_all_clusters([{"name": "cluster"}], {}, {})
assert str(ex.value) == SOMETHING_UNEXPECTED
def test_c2c_base(mocker):
"""
happy path
"""
accepter_cluster = build_cluster(
name="accepter_cluster",
vpc="accepter_vpc",
network_mgmt_accounts=["acc"],
peering_connections=[
build_accepter_connection(name="peername", cluster="requester_cluster")
],
)
requester_cluster = build_cluster(
name="requester_cluster",
vpc="requester_vpc",
network_mgmt_accounts=["acc"],
peering_connections=[
build_requester_connection(name="peername", peer_cluster=accepter_cluster)
],
)
ocm = (
MockOCM()
.register("requester_cluster", "acc", "terraform", "r")
.register("accepter_cluster", "acc", "terraform", "a")
.auto_speced_mock(mocker)
)
awsapi = (
MockAWSAPI()
.register(
vpc="accepter_vpc",
vpc_id="accepter_vpc_id",
route_tables=["accepter_rt_id"],
)
.register(
vpc="requester_vpc",
vpc_id="requester_vpc_id",
route_tables=["requester_rt_id"],
)
.auto_speced_mock(mocker)
)
result = sut.build_desired_state_single_cluster(requester_cluster, ocm, awsapi)
expected = [
{
"connection_provider": "cluster-vpc-requester",
"connection_name": "peername",
"requester": {
"cidr_block": "requester_vpc",
"region": "region",
"vpc_id": "requester_vpc_id",
"route_table_ids": ["requester_rt_id"],
"account": {
"name": "acc",
"uid": "acc",
"terraformUsername": "terraform",
"automationToken": {},
"assume_role": "arn::::r",
"assume_region": "region",
"assume_cidr": "requester_vpc",
},
"peer_owner_id": "a",
},
"accepter": {
"cidr_block": "accepter_vpc",
"region": "region",
"vpc_id": "accepter_vpc_id",
"route_table_ids": ["accepter_rt_id"],
"account": {
"name": "acc",
"uid": "acc",
"terraformUsername": "terraform",
"automationToken": {},
"assume_role": "arn::::a",
"assume_region": "region",
"assume_cidr": "accepter_vpc",
},
},
"deleted": False,
}
]
assert expected == result
def test_c2c_no_peerings(mocker):
"""
in this scenario, the requester cluster has no peerings defines,
which results in an empty desired state
"""
requester_cluster = build_cluster(
name="requester_cluster",
vpc="requester_vpc",
network_mgmt_accounts=["acc"],
peering_connections=[],
)
result = sut.build_desired_state_single_cluster(
requester_cluster,
MockOCM().auto_speced_mock(mocker),
MockAWSAPI().auto_speced_mock(mocker),
)
assert not result
def test_c2c_no_matches(mocker):
"""
in this scenario, the accepter cluster has no cluster-vpc-accepter
connection that references back to the requester cluster
"""
accepter_cluster = build_cluster(
name="accepter_cluster",
vpc="accepter_vpc",
network_mgmt_accounts=["acc"],
peering_connections=[
build_accepter_connection(name="peername", cluster="not_a_matching_cluster")
],
)
requester_cluster = build_cluster(
name="requester_cluster",
vpc="requester_vpc",
network_mgmt_accounts=["acc"],
peering_connections=[
build_requester_connection(name="peername", peer_cluster=accepter_cluster)
],
)
with pytest.raises(sut.BadTerraformPeeringState) as ex:
sut.build_desired_state_single_cluster(
requester_cluster,
MockOCM().auto_speced_mock(mocker),
MockAWSAPI().auto_speced_mock(mocker),
)
assert str(ex.value).startswith("[no_matching_peering]")
def test_c2c_no_vpc_in_aws(mocker):
"""
in this scenario, there are no VPCs found in AWS
"""
accepter_cluster = build_cluster(
name="accepter_cluster",
vpc="accepter_vpc",
network_mgmt_accounts=["acc"],
peering_connections=[
build_accepter_connection(name="peername", cluster="requester_cluster")
],
)
requester_cluster = build_cluster(
name="requester_cluster",
vpc="requester_vpc",
network_mgmt_accounts=["acc"],
peering_connections=[
build_requester_connection(name="peername", peer_cluster=accepter_cluster)
],
)
ocm = (
MockOCM()
.register("requester_cluster", "acc", "terraform", "r")
.register("accepter_cluster", "acc", "terraform", "a")
.auto_speced_mock(mocker)
)
awsapi = MockAWSAPI().auto_speced_mock(mocker)
with pytest.raises(sut.BadTerraformPeeringState) as ex:
sut.build_desired_state_single_cluster(requester_cluster, ocm, awsapi)
assert str(ex.value).endswith("could not find VPC ID for cluster")
def test_c2c_no_peer_account(mocker):
"""
in this scenario, the accepters connection and the accepters cluster
have no aws infrastructura account available to set up the peering″
"""
accepter_cluster = build_cluster(
# no network_mgmt_accounts here
name="accepter_cluster",
vpc="accepter_vpc",
peering_connections=[
build_accepter_connection(
# no network_mgmt_accounts here
name="peername",
cluster="requester_cluster",
)
],
)
requester_cluster = build_cluster(
name="requester_cluster",
vpc="requester_vpc",
network_mgmt_accounts=["acc"],
peering_connections=[
build_requester_connection(name="peername", peer_cluster=accepter_cluster)
],
)
ocm = MockOCM().auto_speced_mock(mocker)
awsapi = MockAWSAPI().auto_speced_mock(mocker)
with pytest.raises(sut.BadTerraformPeeringState) as ex:
sut.build_desired_state_single_cluster(requester_cluster, ocm, awsapi)
assert str(ex.value).startswith("[no_account_available]")
class TestBuildDesiredStateVpcMesh(testslide.TestCase):
def setUp(self):
super().setUp()
self.clusters = [
{
"name": "clustername",
"spec": {
"region": "mars-plain-1",
},
"network": {
"vpc": "172.16.0.0/12",
"service": "10.0.0.0/8",
"pod": "192.168.0.0/16",
},
"peering": {
"connections": [
{
"provider": "account-vpc-mesh",
"name": "peername",
"vpc": {"$ref": "/aws/account/vpcs/mars-plain-1"},
"manageRoutes": True,
"tags": '["tag1"]',
},
]
},
}
]
self.peer = {
"vpc": "172.17.0.0/12",
"service": "10.1.0.0/8",
"pod": "192.168.1.0/16",
}
self.peer_cluster = {
"name": "apeerclustername",
"spec": {
"region": "mars-olympus-2",
},
"network": self.peer,
"peering": {
"connections": [
{
"provider": "cluster-vpc-requester",
"name": "peername",
"vpc": {"$ref": "/aws/account/vpcs/mars-plain-1"},
"manageRoutes": True,
"tags": '["tag1"]',
},
]
},
}
self.aws_account = {
"name": "accountname",
"uid": "anuid",
"terraformUsername": "aterraformusename",
"automationtoken": "anautomationtoken",
"assume_role": "arole:very:useful:indeed:it:is",
"assume_region": "moon-tranquility-1",
"assume_cidr": "172.25.0.0/12",
}
self.peer_account = {
"name": "peer_account",
"uid": "peeruid",
"terraformUsername": "peerterraformusename",
"automationtoken": "peeranautomationtoken",
"assume_role": "a:peer:role:indeed:it:is",
"assume_region": "mars-hellas-1",
"assume_cidr": "172.25.0.0/12",
}
self.clusters[0]["peering"]["connections"][0]["cluster"] = self.peer_cluster
self.clusters[0]["peering"]["connections"][0]["account"] = self.peer_account
self.peer_vpc = {
"cidr_block": "172.30.0.0/12",
"vpc_id": "peervpcid",
"route_table_ids": ["peer_route_table_id"],
}
self.vpc_mesh_single_cluster = self.mock_callable(
sut, "build_desired_state_vpc_mesh_single_cluster"
)
self.maxDiff = None
self.ocm = testslide.StrictMock(ocm.OCM)
self.ocm_map = {"clustername": self.ocm}
self.ocm.get_aws_infrastructure_access_terraform_assume_role = (
lambda cluster, uid, tfuser: self.peer_account["assume_role"]
)
self.awsapi = testslide.StrictMock(aws_api.AWSApi)
self.account_vpcs = [
{
"vpc_id": "vpc1",
"region": "moon-dark-1",
"cidr_block": "192.168.3.0/24",
"route_table_ids": ["vpc1_route_table"],
},
{
"vpc_id": "vpc2",
"region": "mars-utopia-2",
"cidr_block": "192.168.4.0/24",
"route_table_ids": ["vpc2_route_table"],
},
]
self.addCleanup(testslide.mock_callable.unpatch_all_callable_mocks)
def test_all_fine(self):
expected = [
{
"connection_provider": "account-vpc-mesh",
"connection_name": "peername_peer_account-vpc1",
"requester": {
"vpc_id": "vpc_id",
"route_table_ids": ["route_table_id"],
"account": self.peer_account,
"region": "mars-plain-1",
"cidr_block": "172.16.0.0/12",
},
"accepter": {
"vpc_id": "vpc1",
"region": "moon-dark-1",
"cidr_block": "192.168.3.0/24",
"route_table_ids": ["vpc1_route_table"],
"account": self.peer_account,
},
"deleted": False,
},
{
"connection_provider": "account-vpc-mesh",
"connection_name": "peername_peer_account-vpc2",
"requester": {
"vpc_id": "vpc_id",
"route_table_ids": ["route_table_id"],
"account": self.peer_account,
"region": "mars-plain-1",
"cidr_block": "172.16.0.0/12",
},
"accepter": {
"vpc_id": "vpc2",
"region": "mars-utopia-2",
"cidr_block": "192.168.4.0/24",
"route_table_ids": ["vpc2_route_table"],
"account": self.peer_account,
},
"deleted": False,
},
]
self.vpc_mesh_single_cluster.for_call(
self.clusters[0], self.ocm, self.awsapi
).to_return_value(expected)
rs = sut.build_desired_state_vpc_mesh(self.clusters, self.ocm_map, self.awsapi)
self.assertEqual(rs, (expected, False))
def test_cluster_raises(self):
self.vpc_mesh_single_cluster.to_raise(
sut.BadTerraformPeeringState("This is wrong")
)
rs = sut.build_desired_state_vpc_mesh(self.clusters, self.ocm_map, self.awsapi)
self.assertEqual(rs, ([], True))
def test_cluster_raises_unexpected(self):
self.vpc_mesh_single_cluster.to_raise(ValueError("Nope"))
with self.assertRaises(ValueError):
sut.build_desired_state_vpc_mesh(self.clusters, self.ocm_map, self.awsapi)
class TestBuildDesiredStateVpcMeshSingleCluster(testslide.TestCase):
def setUp(self):
super().setUp()
self.cluster = {
"name": "clustername",
"spec": {
"region": "mars-plain-1",
},
"network": {
"vpc": "172.16.0.0/12",
"service": "10.0.0.0/8",
"pod": "192.168.0.0/16",
},
"peering": {
"connections": [
{
"provider": "account-vpc-mesh",
"name": "peername",
"vpc": {"$ref": "/aws/account/vpcs/mars-plain-1"},
"manageRoutes": True,
"tags": '["tag1"]',
},
]
},
}
self.peer = {
"vpc": "172.17.0.0/12",
"service": "10.1.0.0/8",
"pod": "192.168.1.0/16",
}
self.peer_cluster = {
"name": "apeerclustername",
"spec": {
"region": "mars-olympus-2",
},
"network": self.peer,
"peering": {
"connections": [
{
"provider": "cluster-vpc-requester",
"name": "peername",
"vpc": {"$ref": "/aws/account/vpcs/mars-plain-1"},
"manageRoutes": True,
"tags": '["tag1"]',
},
]
},
}
self.awsapi = testslide.StrictMock(aws_api.AWSApi)
self.mock_constructor(aws_api, "AWSApi").to_return_value(self.awsapi)
self.find_matching_peering = self.mock_callable(sut, "find_matching_peering")
self.aws_account = {
"name": "accountname",
"uid": "anuid",
"terraformUsername": "aterraformusename",
"automationtoken": "anautomationtoken",
"assume_role": "arole:very:useful:indeed:it:is",
"assume_region": "moon-tranquility-1",
"assume_cidr": "172.25.0.0/12",
}
self.peer_account = {
"name": "peer_account",
"uid": "peeruid",
"terraformUsername": "peerterraformusename",
"automationtoken": "peeranautomationtoken",
"assume_role": "a:peer:role:indeed:it:is",
"assume_region": "mars-hellas-1",
"assume_cidr": "172.25.0.0/12",
}
self.cluster["peering"]["connections"][0]["cluster"] = self.peer_cluster
self.cluster["peering"]["connections"][0]["account"] = self.peer_account
self.peer_vpc = {
"cidr_block": "172.30.0.0/12",
"vpc_id": "peervpcid",
"route_table_ids": ["peer_route_table_id"],
}
self.maxDiff = None
self.addCleanup(testslide.mock_callable.unpatch_all_callable_mocks)
self.ocm = testslide.StrictMock(template=ocm.OCM)
self.ocm.get_aws_infrastructure_access_terraform_assume_role = (
lambda cluster, uid, tfuser: self.peer_account["assume_role"]
)
self.account_vpcs = [
{
"vpc_id": "vpc1",
"region": "moon-dark-1",
"cidr_block": "192.168.3.0/24",
"route_table_ids": ["vpc1_route_table"],
},
{
"vpc_id": "vpc2",
"region": "mars-utopia-2",
"cidr_block": "192.168.4.0/24",
"route_table_ids": ["vpc2_route_table"],
},
]
def test_one_cluster(self):
req_account = {
**self.peer_account,
"assume_region": "mars-plain-1",
"assume_cidr": "172.16.0.0/12",
}
self.mock_callable(self.awsapi, "get_cluster_vpc_details").for_call(
req_account, route_tables=True
).to_return_value(
("vpc_id", ["route_table_id"], "subnet_id")
).and_assert_called_once()
self.mock_callable(self.awsapi, "get_vpcs_details").for_call(
req_account, tags=["tag1"], route_tables=True
).to_return_value(self.account_vpcs).and_assert_called_once()
expected = [
{
"connection_provider": "account-vpc-mesh",
"connection_name": "peername_peer_account-vpc1",
"requester": {
"vpc_id": "vpc_id",
"route_table_ids": ["route_table_id"],
"account": self.peer_account,
"region": "mars-plain-1",
"cidr_block": "172.16.0.0/12",
},
"accepter": {
"vpc_id": "vpc1",
"region": "moon-dark-1",
"cidr_block": "192.168.3.0/24",
"route_table_ids": ["vpc1_route_table"],
"account": self.peer_account,
},
"deleted": False,
},
{
"connection_provider": "account-vpc-mesh",
"connection_name": "peername_peer_account-vpc2",
"requester": {
"vpc_id": "vpc_id",
"route_table_ids": ["route_table_id"],
"account": self.peer_account,
"region": "mars-plain-1",
"cidr_block": "172.16.0.0/12",
},
"accepter": {
"vpc_id": "vpc2",
"region": "mars-utopia-2",
"cidr_block": "192.168.4.0/24",
"route_table_ids": ["vpc2_route_table"],
"account": self.peer_account,
},
"deleted": False,
},
]
rs = sut.build_desired_state_vpc_mesh_single_cluster(
self.cluster, self.ocm, self.awsapi
)
self.assertEqual(rs, expected)
def test_no_peering_connections(self):
self.cluster["peering"]["connections"] = []
rs = sut.build_desired_state_vpc_mesh_single_cluster(
self.cluster, self.ocm, self.awsapi
)
self.assertEqual(rs, [])
def test_no_peer_vpc_id(self):
self.mock_callable(self.awsapi, "get_cluster_vpc_details").to_return_value(
(None, [None], None)
).and_assert_called_once()
with self.assertRaises(sut.BadTerraformPeeringState):
sut.build_desired_state_vpc_mesh_single_cluster(
self.cluster, self.ocm, self.awsapi
)
class TestBuildDesiredStateVpc(testslide.TestCase):
def setUp(self):
super().setUp()
self.peer = {
"vpc": "172.17.0.0/12",
"service": "10.1.0.0/8",
"pod": "192.168.1.0/16",
}
self.aws_account = {
"name": "accountname",
"uid": "anuid",
"terraformUsername": "aterraformusename",
"automationtoken": "anautomationtoken",
"assume_role": "arole:very:useful:indeed:it:is",
"assume_region": "moon-tranquility-1",
"assume_cidr": "172.25.0.0/12",
}
self.clusters = [
{
"name": "clustername",
"spec": {
"region": "mars-plain-1",
},
"network": {
"vpc": "172.16.0.0/12",
"service": "10.0.0.0/8",
"pod": "192.168.0.0/16",
},
"peering": {
"connections": [
{
"provider": "account-vpc",
"name": "peername",
"vpc": {
"$ref": "/aws/account/vpcs/mars-plain-1",
"cidr_block": "172.30.0.0/12",
"vpc_id": "avpcid",
**self.peer,
"region": "mars-olympus-2",
"account": self.aws_account,
},
"manageRoutes": True,
},
]
},
}
]
self.peer_cluster = {
"name": "apeerclustername",
"spec": {
"region": "mars-olympus-2",
},
"network": self.peer,
"peering": {
"connections": [
{
"provider": "account-vpc",
"name": "peername",
"vpc": {"$ref": "/aws/account/vpcs/mars-plain-1"},
"manageRoutes": True,
},
]
},
}
self.clusters[0]["peering"]["connections"][0]["cluster"] = self.peer_cluster
self.build_single_cluster = self.mock_callable(
sut, "build_desired_state_single_cluster"
)
self.ocm = testslide.StrictMock(template=ocm.OCM)
self.ocm_map = {"clustername": self.ocm}
self.awsapi = testslide.StrictMock(aws_api.AWSApi)
self.build_single_cluster = self.mock_callable(
sut, "build_desired_state_vpc_single_cluster"
)
self.addCleanup(testslide.mock_callable.unpatch_all_callable_mocks)
self.maxDiff = None
def test_all_fine(self):
expected = [
{
"accepter": {
"account": {
"assume_cidr": "172.16.0.0/12",
"assume_region": "mars-plain-1",
"assume_role": "this:wonderful:role:hell:yeah",
"automationtoken": "anautomationtoken",
"name": "accountname",
"terraformUsername": "aterraformusename",
"uid": "anuid",
},
"cidr_block": "172.30.0.0/12",
"region": "mars-olympus-2",
"vpc_id": "avpcid",
},
"connection_name": "peername",
"connection_provider": "account-vpc",
"deleted": False,
"requester": {
"account": {
"assume_cidr": "172.16.0.0/12",
"assume_region": "mars-plain-1",
"assume_role": "this:wonderful:role:hell:yeah",
"automationtoken": "anautomationtoken",
"name": "accountname",
"terraformUsername": "aterraformusename",
"uid": "anuid",
},
"cidr_block": "172.16.0.0/12",
"region": "mars-plain-1",
"route_table_ids": ["routetableid"],
"vpc_id": "vpcid",
},
}
]
self.build_single_cluster.for_call(
self.clusters[0], self.ocm, self.awsapi
).to_return_value(expected).and_assert_called_once()
rs = sut.build_desired_state_vpc(self.clusters, self.ocm_map, self.awsapi)
self.assertEqual(rs, (expected, False))
def test_cluster_fails(self):
self.build_single_cluster.to_raise(
sut.BadTerraformPeeringState("I have failed")
)
self.assertEqual(
sut.build_desired_state_vpc(self.clusters, self.ocm_map, self.awsapi),
([], True),
)
def test_error_persists(self):
self.clusters.append(self.clusters[0].copy())
self.clusters[1]["name"] = "afailingcluster"
self.ocm_map["afailingcluster"] = self.ocm
self.build_single_cluster.for_call(
self.clusters[0], self.ocm, self.awsapi
).to_return_value([{"a dict": "a value"}]).and_assert_called_once()
self.mock_callable(sut, "build_desired_state_vpc_single_cluster").for_call(
self.clusters[1], self.ocm, self.awsapi
).to_raise(sut.BadTerraformPeeringState("Fail!")).and_assert_called_once()
self.assertEqual(
sut.build_desired_state_vpc(self.clusters, self.ocm_map, self.awsapi),
([{"a dict": "a value"}], True),
)
def test_other_exceptions_raise(self):
self.clusters.append(self.clusters[0].copy())
self.clusters[1]["name"] = "afailingcluster"
self.ocm_map["afailingcluster"] = self.ocm
self.build_single_cluster.for_call(
self.clusters[0], self.ocm, self.awsapi
).to_raise(ValueError("I am not planned!")).and_assert_called_once()
with self.assertRaises(ValueError):
sut.build_desired_state_vpc(self.clusters, self.ocm_map, self.awsapi)
class TestBuildDesiredStateVpcSingleCluster(testslide.TestCase):
def setUp(self):
super().setUp()
self.peer = {
"vpc": "172.17.0.0/12",
"service": "10.1.0.0/8",
"pod": "192.168.1.0/16",
}
self.aws_account = {
"name": "accountname",
"uid": "anuid",
"terraformUsername": "aterraformusename",
"automationtoken": "anautomationtoken",
"assume_role": "arole:very:useful:indeed:it:is",
"assume_region": "moon-tranquility-1",
"assume_cidr": "172.25.0.0/12",
}
self.cluster = {
"name": "clustername",
"spec": {
"region": "mars-plain-1",
},
"network": {
"vpc": "172.16.0.0/12",
"service": "10.0.0.0/8",
"pod": "192.168.0.0/16",
},
"peering": {
"connections": [
{
"provider": "account-vpc",
"name": "peername",
"vpc": {
"$ref": "/aws/account/vpcs/mars-plain-1",
"cidr_block": "172.30.0.0/12",
"vpc_id": "avpcid",
**self.peer,
"region": "mars-olympus-2",
"account": self.aws_account,
},
"manageRoutes": True,
},
]
},
}
self.peer_cluster = {
"name": "apeerclustername",
"spec": {
"region": "mars-olympus-2",
},
"network": self.peer,
"peering": {
"connections": [
{
"provider": "account-vpc",
"name": "peername",
"vpc": {"$ref": "/aws/account/vpcs/mars-plain-1"},
"manageRoutes": True,
},
]
},
}
self.cluster["peering"]["connections"][0]["cluster"] = self.peer_cluster
self.build_single_cluster = self.mock_callable(
sut, "build_desired_state_single_cluster"
)
self.ocm = testslide.StrictMock(template=ocm.OCM)
self.awsapi = testslide.StrictMock(aws_api.AWSApi)
self.mock_constructor(aws_api, "AWSApi").to_return_value(self.awsapi)
self.ocm.get_aws_infrastructure_access_terraform_assume_role = (
lambda cluster, uid, tfuser: self.aws_account["assume_role"]
)
self.addCleanup(testslide.mock_callable.unpatch_all_callable_mocks)
self.maxDiff = None
def test_all_fine(self):
expected = [
{
"accepter": {
"account": {
"assume_cidr": "172.16.0.0/12",
"assume_region": "mars-plain-1",
"assume_role": "this:wonderful:role:hell:yeah",
"automationtoken": "anautomationtoken",
"name": "accountname",
"terraformUsername": "aterraformusename",
"uid": "anuid",
},
"cidr_block": "172.30.0.0/12",
"region": "mars-olympus-2",
"vpc_id": "avpcid",
},
"connection_name": "peername",
"connection_provider": "account-vpc",
"deleted": False,
"requester": {
"account": {
"assume_cidr": "172.16.0.0/12",
"assume_region": "mars-plain-1",
"assume_role": "this:wonderful:role:hell:yeah",
"automationtoken": "anautomationtoken",
"name": "accountname",
"terraformUsername": "aterraformusename",
"uid": "anuid",
},
"cidr_block": "172.16.0.0/12",
"region": "mars-plain-1",
"route_table_ids": ["routetableid"],
"vpc_id": "vpcid",
},
}
]
self.mock_callable(self.awsapi, "get_cluster_vpc_details",).for_call(
self.aws_account, route_tables=True
).to_return_value(("vpcid", ["routetableid"], {})).and_assert_called_once()
self.mock_callable(
self.ocm, "get_aws_infrastructure_access_terraform_assume_role"
).for_call(
self.cluster["name"],
self.aws_account["uid"],
self.aws_account["terraformUsername"],
).to_return_value(
"this:wonderful:role:hell:yeah"
).and_assert_called_once()
rs = sut.build_desired_state_vpc_single_cluster(
self.cluster, self.ocm, self.awsapi
)
self.assertEqual(rs, expected)
def test_different_provider(self):
self.cluster["peering"]["connections"][0]["provider"] = "something-else"
self.assertEqual(
sut.build_desired_state_vpc_single_cluster(
self.cluster, self.ocm, self.awsapi
),
[],
)
def test_no_vpc_id(self):
self.mock_callable(self.awsapi, "get_cluster_vpc_details").to_return_value(
(None, None, None)
).and_assert_called_once()
self.mock_callable(
self.ocm, "get_aws_infrastructure_access_terraform_assume_role"
).to_return_value("a:role:that:you:will:like").and_assert_called_once()
with self.assertRaises(sut.BadTerraformPeeringState):
sut.build_desired_state_vpc_single_cluster(
self.cluster, self.ocm, self.awsapi
)
| 35.795386 | 88 | 0.498179 | 3,265 | 35,688 | 5.180704 | 0.075651 | 0.005557 | 0.032161 | 0.033107 | 0.890807 | 0.872894 | 0.853444 | 0.836536 | 0.819923 | 0.798049 | 0 | 0.026095 | 0.372898 | 35,688 | 996 | 89 | 35.831325 | 0.729625 | 0.018494 | 0 | 0.682682 | 0 | 0 | 0.251648 | 0.038497 | 0 | 0 | 0 | 0 | 0.037989 | 1 | 0.027933 | false | 0 | 0.006704 | 0 | 0.039106 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
1a03604ff55d948177af480c29981b33791ab46c | 34 | py | Python | backend/apps/__init__.py | Luanee/MoneyThreads | 786610855ad4d4fdda4a25a95c9e4756c6a9dedf | [
"MIT"
] | 21 | 2021-07-26T05:19:45.000Z | 2022-02-01T07:35:21.000Z | backend/apps/__init__.py | Luanee/MoneyThreads | 786610855ad4d4fdda4a25a95c9e4756c6a9dedf | [
"MIT"
] | 3 | 2021-03-30T14:04:13.000Z | 2021-09-22T19:31:13.000Z | backend/apps/__init__.py | Luanee/MoneyThreads | 786610855ad4d4fdda4a25a95c9e4756c6a9dedf | [
"MIT"
] | 2 | 2021-09-21T06:52:10.000Z | 2021-09-26T07:31:27.000Z | from django.apps import AppConfig
| 17 | 33 | 0.852941 | 5 | 34 | 5.8 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.117647 | 34 | 1 | 34 | 34 | 0.966667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
1a1dc2b61aa6b348ab374bb0c560e8389a2f6b7d | 170 | py | Python | app/admin/__init__.py | zheng-zy/blog | e6f9ae4a4770ea99d48e15140e2eacaa9678b75e | [
"Apache-2.0"
] | null | null | null | app/admin/__init__.py | zheng-zy/blog | e6f9ae4a4770ea99d48e15140e2eacaa9678b75e | [
"Apache-2.0"
] | null | null | null | app/admin/__init__.py | zheng-zy/blog | e6f9ae4a4770ea99d48e15140e2eacaa9678b75e | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# coding=utf-8
# Created by zhezhiyong@163.com on 2016/12/6.
from flask import Blueprint
admin = Blueprint('admin', __name__)
from . import views
| 18.888889 | 45 | 0.735294 | 27 | 170 | 4.481481 | 0.851852 | 0.231405 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.075342 | 0.141176 | 170 | 8 | 46 | 21.25 | 0.753425 | 0.452941 | 0 | 0 | 0 | 0 | 0.055556 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.666667 | 0 | 0.666667 | 0.666667 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | 6 |
1a21624ea7304e77c9d9f630f63e60310bc903cf | 35 | py | Python | STEMWizard/__init__.py | rtphokie/ncsef_automation | 730d16beb38640df579be742b2fcecc2f31e4190 | [
"Apache-2.0"
] | null | null | null | STEMWizard/__init__.py | rtphokie/ncsef_automation | 730d16beb38640df579be742b2fcecc2f31e4190 | [
"Apache-2.0"
] | null | null | null | STEMWizard/__init__.py | rtphokie/ncsef_automation | 730d16beb38640df579be742b2fcecc2f31e4190 | [
"Apache-2.0"
] | null | null | null | from .__main__ import STEMWizardAPI | 35 | 35 | 0.885714 | 4 | 35 | 6.75 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.085714 | 35 | 1 | 35 | 35 | 0.84375 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
c5153f407162751d0b60bcbcfd60b4e7ff700fe6 | 194 | py | Python | brownant/__init__.py | douban/brownant | 3c7e6d30f67b8f0f8ca1f823ea3daed74e8725cd | [
"BSD-3-Clause"
] | 88 | 2015-01-06T08:56:53.000Z | 2022-01-06T08:20:05.000Z | brownant/__init__.py | douban/brownant | 3c7e6d30f67b8f0f8ca1f823ea3daed74e8725cd | [
"BSD-3-Clause"
] | 3 | 2015-07-07T06:24:23.000Z | 2017-03-03T13:13:36.000Z | brownant/__init__.py | douban/brownant | 3c7e6d30f67b8f0f8ca1f823ea3daed74e8725cd | [
"BSD-3-Clause"
] | 34 | 2015-01-20T00:45:08.000Z | 2020-05-11T13:23:55.000Z | from .app import Brownant, BrownAnt, redirect
from .dinergate import Dinergate
from .site import Site
__version__ = "0.1.7"
__all__ = ["Brownant", "BrownAnt", "redirect", "Dinergate", "Site"]
| 24.25 | 67 | 0.726804 | 24 | 194 | 5.541667 | 0.5 | 0.240602 | 0.360902 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.017857 | 0.134021 | 194 | 7 | 68 | 27.714286 | 0.77381 | 0 | 0 | 0 | 0 | 0 | 0.216495 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.6 | 0 | 0.6 | 0 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
c519a841eca9f30c5c0eb37e31f4b1ee3d535c2e | 27,497 | py | Python | pcdet/models/rcnn/partA2_rcnn_net.py | charlesyz/PCDet | 1eb6b1dc5a3d563d7532b1c8ee3be007cbeafc80 | [
"Apache-2.0"
] | null | null | null | pcdet/models/rcnn/partA2_rcnn_net.py | charlesyz/PCDet | 1eb6b1dc5a3d563d7532b1c8ee3be007cbeafc80 | [
"Apache-2.0"
] | null | null | null | pcdet/models/rcnn/partA2_rcnn_net.py | charlesyz/PCDet | 1eb6b1dc5a3d563d7532b1c8ee3be007cbeafc80 | [
"Apache-2.0"
] | null | null | null | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import spconv
from ..model_utils import pytorch_utils as pt_utils
from ...config import cfg
from ..model_utils.proposal_target_layer import proposal_target_layer
from ...ops.roiaware_pool3d import roiaware_pool3d_utils
from ...utils import common_utils, loss_utils, box_coder_utils
class RCNNHead(nn.Module):
def __init__(self, rcnn_target_config):
super().__init__()
self.forward_ret_dict = None
self.rcnn_target_config = rcnn_target_config
self.box_coder = getattr(box_coder_utils, rcnn_target_config.BOX_CODER)()
losses_cfg = cfg.MODEL.LOSSES
code_weights = losses_cfg.LOSS_WEIGHTS['code_weights']
self.reg_loss_func = loss_utils.WeightedSmoothL1LocalizationLoss(sigma=3.0, code_weights=code_weights)
def assign_targets(self, batch_size, rcnn_dict):
with torch.no_grad():
targets_dict = proposal_target_layer(rcnn_dict, roi_sampler_cfg=self.rcnn_target_config)
rois = targets_dict['rois'] # (B, N, 7 + ?)
gt_of_rois = targets_dict['gt_of_rois'] # (B, N, 7 + ? + 1)
targets_dict['gt_of_rois_src'] = gt_of_rois.clone().detach()
# canonical transformation
roi_center = rois[:, :, 0:3]
roi_ry = rois[:, :, 6] % (2 * np.pi)
gt_of_rois[:, :, 0:3] = gt_of_rois[:, :, 0:3] - roi_center
gt_of_rois[:, :, 6] = gt_of_rois[:, :, 6] - roi_ry
for k in range(batch_size):
# transfer LiDAR coords to local coords
gt_of_rois[k] = common_utils.rotate_pc_along_z_torch(
gt_of_rois[k].unsqueeze(dim=1), -(roi_ry[k] + np.pi / 2)
).squeeze(dim=1)
# flip orientation if rois have opposite orientation
ry_label = gt_of_rois[:, :, 6] % (2 * np.pi) # 0 ~ 2pi
opposite_flag = (ry_label > np.pi * 0.5) & (ry_label < np.pi * 1.5)
ry_label[opposite_flag] = (ry_label[opposite_flag] + np.pi) % (2 * np.pi) # (0 ~ pi/2, 3pi/2 ~ 2pi)
flag = ry_label > np.pi
ry_label[flag] = ry_label[flag] - np.pi * 2 # (-pi/2, pi/2)
ry_label = torch.clamp(ry_label, min=-np.pi / 2, max=np.pi / 2)
gt_of_rois[:, :, 6] = ry_label
targets_dict['gt_of_rois'] = gt_of_rois
return targets_dict
def get_loss(self, forward_ret_dict=None):
loss_cfgs = cfg.MODEL.LOSSES
LOSS_WEIGHTS = loss_cfgs.LOSS_WEIGHTS
forward_ret_dict = self.forward_ret_dict if forward_ret_dict is None else forward_ret_dict
code_size = self.box_coder.code_size
rcnn_cls = forward_ret_dict['rcnn_cls']
rcnn_cls_labels = forward_ret_dict['rcnn_cls_labels'].float().view(-1)
reg_valid_mask = forward_ret_dict['reg_valid_mask']
gt_boxes3d_ct = forward_ret_dict['gt_of_rois'][..., 0:code_size]
gt_of_rois_src = forward_ret_dict['gt_of_rois_src'][..., 0:code_size].view(-1, code_size)
rcnn_reg = forward_ret_dict['rcnn_reg']
roi_boxes3d = forward_ret_dict['rois']
rcnn_batch_size = rcnn_cls_labels.shape[0]
rcnn_loss = 0
if loss_cfgs.RCNN_CLS_LOSS == 'BinaryCrossEntropy':
rcnn_cls_flat = rcnn_cls.view(-1)
batch_loss_cls = F.binary_cross_entropy(torch.sigmoid(rcnn_cls_flat), rcnn_cls_labels, reduction='none')
cls_valid_mask = (rcnn_cls_labels >= 0).float()
rcnn_loss_cls = (batch_loss_cls * cls_valid_mask).sum() / torch.clamp(cls_valid_mask.sum(), min=1.0)
rcnn_loss_cls = rcnn_loss_cls * LOSS_WEIGHTS['rcnn_cls_weight']
else:
raise NotImplementedError
rcnn_loss += rcnn_loss_cls
tb_dict = {'rcnn_loss_cls': rcnn_loss_cls.item()}
fg_mask = (reg_valid_mask > 0)
fg_sum = fg_mask.long().sum().item()
if fg_sum == 0:
# To be consistent with DistributedDataParallel
# Faked a rcnn_loss to make gradient of regression branch be zero
temp_rcnn_reg = rcnn_reg.view(rcnn_batch_size, -1)[0].unsqueeze(dim=0)
faked_reg_target = temp_rcnn_reg.detach()
rcnn_loss_reg = self.reg_loss_func(temp_rcnn_reg, faked_reg_target) # [N, M]
rcnn_loss_reg = rcnn_loss_reg.sum() / 1.0
tb_dict['rcnn_loss_reg'] = rcnn_loss_reg.item()
else:
fg_rcnn_reg = rcnn_reg.view(rcnn_batch_size, -1)[fg_mask]
fg_roi_boxes3d = roi_boxes3d.view(-1, code_size)[fg_mask]
if loss_cfgs.RCNN_REG_LOSS == 'smooth-l1':
rois_anchor = roi_boxes3d.clone().detach().view(-1, code_size)
rois_anchor[:, 0:3] = 0
rois_anchor[:, 6] = 0
reg_targets = self.box_coder.encode_torch(
gt_boxes3d_ct.view(rcnn_batch_size, code_size)[fg_mask], rois_anchor[fg_mask]
)
rcnn_loss_reg = self.reg_loss_func(
rcnn_reg.view(rcnn_batch_size, -1)[fg_mask].unsqueeze(dim=0),
reg_targets.unsqueeze(dim=0)
) # [N, M]
rcnn_loss_reg = rcnn_loss_reg.sum() / max(fg_sum, 0)
rcnn_loss_reg = rcnn_loss_reg * LOSS_WEIGHTS['rcnn_reg_weight']
tb_dict['rcnn_loss_reg'] = rcnn_loss_reg.item()
if loss_cfgs.CORNER_LOSS_REGULARIZATION:
# TODO: NEED to BE CHECK
fg_roi_boxes3d = fg_roi_boxes3d.view(1, -1, code_size)
batch_anchors = fg_roi_boxes3d.clone().detach()
roi_ry = fg_roi_boxes3d[:, :, 6].view(-1)
roi_xyz = fg_roi_boxes3d[:, :, 0:3].view(-1, 3)
batch_anchors[:, :, 0:3] = 0
rcnn_boxes3d = self.box_coder.decode_torch(
fg_rcnn_reg.view(batch_anchors.shape[0], -1, code_size), batch_anchors
).view(-1, code_size)
rcnn_boxes3d = common_utils.rotate_pc_along_z_torch(
rcnn_boxes3d.unsqueeze(dim=1), (roi_ry + np.pi / 2)
).squeeze(dim=1)
rcnn_boxes3d[:, 0:3] += roi_xyz
loss_corner = loss_utils.get_corner_loss_lidar(
rcnn_boxes3d[:, 0:-1],
gt_of_rois_src[fg_mask][:, 0:-1]
)
loss_corner = loss_corner.mean()
loss_corner = loss_corner * LOSS_WEIGHTS['rcnn_corner_weight']
rcnn_loss_reg += loss_corner
tb_dict['rcnn_loss_corner'] = loss_corner
else:
raise NotImplementedError
rcnn_loss += rcnn_loss_reg
tb_dict['rcnn_loss'] = rcnn_loss.item()
return rcnn_loss, tb_dict
class SpConvRCNN(RCNNHead):
def __init__(self, num_point_features, rcnn_cfg, **kwargs):
super().__init__(rcnn_target_config=cfg.MODEL.RCNN.TARGET_CONFIG)
self.SA_modules = nn.ModuleList()
block = self.post_act_block
self.conv_part = spconv.SparseSequential(
block(4, 64, 3, padding=1, indice_key='rcnn_subm1'),
block(64, 64, 3, padding=1, indice_key='rcnn_subm1_1'),
)
self.conv_rpn = spconv.SparseSequential(
block(num_point_features, 64, 3, padding=1, indice_key='rcnn_subm2'),
block(64, 64, 3, padding=1, indice_key='rcnn_subm1_2'),
)
self.conv_down = spconv.SparseSequential(
# [14, 14, 14] -> [7, 7, 7]
block(128, 128, 3, padding=1, indice_key='rcnn_subm2'),
block(128, 128, 3, padding=1, indice_key='rcnn_subm2'),
spconv.SparseMaxPool3d(kernel_size=2, stride=2),
block(128, 128, 3, padding=1, indice_key='rcnn_subm3'),
block(128, rcnn_cfg.SHARED_FC[0], 3, padding=1, indice_key='rcnn_subm3'),
)
shared_fc_list = []
pool_size = rcnn_cfg.ROI_AWARE_POOL_SIZE // 2
pre_channel = rcnn_cfg.SHARED_FC[0] * pool_size * pool_size * pool_size
for k in range(1, rcnn_cfg.SHARED_FC.__len__()):
shared_fc_list.append(pt_utils.Conv1d(pre_channel, rcnn_cfg.SHARED_FC[k], bn=True))
pre_channel = rcnn_cfg.SHARED_FC[k]
if k != rcnn_cfg.SHARED_FC.__len__() - 1 and rcnn_cfg.DP_RATIO > 0:
shared_fc_list.append(nn.Dropout(rcnn_cfg.DP_RATIO))
self.shared_fc_layer = nn.Sequential(*shared_fc_list)
channel_in = rcnn_cfg.SHARED_FC[-1]
# Classification layer
cls_channel = 1
cls_layers = []
pre_channel = channel_in
for k in range(0, rcnn_cfg.CLS_FC.__len__()):
cls_layers.append(pt_utils.Conv1d(pre_channel, rcnn_cfg.CLS_FC[k], bn=True))
pre_channel = rcnn_cfg.CLS_FC[k]
cls_layers.append(pt_utils.Conv1d(pre_channel, cls_channel, activation=None))
if rcnn_cfg.DP_RATIO >= 0:
cls_layers.insert(1, nn.Dropout(rcnn_cfg.DP_RATIO))
self.cls_layer = nn.Sequential(*cls_layers)
# Regression layer
reg_layers = []
pre_channel = channel_in
for k in range(0, rcnn_cfg.REG_FC.__len__()):
reg_layers.append(pt_utils.Conv1d(pre_channel, rcnn_cfg.REG_FC[k], bn=True))
pre_channel = rcnn_cfg.REG_FC[k]
reg_layers.append(pt_utils.Conv1d(pre_channel, self.box_coder.code_size, activation=None))
if rcnn_cfg.DP_RATIO >= 0:
reg_layers.insert(1, nn.Dropout(rcnn_cfg.DP_RATIO))
self.reg_layer = nn.Sequential(*reg_layers)
self.roiaware_pool3d_layer = roiaware_pool3d_utils.RoIAwarePool3d(
out_size=rcnn_cfg.ROI_AWARE_POOL_SIZE, max_pts_each_voxel=128
)
self.init_weights(weight_init='xavier')
def init_weights(self, weight_init='xavier'):
if weight_init == 'kaiming':
init_func = nn.init.kaiming_normal_
elif weight_init == 'xavier':
init_func = nn.init.xavier_normal_
elif weight_init == 'normal':
init_func = nn.init.normal_
else:
raise NotImplementedError
for m in self.modules():
if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d):
if weight_init == 'normal':
init_func(m.weight, mean=0, std=0.001)
else:
init_func(m.weight)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
nn.init.normal_(self.reg_layer[-1].conv.weight, mean=0, std=0.001)
def post_act_block(self, in_channels, out_channels, kernel_size, indice_key, stride=1, padding=0, conv_type='subm'):
if conv_type == 'subm':
m = spconv.SparseSequential(
spconv.SubMConv3d(in_channels, out_channels, kernel_size, bias=False, indice_key=indice_key),
nn.BatchNorm1d(out_channels, eps=1e-3, momentum=0.01),
nn.ReLU(),
)
elif conv_type == 'spconv':
m = spconv.SparseSequential(
spconv.SparseConv3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding,
bias=False, indice_key=indice_key),
nn.BatchNorm1d(out_channels, eps=1e-3, momentum=0.01),
nn.ReLU(),
)
elif conv_type == 'inverseconv':
m = spconv.SparseSequential(
spconv.SparseInverseConv3d(in_channels, out_channels, kernel_size,
indice_key=indice_key, bias=False),
nn.BatchNorm1d(out_channels, eps=1e-3, momentum=0.01),
nn.ReLU(),
)
else:
raise NotImplementedError
return m
def roiaware_pool(self, batch_rois, rcnn_dict):
"""
:param batch_rois: (B, N, 7 + ?) [x, y, z, w, l, h, rz] in LiDAR coords
:param rcnn_dict:
:return:
"""
voxel_centers = rcnn_dict['voxel_centers'] # (npoints, 3)
rpn_features = rcnn_dict['rpn_seg_features'] # (npoints, C)
coords = rcnn_dict['coordinates'] # (npoints, 4)
rpn_seg_score = rcnn_dict['rpn_seg_scores'].detach() # (npoints)
rpn_seg_mask = (rpn_seg_score > cfg.MODEL.RPN.BACKBONE.SEG_MASK_SCORE_THRESH)
rpn_part_offsets = rcnn_dict['rpn_part_offsets'].clone().detach()
rpn_part_offsets[rpn_seg_mask == 0] = 0
part_features = torch.cat((rpn_part_offsets, rpn_seg_score.view(-1, 1)), dim=1) # (npoints, 4)
batch_size = batch_rois.shape[0]
pooled_part_features_list, pooled_rpn_features_list = [], []
for bs_idx in range(batch_size):
bs_mask = (coords[:, 0] == bs_idx)
cur_voxel_centers = voxel_centers[bs_mask]
cur_part_features = part_features[bs_mask]
cur_rpn_features = rpn_features[bs_mask]
cur_roi = batch_rois[bs_idx][:, 0:-1].contiguous() # (N, 7)
pooled_part_features = self.roiaware_pool3d_layer.forward(
cur_roi, cur_voxel_centers, cur_part_features, pool_method='avg'
) # (N, out_x, out_y, out_z, 4)
pooled_rpn_features = self.roiaware_pool3d_layer.forward(
cur_roi, cur_voxel_centers, cur_rpn_features, pool_method='max'
) # (N, out_x, out_y, out_z, C)
pooled_part_features_list.append(pooled_part_features)
pooled_rpn_features_list.append(pooled_rpn_features)
pooled_part_features = torch.cat(pooled_part_features_list, dim=0) # (B * N, out_x, out_y, out_z, 4)
pooled_rpn_features = torch.cat(pooled_rpn_features_list, dim=0) # (B * N, out_x, out_y, out_z, C)
return pooled_part_features, pooled_rpn_features
def _break_up_pc(self, pc):
xyz = pc[..., 0:3].contiguous()
features = (
pc[..., 3:].transpose(1, 2).contiguous()
if pc.size(-1) > 3 else None
)
return xyz, features
def fake_sparse_idx(self, sparse_idx, batch_size_rcnn):
print('Warning: GPU_%d: Sparse_Idx_Shape(%s) \r' % (cfg.LOCAL_RANK, str(sparse_idx.shape)), end='', flush=True)
# at most one sample is non-empty, then fake the first voxels of each sample(BN needs at least
# two values each channel) as non-empty for the below calculation
sparse_idx = sparse_idx.new_zeros((batch_size_rcnn, 3))
bs_idxs = torch.arange(batch_size_rcnn).type_as(sparse_idx).view(-1, 1)
sparse_idx = torch.cat((bs_idxs, sparse_idx), dim=1)
return sparse_idx
def forward(self, rcnn_dict):
"""
:param input_data: input dict
:return:
"""
rois = rcnn_dict['rois']
batch_size = rois.shape[0]
if self.training:
targets_dict = self.assign_targets(batch_size, rcnn_dict)
rois = targets_dict['rois'] # (B, N, 7)
rcnn_dict['roi_raw_scores'] = targets_dict['roi_raw_scores']
rcnn_dict['roi_labels'] = targets_dict['roi_labels']
# RoI aware pooling
pooled_part_features, pooled_rpn_features = self.roiaware_pool(rois, rcnn_dict)
batch_size_rcnn = pooled_part_features.shape[0] # (B * N, out_x, out_y, out_z, 4)
# transform to sparse tensors
sparse_shape = np.array(pooled_part_features.shape[1:4], dtype=np.int32)
sparse_idx = pooled_part_features.sum(dim=-1).nonzero() # (non_empty_num, 4) ==> [bs_idx, x_idx, y_idx, z_idx]
if sparse_idx.shape[0] < 3:
sparse_idx = self.fake_sparse_idx(sparse_idx, batch_size_rcnn)
if self.training:
# these are invalid samples
targets_dict['rcnn_cls_labels'].fill_(-1)
targets_dict['reg_valid_mask'].fill_(-1)
part_features = pooled_part_features[sparse_idx[:, 0], sparse_idx[:, 1], sparse_idx[:, 2], sparse_idx[:, 3]]
rpn_features = pooled_rpn_features[sparse_idx[:, 0], sparse_idx[:, 1], sparse_idx[:, 2], sparse_idx[:, 3]]
coords = sparse_idx.int()
part_features = spconv.SparseConvTensor(part_features, coords, sparse_shape, batch_size_rcnn)
rpn_features = spconv.SparseConvTensor(rpn_features, coords, sparse_shape, batch_size_rcnn)
# forward rcnn network
x_part = self.conv_part(part_features)
x_rpn = self.conv_rpn(rpn_features)
merged_feature = torch.cat((x_rpn.features, x_part.features), dim=1) # (N, C)
shared_feature = spconv.SparseConvTensor(merged_feature, coords, sparse_shape, batch_size_rcnn)
x = self.conv_down(shared_feature) #
shared_feature = x.dense().view(batch_size_rcnn, -1, 1)
shared_feature = self.shared_fc_layer(shared_feature)
rcnn_cls = self.cls_layer(shared_feature).transpose(1, 2).contiguous().squeeze(dim=1) # (B, 1 or 2)
rcnn_reg = self.reg_layer(shared_feature).transpose(1, 2).contiguous().squeeze(dim=1) # (B, C)
ret_dict = {
'rcnn_cls': rcnn_cls,
'rcnn_reg': rcnn_reg,
'rois': rois,
'roi_raw_scores': rcnn_dict['roi_raw_scores'],
'roi_labels': rcnn_dict['roi_labels']
}
if self.training:
ret_dict.update(targets_dict)
self.forward_ret_dict = ret_dict
return ret_dict
class FCRCNN(RCNNHead):
def __init__(self, num_point_features, rcnn_cfg, **kwargs):
super().__init__(rcnn_target_config=cfg.MODEL.RCNN.TARGET_CONFIG)
self.SA_modules = nn.ModuleList()
block = self.post_act_block
c0 = rcnn_cfg.SHARED_FC[0] // 2
self.conv_part = spconv.SparseSequential(
block(4, 64, 3, padding=1, indice_key='rcnn_subm1'),
block(64, c0, 3, padding=1, indice_key='rcnn_subm1_1'),
)
self.conv_rpn = spconv.SparseSequential(
block(num_point_features, 64, 3, padding=1, indice_key='rcnn_subm2'),
block(64, c0, 3, padding=1, indice_key='rcnn_subm1_2'),
)
shared_fc_list = []
pool_size = rcnn_cfg.ROI_AWARE_POOL_SIZE
pre_channel = rcnn_cfg.SHARED_FC[0] * pool_size * pool_size * pool_size
for k in range(1, rcnn_cfg.SHARED_FC.__len__()):
shared_fc_list.append(pt_utils.Conv1d(pre_channel, rcnn_cfg.SHARED_FC[k], bn=True))
pre_channel = rcnn_cfg.SHARED_FC[k]
if k != rcnn_cfg.SHARED_FC.__len__() - 1 and rcnn_cfg.DP_RATIO > 0:
shared_fc_list.append(nn.Dropout(rcnn_cfg.DP_RATIO))
self.shared_fc_layer = nn.Sequential(*shared_fc_list)
channel_in = rcnn_cfg.SHARED_FC[-1]
# Classification layer
cls_channel = 1
cls_layers = []
pre_channel = channel_in
for k in range(0, rcnn_cfg.CLS_FC.__len__()):
cls_layers.append(pt_utils.Conv1d(pre_channel, rcnn_cfg.CLS_FC[k], bn=True))
pre_channel = rcnn_cfg.CLS_FC[k]
cls_layers.append(pt_utils.Conv1d(pre_channel, cls_channel, activation=None))
if rcnn_cfg.DP_RATIO >= 0:
cls_layers.insert(1, nn.Dropout(rcnn_cfg.DP_RATIO))
self.cls_layer = nn.Sequential(*cls_layers)
# Regression layer
reg_layers = []
pre_channel = channel_in
for k in range(0, rcnn_cfg.REG_FC.__len__()):
reg_layers.append(pt_utils.Conv1d(pre_channel, rcnn_cfg.REG_FC[k], bn=True))
pre_channel = rcnn_cfg.REG_FC[k]
reg_layers.append(pt_utils.Conv1d(pre_channel, self.box_coder.code_size, activation=None))
if rcnn_cfg.DP_RATIO >= 0:
reg_layers.insert(1, nn.Dropout(rcnn_cfg.DP_RATIO))
self.reg_layer = nn.Sequential(*reg_layers)
self.roiaware_pool3d_layer = roiaware_pool3d_utils.RoIAwarePool3d(
out_size=rcnn_cfg.ROI_AWARE_POOL_SIZE, max_pts_each_voxel=128
)
self.init_weights(weight_init='xavier')
def init_weights(self, weight_init='xavier'):
if weight_init == 'kaiming':
init_func = nn.init.kaiming_normal_
elif weight_init == 'xavier':
init_func = nn.init.xavier_normal_
elif weight_init == 'normal':
init_func = nn.init.normal_
else:
raise NotImplementedError
for m in self.modules():
if isinstance(m, nn.Conv2d) or isinstance(m, nn.Conv1d):
if weight_init == 'normal':
init_func(m.weight, mean=0, std=0.001)
else:
init_func(m.weight)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
nn.init.normal_(self.reg_layer[-1].conv.weight, mean=0, std=0.001)
def post_act_block(self, in_channels, out_channels, kernel_size, indice_key, stride=1, padding=0, conv_type='subm'):
if conv_type == 'subm':
m = spconv.SparseSequential(
spconv.SubMConv3d(in_channels, out_channels, kernel_size, bias=False, indice_key=indice_key),
nn.BatchNorm1d(out_channels, eps=1e-3, momentum=0.01),
nn.ReLU(),
)
elif conv_type == 'spconv':
m = spconv.SparseSequential(
spconv.SparseConv3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding,
bias=False, indice_key=indice_key),
nn.BatchNorm1d(out_channels, eps=1e-3, momentum=0.01),
nn.ReLU(),
)
elif conv_type == 'inverseconv':
m = spconv.SparseSequential(
spconv.SparseInverseConv3d(in_channels, out_channels, kernel_size,
indice_key=indice_key, bias=False),
nn.BatchNorm1d(out_channels, eps=1e-3, momentum=0.01),
nn.ReLU(),
)
else:
raise NotImplementedError
return m
def roiaware_pool(self, batch_rois, rcnn_dict):
"""
:param batch_rois: (B, N, 7 + ?) [x, y, z, w, l, h, rz] in LiDAR coords
:param rcnn_dict:
:return:
"""
voxel_centers = rcnn_dict['voxel_centers'] # (npoints, 3)
rpn_features = rcnn_dict['rpn_seg_features'] # (npoints, C)
coords = rcnn_dict['coordinates'] # (npoints, 4)
rpn_seg_score = rcnn_dict['rpn_seg_scores'].detach() # (npoints)
rpn_seg_mask = (rpn_seg_score > cfg.MODEL.RPN.BACKBONE.SEG_MASK_SCORE_THRESH)
rpn_part_offsets = rcnn_dict['rpn_part_offsets'].clone().detach()
rpn_part_offsets[rpn_seg_mask == 0] = 0
part_features = torch.cat((rpn_part_offsets, rpn_seg_score.view(-1, 1)), dim=1) # (npoints, 4)
batch_size = batch_rois.shape[0]
pooled_part_features_list, pooled_rpn_features_list = [], []
for bs_idx in range(batch_size):
bs_mask = (coords[:, 0] == bs_idx)
cur_voxel_centers = voxel_centers[bs_mask]
cur_part_features = part_features[bs_mask]
cur_rpn_features = rpn_features[bs_mask]
cur_roi = batch_rois[bs_idx][:, 0:-1].contiguous() # (N, 7)
pooled_part_features = self.roiaware_pool3d_layer.forward(
cur_roi, cur_voxel_centers, cur_part_features, pool_method='avg'
) # (N, out_x, out_y, out_z, 4)
pooled_rpn_features = self.roiaware_pool3d_layer.forward(
cur_roi, cur_voxel_centers, cur_rpn_features, pool_method='max'
) # (N, out_x, out_y, out_z, C)
pooled_part_features_list.append(pooled_part_features)
pooled_rpn_features_list.append(pooled_rpn_features)
pooled_part_features = torch.cat(pooled_part_features_list, dim=0) # (B * N, out_x, out_y, out_z, 4)
pooled_rpn_features = torch.cat(pooled_rpn_features_list, dim=0) # (B * N, out_x, out_y, out_z, C)
return pooled_part_features, pooled_rpn_features
def _break_up_pc(self, pc):
xyz = pc[..., 0:3].contiguous()
features = (
pc[..., 3:].transpose(1, 2).contiguous()
if pc.size(-1) > 3 else None
)
return xyz, features
def fake_sparse_idx(self, sparse_idx, batch_size_rcnn):
print('Warning: GPU_%d: Sparse_Idx_Shape(%s) \r' % (cfg.LOCAL_RANK, str(sparse_idx.shape)), end='', flush=True)
# at most one sample is non-empty, then fake the first voxels of each sample(BN needs at least
# two values each channel) as non-empty for the below calculation
sparse_idx = sparse_idx.new_zeros((batch_size_rcnn, 3))
bs_idxs = torch.arange(batch_size_rcnn).type_as(sparse_idx).view(-1, 1)
sparse_idx = torch.cat((bs_idxs, sparse_idx), dim=1)
return sparse_idx
def forward(self, rcnn_dict):
"""
:param input_data: input dict
:return:
"""
rois = rcnn_dict['rois']
batch_size = rois.shape[0]
if self.training:
targets_dict = self.assign_targets(batch_size, rcnn_dict)
rois = targets_dict['rois'] # (B, N, 7)
rcnn_dict['roi_raw_scores'] = targets_dict['roi_raw_scores']
rcnn_dict['roi_labels'] = targets_dict['roi_labels']
# RoI aware pooling
pooled_part_features, pooled_rpn_features = self.roiaware_pool(rois, rcnn_dict)
batch_size_rcnn = pooled_part_features.shape[0] # (B * N, out_x, out_y, out_z, 4)
# transform to sparse tensors
sparse_shape = np.array(pooled_part_features.shape[1:4], dtype=np.int32)
sparse_idx = pooled_part_features.sum(dim=-1).nonzero() # (non_empty_num, 4) ==> [bs_idx, x_idx, y_idx, z_idx]
if sparse_idx.shape[0] < 3:
sparse_idx = self.fake_sparse_idx(sparse_idx, batch_size_rcnn)
if self.training:
# these are invalid samples
targets_dict['rcnn_cls_labels'].fill_(-1)
targets_dict['reg_valid_mask'].fill_(-1)
part_features = pooled_part_features[sparse_idx[:, 0], sparse_idx[:, 1], sparse_idx[:, 2], sparse_idx[:, 3]]
rpn_features = pooled_rpn_features[sparse_idx[:, 0], sparse_idx[:, 1], sparse_idx[:, 2], sparse_idx[:, 3]]
coords = sparse_idx.int()
part_features = spconv.SparseConvTensor(part_features, coords, sparse_shape, batch_size_rcnn)
rpn_features = spconv.SparseConvTensor(rpn_features, coords, sparse_shape, batch_size_rcnn)
# forward rcnn network
x_part = self.conv_part(part_features)
x_rpn = self.conv_rpn(rpn_features)
merged_feature = torch.cat((x_rpn.features, x_part.features), dim=1) # (N, C)
shared_feature = spconv.SparseConvTensor(merged_feature, coords, sparse_shape, batch_size_rcnn)
shared_feature = shared_feature.dense().view(batch_size_rcnn, -1, 1)
shared_feature = self.shared_fc_layer(shared_feature)
rcnn_cls = self.cls_layer(shared_feature).transpose(1, 2).contiguous().squeeze(dim=1) # (B, 1 or 2)
rcnn_reg = self.reg_layer(shared_feature).transpose(1, 2).contiguous().squeeze(dim=1) # (B, C)
ret_dict = {
'rcnn_cls': rcnn_cls,
'rcnn_reg': rcnn_reg,
'rois': rois,
'roi_raw_scores': rcnn_dict['roi_raw_scores'],
'roi_labels': rcnn_dict['roi_labels']
}
if self.training:
ret_dict.update(targets_dict)
self.forward_ret_dict = ret_dict
return ret_dict
| 45.981605 | 120 | 0.617049 | 3,764 | 27,497 | 4.149309 | 0.085813 | 0.02766 | 0.02766 | 0.013446 | 0.812652 | 0.785312 | 0.774875 | 0.758612 | 0.758484 | 0.742349 | 0 | 0.022932 | 0.270502 | 27,497 | 597 | 121 | 46.058626 | 0.755671 | 0.066807 | 0 | 0.690987 | 0 | 0 | 0.041482 | 0 | 0 | 0 | 0 | 0.001675 | 0 | 1 | 0.036481 | false | 0 | 0.021459 | 0 | 0.090129 | 0.004292 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
c546822d68bd30343d24b9e0494c9af6c679b1ab | 1,130 | py | Python | addons/Sprytile-6b68d00/rx/concurrency/__init__.py | trisadmeslek/V-Sekai-Blender-tools | 0d8747387c58584b50c69c61ba50a881319114f8 | [
"MIT"
] | 733 | 2017-08-22T09:47:54.000Z | 2022-03-27T23:56:52.000Z | rx/concurrency/__init__.py | asheraryam/Sprytile | c63be50d14b07192ff134ceab256f0d69b9c4c92 | [
"MIT"
] | 74 | 2017-08-16T09:13:05.000Z | 2022-03-15T02:31:49.000Z | rx/concurrency/__init__.py | asheraryam/Sprytile | c63be50d14b07192ff134ceab256f0d69b9c4c92 | [
"MIT"
] | 77 | 2017-09-14T16:56:11.000Z | 2022-03-27T13:55:16.000Z | from .scheduleditem import ScheduledItem
from .immediatescheduler import ImmediateScheduler, immediate_scheduler
from .currentthreadscheduler import CurrentThreadScheduler, \
current_thread_scheduler
from .virtualtimescheduler import VirtualTimeScheduler
from .timeoutscheduler import TimeoutScheduler, timeout_scheduler
from .newthreadscheduler import NewThreadScheduler, new_thread_scheduler
try:
from .threadpoolscheduler import ThreadPoolScheduler, thread_pool_scheduler
except ImportError:
pass
from .eventloopscheduler import EventLoopScheduler
from .historicalscheduler import HistoricalScheduler
from .catchscheduler import CatchScheduler
from .mainloopscheduler import AsyncIOScheduler
from .mainloopscheduler import IOLoopScheduler
from .mainloopscheduler import GEventScheduler
from .mainloopscheduler import GtkScheduler
from .mainloopscheduler import TwistedScheduler
from .mainloopscheduler import TkinterScheduler
from .mainloopscheduler import PyGameScheduler
from .mainloopscheduler import QtScheduler
from .mainloopscheduler import WxScheduler
from .mainloopscheduler import EventLetEventScheduler
| 41.851852 | 79 | 0.883186 | 97 | 1,130 | 10.206186 | 0.350515 | 0.212121 | 0.272727 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.092035 | 1,130 | 26 | 80 | 43.461538 | 0.964912 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.041667 | 0.875 | 0 | 0.875 | 0 | 0 | 0 | 1 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
c555a428f5636d90502ac178f82e27358a760f97 | 274 | py | Python | pyacc/lexer/exceptions.py | hdyuik/pyacc | 85f6206388ce29a95e39b659257d45be9df250e5 | [
"MIT"
] | 2 | 2019-06-21T23:45:09.000Z | 2019-06-23T23:37:50.000Z | pyacc/lexer/exceptions.py | hdyuik/compiler | 85f6206388ce29a95e39b659257d45be9df250e5 | [
"MIT"
] | null | null | null | pyacc/lexer/exceptions.py | hdyuik/compiler | 85f6206388ce29a95e39b659257d45be9df250e5 | [
"MIT"
] | null | null | null | class RESyntaxError(BaseException):
def __init__(self, pos, msg):
super(RESyntaxError, self).__init__(pos, msg)
class RecognizeError(BaseException):
def __init__(self, recognizer, msg):
super(RecognizeError, self).__init__(recognizer, msg)
| 30.444444 | 62 | 0.70073 | 28 | 274 | 6.285714 | 0.392857 | 0.181818 | 0.227273 | 0.272727 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.189781 | 274 | 8 | 63 | 34.25 | 0.792793 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | false | 0 | 0 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 6 |
c55c081275eac1c2807dc370f220b3699d969b8a | 4,663 | py | Python | discovery-provider/alembic/versions/98e2a0a25ada_drop_aggregate_interval_plays_year_count.py | lucylow/audius-protocol | 5ef93462f9dc7df01a15877c02ca79b9a7d99236 | [
"Apache-2.0"
] | 1 | 2022-03-27T21:40:36.000Z | 2022-03-27T21:40:36.000Z | discovery-provider/alembic/versions/98e2a0a25ada_drop_aggregate_interval_plays_year_count.py | abelxmendoza/audius-protocol | 33757e1b722a4be97960086b98b26ae3a75ee56b | [
"Apache-2.0"
] | null | null | null | discovery-provider/alembic/versions/98e2a0a25ada_drop_aggregate_interval_plays_year_count.py | abelxmendoza/audius-protocol | 33757e1b722a4be97960086b98b26ae3a75ee56b | [
"Apache-2.0"
] | null | null | null | """drop aggregate_interval_plays year count
Revision ID: 98e2a0a25ada
Revises: dc7f691adc79
Create Date: 2022-01-20 20:32:50.898715
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "98e2a0a25ada"
down_revision = "dc7f691adc79"
branch_labels = None
depends_on = None
def upgrade():
connection = op.get_bind()
connection.execute(
"""
DROP MATERIALIZED VIEW IF EXISTS aggregate_interval_plays;
-- same query as 92571f94989a but without year count
CREATE MATERIALIZED VIEW IF NOT EXISTS aggregate_interval_plays as
SELECT
tracks.track_id as track_id,
tracks.genre as genre,
tracks.created_at as created_at,
COALESCE (week_listen_counts.count, 0) as week_listen_counts,
COALESCE (month_listen_counts.count, 0) as month_listen_counts
FROM
tracks
LEFT OUTER JOIN (
SELECT
plays.play_item_id as play_item_id,
count(plays.id) as count
FROM
plays
WHERE
plays.created_at > (now() - interval '1 week')
GROUP BY plays.play_item_id
) as week_listen_counts ON week_listen_counts.play_item_id = tracks.track_id
LEFT OUTER JOIN (
SELECT
plays.play_item_id as play_item_id,
count(plays.id) as count
FROM
plays
WHERE
plays.created_at > (now() - interval '1 month')
GROUP BY plays.play_item_id
) as month_listen_counts ON month_listen_counts.play_item_id = tracks.track_id
WHERE
tracks.is_current is True AND
tracks.is_delete is False AND
tracks.is_unlisted is False AND
tracks.stem_of is Null;
-- create primary key
CREATE INDEX IF NOT EXISTS interval_play_track_id_idx ON aggregate_interval_plays (track_id);
CREATE INDEX IF NOT EXISTS interval_play_week_count_idx ON aggregate_interval_plays (week_listen_counts);
CREATE INDEX IF NOT EXISTS interval_play_month_count_idx ON aggregate_interval_plays (month_listen_counts);
"""
)
def downgrade():
connection = op.get_bind()
connection.execute(
"""
DROP MATERIALIZED VIEW IF EXISTS aggregate_interval_plays;
CREATE MATERIALIZED VIEW IF NOT EXISTS aggregate_interval_plays as
SELECT
tracks.track_id as track_id,
tracks.genre as genre,
tracks.created_at as created_at,
COALESCE (week_listen_counts.count, 0) as week_listen_counts,
COALESCE (month_listen_counts.count, 0) as month_listen_counts,
COALESCE (year_listen_counts.count, 0) as year_listen_counts
FROM
tracks
LEFT OUTER JOIN (
SELECT
plays.play_item_id as play_item_id,
count(plays.id) as count
FROM
plays
WHERE
plays.created_at > (now() - interval '1 week')
GROUP BY plays.play_item_id
) as week_listen_counts ON week_listen_counts.play_item_id = tracks.track_id
LEFT OUTER JOIN (
SELECT
plays.play_item_id as play_item_id,
count(plays.id) as count
FROM
plays
WHERE
plays.created_at > (now() - interval '1 month')
GROUP BY plays.play_item_id
) as month_listen_counts ON month_listen_counts.play_item_id = tracks.track_id
LEFT OUTER JOIN (
SELECT
plays.play_item_id as play_item_id,
count(plays.id) as count
FROM
plays
WHERE
plays.created_at > (now() - interval '1 year')
GROUP BY plays.play_item_id
) as year_listen_counts ON year_listen_counts.play_item_id = tracks.track_id
WHERE
tracks.is_current is True AND
tracks.is_delete is False AND
tracks.is_unlisted is False AND
tracks.stem_of is Null;
CREATE INDEX IF NOT EXISTS interval_play_track_id_idx ON aggregate_interval_plays (track_id);
CREATE INDEX IF NOT EXISTS interval_play_week_count_idx ON aggregate_interval_plays (week_listen_counts);
CREATE INDEX IF NOT EXISTS interval_play_month_count_idx ON aggregate_interval_plays (month_listen_counts);
CREATE INDEX IF NOT EXISTS interval_play_year_count_idx ON aggregate_interval_plays (year_listen_counts);
"""
)
| 37.007937 | 115 | 0.628994 | 595 | 4,663 | 4.635294 | 0.146218 | 0.108774 | 0.072516 | 0.054387 | 0.860044 | 0.852792 | 0.841189 | 0.832487 | 0.832487 | 0.82016 | 0 | 0.02024 | 0.321896 | 4,663 | 125 | 116 | 37.304 | 0.851992 | 0.036243 | 0 | 0.285714 | 0 | 0 | 0.074534 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.142857 | false | 0 | 0.142857 | 0 | 0.285714 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
3d94233ad62feabf823c8e5043844fc7d101845b | 89,751 | py | Python | src/ibm_qiskit/cryptography/semi_quantum_conference_key_agreement/entities/QiskitSQCKAProtocolPartyEntity.py | rubenandrebarreiro/semi-quantum-conference-key-agreement-prototype | adefc5a43e4fb1c2b7926af5da93e346f96497c0 | [
"MIT"
] | null | null | null | src/ibm_qiskit/cryptography/semi_quantum_conference_key_agreement/entities/QiskitSQCKAProtocolPartyEntity.py | rubenandrebarreiro/semi-quantum-conference-key-agreement-prototype | adefc5a43e4fb1c2b7926af5da93e346f96497c0 | [
"MIT"
] | null | null | null | src/ibm_qiskit/cryptography/semi_quantum_conference_key_agreement/entities/QiskitSQCKAProtocolPartyEntity.py | rubenandrebarreiro/semi-quantum-conference-key-agreement-prototype | adefc5a43e4fb1c2b7926af5da93e346f96497c0 | [
"MIT"
] | null | null | null | """
Semi-Quantum Conference Key Agreement (SQCKA)
Author:
- Ruben Andre Barreiro (r.barreiro@campus.fct.unl.pt)
Supervisors:
- Andre Nuno Souto (ansouto@fc.ul.pt)
- Antonio Maria Ravara (aravara@fct.unl.pt)
Acknowledgments:
- Paulo Alexandre Mateus (pmat@math.ist.utl.pt)
"""
# Import Enumerations and Constants
from qiskit import Aer, execute
from src.common.enumerations.SemiQuantumCryptographyProtocolPartyEntityTypes \
import POSSIBLE_SEMI_QUANTUM_CRYPTOGRAPHY_PROTOCOL_PARTY_ENTITY_TYPES, \
QUANTUM_PARTY_ENTITY, SEMI_QUANTUM_PARTY_ENTITY
# Import the possible Bipartite and Multipartite Quantum Entanglement Types and
# the Possible Configurations for Bell States
from src.common.enumerations.QuantumEntanglementTypes \
import POSSIBLE_QUANTUM_ENTANGLEMENT_TYPES, POSSIBLE_CONFIGURATIONS_BELL_STATES, \
BELL_STATE, EPR_PAIR_STATE, BELL_STATE_PHI_PLUS, BELL_STATE_PHI_MINUS, BELL_STATE_PSI_PLUS, BELL_STATE_PSI_MINUS,\
GHZ_STATE, W_STATE, DICKE_STATE, RESOURCE_STATE, GRAPH_STATE, CLUSTER_STATE
# TODO
from src.common.enumerations.SemiQuantumCryptographyProtocolRoundTypes \
import SIFT_MEASURE_AND_RESEND_ROUND_BIT, CTRL_REFLECT_ROUND_BIT, \
SIFT_MEASURE_AND_RESEND_ROUND_3, CTRL_REFLECT_ROUND_3
# Import Packages and Libraries
# Import QiskitBellState from IBM_Qiskit.Entanglements.Bipartite
from src.ibm_qiskit.circuit import QiskitQuantumCircuit
from src.ibm_qiskit.circuit.registers.classical import QiskitClassicalRegister
from src.ibm_qiskit.circuit.registers.quantum import QiskitQuantumRegister
from src.ibm_qiskit.cryptography.semi_quantum_conference_key_agreement.common import QiskitSQCKAProtocolRound
from src.ibm_qiskit.entanglements.bipartite import QiskitBellState
# Import QiskitGHZState from IBM_Qiskit.Entanglements.Multipartite
from src.ibm_qiskit.entanglements.multipartite import QiskitGHZState
# Import QiskitWState from IBM_Qiskit.Entanglements.Multipartite
from src.ibm_qiskit.entanglements.multipartite import QiskitWState
# Import QiskitGraphState from IBM_Qiskit.Entanglements.Multipartite.Resource_States
from src.ibm_qiskit.entanglements.multipartite.resource_states import QiskitGraphState
# Constants
# The number of counts for simulation
NUM_COUNTS_FOR_SIMULATION = 1000
# Class of the IBM Qiskit's Party Entity for the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
class QiskitSQCKAProtocolPartyEntity:
# Constructor of the IBM Qiskit's Party Entity for the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
def __init__(self, party_entity_id, party_user_client, resources_context, distributor_status_flag, bipartite_pre_shared_keys):
# If the Resources' Context for the IBM Qiskit's Party Entity for
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol is valid
if resources_context.upper() in POSSIBLE_SEMI_QUANTUM_CRYPTOGRAPHY_PROTOCOL_PARTY_ENTITY_TYPES:
# Set the 1st possible validation condition for configuration of Resources' Context for
# the IBM Qiskit's Party Entity for the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
boolean_validation_1 = \
(distributor_status_flag and (resources_context.upper() == QUANTUM_PARTY_ENTITY))
# Set the 2nd possible validation condition for configuration of Resources' Context for
# the IBM Qiskit's Party Entity for the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
boolean_validation_2 = \
(not distributor_status_flag and (resources_context.upper() == SEMI_QUANTUM_PARTY_ENTITY))
# If the configuration of the Resources' Context for the IBM Qiskit's Party Entity for
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol is valid
if boolean_validation_1 or boolean_validation_2:
# Set the ID for the IBM Qiskit's Party Entity for
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
self.party_entity_id = party_entity_id
# Set the User/Client for the IBM Qiskit's Party Entity for
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
self.party_user_client = party_user_client
# Set the Resources' Context of the IBM Qiskit's Party Entity for
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
self.resources_context = resources_context.lower()
# Set the boolean flag, responsible to keep the information about if the Party Entity is
# the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol or not
self.distributor_status_flag = distributor_status_flag
# Set the Pre-Shared Key, previously established between the Party Entities
self.bipartite_pre_shared_keys = bipartite_pre_shared_keys
# If the configuration of the Resources' Context for
# the IBM Qiskit's Party Entity for the Semi-Quantum Conference Key Agreement (SQCKA) Protocol is not valid
else:
# If the Party Entity is set to be the Distributor of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
if distributor_status_flag:
# Raise a Runtime Error
raise RuntimeError("The Distributor the Semi-Quantum Conference Key Agreement (SQCKA) Protocol "
"should only have Quantum Resources!!!")
# If the Party Entity is not set to be the Distributor of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
else:
# Raise a Runtime Error
raise RuntimeError("A Receiver Party Entity of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol "
"should only have Semi-Quantum Resources!!!")
# If the Resources' Context for the IBM Qiskit's Party Entity for
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol is not valid
else:
# Raise a Runtime Error
raise RuntimeError("The Resources' Context for this Party Entity is not valid!!!")
# Return the ID for the IBM Qiskit's Party Entity for
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
def get_party_entity_id(self):
return self.party_entity_id
# Return the User/Client for the IBM Qiskit's Party Entity for
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
def get_party_user_client(self):
return self.party_user_client
# Return the Resources' Context of the IBM Qiskit's Party Entity for
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
def get_resources_context(self):
return self.resources_context
# Retrieve the boolean flag, responsible to keep the information about if the Party Entity is
# the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol or not
def is_distributor(self):
return self.distributor_status_flag
# Return the Bipartite Pre-Shared Keys that the Party Entity possesses with other Parties
def get_bipartite_pre_shared_keys(self):
return self.bipartite_pre_shared_keys
# Print the information about
# the IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol's Party Entity
def print_info(self):
# Some prints to draw a top left-side corner
print(" __")
print("|")
print("|")
# Print the ID of the User/Client of the Party Entity involved on the
# IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
print(" - Party Entity's ID: {}".format(self.party_entity_id))
# Print the UUID of the User/Client of the Party Entity involved on the
# IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
print(" - Party Entity's User/Client's UUID: {}".format(self.get_party_user_client().get_user_client_uuid()))
# Print the Name of the User/Client of the Party Entity involved on the
# IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
print(" - Party Entity's User/Client's Name: {}".format(self.get_party_user_client().get_user_client_name()))
# Print the Resources' Context of the IBM Qiskit's Party Entity for
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
print(" - Party Entity's Resources' Context: {}".format(self.get_resources_context()))
# Print the Distributor status of the Party Entity involved on the
# IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
print(" - Party Entity's Distributor Status: {}".format(self.is_distributor()))
# Retrieve the Bipartite Pre-Shared Keys owned/possessed by the Party involved on the
# IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
bipartite_pre_shared_keys = self.get_bipartite_pre_shared_keys()
# If the Party Entity is the Distributor of
# the IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
if self.is_distributor() and (self.get_resources_context().lower() == QUANTUM_PARTY_ENTITY.lower()):
# Retrieve the number of the Bipartite Pre-Shared Keys
# owned/possessed by the Party Entity involved on
# the IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
num_bipartite_pre_shared_keys = len(bipartite_pre_shared_keys)
# Print the header of the Bipartite Pre-Shared Keys
# owned/possessed by the Party Entity involved on
# the IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
print("\n\n - {} Bipartite Pre-Shared Key(s) owned:\n".format(num_bipartite_pre_shared_keys))
# For each Bipartite Pre-Shared Keys owned/possessed by the Party Entity involved on the
# IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
for current_num_bipartite_pre_shared_key in range(num_bipartite_pre_shared_keys):
# Print the information about the current Bipartite Pre-Shared Keys
# owned/possessed by the Party Entity involved on the
# IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
print(" [{}]".format((current_num_bipartite_pre_shared_key + 1)), end='')
bipartite_pre_shared_keys[current_num_bipartite_pre_shared_key].print_info()
# If the Party Entity is not the Distributor of
# the IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
else:
# Initialise the number of the Bipartite Pre-Shared Keys
# owned/possessed by the Party Entity involved on the
# IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
num_bipartite_pre_shared_keys = 1
# Retrieve the Bipartite Pre-Shared Key owned/possessed by the Party Entity involved on the
# IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol, as single instance
bipartite_pre_shared_key = bipartite_pre_shared_keys
# Print the header of the Bipartite Pre-Shared Keys owned/possessed by the Party Entity
# involved on the IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
print("\n\n - {} Bipartite Pre-Shared Key(s) owned:\n".format(num_bipartite_pre_shared_keys))
# Print the information about the current Bipartite Pre-Shared Keys
# owned/possessed by the Party Entity involved on the
# IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
print(" [{}]".format(num_bipartite_pre_shared_keys), end='')
bipartite_pre_shared_key.print_info()
# Some prints to draw a bottom left-side corner
print("|")
print("|__")
# Create the Round for the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
def create_protocol_round(self, num_round, num_qubits_and_bits_for_quantum_circuit):
# If the Party is the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
if self.is_distributor() and (self.get_resources_context().lower() == QUANTUM_PARTY_ENTITY.lower()):
# Retrieve the Bipartite Pre-Shared Keys of the Distributor of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
bipartite_pre_shared_keys = self.get_bipartite_pre_shared_keys()
# Retrieve the bit of the Pre-Shared Key, corresponding to the current round
round_type_bit = bipartite_pre_shared_keys[0].get_bipartite_pre_shared_key()[num_round] # TODO
# If the bit of the Pre-Shared Key, corresponding to the current round is zero
# (i.e., a SIFT / Measure and Resend Round)
if int(round_type_bit) == SIFT_MEASURE_AND_RESEND_ROUND_BIT:
# Set the ID of the SIFT / Measure and Resend Round
round_type_id = SIFT_MEASURE_AND_RESEND_ROUND_3
# If the bit of the Pre-Shared Key, corresponding to the current round is zero
# (i.e., a CTRL / Reflect Round)
else:
# Set the ID of the CTRL / Reflect Round
round_type_id = CTRL_REFLECT_ROUND_3
# Creation of the IBM Qiskit's Quantum Register
qiskit_quantum_register_sqcka_protocol_round = \
QiskitQuantumRegister.QiskitQuantumRegister("qrsqckaround{}".format(num_round),
num_qubits_and_bits_for_quantum_circuit)
# Creation of the IBM Qiskit's Classical Register
qiskit_classical_register_sqcka_protocol_round = \
QiskitClassicalRegister.QiskitClassicalRegister("crsqckaround{}".format(num_round),
num_qubits_and_bits_for_quantum_circuit)
# Creation of the IBM Qiskit's Quantum Circuit with one Quantum and Classical Registers
qiskit_quantum_circuit_sqcka_protocol_round = \
QiskitQuantumCircuit.QiskitQuantumCircuit("qcsqckaround{}".format(num_round),
qiskit_quantum_register_sqcka_protocol_round,
qiskit_classical_register_sqcka_protocol_round,
global_phase=0)
# Create the Round for the IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
qiskit_sqcka_protocol_round = \
QiskitSQCKAProtocolRound\
.QiskitSQCKAProtocolRound(num_round, round_type_id,
qiskit_quantum_circuit_sqcka_protocol_round)
# Return the Round for the IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
return qiskit_sqcka_protocol_round
# If the Party is not the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
else:
# Raise the Runtime Error exception
raise RuntimeError("Only the Distributor Party Entity can create "
"the Rounds for the Semi-Quantum Conference Key Agreement (SQCKA) Protocol!!!")
# Prepare a Bipartite or Multipartite Quantum Entanglement
def prepare_quantum_entanglement(self, quantum_entanglement_type, num_parties, protocol_round,
bell_state_type=None, qubits_edges_indexes_for_resource_state=None):
# If the Party is the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
if self.is_distributor() and (self.get_resources_context().lower() == QUANTUM_PARTY_ENTITY.lower()):
# If the specified type of Quantum Entanglement is one of the possible configurations for
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
if quantum_entanglement_type.upper() in POSSIBLE_QUANTUM_ENTANGLEMENT_TYPES:
# Retrieve the Quantum Circuit of the Protocol Round
quantum_circuit = protocol_round.get_qiskit_quantum_circuit()
# If the Quantum Entanglement to prepare is a Bell State
if quantum_entanglement_type.upper() == BELL_STATE:
# If the number of parties involved is higher than 2
if num_parties > 2:
# If the configuration of the Bell State is specified
if bell_state_type is not None:
# If the configuration of the Bell State is possible
if bell_state_type in POSSIBLE_CONFIGURATIONS_BELL_STATES:
# If the Bipartite Entangled State is Bell State (EPR Pair):
# - |ϕ^+⟩ = 1/sqrt(2) x (|00⟩ + |11⟩)
if (bell_state_type == EPR_PAIR_STATE) or (bell_state_type == BELL_STATE_PHI_PLUS):
# Prepare the EPR Pair (Bell State) for 2 Qubits
qiskit_quantum_circuit_epr_pair_bell_state_phi_plus = QiskitBellState \
.QiskitBellState((BELL_STATE_PHI_PLUS + "_" + EPR_PAIR_STATE).lower(),
BELL_STATE_PHI_PLUS,
quantum_circuit,
0, 1).prepare_bipartite_entanglement()
# Update the Quantum Circuit for the EPR Pair (Bell State) for 2 Qubits, for the Protocol Round
protocol_round.update_qiskit_quantum_circuit(qiskit_quantum_circuit_epr_pair_bell_state_phi_plus)
# Return the Protocol Round updated
return protocol_round
# If the Bipartite Entangled State is Bell State:
# - |ϕ^-⟩ = 1/sqrt(2) x (|00⟩ - |11⟩)
elif bell_state_type == BELL_STATE_PHI_MINUS:
# Prepare the Bell State: |ϕ^-⟩ = 1/sqrt(2) x (|00⟩ - |11⟩), for 2 Qubits
qiskit_quantum_circuit_bell_state_phi_minus = QiskitBellState \
.QiskitBellState(BELL_STATE_PHI_MINUS.lower(),
BELL_STATE_PHI_MINUS,
quantum_circuit,
0, 1).prepare_bipartite_entanglement()
# Update the Quantum Circuit for the Bell State for 2 Qubits, for the Protocol Round
protocol_round.update_qiskit_quantum_circuit(qiskit_quantum_circuit_bell_state_phi_minus)
# Return the Protocol Round updated
return protocol_round
# If the Bipartite Entangled State is Bell State:
# - |ψ^+⟩ = 1/sqrt(2) x (|01⟩ + |10⟩)
elif bell_state_type == BELL_STATE_PSI_PLUS:
# Prepare the Bell State: |ψ^+⟩ = 1/sqrt(2) x (|01⟩ + |10⟩), for 2 Qubits
qiskit_quantum_circuit_bell_state_psi_plus = QiskitBellState \
.QiskitBellState(BELL_STATE_PSI_PLUS.lower(),
BELL_STATE_PSI_PLUS,
quantum_circuit,
0, 1).prepare_bipartite_entanglement()
# Update the Quantum Circuit for the Bell State for 2 Qubits, for the Protocol Round
protocol_round.update_qiskit_quantum_circuit(qiskit_quantum_circuit_bell_state_psi_plus)
# Return the Protocol Round updated
return protocol_round
# If the Bipartite Entangled State is Bell State:
# - |ψ^-⟩ = 1/sqrt(2) x (|01⟩ - |10⟩)
elif bell_state_type == BELL_STATE_PSI_MINUS:
# Prepare the Bell State: |ψ^+-⟩ = 1/sqrt(2) x (|01⟩ - |10⟩), for 2 Qubits
qiskit_quantum_circuit_bell_state_psi_minus = QiskitBellState \
.QiskitBellState(BELL_STATE_PSI_MINUS.lower(),
BELL_STATE_PSI_MINUS,
quantum_circuit,
0, 1).prepare_bipartite_entanglement()
# Update the Quantum Circuit for the Bell State for 2 Qubits, for the Protocol Round
protocol_round.update_qiskit_quantum_circuit(qiskit_quantum_circuit_bell_state_psi_minus)
# Return the Protocol Round updated
return protocol_round
# If the configuration of the Bell State is not possible
else:
# Raise a Value Error
raise ValueError("The configuration of the Bell State specified is not possible!!!")
# If the configuration of the Bell State is not specified
else:
# Raise a Value Error
raise ValueError("The configuration of the Bell State is not specified!!!")
# If the number of parties involved is equal or lower than 2
else:
# Raise a Value Error
raise ValueError("It is impossible to use GHZ States for "
"Semi-Quantum Conference Key Agreement (SQCKA) with less than 3 Parties!!!")
# If the Quantum Entanglement to prepare is a GHZ State
elif quantum_entanglement_type.upper() == GHZ_STATE:
# If the number of parties involved is higher than 2
if num_parties > 2:
# Set the Control-Qubit
control_qubit_index = 0
# Set the list of Target-Qubits
target_qubits_indexes = list(range(1, num_parties))
# Prepare the GHZ State, for multiple Qubits
qiskit_quantum_circuit_ghz_state = QiskitGHZState \
.QiskitGHZState("ghz_state_qubits",
quantum_circuit,
control_qubit_index, target_qubits_indexes) \
.prepare_multipartite_entanglement()
# Update the Quantum Circuit for the GHZ State for n parties, for the Protocol Round
protocol_round.update_qiskit_quantum_circuit(qiskit_quantum_circuit_ghz_state)
# Return the Protocol Round updated
return protocol_round
# If the number of parties involved is equal or lower than 2
else:
# Raise a Value Error
raise ValueError("It is impossible to use GHZ States for "
"Semi-Quantum Conference Key Agreement (SQCKA) with less than 3 Parties!!!")
# If the Quantum Entanglement to prepare is a W State
elif quantum_entanglement_type.upper() == W_STATE:
# If the number of parties involved is higher than 2
if num_parties > 2:
# Set the list of Qubits
qubits_indexes = list(range(0, num_parties))
# Prepare the W State, for multiple Qubits
qiskit_quantum_circuit_w_state = QiskitWState \
.QiskitWState("w_state_qubits",
quantum_circuit,
qubits_indexes) \
.prepare_multipartite_entanglement()
# Update the Quantum Circuit for the W State for n parties, for the Protocol Round
protocol_round.update_qiskit_quantum_circuit(qiskit_quantum_circuit_w_state)
# Return the Protocol Round updated
return protocol_round
# If the number of parties involved is equal or lower than 2
else:
# Raise a Value Error
raise ValueError("It is impossible to use W States for "
"Semi-Quantum Conference Key Agreement (SQCKA) with less than 3 Parties!!!")
# If the Quantum Entanglement to prepare is a Dicke State
elif quantum_entanglement_type.upper() == DICKE_STATE:
# TODO - Handle this situation
return
# If the Quantum Entanglement to prepare is a Resource State
elif quantum_entanglement_type.upper() == RESOURCE_STATE:
# If the number of parties involved is higher than 1
if num_parties > 1:
# Set the list of Qubits
qubits_indexes = list(range(0, num_parties))
# Prepare the Resource State, as a Graph State by default, for multiple Qubits
qiskit_quantum_circuit_resource_state = QiskitGraphState \
.QiskitGraphState("resource_state_qubits",
quantum_circuit,
qubits_indexes,
qubits_edges_indexes_for_resource_state) \
.prepare_multipartite_entanglement()
# Update the Quantum Circuit for the Resource State for n parties, for the Protocol Round
protocol_round.update_qiskit_quantum_circuit(qiskit_quantum_circuit_resource_state)
# Return the Protocol Round updated
return protocol_round
# If the number of parties involved is equal or lower than 2
else:
# Raise a Value Error
raise ValueError("It is impossible to use Resource States for "
"Semi-Quantum Conference Key Agreement (SQCKA) with less than 2 Parties!!!")
# If the Quantum Entanglement to prepare is a Graph State
elif quantum_entanglement_type.upper() == GRAPH_STATE:
# If the number of parties involved is higher than 1
if num_parties > 1:
# Set the list of Qubits
qubits_indexes = list(range(0, num_parties))
# Prepare the Resource State, as a Graph State by default, for multiple Qubits
qiskit_quantum_circuit_graph_state = QiskitGraphState \
.QiskitGraphState("graph_state_qubits",
quantum_circuit,
qubits_indexes,
qubits_edges_indexes_for_resource_state) \
.prepare_multipartite_entanglement()
# Update the Quantum Circuit for the Graph State for n parties, for the Protocol Round
protocol_round.update_qiskit_quantum_circuit(qiskit_quantum_circuit_graph_state)
# Return the Protocol Round updated
return protocol_round
# If the number of parties involved is equal or lower than 2
else:
# Raise a Value Error
raise ValueError("It is impossible to use Graph States for "
"Semi-Quantum Conference Key Agreement (SQCKA) with less than 2 Parties!!!")
# If the Quantum Entanglement to prepare is a Cluster State
elif quantum_entanglement_type.upper() == CLUSTER_STATE:
# TODO - Handle this situation
return
# If the specified type of Quantum Entanglement is not one of the possible configurations for
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
else:
# Raise a Value Error
raise ValueError("The Quantum Entanglement specified for the Protocol is not possible to use!!!")
# If the Party is not the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
else:
# Raise a Runtime Error
raise RuntimeError("Only the Distributor Party Entity can prepare Quantum Entanglements!!!")
# Send the Quantum Data/Information to the Semi-Quantum Party Entities,
# over the Quantum Communication Channels
def send_quantum_data_information_to_semi_quantum_party_entities(self, num_parties, protocol_round):
# If the Party is the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
if self.is_distributor() and (self.get_resources_context().lower() == QUANTUM_PARTY_ENTITY.lower()):
# Retrieve the Quantum Circuit of the Protocol Round
quantum_circuit = protocol_round.get_qiskit_quantum_circuit()
# For each Semi-Quantum Entity
for current_num_semi_quantum_entities in range(1, num_parties):
# Apply the Swap Gate, between the Qubits of the Distributor Party Entity and
# the Qubits of the Quantum Communication Channel
quantum_circuit.apply_swap(current_num_semi_quantum_entities,
(num_parties + current_num_semi_quantum_entities - 1))
# Apply Barriers to all the Qubits of the Quantum Circuit for
# the Round of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
quantum_circuit.apply_barriers_to_all()
# Update the Quantum Circuit of the Protocol Round
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Return the Protocol Round updated
return protocol_round
# If the Party is not the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
else:
# Raise a Runtime Error
raise RuntimeError("Only the Distributor Party Entity can send the Quantum Data/Information, "
"over the Quantum Communication Channels!!!")
# Receive the Quantum Data/Information from the Distributor, over the Quantum Communication Channels
def receive_quantum_data_information_from_distributor(self, num_parties, protocol_round):
# If the Party is not the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
if not self.is_distributor() and \
(self.get_resources_context().lower() == SEMI_QUANTUM_PARTY_ENTITY.lower()):
# Retrieve the Quantum Circuit of the Protocol Round
quantum_circuit = protocol_round.get_qiskit_quantum_circuit()
# Apply the Swap Gate, between the Qubits of the Distributor and
# the Qubits of the Quantum Communication Channel
quantum_circuit.apply_swap((num_parties + self.party_entity_id - 1),
((2 * num_parties) + self.party_entity_id - 2))
# Apply Barriers to all the Qubits of the Quantum Circuit for
# the Round of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
quantum_circuit.apply_barriers_to_all()
# Update the Quantum Circuit of the Protocol Round
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Return the Protocol Round updated
return protocol_round
# If the Party is the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
else:
# Raise a Runtime Error
raise RuntimeError("Only the Semi-Quantum Receiver Party Entities "
"can receive the Quantum Data/Information, "
"over the Quantum Communication Channels!!!")
# Measure and Resend the Qubit, or just Reflect it, according to the Pre-Shared Key
def measure_and_resend_or_reflect_qubit(self, num_parties, protocol_round):
# If the Party is not the Distributor of the Protocol and the Party possesses only
# one Pre-Shared Key between itself and the Distributor of the Protocol
if (not self.is_distributor()) and \
(self.get_resources_context().lower() == SEMI_QUANTUM_PARTY_ENTITY.lower()) and \
(not isinstance(self.bipartite_pre_shared_keys, list)):
# Retrieve the bipartite Pre-Shared Key, with the Distributor of the Protocol
pre_shared_key_bits = self.bipartite_pre_shared_keys.get_bipartite_pre_shared_key()
# Retrieve the number of the Protocol Round
num_round = protocol_round.get_num_round()
# Retrieve the Quantum Circuit of the Protocol Round
quantum_circuit = protocol_round.get_qiskit_quantum_circuit()
# Compute the index of the Quantum Circuit,
# according to the respective qubit and bit of the Semi-Quantum Party Entity
qubit_bit_index = ((2 * num_parties) + self.party_entity_id - 2)
# It is a SIFT Round, thus, the Semi-Quantum Entity Party, will Measure and Resend the Qubit
# back again to the Distributor of the Protocol (more probable)
if int(pre_shared_key_bits[num_round]) == SIFT_MEASURE_AND_RESEND_ROUND_BIT:
# Print the information about the respective operation on the Qubit (Particle)
print("{} measured the Qubit (Particle) received, in the Z-Basis (Computational Basis)!!!"
.format(self.get_party_user_client().get_user_client_name()))
# Prepare and Measure the Qubit in the Z-Basis (Computational Basis),
# according to the Party Entity's ID
quantum_circuit.prepare_measure_single_qubit_in_z_basis(0, 0, qubit_bit_index, qubit_bit_index,
is_final_measurement=True)
# It is a CTRL Round, thus, the Semi-Quantum Entity Party, will just Reflect the Qubit,
# to the Distributor of the Protocol, without measure it (less probable)
elif int(pre_shared_key_bits[num_round]) == CTRL_REFLECT_ROUND_BIT:
# Print the information about the respective operation on the Qubit (Particle)
print("{} reflected the Qubit (Particle) received!!!"
.format(self.get_party_user_client().get_user_client_name()))
# Apply the Pauli-I to the Qubit,
# according to the Party Entity's ID
quantum_circuit.apply_pauli_i(qubit_bit_index)
# Print a blank line
print("\n")
# Update the Quantum Circuit of the Protocol Round
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Return the Protocol Round updated
return protocol_round
# If the Party is the Distributor of the Protocol and the Party possesses
# all the bipartite Pre-Shared Keys between itself and the other PARTIES
else:
# Raise the Value Error exception
raise ValueError("The Distributor Party is not allowed to SIFT (Measure and Resend) Rounds or "
"just Reflect the Qubits (CTRL Rounds)!!!")
# Execute the Quantum Circuit of the Protocol Round, if it is a SIFT (Measure and Resend) Round
# NOTE: This function should be executed only once, and only, by the Distributor Party Entity,
# in order to ensure that its execution is unique
def execute_protocol_round_quantum_circuit_for_sift_rounds(self, num_parties, protocol_round):
# Only the Distributor Party Entity is allowed to check
# if it is required to execute the Quantum Circuit of the Protocol Round,
# in order to allow the Semi-Quantum Party Entities to extract
# the correct results of the Protocol Round of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol,
# since the Quantum Circuit should only be executed once,
# due to the truly random correlated results of the Bipartite and Multipartite Entanglements
# NOTES:
# 1) In practice, should be the Semi-Quantum Party Entities to execute the Quantum Circuit,
# but execute it more than once, can lead to random (and wrong) results;
# And thus, this function should be delegated to the Distributor Party Entity,
# to ensure that the operation is someway unique, regarding a Protocol Round;
if self.is_distributor() and (self.get_resources_context().lower() == QUANTUM_PARTY_ENTITY.lower()):
# Retrieve the number of the Protocol Round
num_round = protocol_round.get_num_round()
# Retrieve the Bipartite Pre-Shared Keys of the Distributor of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
bipartite_pre_shared_keys = self.get_bipartite_pre_shared_keys()
# Retrieve the bit of the Pre-Shared Key, corresponding to the current round
round_type_bit = bipartite_pre_shared_keys[0].get_bipartite_pre_shared_key()[num_round] # TODO
# Retrieve the Quantum Circuit of the Protocol Round
quantum_circuit = protocol_round.get_qiskit_quantum_circuit()
# It is a SIFT (Measure and Resend) Round, thus, the Semi-Quantum Party Entity,
# will Measure and Resend the Qubit back again to the Distributor of the Protocol (more probable)
if int(round_type_bit) == SIFT_MEASURE_AND_RESEND_ROUND_BIT:
# Prepare and Measure the Qubit in the Z-Basis (Computational Basis),
# according to the Distributor Party Entity's ID
# NOTE: This is necessary, since the Quantum Circuit will be executed only once;
quantum_circuit.prepare_measure_single_qubit_in_z_basis(0, 0, 0, 0, is_final_measurement=True)
# Getting the Backend for the QASM (Quantum ASseMbly) for the simulation of the Quantum Circuit
# (i.e., the Measurement Results as a Dictionary Object, for a frequency counting)
qasm_backend = Aer.get_backend("qasm_simulator")
# Execute the Quantum Circuit and store the Measurement results in a Dictionary Object,
# for a frequency counting
final_results_quantum_circuit_measurement = \
execute(quantum_circuit.quantum_circuit, qasm_backend, shots=1).result().get_counts()
# Retrieve the Bits from the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
# NOTE:
# - It is necessary to invert the order of the Bits from the Execution of
# the Quantum Circuit of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol,
# since the resulting Bits are presented and ordered,
# from the most significant to the least significant one
circuit_bits = list(final_results_quantum_circuit_measurement.keys())[0][::-1]
# Concatenate the Bits from the Distributor
protocol_sift_round_results = (circuit_bits[0] + circuit_bits[(2 * num_parties) - 1:])
# Apply Barriers to all the Qubits of the Quantum Circuit for
# the Round of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
quantum_circuit.apply_barriers_to_all()
# Update the Quantum Circuit of the SIFT (Measure and Resend) Round of the Protocol
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Save the Results of the SIFT (Measure and Resend) Round of the Protocol
protocol_round.save_round_results(protocol_sift_round_results)
# Return the Protocol Round updated
return protocol_round
# Apply Barriers to all the Qubits of the Quantum Circuit for
# the Round of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
quantum_circuit.apply_barriers_to_all()
# Update the Quantum Circuit, ready to be just sent back, CTRL (Reflect) Round of the Protocol
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Return the Protocol Round updated
return protocol_round
# If it is not the Distributor Party Entity, then, it cannot execute
# the Quantum Circuit for the SIFT (Measure and Resend) Rounds of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
else:
# Raise a Runtime Error
raise RuntimeError("Only the Distributor Party Entity can execute the "
"Quantum Circuits for the SIFT (Measure and Resend) Rounds of "
"the Semi-Quantum Conference Key Agreement (SQCKA) Protocol!!!")
# Reset the Qubits of the Quantum Circuit of the SIFT (Measure and Resend) Round
# NOTE: This function should be executed only once, and only, by the Distributor Party Entity,
# in order to ensure that its execution is unique
def reset_qubits_to_resend_for_sift_rounds(self, protocol_round):
# Only the Distributor Party Entity is allowed to reset
# the Quantum Circuit of a SIFT (Measure and Resend) Round of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol,
# since the Quantum Circuit should only be executed once,
# due to the truly random correlated results of the Bipartite and Multipartite Entanglements
# NOTES:
# 1) In practice, should be the Semi-Quantum Party Entities to reset its own Qubits,
# in the Quantum Circuit, but reset it more than once, can lead to wrong results;
# And thus, this function should be delegated to the Distributor Party Entity,
# to ensure that the operation is someway unique, regarding a Protocol Round;
if self.is_distributor() and (self.get_resources_context().lower() == QUANTUM_PARTY_ENTITY.lower()):
# Retrieve the number of the Protocol Round
num_round = protocol_round.get_num_round()
# Retrieve the Bipartite Pre-Shared Keys of the Distributor of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
bipartite_pre_shared_keys = self.get_bipartite_pre_shared_keys()
# Retrieve the bit of the Pre-Shared Key, corresponding to the current round
round_type_bit = bipartite_pre_shared_keys[0].get_bipartite_pre_shared_key()[num_round] # TODO
# Retrieve the Quantum Circuit of the Protocol Round
quantum_circuit = protocol_round.get_qiskit_quantum_circuit()
# It is a SIFT (Measure and Resend) Round, thus, the Semi-Quantum Party Entity,
# will Measure and Resend the Qubit back again to the Distributor of the Protocol (more probable)
if int(round_type_bit) == SIFT_MEASURE_AND_RESEND_ROUND_BIT:
# Reset all the Qubits of the Quantum Circuit for
# the Round of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
quantum_circuit.reset_all()
# Print the information about resetting the Quantum Circuit,
# after the Z-Basis (Computational Basis) Measurement,
# for the current Measure and Resend (SIFT Operation) Round
print("Resetting the Qubits (Particles) of the Quantum Circuit,\n"
"after the Z-Basis (Computational Basis) Measurement...")
# Print the blank line
print("\n")
# Update the Quantum Circuit of the Protocol, which was reset
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Return the Protocol Round updated
return protocol_round
# If it is not the Distributor Party Entity, then, it cannot reset
# the Quantum Circuit for the SIFT (Measure and Resend) Rounds of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
else:
# Raise a Runtime Error
raise RuntimeError("Only the Distributor Party Entity can reset the Qubits of "
"the Quantum Circuits for the SIFT (Measure and Resend) Rounds of "
"the Semi-Quantum Conference Key Agreement (SQCKA) Protocol!!!")
# Prepare the Qubits of the Quantum Circuit of the SIFT (Measure and Resend) Round,
# of the Distributor Party Entity and of the Semi-Quantum Party Entities that,
# will send them back over the Quantum Communication Channels
def prepare_qubits_to_be_sent_back_for_sift_rounds(self, num_parties, protocol_round):
# If the Party Entity is the Distributor of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
if self.is_distributor() and (self.get_resources_context().lower() == QUANTUM_PARTY_ENTITY.lower()):
# Retrieve the number of the Protocol Round
num_round = protocol_round.get_num_round()
# Retrieve the Bipartite Pre-Shared Keys of the Distributor of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
bipartite_pre_shared_keys = self.get_bipartite_pre_shared_keys()
# Retrieve the bit of the Pre-Shared Key, corresponding to the current round
round_type_bit = bipartite_pre_shared_keys[0].get_bipartite_pre_shared_key()[num_round] # TODO
# Retrieve the Quantum Circuit of the Protocol Round
quantum_circuit = protocol_round.get_qiskit_quantum_circuit()
# It is a SIFT (Measure and Resend) Round, thus, the Semi-Quantum Party Entity,
# will Measure and Resend the Qubit back again to the Distributor of the Protocol (more probable)
if int(round_type_bit) == SIFT_MEASURE_AND_RESEND_ROUND_BIT:
# Retrieve the Bits of the results of the Protocol Round
protocol_round_results = protocol_round.get_round_results()
# Retrieve the Bit of the result of the Protocol Round,
# regarding the Distributor Party Entity
protocol_round_result_bit = protocol_round_results[0]
# If the Bit of the result of the Protocol Round,
# regarding the Distributor Party Entity, is 0
if int(protocol_round_result_bit) == 0:
# Apply the Pauli-I to the Qubit,
# according to the Party Entity's ID
quantum_circuit.apply_pauli_i(0)
# If the Bit of the result of the Protocol Round,
# regarding the Distributor Party Entity, is 1
elif int(protocol_round_result_bit) == 1:
# Apply the Pauli-X to the Qubit,
# according to the Party Entity's ID
quantum_circuit.apply_pauli_x(0)
# If the Party Entity is not the Distributor of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
else:
# Retrieve the number of the Protocol Round
num_round = protocol_round.get_num_round()
# Retrieve the bipartite Pre-Shared Key, with the Party Entity of the Protocol
pre_shared_key_bits = self.bipartite_pre_shared_keys.get_bipartite_pre_shared_key()
# Retrieve the Bit of the Pre-Shared Key, corresponding to the current round
round_type_bit = pre_shared_key_bits[num_round] # TODO
# Retrieve the Quantum Circuit of the Protocol Round
quantum_circuit = protocol_round.get_qiskit_quantum_circuit()
# It is a SIFT (Measure and Resend) Round, thus, the Semi-Quantum Party Entity,
# will Measure and Resend the Qubit back again to the Distributor of the Protocol (more probable)
if int(round_type_bit) == SIFT_MEASURE_AND_RESEND_ROUND_BIT:
# Compute the index of the Quantum Circuit,
# according to the respective qubit and bit of the Semi-Quantum Party Entity
qubit_bit_index = ((2 * num_parties) + self.party_entity_id - 2)
# Retrieve the Bits of the results of the Protocol Round
protocol_round_results = protocol_round.get_round_results()
# Retrieve the Bit of the result of the Protocol Round,
# regarding the Distributor Party Entity
protocol_round_result_bit = protocol_round_results[self.party_entity_id]
# If the Bit of the result of the Protocol Round,
# regarding the Distributor Party Entity, is 0
if int(protocol_round_result_bit) == 0:
# Apply the Pauli-I to the Qubit,
# according to the Party Entity's ID
quantum_circuit.apply_pauli_i(qubit_bit_index)
# Print the information about flipping or not the state of
# the Qubit (Particle) on the Quantum Circuit of the current Round,
# to introducing the Qubit (Particle) in the same state it was found,
# after the Z-Basis (Computational Basis) Measurement,
# for the current Measure and Resend (SIFT Operation) Round
print("{} does not flipped the Qubit (Particle) (i.e., setting it to |0⟩), before resend it..."
.format(self.get_party_user_client().get_user_client_name()))
# If the Bit of the result of the Protocol Round,
# regarding the Distributor Party Entity, is 1
elif int(protocol_round_result_bit) == 1:
# Apply the Pauli-X to the Qubit,
# according to the Party Entity's ID
quantum_circuit.apply_pauli_x(qubit_bit_index)
# Print the information about flipping or not the state of
# the Qubit (Particle) on the Quantum Circuit of the current Round,
# to introducing the Qubit (Particle) in the same state it was found,
# after the Z-Basis (Computational Basis) Measurement,
# for the current Measure and Resend (SIFT Operation) Round
print("{} flipped the Qubit (Particle) (i.e., setting it to |1⟩), before resend it..."
.format(self.get_party_user_client().get_user_client_name()))
# Print the blank line
print("\n")
# Update the Quantum Circuit, ready to be just sent back, CTRL (Reflect) Round of the Protocol
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Return the Protocol Round updated
return protocol_round
# Send back the Quantum Data/Information to the Distributor Party Entity,
# over the Quantum Communication Channels
def send_back_quantum_data_information_to_distributor_party_entity(self, num_parties, protocol_round):
# If the Party is not the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
if not self.is_distributor() and \
(self.get_resources_context().lower() == SEMI_QUANTUM_PARTY_ENTITY.lower()):
# Retrieve the Quantum Circuit of the Protocol Round
quantum_circuit = protocol_round.get_qiskit_quantum_circuit()
# Compute the index of the Quantum Circuit,
# according to the respective Qubit and Bit of the Semi-Quantum Party Entity
qubit_bit_index_semi_quantum_party_entity = ((2 * num_parties) + self.party_entity_id - 2)
# Compute the index of the Quantum Circuit,
# according to the respective Qubit and Bit of the Semi-Quantum Party Entity
qubit_bit_index_fiber_optic = (num_parties + self.party_entity_id - 1)
# Apply the Swap Gate, between the Qubits of the Distributor Party Entity and
# the Qubits of the Quantum Communication Channel
quantum_circuit.apply_swap(qubit_bit_index_semi_quantum_party_entity,
qubit_bit_index_fiber_optic)
# Update the Quantum Circuit of the Protocol Round
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Return the Protocol Round updated
return protocol_round
# If the Party is not the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
else:
# Raise a Runtime Error
raise RuntimeError("Only the Semi-Quantum Party Entities can send back the Quantum Data/Information, "
"over the Quantum Communication Channels!!!")
# Receive back the Quantum Data/Information from the Semi-Quantum Party Entities,
# over the Quantum Communication Channels
def receive_back_quantum_data_information_from_semi_quantum_party_entities(self, num_parties, protocol_round):
# If the Party Entity is the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
if self.is_distributor() and (self.get_resources_context().lower() == QUANTUM_PARTY_ENTITY.lower()):
# Retrieve the Quantum Circuit of the Protocol Round
quantum_circuit = protocol_round.get_qiskit_quantum_circuit()
# For each Semi-Quantum Entity
for current_num_semi_quantum_entity in range(1, num_parties):
# Apply the Swap Gate, between the Qubits of the Distributor Party Entity and
# the Qubits of the Quantum Communication Channel
quantum_circuit.apply_swap((num_parties + current_num_semi_quantum_entity - 1),
current_num_semi_quantum_entity)
# Apply Barriers to all the Qubits of the Quantum Circuit for
# the Round of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
quantum_circuit.apply_barriers_to_all()
# Update the Quantum Circuit of the Protocol Round
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Return the Protocol Round updated
return protocol_round
# If the Party is not the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
else:
# Raise a Runtime Error
raise RuntimeError("Only the Distributor Party Entity can send the Quantum Data/Information, "
"over the Quantum Communication Channels!!!")
# Prepare to Measurement of a Bipartite or Multipartite Quantum Entanglement, by inverting Quantum Circuit
def measure_quantum_entanglement_by_inverting_quantum_circuit(self, quantum_entanglement_type,
num_parties, protocol_round,
bell_state_type=None,
qubits_edges_indexes_for_resource_state=None):
# If the current Round of the IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
if protocol_round.get_type_round() == CTRL_REFLECT_ROUND_3:
# If the Party Entity is the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
if self.is_distributor() and (self.get_resources_context().lower() == QUANTUM_PARTY_ENTITY.lower()):
# Retrieve the Quantum Circuit of the Protocol Round
quantum_circuit = protocol_round.get_qiskit_quantum_circuit()
# If the Quantum Entanglement to prepare is a Bell State
if quantum_entanglement_type.upper() == BELL_STATE:
# If the number of parties involved is higher than 2
if num_parties > 2:
# If the configuration of the Bell State is specified
if bell_state_type is not None:
# If the configuration of the Bell State is possible
if bell_state_type in POSSIBLE_CONFIGURATIONS_BELL_STATES:
# If the Bipartite Entangled State is Bell State (EPR Pair):
# - |ϕ^+⟩ = 1/sqrt(2) x (|00⟩ + |11⟩)
if (bell_state_type == EPR_PAIR_STATE) or (bell_state_type == BELL_STATE_PHI_PLUS):
# Prepare the inverse of the EPR Pair (Bell State) for 2 Qubits
quantum_circuit = QiskitBellState \
.QiskitBellState((BELL_STATE_PHI_PLUS + "_" + EPR_PAIR_STATE).lower(),
BELL_STATE_PHI_PLUS,
quantum_circuit,
0, 1).measure_bipartite_entanglement()
# Getting the Backend for the QASM (Quantum ASseMbly) for
# the simulation of the Quantum Circuit
# (i.e., the Measurement Results as a Dictionary Object, for a frequency counting)
qasm_backend = Aer.get_backend("qasm_simulator")
# Execute the Quantum Circuit and store the Measurement results
# in a Dictionary Object, for a frequency counting
final_results_quantum_circuit_measurement = \
execute(quantum_circuit.quantum_circuit, qasm_backend, shots=1)\
.result().get_counts()
# Retrieve the Bits from the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
# NOTE:
# - It is necessary to invert the order of the Bits from
# the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol,
# since the resulting Bits are presented and ordered,
# from the most significant to the least significant one
circuit_bits = list(final_results_quantum_circuit_measurement.keys())[0][::-1]
# Retrieve the Bits for the Measurement of the Multipartite Entanglement State
protocol_sift_round_results = circuit_bits[:num_parties]
# Update the Quantum Circuit of the CTRL (Reflected) Round of the Protocol
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Save the Results of the CTRL (Reflected) Round of the Protocol
protocol_round.save_round_results(protocol_sift_round_results)
# Return the Protocol Round updated
return protocol_round
# If the Bipartite Entangled State is Bell State:
# - |ϕ^-⟩ = 1/sqrt(2) x (|00⟩ - |11⟩)
elif bell_state_type == BELL_STATE_PHI_MINUS:
# Prepare the inverse of
# the Bell State: |ϕ^-⟩ = 1/sqrt(2) x (|00⟩ - |11⟩), for 2 Qubits
quantum_circuit = QiskitBellState \
.QiskitBellState(BELL_STATE_PHI_MINUS.lower(),
BELL_STATE_PHI_MINUS,
quantum_circuit,
0, 1).measure_bipartite_entanglement()
# Getting the Backend for the QASM (Quantum ASseMbly) for
# the simulation of the Quantum Circuit
# (i.e., the Measurement Results as a Dictionary Object, for a frequency counting)
qasm_backend = Aer.get_backend("qasm_simulator")
# Execute the Quantum Circuit and store the Measurement results
# in a Dictionary Object, for a frequency counting
final_results_quantum_circuit_measurement = \
execute(quantum_circuit.quantum_circuit, qasm_backend, shots=1) \
.result().get_counts()
# Retrieve the Bits from the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
# NOTE:
# - It is necessary to invert the order of the Bits from
# the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol,
# since the resulting Bits are presented and ordered,
# from the most significant to the least significant one
circuit_bits = list(final_results_quantum_circuit_measurement.keys())[0][::-1]
# Retrieve the Bits for the Measurement of the Multipartite Entanglement State
protocol_sift_round_results = circuit_bits[:num_parties]
# Update the Quantum Circuit of the CTRL (Reflected) Round of the Protocol
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Save the Results of the CTRL (Reflected) Round of the Protocol
protocol_round.save_round_results(protocol_sift_round_results)
# Return the Protocol Round updated
return protocol_round
# If the Bipartite Entangled State is Bell State:
# - |ψ^+⟩ = 1/sqrt(2) x (|01⟩ + |10⟩)
elif bell_state_type == BELL_STATE_PSI_PLUS:
# Prepare the inverse of
# the Bell State: |ψ^+⟩ = 1/sqrt(2) x (|01⟩ + |10⟩), for 2 Qubits
quantum_circuit = QiskitBellState \
.QiskitBellState(BELL_STATE_PSI_PLUS.lower(),
BELL_STATE_PSI_PLUS,
quantum_circuit,
0, 1).measure_bipartite_entanglement()
# Getting the Backend for the QASM (Quantum ASseMbly) for
# the simulation of the Quantum Circuit
# (i.e., the Measurement Results as a Dictionary Object, for a frequency counting)
qasm_backend = Aer.get_backend("qasm_simulator")
# Execute the Quantum Circuit and store the Measurement results
# in a Dictionary Object, for a frequency counting
final_results_quantum_circuit_measurement = \
execute(quantum_circuit.quantum_circuit, qasm_backend, shots=1) \
.result().get_counts()
# Retrieve the Bits from the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
# NOTE:
# - It is necessary to invert the order of the Bits from
# the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol,
# since the resulting Bits are presented and ordered,
# from the most significant to the least significant one
circuit_bits = list(final_results_quantum_circuit_measurement.keys())[0][::-1]
# Retrieve the Bits for the Measurement of the Multipartite Entanglement State
protocol_sift_round_results = circuit_bits[:num_parties]
# Update the Quantum Circuit of the CTRL (Reflected) Round of the Protocol
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Save the Results of the CTRL (Reflected) Round of the Protocol
protocol_round.save_round_results(protocol_sift_round_results)
# Return the Protocol Round updated
return protocol_round
# If the Bipartite Entangled State is Bell State:
# - |ψ^-⟩ = 1/sqrt(2) x (|01⟩ - |10⟩)
elif bell_state_type == BELL_STATE_PSI_MINUS:
# Prepare the inverse of
# the Bell State: |ψ^+-⟩ = 1/sqrt(2) x (|01⟩ - |10⟩), for 2 Qubits
quantum_circuit = QiskitBellState \
.QiskitBellState(BELL_STATE_PSI_MINUS.lower(),
BELL_STATE_PSI_MINUS,
quantum_circuit,
0, 1).measure_bipartite_entanglement()
# Getting the Backend for the QASM (Quantum ASseMbly) for
# the simulation of the Quantum Circuit
# (i.e., the Measurement Results as a Dictionary Object, for a frequency counting)
qasm_backend = Aer.get_backend("qasm_simulator")
# Execute the Quantum Circuit and store the Measurement results
# in a Dictionary Object, for a frequency counting
final_results_quantum_circuit_measurement = \
execute(quantum_circuit.quantum_circuit, qasm_backend, shots=1) \
.result().get_counts()
# Retrieve the Bits from the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
# NOTE:
# - It is necessary to invert the order of the Bits from
# the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol,
# since the resulting Bits are presented and ordered,
# from the most significant to the least significant one
circuit_bits = list(final_results_quantum_circuit_measurement.keys())[0][::-1]
# Retrieve the Bits for the Measurement of the Multipartite Entanglement State
protocol_sift_round_results = circuit_bits[:num_parties]
# Update the Quantum Circuit of the CTRL (Reflected) Round of the Protocol
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Save the Results of the CTRL (Reflected) Round of the Protocol
protocol_round.save_round_results(protocol_sift_round_results)
# Return the Protocol Round updated
return protocol_round
# If the configuration of the Bell State is not possible
else:
# Raise a Value Error
raise ValueError("The configuration of the Bell State specified is not possible!!!")
# If the configuration of the Bell State is not specified
else:
# Raise a Value Error
raise ValueError("The configuration of the Bell State is not specified!!!")
# If the number of parties involved is equal or lower than 2
else:
# Raise a Value Error
raise ValueError("It is impossible to use GHZ States for "
"Semi-Quantum Conference Key Agreement (SQCKA) with less than 3 Parties!!!")
# If the Quantum Entanglement to prepare is a GHZ State
elif quantum_entanglement_type.upper() == GHZ_STATE:
# If the number of parties involved is higher than 2
if num_parties > 2:
# Set the Control-Qubit
control_qubit_index = 0
# Set the list of Target-Qubits
target_qubits_indexes = list(range(1, num_parties))
# Prepare the GHZ State, for multiple Qubits
quantum_circuit = QiskitGHZState \
.QiskitGHZState("ghz_state_qubits",
quantum_circuit,
control_qubit_index, target_qubits_indexes) \
.measure_multipartite_entanglement()
# Getting the Backend for the QASM (Quantum ASseMbly) for
# the simulation of the Quantum Circuit
# (i.e., the Measurement Results as a Dictionary Object, for a frequency counting)
qasm_backend = Aer.get_backend("qasm_simulator")
# Execute the Quantum Circuit and store the Measurement results
# in a Dictionary Object, for a frequency counting
final_results_quantum_circuit_measurement = \
execute(quantum_circuit.quantum_circuit, qasm_backend, shots=1) \
.result().get_counts()
# Retrieve the Bits from the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
# NOTE:
# - It is necessary to invert the order of the Bits from
# the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol,
# since the resulting Bits are presented and ordered,
# from the most significant to the least significant one
circuit_bits = list(final_results_quantum_circuit_measurement.keys())[0][::-1]
# Retrieve the Bits for the Measurement of the Multipartite Entanglement State
protocol_sift_round_results = circuit_bits[:num_parties]
# Update the Quantum Circuit of the CTRL (Reflected) Round of the Protocol
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Save the Results of the CTRL (Reflected) Round of the Protocol
protocol_round.save_round_results(protocol_sift_round_results)
# Return the Protocol Round updated
return protocol_round
# If the number of parties involved is equal or lower than 2
else:
# Raise a Value Error
raise ValueError("It is impossible to use GHZ States for "
"Semi-Quantum Conference Key Agreement (SQCKA) with less than 3 Parties!!!")
# If the Quantum Entanglement to prepare is a W State
elif quantum_entanglement_type.upper() == W_STATE:
# If the number of parties involved is higher than 2
if num_parties > 2:
# Set the list of Qubits
qubits_indexes = list(range(0, num_parties))
# Prepare the W State, for multiple Qubits
quantum_circuit = QiskitWState \
.QiskitWState("w_state_qubits",
quantum_circuit,
qubits_indexes) \
.measure_multipartite_entanglement()
# Getting the Backend for the QASM (Quantum ASseMbly) for
# the simulation of the Quantum Circuit
# (i.e., the Measurement Results as a Dictionary Object, for a frequency counting)
qasm_backend = Aer.get_backend("qasm_simulator")
# Execute the Quantum Circuit and store the Measurement results
# in a Dictionary Object, for a frequency counting
final_results_quantum_circuit_measurement = \
execute(quantum_circuit.quantum_circuit, qasm_backend, shots=1) \
.result().get_counts()
# Retrieve the Bits from the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
# NOTE:
# - It is necessary to invert the order of the Bits from
# the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol,
# since the resulting Bits are presented and ordered,
# from the most significant to the least significant one
circuit_bits = list(final_results_quantum_circuit_measurement.keys())[0][::-1]
# Retrieve the Bits for the Measurement of the Multipartite Entanglement State
protocol_sift_round_results = circuit_bits[:num_parties]
# Update the Quantum Circuit of the CTRL (Reflected) Round of the Protocol
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Save the Results of the CTRL (Reflected) Round of the Protocol
protocol_round.save_round_results(protocol_sift_round_results)
# Return the Protocol Round updated
return protocol_round
# If the number of parties involved is equal or lower than 2
else:
# Raise a Value Error
raise ValueError("It is impossible to use W States for "
"Semi-Quantum Conference Key Agreement (SQCKA) with less than 3 Parties!!!")
# If the Quantum Entanglement to prepare is a Dicke State
elif quantum_entanglement_type.upper() == DICKE_STATE:
# TODO - Handle this situation
return
# If the Quantum Entanglement to prepare is a Resource State
elif quantum_entanglement_type.upper() == RESOURCE_STATE:
# If the number of parties involved is higher than 1
if num_parties > 1:
# Set the list of Qubits
qubits_indexes = list(range(0, num_parties))
# Prepare the Resource State, as a Graph State by default, for multiple Qubits
quantum_circuit = QiskitGraphState \
.QiskitGraphState("resource_state_qubits",
quantum_circuit,
qubits_indexes,
qubits_edges_indexes_for_resource_state) \
.measure_multipartite_entanglement()
# Getting the Backend for the QASM (Quantum ASseMbly) for
# the simulation of the Quantum Circuit
# (i.e., the Measurement Results as a Dictionary Object, for a frequency counting)
qasm_backend = Aer.get_backend("qasm_simulator")
# Execute the Quantum Circuit and store the Measurement results
# in a Dictionary Object, for a frequency counting
final_results_quantum_circuit_measurement = \
execute(quantum_circuit.quantum_circuit, qasm_backend, shots=1) \
.result().get_counts()
# Retrieve the Bits from the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
# NOTE:
# - It is necessary to invert the order of the Bits from
# the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol,
# since the resulting Bits are presented and ordered,
# from the most significant to the least significant one
circuit_bits = list(final_results_quantum_circuit_measurement.keys())[0][::-1]
# Retrieve the Bits for the Measurement of the Multipartite Entanglement State
protocol_sift_round_results = circuit_bits[:num_parties]
# Update the Quantum Circuit of the CTRL (Reflected) Round of the Protocol
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Save the Results of the CTRL (Reflected) Round of the Protocol
protocol_round.save_round_results(protocol_sift_round_results)
# Return the Protocol Round updated
return protocol_round
# If the number of parties involved is equal or lower than 2
else:
# Raise a Value Error
raise ValueError("It is impossible to use Resource States for "
"Semi-Quantum Conference Key Agreement (SQCKA) with less than 2 Parties!!!")
# If the Quantum Entanglement to prepare is a Graph State
elif quantum_entanglement_type.upper() == GRAPH_STATE:
# If the number of parties involved is higher than 1
if num_parties > 1:
# Set the list of Qubits
qubits_indexes = list(range(0, num_parties))
# Prepare the Resource State, as a Graph State by default, for multiple Qubits
quantum_circuit = QiskitGraphState \
.QiskitGraphState("graph_state_qubits",
quantum_circuit,
qubits_indexes,
qubits_edges_indexes_for_resource_state) \
.measure_multipartite_entanglement()
# Getting the Backend for the QASM (Quantum ASseMbly) for
# the simulation of the Quantum Circuit
# (i.e., the Measurement Results as a Dictionary Object, for a frequency counting)
qasm_backend = Aer.get_backend("qasm_simulator")
# Execute the Quantum Circuit and store the Measurement results
# in a Dictionary Object, for a frequency counting
final_results_quantum_circuit_measurement = \
execute(quantum_circuit.quantum_circuit, qasm_backend, shots=1) \
.result().get_counts()
# Retrieve the Bits from the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
# NOTE:
# - It is necessary to invert the order of the Bits from
# the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol,
# since the resulting Bits are presented and ordered,
# from the most significant to the least significant one
circuit_bits = list(final_results_quantum_circuit_measurement.keys())[0][::-1]
# Retrieve the Bits for the Measurement of the Multipartite Entanglement State
protocol_sift_round_results = circuit_bits[:num_parties]
# Update the Quantum Circuit of the CTRL (Reflected) Round of the Protocol
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Save the Results of the CTRL (Reflected) Round of the Protocol
protocol_round.save_round_results(protocol_sift_round_results)
# Return the Protocol Round updated
return protocol_round
# If the number of parties involved is equal or lower than 2
else:
# Raise a Value Error
raise ValueError("It is impossible to use Graph States for "
"Semi-Quantum Conference Key Agreement (SQCKA) with less than 2 Parties!!!")
# If the Quantum Entanglement to prepare is a Cluster State
elif quantum_entanglement_type.upper() == CLUSTER_STATE:
# TODO - Handle this situation
return
# If the specified type of Quantum Entanglement is not one of the possible configurations for
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
else:
# Raise a Value Error
raise ValueError("The Quantum Entanglement specified for the Protocol is not possible to use!!!")
# If the Party is not the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
else:
# Raise a Runtime Error
raise RuntimeError("Only the Distributor Party Entity can prepare Quantum Entanglements!!!")
# Return the Protocol Round updated
return protocol_round
# Measure the Qubits of the Quantum Circuit of the CTRL (Reflect) Round,
# which were reflected back from the Semi-Quantum Party Entities to the Distributor Party Entity,
# over the Quantum Communication Channels
def measure_quantum_data_information_for_ctrl_rounds(self, num_parties, protocol_round):
# If the current Round of the IBM Qiskit's Semi-Quantum Conference Key Agreement (SQCKA) Protocol
if protocol_round.get_type_round() == CTRL_REFLECT_ROUND_3:
# If the Party Entity is the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
if self.is_distributor() and (self.get_resources_context().lower() == QUANTUM_PARTY_ENTITY.lower()):
# Retrieve the Quantum Circuit of the Protocol Round
quantum_circuit = protocol_round.get_qiskit_quantum_circuit()
# Create the list of the range of the Qubits and Bits
num_qubits_bits_indexes = list(range(0, num_parties))
# Measure the Qubits on the Quantum Memory of the Distributor Party Entity
quantum_circuit.measure_qubits_interval(0, 0, num_qubits_bits_indexes, num_qubits_bits_indexes)
# Getting the Backend for the QASM (Quantum ASseMbly) for the simulation of the Quantum Circuit
# (i.e., the Measurement Results as a Dictionary Object, for a frequency counting)
qasm_backend = Aer.get_backend("qasm_simulator")
# Execute the Quantum Circuit and store the Measurement results in a Dictionary Object,
# for a frequency counting
final_results_quantum_circuit_measurement = \
execute(quantum_circuit.quantum_circuit, qasm_backend, shots=1).result().get_counts()
# Retrieve the Bits from the Execution of the Quantum Circuit of
# the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
# NOTE:
# - It is necessary to invert the order of the Bits from the Execution of
# the Quantum Circuit of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol,
# since the resulting Bits are presented and ordered,
# from the most significant to the least significant one
circuit_bits = list(final_results_quantum_circuit_measurement.keys())[0][::-1]
# Retrieve the Bits for the Measurement of the Multipartite Entanglement State
protocol_sift_round_results = circuit_bits[:num_parties]
# Update the Quantum Circuit of the CTRL (Reflected) Round of the Protocol
protocol_round.update_qiskit_quantum_circuit(quantum_circuit)
# Save the Results of the CTRL (Reflected) Round of the Protocol
protocol_round.save_round_results(protocol_sift_round_results)
# Return the Protocol Round updated
return protocol_round
# If the Party is not the Distributor of the Semi-Quantum Conference Key Agreement (SQCKA) Protocol
else:
# Raise a Runtime Error
raise RuntimeError("Only the Distributor Party Entity can measure the "
"reflected back Multipartite Entanglement,\n"
"over the Quantum Communication Channels!!!")
# Return the Protocol Round updated
return protocol_round
| 56.768501 | 133 | 0.586723 | 9,942 | 89,751 | 5.124019 | 0.037417 | 0.029543 | 0.046169 | 0.052765 | 0.911587 | 0.894647 | 0.865418 | 0.853758 | 0.83933 | 0.826296 | 0 | 0.004501 | 0.366325 | 89,751 | 1,580 | 134 | 56.80443 | 0.890458 | 0.401923 | 0 | 0.7 | 0 | 0.003636 | 0.079261 | 0.000792 | 0 | 0 | 0 | 0.000633 | 0 | 1 | 0.034545 | false | 0 | 0.021818 | 0.009091 | 0.127273 | 0.045455 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
9aada8c94698f8868b44ebcef28421edcdfe7764 | 2,458 | py | Python | test/server_test.py | hkariti/higlass-python | 088ac1e8278a987e2aaafe9ba5e8256cac4f3b3b | [
"MIT"
] | 24 | 2018-11-16T15:58:22.000Z | 2022-02-17T19:34:27.000Z | test/server_test.py | hkariti/higlass-python | 088ac1e8278a987e2aaafe9ba5e8256cac4f3b3b | [
"MIT"
] | 45 | 2018-11-19T01:47:26.000Z | 2022-03-04T22:02:47.000Z | test/server_test.py | hkariti/higlass-python | 088ac1e8278a987e2aaafe9ba5e8256cac4f3b3b | [
"MIT"
] | 11 | 2018-11-28T21:10:51.000Z | 2022-03-04T19:46:25.000Z | from unittest.mock import Mock, patch
import higlass.server as server
def test_tcp():
s = server.Server([], host="localhost", port=1234)
with patch("requests.head") as head, patch("multiprocess.Process") as mp:
head.ok = True
s.start()
expected_api_address = "http://localhost:1234/api/v1"
assert s.api_address == expected_api_address
def test_tcp_root_api_address():
s = server.Server(
[], host="localhost", port=1234, root_api_address="http://{host}:{port}/test"
)
with patch("requests.head") as head, patch("multiprocess.Process") as mp:
head.ok = True
s.start()
expected_api_address = "http://localhost:1234/test/api/v1"
assert s.api_address == expected_api_address
def test_unix_host_file():
filename = "/tmp/s.sock"
s = server.Server([], host=f"unix://{filename}")
with patch("requests.head") as head, patch("multiprocess.Process") as mp:
head.ok = True
s.start()
expected_api_address = "http+unix://" + filename.replace("/", "%2F") + "/api/v1"
assert s.api_address == expected_api_address
def test_unix_host_dir_with_port():
filename = "/tmp/s.sock"
s = server.Server([], host=f"unix:///tmp", port="s.sock")
with patch("requests.head") as head, patch("multiprocess.Process") as mp, patch(
"os.makedirs"
) as _:
head.ok = True
s.start()
expected_api_address = "http+unix://" + filename.replace("/", "%2F") + "/api/v1"
assert s.api_address == expected_api_address
def test_unix_host_dir_without_port():
filename = "/tmp/0"
s = server.Server([], host=f"unix:///tmp", port=None)
with patch("requests.head") as head, patch(
"higlass.server.get_free_socket", return_value=0
) as _, patch("multiprocess.Process") as mp, patch("os.makedirs") as _:
head.ok = True
s.start()
expected_api_address = "http+unix://" + filename.replace("/", "%2F") + "/api/v1"
assert s.api_address == expected_api_address
def test_unix_root_api_address():
filename = "/tmp/s.sock"
s = server.Server(
[],
host=f"unix://{filename}",
root_api_address="http+unix://{unix_filename}/test",
)
with patch("requests.head") as head, patch("multiprocess.Process") as mp:
head.ok = True
s.start()
expected_api_address = f"http+unix://{filename}/test/api/v1"
assert s.api_address == expected_api_address
| 31.512821 | 85 | 0.63629 | 335 | 2,458 | 4.480597 | 0.152239 | 0.146569 | 0.143904 | 0.067955 | 0.826782 | 0.826782 | 0.826782 | 0.76016 | 0.736176 | 0.736176 | 0 | 0.013754 | 0.201383 | 2,458 | 77 | 86 | 31.922078 | 0.750891 | 0 | 0 | 0.517241 | 0 | 0 | 0.240033 | 0.039056 | 0 | 0 | 0 | 0 | 0.103448 | 1 | 0.103448 | false | 0 | 0.034483 | 0 | 0.137931 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
9af9a67de21a68e7f4fa88a504dc972e4d2b3611 | 43 | py | Python | pynder/__init__.py | phbprogramming/HackTX2018 | 032d2cb0577c17907836f49a0e2dd7592ae0a1b2 | [
"BSD-3-Clause"
] | null | null | null | pynder/__init__.py | phbprogramming/HackTX2018 | 032d2cb0577c17907836f49a0e2dd7592ae0a1b2 | [
"BSD-3-Clause"
] | null | null | null | pynder/__init__.py | phbprogramming/HackTX2018 | 032d2cb0577c17907836f49a0e2dd7592ae0a1b2 | [
"BSD-3-Clause"
] | 1 | 2019-02-03T19:59:42.000Z | 2019-02-03T19:59:42.000Z | from pynder.session import Session # NOQA
| 21.5 | 42 | 0.790698 | 6 | 43 | 5.666667 | 0.833333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.162791 | 43 | 1 | 43 | 43 | 0.944444 | 0.093023 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
b101558a41b5df03e0240a0c68c1f33537432b5d | 489 | py | Python | tests/test_unit.py | techdragon/python-tempo | c146959a5bd3a6f510a784d89ad3ee0537342677 | [
"BSD-3-Clause"
] | 3 | 2015-06-20T21:20:55.000Z | 2015-07-22T07:25:13.000Z | tests/test_unit.py | techdragon/python-tempo | c146959a5bd3a6f510a784d89ad3ee0537342677 | [
"BSD-3-Clause"
] | null | null | null | tests/test_unit.py | techdragon/python-tempo | c146959a5bd3a6f510a784d89ad3ee0537342677 | [
"BSD-3-Clause"
] | 2 | 2022-01-19T06:02:39.000Z | 2022-01-23T05:31:43.000Z | # coding=utf-8
from tempo.unit import DAYS_OF_COMMON_YEAR, DAYS_OF_LEAP_YEAR
def test_days_of_common_year():
"""DAYS_OF_COMMON_YEAR constant consistency."""
assert len(DAYS_OF_COMMON_YEAR) == 12
assert sum(DAYS_OF_COMMON_YEAR) == 365
assert DAYS_OF_COMMON_YEAR[1] == 28
def test_days_of_leap_year():
"""DAYS_OF_LEAP_YEAR constant consistency."""
assert len(DAYS_OF_LEAP_YEAR) == 12
assert sum(DAYS_OF_LEAP_YEAR) == 366
assert DAYS_OF_LEAP_YEAR[1] == 29
| 28.764706 | 61 | 0.742331 | 81 | 489 | 4.012346 | 0.308642 | 0.221538 | 0.221538 | 0.295385 | 0.566154 | 0.498462 | 0.233846 | 0 | 0 | 0 | 0 | 0.041262 | 0.157464 | 489 | 16 | 62 | 30.5625 | 0.747573 | 0.194274 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | 1 | 0.222222 | true | 0 | 0.111111 | 0 | 0.333333 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
b180a769f87bd560e42569c6f7824f0c6a8212d1 | 8,549 | py | Python | tab.py | Mariaalice1/tabuada | acfa5c8ce07048d77f37a168818e80c7d77c208b | [
"MIT"
] | null | null | null | tab.py | Mariaalice1/tabuada | acfa5c8ce07048d77f37a168818e80c7d77c208b | [
"MIT"
] | null | null | null | tab.py | Mariaalice1/tabuada | acfa5c8ce07048d77f37a168818e80c7d77c208b | [
"MIT"
] | null | null | null | # Potencicao
tabb = [1**1]
tab = [2**1]
tab_2 = [3**1]
tab_3 = [4**1]
tab_4 = [5**1]
tab_5 = [6**1]
tab_6 = [7**1]
tab_7 = [8**1]
tab_8 = [9**1]
tab_9 = [10**1]
for y in tabb:
print("1**1 = {}".format(y))
for i in tab:
print("2**1 = {}".format(i))
for a in tab_2:
print("3**1 = {}".format(a))
for b in tab_3:
print("4**1 = {}".format(b))
for c in tab_4:
print("5**1 = {}".format(c))
for d in tab_5:
print("6**1 = {}".format(d))
for e in tab_6:
print("7**1 = {}".format(e))
for f in tab_7:
print("8**1 = {}".format(f))
for g in tab_8:
print("9**1 = {}".format(g))
for h in tab_9:
print("10**1 = {}".format(h))
print ("----------------------------------------------")
tab_1 = [1**2]
tab_2 = [2**2]
tab_3 = [3**2]
tab_4 = [4**2]
tab_5 = [5**2]
tab_6 = [6**2]
tab_7 = [7**2]
tab_8 = [8**2]
tab_9 = [9**2]
tab_10 = [10**2]
for y in tab_1:
print("1**2 = {}".format(y))
for i in tab_2:
print("2**2 = {}".format(i))
for a in tab_3:
print("3**2 = {}".format(a))
for b in tab_4:
print("4**2 = {}".format(b))
for c in tab_5:
print("5**2 = {}".format(c))
for d in tab_6:
print("6**2 = {}".format(d))
for e in tab_7:
print("7**2 = {}".format(e))
for f in tab_8:
print("8**2 = {}".format(f))
for g in tab_9:
print("9**2 = {}".format(g))
for h in tab_10:
print("10**2 = {}".format(h))
print ("----------------------------------------------")
tab_1 = [1**3]
tab_2 = [2**3]
tab_3 = [3**3]
tab_4 = [4**3]
tab_5 = [5**3]
tab_6 = [6**3]
tab_7 = [7**3]
tab_8 = [8**3]
tab_9 = [9**3]
tab_10 = [10**3]
for y in tab_1:
print("1**3 = {}".format(y))
for i in tab_2:
print("2**3 = {}".format(i))
for a in tab_3:
print("3**3 = {}".format(a))
for b in tab_4:
print("4**3 = {}".format(b))
for c in tab_5:
print("5**3 = {}".format(c))
for d in tab_6:
print("6**3 = {}".format(d))
for e in tab_7:
print("7**3 = {}".format(e))
for f in tab_8:
print("8**3 = {}".format(f))
for g in tab_9:
print("9**3 = {}".format(g))
for h in tab_10:
print("10**3 = {}".format(h))
print ("----------------------------------------------")
tab_1 = [1**4]
tab_2 = [2**4]
tab_3 = [3**4]
tab_4 = [4**4]
tab_5 = [5**4]
tab_6 = [6**4]
tab_7 = [7**4]
tab_8 = [8**4]
tab_9 = [9**4]
tab_10 = [10**4]
for y in tab_1:
print("1**4 = {}".format(y))
for i in tab_2:
print("2**4 = {}".format(i))
for a in tab_3:
print("3**4 = {}".format(a))
for b in tab_4:
print("4**4 = {}".format(b))
for c in tab_5:
print("5**4 = {}".format(c))
for d in tab_6:
print("6**4 = {}".format(d))
for e in tab_7:
print("7**4 = {}".format(e))
for f in tab_8:
print("8**4 = {}".format(f))
for g in tab_9:
print("9**4 = {}".format(g))
for h in tab_10:
print("10**4 = {}".format(h))
print ("----------------------------------------------")
# Divisao
tabb = [1/1]
tab = [2/1]
tab_2 = [3/1]
tab_3 = [4/1]
tab_4 = [5/1]
tab_5 = [6/1]
tab_6 = [7/1]
tab_7 = [8/1]
tab_8 = [9/1]
tab_9 = [10/1]
for y in tabb:
print("1/1 = {}".format(y))
for i in tab:
print("2/1 = {:.2f}".format(i))
for a in tab_2:
print("3/1 = {:.2f}".format(a))
for b in tab_3:
print("4/1 = {:.2f}".format(b))
for c in tab_4:
print("5/1 = {:.2f}".format(c))
for d in tab_5:
print("6/1 = {:.2f}".format(d))
for e in tab_6:
print("7/1 = {:.2f}".format(e))
for f in tab_7:
print("8/1 = {:.2f}".format(f))
for g in tab_8:
print("9/1 = {:.2f}".format(g))
for h in tab_9:
print("10/1 = {:.2f}".format(h))
print ("----------------------------------------------")
tab_1 = [1/2]
tab_2 = [2/2]
tab_3 = [3/2]
tab_4 = [4/2]
tab_5 = [5/2]
tab_6 = [6/2]
tab_7 = [7/2]
tab_8 = [8/2]
tab_9 = [9/2]
tab_10 = [10/2]
for y in tab_1:
print("1/2 = {:.2f}".format(y))
for i in tab_2:
print("2/2 = {:.2f}".format(i))
for a in tab_3:
print("3/2 = {:.2f}".format(a))
for b in tab_4:
print("4/2 = {:.2f}".format(b))
for c in tab_5:
print("5/2 = {:.2f}".format(c))
for d in tab_6:
print("6/2 = {:.2f}".format(d))
for e in tab_7:
print("7/2 = {:.2f}".format(e))
for f in tab_8:
print("8/2 = {:.2f}".format(f))
for g in tab_9:
print("9/2 = {:.2f}".format(g))
for h in tab_10:
print("10/2 = {:.2f}".format(h))
print ("----------------------------------------------")
tab_1 = [1/3]
tab_2 = [2/3]
tab_3 = [3/3]
tab_4 = [4/3]
tab_5 = [5/3]
tab_6 = [6/3]
tab_7 = [7/3]
tab_8 = [8/3]
tab_9 = [9/3]
tab_10 = [10/3]
for y in tab_1:
print("1/3 = {:.2f}".format(y))
for i in tab_2:
print("2/3 = {:.2f}".format(i))
for a in tab_3:
print("3/3 = {:.2f}".format(a))
for b in tab_4:
print("4/3 = {:.2f}".format(b))
for c in tab_5:
print("5/3 = {:.2f}".format(c))
for d in tab_6:
print("6/3 = {:.2f}".format(d))
for e in tab_7:
print("7/3 = {:.2f}".format(e))
for f in tab_8:
print("8/3 = {:.2f}".format(f))
for g in tab_9:
print("9/3 = {:.2f}".format(g))
for h in tab_10:
print("10/3 = {:.2f}".format(h))
print ("----------------------------------------------")
tab_1 = [1/4]
tab_2 = [2/4]
tab_3 = [3/4]
tab_4 = [4/4]
tab_5 = [5/4]
tab_6 = [6/4]
tab_7 = [7/4]
tab_8 = [8/4]
tab_9 = [9/4]
tab_10 = [10/4]
for y in tab_1:
print("1/4 = {:.2f}".format(y))
for i in tab_2:
print("2/4 = {:.2f}".format(i))
for a in tab_3:
print("3/4 = {:.2f}".format(a))
for b in tab_4:
print("4/4 = {:.2f}".format(b))
for c in tab_5:
print("5/4 = {:.2f}".format(c))
for d in tab_6:
print("6/4 = {:.2f}".format(d))
for e in tab_7:
print("7/4 = {:.2f}".format(e))
for f in tab_8:
print("8/4 = {:.2f}".format(f))
for g in tab_9:
print("9/4 = {:.2f}".format(g))
for h in tab_10:
print("10/4 = {:.2f}".format(h))
print ("----------------------------------------------")
#Multiplicacao
tabb = [1*1]
tab = [1*2]
tab_2 = [1*3]
tab_3 = [1*4]
tab_4 = [1*5]
tab_5 = [1*6]
tab_6 = [1*7]
tab_7 = [1*8]
tab_8 = [1*9]
tab_9 = [1*10]
for y in tabb:
print("1x1 = {}".format(y))
for i in tab:
print("1x2 = {}".format(i))
for a in tab_2:
print("1x3 = {}".format(a))
for b in tab_3:
print("1x4 = {}".format(b))
for c in tab_4:
print("1x5 = {}".format(c))
for d in tab_5:
print("1x6 = {}".format(d))
for e in tab_6:
print("1x7 = {}".format(e))
for f in tab_7:
print("1x8 = {}".format(f))
for g in tab_8:
print("1x9 = {}".format(g))
for h in tab_9:
print("1x10 = {}".format(h))
print ("----------------------------------------------")
tab_1 = [2*1]
tab_2 = [2*2]
tab_3 = [2*3]
tab_4 = [2*4]
tab_5 = [2*5]
tab_6 = [2*6]
tab_7 = [2*7]
tab_8 = [2*8]
tab_9 = [2*9]
tab_10 = [2*10]
for y in tab_1:
print("2x1 = {}".format(y))
for i in tab_2:
print("2x2 = {}".format(i))
for a in tab_3:
print("2x3 = {}".format(a))
for b in tab_4:
print("2x4 = {}".format(b))
for c in tab_5:
print("2x5 = {}".format(c))
for d in tab_6:
print("2x6 = {}".format(d))
for e in tab_7:
print("2x7 = {}".format(e))
for f in tab_8:
print("2x8 = {}".format(f))
for g in tab_9:
print("2x9 = {}".format(g))
for h in tab_10:
print("2x10 = {}".format(h))
print ("----------------------------------------------")
tab_1 = [3*1]
tab_2 = [3*2]
tab_3 = [3*3]
tab_4 = [3*4]
tab_5 = [3*5]
tab_6 = [3*6]
tab_7 = [3*7]
tab_8 = [3*8]
tab_9 = [3*9]
tab_10 = [3*10]
for y in tab_1:
print("3x1 = {}".format(y))
for i in tab_2:
print("3x2 = {}".format(i))
for a in tab_3:
print("3x3 = {}".format(a))
for b in tab_4:
print("3x4 = {}".format(b))
for c in tab_5:
print("3x5 = {}".format(c))
for d in tab_6:
print("3x6 = {}".format(d))
for e in tab_7:
print("3x7 = {}".format(e))
for f in tab_8:
print("3x8 = {}".format(f))
for g in tab_9:
print("3x9 = {}".format(g))
for h in tab_10:
print("3x10 = {}".format(h))
print ("----------------------------------------------")
tab_1 = [4*1]
tab_2 = [4*2]
tab_3 = [4*3]
tab_4 = [4*4]
tab_5 = [4*5]
tab_6 = [4*6]
tab_7 = [4*7]
tab_8 = [*8]
tab_9 = [4*9]
tab_10 = [4*10]
for y in tab_1:
print("4x1 = {}".format(y))
for i in tab_2:
print("4x2 = {}".format(i))
for a in tab_3:
print("4x3 = {}".format(a))
for b in tab_4:
print("4x4 = {}".format(b))
for c in tab_5:
print("4x5 = {}".format(c))
for d in tab_6:
print("4x6 = {}".format(d))
for e in tab_7:
print("4x7 = {}".format(e))
for f in tab_8:
print("4x8 = {}".format(f))
for g in tab_9:
print("4x9 = {}".format(g))
for h in tab_10:
print("4x10 = {}".format(h))
print ("----------------------------------------------")
| 21.426065 | 60 | 0.476196 | 1,681 | 8,549 | 2.286139 | 0.041642 | 0.152225 | 0.018735 | 0.034348 | 0.898777 | 0.882384 | 0.874577 | 0.850117 | 0.648972 | 0.648972 | 0 | 0.117402 | 0.214879 | 8,549 | 398 | 61 | 21.4799 | 0.455155 | 0.003626 | 0 | 0.354839 | 0 | 0 | 0.20202 | 0.064834 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.354839 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
b199ac04913d3ccae62dae298088f90ff26b752b | 182 | py | Python | apps/users/admin.py | data4e/data4e | d27fa9580b383ff60134d65227ba9f48870cac52 | [
"MIT"
] | null | null | null | apps/users/admin.py | data4e/data4e | d27fa9580b383ff60134d65227ba9f48870cac52 | [
"MIT"
] | null | null | null | apps/users/admin.py | data4e/data4e | d27fa9580b383ff60134d65227ba9f48870cac52 | [
"MIT"
] | null | null | null | from django.contrib import admin
# Register your models here.
from .models import D4eUser
from django.contrib.auth.admin import UserAdmin
admin.site.register(D4eUser, UserAdmin)
| 18.2 | 47 | 0.807692 | 25 | 182 | 5.88 | 0.52 | 0.136054 | 0.231293 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.012579 | 0.126374 | 182 | 9 | 48 | 20.222222 | 0.91195 | 0.142857 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.75 | 0 | 0.75 | 0 | 1 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
b19cc88e75f7ccd3d7c3f1a028d625de6e83b56d | 112 | py | Python | jstests/views.py | nelliesnoodles/my-first-blog | e552ea38891ebe005316487ae32a324659ad6367 | [
"MIT"
] | null | null | null | jstests/views.py | nelliesnoodles/my-first-blog | e552ea38891ebe005316487ae32a324659ad6367 | [
"MIT"
] | 5 | 2019-12-13T17:37:55.000Z | 2021-06-10T20:59:32.000Z | jstests/views.py | nelliesnoodles/My-Website | e552ea38891ebe005316487ae32a324659ad6367 | [
"MIT"
] | null | null | null | from django.shortcuts import render
def run_app(request):
return render(request, 'jstests/JSindex.html')
| 16 | 50 | 0.758929 | 15 | 112 | 5.6 | 0.866667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | 112 | 6 | 51 | 18.666667 | 0.875 | 0 | 0 | 0 | 0 | 0 | 0.178571 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | false | 0 | 0.333333 | 0.333333 | 1 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 6 |
b1ac95fa2b58268d577410ab6a6387bbac815b61 | 23,280 | py | Python | sisppeo/wcproducts/chla.py | inrae/SISPPEO | f516bb778b505739fdf320affe651b715ed75324 | [
"Apache-2.0"
] | 5 | 2021-11-05T09:23:13.000Z | 2022-02-18T10:39:13.000Z | sisppeo/wcproducts/chla.py | inrae/SISPPEO | f516bb778b505739fdf320affe651b715ed75324 | [
"Apache-2.0"
] | null | null | null | sisppeo/wcproducts/chla.py | inrae/SISPPEO | f516bb778b505739fdf320affe651b715ed75324 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 Arthur Coqué, Guillaume Morin, Pôle OFB-INRAE ECLA, UR RECOVER
#
# 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.
"""This module gathers wc algorithms used for estimating Chl-a concentrations.
Each class of this module correspond to one algorithm. An algorithm can have
several calibrations (a calibration is a set of parameters), either
packaged within SISPPEO (these default calibrations are located in
'resources/wc_algo_calibration') or provided by the user.
Before its utilisation, an algorithm has to be instantiate with specific
settings like the product_type of further input products, the calibration
used, the band used (if needed), etc.
Example:
algo1 = CHLAGons('S2_GRS', 'Gons_2004')
out_array1 = algo1(red_array, rededge_array, nir_array, 'rho')
algo2 = CHLAGittelson('L8_GRS', '3_bands', 'Gitelson_2008')
out_array2 = algo2(red_array, rededge_array, nir_array, 'rrs')
"""
from pathlib import Path
from typing import Optional, Union
import numpy as np
import xarray as xr
from sisppeo.utils.algos import load_calib, producttype_to_sat
from sisppeo.utils.config import wc_algo_config as algo_config, wc_calib
from sisppeo.utils.exceptions import InputError
# pylint: disable=invalid-name
# Ok for a custom type.
P = Union[str, Path]
N = Union[int, float]
class CHLAGons:
"""Chlorophyll-a concentration (in mg/m3) from 3 red bands after Gons et al., 1999, 2002, 2004
Red edge algorithm to retrieve Chlorophyll-a concentration (in mg/m3) from
surface reflectances (rho, unitless) or remote sensing reflectances (Rrs,
in sr-1) at 665nm B4 MSI, 704nm B5 MSI and 783nm B7 MSI.
This algorithm was published in Gons et al., 1999, 2002, 2004
Attributes:
name: The name of the algorithm used. This is the key used by
L3AlgoBuilder and that you must provide in config or when using
the CLI.
requested_bands: A list of bands further used by the algorithm.
meta: A dict of metadata (calibration name, model coefficients, etc).
"""
_default_calibration_file = wc_calib / 'chla-gons.yaml'
_default_calibration_name = 'Gons_2004'
name = 'chla-gons'
def __init__(self,
product_type: str,
calibration: Optional[P] = None,
**_ignored) -> None:
"""Inits an 'CHLAGons' instance with specific settings.
Args:
product_type: The type of the input satellite product (e.g.
S2_ESA_L2A or L8_USGS_L1GT)
calibration: Optional; The calibration (set of parameters) used by
the algorithm (default=_default_calibration_name).
**_ignored: Unused kwargs sent to trash.
"""
try:
self.requested_bands = algo_config[self.name][
producttype_to_sat(product_type)]
except KeyError as invalid_product:
msg = f'{product_type} is not allowed with {self.name}'
raise InputError(msg) from invalid_product
calibration_dict, calibration_name = load_calib(
calibration,
self._default_calibration_file,
self._default_calibration_name
)
self._valid_limit = calibration_dict['validity_limit']
try:
params = calibration_dict[producttype_to_sat(product_type)]
except KeyError as invalid_product:
msg = f'{product_type} is not allowed with this calibration'
raise InputError(msg) from invalid_product
self.__dict__.update(params)
self.meta = {'calibration': calibration_name,
'validity_limit': self._valid_limit,
**params}
def __call__(self,
ref_red: xr.DataArray,
ref_rededge: xr.DataArray,
ref_nir: xr.DataArray,
data_type: str,
**_ignored) -> xr.DataArray:
"""Runs the algorithm on the input array ('ref').
Args:
ref_red: An array (dimension 1 * N * M) of 'data_type'.
ref_redegde: An array (dimension 1 * N * M) of 'data_type'.
ref_nir: An array (dimension 1 * N * M) of 'data_type'.
data_type: Either 'ref' or 'rrs' (respectively surface reflectance
and remote sensing reflectance).
**_ignored: Unused kwargs sent to trash.
Returns:
An array (dimension 1 * N * M) of chl-a (in mg/m3).
"""
if data_type == 'rho':
ref_red = ref_red / np.pi
ref_rededge = ref_rededge / np.pi
ref_nir = ref_nir / np.pi
np.warnings.filterwarnings('ignore')
ref_red = ref_red.where(ref_red >= 0)
ref_rededge = ref_rededge.where(ref_red >= 0)
ref_nir = ref_red.where(ref_nir >= 0)
bb783 = ref_nir.where(ref_nir >= 0).copy()
# pylint: disable=no-member
# Loaded in __init__ whit "__dict__.update".
bb783 = (self.a * bb783) / (0.082 - 0.6 * bb783)
aphy = ref_rededge / ref_red * (self.aw705 + bb783) - self.aw665 \
- np.power(bb783, self.p)
chla = aphy / self.aphy_star
chla = chla.where((chla >= 0) & (chla <= self._valid_limit))
return chla
class CHLAGitelson:
"""Chlorophyll-a concentration (in mg/m3) from 3 red bands after Gitelson et al., 2008
Red edge algorithm to retrieve Chlorophyll-a concentration (in mg/m3) from
surface reflectances (rho, unitless) or remote sensing reflectances (Rrs,
in sr-1) at 665nm B4 MSI, 705nm B5 MSI and 740nm B6 MSI.
This algorithm was published in Gitelson et al., 2008
Attributes:
name: The name of the algorithm used. This is the key used by
L3AlgoBuilder and that you must provide in config or when using
the CLI.
requested_bands: A list of bands further used by the algorithm.
meta: A dict of metadata (calibration name, model coefficients, etc).
"""
_default_calibration_file = wc_calib / 'chla-gitelson.yaml'
_default_calibration_name = 'Gitelson_2008'
_default_design = '3_bands'
name = 'chla-gitelson'
def __init__(self,
product_type: str,
design: str = _default_design,
calibration: Optional[P] = None,
**_ignored) -> None:
"""Inits an 'CHLAGitelson' instance with specific settings.
Args:
product_type: The type of the input satellite product (e.g.
S2_ESA_L2A or L8_USGS_L1GT)
calibration: The calibration (set of parameters) used by the
algorithm (default=_default_calibration_name).
**_ignored: Unused kwargs sent to trash.
"""
self._design = design
try:
self.requested_bands = algo_config[self.name][
producttype_to_sat(product_type)]
except KeyError as invalid_product:
msg = f'{product_type} is not allowed with {self.name}'
raise InputError(msg) from invalid_product
calibration_dict, calibration_name = load_calib(
calibration,
self._default_calibration_file,
self._default_calibration_name
)
self._valid_limit = calibration_dict['validity_limit']
try:
params = calibration_dict[producttype_to_sat(product_type)]
except KeyError as invalid_product:
msg = f'{product_type} is not allowed with this calibration'
raise InputError(msg) from invalid_product
self.__dict__.update(params)
self.meta = {'calibration': calibration_name,
'design': design,
'validity_limit': self._valid_limit,
**params}
def __call__(self,
ref_red: xr.DataArray,
ref_rededge: xr.DataArray,
ref_nir: xr.DataArray,
data_type: str,
**_ignored) -> xr.DataArray:
"""Runs the algorithm on the input array ('ref').
Args:
ref_red: An array (dimension 1 * N * M) of 'data_type'.
ref_redegde: An array (dimension 1 * N * M) of 'data_type'.
ref_nir: An array (dimension 1 * N * M) of 'data_type'.
data_type: Either 'rho' or 'rrs' (respectively surface reflectance
and remote sensing reflectance).
**_ignored: Unused kwargs sent to trash.
Returns:
An array (dimension 1 * N * M) of chl-a (in mg/m3).
"""
if data_type == 'rho':
ref_red = ref_red / np.pi
ref_rededge = ref_rededge / np.pi
ref_nir = ref_nir / np.pi
np.warnings.filterwarnings('ignore')
ref_red = ref_red.where(ref_red >= 0)
ref_rededge = ref_rededge.where(ref_red >= 0)
ref_nir = ref_red.where(ref_nir >= 0)
print(self._design, self._valid_limit)
if self._design == '3_bands':
print('3 bands selected')
# pylint: disable=no-member
# Loaded in __init__ whit "__dict__.update".
chla = self.a_3bands + self.b_3bands \
* (1 / ref_red - 1 / ref_rededge) * ref_nir
else:
print('2 bands selected')
# pylint: disable=no-member
# Loaded in __init__ whit "__dict__.update".
chla = self.a_2bands + self.b_2bands * (1 / ref_red) * ref_nir
chla = chla.where((chla >= 0) & (chla <= self._valid_limit))
return chla
class CHLAGurlin:
"""Chlorophyll-a concentration (in mg/m3) from 3 red bands after Gurlin et al., 2011
Red edge algorithm to retrieve Chlorophyll-a concentration (in mg/m3) from
surface reflectances (rho, unitless) or remote sensing reflectances (Rrs,
in sr-1) at 665nm B4 MSI, 704nm B5 MSI and 783nm B7 MSI.
This algorithm was published in Gons et al., 1999, 2002, 2004
Attributes:
name: The name of the algorithm used. This is the key used by
L3AlgoBuilder and that you must provide in config or when using
the CLI.
requested_bands: A list of bands further used by the algorithm.
meta: A dict of metadata (calibration name, model coefficients, etc).
"""
_default_calibration_file = wc_calib / 'chla-gurlin.yaml'
_default_calibration_name = 'Gurlin_2011'
name = 'chla-gurlin'
def __init__(self,
product_type: str,
calibration: Optional[P] = None,
**_ignored) -> None:
"""Inits an 'CHLAGurlin' instance with specific settings.
Args:
product_type: The type of the input satellite product (e.g.
S2_ESA_L2A or L8_USGS_L1GT)
calibration: The calibration (set of parameters) used by the
algorithm (default=_default_calibration_name).
**_ignored: Unused kwargs sent to trash.
"""
try:
self.requested_bands = algo_config[self.name][
producttype_to_sat(product_type)]
except KeyError as invalid_product:
msg = f'{product_type} is not allowed with {self.name}'
raise InputError(msg) from invalid_product
calibration_dict, calibration_name = load_calib(
calibration,
self._default_calibration_file,
self._default_calibration_name
)
self._valid_limit = calibration_dict['validity_limit']
try:
params = calibration_dict[producttype_to_sat(product_type)]
except KeyError as invalid_product:
msg = f'{product_type} is not allowed with this calibration'
raise InputError(msg) from invalid_product
self.__dict__.update(params)
self.meta = {'calibration': calibration_name,
'validity_limit': self._valid_limit,
**params}
def __call__(self,
ref_red: xr.DataArray,
ref_rededge: xr.DataArray,
data_type: str,
**_ignored) -> xr.DataArray:
"""Runs the algorithm on the input array ('ref').
Args:
ref_red: An array (dimension 1 * N * M) of 'data_type'.
ref_redegde: An array (dimension 1 * N * M) of 'data_type'.
data_type: Either 'rho' or 'rrs' (respectively surface reflectance
and remote sensing reflectance).
**_ignored: Unused kwargs sent to trash.
Returns:
An array (dimension 1 * N * M) of chl-a (in mg/m3).
"""
np.warnings.filterwarnings('ignore')
ref_red = ref_red.where(ref_red >= 0)
ref_rededge = ref_rededge.where(ref_red >= 0)
# pylint: disable=no-member
# Loaded in __init__ whit "__dict__.update".
chla = self.a * pow(ref_rededge / ref_red, 2) + self.b \
* (ref_rededge / ref_red) + self.c
chla = chla.where((chla >= 0) & (chla <= self._valid_limit))
return chla
class CHLAOC:
"""Chlorophyll-a concentration (in mg/m3) from polynomial maximum band ratio by O'Reilly et al., 1998 and updates
Blue/green algorithm to retrieve Chlorophyll-a concentration (in mg/m3) from
surface reflectances (rho, unitless) or remote sensing reflectances (Rrs,
in sr-1)
This algorithm was published in O'Reilly 1998, 2000
calibration OC2 for OLI from Franz et al., 2015, OC3 for OLI O'Reilly and Werdell, 2019
MSI Pahlevan et al., 2020 after O'Reilly and Werdell, 2019
Attributes:
name: The name of the algorithm used. This is the key used by
L3AlgoBuilder and that you must provide in config or when using
the CLI.
requested_bands: A list of bands further used by the algorithm.
meta: A dict of metadata (calibration name, model coefficients, etc).
"""
_default_calibration_file = wc_calib / 'chla-oc.yaml'
_default_calibration_name = 'OC3'
name = 'chla-oc'
def __init__(self,
product_type: str,
calibration: Optional[P] = None,
**_ignored) -> None:
"""Inits an 'CHLAOC' instance with specific settings.
Args:
product_type: The type of the input satellite product (e.g.
S2_ESA_L2A or L8_USGS_L1GT)
calibration: The calibration (set of parameters) used by the
algorithm (default=_default_calibration_name).
**_ignored: Unused kwargs sent to trash.
"""
try:
self.requested_bands = algo_config[self.name][
producttype_to_sat(product_type)]
except KeyError as invalid_product:
msg = f'{product_type} is not allowed with {self.name}'
raise InputError(msg) from invalid_product
calibration_dict, calibration_name = load_calib(
calibration,
self._default_calibration_file,
self._default_calibration_name
)
self._valid_limit = calibration_dict['validity_limit']
self._version = calibration_name
try:
params = calibration_dict[producttype_to_sat(product_type)]
except KeyError as invalid_product:
msg = f'{product_type} is not allowed with this calibration'
raise InputError(msg) from invalid_product
self.__dict__.update(params)
self.meta = {'calibration': self._version,
'validity_limit': self._valid_limit,
**params}
def __call__(self,
ref_violet: xr.DataArray,
ref_blue: xr.DataArray,
ref_green: xr.DataArray,
data_type: str,
**_ignored) -> xr.DataArray:
"""Runs the algorithm on the input array ('ref').
Args:
ref_violet: An array (dimension 1 * N * M) of 'data_type'.
ref_blue: An array (dimension 1 * N * M) of 'data_type'.
ref_green: An array (dimension 1 * N * M) of 'data_type'.
data_type: Either 'ref' or 'rrs' (respectively surface reflectance
and remote sensing reflectance).
**_ignored: Unused kwargs sent to trash.
Returns:
An array (dimension 1 * N * M) of chl-a (in mg/m3).
"""
np.warnings.filterwarnings('ignore')
if data_type == 'rho':
ref_violet = ref_violet / np.pi
ref_blue = ref_blue / np.pi
ref_green = ref_green / np.pi
if self._version == 'OC3':
print(f'{self._version} is used')
max_ratio = np.log(np.maximum(ref_violet.values, ref_blue.values)
/ ref_green)
# np.log(max(Rrs_B1, Rrs_B2) / Rrs_B3))
else: # self._version == 'OC2'
print(f'{self._version} is used')
max_ratio = np.log(ref_blue.values / ref_green)
# pylint: disable=no-member
# Loaded in __init__ whit "__dict__.update".
chla = np.power(10, self.a0 + self.a1 * max_ratio + self.a2
* np.power(max_ratio, 2) + self.a3
* np.power(max_ratio, 3) + self.a4
* np.power(max_ratio, 4))
chla = chla.where((chla >= 0) & (chla <= self._valid_limit))
return chla
class CHLALins:
"""Chlorophyll-a concentration (in mg/m3) from NIR/Red bands ratio after Lins et al., 2017
Red edge algorithm to retrieve Chlorophyll-a concentration (in mg/m3) from
surface reflectances (rho, unitless) or remote sensing reflectances (Rrs,
in sr-1) at 665nm B4 MSI, 705nm B5 MSI
This algorithm was published in Lins et al., 2017
Attributes:
name: The name of the algorithm used. This is the key used by
L3AlgoBuilder and that you must provide in config or when using
the CLI.
requested_bands: A list of bands further used by the algorithm.
meta: A dict of metadata (calibration name, model coefficients, etc).
"""
_default_calibration_file = wc_calib / 'chla-lins.yaml'
_default_calibration_name = 'Lins_2017'
name = 'chla-lins'
def __init__(self,
product_type: str,
calibration: Optional[P] = None,
**_ignored) -> None:
"""Inits an 'CHLALins' instance with specific settings.
Args:
product_type: The type of the input satellite product (e.g.
S2_ESA_L2A or L8_USGS_L1GT)
calibration: The calibration (set of parameters) used by the
algorithm (default=_default_calibration_name).
**_ignored: Unused kwargs sent to trash.
"""
try:
self.requested_bands = algo_config[self.name][
producttype_to_sat(product_type)]
except KeyError as invalid_product:
msg = f'{product_type} is not allowed with {self.name}'
raise InputError(msg) from invalid_product
calibration_dict, calibration_name = load_calib(
calibration,
self._default_calibration_file,
self._default_calibration_name
)
self._valid_limit = calibration_dict['validity_limit']
try:
params = calibration_dict[producttype_to_sat(product_type)]
except KeyError as invalid_product:
msg = f'{product_type} is not allowed with this calibration'
raise InputError(msg) from invalid_product
self.__dict__.update(params)
self.meta = {'calibration': calibration_name,
'validity_limit': self._valid_limit,
**params}
def __call__(self,
ref_red: xr.DataArray,
ref_rededge: xr.DataArray,
data_type: str,
**_ignored) -> xr.DataArray:
"""Runs the algorithm on the input array ('ref').
Args:
ref_red: An array (dimension 1 * N * M) of 'data_type'.
ref_redegde: An array (dimension 1 * N * M) of 'data_type'.
data_type: Either 'rho' or 'rrs' (respectively surface reflectance
and remote sensing reflectance).
**_ignored: Unused kwargs sent to trash.
Returns:
An array (dimension 1 * N * M) of chl-a (in mg/m3).
"""
np.warnings.filterwarnings('ignore')
ref_red = ref_red.where(ref_red >= 0)
ref_rededge = ref_rededge.where(ref_red >= 0)
# pylint: disable=no-member
# Loaded in __init__ whit "__dict__.update".
chla = self.p * (ref_rededge / ref_red) + self.q
chla = chla.where((chla >= 0) & (chla <= self._valid_limit))
return chla
class NDCI:
"""Normalized Difference Chlorophyll Index
NDCI from surface reflectances (rho, unitless) or remote sensing reflectances (Rrs,
in sr-1) at 665nm B4 MSI, 704nm B5 MSI
Attributes:
name: The name of the algorithm used. This is the key used by
L3AlgoBuilder and that you must provide in config or when using
the CLI.
requested_bands: A list of bands further used by the algorithm.
meta: An empty dict, since there is no parametrisation for NDWI.
"""
name = 'ndci'
def __init__(self, product_type: str, **_ignored) -> None:
"""Inits an 'Ndci' instance for a given 'product_type'.
Args:
product_type: The type of the input satellite product (e.g.
S2_ESA_L2A or L8_USGS_L1GT)
**_ignored: Unused kwargs send to trash.
"""
try:
self.requested_bands = algo_config[self.name][
producttype_to_sat(product_type)]
except KeyError as unvalid_product:
msg = f'{product_type} is not allowed with {self.name}'
raise InputError(msg) from unvalid_product
self.meta = {}
def __call__(self,
ref_red: xr.DataArray,
ref_nir: xr.DataArray,
**_ignored) -> xr.DataArray:
"""Runs the algorithm on the input array ('ref').
Args:
ref_red: An array (dimension 1 * N * M) of 'data_type'.
ref_nir: An array (dimension 1 * N * M) of 'data_type'.
data_type: Either 'rho' or 'rrs' (respectively surface reflectance
and remote sensing reflectance).
**_ignored: Unused kwargs sent to trash.
Returns:
An array (dimension 1 * N * M) of NDCI values.
"""
np.warnings.filterwarnings('ignore')
red = ref_red.where(ref_red >= 0)
nir = ref_nir.where(ref_nir >= 0)
return (nir - red) / (nir + red)
| 41.276596 | 117 | 0.610095 | 2,910 | 23,280 | 4.67457 | 0.117869 | 0.017643 | 0.0247 | 0.026244 | 0.790855 | 0.777108 | 0.759979 | 0.75329 | 0.747923 | 0.747923 | 0 | 0.020433 | 0.306271 | 23,280 | 563 | 118 | 41.349911 | 0.821858 | 0.438273 | 0 | 0.710037 | 0 | 0 | 0.087775 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.04461 | false | 0 | 0.026022 | 0 | 0.178439 | 0.018587 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
49221b60761c22ead979162f7b816f39e09d56c3 | 122 | py | Python | dataset/__init__.py | VitoPalmisano/MiB_BiSeNet_SEAM_test | 7b74beb69f135c0bb843ee24c90c3097ce448eec | [
"MIT"
] | 105 | 2020-03-20T17:47:00.000Z | 2022-03-16T16:52:07.000Z | dataset/__init__.py | VitoPalmisano/MiB_BiSeNet_SEAM_test | 7b74beb69f135c0bb843ee24c90c3097ce448eec | [
"MIT"
] | 38 | 2020-03-24T18:21:12.000Z | 2022-02-25T17:44:01.000Z | dataset/__init__.py | VitoPalmisano/MiB_BiSeNet_SEAM_test | 7b74beb69f135c0bb843ee24c90c3097ce448eec | [
"MIT"
] | 28 | 2020-04-27T18:44:37.000Z | 2022-03-28T22:43:54.000Z | from .voc import VOCSegmentation, VOCSegmentationIncremental
from .ade import AdeSegmentation, AdeSegmentationIncremental
| 40.666667 | 60 | 0.885246 | 10 | 122 | 10.8 | 0.8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.081967 | 122 | 2 | 61 | 61 | 0.964286 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 6 |
492659b4fc6193e63ccecdd23ff64e0fdfd35ff0 | 1,219 | py | Python | geomat/stein/migrations/0041_auto_20171102_1755_squashed_0042_auto_20171105_1732.py | mimischi/django-geomat | 8c5bc4c9ba9759b58b52ddf339ccaec40ec5f6ea | [
"BSD-3-Clause"
] | 3 | 2017-01-13T15:53:39.000Z | 2017-05-05T11:57:55.000Z | geomat/stein/migrations/0041_auto_20171102_1755_squashed_0042_auto_20171105_1732.py | mimischi/django-geomat | 8c5bc4c9ba9759b58b52ddf339ccaec40ec5f6ea | [
"BSD-3-Clause"
] | 233 | 2016-11-05T15:19:48.000Z | 2021-09-07T23:33:47.000Z | geomat/stein/migrations/0041_auto_20171102_1755_squashed_0042_auto_20171105_1732.py | GeoMatDigital/django-geomat | 8c5bc4c9ba9759b58b52ddf339ccaec40ec5f6ea | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-05 16:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stein', '0040_auto_20171105_1439'),
]
operations = [
migrations.AlterField(
model_name='quizanswer',
name='feedback_correct',
field=models.CharField(blank=True, max_length=500, null=True, verbose_name='feedback if answered correctly'),
),
migrations.AlterField(
model_name='quizanswer',
name='feedback_incorrect',
field=models.CharField(blank=True, max_length=500, null=True, verbose_name='feedback if answered incorrectly'),
),
migrations.AlterField(
model_name='quizanswer',
name='feedback_correct',
field=models.CharField(blank=True, default='', max_length=500, verbose_name='feedback if answered correctly'),
),
migrations.AlterField(
model_name='quizanswer',
name='feedback_incorrect',
field=models.CharField(blank=True, default='', max_length=500, verbose_name='feedback if answered incorrectly'),
),
]
| 33.861111 | 124 | 0.626743 | 126 | 1,219 | 5.912698 | 0.388889 | 0.128859 | 0.134228 | 0.155705 | 0.786577 | 0.786577 | 0.757047 | 0.757047 | 0.757047 | 0.757047 | 0 | 0.049614 | 0.255948 | 1,219 | 35 | 125 | 34.828571 | 0.771775 | 0.055783 | 0 | 0.592593 | 1 | 0 | 0.226481 | 0.020035 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.037037 | 0 | 0.148148 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.