hexsha
stringlengths
40
40
size
int64
3
1.03M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
972
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
972
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
972
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
3
1.03M
avg_line_length
float64
1.13
941k
max_line_length
int64
2
941k
alphanum_fraction
float64
0
1
e6edb34e4b9936953cdd1f4cc012f2bb515d8363
1,117
py
Python
billy/importers/metadata.py
paultag/billy
70f4c55d760552829a86b30baa6d6eac3f6dc47f
[ "BSD-3-Clause" ]
null
null
null
billy/importers/metadata.py
paultag/billy
70f4c55d760552829a86b30baa6d6eac3f6dc47f
[ "BSD-3-Clause" ]
null
null
null
billy/importers/metadata.py
paultag/billy
70f4c55d760552829a86b30baa6d6eac3f6dc47f
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python import datetime import importlib from billy.core import db PRESERVED_FIELDS = ('latest_json_url', 'latest_json_date', 'latest_csv_url', 'latest_csv_date') def import_metadata(abbr): preserved = {} old_metadata = db.metadata.find_one({'_id': abbr}) or {} for field in PRESERVED_FIELDS: if field in old_metadata: preserved[field] = old_metadata[field] module = importlib.import_module(abbr) metadata = module.metadata metadata['_type'] = 'metadata' for term in metadata['terms']: for k, v in term.iteritems(): if isinstance(v, datetime.date): term[k] = datetime.datetime.combine(v, datetime.time(0, 0)) for session in metadata['session_details'].values(): for k, v in session.iteritems(): if isinstance(v, datetime.date): session[k] = datetime.datetime.combine(v, datetime.time(0, 0)) metadata['_id'] = abbr metadata.update(preserved) metadata['latest_update'] = datetime.datetime.utcnow() db.metadata.save(metadata, safe=True)
30.189189
78
0.644584
44e3e23a653db8efa1013dd18d9932be58c27888
506
py
Python
mysite/comment/migrations/0002_auto_20180824_1532.py
SuperWenFirst/Django-Course
8cc6cabe7789117f37e009db842b8f8e41d8e5a5
[ "CNRI-Python" ]
35
2019-03-28T13:57:01.000Z
2022-03-18T11:29:53.000Z
mysite/comment/migrations/0002_auto_20180824_1532.py
SuperWenFirst/Django-Course
8cc6cabe7789117f37e009db842b8f8e41d8e5a5
[ "CNRI-Python" ]
null
null
null
mysite/comment/migrations/0002_auto_20180824_1532.py
SuperWenFirst/Django-Course
8cc6cabe7789117f37e009db842b8f8e41d8e5a5
[ "CNRI-Python" ]
18
2019-04-10T06:50:46.000Z
2022-03-18T11:30:07.000Z
# Generated by Django 2.0.5 on 2018-08-24 07:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('comment', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='comment', options={'ordering': ['-comment_time']}, ), migrations.AddField( model_name='comment', name='parent_id', field=models.IntegerField(default=0), ), ]
22
52
0.565217
e373497f5be0d3e0307ef679df6f121e4eb06a6b
642
py
Python
haas_lib_bundles/python/libraries/servo/servo.py
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
null
null
null
haas_lib_bundles/python/libraries/servo/servo.py
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
null
null
null
haas_lib_bundles/python/libraries/servo/servo.py
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
null
null
null
""" HaaSPython PWM driver for servo """ from driver import PWM class SERVO(object): def __init__(self, pwmObj): self.pwmObj = None if not isinstance(pwmObj, PWM): raise ValueError("parameter is not an PWM object") self.pwmObj = pwmObj def setOptionSero(self,data): if self.pwmObj is None: raise ValueError("invalid PWM object") data_r = {'freq':50, 'duty': int(((data+90)*2/180+0.5)/20*100)} self.pwmObj.setOption(data_r) def close(self): if self.pwmObj is None: raise ValueError("invalid PWM object") self.pwmObj.close()
22.928571
71
0.602804
7ad959726c43fc81d4c889254bc4e93f7c09c5b7
4,581
py
Python
third_party/wrappers/sal_wrapper/ut_sal.py
ITh4cker/auto_tools
8e0e00cdf8bf60ee3f26fa5ae8f18c376298d0aa
[ "Apache-2.0" ]
null
null
null
third_party/wrappers/sal_wrapper/ut_sal.py
ITh4cker/auto_tools
8e0e00cdf8bf60ee3f26fa5ae8f18c376298d0aa
[ "Apache-2.0" ]
null
null
null
third_party/wrappers/sal_wrapper/ut_sal.py
ITh4cker/auto_tools
8e0e00cdf8bf60ee3f26fa5ae8f18c376298d0aa
[ "Apache-2.0" ]
1
2021-06-16T07:32:17.000Z
2021-06-16T07:32:17.000Z
import sys,os import unittest from sa import * from sa_sal_api import * SAL_ENGINE_FILE = './ut_data/lib/libtmsa.so' SAL_CONFIG_FILE = './ut_data/ptn/tmsa.cfg' SAL_LOG_FILE = './ut_data/tmsa.log' URL = 'http://www.abcxEsoxikdaxcis.com' scanner = SALScanner(SAL_CONFIG_FILE, SAL_LOG_FILE) def sample(rpath): return os.path.join("./ut_data/sample", rpath) class TestDecision(unittest.TestCase): ''' ''' def test_normal(self): page = Page(URL, content_file=sample("normal.html")) result = scanner.scan(page) self.assertEqual(SA_DECISION_NORMAL, result.get_decision()) def test_monitoring(self): page = Page(URL, content_file=sample("06bd.html")) result = scanner.scan(page) self.assertEqual(SA_DECISION_MONITORING, result.get_decision()) info = result.to_feedback_info() self.assertEqual('MONITORING', info['decision']) def test_malicious(self): page = Page(URL, content_file=sample("cd9a.html")) result = scanner.scan(page) self.assertEqual(SA_DECISION_MALICIOUS, result.get_decision()) info = result.to_feedback_info() self.assertEqual('MALICIOUS', info['decision']) class TestCategory(unittest.TestCase): def test_exploit(self): page = Page(URL, content_file=sample("cd9a.html")) result = scanner.scan(page) self.assertEqual(SA_CATEGORY_EXPLOIT, result.get_category()) def test_phishing(self): page = Page(URL, content_file=sample("paypal2.htm")) result = scanner.scan(page) self.assertEqual(SA_CATEGORY_PHISHING, result.get_category()) class TestFiletype(unittest.TestCase): def test_html(self): page = Page(URL, content_file=sample("cd9a.html")) result = scanner.scan(page) self.assertEqual(u"html", page.get_filetype()) def test_pdf(self): page = Page(URL, content_file=sample("038b.pdf")) result = scanner.scan(page) self.assertEqual(u"pdf", page.get_filetype()) def test_swf(self): page = Page(URL, content_file=sample("7cf6.swf")) result = scanner.scan(page) self.assertEqual(u"swf", page.get_filetype()) def test_java(self): page = Page(URL, content_file=sample("06a4.jar")) result = scanner.scan(page) self.assertEqual(u"jar", page.get_filetype()) class TestRules(unittest.TestCase): def test_basic(self): page = Page(URL, content_file=sample("cd9a.html")) result = scanner.scan(page) self.assertEqual([u'Dynamic Script/Generic/JS.GenericCK.A', u'Dynamic Script/Specific/JS.BlackholeKit.F', u'Dynamic Script/Specific/JS.CoolEK.D', u'Dynamic Script/Specific/JS.GenericEK.A', u'Dynamic Script/Specific/JS.BlackholeKit.M'], result.get_rules()) info = result.to_feedback_info() self.assertEqual(";".join( [u'Dynamic Script/Generic/JS.GenericCK.A', u'Dynamic Script/Specific/JS.BlackholeKit.F', u'Dynamic Script/Specific/JS.CoolEK.D', u'Dynamic Script/Specific/JS.GenericEK.A', u'Dynamic Script/Specific/JS.BlackholeKit.M']), info['rule']) def test_java_rule(self): page = Page(URL, content_file=sample("06a4.jar")) result = scanner.scan(page) self.assertEqual([u'cve-2013-1493.1', u'cve-2013-1493.2'], result.get_rules()) info = result.to_feedback_info() self.assertEqual(";".join( [u'cve-2013-1493.1', u'cve-2013-1493.2']), info['rule']) class TestModule(unittest.TestCase): def test_basic(self): page = Page(URL, content_file=sample("cd9a.html")) result = scanner.scan(page) self.assertEqual(u"DynamicScriptAnalyzer", result.get_module()) info = result.to_feedback_info() self.assertEqual('SAL/DynamicScriptAnalyzer', info['module']) class TestDynamicLinks(unittest.TestCase): def test_html(self): page = Page(URL, content_file=sample("gsb01.html")) result = scanner.scan(page) self.assertEqual([u'http://www.imlink.com/a.js'], page.get_dynamic_links()) if __name__=="__main__": unittest.main()
36.648
84
0.602925
8e09e31232efa1037b1f76d7718e8c3152742fef
173
py
Python
src/platform/weblogic/fingerprints/WL11.py
0x27/clusterd
0f04a4955c61aa523274e9ae35d750f4339b1e59
[ "MIT" ]
539
2015-01-08T23:59:32.000Z
2022-03-29T17:53:02.000Z
src/platform/weblogic/fingerprints/WL11.py
M31MOTH/clusterd
d190b2cbaa93820e928a7ce5471c661d4559fb7c
[ "MIT" ]
21
2015-01-17T21:51:21.000Z
2019-09-20T09:23:18.000Z
src/platform/weblogic/fingerprints/WL11.py
M31MOTH/clusterd
d190b2cbaa93820e928a7ce5471c661d4559fb7c
[ "MIT" ]
192
2015-01-26T20:44:14.000Z
2021-12-22T01:39:50.000Z
from src.platform.weblogic.interfaces import WLConsole class FPrint(WLConsole): def __init__(self): super(FPrint, self).__init__() self.version = "11"
21.625
54
0.687861
b73ba8d8419bbabfe1e4d29a255b3fbe909c33f0
4,082
py
Python
test/vanilla/Expected/AcceptanceTests/Http/httpinfrastructure/aio/_auto_rest_http_infrastructure_test_service.py
tasherif-msft/autorest.python
5b0121bcfa802aedaeda36990e8bcaa2b7e26b14
[ "MIT" ]
null
null
null
test/vanilla/Expected/AcceptanceTests/Http/httpinfrastructure/aio/_auto_rest_http_infrastructure_test_service.py
tasherif-msft/autorest.python
5b0121bcfa802aedaeda36990e8bcaa2b7e26b14
[ "MIT" ]
null
null
null
test/vanilla/Expected/AcceptanceTests/Http/httpinfrastructure/aio/_auto_rest_http_infrastructure_test_service.py
tasherif-msft/autorest.python
5b0121bcfa802aedaeda36990e8bcaa2b7e26b14
[ "MIT" ]
null
null
null
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, Optional from azure.core import AsyncPipelineClient from msrest import Deserializer, Serializer from ._configuration import AutoRestHttpInfrastructureTestServiceConfiguration from .operations import HttpFailureOperations from .operations import HttpSuccessOperations from .operations import HttpRedirectsOperations from .operations import HttpClientFailureOperations from .operations import HttpServerFailureOperations from .operations import HttpRetryOperations from .operations import MultipleResponsesOperations from .. import models class AutoRestHttpInfrastructureTestService(object): """Test Infrastructure for AutoRest. :ivar http_failure: HttpFailureOperations operations :vartype http_failure: httpinfrastructure.aio.operations.HttpFailureOperations :ivar http_success: HttpSuccessOperations operations :vartype http_success: httpinfrastructure.aio.operations.HttpSuccessOperations :ivar http_redirects: HttpRedirectsOperations operations :vartype http_redirects: httpinfrastructure.aio.operations.HttpRedirectsOperations :ivar http_client_failure: HttpClientFailureOperations operations :vartype http_client_failure: httpinfrastructure.aio.operations.HttpClientFailureOperations :ivar http_server_failure: HttpServerFailureOperations operations :vartype http_server_failure: httpinfrastructure.aio.operations.HttpServerFailureOperations :ivar http_retry: HttpRetryOperations operations :vartype http_retry: httpinfrastructure.aio.operations.HttpRetryOperations :ivar multiple_responses: MultipleResponsesOperations operations :vartype multiple_responses: httpinfrastructure.aio.operations.MultipleResponsesOperations :param str base_url: Service URL """ def __init__( self, base_url: Optional[str] = None, **kwargs: Any ) -> None: if not base_url: base_url = 'http://localhost:3000' self._config = AutoRestHttpInfrastructureTestServiceConfiguration(**kwargs) self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) self.http_failure = HttpFailureOperations( self._client, self._config, self._serialize, self._deserialize) self.http_success = HttpSuccessOperations( self._client, self._config, self._serialize, self._deserialize) self.http_redirects = HttpRedirectsOperations( self._client, self._config, self._serialize, self._deserialize) self.http_client_failure = HttpClientFailureOperations( self._client, self._config, self._serialize, self._deserialize) self.http_server_failure = HttpServerFailureOperations( self._client, self._config, self._serialize, self._deserialize) self.http_retry = HttpRetryOperations( self._client, self._config, self._serialize, self._deserialize) self.multiple_responses = MultipleResponsesOperations( self._client, self._config, self._serialize, self._deserialize) async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "AutoRestHttpInfrastructureTestService": await self._client.__aenter__() return self async def __aexit__(self, *exc_details) -> None: await self._client.__aexit__(*exc_details)
48.595238
95
0.740078
30685c639f7cc6e520eaa86ae20b8ba0e61d4a9b
515
py
Python
apps/odoo/lib/odoo-10.0.post20170615-py2.7.egg/odoo/addons/website_crm/__manifest__.py
gtfarng/Odoo_migrade
9cc28fae4c379e407645248a29d22139925eafe7
[ "Apache-2.0" ]
1
2019-12-19T01:53:13.000Z
2019-12-19T01:53:13.000Z
apps/odoo/lib/odoo-10.0.post20170615-py2.7.egg/odoo/addons/website_crm/__manifest__.py
gtfarng/Odoo_migrade
9cc28fae4c379e407645248a29d22139925eafe7
[ "Apache-2.0" ]
null
null
null
apps/odoo/lib/odoo-10.0.post20170615-py2.7.egg/odoo/addons/website_crm/__manifest__.py
gtfarng/Odoo_migrade
9cc28fae4c379e407645248a29d22139925eafe7
[ "Apache-2.0" ]
null
null
null
{ 'name': 'Contact Form', 'category': 'Website', 'website': 'https://www.odoo.com/page/website-builder', 'summary': 'Create Leads From Contact Form', 'version': '2.0', 'description': """ Odoo Contact Form ==================== """, 'depends': ['website_form', 'website_partner', 'crm'], 'data': [ 'data/website_crm_data.xml', 'views/website_crm_templates.xml', ], 'qweb': ['static/src/xml/*.xml'], 'installable': True, 'auto_install': True, }
24.52381
59
0.545631
629c283dcd2b4afa6aac41ac1729afe70c17590c
601
py
Python
tests/test_local_recall.py
aliabd/GEM-metrics
4f5b389c447bcbecb5a407df93ec8c8ace1e9ce8
[ "MIT" ]
1
2021-04-18T22:09:34.000Z
2021-04-18T22:09:34.000Z
tests/test_local_recall.py
maybay21/GEM-metrics
2693f3439547a40897bc30c2ab70e27e992883c0
[ "MIT" ]
null
null
null
tests/test_local_recall.py
maybay21/GEM-metrics
2693f3439547a40897bc30c2ab70e27e992883c0
[ "MIT" ]
1
2021-04-07T17:54:57.000Z
2021-04-07T17:54:57.000Z
import unittest import gem_metrics from tests.test_referenced import TestReferencedMetric class TestLocalRecall(TestReferencedMetric, unittest.TestCase): def setUp(self): super().setUp() self.metric = gem_metrics.local_recall.LocalRecall() self.true_results_basic = {'local_recall': {1: 0.6451612903225806}} self.true_results_identical_pred_ref = {'local_recall': {1: 1.0}} self.true_results_mismatched_pred_ref = {'local_recall': {1: 0.0}} self.true_results_empty_pred = {'local_recall': {1: 0.0}} if __name__ == '__main__': unittest.main()
35.352941
75
0.712146
1848bbfa0ace969e34f3c4941bf90468f8a82c24
5,468
py
Python
tests/testhelper.py
pl77/sabnzbd
7e87a0c759944966ce7318134d8ed89b569ae73f
[ "0BSD", "PSF-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause" ]
null
null
null
tests/testhelper.py
pl77/sabnzbd
7e87a0c759944966ce7318134d8ed89b569ae73f
[ "0BSD", "PSF-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause" ]
null
null
null
tests/testhelper.py
pl77/sabnzbd
7e87a0c759944966ce7318134d8ed89b569ae73f
[ "0BSD", "PSF-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause" ]
null
null
null
#!/usr/bin/python3 -OO # Copyright 2007-2019 The SABnzbd-Team <team@sabnzbd.org> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ tests.testhelper - Basic helper functions """ import os import time import unittest import pytest import requests from selenium import webdriver from selenium.common.exceptions import WebDriverException from selenium.webdriver.chrome.options import Options as ChromeOptions from selenium.webdriver.firefox.options import Options as FirefoxOptions from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait import sabnzbd import sabnzbd.cfg as cfg SAB_HOST = "localhost" SAB_PORT = 8081 SAB_BASE_DIR = os.path.dirname(os.path.abspath(__file__)) SAB_CACHE_DIR = os.path.join(SAB_BASE_DIR, "cache") SAB_COMPLETE_DIR = os.path.join(SAB_CACHE_DIR, "Downloads", "complete") def set_config(settings_dict): """ Change config-values on the fly, per test""" def set_config_decorator(func): def wrapper_func(*args, **kwargs): # Setting up as requested for item, val in settings_dict.items(): getattr(cfg, item).set(val) # Perform test value = func(*args, **kwargs) # Reset values for item, val in settings_dict.items(): getattr(cfg, item).default() return value return wrapper_func return set_config_decorator def set_platform(platform): """ Change config-values on the fly, per test""" def set_platform_decorator(func): def wrapper_func(*args, **kwargs): # Save original values is_windows = sabnzbd.WIN32 is_darwin = sabnzbd.DARWIN # Set current platform if platform == "win32": sabnzbd.WIN32 = True sabnzbd.DARWIN = False elif platform == "darwin": sabnzbd.WIN32 = False sabnzbd.DARWIN = True elif platform == "linux": sabnzbd.WIN32 = False sabnzbd.DARWIN = False # Perform test value = func(*args, **kwargs) # Reset values sabnzbd.WIN32 = is_windows sabnzbd.DARWIN = is_darwin return value return wrapper_func return set_platform_decorator def get_url_result(url="", host=SAB_HOST, port=SAB_PORT): """ Do basic request to web page """ arguments = {"session": "apikey"} return requests.get("http://%s:%s/%s/" % (host, port, url), params=arguments).text def get_api_result(mode, host=SAB_HOST, port=SAB_PORT, extra_arguments={}): """ Build JSON request to SABnzbd """ arguments = {"apikey": "apikey", "output": "json", "mode": mode} arguments.update(extra_arguments) r = requests.get("http://%s:%s/api" % (host, port), params=arguments) return r.json() def upload_nzb(filename, host=SAB_HOST, port=SAB_PORT): """ Upload file and return nzo_id reponse """ files = {"name": open(filename, "rb")} arguments = {"apikey": "apikey", "mode": "addfile", "output": "json"} return requests.post("http://%s:%s/api" % (host, port), files=files, data=arguments).json() @pytest.mark.usefixtures("start_sabnzbd") class SABnzbdBaseTest(unittest.TestCase): @classmethod def setUpClass(cls): # We only try Chrome for consistent results driver_options = ChromeOptions() # Headless on Appveyor/Travis if "CI" in os.environ: driver_options.add_argument("--headless") driver_options.add_argument("--no-sandbox") cls.driver = webdriver.Chrome(options=driver_options) # Get the newsserver-info, if available if "SAB_NEWSSERVER_HOST" in os.environ: cls.newsserver_host = os.environ["SAB_NEWSSERVER_HOST"] cls.newsserver_user = os.environ["SAB_NEWSSERVER_USER"] cls.newsserver_password = os.environ["SAB_NEWSSERVER_PASSWORD"] @classmethod def tearDownClass(cls): cls.driver.close() cls.driver.quit() def no_page_crash(self): # Do a base test if CherryPy did not report test self.assertNotIn("500 Internal Server Error", self.driver.title) def open_page(self, url): # Open a page and test for crash self.driver.get(url) self.no_page_crash() def scroll_to_top(self): self.driver.find_element_by_tag_name("body").send_keys(Keys.CONTROL + Keys.HOME) time.sleep(2) def wait_for_ajax(self): wait = WebDriverWait(self.driver, 15) wait.until(lambda driver_wait: self.driver.execute_script("return jQuery.active") == 0) wait.until(lambda driver_wait: self.driver.execute_script("return document.readyState") == "complete")
33.546012
110
0.662765
21be45fb11826b55a18561d81b70bcb04cb740b9
9,975
py
Python
tests/backends/sqlite/tests.py
imjvdn/scratch-game-1
5dffd79f17e0b66d3d2e57262749311aca28e850
[ "PSF-2.0", "BSD-3-Clause" ]
13
2015-04-17T02:12:15.000Z
2021-12-08T19:45:36.000Z
tests/backends/sqlite/tests.py
imjvdn/scratch-game-1
5dffd79f17e0b66d3d2e57262749311aca28e850
[ "PSF-2.0", "BSD-3-Clause" ]
10
2016-05-19T21:54:42.000Z
2019-08-09T15:59:50.000Z
tests/backends/sqlite/tests.py
imjvdn/scratch-game-1
5dffd79f17e0b66d3d2e57262749311aca28e850
[ "PSF-2.0", "BSD-3-Clause" ]
11
2019-09-14T20:57:30.000Z
2022-01-19T17:59:26.000Z
import re import threading import unittest from sqlite3 import dbapi2 from unittest import mock from django.core.exceptions import ImproperlyConfigured from django.db import connection, transaction from django.db.models import Avg, StdDev, Sum, Variance from django.db.models.aggregates import Aggregate from django.db.models.fields import CharField from django.db.utils import NotSupportedError from django.test import ( TestCase, TransactionTestCase, override_settings, skipIfDBFeature, ) from django.test.utils import isolate_apps from ..models import Author, Item, Object, Square try: from django.db.backends.sqlite3.base import check_sqlite_version except ImproperlyConfigured: # Ignore "SQLite is too old" when running tests on another database. pass @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests') class Tests(TestCase): longMessage = True def test_check_sqlite_version(self): msg = 'SQLite 3.8.3 or later is required (found 3.8.2).' with mock.patch.object(dbapi2, 'sqlite_version_info', (3, 8, 2)), \ mock.patch.object(dbapi2, 'sqlite_version', '3.8.2'), \ self.assertRaisesMessage(ImproperlyConfigured, msg): check_sqlite_version() def test_aggregation(self): """ Raise NotImplementedError when aggregating on date/time fields (#19360). """ for aggregate in (Sum, Avg, Variance, StdDev): with self.assertRaises(NotSupportedError): Item.objects.all().aggregate(aggregate('time')) with self.assertRaises(NotSupportedError): Item.objects.all().aggregate(aggregate('date')) with self.assertRaises(NotSupportedError): Item.objects.all().aggregate(aggregate('last_modified')) with self.assertRaises(NotSupportedError): Item.objects.all().aggregate( **{'complex': aggregate('last_modified') + aggregate('last_modified')} ) def test_distinct_aggregation(self): class DistinctAggregate(Aggregate): allow_distinct = True aggregate = DistinctAggregate('first', 'second', distinct=True) msg = ( "SQLite doesn't support DISTINCT on aggregate functions accepting " "multiple arguments." ) with self.assertRaisesMessage(NotSupportedError, msg): connection.ops.check_expression_support(aggregate) def test_memory_db_test_name(self): """A named in-memory db should be allowed where supported.""" from django.db.backends.sqlite3.base import DatabaseWrapper settings_dict = { 'TEST': { 'NAME': 'file:memorydb_test?mode=memory&cache=shared', } } creation = DatabaseWrapper(settings_dict).creation self.assertEqual(creation._get_test_db_name(), creation.connection.settings_dict['TEST']['NAME']) def test_regexp_function(self): tests = ( ('test', r'[0-9]+', False), ('test', r'[a-z]+', True), ('test', None, None), (None, r'[a-z]+', None), (None, None, None), ) for string, pattern, expected in tests: with self.subTest((string, pattern)): with connection.cursor() as cursor: cursor.execute('SELECT %s REGEXP %s', [string, pattern]) value = cursor.fetchone()[0] value = bool(value) if value in {0, 1} else value self.assertIs(value, expected) @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests') @isolate_apps('backends') class SchemaTests(TransactionTestCase): available_apps = ['backends'] def test_autoincrement(self): """ auto_increment fields are created with the AUTOINCREMENT keyword in order to be monotonically increasing (#10164). """ with connection.schema_editor(collect_sql=True) as editor: editor.create_model(Square) statements = editor.collected_sql match = re.search('"id" ([^,]+),', statements[0]) self.assertIsNotNone(match) self.assertEqual( 'integer NOT NULL PRIMARY KEY AUTOINCREMENT', match.group(1), 'Wrong SQL used to create an auto-increment column on SQLite' ) def test_disable_constraint_checking_failure_disallowed(self): """ SQLite schema editor is not usable within an outer transaction if foreign key constraint checks are not disabled beforehand. """ msg = ( 'SQLite schema editor cannot be used while foreign key ' 'constraint checks are enabled. Make sure to disable them ' 'before entering a transaction.atomic() context because ' 'SQLite does not support disabling them in the middle of ' 'a multi-statement transaction.' ) with self.assertRaisesMessage(NotSupportedError, msg): with transaction.atomic(), connection.schema_editor(atomic=True): pass def test_constraint_checks_disabled_atomic_allowed(self): """ SQLite schema editor is usable within an outer transaction as long as foreign key constraints checks are disabled beforehand. """ def constraint_checks_enabled(): with connection.cursor() as cursor: return bool(cursor.execute('PRAGMA foreign_keys').fetchone()[0]) with connection.constraint_checks_disabled(), transaction.atomic(): with connection.schema_editor(atomic=True): self.assertFalse(constraint_checks_enabled()) self.assertFalse(constraint_checks_enabled()) self.assertTrue(constraint_checks_enabled()) @skipIfDBFeature('supports_atomic_references_rename') def test_field_rename_inside_atomic_block(self): """ NotImplementedError is raised when a model field rename is attempted inside an atomic block. """ new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name('renamed') msg = ( "Renaming the 'backends_author'.'name' column while in a " "transaction is not supported on SQLite < 3.26 because it would " "break referential integrity. Try adding `atomic = False` to the " "Migration class." ) with self.assertRaisesMessage(NotSupportedError, msg): with connection.schema_editor(atomic=True) as editor: editor.alter_field(Author, Author._meta.get_field('name'), new_field) @skipIfDBFeature('supports_atomic_references_rename') def test_table_rename_inside_atomic_block(self): """ NotImplementedError is raised when a table rename is attempted inside an atomic block. """ msg = ( "Renaming the 'backends_author' table while in a transaction is " "not supported on SQLite < 3.26 because it would break referential " "integrity. Try adding `atomic = False` to the Migration class." ) with self.assertRaisesMessage(NotSupportedError, msg): with connection.schema_editor(atomic=True) as editor: editor.alter_db_table(Author, "backends_author", "renamed_table") @unittest.skipUnless(connection.vendor == 'sqlite', 'Test only for SQLite') @override_settings(DEBUG=True) class LastExecutedQueryTest(TestCase): def test_no_interpolation(self): # This shouldn't raise an exception (#17158) query = "SELECT strftime('%Y', 'now');" connection.cursor().execute(query) self.assertEqual(connection.queries[-1]['sql'], query) def test_parameter_quoting(self): # The implementation of last_executed_queries isn't optimal. It's # worth testing that parameters are quoted (#14091). query = "SELECT %s" params = ["\"'\\"] connection.cursor().execute(query, params) # Note that the single quote is repeated substituted = "SELECT '\"''\\'" self.assertEqual(connection.queries[-1]['sql'], substituted) def test_large_number_of_parameters(self): # If SQLITE_MAX_VARIABLE_NUMBER (default = 999) has been changed to be # greater than SQLITE_MAX_COLUMN (default = 2000), last_executed_query # can hit the SQLITE_MAX_COLUMN limit (#26063). with connection.cursor() as cursor: sql = "SELECT MAX(%s)" % ", ".join(["%s"] * 2001) params = list(range(2001)) # This should not raise an exception. cursor.db.ops.last_executed_query(cursor.cursor, sql, params) @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests') class EscapingChecks(TestCase): """ All tests in this test case are also run with settings.DEBUG=True in EscapingChecksDebug test case, to also test CursorDebugWrapper. """ def test_parameter_escaping(self): # '%s' escaping support for sqlite3 (#13648). with connection.cursor() as cursor: cursor.execute("select strftime('%s', date('now'))") response = cursor.fetchall()[0][0] # response should be an non-zero integer self.assertTrue(int(response)) @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests') @override_settings(DEBUG=True) class EscapingChecksDebug(EscapingChecks): pass @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests') class ThreadSharing(TransactionTestCase): available_apps = ['backends'] def test_database_sharing_in_threads(self): def create_object(): Object.objects.create() create_object() thread = threading.Thread(target=create_object) thread.start() thread.join() self.assertEqual(Object.objects.count(), 2)
41.049383
105
0.649724
898776d2c6d530043dec0a43ca203dd726805c07
449
py
Python
alipay/aop/api/response/AlipayEcoEprintPrinterDeleteResponse.py
antopen/alipay-sdk-python-all
8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c
[ "Apache-2.0" ]
213
2018-08-27T16:49:32.000Z
2021-12-29T04:34:12.000Z
alipay/aop/api/response/AlipayEcoEprintPrinterDeleteResponse.py
antopen/alipay-sdk-python-all
8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c
[ "Apache-2.0" ]
29
2018-09-29T06:43:00.000Z
2021-09-02T03:27:32.000Z
alipay/aop/api/response/AlipayEcoEprintPrinterDeleteResponse.py
antopen/alipay-sdk-python-all
8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c
[ "Apache-2.0" ]
59
2018-08-27T16:59:26.000Z
2022-03-25T10:08:15.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayEcoEprintPrinterDeleteResponse(AlipayResponse): def __init__(self): super(AlipayEcoEprintPrinterDeleteResponse, self).__init__() def parse_response_content(self, response_content): response = super(AlipayEcoEprintPrinterDeleteResponse, self).parse_response_content(response_content)
28.0625
109
0.783964
aff50b0b3b5e8ab66d00220c6daa7c88157bcba2
2,569
py
Python
repo_health/utils.py
ifinanceCanada/edx-repo-health
4fb9944e084cbaaf171de6b30a98ddf2946a02e5
[ "Apache-2.0" ]
null
null
null
repo_health/utils.py
ifinanceCanada/edx-repo-health
4fb9944e084cbaaf171de6b30a98ddf2946a02e5
[ "Apache-2.0" ]
null
null
null
repo_health/utils.py
ifinanceCanada/edx-repo-health
4fb9944e084cbaaf171de6b30a98ddf2946a02e5
[ "Apache-2.0" ]
null
null
null
""" Utility Functions """ import functools import operator import os from datetime import datetime GITHUB_DATETIME_FMT = "%Y-%m-%dT%H:%M:%SZ" def file_exists(repo_path, file_name): full_path = os.path.join(repo_path, file_name) return os.path.isfile(full_path) def dir_exists(repo_path, dir_name): full_path = os.path.join(repo_path, dir_name) return os.path.isdir(full_path) def parse_build_duration_response(json_response): """ This function is responsible for parsing Github GraphQL API response and calculating build duration """ build_checks = list() first_started_at = None last_completed_at = None total_duration = '' latest_commit = functools.reduce( operator.getitem, ["node", "defaultBranchRef", "target", "history", "edges"], json_response)[0] for check_suite in functools.reduce(operator.getitem, ['node', 'checkSuites', 'edges'], latest_commit): all_check_runs = check_suite['node']['checkRuns']['edges'] for check_run in all_check_runs: # If check is still in progress, skip it if not check_run['node']['completedAt']: continue name = check_run['node']['name'] started_at = datetime.strptime(check_run['node']['startedAt'], GITHUB_DATETIME_FMT) completed_at = datetime.strptime(check_run['node']['completedAt'], GITHUB_DATETIME_FMT) if not first_started_at or started_at < first_started_at: first_started_at = started_at if not last_completed_at or completed_at > last_completed_at: last_completed_at = completed_at job_duration = completed_at - started_at total_seconds = job_duration.total_seconds() minutes, remaining_seconds = divmod(total_seconds, 60) build_checks.append({ 'name': name, 'duration': f'{int(minutes)} minutes {int(remaining_seconds)} seconds', 'seconds': total_seconds }) if build_checks: # sorting checks into descending order of duration to get slowest check on top build_checks = sorted(build_checks, key=lambda k: k['seconds'], reverse=True) for check in build_checks: del check['seconds'] build_duration = last_completed_at - first_started_at minutes, remaining_seconds = divmod(build_duration.total_seconds(), 60) total_duration = f'{int(minutes)} minutes {int(remaining_seconds)} seconds' return total_duration, build_checks
35.191781
107
0.666018
614eba023b0fc45b797f15e50c09508be014173a
398
py
Python
Leetcode/0035. Search Insert Position.py
luckyrabbit85/Python
ed134fd70b4a7b84b183b87b85ad5190f54c9526
[ "MIT" ]
1
2021-07-15T18:40:26.000Z
2021-07-15T18:40:26.000Z
Leetcode/0035. Search Insert Position.py
luckyrabbit85/Python
ed134fd70b4a7b84b183b87b85ad5190f54c9526
[ "MIT" ]
null
null
null
Leetcode/0035. Search Insert Position.py
luckyrabbit85/Python
ed134fd70b4a7b84b183b87b85ad5190f54c9526
[ "MIT" ]
null
null
null
class Solution: def searchInsert(self, nums: list[int], target: int) -> int: left, right = 0, len(nums) - 1 while left <= right: pivot = (left + right) // 2 if nums[pivot] == target: return pivot if target < nums[pivot]: right = pivot - 1 else: left = pivot + 1 return left
30.615385
64
0.457286
2813765a817b9595dd81afb4e61d65c13e1bff4a
5,796
py
Python
tb_rest_client/models/models_pe/page_data_short_entity_view.py
maksonlee/python_tb_rest_client
a6cd17ef4de31f68c3226b7a9835292fbac4b1fa
[ "Apache-2.0" ]
1
2021-07-19T10:09:04.000Z
2021-07-19T10:09:04.000Z
tb_rest_client/models/models_pe/page_data_short_entity_view.py
moravcik94/python_tb_rest_client
985361890cdf4ccce93d2b24905ad9003c8dfcaa
[ "Apache-2.0" ]
null
null
null
tb_rest_client/models/models_pe/page_data_short_entity_view.py
moravcik94/python_tb_rest_client
985361890cdf4ccce93d2b24905ad9003c8dfcaa
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 # Copyright 2020. ThingsBoard # # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pprint import re # noqa: F401 import six class PageDataShortEntityView(object): """NOTE: This class is auto generated by the swagger code generator program. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'data': 'list[ShortEntityView]', 'has_next': 'bool', 'total_elements': 'int', 'total_pages': 'int' } attribute_map = { 'data': 'data', 'has_next': 'hasNext', 'total_elements': 'totalElements', 'total_pages': 'totalPages' } def __init__(self, data=None, has_next=None, total_elements=None, total_pages=None): # noqa: E501 """PageDataShortEntityView - a model defined in Swagger""" # noqa: E501 self._data = None self._has_next = None self._total_elements = None self._total_pages = None self.discriminator = None if data is not None: self.data = data if has_next is not None: self.has_next = has_next if total_elements is not None: self.total_elements = total_elements if total_pages is not None: self.total_pages = total_pages @property def data(self): """Gets the data of this PageDataShortEntityView. # noqa: E501 :return: The data of this PageDataShortEntityView. # noqa: E501 :rtype: list[ShortEntityView] """ return self._data @data.setter def data(self, data): """Sets the data of this PageDataShortEntityView. :param data: The data of this PageDataShortEntityView. # noqa: E501 :type: list[ShortEntityView] """ self._data = data @property def has_next(self): """Gets the has_next of this PageDataShortEntityView. # noqa: E501 :return: The has_next of this PageDataShortEntityView. # noqa: E501 :rtype: bool """ return self._has_next @has_next.setter def has_next(self, has_next): """Sets the has_next of this PageDataShortEntityView. :param has_next: The has_next of this PageDataShortEntityView. # noqa: E501 :type: bool """ self._has_next = has_next @property def total_elements(self): """Gets the total_elements of this PageDataShortEntityView. # noqa: E501 :return: The total_elements of this PageDataShortEntityView. # noqa: E501 :rtype: int """ return self._total_elements @total_elements.setter def total_elements(self, total_elements): """Sets the total_elements of this PageDataShortEntityView. :param total_elements: The total_elements of this PageDataShortEntityView. # noqa: E501 :type: int """ self._total_elements = total_elements @property def total_pages(self): """Gets the total_pages of this PageDataShortEntityView. # noqa: E501 :return: The total_pages of this PageDataShortEntityView. # noqa: E501 :rtype: int """ return self._total_pages @total_pages.setter def total_pages(self, total_pages): """Sets the total_pages of this PageDataShortEntityView. :param total_pages: The total_pages of this PageDataShortEntityView. # noqa: E501 :type: int """ self._total_pages = total_pages def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(PageDataShortEntityView, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, PageDataShortEntityView): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
29.723077
102
0.597826
61d08f3f03dd848d1e16801cb2b8d409398166ba
5,410
py
Python
src/metarl/tf/algos/erwr.py
neurips2020submission11699/metarl
ae4825d21478fa1fd0aa6b116941ea40caa152a5
[ "MIT" ]
2
2021-02-07T12:14:52.000Z
2021-07-29T08:07:22.000Z
src/metarl/tf/algos/erwr.py
neurips2020submission11699/metarl
ae4825d21478fa1fd0aa6b116941ea40caa152a5
[ "MIT" ]
null
null
null
src/metarl/tf/algos/erwr.py
neurips2020submission11699/metarl
ae4825d21478fa1fd0aa6b116941ea40caa152a5
[ "MIT" ]
null
null
null
"""Episodic Reward Weighted Regression.""" from metarl.tf.algos.vpg import VPG from metarl.tf.optimizers import LbfgsOptimizer class ERWR(VPG): """Episodic Reward Weighted Regression [1]. Note: This does not implement the original RwR [2]_ that deals with "immediate reward problems" since it doesn't find solutions that optimize for temporally delayed rewards. .. [1] Kober, Jens, and Jan R. Peters. "Policy search for motor primitives in robotics." Advances in neural information processing systems. 2009. .. [2] Peters, Jan, and Stefan Schaal. "Using reward-weighted regression for reinforcement learning of task space control. " Approximate Dynamic Programming and Reinforcement Learning, 2007. ADPRL 2007. IEEE International Symposium on. IEEE, 2007. Args: env_spec (metarl.envs.EnvSpec): Environment specification. policy (metarl.tf.policies.StochasticPolicy): Policy. baseline (metarl.tf.baselines.Baseline): The baseline. scope (str): Scope for identifying the algorithm. Must be specified if running multiple algorithms simultaneously, each using different environments and policies. max_path_length (int): Maximum length of a single rollout. discount (float): Discount. gae_lambda (float): Lambda used for generalized advantage estimation. center_adv (bool): Whether to rescale the advantages so that they have mean 0 and standard deviation 1. positive_adv (bool): Whether to shift the advantages so that they are always positive. When used in conjunction with center_adv the advantages will be standardized before shifting. fixed_horizon (bool): Whether to fix horizon. lr_clip_range (float): The limit on the likelihood ratio between policies, as in PPO. max_kl_step (float): The maximum KL divergence between old and new policies, as in TRPO. optimizer (object): The optimizer of the algorithm. Should be the optimizers in metarl.tf.optimizers. optimizer_args (dict): The arguments of the optimizer. policy_ent_coeff (float): The coefficient of the policy entropy. Setting it to zero would mean no entropy regularization. use_softplus_entropy (bool): Whether to estimate the softmax distribution of the entropy to prevent the entropy from being negative. use_neg_logli_entropy (bool): Whether to estimate the entropy as the negative log likelihood of the action. stop_entropy_gradient (bool): Whether to stop the entropy gradient. entropy_method (str): A string from: 'max', 'regularized', 'no_entropy'. The type of entropy method to use. 'max' adds the dense entropy to the reward for each time step. 'regularized' adds the mean entropy to the surrogate objective. See https://arxiv.org/abs/1805.00909 for more details. flatten_input (bool): Whether to flatten input along the observation dimension. If True, for example, an observation with shape (2, 4) will be flattened to 8. name (str): The name of the algorithm. """ def __init__(self, env_spec, policy, baseline, scope=None, max_path_length=500, discount=0.99, gae_lambda=1, center_adv=True, positive_adv=True, fixed_horizon=False, lr_clip_range=0.01, max_kl_step=0.01, optimizer=None, optimizer_args=None, policy_ent_coeff=0.0, use_softplus_entropy=False, use_neg_logli_entropy=False, stop_entropy_gradient=False, entropy_method='no_entropy', flatten_input=True, name='ERWR'): if optimizer is None: optimizer = LbfgsOptimizer if optimizer_args is None: optimizer_args = dict() super().__init__(env_spec=env_spec, policy=policy, baseline=baseline, scope=scope, max_path_length=max_path_length, discount=discount, gae_lambda=gae_lambda, center_adv=center_adv, positive_adv=positive_adv, fixed_horizon=fixed_horizon, lr_clip_range=lr_clip_range, max_kl_step=max_kl_step, optimizer=optimizer, optimizer_args=optimizer_args, policy_ent_coeff=policy_ent_coeff, use_softplus_entropy=use_softplus_entropy, use_neg_logli_entropy=use_neg_logli_entropy, stop_entropy_gradient=stop_entropy_gradient, entropy_method=entropy_method, flatten_input=flatten_input, name=name)
47.043478
78
0.590943
02613aaf7a1a94e5a2996158ddc8316f7d3e5934
13,270
py
Python
adaptive_binning_chisquared_2sam/chi2_adaptive_binning.py
weissercn/adaptive_binning_chisquared_2sam
f4684e70af94add187263522fa784bf02b096051
[ "MIT" ]
null
null
null
adaptive_binning_chisquared_2sam/chi2_adaptive_binning.py
weissercn/adaptive_binning_chisquared_2sam
f4684e70af94add187263522fa784bf02b096051
[ "MIT" ]
null
null
null
adaptive_binning_chisquared_2sam/chi2_adaptive_binning.py
weissercn/adaptive_binning_chisquared_2sam
f4684e70af94add187263522fa784bf02b096051
[ "MIT" ]
null
null
null
from __future__ import print_function import sys import chi2_plots import random import ast import pickle """ This script can be used to get the p value for the Miranda method (=chi squared). It takes input files with column vectors corresponding to features and lables. """ print(__doc__) import sys #sys.path.insert(0,'../..') import os from scipy import stats import numpy as np from sklearn import preprocessing import matplotlib.pylab as plt #import matplotlib.pyplot as plt #import numpy.matlib #from matplotlib.colors import Normalize #from sklearn.preprocessing import StandardScaler ############################################################################## # Setting parameters # #orig_name= sys.argv[1] #number_of_splits_list= ast.literal_eval(sys.argv[2]) #print("number_of_splits_list : ", number_of_splits_list) #dim_list = ast.literal_eval(sys.argv[3]) #comp_file_list_list = ast.literal_eval(sys.argv[4]) def norm_highD_searchsorted(l_test): l_test = np.array(l_test).tolist() l_set = sorted(set(l_test)) pos = [0]*len(l_test) pos_counter = 0 for item in l_set: matches = [i for i in range(0,len(l_test)) if l_test[i]==item] random.shuffle(matches) for m in matches: pos[m]= pos_counter pos_counter+=1 pos = np.array(pos) pos = pos/np.float(len(l_test)-1) return pos def chi2_adaptive_binning_wrapper(orig_title, orig_name, dim_list, comp_file_list_list,number_of_splits_list,systematics_fraction): sample1_name="original" sample2_name="modified" #transform='uniform' transform='StandardScalar' #transform='fill01' DEBUG = False ############################################################################## for dim_index, dim_data in enumerate(dim_list): print("We are now in "+str(dim_data) + " Dimensions") #comp_file_list=[] comp_file_list = comp_file_list_list[dim_index] #for i in range(2): #comp_file_list.append((os.environ['MLToolsDir']+"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high" +str(dim_data)+"Dgauss_10000_0.5_0.1_0.0_{0}.txt".format(i),os.environ['MLToolsDir']+"/Dalitz/gaussian_samples/higher_dimensional_gauss/gauss_data/data_high"+str(dim_data)+"Dgauss_10000_0.5_0.1_0.01_{0}.txt".format(i))) #comp_file_list.append((os.environ['MLToolsDir']+"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__10__sample_{0}.txt".format(i),os.environ['MLToolsDir']+"/Dalitz/gaussian_samples/legendre/legendre_data/data_legendre_contrib0__1__9__sample_{0}.txt".format(i))) #comp_file_list.append((os.environ['MLToolsDir']+"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_redefined_{1}D_1000_0.6_0.2_0.1_{0}.txt".format(i,dim_data),os.environ['MLToolsDir']+"/Dalitz/gaussian_samples/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_redefined_{1}D_1000_0.6_0.2_0.075_{0}.txt".format(i,dim_data))) #print(comp_file_list) score_dict = {} for number_of_splits in number_of_splits_list: score_dict[str(number_of_splits)]=[] counter = 0 for comp_file_0,comp_file_1 in comp_file_list: print("Operating of files :"+comp_file_0+" "+comp_file_1) #extracts data from the files features_0=np.loadtxt(comp_file_0,dtype='d', ndmin=2) features_1=np.loadtxt(comp_file_1,dtype='d', ndmin=2) #only make a plot for the first data set results_list=chi2_adaptive_binning(features_0,features_1,number_of_splits_list,systematics_fraction,orig_title,orig_name, not counter,DEBUG, transform) for number_of_splits_index, number_of_splits in enumerate(number_of_splits_list): score_dict[str(number_of_splits)].append(results_list[number_of_splits_index]) counter+=1 for number_of_splits in number_of_splits_list: name = orig_name + "_" +str(dim_data) + "D_chi2_" + str(number_of_splits) + "_splits" title= orig_title+ " " +str(dim_data) + "D " + str(number_of_splits) + " splits" print("score_dict[{}] : ".format(number_of_splits), score_dict[str(number_of_splits)]) with open(name+"_p_values", "wb") as test_statistics_file: for score in score_dict[str(number_of_splits)]: test_statistics_file.write(str(score)+"\n") #if dim_data==2: os.rename("name_"+str(dim_data) + "D_" + str(number_of_splits) + "_splits"+"_bin_definitions_2D.png",name+"_bin_definitions_2D.png") #if dim_data==1: os.rename("name_"+str(dim_data) + "D_" + str(number_of_splits) + "_splits"+"_bin_definitions_1D.png",name+"_binning_bin_definitions_1D.png") chi2_plots.histo_plot_pvalue(score_dict[str(number_of_splits)],50,"p value","Frequency",title,name) def chi2_adaptive_binning(features_0,features_1,number_of_splits_list,systematics_fraction=0.0,title = "title", name="name", PLOT = True, DEBUG = False, transform='StandardScalar'): """This function takes in two 2D arrays with all features being columns""" max_number_of_splits = np.max(number_of_splits_list) #determine how many data points are in each sample no_0=features_0.shape[0] no_1=features_1.shape[0] print("features_0.shape : ", features_0.shape) no_dim = features_0.shape[1] #Give all samples in file 0 the label 0 and in file 1 the feature 1 label_0=np.zeros((no_0,1)) label_1=np.ones((no_1,1)) #Create an array containing samples and features. data_0=np.c_[features_0,label_0] data_1=np.c_[features_1,label_1] features= np.r_[features_0,features_1] labels= np.r_[label_0, label_1] data=np.r_[data_0,data_1] data_same=np.c_[features,labels] #print("data : ",data) #print("data_same : ", data_same) #print("np.sum(data!=data_same) : ",np.sum(data!=data_same)) assert np.sum(data!=data_same)==0 assert (no_dim == data.shape[1]-1) if no_dim==2: plt.scatter(features[:,0],features[:,1], 0.1) plt.savefig('test.png') plt.clf() if transform=='StandardScalar': features = preprocessing.scale(features) data = np.c_[features,labels] if transform=='uniform': #data_new2 = data[:,0] data_new = norm_highD_searchsorted(data[:,0]) for D in range(1,no_dim): temp = norm_highD_searchsorted(data[:,D]) data_new = np.c_[data_new,temp] #data_new2= np.c_[data_new2,data[:,D]] data_new = np.c_[data_new, np.r_[label_0,label_1]] #data_new2= np.c_[data_new2,np.r_[label_0,label_1]] print("data : ", data) data = data_new print("data new : ", data) #print("data_new2 : ", data_new2) #print("np.sum(data!=data_new2) : ",np.sum(data!=data_new2)) np.random.shuffle(data) assert (no_dim == data.shape[1]-1) labels=data[:,-1] X_values= data[:,:-1] X_max = np.amax(data,axis=0)[:-1] X_min = np.amin(data,axis=0)[:-1] X_total_width = (np.subtract(X_max,X_min)) del data if transform=='fill01': #Scaling X_values = X_values - X_min[None,:] X_values = X_values / X_total_width[None,:] if True: X_min = [0.]*no_dim X_total_width = [1.]*no_dim #b = X_values[:,0] #print("b[b[:]>2].shape[0] : \n", b[b[:]>2].shape[0] ) data = np.concatenate((X_values, labels[:,None]), axis=1) if no_dim==2: plt.scatter(data[:,0],data[:,1],0.1) plt.savefig('test_scaled.png') #print("X_values.shape : ",X_values.shape) starting_boundary = [] for i in range(no_dim): starting_boundary.append([0.0,1.0]) #Each key has the following stricture: # of splits and for each split if it was closer (a) or further away from (b) the origin. The original bin is "0" #For example "2ab" means it is the bin that was closer to the origin for the first split and further away for the second one. bin_boundaries_dict = {'0' : np.array(starting_boundary)} bin_points_dict = {'0' : data} for split_number in range(1,1+max_number_of_splits): for bin_key, bin_boundary in bin_boundaries_dict.items(): if str(split_number-1) in bin_key: variances= np.var(bin_points_dict[bin_key][:,:-1], axis=0) #print("\nvariances : ", variances) dim_to_be_sliced = np.argmax(variances) #print("dim_to_be_sliced : ",dim_to_be_sliced) #print("bin_points_dict[bin_key] : ",bin_points_dict[bin_key]) #print("bin_points_dict[bin_key][:,dim_to_be_sliced] : ",bin_points_dict[bin_key][:,dim_to_be_sliced]) median = np.median(bin_points_dict[bin_key][:,dim_to_be_sliced]) #print("median : ",median) a_bin_boundary, b_bin_boundary = bin_boundary.copy(), bin_boundary.copy() #print("a_bin_boundary : ",a_bin_boundary) a_bin_boundary[dim_to_be_sliced,1] = median b_bin_boundary[dim_to_be_sliced,0] = median bin_boundaries_dict[str(split_number)+bin_key[1:]+'a'] = a_bin_boundary bin_boundaries_dict[str(split_number)+bin_key[1:]+'b'] = b_bin_boundary a_points, b_points = [],[] for event_number in range(bin_points_dict[bin_key].shape[0]): if bin_points_dict[bin_key][event_number,dim_to_be_sliced] < median: a_points.append(bin_points_dict[bin_key][event_number,:].tolist()) else: b_points.append(bin_points_dict[bin_key][event_number,:].tolist()) bin_points_dict[str(split_number)+bin_key[1:]+'a'] = np.array(a_points) bin_points_dict[str(split_number)+bin_key[1:]+'b'] = np.array(b_points) #If a bin contains no particles it should be deleted if len(a_points)==0: del bin_points_dict[str(split_number)+bin_key[1:]+'a'] del bin_boundaries_dict[str(split_number)+bin_key[1:]+'a'] if len(b_points)==0: del bin_points_dict[str(split_number)+bin_key[1:]+'b'] del bin_boundaries_dict[str(split_number)+bin_key[1:]+'b'] if PLOT: pickle.dump( bin_boundaries_dict, open( "bin_boundaries_dict.p", "wb" ) ) bins_sample01_dict= {} signed_Scp2_dict= {} results_list = [] for number_of_splits in number_of_splits_list: print("\nnumber_of_splits : ",number_of_splits,"\nsystematics_fraction : ",systematics_fraction) bins_sample0, bins_sample1 = [] , [] for bin_key, bin_points in bin_points_dict.items(): if str(number_of_splits) in bin_key: labels_in_bin = bin_points[:,-1] #print("labels_in_bin : ",labels_in_bin) bin_sample0 = np.count_nonzero( labels_in_bin == 0) bin_sample1 = np.count_nonzero( labels_in_bin == 1) #print("bin_sample0 : ",bin_sample0) #print("bin_sample1 : ",bin_sample1) #simulate uncertainties if(systematics_fraction*float(bin_sample0)!=0.): bin_sample0 += int(round(np.random.normal(0.,systematics_fraction*float(bin_sample0)))) if(systematics_fraction*float(bin_sample1)!=0.): bin_sample1 += int(round(np.random.normal(0.,systematics_fraction*float(bin_sample1)))) bins_sample01_dict[bin_key]=[bin_sample0,bin_sample1] signed_Scp2_dict[bin_key] = np.square(float(bin_sample1-bin_sample0))/(float(bin_sample1)+float(bin_sample0)+np.square(float(bin_sample1)*systematics_fraction)+np.square(float(bin_sample1)*systematics_fraction))*np.sign(bin_sample1-bin_sample0) #print("\n\nbin_sample0 : ",bin_sample0, "\n bins_sample0 : ", bins_sample0 ) #print("type(bin_sample0) : ",type(bin_sample0), " type(bins_sample0) : ",type(bins_sample0)) bins_sample0.append(bin_sample0) #print(" bins_sample0 : ", bins_sample0, "\n\n" ) bins_sample1.append(bin_sample1) bins_sample0, bins_sample1 = np.array(bins_sample0,dtype=float), np.array(bins_sample1, dtype=float) print("bins_sample0 : ",bins_sample0,"\n bins_sample1 : ",bins_sample1) #element wise subtraction and division Scp2 = ((bins_sample1-bins_sample0)**2)/ (bins_sample1+bins_sample0+(systematics_fraction*bins_sample1)**2+(systematics_fraction*bins_sample0)**2 ) #Scp2 = np.divide(np.square(np.subtract(bins_sample1,bins_sample0)),np.add(bins_sample1,bins_sample0)) if DEBUG: print(Scp2) #nansum ignores all the contributions that are Not A Number (NAN) Chi2 = np.nansum(Scp2) if DEBUG: print("Chi2") print(Chi2) dof=bins_sample0.shape[0]-1 pvalue= 1 - stats.chi2.cdf(Chi2,dof) print("\nThe p value for Scp2 = ",Scp2," and Chi2 = ", Chi2, " is ",pvalue,"\n\n") if DEBUG: print(bins_sample0) print(bins_sample1) print("Chi2/dof : {0}".format(str(Chi2/dof))) print("pvalue : {0}".format(str(pvalue))) results_list.append(pvalue) if PLOT: if no_dim==1: chi2_plots.adaptive_binning_1Dplot(bin_boundaries_dict,data,number_of_splits,title+" "+str(no_dim) + "D "+str(number_of_splits)+ " splits ",name+"_"+str(no_dim) + "D_chi2_"+str(number_of_splits)+"_splits") if no_dim==2: chi2_plots.adaptive_binning_2Dplot(bin_boundaries_dict,signed_Scp2_dict,number_of_splits,X_values,title+" "+str(no_dim) + "D"+str(number_of_splits)+ " splits ",name+"_"+str(no_dim) + "D_chi2_"+str(number_of_splits)+"_splits", X_min= X_min,X_total_width=X_total_width ) if no_dim>1: chi2_plots.adaptive_binning_2D1Dplot(bin_boundaries_dict,bins_sample01_dict,number_of_splits,X_values,title+" "+str(no_dim) + "D"+str(number_of_splits)+ " splits ",name+"_"+str(no_dim) + "D_chi2_"+str(number_of_splits)+"_splits", no_dim) return results_list
43.366013
426
0.705275
4f4ca7e0bf36ed6c13de1ad3ccd4a51a9751acab
10,153
py
Python
example.streambook.py
Davidnet/treex-1
40a0c498c7e50afa917316bf9b4d55138c58378e
[ "MIT" ]
null
null
null
example.streambook.py
Davidnet/treex-1
40a0c498c7e50afa917316bf9b4d55138c58378e
[ "MIT" ]
null
null
null
example.streambook.py
Davidnet/treex-1
40a0c498c7e50afa917316bf9b4d55138c58378e
[ "MIT" ]
null
null
null
import streamlit as __st import streambook __toc = streambook.TOCSidebar() __toc._add(streambook.H1('Treex')) __toc._add(streambook.H3('Initialization')) __toc._add(streambook.H3('Modules are Pytrees')) __toc._add(streambook.H3('Modules can be sliced')) __toc._add(streambook.H3('Modules can be merged')) __toc._add(streambook.H3('Modules compose')) __toc._add(streambook.H3('Full Example')) __toc.generate() __st.markdown(r"""<span id='Treex'> </span> # Treex **Main features**: * Modules contain their parameters * Easy transfer learning * Simple initialization * No metaclass magic * No apply method * No need special versions of `vmap`, `jit`, and friends. To prove the previous we will start with by creating a very contrived but complete module which will use everything from parameters, states, and random state:""", unsafe_allow_html=True) with __st.echo(), streambook.st_stdout('info'): from typing import Tuple import jax.numpy as jnp import numpy as np import treex as tx class NoisyStatefulLinear(tx.Module): # tree parts are defined by treex annotations w: tx.Parameter b: tx.Parameter count: tx.State rng: tx.Rng # other annotations are possible but ignored by type name: str def __init__(self, din, dout, name="noisy_stateful_linear"): self.name = name # Initializers only expect RNG key self.w = tx.Initializer(lambda k: jax.random.uniform(k, shape=(din, dout))) self.b = tx.Initializer(lambda k: jax.random.uniform(k, shape=(dout,))) # random state is JUST state, we can keep it locally self.rng = tx.Initializer(lambda k: k) # if value is known there is no need for an Initiaizer self.count = jnp.array(1) def __call__(self, x: np.ndarray) -> np.ndarray: assert isinstance(self.count, jnp.ndarray) assert isinstance(self.rng, jnp.ndarray) # state can easily be updated self.count = self.count + 1 # random state is no different :) key, self.rng = jax.random.split(self.rng, 2) # your typical linear operation y = jnp.dot(x, self.w) + self.b # add noise for fun state_noise = 1.0 / self.count random_noise = 0.8 * jax.random.normal(key, shape=y.shape) return y + state_noise + random_noise def __repr__(self) -> str: return f"NoisyStatefulLinear(w={self.w}, b={self.b}, count={self.count}, rng={self.rng})" linear = NoisyStatefulLinear(1, 1) linear __st.markdown(r"""<span id='Initialization'> </span> ### Initialization As advertised, initialization is easy, the only thing you need to do is to call `init` on your module with a random key:""", unsafe_allow_html=True) with __st.echo(), streambook.st_stdout('info'): import jax linear = linear.init(key=jax.random.PRNGKey(42)) linear __st.markdown(r"""<span id='Modules are Pytrees'> </span> ### Modules are Pytrees Its fundamentally important that modules are also Pytrees, we can check that they are by using `tree_map` with an arbitrary function:""", unsafe_allow_html=True) with __st.echo(), streambook.st_stdout('info'): # its a pytree alright doubled = jax.tree_map(lambda x: 2 * x, linear) doubled __st.markdown(r"""<span id='Modules can be sliced'> </span> ### Modules can be sliced An important feature of this Module system is that it can be sliced based on the type of its parameters, the `slice` method does exactly that:""", unsafe_allow_html=True) with __st.echo(), streambook.st_stdout('info'): params = linear.slice(tx.Parameter) states = linear.slice(tx.State) print(f"{params=}") print(f"{states=}") __st.markdown(r"""<span id='Modules can be merged'> </span> Notice the following: * Both `params` and `states` are `NoisyStatefulLinear` objects, their type doesn't change after being sliced. * The fields that are filtered out by the `slice` on each field get a special value of type `tx.Nothing`. Why is this important? As we will see later, it is useful keep parameters and state separate as they will crusially flow though different parts of `value_and_grad`. ### Modules can be merged This is just the inverse operation to `slice`, `merge` behaves like dict's `update` but returns a new module leaving the original modules intact:""", unsafe_allow_html=True) with __st.echo(), streambook.st_stdout('info'): linear = params.merge(states) linear __st.markdown(r"""<span id='Modules compose'> </span> ### Modules compose As you'd expect, you can have modules inside ther modules, same as previously the key is to annotate the class fields. Here we will create an `MLP` class that uses two `NoisyStatefulLinear` modules:""", unsafe_allow_html=True) with __st.echo(), streambook.st_stdout('info'): class MLP(tx.Module): linear1: NoisyStatefulLinear linear2: NoisyStatefulLinear def __init__(self, din, dmid, dout): self.linear1 = NoisyStatefulLinear(din, dmid, name="linear1") self.linear2 = NoisyStatefulLinear(dmid, dout, name="linear2") def __call__(self, x: np.ndarray) -> np.ndarray: x = jax.nn.relu(self.linear1(x)) x = self.linear2(x) return x def __repr__(self) -> str: return f"MLP(linear1={self.linear1}, linear2={self.linear2})" model = MLP(din=1, dmid=2, dout=1).init(key=42) model __st.markdown(r"""<span id='Full Example'> </span> ### Full Example Using the previous `model` we will show how to train it using the proposed Module system. First lets get some data:""", unsafe_allow_html=True) with __st.echo(), streambook.st_stdout('info'): import numpy as np import matplotlib.pyplot as plt np.random.seed(0) def get_data(dataset_size: int) -> Tuple[np.ndarray, np.ndarray]: x = np.random.normal(size=(dataset_size, 1)) y = 5 * x - 2 + 0.4 * np.random.normal(size=(dataset_size, 1)) return x, y def get_batch( data: Tuple[np.ndarray, np.ndarray], batch_size: int ) -> Tuple[np.ndarray, np.ndarray]: idx = np.random.choice(len(data[0]), batch_size) return jax.tree_map(lambda x: x[idx], data) data = get_data(1000) fig = plt.figure() # __st plt.scatter(data[0], data[1]) plt.show() fig # __st __st.markdown(r"""Now we will be reusing the previous MLP model, and we will create an optax optimizer that will be used to train the model:""", unsafe_allow_html=True) with __st.echo(), streambook.st_stdout('info'): import optax optimizer = optax.adam(1e-2) params = model.slice(tx.Parameter) states = model.slice(tx.State) opt_state = optimizer.init(params) __st.markdown(r"""Notice that we are already splitting the model into `params` and `states` since we need to pass the `params` only to the optimizer. Next we will create the loss function, it will take the model parts and the data parts and return the loss plus the new states:""", unsafe_allow_html=True) with __st.echo(), streambook.st_stdout('info'): from functools import partial @partial(jax.value_and_grad, has_aux=True) def loss_fn(params: MLP, states: MLP, x, y): # merge params and states to get a full model model: MLP = params.merge(states) # apply model pred_y = model(x) # MSE loss loss = jnp.mean((y - pred_y) ** 2) # new states states = model.slice(tx.State) return loss, states __st.markdown(r"""Notice that the first thing we are doing is merging the `params` and `states` into the complete model since we need everything in place to perform the forward pass. Also, we return the updated states from the model, this is needed because JAX functional API requires us to be explicit about state management. **Note**: inside `loss_fn` (which is wrapped by `value_and_grad`) module can behave like a regular mutable python object, however, every time its treated as pytree a new reference will be created as happens in `jit`, `grad`, `vmap`, etc. Its important to keep this into account when using functions like `vmap` inside a module as certain book keeping will be needed to manage state correctly. Next we will implement the `update` function, it will look indistinguishable from your standard Haiku update which also separates weights into `params` and `states`: """, unsafe_allow_html=True) with __st.echo(), streambook.st_stdout('info'): @jax.jit def update(params: MLP, states: MLP, opt_state, x, y): (loss, states), grads = loss_fn(params, states, x, y) updates, opt_state = optimizer.update(grads, opt_state, params) # use regular optax params = optax.apply_updates(params, updates) return params, states, opt_state, loss __st.markdown(r"""Finally we create a simple training loop that perform a few thousand updates and merge `params` and `states` back into a single `model` at the end:""", unsafe_allow_html=True) with __st.echo(), streambook.st_stdout('info'): steps = 10_000 for step in range(steps): x, y = get_batch(data, batch_size=32) params, states, opt_state, loss = update(params, states, opt_state, x, y) if step % 1000 == 0: print(f"[{step}] loss = {loss}") # get the final model model = params.merge(states) __st.markdown(r"""Now lets generate some test data and see how our model performed:""", unsafe_allow_html=True) with __st.echo(), streambook.st_stdout('info'): import matplotlib.pyplot as plt X_test = np.linspace(data[0].min(), data[0].max(), 100)[:, None] y_pred = model(X_test) fig = plt.figure() # __st plt.scatter(data[0], data[1], label="data", color="k") plt.plot(X_test, y_pred, label="prediction") plt.legend() plt.show() fig # __st __st.markdown(r"""As you can see the model learned the general trend but because of the `NoisyStatefulLinear` modules we have a bit of noise in the predictions.""", unsafe_allow_html=True)
41.272358
392
0.681079
8462c9c3dd960d9eac4a801b7fd6555293d5c345
6,217
py
Python
kuveytturk/api.py
iuysal/kuveytturk
e726b933d7a957197902b410d60591967147a7b0
[ "MIT" ]
4
2019-05-06T10:58:47.000Z
2020-07-10T12:28:49.000Z
kuveytturk/api.py
iuysal/kuveytturk
e726b933d7a957197902b410d60591967147a7b0
[ "MIT" ]
null
null
null
kuveytturk/api.py
iuysal/kuveytturk
e726b933d7a957197902b410d60591967147a7b0
[ "MIT" ]
null
null
null
from kuveytturk.binder import bind_api from kuveytturk.parsers import JSONParser def prepare_params(*args, **kwargs): """Converts both positional and named arguments into a dict.""" if not kwargs: kwargs = {} for arg in args: # if the positional argument is a dictionary, then put its items # into kwargs dict. Otherwise, ignore the argument if isinstance(arg, dict): for k, v in arg.items(): kwargs[k] = v # Finally, all the supplied arguments are in a unified dict. return kwargs class API(object): """ KuveytTurk API This class contains 4 different api endpoints to give you an idea of what type of url paths are supported. You can simply call the generic_request method with the desired endpoint parameter settings that are documented on the API Market. Please see the examples for getting started. """ def __init__(self, auth_handler=None, host='https://apitest.kuveytturk.com.tr/prep', timeout=60, parser=None): """ API instance Constructor :param auth_handler: :param host: url of the server of the rest api, default: 'https://apitest.kuveytturk.com.tr/prep' :param timeout: delay before to consider the request as timed out in seconds, default:60 :param parser: Parser instance to parse the responses, default:None """ self.auth = auth_handler self.host = host self.timeout = timeout self.parser = parser or JSONParser() def _call_endpoint(self, endpoint_params, *args, **kwargs): """ Initiatest the api request after modifying the parameters if necessary. :param endpoint_params: :param args: :param kwargs: :return: """ if 'host' in kwargs: self.host = kwargs['host'] return bind_api( api=self, endpoint_params=endpoint_params, post_data=prepare_params(*args, **kwargs) ) def generic_request(self, endpoint_params, *args, **kwargs): """ This method can be used to call the endpoints that are not wrapped in this class, by simply passing the endpoint_params dict with the following keys: 'path', 'method', 'scope', and 'authorization_flow' :param endpoint_params: :param args: positional arguments :param kwargs: named arguments :return: A ResultModel instance """ return self._call_endpoint(endpoint_params, *args, **kwargs) def test_customer_list(self, *args, **kwargs): """ :reference: https://developer.kuveytturk.com.tr/#/documentation/general/Test%20Customer%20List """ return self._call_endpoint( { 'path': '/v1/data/testcustomers', 'method': 'GET', 'scope': 'public', 'authorization_flow': 'client credentials' }, *args, **kwargs) def account_list(self, *args, **kwargs): """ :reference: https://developer.kuveytturk.com.tr/#/documentation/Accounts/Account%20List """ return self._call_endpoint( { 'path': '/v1/accounts/{suffix?}', 'method': 'GET', 'scope': 'accounts', 'authorization_flow': 'authorization code' }, *args, **kwargs) def bank_branch_list(self, *args, **kwargs): """ :reference: https://developer.kuveytturk.com.tr/#/documentation/Information%20Services/Bank%20Branch%20List """ return self._call_endpoint( { 'path': '/v1/data/banks/{bankId}/branches?cityId={cityId}', 'method': 'GET', 'scope': 'public', 'authorization_flow': 'client credentials' }, *args, **kwargs) def collection_list(self, *args, **kwargs): """ :reference: https://developer.kuveytturk.com.tr/#/documentation/Loans%2FFinancing/Collection%20List """ return self._call_endpoint( { 'path': '/v1/collections', 'method': 'POST', 'scope': 'loans', 'authorization_flow': 'client credentials' }, *args, **kwargs) # def fx_currency_rates(self, *args, **kwargs): # """ # :reference: https://developer.kuveytturk.com.tr/#/documentation/Information%20Services/FX%20Currency%20Rates # """ # return self._call_endpoint( # { # 'path': '/v1/fx/rates', # 'method': 'GET', # 'scope': 'public', # 'authorization_flow': 'client credentials' # }, *args, **kwargs) # def bank_list(self, *args, **kwargs): # """ # :reference: https://developer.kuveytturk.com.tr/#/documentation/Information%20Services/Bank%20List # """ # return self._call_endpoint( # { # 'path': '/v1/data/banks', # 'method': 'GET', # 'scope': 'public', # 'authorization_flow': 'client credentials' # }, *args, **kwargs) # def moneygram_send(self, *args, **kwargs): # """ # :reference: https://developer.kuveytturk.com.tr/#/documentation/MoneyGram/MoneyGram%20Send # """ # return self._call_endpoint( # { # 'path': '/v1/moneygram/send', # 'method': 'POST', # 'scope': 'transfers', # 'authorization_flow': 'authorization code' # }, *args, **kwargs) # # def money_transfer_to_iban(self, *args, **kwargs): # """ # :reference: https://developer.kuveytturk.com.tr/#/documentation/Money%20Transfers/Money%20Transfer%20to%20IBAN # """ # return self._call_endpoint( # { # 'path': '/v1/transfers/toIBAN', # 'method': 'POST', # 'scope': 'transfers', # 'authorization_flow': 'authorization code' # }, *args, **kwargs)
35.936416
120
0.557021
3891c554d7633437ec078fab89148b88011395b0
800
py
Python
app/app.py
shujams/Web-Scraping-Challenge
0883db0aada1dca77b3df3e275c559433ca48a62
[ "MIT" ]
null
null
null
app/app.py
shujams/Web-Scraping-Challenge
0883db0aada1dca77b3df3e275c559433ca48a62
[ "MIT" ]
null
null
null
app/app.py
shujams/Web-Scraping-Challenge
0883db0aada1dca77b3df3e275c559433ca48a62
[ "MIT" ]
null
null
null
from flask import Flask, render_template from flask_pymongo import PyMongo import scrape_mars import pymongo app = Flask(__name__) # Use flask pymongo to set up mongo connection app.config["MONGO_URI"] = "mongodb://localhost:27017/mars_app" mongo = PyMongo(app) # conn = "mongodb://localhost:27017" # client = pymongo.MongoClient(conn) # db = client.mars_db # collection = db.mars @app.route("/") def index(): mars = mongo.db.mars.find_one() # mars = db.collection.find_one() return render_template("index.html", mars=mars) @app.route("/scrape") def scrape(): mars = db.collection #mars = mongo.db.mars mars_data = scrape_mars.scrape_all() mars.update({}, mars_data, upsert=True) return "Scraping Successful!" if __name__=="__main__": app.run(debug=True)
22.222222
62
0.70625
b6d0d1f6ed4dc6df353285336f6efd40fe3bb6f9
13,453
py
Python
e2e_tests/tests/experiment/test_noop.py
coreystatendet/determined
abe5f3d0f64f7b05422507731d800621cf0ace8e
[ "Apache-2.0" ]
null
null
null
e2e_tests/tests/experiment/test_noop.py
coreystatendet/determined
abe5f3d0f64f7b05422507731d800621cf0ace8e
[ "Apache-2.0" ]
null
null
null
e2e_tests/tests/experiment/test_noop.py
coreystatendet/determined
abe5f3d0f64f7b05422507731d800621cf0ace8e
[ "Apache-2.0" ]
null
null
null
import copy import os import shutil import tempfile import time from typing import Union import pytest from determined.common import check, yaml from determined.common.api import bindings from tests import config as conf from tests import experiment as exp @pytest.mark.e2e_cpu def test_noop_long_train_step() -> None: exp.run_basic_test( conf.fixtures_path("no_op/single-long-train-step.yaml"), conf.fixtures_path("no_op"), 1, ) @pytest.mark.e2e_cpu def test_noop_pause() -> None: """ Walk through starting, pausing, and resuming a single no-op experiment. """ experiment_id = exp.create_experiment( conf.fixtures_path("no_op/single-medium-train-step.yaml"), conf.fixtures_path("no_op"), None, ) exp.wait_for_experiment_state(experiment_id, bindings.determinedexperimentv1State.STATE_ACTIVE) # Wait for the only trial to get scheduled. exp.wait_for_experiment_active_workload(experiment_id) # Wait for the only trial to show progress, indicating the image is built and running. exp.wait_for_experiment_workload_progress(experiment_id) # Pause the experiment. Note that Determined does not currently differentiate # between a "stopping paused" and a "paused" state, so we follow this check # up by ensuring the experiment cleared all scheduled workloads. exp.pause_experiment(experiment_id) exp.wait_for_experiment_state(experiment_id, bindings.determinedexperimentv1State.STATE_PAUSED) # Wait at most 20 seconds for the experiment to clear all workloads (each # train step should take 5 seconds). for _ in range(20): workload_active = exp.experiment_has_active_workload(experiment_id) if not workload_active: break else: time.sleep(1) check.true( not workload_active, "The experiment cannot be paused within 20 seconds.", ) # Resume the experiment and wait for completion. exp.activate_experiment(experiment_id) exp.wait_for_experiment_state( experiment_id, bindings.determinedexperimentv1State.STATE_COMPLETED ) @pytest.mark.e2e_cpu def test_noop_pause_of_experiment_without_trials() -> None: """ Walk through starting, pausing, and resuming a single no-op experiment which will never schedule a trial. """ config_obj = conf.load_config(conf.fixtures_path("no_op/single-one-short-step.yaml")) impossibly_large = 100 config_obj["max_restarts"] = 0 config_obj["resources"] = {"slots_per_trial": impossibly_large} with tempfile.NamedTemporaryFile() as tf: with open(tf.name, "w") as f: yaml.dump(config_obj, f) experiment_id = exp.create_experiment(tf.name, conf.fixtures_path("no_op"), None) exp.pause_experiment(experiment_id) exp.wait_for_experiment_state(experiment_id, bindings.determinedexperimentv1State.STATE_PAUSED) exp.activate_experiment(experiment_id) exp.wait_for_experiment_state(experiment_id, bindings.determinedexperimentv1State.STATE_ACTIVE) for _ in range(5): assert ( exp.experiment_state(experiment_id) == bindings.determinedexperimentv1State.STATE_ACTIVE ) time.sleep(1) exp.cancel_single(experiment_id) @pytest.mark.e2e_cpu def test_noop_single_warm_start() -> None: experiment_id1 = exp.run_basic_test( conf.fixtures_path("no_op/single.yaml"), conf.fixtures_path("no_op"), 1 ) trials = exp.experiment_trials(experiment_id1) assert len(trials) == 1 first_trial = trials[0].trial first_trial_id = first_trial.id first_workloads = trials[0].workloads assert len(first_workloads or []) == 90 checkpoints = exp.workloads_for_mode(first_workloads, "checkpoint") assert len(checkpoints or []) == 30 assert checkpoints[0] and checkpoints[0].checkpoint first_checkpoint_uuid = checkpoints[0].checkpoint.uuid assert checkpoints[-1] and checkpoints[-1].checkpoint last_checkpoint_uuid = checkpoints[-1].checkpoint.uuid last_validation = exp.workloads_for_mode(first_workloads, "validation")[-1] assert last_validation and last_validation.validation and last_validation.validation.metrics assert last_validation.validation.metrics["validation_error"] == pytest.approx(0.9 ** 30) config_base = conf.load_config(conf.fixtures_path("no_op/single.yaml")) # Test source_trial_id. config_obj = copy.deepcopy(config_base) # Add a source trial ID to warm start from. config_obj["searcher"]["source_trial_id"] = first_trial_id experiment_id2 = exp.run_basic_test_with_temp_config(config_obj, conf.fixtures_path("no_op"), 1) trials = exp.experiment_trials(experiment_id2) assert len(trials) == 1 second_trial = trials[0] assert len(second_trial.workloads or []) == 90 # Second trial should have a warm start checkpoint id. assert second_trial.trial assert second_trial.trial.warmStartCheckpointUuid == last_checkpoint_uuid val_workloads = exp.workloads_for_mode(second_trial.workloads, "validation") assert ( val_workloads[-1] and val_workloads[-1].validation and val_workloads[-1].validation.metrics ) assert val_workloads[-1].validation.metrics["validation_error"] == pytest.approx(0.9 ** 60) # Now test source_checkpoint_uuid. config_obj = copy.deepcopy(config_base) # Add a source trial ID to warm start from. config_obj["searcher"]["source_checkpoint_uuid"] = checkpoints[0].checkpoint.uuid with tempfile.NamedTemporaryFile() as tf: with open(tf.name, "w") as f: yaml.dump(config_obj, f) experiment_id3 = exp.run_basic_test(tf.name, conf.fixtures_path("no_op"), 1) trials = exp.experiment_trials(experiment_id3) assert len(trials) == 1 third_trial = trials[0] assert len(third_trial.workloads or []) == 90 assert third_trial.trial assert third_trial.trial.warmStartCheckpointUuid == first_checkpoint_uuid validations = exp.workloads_for_mode(third_trial.workloads, "validation") assert validations[1] and validations[1].validation and validations[1].validation.metrics assert validations[1].validation.metrics["validation_error"] == pytest.approx(0.9 ** 3) @pytest.mark.e2e_cpu def test_cancel_one_experiment() -> None: experiment_id = exp.create_experiment( conf.fixtures_path("no_op/single-many-long-steps.yaml"), conf.fixtures_path("no_op"), ) exp.cancel_single(experiment_id) @pytest.mark.e2e_cpu def test_cancel_one_active_experiment_unready() -> None: experiment_id = exp.create_experiment( conf.fixtures_path("no_op/single-many-long-steps.yaml"), conf.fixtures_path("no_op"), ) for _ in range(15): if exp.experiment_has_active_workload(experiment_id): break time.sleep(1) else: raise AssertionError("no workload active after 15 seconds") exp.cancel_single(experiment_id, should_have_trial=True) @pytest.mark.e2e_cpu @pytest.mark.timeout(3 * 60) def test_cancel_one_active_experiment_ready() -> None: experiment_id = exp.create_experiment( conf.tutorials_path("mnist_pytorch/const.yaml"), conf.tutorials_path("mnist_pytorch"), ) while 1: if exp.experiment_has_completed_workload(experiment_id): break time.sleep(1) exp.cancel_single(experiment_id, should_have_trial=True) exp.assert_performed_final_checkpoint(experiment_id) @pytest.mark.e2e_cpu def test_cancel_one_paused_experiment() -> None: experiment_id = exp.create_experiment( conf.fixtures_path("no_op/single-many-long-steps.yaml"), conf.fixtures_path("no_op"), ["--paused"], ) exp.cancel_single(experiment_id) @pytest.mark.e2e_cpu def test_cancel_ten_experiments() -> None: experiment_ids = [ exp.create_experiment( conf.fixtures_path("no_op/single-many-long-steps.yaml"), conf.fixtures_path("no_op"), ) for _ in range(10) ] for experiment_id in experiment_ids: exp.cancel_single(experiment_id) @pytest.mark.e2e_cpu def test_cancel_ten_paused_experiments() -> None: experiment_ids = [ exp.create_experiment( conf.fixtures_path("no_op/single-many-long-steps.yaml"), conf.fixtures_path("no_op"), ["--paused"], ) for _ in range(10) ] for experiment_id in experiment_ids: exp.cancel_single(experiment_id) @pytest.mark.e2e_cpu def test_startup_hook() -> None: exp.run_basic_test( conf.fixtures_path("no_op/startup-hook.yaml"), conf.fixtures_path("no_op"), 1, ) @pytest.mark.e2e_cpu def test_large_model_def_experiment() -> None: with tempfile.TemporaryDirectory() as td: shutil.copy(conf.fixtures_path("no_op/model_def.py"), td) # Write a 94MB file into the directory. Use random data because it is not compressible. with open(os.path.join(td, "junk.txt"), "wb") as f: f.write(os.urandom(94 * 1024 * 1024)) exp.run_basic_test(conf.fixtures_path("no_op/single-one-short-step.yaml"), td, 1) def _test_rng_restore(fixture: str, metrics: list, tf2: Union[None, bool] = None) -> None: """ This test confirms that an experiment can be restarted from a checkpoint with the same RNG state. It requires a test fixture that will emit random numbers from all of the RNGs used in the relevant framework as metrics. The experiment must have a const.yaml, run for at least 3 steps, checkpoint every step, and keep the first checkpoint (either by having metrics get worse over time, or by configuring the experiment to keep all checkpoints). """ config_base = conf.load_config(conf.fixtures_path(fixture + "/const.yaml")) config = copy.deepcopy(config_base) if tf2 is not None: config = conf.set_tf2_image(config) if tf2 else conf.set_tf1_image(config) experiment = exp.run_basic_test_with_temp_config( config, conf.fixtures_path(fixture), 1, ) first_trial = exp.experiment_trials(experiment)[0] assert len(first_trial.workloads or []) >= 4 first_checkpoint = exp.workloads_for_mode(first_trial.workloads, "checkpoint")[0] assert first_checkpoint and first_checkpoint.checkpoint first_checkpoint_uuid = first_checkpoint.checkpoint.uuid config = copy.deepcopy(config_base) if tf2 is not None: config = conf.set_tf2_image(config) if tf2 else conf.set_tf1_image(config) config["searcher"]["source_checkpoint_uuid"] = first_checkpoint.checkpoint.uuid experiment2 = exp.run_basic_test_with_temp_config(config, conf.fixtures_path(fixture), 1) second_trial = exp.experiment_trials(experiment2)[0] assert len(second_trial.workloads or []) >= 4 assert second_trial.trial.warmStartCheckpointUuid == first_checkpoint_uuid first_trial_validations = exp.workloads_for_mode(first_trial.workloads, "validation") second_trial_validations = exp.workloads_for_mode(second_trial.workloads, "validation") for wl in range(0, 2): for metric in metrics: first_trial_val = first_trial_validations[wl + 1] assert ( first_trial_val and first_trial_val.validation and first_trial_val.validation.metrics ) first_metric = first_trial_val.validation.metrics[metric] second_trial_val = second_trial_validations[wl] assert ( second_trial_val and second_trial_val.validation and second_trial_val.validation.metrics ) second_metric = second_trial_val.validation.metrics[metric] assert ( first_metric == second_metric ), f"failures on iteration: {wl} with metric: {metric}" @pytest.mark.e2e_cpu @pytest.mark.parametrize( "tf2", [ pytest.param(True, marks=pytest.mark.tensorflow2_cpu), pytest.param(False, marks=pytest.mark.tensorflow1_cpu), ], ) def test_keras_rng_restore(tf2: bool) -> None: _test_rng_restore("keras_no_op", ["val_rand_rand", "val_np_rand", "val_tf_rand"], tf2=tf2) @pytest.mark.e2e_cpu @pytest.mark.tensorflow1_cpu @pytest.mark.tensorflow2_cpu def test_estimator_rng_restore() -> None: _test_rng_restore("estimator_no_op", ["rand_rand", "np_rand"]) @pytest.mark.e2e_cpu def test_pytorch_cpu_rng_restore() -> None: _test_rng_restore("pytorch_no_op", ["np_rand", "rand_rand", "torch_rand"]) @pytest.mark.e2e_gpu def test_pytorch_gpu_rng_restore() -> None: _test_rng_restore("pytorch_no_op", ["np_rand", "rand_rand", "torch_rand", "gpu_rand"]) @pytest.mark.e2e_cpu def test_noop_experiment_config_override() -> None: config_obj = conf.load_config(conf.fixtures_path("no_op/single-one-short-step.yaml")) with tempfile.NamedTemporaryFile() as tf: with open(tf.name, "w") as f: yaml.dump(config_obj, f) experiment_id = exp.create_experiment( tf.name, conf.fixtures_path("no_op"), ["--config", "reproducibility.experiment_seed=8200"], ) exp_config = exp.experiment_config_json(experiment_id) assert exp_config["reproducibility"]["experiment_seed"] == 8200 exp.cancel_single(experiment_id)
35.309711
100
0.707129
8a2dbef455db7314911f92d9224ff651d6ad6773
3,028
py
Python
src/scripts/swagger_client/models/inline_response200.py
shipyardbuild/circleci-orb
5cc1393aac44ff62b95db5ec725702d8a7dbb216
[ "MIT" ]
null
null
null
src/scripts/swagger_client/models/inline_response200.py
shipyardbuild/circleci-orb
5cc1393aac44ff62b95db5ec725702d8a7dbb216
[ "MIT" ]
4
2021-09-01T21:15:02.000Z
2022-01-04T18:37:48.000Z
src/scripts/swagger_client/models/inline_response200.py
shipyardbuild/circleci-orb
5cc1393aac44ff62b95db5ec725702d8a7dbb216
[ "MIT" ]
null
null
null
# coding: utf-8 """ Shipyard API The official OpenAPI spec for the Shipyard API. # noqa: E501 OpenAPI spec version: 0.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class InlineResponse200(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'data': 'list[object]' } attribute_map = { 'data': 'data' } def __init__(self, data=None): # noqa: E501 """InlineResponse200 - a model defined in Swagger""" # noqa: E501 self._data = None self.discriminator = None if data is not None: self.data = data @property def data(self): """Gets the data of this InlineResponse200. # noqa: E501 :return: The data of this InlineResponse200. # noqa: E501 :rtype: list[object] """ return self._data @data.setter def data(self, data): """Sets the data of this InlineResponse200. :param data: The data of this InlineResponse200. # noqa: E501 :type: list[object] """ self._data = data def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(InlineResponse200, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, InlineResponse200): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
27.279279
80
0.548877
347b02095963564e862d9acd9080cb64ed1dcbac
1,414
py
Python
mc/inventory.py
r58Playz/Minecraft
d7a7b3169f12ff9c3014a51474b2875a65458a8e
[ "MIT" ]
1
2020-01-08T15:20:29.000Z
2020-01-08T15:20:29.000Z
mc/inventory.py
r58Playz/Minecraft
d7a7b3169f12ff9c3014a51474b2875a65458a8e
[ "MIT" ]
1
2020-06-17T23:16:18.000Z
2020-06-19T03:42:45.000Z
mc/inventory.py
r58Playz/Minecraft
d7a7b3169f12ff9c3014a51474b2875a65458a8e
[ "MIT" ]
1
2020-06-16T03:07:30.000Z
2020-06-16T03:07:30.000Z
import pyglet import mc.globals as G from pyglet.gl import * class Hotbar: file='textures/gui/widgets.png' tex = None batch = None vlist = None def __init__(self, winwidth, winheight): self.x, self.y = (winwidth//2)-181, 30 self.tex = pyglet.graphics.TextureGroup(G.RESOURCE_LOADER.texture(self.file)) self.batch = pyglet.graphics.Batch() def add(self): tex_coords = ('t2f',(0,0.915, 0.75,0.915, 0.75,1, 0,1)) self.vlist = self.batch.add(4,GL_QUADS, self.tex, tex_coords, ('v2i', (self.x, self.y, self.x+362, self.y, self.x+362, self.y+44, self.x, self.y+44)), ('c3B', ((127, 127, 127)*4))) def remove(self): self.vlist.delete() #175, 166 class Inventory: file='textures/gui/container/inventory.png' tex = None batch = None vlist = None def __init__(self, winwidth, winheight): self.x, self.y = (winwidth//2)-130, (winheight//2)-110 self.tex = pyglet.graphics.TextureGroup(G.RESOURCE_LOADER.texture(self.file)) self.batch = pyglet.graphics.Batch() def add(self): tex_coords = ('t2f/stream',(0,0.35, 0.69,0.35, 0.69,1, 0,1)) self.vlist = self.batch.add(4,GL_QUADS, self.tex, tex_coords, ('v2i', (self.x, self.y, self.x+250, self.y, self.x+250, self.y+232, self.x, self.y+232)), ('c3B', ((127, 127, 127)*4))) def remove(self): self.vlist.delete()
37.210526
190
0.613154
58adb81fb2f5e2ba8069835bca4e9e4b56c4e14f
12,158
py
Python
src/poliastro/earth/atmosphere/coesa62.py
DhruvJ22/poliastro
ac5fafc6d054b2c545e111e5a6aa32259998074a
[ "MIT" ]
8
2015-05-09T17:21:57.000Z
2020-01-28T06:59:18.000Z
src/poliastro/earth/atmosphere/coesa62.py
DhruvJ22/poliastro
ac5fafc6d054b2c545e111e5a6aa32259998074a
[ "MIT" ]
4
2015-12-29T13:08:01.000Z
2019-12-27T12:58:04.000Z
src/poliastro/earth/atmosphere/coesa62.py
DhruvJ22/poliastro
ac5fafc6d054b2c545e111e5a6aa32259998074a
[ "MIT" ]
1
2016-10-05T08:34:44.000Z
2016-10-05T08:34:44.000Z
""" The U.S. Standard Atmosphere 1966 depicts idealized middle-latitude year-round mean conditions for the range of solar activity that occurs between sunspot minimum and sunspot maximum. +--------+---------+---------+-----------+---------------+---------------+ | Z (km) | H (km) | T (K) | p (mbar) | rho (kg / m3) | beta (K / km) | +--------+---------+---------+-----------+---------------+---------------+ | 0.0 | 0.0 | 288.150 | 1.01325e3 | 1.2250 | -6.5 | +--------+---------+---------+-----------+---------------+---------------+ | 11.019 | 11.0 | 216.650 | 2.2632e2 | 3.6392e-1 | 0.0 | +--------+---------+---------+-----------+---------------+---------------+ | 20.063 | 20.0 | 216.650 | 5.4749e1 | 8.8035e-2 | 1.0 | +--------+---------+---------+-----------+---------------+---------------+ | 32.162 | 32.0 | 228.650 | 8.68014 | 1.3225e-2 | 2.8 | +--------+---------+---------+-----------+---------------+---------------+ | 47.350 | 47.0 | 270.650 | 1.109050 | 1.4275e-3 | 0.0 | +--------+---------+---------+-----------+---------------+---------------+ | 51.413 | 52.0 | 270.650 | 5.90005e-1| 7.5943e-4 | -2.8 | +--------+---------+---------+-----------+---------------+---------------+ | 61.591 | 61.0 | 252.650 | 1.82099e-1| 2.5109e-4 | -2.0 | +--------+---------+---------+-----------+---------------+---------------+ | 79.994 | 79.0 | 180.650 | 1.0377e-2 | 2.001e-5 | 0.0 | +--------+---------+---------+-----------+---------------+---------------+ | 90.0 | 88.743 | 180.650 | 1.6438e-3 | 3.170e-6 | 0.0 | +--------+---------+---------+-----------+---------------+---------------+ | 100.0 | 98.451 | 210.020 | 3.0075e-4 | 4.974e-7 | 5.0 | +--------+---------+---------+-----------+---------------+---------------+ | 110.0 | 108.129 | 257.000 | 7.3544e-5 | 9.829e-8 | 10.0 | +--------+---------+---------+-----------+---------------+---------------+ | 120.0 | 117.776 | 349.490 | 2.5217e-5 | 2.436e-8 | 20.0 | +--------+---------+---------+-----------+---------------+---------------+ | 150.0 | 146.541 | 892.790 | 5.0617e-6 | 1.836e-9 | 15.0 | +--------+---------+---------+-----------+---------------+---------------+ | 160.0 | 156.071 | 1022.23 | 3.6943e-6 | 1.159e-9 | 10.0 | +--------+---------+---------+-----------+---------------+---------------+ | 170.0 | 165.571 | 1105.51 | 2.7926e-6 | 8.036e-10 | 7.0 | +--------+---------+---------+-----------+---------------+---------------+ | 190.0 | 184.485 | 1205.50 | 1.6852e-6 | 4.347e-10 | 5.0 | +--------+---------+---------+-----------+---------------+---------------+ | 230.0 | 221.967 | 1321.70 | 6.9604e-7 | 1.564e-10 | 4.0 | +--------+---------+---------+-----------+---------------+---------------+ | 300.0 | 286.476 | 1432.11 | 1.8838e-7 | 3.585e-11 | 3.3 | +--------+---------+---------+-----------+---------------+---------------+ | 400.0 | 376.312 | 1487.38 | 4.0304e-8 | 6.498e-12 | 2.6 | +--------+---------+---------+-----------+---------------+---------------+ | 500.0 | 463.526 | 1499.22 | 1.0957e-8 | 1.577e-12 | 1.7 | +--------+---------+---------+-----------+---------------+---------------+ | 600.0 | 548.230 | 1506.13 | 3.4502e-9 | 4.640e-13 | 1.1 | +--------+---------+---------+-----------+---------------+---------------+ | 700.0 | 630.530 | 1507.61 | 1.1918e-9 | 1.537e-13 | 0.0 | +--------+---------+---------+-----------+---------------+---------------+ """ import numpy as np from astropy import units as u from astropy.io import ascii from astropy.units import imperial from astropy.utils.data import get_pkg_data_filename from poliastro._math.integrate import quad from poliastro.earth.atmosphere.base import COESA # Constants come from the original paper to achieve pure implementation r0 = 6356.766 * u.km p0 = 1.013250e5 * u.Pa rho0 = 1.2250 * u.K T0 = 288.15 * u.K g0 = 9.80665 * u.m / u.s**2 S = 110.4 * u.K Ti = 273.15 * u.K beta = 1.458e-6 * u.kg / u.s / u.m / u.K ** (0.5) _gamma = 1.4 sigma = 3.65e-10 * u.m N = 6.02257e26 * (u.kg * u.mol) ** -1 R = 8314.32 * u.J / u.kmol / u.K R_air = 287.053 * u.J / u.kg / u.K alpha = 34.1632 * u.K / u.km # Reading layer parameters file coesa_file = get_pkg_data_filename("data/coesa62.dat") coesa62_data = ascii.read(coesa_file) b_levels = coesa62_data["b"].data zb_levels = coesa62_data["Zb [km]"].data * u.km hb_levels = coesa62_data["Hb [km]"].data * u.km Tb_levels = coesa62_data["Tb [K]"].data * u.K Lb_levels = coesa62_data["Lb [K/km]"].data * u.K / u.km pb_levels = coesa62_data["pb [mbar]"].data * u.mbar class COESA62(COESA): """Holds the model for U.S Standard Atmosphere 1962.""" def __init__(self): """Constructor for the class.""" super().__init__( b_levels, zb_levels, hb_levels, Tb_levels, Lb_levels, pb_levels ) def temperature(self, alt, geometric=True): """Solves for temperature at given altitude. Parameters ---------- alt : ~astropy.units.Quantity Geometric/Geopotential altitude. geometric : bool If `True`, assumes geometric altitude kind. Returns ------- T: ~astropy.units.Quantity Kinetic temeperature. """ # Test if altitude is inside valid range z, h = self._check_altitude(alt, r0, geometric=geometric) # Get base parameters i = self._get_index(z, self.zb_levels) zb = self.zb_levels[i] Tb = self.Tb_levels[i] Lb = self.Lb_levels[i] hb = self.hb_levels[i] # Apply different equations if z <= 90 * u.km: T = Tb + Lb * (h - hb) else: T = Tb + Lb * (z - zb) return T.to(u.K) def pressure(self, alt, geometric=True): """Solves pressure at given altitude. Parameters ---------- alt : ~astropy.units.Quantity Geometric/Geopotential altitude. geometric : bool If `True`, assumes geometric altitude. Returns ------- p: ~astropy.units.Quantity Pressure at given altitude. """ # Check if valid range and convert to geopotential z, h = self._check_altitude(alt, r0, geometric=geometric) # Get base parameters i = self._get_index(z, self.zb_levels) zb = self.zb_levels[i] hb = self.hb_levels[i] Tb = self.Tb_levels[i] Lb = self.Lb_levels[i] pb = self.pb_levels[i] # If z <= 90km then apply eqn 1.2.10-(3) if z <= 90 * u.km: # If Lb is zero then apply eqn 1.2.10-(4) if Lb == 0.0: p = pb * np.exp(-g0 * (h - hb) / Tb / R_air) else: T = self.temperature(z) p = pb * (T / Tb) ** (-g0 / R_air / Lb) # If 90 < Z < 700 km then eqn 1.2.10-(5) is applied else: # Converting all the units into SI unit and taking their magnitude Lb_v = Lb.to_value(u.K / u.m) r0_v = r0.to_value(u.m) z_v = z.to_value(u.m) zb_v = zb.to_value(u.m) Tb_v = Tb.value g0_v = g0.value R_air_v = R_air.value # Putting g = (g0*(r0/(r0 +z))**2) in (g * dz / z - zb + Tb/Lb) # and integrating it. integrand = quad( lambda x: (g0_v * (r0_v / (r0_v + x)) ** 2) / (x - zb_v + Tb_v / Lb_v), zb_v, z_v, ) pb = pb.to(u.Pa) p = (pb * np.exp((-1 / R_air_v / Lb_v) * integrand[0])).to(u.mbar) return p def density(self, alt, geometric=True): """Solves density at given altitude. Parameters ---------- alt : ~astropy.units.Quantity Geometric/Geopotential altitude. geometric : bool If `True`, assumes geometric altitude. Returns ------- rho: ~astropy.units.Quantity Density at given altitude. """ # Check if valid range and convert to geopotential z, h = self._check_altitude(alt, r0, geometric=geometric) # Solve temperature and pressure T = self.temperature(z) p = self.pressure(z) rho = p / R_air / T return rho.to(u.kg / u.m**3) def properties(self, alt, geometric=True): """Solves density at given height. Parameters ---------- alt : ~astropy.units.Quantity Geometric/Geopotential height. geometric : bool If `True`, assumes that `alt` argument is geometric kind. Returns ------- T: ~astropy.units.Quantity Temperature at given height. p: ~astropy.units.Quantity Pressure at given height. rho: ~astropy.units.Quantity Density at given height. """ T = self.temperature(alt, geometric=geometric) p = self.pressure(alt, geometric=geometric) rho = self.density(alt, geometric=geometric) return T, p, rho def sound_speed(self, alt, geometric=True): """Solves speed of sound at given height. Parameters ---------- alt : ~astropy.units.Quantity Geometric/Geopotential height. geometric : bool If `True`, assumes that `alt` argument is geometric kind. Returns ------- Cs: ~astropy.units.Quantity Speed of Sound at given height. """ # Check if valid range and convert to geopotential z, h = self._check_altitude(alt, r0, geometric=geometric) if z > 90 * u.km: raise ValueError( "Speed of sound in COESA62 has just been implemented up to 90km." ) T = self.temperature(alt, geometric).value # Using eqn-1.3.7-(1) Cs = ((_gamma * R_air.value * T) ** 0.5) * (u.m / u.s) return Cs def viscosity(self, alt, geometric=True): """Solves dynamic viscosity at given height. Parameters ---------- alt : ~astropy.units.Quantity Geometric/Geopotential height. geometric : bool If `True`, assumes that `alt` argument is geometric kind. Returns ------- mu: ~astropy.units.Quantity Dynamic viscosity at given height. """ # Check if valid range and convert to geopotential z, h = self._check_altitude(alt, r0, geometric=geometric) if z > 90 * u.km: raise ValueError( "Dynamic Viscosity in COESA62 has just been implemented up to 90km." ) T = self.temperature(alt, geometric).value # Using eqn-1.3.8-(1) mu = (beta.value * T**1.5 / (T + S.value)) * (u.kg / u.m / u.s) return mu def thermal_conductivity(self, alt, geometric=True): """Solves coefficient of thermal conductivity at given height. Parameters ---------- alt : ~astropy.units.Quantity Geometric/Geopotential height. geometric : bool If `True`, assumes that `alt` argument is geometric kind. Returns ------- k: ~astropy.units.Quantity coefficient of thermal conductivity at given height. """ # Check if valid range and convert to geopotential z, h = self._check_altitude(alt, r0, geometric=geometric) if z > 90 * u.km: raise ValueError( "Thermal conductivity in COESA62 has just been implemented up to 90km." ) T = self.temperature(alt, geometric=geometric).value # Using eqn-1.3.10-(1) k = (6.325e-7 * T**1.5 / (T + 245.4 * (10 ** (-12.0 / T)))) * ( imperial.kcal / u.m / u.s / u.K ) return k
36.731118
87
0.449252
6144b2af1bc515fd69c8cad60ad3bfaeac63dc63
1,385
py
Python
app.py
Sravanalakshmi123/FAKE_NEWS
6d8da534d3f0e79275c4293643b820967308aab1
[ "MIT" ]
null
null
null
app.py
Sravanalakshmi123/FAKE_NEWS
6d8da534d3f0e79275c4293643b820967308aab1
[ "MIT" ]
null
null
null
app.py
Sravanalakshmi123/FAKE_NEWS
6d8da534d3f0e79275c4293643b820967308aab1
[ "MIT" ]
null
null
null
from flask import Flask, render_template, url_for, request import pandas as pd import pickle import re import os import numpy as np app = Flask(__name__) # Used by bow pickle file def clean_article(article): art = re.sub("[^A-Za-z0-9' ]", '', str(article)) art2 = re.sub("[( ' )(' )( ')]", ' ', str(art)) art3 = re.sub("\s[A-Za-z]\s", ' ', str(art2)) return art3.lower() bow = pickle.load(open("bow.pkl", "rb")) model = pickle.load(open("model.pkl", "rb")) @app.route('/') def home(): return render_template('home.html') @app.route('/predict', methods=['POST']) def predict(): if request.method == 'POST': comment = request.form['article'] list_comment = [comment] list_comment = clean_article(list_comment) list_comment = [list_comment] vect = bow.transform(list_comment) vect = pd.DataFrame(vect.toarray()) vect.columns = bow.get_feature_names() prediction_array = model.predict(vect) proba_array = model.predict_proba(vect) maxProba = np.amax(proba_array) maxProba = format(maxProba, ".2%") print(maxProba) return render_template('result.html', prediction=prediction_array, proba = maxProba) if __name__ == '__main__': app.run(debug=True) #bow = pickle.load(open("bow.pkl", "rb")) #model = pickle.load(open("model.pkl", "rb"))
23.87931
88
0.626715
8648f7b9cda4f231a176a55acf845f4832ce4b37
28,620
py
Python
app/models.py
ukblumf/randomise-it
0610721eba649dfa205b0d3c4b3e24d67aa1d781
[ "MIT" ]
null
null
null
app/models.py
ukblumf/randomise-it
0610721eba649dfa205b0d3c4b3e24d67aa1d781
[ "MIT" ]
null
null
null
app/models.py
ukblumf/randomise-it
0610721eba649dfa205b0d3c4b3e24d67aa1d781
[ "MIT" ]
null
null
null
from datetime import datetime import hashlib from werkzeug.security import generate_password_hash, check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from markdown import markdown import bleach from flask import current_app, request, url_for from flask_login import UserMixin, AnonymousUserMixin from app.exceptions import ValidationError from . import db, login_manager from app.public_models import * class Permission: FOLLOW = 0x01 COMMENT = 0x02 WRITE_ARTICLES = 0x04 MODERATE_COMMENTS = 0x08 ADMINISTER = 0x80 class ProductPermission: PUBLIC = 1 COMMERCIAL = 2 OPEN = 4 EDITABLE = 8 PRIVATE = 0 PUBLIC_OPEN = 5 PUBLIC_OPEN_EDITABLE = 13 COMMERCIAL_OPEN = 6 COMMERCIAL_OPEN_EDITABLE = 14 class Role(db.Model): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) default = db.Column(db.Boolean, default=False, index=True) permissions = db.Column(db.Integer) users = db.relationship('User', backref='role', lazy='dynamic') @staticmethod def insert_roles(): roles = { 'User': (Permission.FOLLOW | Permission.COMMENT | Permission.WRITE_ARTICLES, True), 'Moderator': (Permission.FOLLOW | Permission.COMMENT | Permission.WRITE_ARTICLES | Permission.MODERATE_COMMENTS, False), 'Administrator': (0xff, False) } for r in roles: role = Role.query.filter_by(name=r).first() if role is None: role = Role(name=r) role.permissions = roles[r][0] role.default = roles[r][1] db.session.add(role) db.session.commit() def __repr__(self): return '<Role %r>' % self.name # class Follow(db.Model): # __tablename__ = 'follows' # follower_id = db.Column(db.Integer, db.ForeignKey('users.id'), # primary_key=True) # followed_id = db.Column(db.Integer, db.ForeignKey('users.id'), # primary_key=True) # timestamp = db.Column(db.DateTime, default=datetime.utcnow) class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(64), unique=True, index=True) username = db.Column(db.String(64), unique=True, index=True) role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) password_hash = db.Column(db.String(128)) confirmed = db.Column(db.Boolean, default=False) name = db.Column(db.String(64)) location = db.Column(db.String(64)) about_me = db.Column(db.Text()) member_since = db.Column(db.DateTime(), default=datetime.utcnow) last_seen = db.Column(db.DateTime(), default=datetime.utcnow) avatar_hash = db.Column(db.String(32)) share_ban = db.Column(db.Boolean, default=False) share_ban_until = db.Column(db.DateTime()) share_ban_description = db.Column(db.String(512)) login_ban = db.Column(db.Boolean, default=False) login_ban_until = db.Column(db.DateTime()) login_ban_description = db.Column(db.String(512)) posts = db.relationship('Post', backref='author', lazy='dynamic') tables = db.relationship('RandomTable', backref='author', lazy='dynamic') macros = db.relationship('Macros', backref='author', lazy='dynamic') public_announcements = db.relationship('PublicAnnouncements', backref='author', lazy='dynamic') collections = db.relationship('Collection', backref='author', lazy='dynamic') public_tables = db.relationship('PublicRandomTable', backref='author', lazy='dynamic') public_macros = db.relationship('PublicMacros', backref='author', lazy='dynamic') public_collections = db.relationship('PublicCollection', backref='author', lazy='dynamic') public_linked_tables = db.relationship('PublicLinkedTables', foreign_keys=[PublicLinkedTables.original_author_id], backref=db.backref('original_author', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') public_linked_macros = db.relationship('PublicLinkedMacros', foreign_keys=[PublicLinkedMacros.original_author_id], backref=db.backref('original_author', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') public_linked_collections = db.relationship('PublicLinkedCollections', foreign_keys=[PublicLinkedCollections.original_author_id], backref=db.backref('original_author', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan') # followed = db.relationship('Follow', # foreign_keys=[Follow.follower_id], # backref=db.backref('follower', lazy='joined'), # lazy='dynamic', # cascade='all, delete-orphan') # followers = db.relationship('Follow', # foreign_keys=[Follow.followed_id], # backref=db.backref('followed', lazy='joined'), # lazy='dynamic', # cascade='all, delete-orphan') # comments = db.relationship('Comment', backref='author', lazy='dynamic') @staticmethod def generate_fake(count=100): from sqlalchemy.exc import IntegrityError from random import seed import forgery_py seed() for i in range(count): u = User(email=forgery_py.internet.email_address(), username=forgery_py.internet.user_name(True), password=forgery_py.lorem_ipsum.word(), confirmed=True, name=forgery_py.name.full_name(), location=forgery_py.address.city(), about_me=forgery_py.lorem_ipsum.sentence(), member_since=forgery_py.date.date(True)) db.session.add(u) try: db.session.commit() except IntegrityError: db.session.rollback() # @staticmethod # def add_self_follows(): # for user in User.query.all(): # if not user.is_following(user): # user.follow(user) # db.session.add(user) # db.session.commit() def __init__(self, **kwargs): super(User, self).__init__(**kwargs) if self.role is None: if self.email == current_app.config['RANDOMIST_ADMIN']: self.role = Role.query.filter_by(permissions=0xff).first() if self.role is None: self.role = Role.query.filter_by(default=True).first() if self.email is not None and self.avatar_hash is None: self.avatar_hash = hashlib.md5( self.email.encode('utf-8')).hexdigest() # self.followed.append(Follow(followed=self)) @property def password(self): raise AttributeError('password is not a readable attribute') @password.setter def password(self, password): self.password_hash = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.password_hash, password) def generate_confirmation_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id}) def confirm(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False if data.get('confirm') != self.id: return False self.confirmed = True db.session.add(self) return True def generate_reset_token(self, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'reset': self.id}) def reset_password(self, token, new_password): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False if data.get('reset') != self.id: return False self.password = new_password db.session.add(self) return True def generate_email_change_token(self, new_email, expiration=3600): s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'change_email': self.id, 'new_email': new_email}) def change_email(self, token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return False if data.get('change_email') != self.id: return False new_email = data.get('new_email') if new_email is None: return False if self.query.filter_by(email=new_email).first() is not None: return False self.email = new_email self.avatar_hash = hashlib.md5( self.email.encode('utf-8')).hexdigest() db.session.add(self) return True def can(self, permissions): return self.role is not None and \ (self.role.permissions & permissions) == permissions def is_administrator(self): return self.can(Permission.ADMINISTER) def ping(self): self.last_seen = datetime.utcnow() db.session.add(self) def gravatar(self, size=100, default='identicon', rating='g'): # if request.is_secure: url = 'https://secure.gravatar.com/avatar' # else: # url = 'http://www.gravatar.com/avatar' hash = self.avatar_hash or hashlib.md5( self.email.encode('utf-8')).hexdigest() return '{url}/{hash}?s={size}&d={default}&r={rating}'.format( url=url, hash=hash, size=size, default=default, rating=rating) # def follow(self, user): # if not self.is_following(user): # f = Follow(follower=self, followed=user) # db.session.add(f) # # def unfollow(self, user): # f = self.followed.filter_by(followed_id=user.id).first() # if f: # db.session.delete(f) # def is_following(self, user): # return self.followed.filter_by( # followed_id=user.id).first() is not None # # def is_followed_by(self, user): # return self.followers.filter_by( # follower_id=user.id).first() is not None # # @property # def followed_posts(self): # return Post.query.join(Follow, Follow.followed_id == Post.author_id) \ # .filter(Follow.follower_id == self.id) def to_json(self): json_user = { 'url': url_for('api.get_user', id=self.id, _external=True), 'username': self.username, 'member_since': self.member_since, 'last_seen': self.last_seen, 'posts': url_for('api.get_user_posts', id=self.id, _external=True), 'post_count': self.posts.count() } return json_user def generate_auth_token(self, expiration): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.id}).decode('ascii') @staticmethod def verify_auth_token(token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return None return User.query.get(data['id']) def __repr__(self): return '<User %r>' % self.username class AnonymousUser(AnonymousUserMixin): def can(self, permissions): return False def is_administrator(self): return False login_manager.anonymous_user = AnonymousUser @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class Post(db.Model): __tablename__ = 'posts' id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.Text) body = db.Column(db.Text) body_html = db.Column(db.Text) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) author_id = db.Column(db.Integer, db.ForeignKey('users.id')) pins = db.Column(db.Text) last_modified = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) # comments = db.relationship('Comment', backref='post', lazy='dynamic') @staticmethod def on_changed_body(target, value, oldvalue, initiator): allowed_tags = ['a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul', 'h1', 'h2', 'h3', 'p'] target.body_html = bleach.linkify(bleach.clean( markdown(value, output_format='html'), tags=allowed_tags, strip=True)) def to_json(self): json_post = { 'url': url_for('api.get_post', id=self.id, _external=True), 'title': self.title, 'body': self.body, 'body_html': self.body_html, 'pins': self.pins, 'timestamp': self.timestamp, 'author': url_for('api.get_user', id=self.author_id, _external=True) } return json_post @staticmethod def from_json(json_post): body = json_post.get('body') if body is None or body == '': raise ValidationError('post does not have a body') title = json_post.get('title') return Post(body=body, title=title) db.event.listen(Post.body, 'set', Post.on_changed_body) # class Comment(db.Model): # __tablename__ = 'comments' # id = db.Column(db.Integer, primary_key=True) # body = db.Column(db.Text) # body_html = db.Column(db.Text) # timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) # disabled = db.Column(db.Boolean) # author_id = db.Column(db.Integer, db.ForeignKey('users.id')) # # @staticmethod # def on_changed_body(target, value, oldvalue, initiator): # allowed_tags = ['a', 'abbr', 'acronym', 'b', 'code', 'em', 'i', # 'strong'] # target.body_html = bleach.linkify(bleach.clean( # markdown(value, output_format='html'), # tags=allowed_tags, strip=True)) # # def to_json(self): # json_comment = { # 'url': url_for('api.get_comment', id=self.id, _external=True), # 'body': self.body, # 'body_html': self.body_html, # 'timestamp': self.timestamp, # 'author': url_for('api.get_user', id=self.author_id, # _external=True), # } # return json_comment # # @staticmethod # def from_json(json_comment): # body = json_comment.get('body') # if body is None or body == '': # raise ValidationError('comment does not have a body') # return Comment(body=body) # # db.event.listen(Comment.body, 'set', Comment.on_changed_body) class RandomTable(db.Model): __tablename__ = 'random_table' id = db.Column(db.Text, primary_key=True) author_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True) name = db.Column(db.Text) description = db.Column(db.Text) definition = db.Column(db.Text) min = db.Column(db.Integer) max = db.Column(db.Integer) description_html = db.Column(db.Text) permissions = db.Column(db.Integer, index=True) line_type = db.Column(db.Integer) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) tags = db.Column(db.Text, index=True) original_author_id = db.Column(db.Integer) row_count = db.Column(db.Integer) modifier_name = db.Column(db.Text) last_modified = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) supporting = db.Column(db.Boolean, default=False) visible_contents = db.Column(db.Boolean, default=False) @staticmethod def on_changed_table(target, value, oldvalue, initiator): allowed_tags = ['a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul', 'h1', 'h2', 'h3', 'p'] target.description_html = bleach.linkify(bleach.clean( markdown(value, output_format='html'), tags=allowed_tags, strip=True)) def to_json(self): definition = self.definition.splitlines() json_post = { 'url': url_for('api.get_table', id=self.id, _external=True), 'id': self.id, 'name': self.name, 'description': self.description, 'definition': definition, 'permissions': self.permissions, 'timestamp': self.timestamp, 'author': url_for('api.get_user', id=self.author_id, _external=True), 'tags': self.tags, 'original_author_id': self.original_author_id } return json_post @staticmethod def from_json(json_post): # check required fields for field in ('id', 'name', 'definition'): value = json_post.get(field) if value is None or value == '': raise ValidationError('Missing Field: ' + field) id = json_post.get('id') name = json_post.get('name') description = json_post.get('description') definition_lines = json_post.get('definition') definition = "" for idx, line in enumerate(definition_lines): definition += line if idx < len(definition_lines) - 1: definition += "\n" # permisssions = json_post.get('permissions') return RandomTable(id=id, name=name, description=description, definition=definition) db.event.listen(RandomTable.description, 'set', RandomTable.on_changed_table) class Macros(db.Model): __tablename__ = 'macros' id = db.Column(db.Text, primary_key=True) author_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True) name = db.Column(db.Text) definition = db.Column(db.Text) definition_html = db.Column(db.Text) permissions = db.Column(db.Integer, index=True) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) tags = db.Column(db.Text, index=True) original_author_id = db.Column(db.Integer) last_modified = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) supporting = db.Column(db.Boolean, default=False) visible_contents = db.Column(db.Boolean, default=False) @staticmethod def on_changed_table(target, value, oldvalue, initiator): allowed_tags = ['a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul', 'h1', 'h2', 'h3', 'p'] target.definition_html = bleach.linkify(bleach.clean( markdown(value, output_format='html'), tags=allowed_tags, strip=True)) def to_json(self): definition = self.definition.splitlines() json_post = { 'url': url_for('api.get_macro', id=self.id, _external=True), 'id': self.id, 'name': self.name, 'definition': definition, 'permissions': self.permissions, 'timestamp': self.timestamp, 'author': url_for('api.get_user', id=self.author_id, _external=True), 'tags': self.tags, 'original_author_id': self.original_author_id } return json_post @staticmethod def from_json(json_post): # check required fields for field in ('id', 'name', 'definition'): value = json_post.get(field) if value is None or value == '': raise ValidationError('Missing Field: ' + field) id = json_post.get('id') name = json_post.get('name') definition_lines = json_post.get('definition') definition = "" for idx, line in enumerate(definition_lines): definition += line if idx < len(definition_lines) - 1: definition += "\n" # permissions = json_post.get('permissions') return Macros(id=id, name=name, definition=definition) db.event.listen(Macros.definition, 'set', Macros.on_changed_table) class Collection(db.Model): __tablename__ = 'collection' id = db.Column(db.Text, primary_key=True) author_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True) name = db.Column(db.Text) description = db.Column(db.Text) definition = db.Column(db.Text) permissions = db.Column(db.Integer, index=True) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) tags = db.Column(db.Text, index=True) original_author_id = db.Column(db.Integer) last_modified = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) supporting = db.Column(db.Boolean, default=False) def to_json(self): items = self.items.splitlines() json_post = { 'url': url_for('api.get_collection', id=self.id, _external=True), 'id': self.id, 'name': self.name, 'description': self.description, 'definition': items, 'parent': self.parent, 'permissions': self.permissions, 'timestamp': self.timestamp, 'author': url_for('api.get_user', id=self.author_id, _external=True), 'tags': self.tags, 'original_author_id': self.original_author_id } return json_post @staticmethod def from_json(json_post): # check required fields for field in ('id', 'name', 'definition', 'parent'): value = json_post.get(field) if value is None or value == '': raise ValidationError('Missing Field: ' + field) id = json_post.get('id') name = json_post.get('name') definition_lines = json_post.get('definition') parent = json_post.get('parent') description = json_post.get('description') definition = "" for idx, line in enumerate(definition_lines): definition += line if idx < len(definition_lines) - 1: definition += "\n" # permissions = json_post.get('permissions') return Collection(id=id, name=name, definition=definition, parent=parent, description=description) class Tags(db.Model): __tablename__ = 'tags' id = db.Column(db.Text, primary_key=True) author_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) def to_json(self): json_post = { 'url': url_for('api.get_macro', id=self.id, _external=True), 'id': self.id, 'timestamp': self.timestamp, 'author': url_for('api.get_user', id=self.author_id, _external=True) } return json_post @staticmethod def from_json(json_post): # check required fields for field in ('id'): value = json_post.get(field) if value is None or value == '': raise ValidationError('Missing Field: ' + field) id = json_post.get('id') return Tags(id=id) class MarketPlace(db.Model): __tablename__ = 'marketplace' id = db.Column(db.Integer, primary_key=True) author_id = db.Column(db.Integer, db.ForeignKey('users.id')) name = db.Column(db.Text) description = db.Column(db.Text) description_html = db.Column(db.Text) tags = db.Column(db.Text, index=True) permissions = db.Column(db.Integer) count = db.Column(db.Integer, default=0) price = db.Column(db.Float, default=0) on_sale = db.Column(db.Boolean, default=False) sale_price = db.Column(db.Float, default=0) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) categories = db.relationship('MarketCategory', backref='market_product', lazy='dynamic') last_modified = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) @staticmethod def on_changed_body(target, value, oldvalue, initiator): allowed_tags = ['a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul', 'h1', 'h2', 'h3', 'p'] target.description_html = bleach.linkify(bleach.clean( markdown(value, output_format='html'), tags=allowed_tags, strip=True)) def to_json(self): json_post = { 'id': self.id, 'name': self.name, 'description': self.description, 'description_html': self.description_html, 'tags': self.tags, 'permissions': self.permissions, 'timestamp': self.timestamp, 'author': url_for('api.get_user', id=self.author_id, _external=True) } return json_post @staticmethod def from_json(json_post): # check required fields for field in ('name', 'description', 'product_id'): value = json_post.get(field) if value is None or value == '': raise ValidationError('Missing Field: ' + field) name = json_post.get('name') description = json_post.get('description') tags = str(json_post.get('tags')) permissions = 0 return MarketPlace(name=name, description=description, product_id=product_id, permissions=permissions) db.event.listen(MarketPlace.description, 'set', MarketPlace.on_changed_body) class MarketCategory(db.Model): __tablename__ = 'market_category' author_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True) marketplace_id = db.Column(db.Integer, db.ForeignKey('marketplace.id'), primary_key=True) category_id = db.Column(db.Text, primary_key=True) def to_json(self): json_post = { 'author': url_for('api.get_user', id=self.author_id, _external=True), 'marketplace_id': self.marketplace_id, 'category_id': self.category_id } return json_post @staticmethod def from_json(json_post): # check required fields for field in ('marketplace_id', 'category_id'): value = json_post.get(field) if value is None or value == '': raise ValidationError('Missing Field: ' + field) marketplace_id = json_post.get('marketplace_id') category_id = json_post.get('category_id') return MarketCategory(marketplace_id=marketplace_id, category_id=category_id)
39.151847
111
0.573655
429960c42f6dba6516a4568e280e7a1048d0f58d
4,444
py
Python
kineticstoolkit/external/icp.py
alcantarar/kineticstoolkit
d73f6a1102ca40376e52a8ab8575d7fa9591834f
[ "Apache-2.0" ]
13
2020-10-08T12:53:34.000Z
2022-02-27T17:20:15.000Z
kineticstoolkit/external/icp.py
alcantarar/kineticstoolkit
d73f6a1102ca40376e52a8ab8575d7fa9591834f
[ "Apache-2.0" ]
81
2020-10-08T11:49:05.000Z
2022-03-06T23:26:18.000Z
kineticstoolkit/external/icp.py
alcantarar/kineticstoolkit
d73f6a1102ca40376e52a8ab8575d7fa9591834f
[ "Apache-2.0" ]
1
2021-09-14T02:59:04.000Z
2021-09-14T02:59:04.000Z
# Copyright 2016 Clay Flannigan # # 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. """ Python implementation of m-dimensional Iterative Closest Point method. Author: Clay Flannigan https://github.com/ClayFlannigan/icp Python implementation of m-dimensional Iterative Closest Point method. ICP finds a best fit rigid body transformation between two point sets. Correspondence between the points is not assumed. Included is an SVD-based least-squared best-fit algorithm for corresponding point sets. """ import numpy as np from sklearn.neighbors import NearestNeighbors def best_fit_transform(A, B): ''' Calculates the least-squares best-fit transform that maps corresponding points A to B in m spatial dimensions Input: A: Nxm numpy array of corresponding points B: Nxm numpy array of corresponding points Returns: T: (m+1)x(m+1) homogeneous transformation matrix that maps A on to B R: mxm rotation matrix t: mx1 translation vector ''' assert A.shape == B.shape # get number of dimensions m = A.shape[1] # translate points to their centroids centroid_A = np.mean(A, axis=0) centroid_B = np.mean(B, axis=0) AA = A - centroid_A BB = B - centroid_B # rotation matrix H = np.dot(AA.T, BB) U, S, Vt = np.linalg.svd(H) R = np.dot(Vt.T, U.T) # special reflection case if np.linalg.det(R) < 0: Vt[m-1, :] *= -1 R = np.dot(Vt.T, U.T) # translation t = centroid_B.T - np.dot(R, centroid_A.T) # homogeneous transformation T = np.identity(m+1) T[:m, :m] = R T[:m, m] = t return T, R, t def nearest_neighbor(src, dst): ''' Find the nearest (Euclidean) neighbor in dst for each point in src Input: src: Nxm array of points dst: Nxm array of points Output: distances: Euclidean distances of the nearest neighbor indices: dst indices of the nearest neighbor ''' assert src.shape == dst.shape neigh = NearestNeighbors(n_neighbors=1) neigh.fit(dst) distances, indices = neigh.kneighbors(src, return_distance=True) return distances.ravel(), indices.ravel() def icp(A, B, init_pose=None, max_iterations=20, tolerance=0.001): ''' The Iterative Closest Point method: finds best-fit transform that maps points A on to points B Input: A: Nxm numpy array of source mD points B: Nxm numpy array of destination mD point init_pose: (m+1)x(m+1) homogeneous transformation max_iterations: exit algorithm after max_iterations tolerance: convergence criteria Output: T: final homogeneous transformation that maps A on to B distances: Euclidean distances (errors) of the nearest neighbor i: number of iterations to converge ''' assert A.shape == B.shape # get number of dimensions m = A.shape[1] # make points homogeneous, copy them to maintain the originals src = np.ones((m+1, A.shape[0])) dst = np.ones((m+1, B.shape[0])) src[:m, :] = np.copy(A.T) dst[:m, :] = np.copy(B.T) # apply the initial pose estimation if init_pose is not None: src = np.dot(init_pose, src) prev_error = 0 for i in range(max_iterations): # find the nearest neighbors between the current source and destination points distances, indices = nearest_neighbor(src[:m, :].T, dst[:m, :].T) # compute the transformation between the current source and nearest destination points T, _, _ = best_fit_transform(src[:m, :].T, dst[:m, indices].T) # update the current source src = np.dot(T, src) # check error mean_error = np.mean(distances) if np.abs(prev_error - mean_error) < tolerance: break prev_error = mean_error # calculate final transformation T, _, _ = best_fit_transform(A, src[:m, :].T) return T, distances, i
30.438356
113
0.667417
8e2aba32e16d061dbecca31db6777cc49f460602
75,594
py
Python
saleor/graphql/order/tests/test_fulfillment.py
victor-abz/saleor
f8e2b49703d995d4304d5a690dbe9c83631419d0
[ "CC-BY-4.0" ]
1
2022-03-25T00:21:11.000Z
2022-03-25T00:21:11.000Z
saleor/graphql/order/tests/test_fulfillment.py
victor-abz/saleor
f8e2b49703d995d4304d5a690dbe9c83631419d0
[ "CC-BY-4.0" ]
86
2021-11-01T04:51:55.000Z
2022-03-30T16:30:16.000Z
saleor/graphql/order/tests/test_fulfillment.py
victor-abz/saleor
f8e2b49703d995d4304d5a690dbe9c83631419d0
[ "CC-BY-4.0" ]
1
2021-12-28T18:02:49.000Z
2021-12-28T18:02:49.000Z
from unittest.mock import ANY, patch import graphene import pytest from ....core.exceptions import InsufficientStock, InsufficientStockData from ....giftcard import GiftCardEvents from ....giftcard.models import GiftCard, GiftCardEvent from ....order import OrderStatus from ....order.actions import fulfill_order_lines from ....order.error_codes import OrderErrorCode from ....order.events import OrderEvents from ....order.fetch import OrderLineInfo from ....order.models import Fulfillment, FulfillmentLine, FulfillmentStatus, OrderLine from ....plugins.manager import get_plugins_manager from ....product.models import Product, ProductVariant from ....tests.utils import flush_post_commit_hooks from ....warehouse.models import Allocation, Stock from ...tests.utils import assert_no_permission, get_graphql_content ORDER_FULFILL_QUERY = """ mutation fulfillOrder( $order: ID, $input: OrderFulfillInput! ) { orderFulfill( order: $order, input: $input ) { errors { field code message warehouse orderLines } } } """ @patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock") def test_order_fulfill_with_out_of_stock_webhook( product_variant_out_of_stock_webhooks, staff_api_client, order_with_lines, permission_manage_orders, warehouse, ): order = order_with_lines query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order.id) _, order_line2 = order.lines.all() order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) variables = { "order": order_id, "input": { "notifyCustomer": True, "lines": [ { "orderLineId": order_line2_id, "stocks": [{"quantity": 2, "warehouse": warehouse_id}], }, ], }, } staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) stock = order_line2.variant.stocks.filter(warehouse=warehouse).first() product_variant_out_of_stock_webhooks.assert_called_once_with(stock) @pytest.mark.parametrize("fulfillment_auto_approve", [True, False]) @patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments") def test_order_fulfill( mock_create_fulfillments, fulfillment_auto_approve, staff_api_client, staff_user, order_with_lines, permission_manage_orders, warehouse, site_settings, ): site_settings.fulfillment_auto_approve = fulfillment_auto_approve site_settings.save(update_fields=["fulfillment_auto_approve"]) order = order_with_lines query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order.id) order_line, order_line2 = order.lines.all() order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) variables = { "order": order_id, "input": { "notifyCustomer": True, "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": 3, "warehouse": warehouse_id}], }, { "orderLineId": order_line2_id, "stocks": [{"quantity": 2, "warehouse": warehouse_id}], }, ], }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert not data["errors"] fulfillment_lines_for_warehouses = { str(warehouse.pk): [ {"order_line": order_line, "quantity": 3}, {"order_line": order_line2, "quantity": 2}, ] } mock_create_fulfillments.assert_called_once_with( staff_user, None, order, fulfillment_lines_for_warehouses, ANY, site_settings, True, allow_stock_to_be_exceeded=False, approved=fulfillment_auto_approve, ) def test_order_fulfill_with_stock_exceeded_with_flag_disabled( staff_api_client, staff_user, order_with_lines, permission_manage_orders, warehouse, ): order = order_with_lines query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order.id) order_line, order_line2 = order.lines.all() order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) # set stocks to out of quantity and assert Stock.objects.filter(warehouse=warehouse).update(quantity=0) # make first stock quantity < 0 stock = Stock.objects.filter(warehouse=warehouse).first() stock.quantity = -99 stock.save() for stock in Stock.objects.filter(warehouse=warehouse): assert stock.quantity <= 0 variables = { "order": order_id, "input": { "notifyCustomer": False, "allowStockToBeExceeded": False, "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": 3, "warehouse": warehouse_id}], }, { "orderLineId": order_line2_id, "stocks": [{"quantity": 2, "warehouse": warehouse_id}], }, ], }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert data["errors"] errors = data["errors"] assert errors[0]["code"] == "INSUFFICIENT_STOCK" assert errors[0]["message"] == "Insufficient product stock: SKU_AA" assert errors[1]["code"] == "INSUFFICIENT_STOCK" assert errors[1]["message"] == "Insufficient product stock: SKU_B" def test_order_fulfill_with_stock_exceeded_with_flag_enabled( staff_api_client, staff_user, order_with_lines, permission_manage_orders, warehouse, ): order = order_with_lines query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order.id) order_line, order_line2 = order.lines.all() order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) # set stocks to out of quantity and assert Stock.objects.filter(warehouse=warehouse).update(quantity=0) for stock in Stock.objects.filter(warehouse=warehouse): assert stock.quantity == 0 variables = { "order": order_id, "input": { "notifyCustomer": False, "allowStockToBeExceeded": True, "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": 3, "warehouse": warehouse_id}], }, { "orderLineId": order_line2_id, "stocks": [{"quantity": 2, "warehouse": warehouse_id}], }, ], }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert not data["errors"] order.refresh_from_db() assert order.status == OrderStatus.FULFILLED order_lines = order.lines.all() assert order_lines[0].quantity_fulfilled == 3 assert order_lines[0].quantity_unfulfilled == 0 assert order_lines[1].quantity_fulfilled == 2 assert order_lines[1].quantity_unfulfilled == 0 # check if stocks quantity are < 0 after fulfillments for stock in Stock.objects.filter(warehouse=warehouse): assert stock.quantity < 0 def test_order_fulfill_with_allow_stock_to_be_exceeded_flag_enabled_and_deleted_stocks( staff_api_client, staff_user, permission_manage_orders, order_fulfill_data ): order = order_fulfill_data.order Stock.objects.filter(warehouse=order_fulfill_data.warehouse).delete() response = staff_api_client.post_graphql( ORDER_FULFILL_QUERY, order_fulfill_data.variables, permissions=[permission_manage_orders], ) get_graphql_content(response) order.refresh_from_db() assert order.status == OrderStatus.FULFILLED order_lines = order.lines.all() assert order_lines[0].quantity_fulfilled == 3 assert order_lines[0].quantity_unfulfilled == 0 assert order_lines[1].quantity_fulfilled == 2 assert order_lines[1].quantity_unfulfilled == 0 def test_order_fulfill_with_allow_stock_to_be_exceeded_flag_disabled_deleted_stocks( staff_api_client, staff_user, permission_manage_orders, order_fulfill_data ): order = order_fulfill_data.order order_fulfill_data.variables["input"]["allowStockToBeExceeded"] = False Stock.objects.filter(warehouse=order_fulfill_data.warehouse).delete() response = staff_api_client.post_graphql( ORDER_FULFILL_QUERY, order_fulfill_data.variables, permissions=[permission_manage_orders], ) get_graphql_content(response) order.refresh_from_db() assert not order.status == OrderStatus.FULFILLED order_lines = order.lines.all() assert order_lines[0].quantity_fulfilled == 0 assert order_lines[0].quantity_unfulfilled == 3 assert order_lines[1].quantity_fulfilled == 0 assert order_lines[1].quantity_unfulfilled == 2 def test_order_fulfill_with_allow_stock_to_be_exceeded_flag_enabled_and_deleted_variant( staff_api_client, staff_user, permission_manage_orders, order_fulfill_data ): order = order_fulfill_data.order order.lines.first().variant.delete() response = staff_api_client.post_graphql( ORDER_FULFILL_QUERY, order_fulfill_data.variables, permissions=[permission_manage_orders], ) get_graphql_content(response) order.refresh_from_db() assert order.status == OrderStatus.FULFILLED order_lines = order.lines.all() assert order_lines[0].quantity_fulfilled == 3 assert order_lines[0].quantity_unfulfilled == 0 assert order_lines[1].quantity_fulfilled == 2 assert order_lines[1].quantity_unfulfilled == 0 def test_order_fulfill_with_allow_stock_to_be_exceeded_flag_disabled_deleted_variant( staff_api_client, staff_user, permission_manage_orders, order_fulfill_data ): order = order_fulfill_data.order order_fulfill_data.variables["input"]["allowStockToBeExceeded"] = False order.lines.first().variant.delete() response = staff_api_client.post_graphql( ORDER_FULFILL_QUERY, order_fulfill_data.variables, permissions=[permission_manage_orders], ) get_graphql_content(response) order.refresh_from_db() assert not order.status == OrderStatus.FULFILLED order_lines = order.lines.all() assert order_lines[0].quantity_fulfilled == 0 assert order_lines[0].quantity_unfulfilled == 3 assert order_lines[1].quantity_fulfilled == 0 assert order_lines[1].quantity_unfulfilled == 2 @patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments") def test_order_fulfill_above_available_quantity( mock_create_fulfillments, staff_api_client, staff_user, order_with_lines, permission_manage_orders, warehouse, ): order = order_with_lines query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order.id) order_line, order_line2 = order.lines.all() order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) fulfillment = Fulfillment.objects.create( order=order, status=FulfillmentStatus.WAITING_FOR_APPROVAL ) FulfillmentLine.objects.create( order_line=order_line, quantity=1, stock=warehouse.stock_set.first(), fulfillment_id=fulfillment.pk, ) variables = { "order": order_id, "input": { "notifyCustomer": True, "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": 4, "warehouse": warehouse_id}], }, { "orderLineId": order_line2_id, "stocks": [{"quantity": 2, "warehouse": warehouse_id}], }, ], }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] error = data["errors"][0] assert error["field"] == "orderLineId" assert error["code"] == OrderErrorCode.FULFILL_ORDER_LINE.name mock_create_fulfillments.assert_not_called() @patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments") def test_order_fulfill_as_app( mock_create_fulfillments, app_api_client, order_with_lines, permission_manage_orders, warehouse, site_settings, ): order = order_with_lines query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order.id) order_line, order_line2 = order.lines.all() order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) variables = { "order": order_id, "input": { "notifyCustomer": True, "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": 3, "warehouse": warehouse_id}], }, { "orderLineId": order_line2_id, "stocks": [{"quantity": 2, "warehouse": warehouse_id}], }, ], }, } response = app_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert not data["errors"] fulfillment_lines_for_warehouses = { str(warehouse.pk): [ {"order_line": order_line, "quantity": 3}, {"order_line": order_line2, "quantity": 2}, ] } mock_create_fulfillments.assert_called_once_with( None, app_api_client.app, order, fulfillment_lines_for_warehouses, ANY, site_settings, True, allow_stock_to_be_exceeded=False, approved=True, ) @patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments") def test_order_fulfill_many_warehouses( mock_create_fulfillments, staff_api_client, staff_user, order_with_lines, permission_manage_orders, warehouses, site_settings, ): order = order_with_lines query = ORDER_FULFILL_QUERY warehouse1, warehouse2 = warehouses order_line1, order_line2 = order.lines.all() order_id = graphene.Node.to_global_id("Order", order.id) order_line1_id = graphene.Node.to_global_id("OrderLine", order_line1.id) order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id) warehouse1_id = graphene.Node.to_global_id("Warehouse", warehouse1.pk) warehouse2_id = graphene.Node.to_global_id("Warehouse", warehouse2.pk) variables = { "order": order_id, "input": { "lines": [ { "orderLineId": order_line1_id, "stocks": [{"quantity": 3, "warehouse": warehouse1_id}], }, { "orderLineId": order_line2_id, "stocks": [ {"quantity": 1, "warehouse": warehouse1_id}, {"quantity": 1, "warehouse": warehouse2_id}, ], }, ], }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert not data["errors"] fulfillment_lines_for_warehouses = { str(warehouse1.pk): [ {"order_line": order_line1, "quantity": 3}, {"order_line": order_line2, "quantity": 1}, ], str(warehouse2.pk): [{"order_line": order_line2, "quantity": 1}], } mock_create_fulfillments.assert_called_once_with( staff_user, None, order, fulfillment_lines_for_warehouses, ANY, site_settings, True, allow_stock_to_be_exceeded=False, approved=True, ) @patch("saleor.giftcard.utils.send_gift_card_notification") def test_order_fulfill_with_gift_cards( mock_send_notification, staff_api_client, staff_user, order, gift_card_non_shippable_order_line, gift_card_shippable_order_line, permission_manage_orders, warehouse, ): query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order.id) order_line, order_line2 = ( gift_card_non_shippable_order_line, gift_card_shippable_order_line, ) order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) variables = { "order": order_id, "input": { "notifyCustomer": True, "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": 1, "warehouse": warehouse_id}], }, { "orderLineId": order_line2_id, "stocks": [{"quantity": 1, "warehouse": warehouse_id}], }, ], }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) flush_post_commit_hooks() data = content["data"]["orderFulfill"] assert not data["errors"] gift_cards = GiftCard.objects.all() assert gift_cards.count() == 2 non_shippable_gift_card = gift_cards.get( product_id=gift_card_non_shippable_order_line.variant.product_id ) shippable_gift_card = gift_cards.get( product_id=gift_card_shippable_order_line.variant.product_id ) assert non_shippable_gift_card.initial_balance.amount == round( gift_card_non_shippable_order_line.unit_price_gross.amount, 2 ) assert non_shippable_gift_card.current_balance.amount == round( gift_card_non_shippable_order_line.unit_price_gross.amount, 2 ) assert non_shippable_gift_card.fulfillment_line assert shippable_gift_card.initial_balance.amount == round( gift_card_shippable_order_line.unit_price_gross.amount, 2 ) assert shippable_gift_card.current_balance.amount == round( gift_card_shippable_order_line.unit_price_gross.amount, 2 ) assert shippable_gift_card.fulfillment_line assert GiftCardEvent.objects.filter( gift_card=shippable_gift_card, type=GiftCardEvents.BOUGHT ) assert GiftCardEvent.objects.filter( gift_card=non_shippable_gift_card, type=GiftCardEvents.BOUGHT ) mock_send_notification.assert_called_once_with( staff_user, None, order.user, order.user_email, non_shippable_gift_card, ANY, order.channel.slug, resending=False, ) @patch("saleor.giftcard.utils.send_gift_card_notification") def test_order_fulfill_with_gift_card_lines_waiting_for_approval( mock_send_notification, staff_api_client, staff_user, order, gift_card_non_shippable_order_line, gift_card_shippable_order_line, permission_manage_orders, warehouse, site_settings, ): query = ORDER_FULFILL_QUERY site_settings.fulfillment_auto_approve = False site_settings.save(update_fields=["fulfillment_auto_approve"]) order_id = graphene.Node.to_global_id("Order", order.id) order_line, order_line2 = ( gift_card_non_shippable_order_line, gift_card_shippable_order_line, ) order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) quantity = 1 variables = { "order": order_id, "input": { "notifyCustomer": True, "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": quantity, "warehouse": warehouse_id}], }, { "orderLineId": order_line2_id, "stocks": [{"quantity": quantity, "warehouse": warehouse_id}], }, ], }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert not data["errors"] # ensure gift card weren't created assert GiftCard.objects.count() == 0 mock_send_notification.assert_not_called() @patch("saleor.giftcard.utils.send_gift_card_notification") def test_order_fulfill_with_gift_cards_by_app( mock_send_notification, app_api_client, order, gift_card_shippable_order_line, permission_manage_orders, warehouse, site_settings, ): query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order.id) order_line = gift_card_shippable_order_line order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) quantity = 2 variables = { "order": order_id, "input": { "notifyCustomer": True, "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": quantity, "warehouse": warehouse_id}], }, ], }, } response = app_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert not data["errors"] assert GiftCard.objects.count() == quantity mock_send_notification.assert_not_called @patch("saleor.giftcard.utils.send_gift_card_notification") def test_order_fulfill_with_gift_cards_multiple_warehouses( mock_send_notification, app_api_client, order, gift_card_shippable_order_line, permission_manage_orders, warehouses, shipping_zone, site_settings, ): query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order.id) order_line = gift_card_shippable_order_line order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) warehouse1, warehouse2 = warehouses for warehouse in warehouses: warehouse.shipping_zones.add(shipping_zone) warehouse.save() stock_1 = Stock.objects.create( warehouse=warehouse1, product_variant=order_line.variant, quantity=1 ) Allocation.objects.create( order_line=order_line, stock=stock_1, quantity_allocated=1 ) stock_2 = Stock.objects.create( warehouse=warehouse2, product_variant=order_line.variant, quantity=1 ) Allocation.objects.create( order_line=order_line, stock=stock_2, quantity_allocated=1 ) warehouse1_id = graphene.Node.to_global_id("Warehouse", warehouse1.pk) warehouse2_id = graphene.Node.to_global_id("Warehouse", warehouse2.pk) quantity_1 = 2 quantity_2 = 1 variables = { "order": order_id, "input": { "notifyCustomer": True, "lines": [ { "orderLineId": order_line_id, "stocks": [ {"quantity": quantity_1, "warehouse": warehouse1_id}, {"quantity": quantity_2, "warehouse": warehouse2_id}, ], }, ], }, } response = app_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert not data["errors"] assert GiftCard.objects.count() == quantity_1 + quantity_2 mock_send_notification.assert_not_called @patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments") def test_order_fulfill_without_notification( mock_create_fulfillments, staff_api_client, staff_user, order_with_lines, permission_manage_orders, warehouse, site_settings, ): order = order_with_lines query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order.id) order_line = order.lines.first() order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) variables = { "order": order_id, "input": { "notifyCustomer": False, "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": 1, "warehouse": warehouse_id}], } ], }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert not data["errors"] fulfillment_lines_for_warehouses = { str(warehouse.pk): [{"order_line": order_line, "quantity": 1}] } mock_create_fulfillments.assert_called_once_with( staff_user, None, order, fulfillment_lines_for_warehouses, ANY, site_settings, False, allow_stock_to_be_exceeded=False, approved=True, ) @patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments") def test_order_fulfill_lines_with_empty_quantity( mock_create_fulfillments, staff_api_client, staff_user, order_with_lines, permission_manage_orders, warehouse, warehouse_no_shipping_zone, site_settings, ): order = order_with_lines query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order.id) order_line, order_line2 = order.lines.all() order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) warehouse2_id = graphene.Node.to_global_id( "Warehouse", warehouse_no_shipping_zone.pk ) assert not order.events.all() variables = { "order": order_id, "input": { "lines": [ { "orderLineId": order_line_id, "stocks": [ {"quantity": 0, "warehouse": warehouse_id}, {"quantity": 0, "warehouse": warehouse2_id}, ], }, { "orderLineId": order_line2_id, "stocks": [ {"quantity": 2, "warehouse": warehouse_id}, {"quantity": 0, "warehouse": warehouse2_id}, ], }, ], }, } variables["input"]["lines"][0]["stocks"][0]["quantity"] = 0 response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert not data["errors"] fulfillment_lines_for_warehouses = { str(warehouse.pk): [{"order_line": order_line2, "quantity": 2}] } mock_create_fulfillments.assert_called_once_with( staff_user, None, order, fulfillment_lines_for_warehouses, ANY, site_settings, True, allow_stock_to_be_exceeded=False, approved=True, ) @pytest.mark.parametrize("fulfillment_auto_approve", [True, False]) @patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments") def test_order_fulfill_without_sku( mock_create_fulfillments, fulfillment_auto_approve, staff_api_client, staff_user, order_with_lines, permission_manage_orders, warehouse, site_settings, ): ProductVariant.objects.update(sku=None) site_settings.fulfillment_auto_approve = fulfillment_auto_approve site_settings.save(update_fields=["fulfillment_auto_approve"]) order = order_with_lines query = ORDER_FULFILL_QUERY order.lines.update(product_sku=None) order_id = graphene.Node.to_global_id("Order", order.id) order_line, order_line2 = order.lines.all() order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) variables = { "order": order_id, "input": { "notifyCustomer": True, "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": 3, "warehouse": warehouse_id}], }, { "orderLineId": order_line2_id, "stocks": [{"quantity": 2, "warehouse": warehouse_id}], }, ], }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert not data["errors"] fulfillment_lines_for_warehouses = { str(warehouse.pk): [ {"order_line": order_line, "quantity": 3}, {"order_line": order_line2, "quantity": 2}, ] } mock_create_fulfillments.assert_called_once_with( staff_user, None, order, fulfillment_lines_for_warehouses, ANY, site_settings, True, allow_stock_to_be_exceeded=False, approved=fulfillment_auto_approve, ) @patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments") def test_order_fulfill_zero_quantity( mock_create_fulfillments, staff_api_client, staff_user, order_with_lines, permission_manage_orders, warehouse, ): query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order_with_lines.id) order_line = order_with_lines.lines.first() order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) variables = { "order": order_id, "input": { "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": 0, "warehouse": warehouse_id}], } ] }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert data["errors"] error = data["errors"][0] assert error["field"] == "lines" assert error["code"] == OrderErrorCode.ZERO_QUANTITY.name assert not error["orderLines"] assert not error["warehouse"] mock_create_fulfillments.assert_not_called() def test_order_fulfill_channel_without_shipping_zones( staff_api_client, order_with_lines, permission_manage_orders, warehouse, ): order = order_with_lines order.channel.shipping_zones.clear() query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order.id) order_line = order.lines.first() order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) variables = { "order": order_id, "input": { "notifyCustomer": True, "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": 3, "warehouse": warehouse_id}], }, ], }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert len(data["errors"]) == 1 error = data["errors"][0] assert error["field"] == "stocks" assert error["code"] == OrderErrorCode.INSUFFICIENT_STOCK.name @patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments") def test_order_fulfill_fulfilled_order( mock_create_fulfillments, staff_api_client, staff_user, order_with_lines, permission_manage_orders, warehouse, ): query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order_with_lines.id) order_line = order_with_lines.lines.first() order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) variables = { "order": order_id, "input": { "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": 100, "warehouse": warehouse_id}], } ] }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert data["errors"] error = data["errors"][0] assert error["field"] == "orderLineId" assert error["code"] == OrderErrorCode.FULFILL_ORDER_LINE.name assert error["orderLines"] == [order_line_id] assert not error["warehouse"] mock_create_fulfillments.assert_not_called() @patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments") def test_order_fulfill_unpaid_order_and_disallow_unpaid( mock_create_fulfillments, staff_api_client, order_with_lines, permission_manage_orders, warehouse, site_settings, ): site_settings.fulfillment_allow_unpaid = False site_settings.save(update_fields=["fulfillment_allow_unpaid"]) query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order_with_lines.id) order_line = order_with_lines.lines.first() order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) variables = { "order": order_id, "input": { "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": 100, "warehouse": warehouse_id}], } ] }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert data["errors"] error = data["errors"][0] assert error["field"] == "order" assert error["code"] == OrderErrorCode.CANNOT_FULFILL_UNPAID_ORDER.name mock_create_fulfillments.assert_not_called() @patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments", autospec=True) def test_order_fulfill_warehouse_with_insufficient_stock_exception( mock_create_fulfillments, staff_api_client, order_with_lines, permission_manage_orders, warehouse_no_shipping_zone, ): order = order_with_lines query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order.id) order_line = order.lines.first() order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) warehouse_id = graphene.Node.to_global_id( "Warehouse", warehouse_no_shipping_zone.pk ) variables = { "order": order_id, "input": { "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": 1, "warehouse": warehouse_id}], } ] }, } mock_create_fulfillments.side_effect = InsufficientStock( [ InsufficientStockData( variant=order_line.variant, order_line=order_line, warehouse_pk=warehouse_no_shipping_zone.pk, ) ] ) response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert data["errors"] error = data["errors"][0] assert error["field"] == "stocks" assert error["code"] == OrderErrorCode.INSUFFICIENT_STOCK.name assert error["orderLines"] == [order_line_id] assert error["warehouse"] == warehouse_id @patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments", autospec=True) def test_order_fulfill_warehouse_duplicated_warehouse_id( mock_create_fulfillments, staff_api_client, order_with_lines, permission_manage_orders, warehouse, ): order = order_with_lines query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order.id) order_line = order.lines.first() order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) variables = { "order": order_id, "input": { "lines": [ { "orderLineId": order_line_id, "stocks": [ {"quantity": 1, "warehouse": warehouse_id}, {"quantity": 2, "warehouse": warehouse_id}, ], } ] }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert data["errors"] error = data["errors"][0] assert error["field"] == "warehouse" assert error["code"] == OrderErrorCode.DUPLICATED_INPUT_ITEM.name assert not error["orderLines"] assert error["warehouse"] == warehouse_id mock_create_fulfillments.assert_not_called() @patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments", autospec=True) def test_order_fulfill_warehouse_duplicated_order_line_id( mock_create_fulfillments, staff_api_client, order_with_lines, permission_manage_orders, warehouse, ): order = order_with_lines query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order.id) order_line = order.lines.first() order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) variables = { "order": order_id, "input": { "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": 3, "warehouse": warehouse_id}], }, { "orderLineId": order_line_id, "stocks": [{"quantity": 3, "warehouse": warehouse_id}], }, ] }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert data["errors"] error = data["errors"][0] assert error["field"] == "orderLineId" assert error["code"] == OrderErrorCode.DUPLICATED_INPUT_ITEM.name assert error["orderLines"] == [order_line_id] assert not error["warehouse"] mock_create_fulfillments.assert_not_called() @patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments") def test_order_fulfill_preorder( mock_create_fulfillments, staff_api_client, staff_user, order_with_lines, permission_manage_orders, warehouse, ): query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order_with_lines.id) order_line = order_with_lines.lines.first() variant = order_line.variant variant.is_preorder = True variant.save(update_fields=["is_preorder"]) order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) variables = { "order": order_id, "input": { "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": 0, "warehouse": warehouse_id}], } ] }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert data["errors"] error = data["errors"][0] assert error["field"] == "orderLineId" assert error["code"] == OrderErrorCode.FULFILL_ORDER_LINE.name assert error["orderLines"] mock_create_fulfillments.assert_not_called() def test_order_fulfill_preorder_waiting_fulfillment( staff_api_client, order_with_lines, permission_manage_orders, warehouse, site_settings, ): """If fulfillment_auto_approve is set to False, it's possible to fulfill lines to WAITING_FOR_APPROVAL status.""" site_settings.fulfillment_auto_approve = False site_settings.save(update_fields=["fulfillment_auto_approve"]) query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order_with_lines.id) order_line = order_with_lines.lines.first() variant = order_line.variant variant.is_preorder = True variant.save(update_fields=["is_preorder"]) order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) variables = { "order": order_id, "input": { "lines": [ { "orderLineId": order_line_id, "stocks": [{"quantity": 3, "warehouse": warehouse_id}], } ] }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfill"] assert not data["errors"] assert ( order_with_lines.fulfillments.first().status == FulfillmentStatus.WAITING_FOR_APPROVAL ) @patch("saleor.plugins.manager.PluginsManager.notify") def test_fulfillment_update_tracking( send_fulfillment_update_mock, staff_api_client, fulfillment, permission_manage_orders, ): query = """ mutation updateFulfillment($id: ID!, $tracking: String) { orderFulfillmentUpdateTracking( id: $id, input: { trackingNumber: $tracking } ) { fulfillment { trackingNumber } } } """ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) tracking = "stationary tracking" variables = {"id": fulfillment_id, "tracking": tracking} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfillmentUpdateTracking"]["fulfillment"] assert data["trackingNumber"] == tracking send_fulfillment_update_mock.assert_not_called() FULFILLMENT_UPDATE_TRACKING_WITH_SEND_NOTIFICATION_QUERY = """ mutation updateFulfillment( $id: ID! $tracking: String $notifyCustomer: Boolean ) { orderFulfillmentUpdateTracking( id: $id input: { trackingNumber: $tracking, notifyCustomer: $notifyCustomer } ) { fulfillment { trackingNumber } } } """ @patch("saleor.graphql.order.mutations.fulfillments.send_fulfillment_update") def test_fulfillment_update_tracking_send_notification_true( send_fulfillment_update_mock, staff_api_client, fulfillment, permission_manage_orders, ): fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) tracking = "stationary tracking" variables = {"id": fulfillment_id, "tracking": tracking, "notifyCustomer": True} response = staff_api_client.post_graphql( FULFILLMENT_UPDATE_TRACKING_WITH_SEND_NOTIFICATION_QUERY, variables, permissions=[permission_manage_orders], ) content = get_graphql_content(response) data = content["data"]["orderFulfillmentUpdateTracking"]["fulfillment"] assert data["trackingNumber"] == tracking send_fulfillment_update_mock.assert_called_once_with( fulfillment.order, fulfillment, ANY ) @patch("saleor.order.notifications.send_fulfillment_update") def test_fulfillment_update_tracking_send_notification_false( send_fulfillment_update_mock, staff_api_client, fulfillment, permission_manage_orders, ): fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) tracking = "stationary tracking" variables = {"id": fulfillment_id, "tracking": tracking, "notifyCustomer": False} response = staff_api_client.post_graphql( FULFILLMENT_UPDATE_TRACKING_WITH_SEND_NOTIFICATION_QUERY, variables, permissions=[permission_manage_orders], ) content = get_graphql_content(response) data = content["data"]["orderFulfillmentUpdateTracking"]["fulfillment"] assert data["trackingNumber"] == tracking send_fulfillment_update_mock.assert_not_called() CANCEL_FULFILLMENT_MUTATION = """ mutation cancelFulfillment($id: ID!, $warehouseId: ID) { orderFulfillmentCancel(id: $id, input: {warehouseId: $warehouseId}) { fulfillment { status } order { status } errors { code field } } } """ def test_cancel_fulfillment( staff_api_client, fulfillment, staff_user, permission_manage_orders, warehouse ): query = CANCEL_FULFILLMENT_MUTATION fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id) variables = {"id": fulfillment_id, "warehouseId": warehouse_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfillmentCancel"] assert data["fulfillment"]["status"] == FulfillmentStatus.CANCELED.upper() assert data["order"]["status"] == OrderStatus.UNFULFILLED.upper() event_cancelled, event_restocked_items = fulfillment.order.events.all() assert event_cancelled.type == (OrderEvents.FULFILLMENT_CANCELED) assert event_cancelled.parameters == {"composed_id": fulfillment.composed_id} assert event_cancelled.user == staff_user assert event_restocked_items.type == (OrderEvents.FULFILLMENT_RESTOCKED_ITEMS) assert event_restocked_items.parameters == { "quantity": fulfillment.get_total_quantity(), "warehouse": str(warehouse.pk), } assert event_restocked_items.user == staff_user assert Fulfillment.objects.filter( pk=fulfillment.pk, status=FulfillmentStatus.CANCELED ).exists() def test_cancel_fulfillment_for_order_with_gift_card_lines( staff_api_client, fulfillment, gift_card_shippable_order_line, staff_user, permission_manage_orders, warehouse, ): query = CANCEL_FULFILLMENT_MUTATION order = gift_card_shippable_order_line.order order_fulfillment = order.fulfillments.first() fulfillment_id = graphene.Node.to_global_id("Fulfillment", order_fulfillment.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id) variables = {"id": fulfillment_id, "warehouseId": warehouse_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfillmentCancel"] assert not data["fulfillment"] assert len(data["errors"]) == 1 assert data["errors"][0]["code"] == OrderErrorCode.CANNOT_CANCEL_FULFILLMENT.name assert data["errors"][0]["field"] == "fulfillment" def test_cancel_fulfillment_no_warehouse_id( staff_api_client, fulfillment, permission_manage_orders ): query = """ mutation cancelFulfillment($id: ID!) { orderFulfillmentCancel(id: $id) { fulfillment { status } order { status } errors { code field } } } """ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) variables = {"id": fulfillment_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) errors = content["data"]["orderFulfillmentCancel"]["errors"] assert len(errors) == 1 error = errors[0] assert error["field"] == "warehouseId" assert error["code"] == OrderErrorCode.REQUIRED.name @patch("saleor.order.actions.restock_fulfillment_lines") def test_cancel_fulfillment_awaiting_approval( mock_restock_lines, staff_api_client, fulfillment, permission_manage_orders ): fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL fulfillment.save(update_fields=["status"]) query = CANCEL_FULFILLMENT_MUTATION fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) variables = {"id": fulfillment_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfillmentCancel"] assert data["fulfillment"] is None mock_restock_lines.assert_not_called() event_cancelled = fulfillment.order.events.get() assert event_cancelled.type == (OrderEvents.FULFILLMENT_CANCELED) assert event_cancelled.parameters == {} assert event_cancelled.user == staff_api_client.user assert not Fulfillment.objects.filter(pk=fulfillment.pk).exists() @patch("saleor.order.actions.restock_fulfillment_lines") def test_cancel_fulfillment_awaiting_approval_warehouse_specified( mock_restock_lines, staff_api_client, fulfillment, permission_manage_orders, warehouse, ): fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL fulfillment.save(update_fields=["status"]) query = CANCEL_FULFILLMENT_MUTATION fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id) variables = {"id": fulfillment_id, "warehouseId": warehouse_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfillmentCancel"] assert data["fulfillment"] is None mock_restock_lines.assert_not_called() event_cancelled = fulfillment.order.events.get() assert event_cancelled.type == (OrderEvents.FULFILLMENT_CANCELED) assert event_cancelled.parameters == {} assert event_cancelled.user == staff_api_client.user assert not Fulfillment.objects.filter(pk=fulfillment.pk).exists() def test_cancel_fulfillment_canceled_state( staff_api_client, fulfillment, permission_manage_orders, warehouse ): query = CANCEL_FULFILLMENT_MUTATION fulfillment.status = FulfillmentStatus.CANCELED fulfillment.save(update_fields=["status"]) fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id) variables = {"id": fulfillment_id, "warehouseId": warehouse_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) errors = content["data"]["orderFulfillmentCancel"]["errors"] assert len(errors) == 1 error = errors[0] assert error["field"] == "fulfillment" assert error["code"] == OrderErrorCode.CANNOT_CANCEL_FULFILLMENT.name def test_cancel_fulfillment_warehouse_without_stock( order_line, warehouse, staff_api_client, permission_manage_orders, staff_user ): query = CANCEL_FULFILLMENT_MUTATION order = order_line.order fulfillment = order.fulfillments.create(tracking_number="123") fulfillment.lines.create(order_line=order_line, quantity=order_line.quantity) order.status = OrderStatus.FULFILLED order.save(update_fields=["status"]) assert not Stock.objects.filter( warehouse=warehouse, product_variant=order_line.variant ) assert not Allocation.objects.filter(order_line=order_line) fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id) variables = {"id": fulfillment_id, "warehouseId": warehouse_id} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfillmentCancel"]["fulfillment"] assert data["status"] == FulfillmentStatus.CANCELED.upper() event_cancelled, event_restocked_items = fulfillment.order.events.all() assert event_cancelled.type == (OrderEvents.FULFILLMENT_CANCELED) assert event_cancelled.parameters == {"composed_id": fulfillment.composed_id} assert event_cancelled.user == staff_user assert event_restocked_items.type == (OrderEvents.FULFILLMENT_RESTOCKED_ITEMS) assert event_restocked_items.parameters == { "quantity": fulfillment.get_total_quantity(), "warehouse": str(warehouse.pk), } assert event_restocked_items.user == staff_user stock = Stock.objects.filter( warehouse=warehouse, product_variant=order_line.variant ).first() assert stock.quantity == order_line.quantity allocation = order_line.allocations.filter(stock=stock).first() assert allocation.quantity_allocated == order_line.quantity @patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True) def test_create_digital_fulfillment( mock_email_fulfillment, digital_content, staff_api_client, order_with_lines, warehouse, permission_manage_orders, ): order = order_with_lines query = ORDER_FULFILL_QUERY order_id = graphene.Node.to_global_id("Order", order.id) order_line = order.lines.first() order_line.variant = digital_content.product_variant order_line.save() order_line.allocations.all().delete() stock = digital_content.product_variant.stocks.get(warehouse=warehouse) Allocation.objects.create( order_line=order_line, stock=stock, quantity_allocated=order_line.quantity ) second_line = order.lines.last() first_line_id = graphene.Node.to_global_id("OrderLine", order_line.id) second_line_id = graphene.Node.to_global_id("OrderLine", second_line.id) warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) variables = { "order": order_id, "input": { "notifyCustomer": True, "lines": [ { "orderLineId": first_line_id, "stocks": [{"quantity": 1, "warehouse": warehouse_id}], }, { "orderLineId": second_line_id, "stocks": [{"quantity": 1, "warehouse": warehouse_id}], }, ], }, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) get_graphql_content(response) assert mock_email_fulfillment.call_count == 1 APPROVE_FULFILLMENT_MUTATION = """ mutation approveFulfillment( $id: ID!, $notifyCustomer: Boolean!, $allowStockToBeExceeded: Boolean = false ) { orderFulfillmentApprove( id: $id, notifyCustomer: $notifyCustomer, allowStockToBeExceeded: $allowStockToBeExceeded) { fulfillment { status } order { status } errors { field code } } } """ @patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True) def test_fulfillment_approve( mock_email_fulfillment, staff_api_client, fulfillment, permission_manage_orders, ): fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL fulfillment.save(update_fields=["status"]) query = APPROVE_FULFILLMENT_MUTATION fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) variables = {"id": fulfillment_id, "notifyCustomer": True} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfillmentApprove"] assert not data["errors"] assert data["fulfillment"]["status"] == FulfillmentStatus.FULFILLED.upper() assert data["order"]["status"] == OrderStatus.FULFILLED.upper() fulfillment.refresh_from_db() assert fulfillment.status == FulfillmentStatus.FULFILLED assert mock_email_fulfillment.call_count == 1 events = fulfillment.order.events.all() assert len(events) == 1 event = events[0] assert event.type == OrderEvents.FULFILLMENT_FULFILLED_ITEMS assert event.user == staff_api_client.user @patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True) def test_fulfillment_approve_delete_products_before_approval_allow_stock_exceeded_true( mock_email_fulfillment, staff_api_client, fulfillment, permission_manage_orders, ): fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL fulfillment.save(update_fields=["status"]) Product.objects.all().delete() query = APPROVE_FULFILLMENT_MUTATION fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) variables = { "id": fulfillment_id, "notifyCustomer": True, "allowStockToBeExceeded": True, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfillmentApprove"] assert not data["errors"] assert data["fulfillment"]["status"] == FulfillmentStatus.FULFILLED.upper() assert data["order"]["status"] == OrderStatus.FULFILLED.upper() fulfillment.refresh_from_db() assert fulfillment.status == FulfillmentStatus.FULFILLED assert mock_email_fulfillment.call_count == 1 events = fulfillment.order.events.all() assert len(events) == 1 event = events[0] assert event.type == OrderEvents.FULFILLMENT_FULFILLED_ITEMS assert event.user == staff_api_client.user @patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True) def test_fulfillment_approve_delete_products_before_approval_allow_stock_exceeded_false( mock_email_fulfillment, staff_api_client, fulfillment, permission_manage_orders, ): fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL fulfillment.save(update_fields=["status"]) Product.objects.all().delete() query = APPROVE_FULFILLMENT_MUTATION fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) variables = { "id": fulfillment_id, "notifyCustomer": True, "allowStockToBeExceeded": False, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response, ignore_errors=True) errors = content["errors"] assert len(errors) == 1 assert ( errors[0]["message"] == "Insufficient stock for Test product (SKU_AA), Test product 2 (SKU_B)" ) fulfillment.refresh_from_db() assert fulfillment.status == FulfillmentStatus.WAITING_FOR_APPROVAL assert mock_email_fulfillment.call_count == 1 events = fulfillment.order.events.all() assert len(events) == 0 @patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True) def test_fulfillment_approve_gift_cards_created( mock_email_fulfillment, staff_api_client, fulfillment, permission_manage_orders, gift_card_shippable_order_line, gift_card_non_shippable_order_line, ): fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL fulfillment.save(update_fields=["status"]) gift_card_line_1 = gift_card_shippable_order_line gift_card_line_2 = gift_card_non_shippable_order_line stock_1 = gift_card_line_1.variant.stocks.first() stock_2 = gift_card_line_2.variant.stocks.first() fulfillment_line_1 = fulfillment.lines.create( order_line=gift_card_line_1, quantity=gift_card_line_1.quantity, stock=stock_1 ) fulfillment_line_2 = fulfillment.lines.create( order_line=gift_card_line_2, quantity=gift_card_line_2.quantity, stock=stock_2 ) fulfill_order_lines( [ OrderLineInfo( line=gift_card_line_1, quantity=gift_card_line_1.quantity, warehouse_pk=stock_1.warehouse.pk, ), OrderLineInfo( line=gift_card_line_2, quantity=gift_card_line_2.quantity, warehouse_pk=stock_2.warehouse.pk, ), ], manager=get_plugins_manager(), ) query = APPROVE_FULFILLMENT_MUTATION fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) variables = {"id": fulfillment_id, "notifyCustomer": True} assert GiftCard.objects.count() == 0 response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfillmentApprove"] assert not data["errors"] assert data["fulfillment"]["status"] == FulfillmentStatus.FULFILLED.upper() assert data["order"]["status"] == OrderStatus.FULFILLED.upper() fulfillment.refresh_from_db() assert fulfillment.status == FulfillmentStatus.FULFILLED assert mock_email_fulfillment.call_count == 1 events = fulfillment.order.events.all() assert len(events) == 1 event = events[0] assert event.type == OrderEvents.FULFILLMENT_FULFILLED_ITEMS assert event.user == staff_api_client.user gift_cards = GiftCard.objects.all() assert gift_cards.count() == gift_card_line_1.quantity + gift_card_line_2.quantity for gift_card in gift_cards: if gift_card.product == gift_card_line_1.variant.product: assert gift_card.fulfillment_line == fulfillment_line_1 else: assert gift_card.fulfillment_line == fulfillment_line_2 @patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True) def test_fulfillment_approve_when_stock_is_exceeded_and_flag_enabled( mock_email_fulfillment, staff_api_client, fulfillment, permission_manage_orders, ): # make stocks exceeded for stock in [line.stock for line in fulfillment.lines.all()]: stock.quantity = -99 stock.save() fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL fulfillment.save(update_fields=["status"]) query = APPROVE_FULFILLMENT_MUTATION fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) # make response with flag disabled, raised error is expected variables = { "id": fulfillment_id, "notifyCustomer": True, "allowStockToBeExceeded": True, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfillmentApprove"] assert not data["errors"] assert data["fulfillment"]["status"] == FulfillmentStatus.FULFILLED.upper() assert data["order"]["status"] == OrderStatus.FULFILLED.upper() fulfillment.refresh_from_db() assert fulfillment.status == FulfillmentStatus.FULFILLED assert mock_email_fulfillment.call_count == 1 events = fulfillment.order.events.all() assert len(events) == 1 event = events[0] assert event.type == OrderEvents.FULFILLMENT_FULFILLED_ITEMS assert event.user == staff_api_client.user @patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True) def test_fulfillment_approve_when_stock_is_exceeded_and_flag_disabled( mock_email_fulfillment, staff_api_client, fulfillment, permission_manage_orders, ): # make stocks exceeded for stock in [line.stock for line in fulfillment.lines.all()]: stock.quantity = -99 stock.save() fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL fulfillment.save(update_fields=["status"]) query = APPROVE_FULFILLMENT_MUTATION fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) variables = { "id": fulfillment_id, "notifyCustomer": True, "allowStockToBeExceeded": False, } response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response, ignore_errors=True) assert content["errors"] assert content["errors"][0]["message"] == "Insufficient stock for SKU_AA, SKU_B" @patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True) def test_fulfillment_approve_partial_order_fulfill( mock_email_fulfillment, staff_api_client, fulfillment_awaiting_approval, permission_manage_orders, ): # given query = APPROVE_FULFILLMENT_MUTATION order = fulfillment_awaiting_approval.order second_fulfillment = order.fulfillments.create() line_1 = order.lines.first() line_2 = order.lines.last() second_fulfillment.lines.create( order_line=line_1, quantity=line_1.quantity - line_1.quantity_fulfilled ) second_fulfillment.lines.create( order_line=line_2, quantity=line_2.quantity - line_2.quantity_fulfilled ) second_fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL second_fulfillment.save() line_1.quantity_fulfilled = line_1.quantity line_2.quantity_fulfilled = line_2.quantity OrderLine.objects.bulk_update([line_1, line_2], ["quantity_fulfilled"]) fulfillment_id = graphene.Node.to_global_id( "Fulfillment", fulfillment_awaiting_approval.id ) variables = {"id": fulfillment_id, "notifyCustomer": False} # when response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) # then content = get_graphql_content(response) data = content["data"]["orderFulfillmentApprove"] assert not data["errors"] assert data["fulfillment"]["status"] == FulfillmentStatus.FULFILLED.upper() assert data["order"]["status"] == "PARTIALLY_FULFILLED" fulfillment_awaiting_approval.refresh_from_db() assert fulfillment_awaiting_approval.status == FulfillmentStatus.FULFILLED assert mock_email_fulfillment.call_count == 0 def test_fulfillment_approve_invalid_status( staff_api_client, fulfillment, permission_manage_orders, ): query = APPROVE_FULFILLMENT_MUTATION fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) variables = {"id": fulfillment_id, "notifyCustomer": True} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfillmentApprove"] assert data["errors"][0]["code"] == OrderErrorCode.INVALID.name def test_fulfillment_approve_order_unpaid( staff_api_client, fulfillment, site_settings, permission_manage_orders, ): site_settings.fulfillment_allow_unpaid = False site_settings.save(update_fields=["fulfillment_allow_unpaid"]) fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL fulfillment.save(update_fields=["status"]) query = APPROVE_FULFILLMENT_MUTATION fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) variables = {"id": fulfillment_id, "notifyCustomer": True} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfillmentApprove"] assert data["errors"][0]["code"] == OrderErrorCode.CANNOT_FULFILL_UNPAID_ORDER.name def test_fulfillment_approve_preorder( staff_api_client, fulfillment, permission_manage_orders, site_settings ): """Fulfillment with WAITING_FOR_APPROVAL status can not be fulfilled if it contains variant in preorder.""" site_settings.fulfillment_auto_approve = False site_settings.save(update_fields=["fulfillment_auto_approve"]) order_line = fulfillment.order.lines.first() variant = order_line.variant variant.is_preorder = True variant.save(update_fields=["is_preorder"]) fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL fulfillment.save(update_fields=["status"]) query = APPROVE_FULFILLMENT_MUTATION fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id) variables = {"id": fulfillment_id, "notifyCustomer": False} response = staff_api_client.post_graphql( query, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["orderFulfillmentApprove"] assert data["errors"] error = data["errors"][0] assert error["field"] == "orderLineId" assert error["code"] == OrderErrorCode.FULFILL_ORDER_LINE.name QUERY_FULFILLMENT = """ query fulfillment($id: ID!) { order(id: $id) { fulfillments { id fulfillmentOrder status trackingNumber warehouse { id } lines { orderLine { id } quantity } } } } """ def test_fulfillment_query( staff_api_client, fulfilled_order, warehouse, permission_manage_orders, ): order = fulfilled_order order_line_1, order_line_2 = order.lines.all() order_id = graphene.Node.to_global_id("Order", order.pk) order_line_1_id = graphene.Node.to_global_id("OrderLine", order_line_1.pk) order_line_2_id = graphene.Node.to_global_id("OrderLine", order_line_2.pk) warehose_id = graphene.Node.to_global_id("Warehouse", warehouse.pk) variables = {"id": order_id} response = staff_api_client.post_graphql( QUERY_FULFILLMENT, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["order"]["fulfillments"] assert len(data) == 1 fulfillment_data = data[0] assert fulfillment_data["fulfillmentOrder"] == 1 assert fulfillment_data["status"] == FulfillmentStatus.FULFILLED.upper() assert fulfillment_data["trackingNumber"] == "123" assert fulfillment_data["warehouse"]["id"] == warehose_id assert len(fulfillment_data["lines"]) == 2 assert { "orderLine": {"id": order_line_1_id}, "quantity": order_line_1.quantity, } in fulfillment_data["lines"] assert { "orderLine": {"id": order_line_2_id}, "quantity": order_line_2.quantity, } in fulfillment_data["lines"] QUERY_ORDER_FULFILL_DATA = """ query OrderFulfillData($id: ID!) { order(id: $id) { id lines { variant { stocks { warehouse { id } quantity quantityAllocated } } } } } """ def test_staff_can_query_order_fulfill_data( staff_api_client, order_with_lines, permission_manage_orders ): order_id = graphene.Node.to_global_id("Order", order_with_lines.pk) variables = {"id": order_id} response = staff_api_client.post_graphql( QUERY_ORDER_FULFILL_DATA, variables, permissions=[permission_manage_orders] ) content = get_graphql_content(response) data = content["data"]["order"]["lines"] assert len(data) == 2 assert data[0]["variant"]["stocks"][0]["quantity"] == 5 assert data[0]["variant"]["stocks"][0]["quantityAllocated"] == 3 assert data[1]["variant"]["stocks"][0]["quantity"] == 2 assert data[1]["variant"]["stocks"][0]["quantityAllocated"] == 2 def test_staff_can_query_order_fulfill_data_without_permission( staff_api_client, order_with_lines ): order_id = graphene.Node.to_global_id("Order", order_with_lines.pk) variables = {"id": order_id} response = staff_api_client.post_graphql(QUERY_ORDER_FULFILL_DATA, variables) assert_no_permission(response)
34.486314
88
0.670013
90a8127d5e6a688ed8dd5239fd01785508696718
22,668
py
Python
ngcasa/imaging/_imaging_utils/_standard_grid_bu.py
FedeMPouzols/cngi_prototype
421a99c460f4092b79120f5bec122de7ce9b8b96
[ "Apache-2.0" ]
null
null
null
ngcasa/imaging/_imaging_utils/_standard_grid_bu.py
FedeMPouzols/cngi_prototype
421a99c460f4092b79120f5bec122de7ce9b8b96
[ "Apache-2.0" ]
null
null
null
ngcasa/imaging/_imaging_utils/_standard_grid_bu.py
FedeMPouzols/cngi_prototype
421a99c460f4092b79120f5bec122de7ce9b8b96
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 AUI, Inc. Washington DC, USA # # 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. from numba import jit import numpy as np import math def ndim_list(shape): return [ndim_list(shape[1:]) if len(shape) > 1 else None for _ in range(shape[0])] def _graph_standard_grid(vis_dataset, cgk_1D, grid_parms): import dask import dask.array as da import xarray as xr import time import itertools # Getting data for gridding chan_chunk_size = vis_dataset[grid_parms["imaging_weight_name"]].chunks[2][0] freq_chan = da.from_array(vis_dataset.coords['chan'].values, chunks=(chan_chunk_size)) n_chunks_in_each_dim = vis_dataset[grid_parms["imaging_weight_name"]].data.numblocks chunk_indx = [] iter_chunks_indx = itertools.product(np.arange(n_chunks_in_each_dim[0]), np.arange(n_chunks_in_each_dim[1]), np.arange(n_chunks_in_each_dim[2]), np.arange(n_chunks_in_each_dim[3])) if grid_parms['chan_mode'] == 'continuum': n_chan_chunks_img = 1 n_other_chunks = n_chunks_in_each_dim[0]*n_chunks_in_each_dim[1]*n_chunks_in_each_dim[2]*n_chunks_in_each_dim[3] elif grid_parms['chan_mode'] == 'cube': n_chan_chunks_img = n_chunks_in_each_dim[2] n_other_chunks = n_chunks_in_each_dim[0]*n_chunks_in_each_dim[1]*n_chunks_in_each_dim[3] #n_delayed = np.prod(n_chunks_in_each_dim) chunk_sizes = vis_dataset[grid_parms["imaging_weight_name"]].chunks list_of_grids = ndim_list((n_chan_chunks_img,n_other_chunks)) list_of_sum_weights = ndim_list((n_chan_chunks_img,n_other_chunks)) # Build graph for c_time, c_baseline, c_chan, c_pol in iter_chunks_indx: #There are two diffrent gridder wrapped functions _standard_grid_psf_numpy_wrap and _standard_grid_numpy_wrap. #This is done to simplify the psf and weight gridding graphs so that the vis_dataset is not loaded. if grid_parms['do_psf']: sub_grid_and_sum_weights = dask.delayed(_standard_grid_psf_numpy_wrap)( vis_dataset[grid_parms["uvw_name"]].data.partitions[c_time, c_baseline, 0], vis_dataset[grid_parms["imaging_weight_name"]].data.partitions[c_time, c_baseline, c_chan, c_pol], freq_chan.partitions[c_chan], dask.delayed(cgk_1D), dask.delayed(grid_parms)) grid_dtype = np.double else: sub_grid_and_sum_weights = dask.delayed(_standard_grid_numpy_wrap)( vis_dataset[grid_parms["data_name"]].data.partitions[c_time, c_baseline, c_chan, c_pol], vis_dataset[grid_parms["uvw_name"]].data.partitions[c_time, c_baseline, 0], vis_dataset[grid_parms["imaging_weight_name"]].data.partitions[c_time, c_baseline, c_chan, c_pol], freq_chan.partitions[c_chan], dask.delayed(cgk_1D), dask.delayed(grid_parms)) grid_dtype = np.complex128 if grid_parms['chan_mode'] == 'continuum': c_time_baseline_chan_pol = c_pol + c_chan*n_chunks_in_each_dim[3] + c_baseline*n_chunks_in_each_dim[3]*n_chunks_in_each_dim[2] + c_time*n_chunks_in_each_dim[3]*n_chunks_in_each_dim[2]*n_chunks_in_each_dim[1] list_of_grids[0][c_time_baseline_chan_pol] = da.from_delayed(sub_grid_and_sum_weights[0], (1, chunk_sizes[3][c_pol], grid_parms['imsize_padded'][0], grid_parms['imsize_padded'][1]),dtype=grid_dtype) list_of_sum_weights[0][c_time_baseline_chan_pol] = da.from_delayed(sub_grid_and_sum_weights[1],(1, chunk_sizes[3][c_pol]),dtype=np.float64) elif grid_parms['chan_mode'] == 'cube': c_time_baseline_pol = c_pol + c_baseline*n_chunks_in_each_dim[3] + c_time*n_chunks_in_each_dim[1]*n_chunks_in_each_dim[3] list_of_grids[c_chan][c_time_baseline_pol] = da.from_delayed(sub_grid_and_sum_weights[0], (chunk_sizes[2][c_chan], chunk_sizes[3][c_pol], grid_parms['imsize_padded'][0], grid_parms['imsize_padded'][1]),dtype=grid_dtype) list_of_sum_weights[c_chan][c_time_baseline_pol] = da.from_delayed(sub_grid_and_sum_weights[1],(chunk_sizes[2][c_chan], chunk_sizes[3][c_pol]),dtype=np.float64) # Sum grids for c_chan in range(n_chan_chunks_img): list_of_grids[c_chan] = _tree_sum_list(list_of_grids[c_chan]) list_of_sum_weights[c_chan] = _tree_sum_list(list_of_sum_weights[c_chan]) # Concatenate Cube if grid_parms['chan_mode'] == 'cube': list_of_grids_and_sum_weights = [da.concatenate(list_of_grids,axis=1)[0],da.concatenate(list_of_sum_weights,axis=1)[0]] else: list_of_grids_and_sum_weights = [list_of_grids[0][0],list_of_sum_weights[0][0]] # Put axes in image orientation. How much does this add to compute? list_of_grids_and_sum_weights[0] = da.moveaxis(list_of_grids_and_sum_weights[0], [0, 1], [-2, -1]) list_of_grids_and_sum_weights[1] = da.moveaxis(list_of_grids_and_sum_weights[1],[0, 1], [-2, -1]) return list_of_grids_and_sum_weights def _tree_sum_list(list_to_sum): import dask.array as da while len(list_to_sum) > 1: new_list_to_sum = [] for i in range(0, len(list_to_sum), 2): if i < len(list_to_sum) - 1: lazy = da.add(list_to_sum[i],list_to_sum[i+1]) else: lazy = list_to_sum[i] new_list_to_sum.append(lazy) list_to_sum = new_list_to_sum return list_to_sum def _standard_grid_numpy_wrap(vis_data, uvw, weight, freq_chan, cgk_1D, grid_parms): """ Wraps the jit gridder code. Parameters ---------- grid : complex array (n_chan, n_pol, n_u, n_v) sum_weight : float array (n_chan, n_pol) uvw : float array (n_time, n_baseline, 3) freq_chan : float array (n_chan) weight : float array (n_time, n_baseline, n_vis_chan) cgk_1D : float array (oversampling*(support//2 + 1)) grid_parms : dictionary keys ('imsize','cell','oversampling','support') Returns ------- grid : complex array (1,n_imag_chan,n_imag_pol,n_u,n_v) """ n_chan = weight.shape[2] if grid_parms['chan_mode'] == 'cube': n_imag_chan = n_chan chan_map = (np.arange(0, n_chan)).astype(np.int) else: # continuum n_imag_chan = 1 # Making only one continuum image. chan_map = (np.zeros(n_chan)).astype(np.int) n_imag_pol = weight.shape[3] pol_map = (np.arange(0, n_imag_pol)).astype(np.int) n_uv = grid_parms['imsize_padded'] delta_lm = grid_parms['cell'] oversampling = grid_parms['oversampling'] support = grid_parms['support'] if grid_parms['complex_grid']: grid = np.zeros((n_imag_chan, n_imag_pol, n_uv[0], n_uv[1]), dtype=np.complex128) else: grid = np.zeros((n_imag_chan, n_imag_pol, n_uv[0], n_uv[1]), dtype=np.double) sum_weight = np.zeros((n_imag_chan, n_imag_pol), dtype=np.double) do_psf = grid_parms['do_psf'] _standard_grid_jit(grid, sum_weight, do_psf, vis_data, uvw, freq_chan, chan_map, pol_map, weight, cgk_1D, n_uv, delta_lm, support, oversampling) return grid, sum_weight def _standard_grid_psf_numpy_wrap(uvw, weight, freq_chan, cgk_1D, grid_parms): """ Wraps the jit gridder code. Parameters ---------- grid : complex array (n_chan, n_pol, n_u, n_v) sum_weight : float array (n_chan, n_pol) uvw : float array (n_time, n_baseline, 3) freq_chan : float array (n_chan) weight : float array (n_time, n_baseline, n_vis_chan) cgk_1D : float array (oversampling*(support//2 + 1)) grid_parms : dictionary keys ('imsize','cell','oversampling','support') Returns ------- grid : complex array (1,n_imag_chan,n_imag_pol,n_u,n_v) """ n_chan = weight.shape[2] if grid_parms['chan_mode'] == 'cube': n_imag_chan = n_chan chan_map = (np.arange(0, n_chan)).astype(np.int) else: # continuum n_imag_chan = 1 # Making only one continuum image. chan_map = (np.zeros(n_chan)).astype(np.int) n_imag_pol = weight.shape[3] pol_map = (np.arange(0, n_imag_pol)).astype(np.int) n_uv = grid_parms['imsize_padded'] delta_lm = grid_parms['cell'] oversampling = grid_parms['oversampling'] support = grid_parms['support'] grid = np.zeros((n_imag_chan, n_imag_pol, n_uv[0], n_uv[1]), dtype=np.double) sum_weight = np.zeros((n_imag_chan, n_imag_pol), dtype=np.double) do_psf = grid_parms['do_psf'] vis_data = np.zeros((1, 1, 1, 1), dtype=np.bool) #This 0 bool array is needed to pass to _standard_grid_jit so that the code can be resued and to keep numba happy. _standard_grid_jit(grid, sum_weight, do_psf, vis_data, uvw, freq_chan, chan_map, pol_map, weight, cgk_1D, n_uv, delta_lm, support, oversampling) return grid, sum_weight import numpy as np #When jit is used round is repolaced by standard c++ round that is different to python round @jit(nopython=True, cache=True, nogil=True) def _standard_grid_jit(grid, sum_weight, do_psf, vis_data, uvw, freq_chan, chan_map, pol_map, weight, cgk_1D, n_uv, delta_lm, support, oversampling): """ Parameters ---------- grid : complex array (n_chan, n_pol, n_u, n_v) sum_weight : float array (n_chan, n_pol) vis_data : complex array (n_time, n_baseline, n_vis_chan, n_pol) uvw : float array (n_time, n_baseline, 3) freq_chan : float array (n_chan) chan_map : int array (n_chan) pol_map : int array (n_pol) weight : float array (n_time, n_baseline, n_vis_chan) cgk_1D : float array (oversampling*(support//2 + 1)) grid_parms : dictionary keys ('n_imag_chan','n_imag_pol','n_uv','delta_lm','oversampling','support') Returns ------- """ c = 299792458.0 uv_scale = np.zeros((2, len(freq_chan)), dtype=np.double) uv_scale[0, :] = -(freq_chan * delta_lm[0] * n_uv[0]) / c uv_scale[1, :] = -(freq_chan * delta_lm[1] * n_uv[1]) / c #oversampling_center = int(oversampling // 2) support_center = int(support // 2) uv_center = n_uv // 2 start_support = - support_center end_support = support - support_center # end_support is larger by 1 so that python range() gives correct indices n_time = uvw.shape[0] n_baseline = uvw.shape[1] n_chan = len(chan_map) n_pol = len(pol_map) n_u = n_uv[0] n_v = n_uv[1] for i_time in range(n_time): for i_baseline in range(n_baseline): for i_chan in range(n_chan): a_chan = chan_map[i_chan] u = uvw[i_time, i_baseline, 0] * uv_scale[0, i_chan] v = uvw[i_time, i_baseline, 1] * uv_scale[1, i_chan] if ~np.isnan(u) and ~np.isnan(v): u_pos = u + uv_center[0] v_pos = v + uv_center[1] #Doing round as int(x+0.5) since u_pos/v_pos should always positive and this matices fortran and gives consistant rounding. #u_center_indx = int(u_pos + 0.5) #v_center_indx = int(v_pos + 0.5) #Do not use numpy round u_center_indx = int(u_pos + 0.5) v_center_indx = int(v_pos + 0.5) if (u_center_indx+support_center < n_u) and (v_center_indx+support_center < n_v) and (u_center_indx-support_center >= 0) and (v_center_indx-support_center >= 0): u_offset = u_center_indx - u_pos u_center_offset_indx = math.floor(u_offset * oversampling + 0.5) v_offset = v_center_indx - v_pos v_center_offset_indx = math.floor(v_offset * oversampling + 0.5) for i_pol in range(n_pol): if do_psf: weighted_data = weight[i_time, i_baseline, i_chan, i_pol] else: weighted_data = vis_data[i_time, i_baseline, i_chan, i_pol] * weight[i_time, i_baseline, i_chan, i_pol] #print('1. u_center_indx, v_center_indx', u_center_indx, v_center_indx, vis_data[i_time, i_baseline, i_chan, i_pol], weight[i_time, i_baseline, i_chan, i_pol]) if ~np.isnan(weighted_data) and (weighted_data != 0.0): a_pol = pol_map[i_pol] norm = 0.0 for i_v in range(start_support,end_support): v_indx = v_center_indx + i_v v_offset_indx = np.abs(oversampling * i_v + v_center_offset_indx) conv_v = cgk_1D[v_offset_indx] for i_u in range(start_support,end_support): u_indx = u_center_indx + i_u u_offset_indx = np.abs(oversampling * i_u + u_center_offset_indx) conv_u = cgk_1D[u_offset_indx] conv = conv_u * conv_v grid[a_chan, a_pol, u_indx, v_indx] = grid[a_chan, a_pol, u_indx, v_indx] + conv * weighted_data norm = norm + conv sum_weight[a_chan, a_pol] = sum_weight[a_chan, a_pol] + weight[i_time, i_baseline, i_chan, i_pol] * norm return ############################################################################################################################################################################################################################################################################################################################################################################################################################################################ ############################################################################################################################################################################################################################################################################################################################################################################################################################################################ ############################################################################################################################################################################################################################################################################################################################################################################################################################################################ def _graph_standard_degrid(vis_dataset, grid, briggs_factors, cgk_1D, grid_parms): import dask import dask.array as da import xarray as xr import time import itertools # Getting data for gridding chan_chunk_size = vis_dataset[grid_parms["imaging_weight_name"]].chunks[2][0] freq_chan = da.from_array(vis_dataset.coords['chan'].values, chunks=(chan_chunk_size)) n_chunks_in_each_dim = vis_dataset[grid_parms["imaging_weight_name"]].data.numblocks chunk_indx = [] iter_chunks_indx = itertools.product(np.arange(n_chunks_in_each_dim[0]), np.arange(n_chunks_in_each_dim[1]), np.arange(n_chunks_in_each_dim[2]), np.arange(n_chunks_in_each_dim[3])) #n_delayed = np.prod(n_chunks_in_each_dim) chunk_sizes = vis_dataset[grid_parms["imaging_weight_name"]].chunks n_chan_chunks_img = n_chunks_in_each_dim[2] list_of_degrids = [] list_of_sum_weights = [] list_of_degrids = ndim_list(n_chunks_in_each_dim) # Build graph for c_time, c_baseline, c_chan, c_pol in iter_chunks_indx: if grid_parms['chan_mode'] == 'cube': a_c_chan = c_chan else: a_c_chan = 0 if grid_parms['do_imaging_weight']: sub_degrid = dask.delayed(_standard_imaging_weight_degrid_numpy_wrap)( grid.partitions[0,0,a_c_chan,c_pol], vis_dataset[grid_parms["uvw_name"]].data.partitions[c_time, c_baseline, 0], vis_dataset[grid_parms["imaging_weight_name"]].data.partitions[c_time, c_baseline, c_chan, c_pol], briggs_factors.partitions[:,a_c_chan,c_pol], freq_chan.partitions[c_chan], dask.delayed(grid_parms)) single_chunk_size = (chunk_sizes[0][c_time], chunk_sizes[1][c_baseline],chunk_sizes[2][c_chan], chunk_sizes[3][c_pol]) list_of_degrids[c_time][c_baseline][c_chan][c_pol] = da.from_delayed(sub_degrid, single_chunk_size,dtype=np.double) else: print('Degridding of visibilities and psf still needs to be implemented') #sub_grid_and_sum_weights = dask.delayed(_standard_grid_numpy_wrap)( #vis_dataset[vis_dataset[grid_parms["data"]].data.partitions[c_time, c_baseline, c_chan, c_pol], #vis_dataset[grid_parms["uvw"]].data.partitions[c_time, c_baseline, 0], #vis_dataset[grid_parms["imaging_weight"]].data.partitions[c_time, c_baseline, c_chan, c_pol], #freq_chan.partitions[c_chan], #dask.delayed(cgk_1D), dask.delayed(grid_parms)) degrid = da.block(list_of_degrids) return degrid def _standard_imaging_weight_degrid_numpy_wrap(grid_imaging_weight, uvw, natural_imaging_weight, briggs_factors, freq_chan, grid_parms): n_chan = natural_imaging_weight.shape[2] n_imag_chan = n_chan if grid_parms['chan_mode'] == 'cube': n_imag_chan = n_chan chan_map = (np.arange(0, n_chan)).astype(np.int) else: # continuum n_imag_chan = 1 chan_map = (np.zeros(n_chan)).astype(np.int) n_imag_pol = natural_imaging_weight.shape[3] pol_map = (np.arange(0, n_imag_pol)).astype(np.int) n_uv = grid_parms['imsize_padded'] delta_lm = grid_parms['cell'] imaging_weight = np.zeros(natural_imaging_weight.shape, dtype=np.double) _standard_imaging_weight_degrid_jit(imaging_weight, grid_imaging_weight, briggs_factors, uvw, freq_chan, chan_map, pol_map, natural_imaging_weight,n_uv, delta_lm) return imaging_weight @jit(nopython=True, cache=True, nogil=True) def _standard_imaging_weight_degrid_jit(imaging_weight, grid_imaging_weight, briggs_factors, uvw, freq_chan, chan_map, pol_map, natural_imaging_weight, n_uv, delta_lm): c = 299792458.0 uv_scale = np.zeros((2, len(freq_chan)), dtype=np.double) uv_scale[0, :] = -(freq_chan * delta_lm[0] * n_uv[0]) / c uv_scale[1, :] = -(freq_chan * delta_lm[1] * n_uv[1]) / c uv_center = n_uv // 2 n_time = uvw.shape[0] n_baseline = uvw.shape[1] n_chan = len(chan_map) n_pol = len(pol_map) n_imag_chan = chan_map.shape[0] n_u = n_uv[0] n_v = n_uv[1] #print('Degrid operation') for i_time in range(n_time): for i_baseline in range(n_baseline): for i_chan in range(n_chan): a_chan = chan_map[i_chan] u = uvw[i_time, i_baseline, 0] * uv_scale[0, i_chan] v = uvw[i_time, i_baseline, 1] * uv_scale[1, i_chan] if ~np.isnan(u) and ~np.isnan(v): u_pos = u + uv_center[0] v_pos = v + uv_center[1] #Doing round as int(x+0.5) since u_pos/v_pos should always be positive and fortran and gives consistant rounding. u_center_indx = int(u_pos + 0.5) v_center_indx = int(v_pos + 0.5) #print('f uv', freq_chan[i_chan], uvw[i_time, i_baseline, 0],uvw[i_time, i_baseline, 1]) if (u_center_indx < n_u) and (v_center_indx < n_v) and (u_center_indx >= 0) and (v_center_indx >= 0): #print('u_center_indx, v_center_indx', u_center_indx, v_center_indx) for i_pol in range(n_pol): a_pol = pol_map[i_pol] imaging_weight[i_time, i_baseline, i_chan, i_pol] = natural_imaging_weight[i_time, i_baseline, i_chan, i_pol] if ~np.isnan(natural_imaging_weight[i_time, i_baseline, i_chan, i_pol]) and (natural_imaging_weight[i_time, i_baseline, i_chan, i_pol] != 0.0): if ~np.isnan(grid_imaging_weight[u_center_indx, v_center_indx, a_chan, a_pol]) and (grid_imaging_weight[u_center_indx, v_center_indx, a_chan, a_pol] != 0.0): briggs_grid_imaging_weight = briggs_factors[0,a_chan,a_pol]*grid_imaging_weight[u_center_indx, v_center_indx, a_chan, a_pol] + briggs_factors[1,a_chan,a_pol] imaging_weight[i_time, i_baseline, i_chan, i_pol] = imaging_weight[i_time, i_baseline, i_chan, i_pol] / briggs_grid_imaging_weight return
46.641975
444
0.575878
d661b2ed6b1f4edee72c86a5b4b9a35347cdc5e7
7,825
py
Python
tests/integration/workflows/java_maven/test_java_maven.py
zhuhaow/aws-lambda-builders
ca658b37ed5242bfec82e01e33046b22484585cd
[ "Apache-2.0" ]
null
null
null
tests/integration/workflows/java_maven/test_java_maven.py
zhuhaow/aws-lambda-builders
ca658b37ed5242bfec82e01e33046b22484585cd
[ "Apache-2.0" ]
null
null
null
tests/integration/workflows/java_maven/test_java_maven.py
zhuhaow/aws-lambda-builders
ca658b37ed5242bfec82e01e33046b22484585cd
[ "Apache-2.0" ]
null
null
null
import os import shutil import tempfile from pathlib import Path from unittest import TestCase from os.path import join from aws_lambda_builders.builder import LambdaBuilder from aws_lambda_builders.exceptions import WorkflowFailedError from aws_lambda_builders.workflows.java.utils import EXPERIMENTAL_MAVEN_SCOPE_AND_LAYER_FLAG from tests.integration.workflows.common_test_utils import ( does_folder_contain_all_files, does_folder_contain_file, folder_should_not_contain_files, ) class TestJavaMaven(TestCase): # Have to use str(Path(__file__).resolve()) here to workaround a Windows VSCode issue # __file__ will return lower case drive letters. Ex: c:\folder\test.py instead of C:\folder\test.py # This will break the hashing algorithm we use for build directory generation SINGLE_BUILD_TEST_DATA_DIR = join(os.path.dirname(str(Path(__file__).resolve())), "testdata", "single-build") def setUp(self): self.artifacts_dir = tempfile.mkdtemp() self.scratch_dir = tempfile.mkdtemp() self.dependencies_dir = tempfile.mkdtemp() self.builder = LambdaBuilder(language="java", dependency_manager="maven", application_framework=None) self.runtime = "java8" def tearDown(self): shutil.rmtree(self.artifacts_dir) shutil.rmtree(self.scratch_dir) shutil.rmtree(self.dependencies_dir) def test_build_single_build_with_deps_resources_exclude_test_jars(self): source_dir = join(self.SINGLE_BUILD_TEST_DATA_DIR, "with-deps") manifest_path = join(source_dir, "pom.xml") self.builder.build(source_dir, self.artifacts_dir, self.scratch_dir, manifest_path, runtime=self.runtime) expected_files = [ join("aws", "lambdabuilders", "Main.class"), join("some_data.txt"), join("lib", "software.amazon.awssdk.annotations-2.1.0.jar"), ] self.assertTrue(does_folder_contain_all_files(self.artifacts_dir, expected_files)) self.assertFalse(does_folder_contain_file(self.artifacts_dir, join("lib", "junit-4.12.jar"))) self.assert_src_dir_not_touched(source_dir) def test_build_single_build_no_deps(self): source_dir = join(self.SINGLE_BUILD_TEST_DATA_DIR, "no-deps") manifest_path = join(source_dir, "pom.xml") self.builder.build(source_dir, self.artifacts_dir, self.scratch_dir, manifest_path, runtime=self.runtime) expected_files = [join("aws", "lambdabuilders", "Main.class"), join("some_data.txt")] self.assertTrue(does_folder_contain_all_files(self.artifacts_dir, expected_files)) self.assertFalse(does_folder_contain_file(self.artifacts_dir, join("lib"))) self.assert_src_dir_not_touched(source_dir) def test_build_single_build_with_deps_broken(self): source_dir = join(self.SINGLE_BUILD_TEST_DATA_DIR, "with-deps-broken") manifest_path = join(source_dir, "pom.xml") with self.assertRaises(WorkflowFailedError) as raised: self.builder.build(source_dir, self.artifacts_dir, self.scratch_dir, manifest_path, runtime=self.runtime) self.assertTrue(raised.exception.args[0].startswith("JavaMavenWorkflow:MavenBuild - Maven Failed")) self.assert_src_dir_not_touched(source_dir) def test_build_single_build_with_deps_resources_exclude_test_jars_deps_dir(self): source_dir = join(self.SINGLE_BUILD_TEST_DATA_DIR, "with-deps") manifest_path = join(source_dir, "pom.xml") self.builder.build( source_dir, self.artifacts_dir, self.scratch_dir, manifest_path, runtime=self.runtime, dependencies_dir=self.dependencies_dir, ) expected_files = [ join("aws", "lambdabuilders", "Main.class"), join("some_data.txt"), join("lib", "software.amazon.awssdk.annotations-2.1.0.jar"), ] dependencies_expected_files = [ join("lib", "software.amazon.awssdk.annotations-2.1.0.jar"), ] self.assertTrue(does_folder_contain_all_files(self.artifacts_dir, expected_files)) self.assertTrue(does_folder_contain_all_files(self.dependencies_dir, dependencies_expected_files)) self.assertFalse(does_folder_contain_file(self.artifacts_dir, join("lib", "junit-4.12.jar"))) self.assert_src_dir_not_touched(source_dir) def assert_src_dir_not_touched(self, source_dir): self.assertFalse(os.path.exists(join(source_dir, "target"))) def test_build_single_build_with_deps_resources_exclude_test_jars_deps_dir_without_combine_dependencies(self): source_dir = join(self.SINGLE_BUILD_TEST_DATA_DIR, "with-deps") manifest_path = join(source_dir, "pom.xml") self.builder.build( source_dir, self.artifacts_dir, self.scratch_dir, manifest_path, runtime=self.runtime, dependencies_dir=self.dependencies_dir, combine_dependencies=False, ) artifact_expected_files = [ join("aws", "lambdabuilders", "Main.class"), join("some_data.txt"), ] dependencies_expected_files = [ join("lib", "software.amazon.awssdk.annotations-2.1.0.jar"), ] self.assertTrue(does_folder_contain_all_files(self.artifacts_dir, artifact_expected_files)) self.assertTrue(does_folder_contain_all_files(self.dependencies_dir, dependencies_expected_files)) self.assertFalse(does_folder_contain_file(self.artifacts_dir, join("lib", "junit-4.12.jar"))) self.assert_src_dir_not_touched(source_dir) def test_build_with_layers_and_scope(self): # first build layer and validate self.validate_layer_build() # then build function which uses this layer as dependency with provided scope self.validate_function_build() def validate_layer_build(self): layer_source_dir = join(self.SINGLE_BUILD_TEST_DATA_DIR, "layer") layer_manifest_path = join(layer_source_dir, "pom.xml") self.builder.build( layer_source_dir, self.artifacts_dir, self.scratch_dir, layer_manifest_path, runtime=self.runtime, is_building_layer=True, experimental_flags=[EXPERIMENTAL_MAVEN_SCOPE_AND_LAYER_FLAG], ) artifact_expected_files = [ join("lib", "com.amazonaws.aws-lambda-java-core-1.2.0.jar"), join("lib", "common-layer-1.0.jar"), ] self.assertTrue(does_folder_contain_all_files(self.artifacts_dir, artifact_expected_files)) self.assert_src_dir_not_touched(layer_source_dir) def validate_function_build(self): self.setUp() # re-initialize folders function_source_dir = join(self.SINGLE_BUILD_TEST_DATA_DIR, "with-layer-deps") function_manifest_path = join(function_source_dir, "pom.xml") self.builder.build( function_source_dir, self.artifacts_dir, self.scratch_dir, function_manifest_path, runtime=self.runtime, is_building_layer=False, experimental_flags=[EXPERIMENTAL_MAVEN_SCOPE_AND_LAYER_FLAG], ) artifact_expected_files = [ join("aws", "lambdabuilders", "Main.class"), ] artifact_not_expected_files = [ join("lib", "com.amazonaws.aws-lambda-java-core-1.2.0.jar"), join("lib", "common-layer-1.0.jar"), ] self.assertTrue(does_folder_contain_all_files(self.artifacts_dir, artifact_expected_files)) self.assertTrue(folder_should_not_contain_files(self.artifacts_dir, artifact_not_expected_files)) self.assert_src_dir_not_touched(function_source_dir)
46.301775
117
0.698147
86521622d97eeb01e0bc6d39b28827f1ac180594
2,270
py
Python
software/scripts/gui.py
slaclab/atlas-rd53-fmc-dev
1c5e50980dca3389c9b9a8eaa7c215f5c21eff87
[ "BSD-3-Clause-LBNL" ]
2
2021-08-17T17:59:19.000Z
2021-08-17T17:59:44.000Z
software/scripts/gui.py
slaclab/atlas-rd53-fmc-dev
1c5e50980dca3389c9b9a8eaa7c215f5c21eff87
[ "BSD-3-Clause-LBNL" ]
3
2020-09-14T21:36:26.000Z
2020-11-02T17:51:41.000Z
software/scripts/gui.py
slaclab/atlas-rd53-fmc-dev
1c5e50980dca3389c9b9a8eaa7c215f5c21eff87
[ "BSD-3-Clause-LBNL" ]
1
2020-12-12T23:14:16.000Z
2020-12-12T23:14:16.000Z
#!/usr/bin/env python3 #----------------------------------------------------------------------------- # This file is part of the 'Camera link gateway'. It is subject to # the license terms in the LICENSE.txt file found in the top-level directory # of this distribution and at: # https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html. # No part of the 'Camera link gateway', including this file, may be # copied, modified, propagated, or distributed except according to the terms # contained in the LICENSE.txt file. #----------------------------------------------------------------------------- import setupLibPaths import sys import argparse import FmcDev import pyrogue.gui ################################################################# # Set the argument parser parser = argparse.ArgumentParser() # Convert str to bool argBool = lambda s: s.lower() in ['true', 't', 'yes', '1'] # Add arguments parser.add_argument( "--dev", type = str, required = False, default = '/dev/datadev_0', help = "path to device", ) parser.add_argument( "--hwType", type = str, required = False, default = 'eth', help = "Define whether sim/rce/pcie/eth HW config", ) parser.add_argument( "--ip", type = str, required = False, default = '192.168.2.10', help = "IP address for hwType=eth", ) parser.add_argument( "--pollEn", type = argBool, required = False, default = True, help = "Enable auto-polling", ) parser.add_argument( "--initRead", type = argBool, required = False, default = True, help = "Enable read all variables at start", ) # Get the arguments args = parser.parse_args() ################################################################# cl = FmcDev.FmcDev( dev = args.dev, hwType = args.hwType, ip = args.ip, pollEn = args.pollEn, initRead = args.initRead, ) ################################################################# # # Dump the address map # pr.generateAddressMap(cl,'addressMapDummp.txt') # Create GUI appTop = pyrogue.gui.application(sys.argv) guiTop = pyrogue.gui.GuiTop() guiTop.addTree(cl) guiTop.resize(800, 1000) # Run gui appTop.exec_() cl.stop()
24.148936
78
0.546696
ec82b281513c9ca5163de5c3556a478f3bfa3b14
2,969
py
Python
feed.py
Ajnasz/pippo
df9092b1261420f7afad7bf1180e59598cb1cdd9
[ "MIT" ]
1
2016-01-05T16:18:35.000Z
2016-01-05T16:18:35.000Z
feed.py
Ajnasz/pippo
df9092b1261420f7afad7bf1180e59598cb1cdd9
[ "MIT" ]
null
null
null
feed.py
Ajnasz/pippo
df9092b1261420f7afad7bf1180e59598cb1cdd9
[ "MIT" ]
null
null
null
#!/usr/bin/env python import sys import os import Adafruit_DHT import Adafruit_IO import json import requests import traceback from lib import DHTStorage PIDFILE = "/tmp/pippo.pid" class PippoLockedError(Exception): def __init__(self): self.msg = "Pippo locked" class PippoNotLockedError(Exception): def __init__(self): self.msg = "Pippo not locked" class PippoArgumentError(Exception): def __init__(self): self.msg = "Bad argument! usage: sudo ./Adafruit_DHT.py [11|22|2302] 4" class PippoCantRead(Exception): def __init__(self): self.msg = "Failed to get reading. Try again!" def send(client, humidity, temperature): client.send('humidity', '{0:0.3f}'.format(humidity)) client.send('temperature', '{0:0.3f}'.format(temperature)) def toadaio(config, humidity, temperature): client_key = config['key'] try: aio = Adafruit_IO.Client(client_key) send(aio, humidity, temperature) except Adafruit_IO.errors.RequestError: pass except requests.exceptions.ConnectionError: pass except Adafruit_IO.errors.ThrottlingError: pass def todhtstorage(config, humidity, temperature): storage = DHTStorage(key=config['key'], host=config['host'], port=config['port'], db=config['db']) storage.add_temperature(temperature) storage.add_humidity(humidity) def lock(): if islocked(): raise PippoLockedError() pid = str(os.getpid()) file(PIDFILE, "w").write(pid) def unlock(): if not islocked(): raise PippoNotLockedError() os.unlink(PIDFILE) def islocked(): return os.path.isfile(PIDFILE) def main(): err = False try: lock() # Parse command line parameters. sensor_args = { '11': Adafruit_DHT.DHT11, '22': Adafruit_DHT.DHT22, '2302': Adafruit_DHT.AM2302 } if len(sys.argv) == 3 and sys.argv[1] in sensor_args: sensor = sensor_args[sys.argv[1]] pin = sys.argv[2] else: raise PippoArgumentError() # Try to grab a sensor reading. Use the read_retry method which will retry up # to 15 times to get a sensor reading (waiting 2 seconds between each retry). humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) # Un-comment the line below to convert the temperature to Fahrenheit. # temperature = temperature * 9/5.0 + 32 # Note that sometimes you won't get a reading and # the results will be null (because Linux can't # guarantee the timing of calls to read the sensor). # If this happens try again! if humidity is not None and temperature is not None: with open(os.path.join(os.path.dirname(__file__), 'config.json')) as data_file: config = json.load(data_file) todhtstorage(config, humidity, temperature) toadaio(config, humidity, temperature) # print 'Temp={0:0.1f}* Humidity={1:0.1f}%'.format(temperature, humidity) else: raise PippoCantRead() except Exception as ex: err = True print traceback.format_exc() print ex.msg try: unlock() except PippoNotLockedError: pass if err: sys.exit(1) main() # vim: set ts=4 sw=4 noet
24.53719
99
0.720108
6a188355f8fe2eb78eedcb4e2be147585764891b
600
py
Python
magicMirror/weatherModule.py
amldjlee8/MagicMirror
12f1435ceae629a35d31c43423ff5d5cea813604
[ "MIT" ]
null
null
null
magicMirror/weatherModule.py
amldjlee8/MagicMirror
12f1435ceae629a35d31c43423ff5d5cea813604
[ "MIT" ]
null
null
null
magicMirror/weatherModule.py
amldjlee8/MagicMirror
12f1435ceae629a35d31c43423ff5d5cea813604
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from urllib.request import urlopen import json key = '7047852fabf9ea82' def getCurWeatInfo(): url = 'http://api.wunderground.com/api/' + key + '/geolookup/conditions/q/UK/London.json' f = urlopen(url) json_string = f.read() parsed_json = json.loads(json_string.decode()) weather = parsed_json['current_observation']['weather'] temperature = str(parsed_json['current_observation']['temp_c']) + '°C' # feelLikeTemp = 'Feels Like %s°C' %(parsed_json['current_observation']['feelslike_c']) f.close() return weather, temperature
37.5
94
0.67
8ef3ed5f1ac0eb50c273a793f813e28ec40a021e
3,654
py
Python
homeassistant/components/shelly/const.py
learn-home-automation/core
c5d8792c3487e9b418b1e7d623bf59e7dbddd6b7
[ "Apache-2.0" ]
22,481
2020-03-02T13:09:59.000Z
2022-03-31T23:34:28.000Z
homeassistant/components/shelly/const.py
learn-home-automation/core
c5d8792c3487e9b418b1e7d623bf59e7dbddd6b7
[ "Apache-2.0" ]
31,101
2020-03-02T13:00:16.000Z
2022-03-31T23:57:36.000Z
homeassistant/components/shelly/const.py
learn-home-automation/core
c5d8792c3487e9b418b1e7d623bf59e7dbddd6b7
[ "Apache-2.0" ]
11,411
2020-03-02T14:19:20.000Z
2022-03-31T22:46:07.000Z
"""Constants for the Shelly integration.""" from __future__ import annotations import re from typing import Final BLOCK: Final = "block" DATA_CONFIG_ENTRY: Final = "config_entry" DEVICE: Final = "device" DOMAIN: Final = "shelly" REST: Final = "rest" RPC: Final = "rpc" CONF_COAP_PORT: Final = "coap_port" DEFAULT_COAP_PORT: Final = 5683 FIRMWARE_PATTERN: Final = re.compile(r"^(\d{8})") # Firmware 1.11.0 release date, this firmware supports light transition LIGHT_TRANSITION_MIN_FIRMWARE_DATE: Final = 20210226 # max light transition time in milliseconds MAX_TRANSITION_TIME: Final = 5000 RGBW_MODELS: Final = ( "SHBLB-1", "SHRGBW2", ) MODELS_SUPPORTING_LIGHT_TRANSITION: Final = ( "SHBDUO-1", "SHCB-1", "SHDM-1", "SHDM-2", "SHRGBW2", "SHVIN-1", ) MODELS_SUPPORTING_LIGHT_EFFECTS: Final = ( "SHBLB-1", "SHCB-1", "SHRGBW2", ) # Bulbs that support white & color modes DUAL_MODE_LIGHT_MODELS: Final = ( "SHBLB-1", "SHCB-1", ) # Used in "_async_update_data" as timeout for polling data from devices. POLLING_TIMEOUT_SEC: Final = 18 # Refresh interval for REST sensors REST_SENSORS_UPDATE_INTERVAL: Final = 60 # Timeout used for aioshelly calls AIOSHELLY_DEVICE_TIMEOUT_SEC: Final = 10 # Multiplier used to calculate the "update_interval" for sleeping devices. SLEEP_PERIOD_MULTIPLIER: Final = 1.2 CONF_SLEEP_PERIOD: Final = "sleep_period" # Multiplier used to calculate the "update_interval" for non-sleeping devices. UPDATE_PERIOD_MULTIPLIER: Final = 2.2 # Reconnect interval for GEN2 devices RPC_RECONNECT_INTERVAL = 60 # Shelly Air - Maximum work hours before lamp replacement SHAIR_MAX_WORK_HOURS: Final = 9000 # Map Shelly input events INPUTS_EVENTS_DICT: Final = { "S": "single", "SS": "double", "SSS": "triple", "L": "long", "SL": "single_long", "LS": "long_single", } # List of battery devices that maintain a permanent WiFi connection BATTERY_DEVICES_WITH_PERMANENT_CONNECTION: Final = ["SHMOS-01"] # Button/Click events for Block & RPC devices EVENT_SHELLY_CLICK: Final = "shelly.click" ATTR_CLICK_TYPE: Final = "click_type" ATTR_CHANNEL: Final = "channel" ATTR_DEVICE: Final = "device" ATTR_GENERATION: Final = "generation" CONF_SUBTYPE: Final = "subtype" ATTR_BETA: Final = "beta" CONF_OTA_BETA_CHANNEL: Final = "ota_beta_channel" BASIC_INPUTS_EVENTS_TYPES: Final = {"single", "long"} SHBTN_INPUTS_EVENTS_TYPES: Final = {"single", "double", "triple", "long"} RPC_INPUTS_EVENTS_TYPES: Final = { "btn_down", "btn_up", "single_push", "double_push", "long_push", } BLOCK_INPUTS_EVENTS_TYPES: Final = { "single", "double", "triple", "long", "single_long", "long_single", } SHIX3_1_INPUTS_EVENTS_TYPES = BLOCK_INPUTS_EVENTS_TYPES INPUTS_EVENTS_SUBTYPES: Final = { "button": 1, "button1": 1, "button2": 2, "button3": 3, "button4": 4, } SHBTN_MODELS: Final = ["SHBTN-1", "SHBTN-2"] STANDARD_RGB_EFFECTS: Final = { 0: "Off", 1: "Meteor Shower", 2: "Gradual Change", 3: "Flash", } SHBLB_1_RGB_EFFECTS: Final = { 0: "Off", 1: "Meteor Shower", 2: "Gradual Change", 3: "Flash", 4: "Breath", 5: "On/Off Gradual", 6: "Red/Green Change", } SHTRV_01_TEMPERATURE_SETTINGS: Final = { "min": 4, "max": 31, "step": 1, } # Kelvin value for colorTemp KELVIN_MAX_VALUE: Final = 6500 KELVIN_MIN_VALUE_WHITE: Final = 2700 KELVIN_MIN_VALUE_COLOR: Final = 3000 UPTIME_DEVIATION: Final = 5 # Max RPC switch/input key instances MAX_RPC_KEY_INSTANCES = 4 # Time to wait before reloading entry upon device config change ENTRY_RELOAD_COOLDOWN = 60
22.280488
78
0.700055
9602598f5a4a31c6c87b803d962cf618e3a54bc1
15,558
py
Python
addon_common/common/utils.py
Unnoen/retopoflow
73c7cfc10a0b58937198d60e308ba5248b446490
[ "OML" ]
1
2022-01-10T23:40:21.000Z
2022-01-10T23:40:21.000Z
addon_common/common/utils.py
Unnoen/retopoflow
73c7cfc10a0b58937198d60e308ba5248b446490
[ "OML" ]
null
null
null
addon_common/common/utils.py
Unnoen/retopoflow
73c7cfc10a0b58937198d60e308ba5248b446490
[ "OML" ]
null
null
null
''' Copyright (C) 2021 CG Cookie http://cgcookie.com hello@cgcookie.com Created by Jonathan Denning, Jonathan Williamson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import os import re import sys import glob import inspect import operator import itertools import importlib import bpy from mathutils import Vector, Matrix from .blender import get_preferences from .profiler import profiler from .debug import dprint, debugger from .maths import ( Point, Direction, Normal, Frame, Point2D, Vec2D, Direction2D, Ray, XForm, BBox, Plane ) ################################################## StructRNA = bpy.types.bpy_struct def still_registered(self, oplist): if getattr(still_registered, 'is_broken', False): return False def is_registered(): cur = bpy.ops for n in oplist: if not hasattr(cur, n): return False cur = getattr(cur, n) try: StructRNA.path_resolve(self, "properties") except: print('no properties!') return False return True if is_registered(): return True still_registered.is_broken = True print('bpy.ops.%s is no longer registered!' % '.'.join(oplist)) return False registered_objects = {} def registered_object_add(self): global registered_objects opid = self.operator_id print('Registering bpy.ops.%s' % opid) registered_objects[opid] = (self, opid.split('.')) def registered_check(): global registered_objects return all(still_registered(s, o) for (s, o) in registered_objects.values()) ################################################# def find_and_import_all_subclasses(cls, root_path=None): here_path = os.path.realpath(os.path.dirname(__file__)) if root_path is None: root_path = os.path.realpath(os.path.join(here_path, '..')) touched_paths = set() found_subclasses = set() def search(root): nonlocal touched_paths, found_subclasses, here_path root = os.path.realpath(root) if root in touched_paths: return touched_paths.add(root) relpath = os.path.relpath(root, here_path) #print(' relpath: %s' % relpath) for path in glob.glob(os.path.join(root, '*')): if os.path.isdir(path): if not path.endswith('__pycache__'): search(path) continue if os.path.splitext(path)[1] != '.py': continue try: pyfile = os.path.splitext(os.path.basename(path))[0] if pyfile == '__init__': continue pyfile = os.path.join(relpath, pyfile) pyfile = re.sub(r'\\', '/', pyfile) if pyfile.startswith('./'): pyfile = pyfile[2:] level = pyfile.count('..') pyfile = re.sub(r'^(\.\./)*', '', pyfile) pyfile = re.sub('/', '.', pyfile) #print(' Searching: %s (%d, %s)' % (pyfile, level, path)) try: tmp = importlib.__import__(pyfile, globals(), locals(), [], level=level+1) except Exception as e: print('Caught exception while attempting to search for classes') print(' cls: %s' % str(cls)) print(' pyfile: %s' % pyfile) print(' %s' % str(e)) #print(' Could not import') continue for tk in dir(tmp): m = getattr(tmp, tk) if not inspect.ismodule(m): continue for k in dir(m): v = getattr(m, k) if not inspect.isclass(v): continue if v is cls: continue if not issubclass(v, cls): continue # v is a subclass of cls, so add it to the global namespace #print(' Found %s in %s' % (str(v), pyfile)) globals()[k] = v found_subclasses.add(v) except Exception as e: print('Exception occurred while searching %s' % path) debugger.print_exception() #print('Searching for class %s' % str(cls)) #print(' cwd: %s' % os.getcwd()) #print(' Root: %s' % root_path) search(root_path) return found_subclasses ######################################################### def delay_exec(action, f_globals=None, f_locals=None, ordered_parameters=None, precall=None): if f_globals is None or f_locals is None: frame = inspect.currentframe().f_back # get frame of calling function if f_globals is None: f_globals = frame.f_globals # get globals of calling function if f_locals is None: f_locals = frame.f_locals # get locals of calling function def run_it(*args, **kwargs): # args are ignored!? nf_locals = dict(f_locals) if ordered_parameters: for k,v in zip(ordered_parameters, args): nf_locals[k] = v nf_locals.update(kwargs) try: if precall: precall(nf_locals) return exec(action, f_globals, nf_locals) except Exception as e: print('Caught exception while trying to run a delay_exec') print(' action:', action) print(' except:', e) raise e return run_it ######################################################### def git_info(start_at_caller=True): if start_at_caller: path_root = os.path.abspath(inspect.stack()[1][1]) else: path_root = os.path.abspath(os.path.dirname(__file__)) try: path_git_head = None while path_root: path_test = os.path.join(path_root, '.git', 'HEAD') if os.path.exists(path_test): # found it! path_git_head = path_test break if os.path.split(path_root)[1] in {'addons', 'addons_contrib'}: break path_root = os.path.dirname(path_root) # try next level up if not path_git_head: # could not find .git folder return None path_git_ref = open(path_git_head).read().split()[1] if not path_git_ref.startswith('refs/heads/'): print('git detected, but HEAD uses unexpected format') return None path_git_ref = path_git_ref[len('refs/heads/'):] git_ref_fullpath = os.path.join(path_root, '.git', 'logs', 'refs', 'heads', path_git_ref) if not os.path.exists(git_ref_fullpath): print('git detected, but could not find ref file %s' % git_ref_fullpath) return None log = open(git_ref_fullpath).read().splitlines() commit = log[-1].split()[1] return ('%s %s' % (path_git_ref, commit)) except Exception as e: print('An exception occurred while checking git info') print(e) return None ######################################################### def kwargopts(kwargs, defvals=None, **mykwargs): opts = defvals.copy() if defvals else {} opts.update(mykwargs) opts.update(kwargs) if 'opts' in kwargs: opts.update(opts['opts']) def factory(): class Opts(): ''' pretend to be a dictionary, but also add . access fns ''' def __init__(self): self.touched = set() def __getattr__(self, opt): self.touched.add(opt) return opts[opt] def __getitem__(self, opt): self.touched.add(opt) return opts[opt] def __len__(self): return len(opts) def has_key(self, opt): return opt in opts def keys(self): return opts.keys() def values(self): return opts.values() def items(self): return opts.items() def __contains__(self, opt): return opt in opts def __iter__(self): return iter(opts) def print_untouched(self): print('untouched: %s' % str(set(opts.keys()) - self.touched)) def pass_through(self, *args): return {key:self[key] for key in args} return Opts() return factory() def kwargs_translate(key_from, key_to, kwargs): if key_from in kwargs: kwargs[key_to] = kwargs[key_from] del kwargs[key_from] def kwargs_splitter(keys, kwargs): if type(keys) is str: keys = [keys] kw = {k:v for (k,v) in kwargs.items() if k in keys} for k in keys: if k in kwargs: del kwargs[k] return kw def any_args(*args): return any(bool(a) for a in args) def get_and_discard(d, k, default=None): if k not in d: return default v = d[k] del d[k] return v ################################################# def abspath(*args, frame_depth=1, **kwargs): frame = inspect.currentframe() for i in range(frame_depth): frame = frame.f_back module = inspect.getmodule(frame) path = os.path.dirname(module.__file__) return os.path.abspath(os.path.join(path, *args, **kwargs)) ################################################# def strshort(s, l=50): s = str(s) return s[:l] + ('...' if len(s) > l else '') def join(sep, iterable, preSep='', postSep='', toStr=str): ''' this function adds features on to sep.join(iterable) if iterable is not empty, preSep is prepended and postSep is appended also, all items of iterable are turned to strings using toStr, which can be customized ex: join(', ', [1,2,3]) => '1, 2, 3' ex: join('.', ['foo', 'bar'], preSep='.') => '.foo.bar' ''' s = sep.join(map(toStr, iterable)) if not s: return '' return f'{preSep}{s}{postSep}' def accumulate_last(iterable, *args, **kwargs): # returns last result when accumulating # https://docs.python.org/3.7/library/itertools.html#itertools.accumulate final = None for step in itertools.accumulate(iterable, *args, **kwargs): final = step return final def selection_mouse(): select_type = get_preferences().inputs.select_mouse return ['%sMOUSE' % select_type, 'SHIFT+%sMOUSE' % select_type] def get_settings(): if not hasattr(get_settings, 'cache'): addons = get_preferences().addons folderpath = os.path.dirname(os.path.abspath(__file__)) while folderpath: folderpath,foldername = os.path.split(folderpath) if foldername in {'lib','addons', 'addons_contrib'}: continue if foldername in addons: break else: assert False, 'Could not find non-"lib" folder' if not addons[foldername].preferences: return None get_settings.cache = addons[foldername].preferences return get_settings.cache def get_dpi(): system_preferences = get_preferences().system factor = getattr(system_preferences, "pixel_size", 1) return int(system_preferences.dpi * factor) def get_dpi_factor(): return get_dpi() / 72 def blender_version(): major,minor,rev = bpy.app.version # '%03d.%03d.%03d' % (major, minor, rev) return '%d.%02d' % (major,minor) def iter_head(i, default=None): try: return next(iter(i)) except StopIteration: return default def iter_running_sum(lw): s = 0 for w in lw: s += w yield (w,s) def iter_pairs(items, wrap, repeat=False): if not items: return while True: for i0,i1 in zip(items[:-1],items[1:]): yield i0,i1 if wrap: yield items[-1],items[0] if not repeat: return def rotate_cycle(cycle, offset): l = len(cycle) return [cycle[(l + ((i - offset) % l)) % l] for i in range(l)] def max_index(vals, key=None): if not key: return max(enumerate(vals), key=lambda ival:ival[1])[0] return max(enumerate(vals), key=lambda ival:key(ival[1]))[0] def min_index(vals, key=None): if not key: return min(enumerate(vals), key=lambda ival:ival[1])[0] return min(enumerate(vals), key=lambda ival:key(ival[1]))[0] def shorten_floats(s): # reduces number of digits (for float) found in a string # useful for reducing noise of printing out a Vector, Buffer, Matrix, etc. s = re.sub(r'(?P<neg>-?)(?P<d0>\d)\.(?P<d1>\d)\d\d+e-02', r'\g<neg>0.0\g<d0>\g<d1>', s) s = re.sub(r'(?P<neg>-?)(?P<d0>\d)\.\d\d\d+e-03', r'\g<neg>0.00\g<d0>', s) s = re.sub(r'-?\d\.\d\d\d+e-0[4-9]', r'0.000', s) s = re.sub(r'-?\d\.\d\d\d+e-[1-9]\d', r'0.000', s) s = re.sub(r'(?P<digs>\d\.\d\d\d)\d+', r'\g<digs>', s) return s def get_matrices(ob): ''' obtain blender object matrices ''' mx = ob.matrix_world imx = mx.inverted_safe() return (mx, imx) class AddonLocator(object): def __init__(self, f=None): self.fullInitPath = f if f else __file__ self.FolderPath = os.path.dirname(self.fullInitPath) self.FolderName = os.path.basename(self.FolderPath) def AppendPath(self): sys.path.append(self.FolderPath) print("Addon path has been registered into system path for this session") class UniqueCounter(): __counter = 0 @staticmethod def next(): UniqueCounter.__counter += 1 return UniqueCounter.__counter class Dict(): ''' a fancy dictionary object ''' def __init__(self, *args, **kwargs): self.__dict__['__d'] = {} self.set(*args, **kwargs) def __getitem__(self, k): return self.__dict__['__d'][k] def __setitem__(self, k, v): self.__dict__['__d'][k] = v return v def __delitem__(self, k): del self.__dict__['__d'][k] def __getattr__(self, k): return self.__dict__['__d'][k] def __setattr__(self, k, v): self.__dict__['__d'][k] = v return v def __delattr__(self, k): del self.__dict__['__d'][k] def set(self, d=None, **kwargs): if d: for k,v in d.items(): self[k] = v for k,v in kwargs.items(): self[k] = v def __str__(self): return str(self.__dict__['__d']) def __repr__(self): return repr(self.__dict__['__d']) def has_duplicates(lst): l = len(lst) if l == 0: return False if l < 20 or not hasattr(lst[0], '__hash__'): # runs in O(n^2) time (perfectly fine if n is small, assuming [:index] uses iter) # does not require items in list to hash # requires O(1) memory return any(item in lst[:index] for (index,item) in enumerate(lst)) else: # runs in either O(n) time (assuming hash-set) # requires items to hash # requires O(N) memory seen = set() for i in lst: if i in seen: return True seen.add(i) return False def deduplicate_list(l): nl = [] for i in l: if i in nl: continue nl.append(i) return nl
32.961864
97
0.575652
75e12cf491c5104839b8d2d7628733e5a89df5fa
3,639
py
Python
python/main.py
maaaybe/gameoflife
bba3d47204d8939c0bb15875f681e5b35209e708
[ "MIT" ]
2
2020-07-12T21:07:15.000Z
2022-03-23T15:33:06.000Z
python/main.py
maaaybe/gameoflife
bba3d47204d8939c0bb15875f681e5b35209e708
[ "MIT" ]
null
null
null
python/main.py
maaaybe/gameoflife
bba3d47204d8939c0bb15875f681e5b35209e708
[ "MIT" ]
null
null
null
from time import sleep import numpy as np import math import multiprocessing AVAILABLE_TOKEN_LENGHT = [n ** 2 for n in range(1, 16)] class GameOfLife(object): def __init__(self, x_scale, y_scale, multithreaded=False): self.width = 16 * x_scale self.height = 16 * y_scale self.board = np.zeros((self.width, self.height), dtype=int) self.multithreaded = multithreaded self.processes = max([l for l in AVAILABLE_TOKEN_LENGHT if multiprocessing.cpu_count() >= l]) self.tokens_per_direction = round(math.sqrt(self.processes)) self.token_width = round(self.board.shape[0] / math.sqrt(self.processes)) self.token_height = round(self.board.shape[1] / math.sqrt(self.processes)) self.thread_areas = [] self.init() def init(self): for x in range(self.width): for y in range(self.height): self.board[x][y] = np.random.randint(0, 2) def parse(self): if self.multithreaded: token_queue = [] for x in range(0, self.tokens_per_direction): for y in range(0, self.tokens_per_direction): x_init = x * self.token_width y_init = y * self.token_height x_end = x * self.token_width + self.token_width y_end = y * self.token_height + self.token_height if len(self.thread_areas) < self.processes: self.thread_areas.append((x_init, y_init, self.token_width, self.token_height)) token_queue.append((self.board[x_init:x_end, y_init:y_end], (x, y))) # processing token queue parsed_tokens = [] with multiprocessing.Pool(self.processes) as pool: parsed_tokens = pool.map(self.parse_token, token_queue) for token in parsed_tokens: x_init = token[1][0] * self.token_width y_init = token[1][1] * self.token_height x_end = token[1][0] * self.token_width + self.token_width y_end = token[1][1] * self.token_height + self.token_height for x in range(x_init, x_end): for y in range(y_init, y_end): self.board[x][y] = token[0][x % self.token_width][y % self.token_height] else: self.thread_areas.append((0, 0, self.board.shape[0], self.board.shape[1])) self.board = self.parse_token([self.board, (0, 0)])[0] def parse_token(self, token): token_id = token[1] token = token[0] copy = np.copy(token) for x in range(token.shape[0]): neighbour = 0 for y in range(token.shape[1]): sliced = copy[max(0, x-1):min(x+2, token.shape[0]+1),max(0, y-1):min(y+2, token.shape[1]+1)] neighbour = np.sum(sliced) - copy[x][y] if copy[x][y] and (neighbour < 2 or neighbour > 3): token[x][y] = 0 elif not copy[x][y] and neighbour == 3: token[x][y] = 1 return token, token_id def get_board(self): return self.board, self.thread_areas def __str__(self): result = "" for x in range(self.width): for y in range(self.height): result += "*" if self.board[x][y] else " " result += "\n" return result if __name__ == "__main__": gol = GameOfLife(4, 4, multithreaded=True) while True: gol.parse() print(gol)
36.757576
108
0.548228
fb6ca365c047999a43007e3be6ff9a1d58936074
1,216
py
Python
testing_again/public/forms.py
jsmyth/testing_again
897848b0091e76f90d97c05d8c8462af13876d39
[ "MIT" ]
null
null
null
testing_again/public/forms.py
jsmyth/testing_again
897848b0091e76f90d97c05d8c8462af13876d39
[ "MIT" ]
null
null
null
testing_again/public/forms.py
jsmyth/testing_again
897848b0091e76f90d97c05d8c8462af13876d39
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """Public forms.""" from flask_wtf import FlaskForm from wtforms import PasswordField, StringField from wtforms.validators import DataRequired from testing_again.user.models import User class LoginForm(FlaskForm): """Login form.""" username = StringField("Username", validators=[DataRequired()]) password = PasswordField("Password", validators=[DataRequired()]) def __init__(self, *args, **kwargs): """Create instance.""" super(LoginForm, self).__init__(*args, **kwargs) self.user = None def validate(self): """Validate the form.""" initial_validation = super(LoginForm, self).validate() if not initial_validation: return False self.user = User.query.filter_by(username=self.username.data).first() if not self.user: self.username.errors.append("Unknown username") return False if not self.user.check_password(self.password.data): self.password.errors.append("Invalid password") return False if not self.user.active: self.username.errors.append("User not activated") return False return True
30.4
77
0.644737
b6f90840f2cc6c857fcec635def31bd21be15fc5
3,535
py
Python
undatum/cmds/transformer.py
infoculture/datum
e8ea97ca916ec718c5c2b8866a01fbbe55d6cc55
[ "MIT" ]
26
2020-04-16T13:54:12.000Z
2022-03-26T06:21:48.000Z
undatum/cmds/transformer.py
infoculture/datum
e8ea97ca916ec718c5c2b8866a01fbbe55d6cc55
[ "MIT" ]
10
2020-04-16T13:00:37.000Z
2022-02-09T11:52:06.000Z
undatum/cmds/transformer.py
infoculture/datum
e8ea97ca916ec718c5c2b8866a01fbbe55d6cc55
[ "MIT" ]
5
2020-04-20T10:48:08.000Z
2022-01-30T11:56:54.000Z
from xlrd import open_workbook from operator import itemgetter, attrgetter import csv import zipfile import sys import orjson import bson import logging #from xmlr import xmliter import xml.etree.ElementTree as etree from collections import defaultdict from ..utils import get_file_type, get_option, write_items, get_dict_value, strip_dict_fields, dict_generator import dictquery as dq from runpy import run_path class Transformer: def __init__(self): pass def script(self, fromfile, options={}): """Run certain script against selected file""" f_type = get_file_type(fromfile) if options['format_in'] is None else options['format_in'] if options['zipfile']: z = zipfile.ZipFile(fromfile, mode='r') fnames = z.namelist() if f_type == 'bson': infile = z.open(fnames[0], 'rb') else: infile = z.open(fnames[0], 'r') else: if f_type == 'bson': infile = open(fromfile, 'rb') else: infile = open(fromfile, 'r', encoding=get_option(options, 'encoding')) to_file = get_option(options, 'output') if to_file: to_type = get_file_type(to_file) if not to_file: print('Output file type not supported') return if to_type == 'bson': out = open(to_file, 'wb') elif to_type == 'jsonl': out = open(to_file, 'wb') else: out = open(to_file, 'w', encoding='utf8') else: to_type = f_type out = sys.stdout # fields = options['fields'].split(',') if options['fields'] else None script = run_path(options['script']) __process_func = script['process'] delimiter = get_option(options, 'delimiter') if f_type == 'csv': reader = csv.DictReader(infile, delimiter=delimiter) if to_type == 'csv': writer = csv.DictWriter(out, fieldnames=fields, delimiter=delimiter) writer.writeheader() n = 0 for r in reader: n += 1 if n % 10000 == 0: logging.info('apply script: processing %d records of %s' % (n, fromfile)) item = __process_func(r) if to_type == 'csv': writer.writerow(item) elif to_type == 'jsonl': out.write(orjson.dumps(item, option=orjson.OPT_APPEND_NEWLINE)) elif f_type == 'jsonl': n = 0 for l in infile: n += 1 if n % 10000 == 0: logging.info('apply script: processing %d records of %s' % (n, fromfile)) r = orjson.loads(l) item = __process_func(r) out.write(orjson.dumps(item, option=orjson.OPT_APPEND_NEWLINE)) elif f_type == 'bson': bson_iter = bson.decode_file_iter(infile) n = 0 for r in bson_iter: n += 1 if n % 10000 == 0: logging.info('apply script: processing %d records of %s' % (n, fromfile)) item = __process_func(r) out.write(str(orjson.dumps(item, option=orjson.OPT_APPEND_NEWLINE))) else: logging.info('File type not supported') return logging.debug('select: %d records processed' % (n)) out.close()
37.210526
109
0.537199
d325541692490525347ed59a8124511baa8ccf3f
801
py
Python
docs/source/examples/external-credentials.py
aviramha/aio-pika
c480d2e62ac3f3e31a0714114e368bb6fd6eeb34
[ "Apache-2.0" ]
null
null
null
docs/source/examples/external-credentials.py
aviramha/aio-pika
c480d2e62ac3f3e31a0714114e368bb6fd6eeb34
[ "Apache-2.0" ]
null
null
null
docs/source/examples/external-credentials.py
aviramha/aio-pika
c480d2e62ac3f3e31a0714114e368bb6fd6eeb34
[ "Apache-2.0" ]
null
null
null
import asyncio import aio_pika import ssl async def main(loop): connection = await aio_pika.connect_robust( host='127.0.0.1', login='', ssl=True, ssl_options=dict( ca_certs="cacert.pem", certfile="cert.pem", keyfile="key.pem", cert_reqs=ssl.CERT_REQUIRED, ), loop=loop ) async with connection: routing_key = "test_queue" channel = await connection.channel() await channel.default_exchange.publish( aio_pika.Message( body='Hello {}'.format(routing_key).encode() ), routing_key=routing_key ) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main(loop)) loop.close()
22.25
60
0.573034
85bf5e058412fedab966b2f661db34e58d6cc46f
1,808
py
Python
app/model/charts/maps/mixed.py
smartlab-br/datahub-api
193e71172bb4891a5bbffc902da07ef57df9ab07
[ "MIT" ]
1
2019-07-25T21:15:05.000Z
2019-07-25T21:15:05.000Z
app/model/charts/maps/mixed.py
smartlab-br/datahub-api
193e71172bb4891a5bbffc902da07ef57df9ab07
[ "MIT" ]
44
2019-08-05T15:24:00.000Z
2022-01-31T23:11:31.000Z
app/model/charts/maps/mixed.py
smartlab-br/datahub-api
193e71172bb4891a5bbffc902da07ef57df9ab07
[ "MIT" ]
1
2021-05-11T07:49:51.000Z
2021-05-11T07:49:51.000Z
''' Model for fetching chart ''' import folium from model.charts.maps.base import BaseMap class Mixed(BaseMap): """ Mixed map building class """ def __init__(self, layers): super().__init__(None, None) # Blocks instantiation of dataframes and options self.layers = layers def draw(self): """ Generates a base map and add layers according to config """ # Creating map instance result = folium.Map(tiles=self.TILES_URL, attr=self.TILES_ATTRIBUTION, control_scale=True) # Generates layers for layer in self.layers: analysis_unit = layer.options.get('au') if layer.options.get('chart_type') == 'MAP_TOPOJSON': layer.prepare_dataframe() # Join dataframe and state_geo (state_geo, centroid) = layer.join_df_geo(layer.get_geometry(analysis_unit)) # Generating choropleth layer layer.layer_gen(state_geo).add_to(result) elif layer.options.get('chart_type') == 'MAP_BUBBLES': layer.prepare_dataframe(layer.get_tooltip_data()) # Get grouped dataframe grouped = layer.dataframe.groupby(layer.options.get('layer_id', 'cd_indicador')) for group_id, group in grouped: layer.layer_gen(group, group_id, True).add_to(result) folium.LayerControl().add_to(result) result.get_root().header.add_child(folium.Element(self.STYLE_STATEMENT)) # Getting bounds from topojson lower_left = state_geo.get('bbox')[:2] lower_left.reverse() upper_right = state_geo.get('bbox')[2:] upper_right.reverse() # Zooming to bounds result.fit_bounds([lower_left, upper_right]) return result
38.468085
98
0.627212
e207dfe8e8beb68e5cb15408532c7ef862e88f83
517
py
Python
hooks/pre_gen_project.py
Blueshoe/hurricane-based-helm-template
af96f375509d74744becd1b31edf3c9538bf28a6
[ "MIT" ]
3
2021-11-10T14:56:42.000Z
2022-03-17T13:02:55.000Z
hooks/pre_gen_project.py
django-hurricane/hurricane-based-helm-template
6d69f115b8da5b879b7f243708406b7b18ce71ab
[ "MIT" ]
8
2021-07-19T11:50:34.000Z
2022-03-17T11:08:14.000Z
hooks/pre_gen_project.py
django-hurricane/hurricane-based-helm-template
6d69f115b8da5b879b7f243708406b7b18ce71ab
[ "MIT" ]
null
null
null
import re import sys try: import gnupg except ImportError: print("Warning: there is a problem with the import of 'gnupg' which is required for encrypting secret value files.") APP_SLUG_REGEX = "^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$" app_slug = '{{ cookiecutter.app_slug }}' if not re.match(APP_SLUG_REGEX, app_slug): print('ERROR: %s is not a valid app slug. It must resemble a valid domain name.' % app_slug) # exits with status 1 to indicate failure sys.exit(1)
28.722222
120
0.67118
3183735bcca38f1022ba8bfee7781730724440cb
135
py
Python
T07-25/program.py
maa76/SSof-Project1920
9b4ad9ac41a648c425fcfcd49cd52ff84e528bde
[ "MIT" ]
2
2019-11-20T19:26:07.000Z
2019-11-22T00:42:23.000Z
T07-25/program.py
maa76/SSof-Project1920
9b4ad9ac41a648c425fcfcd49cd52ff84e528bde
[ "MIT" ]
2
2019-11-28T05:21:24.000Z
2019-11-28T05:21:58.000Z
T07-25/program.py
maa76/SSof-Project1920
9b4ad9ac41a648c425fcfcd49cd52ff84e528bde
[ "MIT" ]
25
2019-11-27T01:40:56.000Z
2019-12-04T23:38:59.000Z
a = source() b = source2() c = source3() d = source4() e = a f = b + c g = 2*c + d c = 1 print(sink(sink(e), c, sink(f), sink(g, 4*a)))
15
46
0.511111
3ccf98c1450396bc27d3b6ad8c8830fc33b1caac
3,301
py
Python
dataLoad.py
sagarcasm/ApacheWebLogExtraction
63c8ac392fbf80d60de6cef49bb00272c4fc1671
[ "Apache-2.0" ]
1
2018-12-13T14:59:01.000Z
2018-12-13T14:59:01.000Z
dataLoad.py
sagarcasm/ApacheWebLogExtraction
63c8ac392fbf80d60de6cef49bb00272c4fc1671
[ "Apache-2.0" ]
null
null
null
dataLoad.py
sagarcasm/ApacheWebLogExtraction
63c8ac392fbf80d60de6cef49bb00272c4fc1671
[ "Apache-2.0" ]
null
null
null
import pymysql class webLogs: def __init__(self, path): self.path = path def initialdataLoad(self): print(self.path) data = [] #read lines from the csv with open(self.path) as file: file = file.readlines() for line in file: print(line) logdata = line.split(" ") ip = logdata[0] dateTime = self.cleanData(logdata[3] + " " + logdata[4]) methods = self.cleanData(logdata[5]) requestResource = self.cleanData(logdata[6]) protocol = self.cleanData(logdata[7]) status = self.cleanData(logdata[8]) bytesTransfered = self.cleanData(logdata[9]) try: requestUrl = logdata[10] except IndexError: requestUrl = "NA" if (bytesTransfered == '-'): bytesTransfered = '0' http_user_agent = " ".join(logdata[11:]) if (http_user_agent == ''): http_user_agent = 'NA' logDataDict = {'remote_addr':ip,'time_local':dateTime,'request_type':methods,'request_resource':requestResource,'request_url':requestUrl,\ 'request_status': status,'bytes_sent':bytesTransfered,'http_referer':protocol,'http_user_agent':http_user_agent,'raw_log':line} self.insertQuery(logDataDict) # function to insert data into database def insertQuery(self,data): # database paramters HOSTNAME = '----ADD ypur MYSQL host-----' USER = '----ADD ypur MYSQL USER-----' PASSWORD = '----ADD ypur MYSQL PASSKEY-----' DATABASE = '----ADD ypur MYSQL DB-----' sqlConnection = pymysql.connect(host=HOSTNAME, user=USER, passwd=PASSWORD, db=DATABASE) cur = sqlConnection.cursor() query = "INSERT INTO weblogs (remote_addr, time_local, request_type,request_resource, request_url,request_status,bytes_sent, http_referer, http_user_agent,raw_log) \ VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" try: cur.execute(query, ( str(data['remote_addr']), str(data['time_local']), str(data['request_type']), str(data['request_resource']), str(data['request_url']), \ str(data['request_status']), str(data['bytes_sent']), str(data['http_referer']), str(data['http_user_agent']), str(data['raw_log']))) sqlConnection.commit() #for debug purposes to check your Query # if cur.lastrowid: # print('last insert id', cur.lastrowid) # print(cur._last_executed) # else: # print('last insert id not found') except: sqlConnection.rollback() sqlConnection.close() #clean the data to strip of the extra special characters from the data def cleanData(self,item): characters = ['[', ']', "'", '\n'] for char in characters: item = item.replace(char, "") return item #provide the directory of Apache weblog file you want to upload in the SQL table wl = webLogs("ADD your web log location") wl.initialdataLoad()
35.880435
175
0.55771
c3ab7f99bb0ddef4197783f8a6e02d61c4564180
702
py
Python
digHostnameExtractor/hostname_extractor.py
darkshadows123/dig-hostname-extractor
70f3529cb9a4a683cc0b36392e7949dd09021baa
[ "MIT" ]
null
null
null
digHostnameExtractor/hostname_extractor.py
darkshadows123/dig-hostname-extractor
70f3529cb9a4a683cc0b36392e7949dd09021baa
[ "MIT" ]
null
null
null
digHostnameExtractor/hostname_extractor.py
darkshadows123/dig-hostname-extractor
70f3529cb9a4a683cc0b36392e7949dd09021baa
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # @Author: darkshadows123 import copy from digExtractor.extractor import Extractor from dig_hostname_extractor import DIGHostnameExtractor class HostnameExtractor(Extractor): def __init__(self): self.renamed_input_fields = ['text'] self.dhostname = DIGHostnameExtractor() def extract(self, doc): if 'text' in doc: return self.dhostname.extract_hostname(doc['text']) return None def get_metadata(self): return copy.copy(self.metadata) def set_metadata(self, metadata): self.metadata = metadata return self def get_renamed_input_fields(self): return self.renamed_input_fields
24.206897
63
0.68661
edc4240cd8bf5e7a41af6f0e501764e332f19a9c
1,466
py
Python
01-Apprenez/4.06a.py
gruiick/openclassrooms-py
add4b28eab8b311dea7c1d3915a22061f54326a9
[ "BSD-2-Clause" ]
null
null
null
01-Apprenez/4.06a.py
gruiick/openclassrooms-py
add4b28eab8b311dea7c1d3915a22061f54326a9
[ "BSD-2-Clause" ]
null
null
null
01-Apprenez/4.06a.py
gruiick/openclassrooms-py
add4b28eab8b311dea7c1d3915a22061f54326a9
[ "BSD-2-Clause" ]
null
null
null
#!/usr/bin/env python3 # coding: utf-8 # $Id: 4.06a.py 1.4 $ # SPDX-License-Identifier: BSD-2-Clause """ Réseau (TCP) """ import socket """ # serveur : connexion_principale = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connexion_principale.bind(('', 12800)) connexion_principale.listen(5) connexion_avec_client, infos_connexion = connexion_principale.accept() # client connexion_avec_serveur = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connexion_avec_serveur.connect(('localhost', 12800)) # serveur print(infos_connexion) connexion_avec_client.send(b'connexion acceptee') # ASCII literal only # client msg_recu = connexion_avec_serveur.recv(1024) print(msg_recu) connexion_avec_serveur.send(b'Cool') connexion_avec_serveur.close() # serveur msg = connexion_avec_client.recv(1024) print(msg) connexion_avec_client.close() """ hote = '' port = 12800 connexion_principale = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connexion_principale.bind((hote, port)) connexion_principale.listen(5) print('Le serveur écoute sur le port {}'.format(port)) connexion_avec_client, infos_connexion = connexion_principale.accept() msg_recu = b'' while msg_recu != b'fin': msg_recu = connexion_avec_client.recv(1024) # si le msg contient des accents, il y aura une exception print(msg_recu.decode()) connexion_avec_client.send(b'copy, 5/5') print('Fermeture de la connexion') connexion_avec_client.close() connexion_principale.close()
24.847458
74
0.772851
04cbf20c71f152d152911b0da152ed6eda38d543
13,146
py
Python
tensorflow_probability/python/bijectors/bijector_test_util.py
bourov/probability
1e4053a0938b4773c3425bcbb07b3f1e5d50c7e2
[ "Apache-2.0" ]
2
2020-12-17T20:43:24.000Z
2021-06-11T22:09:16.000Z
tensorflow_probability/python/bijectors/bijector_test_util.py
bourov/probability
1e4053a0938b4773c3425bcbb07b3f1e5d50c7e2
[ "Apache-2.0" ]
null
null
null
tensorflow_probability/python/bijectors/bijector_test_util.py
bourov/probability
1e4053a0938b4773c3425bcbb07b3f1e5d50c7e2
[ "Apache-2.0" ]
1
2020-12-19T13:05:15.000Z
2020-12-19T13:05:15.000Z
# Copyright 2018 The TensorFlow Probability Authors. # # 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. # ============================================================================ """Bijector unit-test utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools # Dependency imports from absl import logging import numpy as np import tensorflow.compat.v2 as tf from tensorflow_probability.python.bijectors import reshape as reshape_bijector from tensorflow_probability.python.distributions import uniform as uniform_distribution from tensorflow_probability.python.internal import dtype_util from tensorflow_probability.python.internal import tensorshape_util from tensorflow_probability.python.internal import test_util as tfp_test_util from tensorflow_probability.python.math.gradient import batch_jacobian JAX_MODE = False def assert_finite(array): if not np.isfinite(array).all(): raise AssertionError('array was not all finite. %s' % array[:15]) def assert_strictly_increasing(array): np.testing.assert_array_less(0., np.diff(array)) def assert_strictly_decreasing(array): np.testing.assert_array_less(np.diff(array), 0.) def assert_strictly_monotonic(array): if array[0] < array[-1]: assert_strictly_increasing(array) else: assert_strictly_decreasing(array) def assert_scalar_congruency(bijector, lower_x, upper_x, eval_func, n=int(10e3), rtol=0.01): """Assert `bijector`'s forward/inverse/inverse_log_det_jacobian are congruent. We draw samples `X ~ U(lower_x, upper_x)`, then feed these through the `bijector` in order to check that: 1. the forward is strictly monotonic. 2. the forward/inverse methods are inverses of each other. 3. the jacobian is the correct change of measure. This can only be used for a Bijector mapping open subsets of the real line to themselves. This is due to the fact that this test compares the `prob` before/after transformation with the Lebesgue measure on the line. Args: bijector: Instance of Bijector lower_x: Python scalar. upper_x: Python scalar. Must have `lower_x < upper_x`, and both must be in the domain of the `bijector`. The `bijector` should probably not produce huge variation in values in the interval `(lower_x, upper_x)`, or else the variance based check of the Jacobian will require small `rtol` or huge `n`. eval_func: Function to evaluate any intermediate results. n: Number of samples to draw for the checks. rtol: Positive number. Used for the Jacobian check. Raises: AssertionError: If tests fail. """ # Should be monotonic over this interval ten_x_pts = np.linspace(lower_x, upper_x, num=10).astype(np.float32) if bijector.dtype is not None: ten_x_pts = ten_x_pts.astype(dtype_util.as_numpy_dtype(bijector.dtype)) lower_x = np.cast[dtype_util.as_numpy_dtype(bijector.dtype)](lower_x) upper_x = np.cast[dtype_util.as_numpy_dtype(bijector.dtype)](upper_x) forward_on_10_pts = bijector.forward(ten_x_pts) # Set the lower/upper limits in the range of the bijector. lower_y, upper_y = eval_func( [bijector.forward(lower_x), bijector.forward(upper_x)]) if upper_y < lower_y: # If bijector.forward is a decreasing function. lower_y, upper_y = upper_y, lower_y # Uniform samples from the domain, range. seed_stream = tfp_test_util.test_seed_stream(salt='assert_scalar_congruency') uniform_x_samps = uniform_distribution.Uniform( low=lower_x, high=upper_x).sample(n, seed=seed_stream()) uniform_y_samps = uniform_distribution.Uniform( low=lower_y, high=upper_y).sample(n, seed=seed_stream()) # These compositions should be the identity. inverse_forward_x = bijector.inverse(bijector.forward(uniform_x_samps)) forward_inverse_y = bijector.forward(bijector.inverse(uniform_y_samps)) # For a < b, and transformation y = y(x), # (b - a) = \int_a^b dx = \int_{y(a)}^{y(b)} |dx/dy| dy # "change_measure_dy_dx" below is a Monte Carlo approximation to the right # hand side, which should then be close to the left, which is (b - a). # We assume event_ndims=0 because we assume scalar -> scalar. The log_det # methods will handle whether they expect event_ndims > 0. dy_dx = tf.exp( bijector.inverse_log_det_jacobian(uniform_y_samps, event_ndims=0)) # E[|dx/dy|] under Uniform[lower_y, upper_y] # = \int_{y(a)}^{y(b)} |dx/dy| dP(u), where dP(u) is the uniform measure expectation_of_dy_dx_under_uniform = tf.reduce_mean(dy_dx) # dy = dP(u) * (upper_y - lower_y) change_measure_dy_dx = ( (upper_y - lower_y) * expectation_of_dy_dx_under_uniform) # We'll also check that dy_dx = 1 / dx_dy. dx_dy = tf.exp( bijector.forward_log_det_jacobian( bijector.inverse(uniform_y_samps), event_ndims=0)) [ forward_on_10_pts_v, dy_dx_v, dx_dy_v, change_measure_dy_dx_v, uniform_x_samps_v, uniform_y_samps_v, inverse_forward_x_v, forward_inverse_y_v, ] = eval_func([ forward_on_10_pts, dy_dx, dx_dy, change_measure_dy_dx, uniform_x_samps, uniform_y_samps, inverse_forward_x, forward_inverse_y, ]) assert_strictly_monotonic(forward_on_10_pts_v) # Composition of forward/inverse should be the identity. np.testing.assert_allclose( inverse_forward_x_v, uniform_x_samps_v, atol=1e-5, rtol=1e-3) np.testing.assert_allclose( forward_inverse_y_v, uniform_y_samps_v, atol=1e-5, rtol=1e-3) # Change of measure should be correct. np.testing.assert_allclose( desired=upper_x - lower_x, actual=change_measure_dy_dx_v, atol=0, rtol=rtol) # Inverse Jacobian should be equivalent to the reciprocal of the forward # Jacobian. np.testing.assert_allclose( desired=dy_dx_v, actual=np.reciprocal(dx_dy_v), atol=1e-5, rtol=1e-3) def assert_bijective_and_finite(bijector, x, y, event_ndims, eval_func, inverse_event_ndims=None, atol=0, rtol=1e-5): """Assert that forward/inverse (along with jacobians) are inverses and finite. It is recommended to use x and y values that are very very close to the edge of the Bijector's domain. Args: bijector: A Bijector instance. x: np.array of values in the domain of bijector.forward. y: np.array of values in the domain of bijector.inverse. event_ndims: Integer describing the number of event dimensions this bijector operates on. eval_func: Function to evaluate any intermediate results. inverse_event_ndims: Integer describing the number of event dimensions for the bijector codomain. If None, then the value of `event_ndims` is used. atol: Absolute tolerance. rtol: Relative tolerance. Raises: AssertionError: If tests fail. """ if inverse_event_ndims is None: inverse_event_ndims = event_ndims # These are the incoming points, but people often create a crazy range of # values for which these end up being bad, especially in 16bit. assert_finite(x) assert_finite(y) f_x = bijector.forward(x) g_y = bijector.inverse(y) [ x_from_x, y_from_y, ildj_f_x, fldj_x, ildj_y, fldj_g_y, f_x_v, g_y_v, ] = eval_func([ bijector.inverse(f_x), bijector.forward(g_y), bijector.inverse_log_det_jacobian(f_x, event_ndims=inverse_event_ndims), bijector.forward_log_det_jacobian(x, event_ndims=event_ndims), bijector.inverse_log_det_jacobian(y, event_ndims=inverse_event_ndims), bijector.forward_log_det_jacobian(g_y, event_ndims=event_ndims), f_x, g_y, ]) assert_finite(x_from_x) assert_finite(y_from_y) assert_finite(ildj_f_x) assert_finite(fldj_x) assert_finite(ildj_y) assert_finite(fldj_g_y) assert_finite(f_x_v) assert_finite(g_y_v) np.testing.assert_allclose(x_from_x, x, atol=atol, rtol=rtol) np.testing.assert_allclose(y_from_y, y, atol=atol, rtol=rtol) np.testing.assert_allclose(-ildj_f_x, fldj_x, atol=atol, rtol=rtol) np.testing.assert_allclose(-ildj_y, fldj_g_y, atol=atol, rtol=rtol) def get_fldj_theoretical(bijector, x, event_ndims, inverse_event_ndims=None, input_to_unconstrained=None, output_to_unconstrained=None): """Numerically approximate the forward log det Jacobian of a bijector. We compute the Jacobian of the chain output_to_unconst_vec(bijector(inverse(input_to_unconst_vec))) so that we're working with a full rank matrix. We then adjust the resulting Jacobian for the unconstraining bijectors. Bijectors that constrain / unconstrain their inputs/outputs may not be testable with this method, since the composition above may reduce the test to something trivial. However, bijectors that map within constrained spaces should be fine. Args: bijector: the bijector whose Jacobian we wish to approximate x: the value for which we want to approximate the Jacobian. Must have rank at least `event_ndims`. event_ndims: number of dimensions in an event inverse_event_ndims: Integer describing the number of event dimensions for the bijector codomain. If None, then the value of `event_ndims` is used. input_to_unconstrained: bijector that maps the input to the above bijector to an unconstrained 1-D vector. If unspecified, flatten the input into a 1-D vector according to its event_ndims. output_to_unconstrained: bijector that maps the output of the above bijector to an unconstrained 1-D vector. If unspecified, flatten the input into a 1-D vector according to its event_ndims. Returns: fldj: A gradient-based evaluation of the log det Jacobian of `bijector.forward` at `x`. """ if inverse_event_ndims is None: inverse_event_ndims = event_ndims if input_to_unconstrained is None: input_to_unconstrained = reshape_bijector.Reshape( event_shape_in=x.shape[tensorshape_util.rank(x.shape) - event_ndims:], event_shape_out=[-1]) if output_to_unconstrained is None: f_x_shape = bijector.forward_event_shape(x.shape) output_to_unconstrained = reshape_bijector.Reshape( event_shape_in=f_x_shape[tensorshape_util.rank(f_x_shape) - inverse_event_ndims:], event_shape_out=[-1]) x = tf.convert_to_tensor(x) x_unconstrained = 1 * input_to_unconstrained.forward(x) # Collapse any batch dimensions (including scalar) to a single axis. batch_shape = x_unconstrained.shape[:-1] x_unconstrained = tf.reshape( x_unconstrained, [int(np.prod(batch_shape)), x_unconstrained.shape[-1]]) def f(x_unconstrained, batch_shape=batch_shape): # Unflatten any batch dimensions now under the tape. unflattened_x_unconstrained = tf.reshape( x_unconstrained, tensorshape_util.concatenate(batch_shape, x_unconstrained.shape[-1:])) f_x = bijector.forward(input_to_unconstrained.inverse( unflattened_x_unconstrained)) return f_x def f_unconstrained(x_unconstrained, batch_shape=batch_shape): f_x_unconstrained = output_to_unconstrained.forward( f(x_unconstrained, batch_shape=batch_shape)) # Flatten any batch dimensions to a single axis. return tf.reshape( f_x_unconstrained, [int(np.prod(batch_shape)), f_x_unconstrained.shape[-1]]) if JAX_MODE: f_unconstrained = functools.partial(f_unconstrained, batch_shape=[]) jacobian = batch_jacobian(f_unconstrained, x_unconstrained) jacobian = tf.reshape( jacobian, tensorshape_util.concatenate(batch_shape, jacobian.shape[-2:])) logging.vlog(1, 'Jacobian: %s', jacobian) log_det_jacobian = 0.5 * tf.linalg.slogdet( tf.matmul(jacobian, jacobian, adjoint_a=True)).log_abs_determinant input_correction = input_to_unconstrained.forward_log_det_jacobian( x, event_ndims=event_ndims) output_correction = output_to_unconstrained.forward_log_det_jacobian( f(x_unconstrained), event_ndims=inverse_event_ndims) return (log_det_jacobian + tf.cast(input_correction, log_det_jacobian.dtype) - tf.cast(output_correction, log_det_jacobian.dtype))
38.893491
87
0.71246
6525ee9bfbe1b4c253d4636c5f42f72dcf481413
442
py
Python
examples/multifunction.py
CuadrosNicolas/Python-Command-Function
6f9c050a57b2849823f31831186ee2d9bf4bb975
[ "MIT" ]
null
null
null
examples/multifunction.py
CuadrosNicolas/Python-Command-Function
6f9c050a57b2849823f31831186ee2d9bf4bb975
[ "MIT" ]
null
null
null
examples/multifunction.py
CuadrosNicolas/Python-Command-Function
6f9c050a57b2849823f31831186ee2d9bf4bb975
[ "MIT" ]
null
null
null
#examples/multifunction.py from autofunccli import cmdfusion cmd = cmdfusion("Test with multiple function.") @cmd.add def plus(a:int,b:int)->int: """ plus operation :param a: first number :param b: second number :return: a+b """ return a+b @cmd.add def minus(a:int,b:int)->int: """ minus operation :param a: first number :param b: second number :return: a-b """ return a-b out = cmd.main(__name__) if(out != None): print(out)
17
47
0.683258
5006ddadf1564198ee2071ff099e400c38be55d5
1,240
py
Python
examples/lpf-kafka.py
CAIDA/pytimeseries
eb1528b0593f55ab42885d831c05b0adb652e1f9
[ "BSD-2-Clause" ]
null
null
null
examples/lpf-kafka.py
CAIDA/pytimeseries
eb1528b0593f55ab42885d831c05b0adb652e1f9
[ "BSD-2-Clause" ]
1
2021-06-02T18:54:27.000Z
2021-06-03T13:06:19.000Z
examples/lpf-kafka.py
CAIDA/pytimeseries
eb1528b0593f55ab42885d831c05b0adb652e1f9
[ "BSD-2-Clause" ]
null
null
null
#!/usr/bin/env python """ Trivial sample code for writing InfluxDB LPF-formatted data into the hicube time series platform. This code will not work as-is (i.e., you need a kafka topic created), but should serve as a starting point for writing producers. See https://docs.influxdata.com/influxdb/v1.8/write_protocols/line_protocol_tutorial/ for information about LPF. """ import confluent_kafka KAFKA_TOPIC = "telegraf-production.changeme" KAFKA_BROKERS = "kafka.rogues.caida.org:9092" kp = confluent_kafka.Producer({"bootstrap.servers": KAFKA_BROKERS,}) # send some time series data in LPF kp.produce(KAFKA_TOPIC, "weather,location=us-midwest temperature=82 1465839830100400200") # NB: in production you will likely want to batch these up and send many newline-separated points # in each kafka message, like this: kp.produce(KAFKA_TOPIC, "weather,location=us-midwest temperature=82 1465839830100400200\n" "weather,location=us-midwest temperature=83 1465839830200400200\n" "weather,location=us-midwest temperature=84 1465839830300400200\n" "weather,location=us-midwest temperature=85 1465839830400400200\n") # ensure all pending messages are written kp.flush(10)
44.285714
118
0.755645
b1dac4e752179255ed7e2e3ace6ee1b569c48759
1,821
py
Python
deep-rl/lib/python2.7/site-packages/OpenGL/GL/SGIX/framezoom.py
ShujaKhalid/deep-rl
99c6ba6c3095d1bfdab81bd01395ced96bddd611
[ "MIT" ]
210
2016-04-09T14:26:00.000Z
2022-03-25T18:36:19.000Z
deep-rl/lib/python2.7/site-packages/OpenGL/GL/SGIX/framezoom.py
ShujaKhalid/deep-rl
99c6ba6c3095d1bfdab81bd01395ced96bddd611
[ "MIT" ]
72
2016-09-04T09:30:19.000Z
2022-03-27T17:06:53.000Z
deep-rl/lib/python2.7/site-packages/OpenGL/GL/SGIX/framezoom.py
ShujaKhalid/deep-rl
99c6ba6c3095d1bfdab81bd01395ced96bddd611
[ "MIT" ]
64
2016-04-09T14:26:49.000Z
2022-03-21T11:19:47.000Z
'''OpenGL extension SGIX.framezoom This module customises the behaviour of the OpenGL.raw.GL.SGIX.framezoom to provide a more Python-friendly API Overview (from the spec) This extension provides a additional way to rasterize geometric primitives and pixel rectangles. The techique is to reduce the number of pixels rasterized and (possibly) the number of depth and stencil operations performed per primitive. Each pixel is zoomed up and used to render an N x N block of screen pixels. The implementation is free to choose the number of stencil and z pixels that will correspond to each N x N block. This extension provides an opportunity to the implementation to perform expensive raster operations at a reduced resolution, increasing performance. Such operations may include texture-mapping, depth & stencil tests, etc. The hardware should be allowed to perform operations that it accelerates at full hardware speed. The visual result will be the same as if a scene were rendered into a small window, and then that buffer was copied and zoomed up into a large window. All OpenGL parameters that effect rasterization size will implicitly be multipled by N (this includes point size, line width, etc). The official definition of this extension is available here: http://www.opengl.org/registry/specs/SGIX/framezoom.txt ''' from OpenGL import platform, constant, arrays from OpenGL import extensions, wrapper import ctypes from OpenGL.raw.GL import _types, _glgets from OpenGL.raw.GL.SGIX.framezoom import * from OpenGL.raw.GL.SGIX.framezoom import _EXTENSION_NAME def glInitFramezoomSGIX(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME ) ### END AUTOGENERATED SECTION
38.744681
71
0.794069
859c81e5d6d1ddb79fbf4bb8c38fbcf0dcfa829a
9,052
py
Python
tasks/utils.py
fk-currenxie/datadog-agent
ff813a337367cd4559cc6edb6794ced266d55c61
[ "Apache-2.0" ]
null
null
null
tasks/utils.py
fk-currenxie/datadog-agent
ff813a337367cd4559cc6edb6794ced266d55c61
[ "Apache-2.0" ]
null
null
null
tasks/utils.py
fk-currenxie/datadog-agent
ff813a337367cd4559cc6edb6794ced266d55c61
[ "Apache-2.0" ]
null
null
null
""" Miscellaneous functions, no tasks here """ from __future__ import print_function import os import platform import re import sys import json from subprocess import check_output import invoke # constants ORG_PATH = "github.com/DataDog" REPO_PATH = "{}/datadog-agent".format(ORG_PATH) def bin_name(name, android=False): """ Generate platform dependent names for binaries """ if android: return "{}.aar".format(name) if sys.platform == 'win32': return "{}.exe".format(name) return name def get_gopath(ctx): gopath = os.environ.get("GOPATH") if not gopath: gopath = ctx.run("go env GOPATH", hide=True).stdout.strip() return gopath def get_multi_python_location(embedded_path=None, rtloader_root=None): if rtloader_root is None: rtloader_lib = "{}/lib".format(embedded_path) else: # if rtloader_root is specified we're working in dev mode from the rtloader folder rtloader_lib = "{}/rtloader".format(rtloader_root) rtloader_headers = "{}/include".format(rtloader_root or embedded_path) rtloader_common_headers = "{}/common".format(rtloader_root or embedded_path) return rtloader_lib, rtloader_headers, rtloader_common_headers def get_build_flags(ctx, static=False, prefix=None, embedded_path=None, rtloader_root=None, python_home_2=None, python_home_3=None, arch="x64"): """ Build the common value for both ldflags and gcflags, and return an env accordingly. We need to invoke external processes here so this function need the Context object. """ gcflags = "" ldflags = get_version_ldflags(ctx, prefix) env = {} if sys.platform == 'win32': env["CGO_LDFLAGS_ALLOW"] = "-Wl,--allow-multiple-definition" if embedded_path is None: # fall back to local dev path embedded_path = "{}/src/github.com/DataDog/datadog-agent/dev".format(get_gopath(ctx)) rtloader_lib, rtloader_headers, rtloader_common_headers = \ get_multi_python_location(embedded_path, rtloader_root) # setting python homes in the code if python_home_2: ldflags += "-X {}/pkg/collector/python.pythonHome2={} ".format(REPO_PATH, python_home_2) if python_home_3: ldflags += "-X {}/pkg/collector/python.pythonHome3={} ".format(REPO_PATH, python_home_3) # adding rtloader libs and headers to the env env['DYLD_LIBRARY_PATH'] = os.environ.get('DYLD_LIBRARY_PATH', '') + ":{}".format(rtloader_lib) # OSX env['LD_LIBRARY_PATH'] = os.environ.get('LD_LIBRARY_PATH', '') + ":{}".format(rtloader_lib) # linux env['CGO_LDFLAGS'] = os.environ.get('CGO_LDFLAGS', '') + " -L{}".format(rtloader_lib) env['CGO_CFLAGS'] = os.environ.get('CGO_CFLAGS', '') + " -w -I{} -I{}".format(rtloader_headers, rtloader_common_headers) # if `static` was passed ignore setting rpath, even if `embedded_path` was passed as well if static: ldflags += "-s -w -linkmode=external '-extldflags=-static' " else: ldflags += "-r {}/lib ".format(embedded_path) if os.environ.get("DELVE"): gcflags = "-N -l" if sys.platform == 'win32': # On windows, need to build with the extra argument -ldflags="-linkmode internal" # if you want to be able to use the delve debugger. ldflags += "-linkmode internal " elif os.environ.get("NO_GO_OPT"): gcflags = "-N -l" return ldflags, gcflags, env def get_payload_version(): """ Return the Agent payload version found in the Gopkg.toml file. """ current = {} # parse the TOML file line by line with open("Gopkg.lock") as toml: for line in toml.readlines(): # skip empty lines and comments if not line or line[0] == "#": continue # change the parser "state" when we find a [[projects]] section if "[[projects]]" in line: # see if the current section is what we're searching for if current.get("name") == "github.com/DataDog/agent-payload": return current.get("version") # if not, reset the "state" and proceed with the next line current = {} continue # search for an assignment, ignore subsequent `=` chars toks = line.split('=', 2) if len(toks) == 2: # strip whitespaces key = toks[0].strip() # strip whitespaces and quotes value = toks[-1].replace('"', '').strip() current[key] = value return "" def get_version_ldflags(ctx, prefix=None): """ Compute the version from the git tags, and set the appropriate compiler flags """ payload_v = get_payload_version() commit = get_git_commit() ldflags = "-X {}/pkg/version.Commit={} ".format(REPO_PATH, commit) ldflags += "-X {}/pkg/version.AgentVersion={} ".format(REPO_PATH, get_version(ctx, include_git=True, prefix=prefix)) ldflags += "-X {}/pkg/serializer.AgentPayloadVersion={} ".format(REPO_PATH, payload_v) return ldflags def get_git_commit(): """ Get the current commit """ return check_output(['git', 'rev-parse', '--short', 'HEAD']).decode('utf-8').strip() def get_go_version(): """ Get the version of Go used """ return check_output(['go', 'version']).decode('utf-8').strip() def get_root(): """ Get the root of the Go project """ return check_output(['git', 'rev-parse', '--show-toplevel']).decode('utf-8').strip() def get_git_branch_name(): """ Return the name of the current git branch """ return check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"]).decode('utf-8').strip() def query_version(ctx, git_sha_length=7, prefix=None): # The string that's passed in will look something like this: 6.0.0-beta.0-1-g4f19118 # if the tag is 6.0.0-beta.0, it has been one commit since the tag and that commit hash is g4f19118 cmd = "git describe --tags --candidates=50" if prefix and type(prefix) == str: cmd += " --match \"{}-*\"".format(prefix) else: cmd += " --match \"[0-9]*\"" if git_sha_length and type(git_sha_length) == int: cmd += " --abbrev={}".format(git_sha_length) described_version = ctx.run(cmd, hide=True).stdout.strip() # for the example above, 6.0.0-beta.0-1-g4f19118, this will be 1 commit_number_match = re.match(r"^.*-(?P<commit_number>\d+)-g[0-9a-f]+$", described_version) commit_number = 0 if commit_number_match: commit_number = int(commit_number_match.group('commit_number')) version_re = r"v?(?P<version>\d+\.\d+\.\d+)(?:(?:-|\.)(?P<pre>[0-9A-Za-z.-]+))?" if prefix and type(prefix) == str: version_re = r"^(?:{}-)?".format(prefix) + version_re else: version_re = r"^" + version_re if commit_number == 0: version_re += r"(?P<git_sha>)$" else: version_re += r"-\d+-g(?P<git_sha>[0-9a-f]+)$" version_match = re.match( version_re, described_version) if not version_match: raise Exception("Could not query valid version from tags of local git repository") # version: for the tag 6.0.0-beta.0, this will match 6.0.0 # pre: for the output, 6.0.0-beta.0-1-g4f19118, this will match beta.0 # if there have been no commits since, it will be just 6.0.0-beta.0, # and it will match beta.0 # git_sha: for the output, 6.0.0-beta.0-1-g4f19118, this will match g4f19118 version, pre, git_sha = version_match.group('version', 'pre', 'git_sha') return version, pre, commit_number, git_sha def get_version(ctx, include_git=False, url_safe=False, git_sha_length=7, prefix=None): # we only need the git info for the non omnibus builds, omnibus includes all this information by default version = "" version, pre, commits_since_version, git_sha = query_version(ctx, git_sha_length, prefix) if pre: version = "{0}-{1}".format(version, pre) if commits_since_version and include_git: if url_safe: version = "{0}.git.{1}.{2}".format(version, commits_since_version,git_sha) else: version = "{0}+git.{1}.{2}".format(version, commits_since_version,git_sha) # version could be unicode as it comes from `query_version` return str(version) def get_version_numeric_only(ctx): version, _, _, _ = query_version(ctx) return version def load_release_versions(ctx, target_version): with open("release.json", "r") as f: versions = json.load(f) if target_version in versions: # windows runners don't accepts anything else than strings in the # environment when running a subprocess. return {str(k):str(v) for k, v in versions[target_version].items()} raise Exception("Could not find '{}' version in release.json".format(target_version))
36.796748
120
0.631242
3ab43488cb4ac2fd7b49b3a681cf9e8bbad59e43
8,231
py
Python
tree_generator.py
elfnor/spacetree-sverchok
7ba7128478db1f93e32ac2e0b4e5088745babb62
[ "CC0-1.0" ]
15
2016-09-13T10:48:59.000Z
2021-04-10T22:42:04.000Z
tree_generator.py
elfnor/spacetree-sverchok
7ba7128478db1f93e32ac2e0b4e5088745babb62
[ "CC0-1.0" ]
1
2016-09-26T11:58:36.000Z
2016-09-29T14:06:28.000Z
tree_generator.py
elfnor/spacetree-sverchok
7ba7128478db1f93e32ac2e0b4e5088745babb62
[ "CC0-1.0" ]
3
2017-01-25T23:17:50.000Z
2020-06-26T15:28:53.000Z
""" in maximum branches s d=100 n=2 in_sockets = [ ['s', 'maximum branches', npoints], ['s', 'branch length', dist], ['s', 'minimum distance', min_dist], ['s', 'maximum distance', max_dist], ['s', 'tip radius', tip_radius], ['v', 'tropism', trop], ['v', 'End Vertices', verts_in], ['v', 'Start Vertices', verts_start] ] import numpy as np import time from mathutils import Vector, Matrix from sverchok.data_structure import Matrix_listing def closest_np2(xyz1, xyz2): x2 = np.subtract.outer(xyz2[:,0], xyz1[:,0]) y2 = np.subtract.outer(xyz2[:,1], xyz1[:,1]) z2 = np.subtract.outer(xyz2[:,2], xyz1[:,2]) d2 = np.sum((x2**2, y2**2, z2**2), axis=0) ci = d2.argmin(axis=1) column_i = range(d2.shape[0]) dout = np.sqrt(d2[column_i, ci]) v = np.vstack((x2[column_i, ci], y2[column_i, ci], z2[column_i, ci])) return dout, ci, v.T class SCA: def __init__(self, d=0.3, NBP=2000, KILLDIST=5, INFLUENCE=15, endpoints=[], TROPISM=0.0, max_time=1.0, startpoints=[]): self.killdistance = KILLDIST self.branchlength = d self.maxiterations = NBP self.tropism = np.array(TROPISM) self.influence = INFLUENCE if INFLUENCE > 0 else 1e16 self.max_time = max_time if len(startpoints) > 0: self.bpalln = np.array(startpoints) else: self.bpalln = np.array([[0, 0, 0]]) self.bpp = [None] * self.bpalln.shape[0] self.bpc = [0] * self.bpalln.shape[0] self.bpg = [0] * self.bpalln.shape[0] self.epn = np.array(endpoints) d, ci, v = closest_np2(self.bpalln, self.epn) self.epbn = ci self.epdn = d self.epvn = v / self.epdn.reshape((-1, 1)) self.epbn[self.epdn >= self.influence] = -2 def addBranchPoint(self, bpn, pi, generation): self.bpalln = np.append(self.bpalln, [bpn], axis=0) self.bpp.append(pi) self.bpc.append(0) #self.bpg.append(generation + 1) self.bpg = np.append(self.bpg, [generation+1]) self.bpc[pi] += 1 bi = self.bpalln.shape[0] - 1 v = self.epn - bpn d2 = (v**2).sum(axis=1) index = (self.epbn != -1) & (d2 < self.epdn**2) & (d2 > self.killdistance**2) d = np.sqrt(d2[index]) self.epvn[index] = v[index, :] / d.reshape((-1,1)) self.epdn[index] = d index2 = (index & (d2 < self.influence**2)) self.epbn[index2] = bi index3 = (index & (d2 >= self.influence**2)) self.epbn[index3] = -2 index4 = (self.epbn != -1) & (d2 < self.epdn**2) & (d2 <= self.killdistance**2) self.epbn[index4] = -1 if self.bpc[pi] > 1: # a branch point with two children will not grow any new branches ... index_e = (self.epbn == pi) index_b = (np.array(self.bpc) <= 1) d, c, v = closest_np2(self.bpalln[index_b], self.epn[index_e]) # this turns c indixes into self.bpalln[index_b] into u indices into self.bpalln #needs better variable names t = np.arange(self.bpalln.shape[0])[index_b] u = t[c] # set points not within influence distance to -2 so they will be # ignored in growBranches u[d >= self.influence] = -2 self.epdn[index_e] = d self.epbn[index_e] = u self.epvn[index_e] = v / d.reshape((-1,1)) def growBranches(self, generation): index = self.epbn >= 0 epbn = self.epbn[index] bis = np.unique(epbn) v_sums = np.empty((bis.shape[0], 3)) for col in range(3): v_sums[:, col] = np.bincount(epbn, weights=self.epvn[index, col])[bis] # d2 = (v_sums**2).sum(axis=1) # d = np.sqrt(d2) /self.branchlength # vd = v_sums / d.reshape((-1, 1)) n_hat = v_sums/(((v_sums**2).sum(axis=1))**0.5).reshape((-1,1)) n_tilde = (n_hat + self.tropism) n_tilde = n_tilde/(((n_tilde**2).sum(axis=1))**0.5).reshape((-1,1)) newbps = self.bpalln[bis] + n_tilde * self.branchlength newbpps = bis for newbp, newbpp in zip(newbps, newbpps): self.addBranchPoint(newbp, newbpp, generation) def iterate(self): t0 = time.time() for i in range(self.maxiterations): nbp = self.bpalln.shape[0] self.growBranches(i) if self.bpalln.shape[0] == nbp: return if (time.time() - t0) > self.max_time: print('SCA timed out') return return def bp_verts_edges_n(self): """ returns branchpoints verts as a list of positions and edges as index to connect the branch points and leaves matrices """ verts = [] edges = [] ends = [] ends_inds = [] for i, b in enumerate(self.bpalln): bp_parent = self.bpp[i] verts.append(list(b)) if bp_parent != None: edges.append((bp_parent, i)) if self.bpc[i] == 0: ends.append(True) ends_inds.append(i) else: ends.append(False) process = ends_inds # branch radii br = [int(t) for t in ends] finished = [] while len(process) > 0: process.sort() i = process.pop() finished.append(i) p = self.bpp[i] if p != None: br[p] = br[p] + br[i] if p not in process: if p not in finished: process.insert(0, p) mats= [] for edge in edges: if ends[edge[1]]: #calculate leaf directions #end will always be edge[1] v0 = Vector(verts[edge[0]]) v1 = Vector(verts[edge[1]]) dir1 = (v1 - v0).normalized() dir2 = (dir1.cross(Vector((0.0, 0.0, 1.0)))).normalized() dir3 = -(dir1.cross(dir2)).normalized() m = Matrix.Identity(4) m[0][0:3] = dir1 m[1][0:3] = dir2 m[2][0:3] = dir3 m[3][0:3] = v1 m.transpose() mats.append(m) mats_out = Matrix_listing(mats) return verts, edges, ends, br, mats_out def sv_main(npoints=100 , dist=0.05, min_dist=0.05, max_dist=2.0, tip_radius=0.01, trop=[], verts_in=[], verts_start=[]): in_sockets = [ ['s', 'maximum branches', npoints], ['s', 'branch length', dist], ['s', 'minimum distance', min_dist], ['s', 'maximum distance', max_dist], ['s', 'tip radius', tip_radius], ['v', 'tropism', trop], ['v', 'End Vertices', verts_in], ['v', 'Start Vertices', verts_start] ] verts_out = [] edges_out = [] rad_out = [] ends_out = [] mats_out = [] if not verts_start: verts_start = [[]] if not trop: trop = [0., 0., 0.] if verts_in : sca = SCA(NBP = npoints, d=dist, KILLDIST=min_dist, INFLUENCE=max_dist, TROPISM=trop[0], endpoints=verts_in[0], startpoints = verts_start[0]) sca.iterate() verts_out, edges_out, ends_out, br, mats_out = sca.bp_verts_edges_n() rad_out = [tip_radius*b**0.5 for b in br] out_sockets = [ ['v', 'Vertices', [verts_out]], ['s', 'Edges', [edges_out]], ['s', 'Branch radii', [rad_out]], ['s', 'Ends mask', [ends_out]], ['m', 'Leaf matrices', mats_out], ] return in_sockets, out_sockets
34.295833
121
0.486697
58aa2d559140a48aa6b78946a8ad76edd1dfd6c4
6,239
py
Python
updown/data/proto_batch_sampler.py
elipugh/nocaps-meta
c8bd3c32c8d223e0ea5457159fb0637d2cdc8116
[ "MIT" ]
1
2021-08-15T14:03:09.000Z
2021-08-15T14:03:09.000Z
updown/data/proto_batch_sampler.py
elipugh/nocaps-meta
c8bd3c32c8d223e0ea5457159fb0637d2cdc8116
[ "MIT" ]
3
2021-09-08T02:38:41.000Z
2022-03-12T00:50:53.000Z
updown/data/proto_batch_sampler.py
elipugh/nocaps-meta
c8bd3c32c8d223e0ea5457159fb0637d2cdc8116
[ "MIT" ]
null
null
null
# coding=utf-8 import numpy as np import torch from torch.utils.data import Dataset from allennlp.data import Vocabulary from updown.config import Config from updown.data.readers import CocoCaptionsReader, ConstraintBoxesReader, ImageFeaturesReader from updown.utils.constraints import ConstraintFilter, FiniteStateMachineBuilder class PrototypicalBatchSampler(Dataset): r''' PrototypicalBatchSampler: yield a batch of indexes at each iteration. Indexes are calculated by keeping in account 'classes_per_it' and 'num_samples', In fact at every iteration the batch indexes will refer to 'num_support' + 'num_query' samples for 'classes_per_it' random classes. __len__ returns the number of episodes per epoch (same as 'self.iterations'). ''' def __init__(self, vocabulary, captions_jsonpath, image_features_h5path, classes_per_it, num_samples, iterations, max_caption_length=20, in_memory=False): ''' Initialize the PrototypicalBatchSampler object Args: - labels: an iterable containing all the labels for the current dataset samples indexes will be infered from this iterable. - classes_per_it: number of random classes for each iteration - num_samples: number of samples for each iteration for each class (support + query) - iterations: number of iterations (episodes) per epoch ''' super(PrototypicalBatchSampler, self).__init__() self.vocabulary = vocabulary self._image_features_reader = ImageFeaturesReader(image_features_h5path, in_memory) self._captions_reader = CocoCaptionsReader(captions_jsonpath) self._max_caption_length = max_caption_length self.classes_per_it = classes_per_it self.sample_per_class = num_samples self.iterations = iterations self.classes, self.counts = np.unique(self.labels, return_counts=True) self.classes = torch.LongTensor(self.classes) # create a matrix, indexes, of dim: classes X max(elements per class) # fill it with nans # for every class c, fill the relative row with the indices samples belonging to c # in numel_per_class we store the number of samples for each class/row self.idxs = range(len(self.labels)) self.indexes = np.empty((len(self.classes), max(self.counts)), dtype=int) * np.nan self.indexes = torch.Tensor(self.indexes) self.numel_per_class = torch.zeros_like(self.classes) for idx, label in enumerate(self.labels): label_idx = np.argwhere(self.classes == label).item() self.indexes[label_idx, np.where(np.isnan(self.indexes[label_idx]))[0][0]] = idx self.numel_per_class[label_idx] += 1 @classmethod def from_config(cls, config: Config, **kwargs): r"""Instantiate this class directly from a :class:`~updown.config.Config`.""" _C = config vocabulary = kwargs.pop("vocabulary") return cls( vocabulary=vocabulary, captions_jsonpath=_C.DATA.TRAIN_CAPTIONS, image_features_h5path=_C.DATA.TRAIN_FEATURES, classes_per_it=_C.DATA.CLASSES_PER_IT, num_samples=_C.DATA.NUM_SAMPLES, iterations=_C.DATA.ITERATIONS, max_caption_length=_C.DATA.MAX_CAPTION_LENGTH, in_memory=kwargs.pop("in_memory"), ) ############################################################################################### ## To Remove ## ############### def __iter__(self): ''' yield a batch of indexes ''' spc = self.sample_per_class cpi = self.classes_per_it for it in range(self.iterations): batch_size = spc * cpi batch = torch.LongTensor(batch_size) c_idxs = torch.randperm(len(self.classes))[:cpi] for i, c in enumerate(self.classes[c_idxs]): s = slice(i * spc, (i + 1) * spc) # FIXME when torch.argwhere will exists label_idx = torch.arange(len(self.classes)).long()[self.classes == c].item() sample_idxs = torch.randperm(self.numel_per_class[label_idx])[:spc] batch[s] = self.indexes[label_idx][sample_idxs] batch = batch[torch.randperm(len(batch))] yield batch ############################################################################################### def __len__(self): # Number of training examples are number of captions, not number of images. return len(self._captions_reader) def __getitem__(self, index: int) -> TrainingInstance: image_id, caption = self._captions_reader[index] image_features = self._image_features_reader[image_id] # Tokenize caption. caption_tokens: List[int] = [self._vocabulary.get_token_index(c) for c in caption] # Pad upto max_caption_length. caption_tokens = caption_tokens[: self._max_caption_length] caption_tokens.extend( [self._vocabulary.get_token_index("@@UNKNOWN@@")] * (self._max_caption_length - len(caption_tokens)) ) item: TrainingInstance = { "image_id": image_id, "image_features": image_features, "caption_tokens": caption_tokens, } return item def collate_fn(self, batch_list: List[TrainingInstance]) -> TrainingBatch: # Convert lists of ``image_id``s and ``caption_tokens``s as tensors. image_id = torch.tensor([instance["image_id"] for instance in batch_list]).long() caption_tokens = torch.tensor( [instance["caption_tokens"] for instance in batch_list] ).long() # Pad adaptive image features in the batch. image_features = torch.from_numpy( _collate_image_features([instance["image_features"] for instance in batch_list]) ) batch: TrainingBatch = { "image_id": image_id, "image_features": image_features, "caption_tokens": caption_tokens, } return batch
40.512987
99
0.626863
f5ecd1d49fb65af07605e8133045937cd0758e10
4,847
py
Python
torchwisdom/vision/datasets/datasets.py
abbiyanaila/torchwisdom
56dc95ebca3f6861c7009cb4fa0c034e260236b1
[ "MIT" ]
1
2019-04-29T12:35:07.000Z
2019-04-29T12:35:07.000Z
torchwisdom/vision/datasets/datasets.py
abbiyanaila/torchwisdom
56dc95ebca3f6861c7009cb4fa0c034e260236b1
[ "MIT" ]
null
null
null
torchwisdom/vision/datasets/datasets.py
abbiyanaila/torchwisdom
56dc95ebca3f6861c7009cb4fa0c034e260236b1
[ "MIT" ]
null
null
null
import os import random import pathlib from bisect import insort_right from collections import defaultdict import torch.utils.data as data import PIL import PIL.Image from torchwisdom.vision.transforms import pair as ptransforms class SiamesePairDataset(data.Dataset): def __init__(self, root, ext='jpg', transform=None, pair_transform=None, target_transform=None): super(SiamesePairDataset, self).__init__() self.transform = transform self.pair_transform = pair_transform self.target_transform = target_transform self.root = root self.base_path = pathlib.Path(root) self.files = sorted(list(self.base_path.glob("*/*." + ext))) self.files_map = self._files_mapping() self.pair_files = self._pair_files() def __len__(self): return len(self.pair_files) def __getitem__(self, idx): (imp1, imp2), sim = self.pair_files[idx] im1 = PIL.Image.open(imp1) im2 = PIL.Image.open(imp2) if self.transform: im1 = self.transform(im1) im2 = self.transform(im2) if self.pair_transform: im1, im2 = self.pair_transform(im1, im2) if self.target_transform: sim = self.target_transform(sim) return im1, im2, sim def _files_mapping(self): dct = defaultdict(list) for f in self.files: dirname = f.parent.name filename = f.name insort_right(dct[dirname], filename) return dct def _similar_pair(self): fmap = self.files_map atp = defaultdict(list) for _dir in fmap.keys(): n = len(fmap[_dir]) for i in range(n): for j in range(n): fp = os.path.join(_dir, fmap[_dir][i]) fo = os.path.join(_dir, fmap[_dir][j]) atp[_dir].append(((fp,fo),0)) return atp def _len_similar_pair(self): spair = self._similar_pair() return {key: len(spair[key]) for key in spair} def _diff_pair_dircomp(self): fmap = self.files_map return [(_class, list(filter(lambda other_class: other_class is not _class, fmap))) for _class in fmap] def _different_pair(self): fmap = self.files_map pair_sampled = defaultdict(list) pair_dircomp = self._diff_pair_dircomp() len_spair = self._len_similar_pair() for idx, (kp, kvo) in enumerate(pair_dircomp): val_pri = fmap[kp] num_sample = len(val_pri) // 4 if len(val_pri) >= 4 else len(val_pri) for vp in val_pri: # get filename file primary fp = os.path.join(kp, vp) for ko in kvo: vov = fmap[ko] pair = [] for vo in vov: fo = os.path.join(ko, vo) pair.append(((fp, fo), 1)) if len(pair)>num_sample: mout = random.sample(pair, num_sample) else: mout = pair pair_sampled[kp].append(mout) for key in pair_sampled.keys(): val = pair_sampled[key] num_sample = len_spair[key] tmp_val = [] for va in val: for v in va: tmp_val.append(v) if len(tmp_val) > num_sample: pair_sampled[key] = random.sample(tmp_val, num_sample) else: pair_sampled[key] = tmp_val return pair_sampled def _pair_files(self): fmap = self.files_map base_path = self.root sim_pair = self._similar_pair() diff_pair = self._different_pair() files_list = [] for key in fmap.keys(): spair = sim_pair[key] dpair = diff_pair[key] n = len(spair) for i in range(n): spair_p = os.path.join(base_path, spair[i][0][0]) spair_o = os.path.join(base_path, spair[i][0][1]) spair[i] = ((spair_p, spair_o), 0) dpair_p = os.path.join(base_path, dpair[i][0][0]) dpair_o = os.path.join(base_path, dpair[i][0][1]) dpair[i] = ((dpair_p, dpair_o), 1) files_list.append(spair[i]) files_list.append(dpair[i]) return files_list if __name__ == '__main__': train_tmft = ptransforms.PairCompose([ ptransforms.PairResize((220)), ptransforms.PairRandomRotation(20), ptransforms.PairToTensor(), ]) root = '/data/att_faces_new/valid' sd = SiamesePairDataset(root, ext="pgm", pair_transform=train_tmft) # loader = data.DataLoader(sd, batch_size=32, shuffle=True) print(sd.__getitem__(0))
33.427586
111
0.557871
fb2885ae5da226182dccb3ebd15533bd943d0078
95
py
Python
estimation/apps.py
ahmadsyafrudin/estimation-test
25b0b80065c8a0c0ba1a1a3b019b522d81501afa
[ "MIT" ]
null
null
null
estimation/apps.py
ahmadsyafrudin/estimation-test
25b0b80065c8a0c0ba1a1a3b019b522d81501afa
[ "MIT" ]
8
2020-02-12T00:12:47.000Z
2021-09-22T18:01:47.000Z
estimation/apps.py
ahmadsyafrudin/estimation-test
25b0b80065c8a0c0ba1a1a3b019b522d81501afa
[ "MIT" ]
null
null
null
from django.apps import AppConfig class EstimationConfig(AppConfig): name = 'estimation'
15.833333
34
0.768421
135b00dbbc56a70158b4f16a50891fc8f32b9c33
6,341
py
Python
backend/server.py
AMAI-GmbH/label-studio
8c7ec9e81ae1082a47953c143c1535c881c175d7
[ "Apache-2.0" ]
3
2020-11-08T16:56:21.000Z
2021-05-24T06:20:16.000Z
backend/server.py
AMAI-GmbH/label-studio
8c7ec9e81ae1082a47953c143c1535c881c175d7
[ "Apache-2.0" ]
null
null
null
backend/server.py
AMAI-GmbH/label-studio
8c7ec9e81ae1082a47953c143c1535c881c175d7
[ "Apache-2.0" ]
2
2021-05-24T06:20:18.000Z
2021-09-03T00:09:30.000Z
#!/usr/bin/env python from __future__ import print_function import os import flask import json # it MUST be included after flask! import db from flask import request, jsonify, make_response, Response from utils import exception_treatment, answer, log_config, log, config_line_stripped, load_config # init c = load_config() app = flask.Flask(__name__, static_url_path='') app.secret_key = 'A0Zrdqwf1AQWj12ajkhgFN]dddd/,?RfDWQQT' @app.template_filter('json') def json_filter(s): return json.dumps(s) @app.before_first_request def app_init(): pass @app.route('/static/editor/<path:path>') def send_editor(path): """ Static for label tool js and css """ return flask.send_from_directory(c['editor']['build_path'], path) @app.route('/static/media/<path:path>') def send_media(path): """ Static for label tool js and css """ return flask.send_from_directory(c['editor']['build_path'] + '/media', path) @app.route('/static/<path:path>') def send_static(path): """ Static serving """ return flask.send_from_directory('static', path) @app.route('/logs') def send_log(): """ Log access via web """ logfile = log_config['handlers']['file']['filename'] return Response(open(logfile).read(), mimetype='text/plain') @app.route('/') def index(): """ Main page: index.html """ global c # load config at each page reload (for fast changing of config/input_path/output_path) c = load_config() # find editor files to include in html editor_dir = c['editor']['build_path'] editor_js_dir = os.path.join(editor_dir, 'js') editor_js = ['/static/editor/js/' + f for f in os.listdir(editor_js_dir) if f.endswith('.js')] editor_css_dir = os.path.join(editor_dir, 'css') editor_css = ['/static/editor/css/' + f for f in os.listdir(editor_css_dir) if f.endswith('.css')] # load editor config from XML label_config_line = config_line_stripped(open(c['label_config']).read()) # task data: load task or task with completions if it exists task_data = None task_id = request.args.get('task_id', None) if task_id is not None: task_data = db.get_completion(task_id) if task_data is None: task_data = db.get_task(task_id) return flask.render_template('index.html', config=c, label_config_line=label_config_line, editor_css=editor_css, editor_js=editor_js, task_id=task_id, task_data=task_data) @app.route('/tasks') def tasks_page(): """ Tasks and completions page: tasks.html """ global c c = load_config() label_config = open(c['label_config']).read() # load editor config from XML task_ids = db.get_tasks().keys() completed_at = db.get_completed_at(task_ids) # sort by completed time task_ids = sorted([(i, completed_at[i] if i in completed_at else '9') for i in task_ids], key=lambda x: x[1]) task_ids = [i[0] for i in task_ids] # take only id back return flask.render_template('tasks.html', config=c, label_config=label_config, task_ids=task_ids, completions=db.get_completions_ids(), completed_at=completed_at) @app.route('/api/projects/1/next/', methods=['GET']) @exception_treatment def api_generate_next_task(): """ Generate next task to label """ # try to find task is not presented in completions completions = db.get_completions_ids() for (task_id, task) in db.get_tasks().items(): if task_id not in completions: log.info(msg='New task for labeling', extra=task) return make_response(jsonify(task), 200) # no tasks found return make_response('', 404) @app.route('/api/projects/1/task_ids/', methods=['GET']) @exception_treatment def api_all_task_ids(): """ Get all tasks ids """ ids = sorted(db.get_task_ids()) return make_response(jsonify(ids), 200) @app.route('/api/tasks/<task_id>/', methods=['GET']) @exception_treatment def api_tasks(task_id): """ Get task by id """ # try to get task with completions first task_data = db.get_completion(task_id) task_data = db.get_task(task_id) if task_data is None else task_data return make_response(jsonify(task_data), 200) @app.route('/api/projects/1/completions_ids/', methods=['GET']) @exception_treatment def api_all_completion_ids(): """ Get all completion ids """ ids = db.get_completions_ids() return make_response(jsonify(ids), 200) @app.route('/api/tasks/<task_id>/completions/', methods=['POST', 'DELETE']) @exception_treatment def api_completions(task_id): """ Delete or save new completion to output_dir with the same name as task_id """ global c if request.method == 'POST': completion = request.json completion.pop('state', None) # remove editor state db.save_completion(task_id, completion) log.info(msg='Completion saved', extra={'task_id': task_id, 'output': request.json}) return answer(201, 'ok') elif request.method == 'DELETE': if c.get('allow_delete_completions', False): db.delete_completion(task_id) return answer(204, 'deleted') else: return answer(422, 'Completion removing is not allowed in server config') else: return answer(500, 'Incorrect request method') @app.route('/api/tasks/<task_id>/completions/<completion_id>', methods=['PATCH']) @exception_treatment def api_completion_rewrite(task_id, completion_id): """ Rewrite existing completion with patch. This is technical api call for editor testing only. It's used for Rewrite button in editor. """ global c completion = request.json assert task_id == completion_id, \ f'Task ID != Completion ID, {task_id} != {completion_id}' completion.pop('state', None) # remove editor state db.save_completion(task_id, completion) log.info(msg='Completion saved', extra={'task_id': task_id, 'output': request.json}) return answer(201, 'ok') @app.route('/api/projects/1/expert_instruction') @exception_treatment def api_instruction(): return make_response(c['instruction'], 200) if __name__ == "__main__": app.run(host='0.0.0.0', port=c['port'], debug=c['debug'])
31.083333
113
0.66898
6287695480428d75acf27d3b957e3ef1e513e63b
235
py
Python
lib/pyfrc/config.py
virtuald/pyfrc
f04a70fecc2897129e2f1318a97304e7a9202d31
[ "MIT" ]
null
null
null
lib/pyfrc/config.py
virtuald/pyfrc
f04a70fecc2897129e2f1318a97304e7a9202d31
[ "MIT" ]
null
null
null
lib/pyfrc/config.py
virtuald/pyfrc
f04a70fecc2897129e2f1318a97304e7a9202d31
[ "MIT" ]
null
null
null
# # Holds settings that can be checked # # Set to True if running in code coverage mode # -> Since pyfrc 2014.6.0 coverage_mode = False # Indicates how pyfrc was run: netsim/sim/upload, etc... # -> Since pyfrc 2014.6.0 mode = None
18.076923
56
0.697872
4a3e815fda391596d86a0fa1f4d07e596bc13678
2,080
py
Python
tests/test_api_extensions.py
tesselo/stac-pydantic
9a5a6534b9fe48b0106317e1a6fc5a09bf95a27b
[ "MIT" ]
14
2021-05-19T19:06:01.000Z
2022-03-24T11:41:10.000Z
tests/test_api_extensions.py
tesselo/stac-pydantic
9a5a6534b9fe48b0106317e1a6fc5a09bf95a27b
[ "MIT" ]
43
2020-05-20T23:42:30.000Z
2021-03-02T19:40:20.000Z
tests/test_api_extensions.py
tesselo/stac-pydantic
9a5a6534b9fe48b0106317e1a6fc5a09bf95a27b
[ "MIT" ]
7
2021-04-16T12:55:15.000Z
2022-03-01T19:09:25.000Z
from datetime import datetime import pytest from pydantic import ValidationError from shapely.geometry import Polygon, shape from stac_pydantic import Item from stac_pydantic.api.extensions.fields import FieldsExtension from stac_pydantic.api.search import Search def test_fields_filter(): fields = FieldsExtension( includes={"id", "geometry", "properties.foo"}, excludes={"properties.bar"} ) item = Item( id="test-fields-filter", geometry=Polygon.from_bounds(0, 0, 0, 0), properties={"datetime": datetime.utcnow(), "foo": "foo", "bar": "bar"}, assets={}, links=[], bbox=[0, 0, 0, 0], ) d = item.to_dict(**fields.filter) assert d.pop("id") == item.id assert d.pop("geometry") == item.geometry props = d.pop("properties") assert props["foo"] == "foo" assert not props.get("bar") assert not d def test_search_geometry_bbox(): search = Search(collections=["foo", "bar"], bbox=[0, 0, 1, 1]) geom1 = shape(search.spatial_filter) geom2 = Polygon.from_bounds(*search.bbox) assert (geom1.intersection(geom2).area / geom1.union(geom2).area) == 1.0 @pytest.mark.parametrize( "bbox", [ (100.0, 1.0, 105.0, 0.0), # ymin greater than ymax (100.0, 0.0, 95.0, 1.0), # xmin greater than xmax (100.0, 0.0, 5.0, 105.0, 1.0, 4.0), # min elev greater than max elev (-200.0, 0.0, 105.0, 1.0), # xmin is invalid WGS84 (100.0, -100, 105.0, 1.0), # ymin is invalid WGS84 (100.0, 0.0, 190.0, 1.0), # xmax is invalid WGS84 (100.0, 0.0, 190.0, 100.0), # ymax is invalid WGS84 (-200.0, 0.0, 0.0, 105.0, 1.0, 4.0), # xmin is invalid WGS84 (3d) (100.0, -100, 0.0, 105.0, 1.0, 4.0), # ymin is invalid WGS84 (3d) (100.0, 0.0, 0.0, 190.0, 1.0, 4.0), # xmax is invalid WGS84 (3d) (100.0, 0.0, 0.0, 190.0, 100.0, 4.0), # ymax is invalid WGS84 (3d) ], ) def test_search_invalid_bbox(bbox): with pytest.raises(ValidationError): Search(collections=["foo"], bbox=bbox)
33.548387
82
0.600481
9fe0d9faa3bc2e224fdc9a9ef215edd89e13d0cd
32,358
py
Python
skinematics/quat.py
stes/scikit-kinematics
1a4d7212c8fff93428cb1d56ac6d77faa32e6bc5
[ "BSD-3-Clause" ]
103
2016-04-14T14:06:37.000Z
2022-03-24T12:38:31.000Z
skinematics/quat.py
stes/scikit-kinematics
1a4d7212c8fff93428cb1d56ac6d77faa32e6bc5
[ "BSD-3-Clause" ]
42
2016-11-09T15:22:33.000Z
2021-09-06T09:17:46.000Z
skinematics/quat.py
stes/scikit-kinematics
1a4d7212c8fff93428cb1d56ac6d77faa32e6bc5
[ "BSD-3-Clause" ]
48
2016-05-23T07:54:23.000Z
2022-03-24T14:34:41.000Z
''' Functions for working with quaternions. Note that all the functions also work on arrays, and can deal with full quaternions as well as with quaternion vectors. A "Quaternion" class is defined, with - operator overloading for mult, div, and inv. - indexing ''' ''' author: Thomas Haslwanter date: Feb-2018 ''' import numpy as np import matplotlib.pyplot as plt from scipy import signal # The following construct is required since I want to run the module as a script # inside the skinematics-directory import os import sys file_dir = os.path.dirname(__file__) if file_dir not in sys.path: sys.path.insert(0, file_dir) import vector, rotmat #import deprecation #import warnings #warnings.simplefilter('always', DeprecationWarning) pi = np.pi class Quaternion(): '''Quaternion class, with multiplication, division, and inversion. A Quaternion can be created from vectors, rotation matrices, or from Fick-angles, Helmholtz-angles, or Euler angles (in deg). It provides * operator overloading for mult, div, and inv. * indexing * access to the data, in the attribute *values*. Parameters ---------- inData : ndarray Contains the data in one of the following formats: * vector : (3 x n) or (4 x n) array, containing the quaternion values * rotmat : array, shape (3,3) or (N,9) single rotation matrix, or matrix with rotation-matrix elements. * Fick : (3 x n) array, containing (psi, phi, theta) rotations about the (1,2,3) axes [deg] (Fick sequence) * Helmholtz : (3 x n) array, containing (psi, phi, theta) rotations about the (1,2,3) axes [deg] (Helmholtz sequence) * Euler : (3 x n) array, containing (alpha, beta, gamma) rotations about the (3,1,3) axes [deg] (Euler sequence) inType : string Specifies the type of the input and has to have one of the following values 'vector'[Default], 'rotmat', 'Fick', 'Helmholtz', 'Euler' Attributes ---------- values : (4 x n) array quaternion values Methods ------- inv() Inverse of the quaterion export(to='rotmat') Export to one of the following formats: 'rotmat', 'Euler', 'Fick', 'Helmholtz' Notes ----- .. math:: \\vec {q}_{Euler} = \\left[ {\\begin{array}{*{20}{c}} {\\cos \\frac{\\alpha }{2}*\\cos \\frac{\\beta }{2}*\\cos \\frac{\\gamma }{2} - \\sin \\frac{\\alpha }{2}\\cos \\frac{\\beta }{2}\\sin \\frac{\\gamma }{2}} \\\\ {\\cos \\frac{\\alpha }{2}*\\sin \\frac{\\beta }{2}*\\cos \\frac{\\gamma }{2} + \\sin \\frac{\\alpha }{2}\\sin \\frac{\\beta }{2}\\sin \\frac{\\gamma }{2}} \\\\ {\\cos \\frac{\\alpha }{2}*\\sin \\frac{\\beta }{2}*\\sin \\frac{\\gamma }{2} - \\sin \\frac{\\alpha }{2}\\sin \\frac{\\beta }{2}\\cos \\frac{\\gamma }{2}} \\\\ {\\cos \\frac{\\alpha }{2}*\\cos \\frac{\\beta }{2}*\\sin \\frac{\\gamma }{2} + \\sin \\frac{\\alpha }{2}\\cos \\frac{\\beta }{2}\\cos \\frac{\\gamma }{2}} \\end{array}} \\right] .. math:: \\vec {q}_{Fick} = \\left[ {\\begin{array}{*{20}{c}} {\\cos \\frac{\\psi }{2}*\\cos \\frac{\\phi }{2}*\\cos \\frac{\\theta }{2} + \\sin \\frac{\\psi }{2}\\sin \\frac{\\phi }{2}\\sin \\frac{\\theta }{2}} \\\\ {\\sin \\frac{\\psi }{2}*\\cos \\frac{\\phi }{2}*\\cos \\frac{\\theta }{2} - \\cos \\frac{\\psi }{2}\\sin \\frac{\\phi }{2}\\sin \\frac{\\theta }{2}} \\\\ {\\cos \\frac{\\psi }{2}*\\sin \\frac{\\phi }{2}*\\cos \\frac{\\theta }{2} + \\sin \\frac{\\psi }{2}\\cos \\frac{\\phi }{2}\\sin \\frac{\\theta }{2}} \\\\ {\\cos \\frac{\\psi }{2}*\\cos \\frac{\\phi }{2}*\\sin \\frac{\\theta }{2} - \\sin \\frac{\\psi }{2}\\sin \\frac{\\phi }{2}\\cos \\frac{\\theta }{2}} \\end{array}} \\right] .. math:: \\vec {q}_{Helmholtz} = \\left[ {\\begin{array}{*{20}{c}} {\\cos \\frac{\\psi }{2}*\\cos \\frac{\\phi }{2}*\\cos \\frac{\\theta }{2} - \\sin \\frac{\\psi }{2}\\sin \\frac{\\phi }{2}\\sin \\frac{\\theta }{2}} \\\\ {\\sin \\frac{\\psi }{2}*\\cos \\frac{\\phi }{2}*\\cos \\frac{\\theta }{2} + \\cos \\frac{\\psi }{2}\\sin \\frac{\\phi }{2}\\sin \\frac{\\theta }{2}} \\\\ {\\cos \\frac{\\psi }{2}*\\sin \\frac{\\phi }{2}*\\cos \\frac{\\theta }{2} + \\sin \\frac{\\psi }{2}\\cos \\frac{\\phi }{2}\\sin \\frac{\\theta }{2}} \\\\ {\\cos \\frac{\\psi }{2}*\\cos \\frac{\\phi }{2}*\\sin \\frac{\\theta }{2} - \\sin \\frac{\\psi }{2}\\sin \\frac{\\phi }{2}\\cos \\frac{\\theta }{2}} \\end{array}} \\right] Examples -------- >>> q = Quaternion(array([[0,0,0.1], [0,0,0.2], [0,0,0.5]])) >>> p = Quaternion(array([0,0,0.2])) >>> fick = Quaternion( array([[0,0,10], [0,10,10]]), 'Fick') >>> combined = p * q >>> divided = q / p >>> extracted = q[1:2] >>> len(q) >>> data = q.values >>> 2 >>> inv(q) ''' def __init__(self, inData, inType='vector'): '''Initialization''' if inType.lower() == 'vector': if isinstance(inData, np.ndarray) or isinstance(inData, list): self.values = unit_q(inData) elif isinstance(inData, Quaternion): self.values = inData.values else: raise TypeError('Quaternions can only be based on ndarray or Quaternions!') elif inType.lower() == 'rotmat': '''Conversion from rotation matrices to quaternions.''' self.values = rotmat2quat(inData) elif inType.lower() == 'euler': ''' Conversion from Euler angles to quaternions. (a,b,g) stands for (alpha, beta, gamma) ''' inData[inData<0] += 360 inData = np.deg2rad(inData/2) (ca, cb, cg) = np.cos(inData.T) (sa, sb, sg) = np.sin(inData.T) self.values = np.vstack( (ca*cb*cg - sa*cb*sg, ca*sb*cg + sa*sb*sg, ca*sb*sg - sa*sb*cg, ca*cb*sg + sa*cb*cg) ).T elif inType.lower() == 'fick': ''' Conversion from Fick angles to quaternions. (p,f,t) stands for (psi, phi, theta) ''' inData[inData<0] += 360 inData = np.deg2rad(inData/2) (cp, cf, ct) = np.cos(inData.T) (sp, sf, st) = np.sin(inData.T) self.values = np.vstack( (cp*cf*ct + sp*sf*st, sp*cf*ct - cp*sf*st, cp*sf*ct + sp*cf*st, cp*cf*st - sp*sf*ct) ).T elif inType.lower() == 'helmholtz': ''' Conversion from Helmholtz angles to quaternions. (p,f,t) stands for (psi, phi, theta) ''' inData[inData<0] += 360 inData = np.deg2rad(inData/2) (cp, cf, ct) = np.cos(inData.T) (sp, sf, st) = np.sin(inData.T) self.values = np.vstack( (cp*cf*ct - sp*sf*st, sp*cf*ct + cp*sf*st, cp*sf*ct + sp*cf*st, cp*cf*st - sp*sf*ct ) ).T def __len__(self): '''The "length" is given by the number of quaternions.''' return len(self.values) def __mul__(self, other): '''Operator overloading for multiplication.''' if isinstance(other, int) or isinstance(other, float): return Quaternion(self.values * other) else: return Quaternion(q_mult(self.values, other.values)) def __div__(self, other): '''Operator overloading for division.''' if isinstance(other, int) or isinstance(other, float): return Quaternion(self.values / other) else: return Quaternion(q_mult(self.values, q_inv(other.values))) def __truediv__(self, other): '''Operator overloading for division.''' if isinstance(other, int) or isinstance(other, float): return Quaternion(self.values / other) else: return Quaternion(q_mult(self.values, q_inv(other.values))) def __getitem__(self, select): return Quaternion(self.values[select]) def __setitem__(self, select, item): self.values[select] = unit_q(item) #def __delitem__(self, select): #np.delete(self.values, select, axis=0) def inv(self): '''Inverse of a quaternion.''' return Quaternion(q_inv(self.values)) def __repr__(self): return 'Quaternion ' + str(self.values) def export(self, to='rotmat'): ''' Conversion to other formats. May be slow for "Fick", "Helmholtz", and "Euler". Parameters ---------- to : string content of returned values * 'rotmat' : rotation matrices (default), each flattened to a 9-dim vector * 'Euler' : Euler angles * 'Fick' : Fick angles * 'Helmholtz' : Helmholtz angles * 'vector' : vector part of the quaternion Returns ------- ndarray, with the specified content Examples -------- >>> q = Quaternion([0,0.2,0.1]) >>> rm = q.export() >>> fick = q.export('Fick') ''' if to.lower() == 'rotmat' : return convert(self.values, 'rotmat') if to.lower() == 'vector' : return self.values[:,1:] if to.lower() == 'euler': Euler = np.zeros((len(self),3)) rm = self.export() if rm.shape == (3,3): rm = rm.reshape((1,9)) for ii in range(len(self)): Euler[ii,:] = rotmat.rotmat2Euler(rm[ii].reshape((3,3))) return Euler if to.lower() == 'fick': Fick = np.zeros((len(self),3)) rm = self.export() if rm.shape == (3,3): rm = rm.reshape((1,9)) for ii in range(len(self)): Fick[ii,:] = rotmat.rotmat2Fick(rm[ii].reshape((3,3))) return Fick if to.lower() == 'helmholtz': Helmholtz = np.zeros((len(self),3)) rm = self.export() if rm.shape == (3,3): rm = rm.reshape((1,9)) for ii in range(len(self)): Helmholtz[ii,:] = rotmat.rotmat2Helmholtz(rm[ii].reshape((3,3))) return Helmholtz def convert(quat, to='rotmat'): ''' Calculate the rotation matrix corresponding to the quaternion. If "inQuat" contains more than one quaternion, the matrix is flattened (to facilitate the work with rows of quaternions), and can be restored to matrix form by "reshaping" the resulting rows into a (3,3) shape. Parameters ---------- inQuat : array_like, shape ([3,4],) or (N,[3,4]) quaternions or quaternion vectors to : string Has to be one of the following: - rotmat : rotation matrix - Gibbs : Gibbs vector Returns ------- rotMat : corresponding rotation matrix/matrices (flattened) Notes ----- .. math:: {\\bf{R}} = \\left( {\\begin{array}{*{20}{c}} {q_0^2 + q_1^2 - q_2^2 - q_3^2}&{2({q_1}{q_2} - {q_0}{q_3})}&{2({q_1}{q_3} + {q_0}{q_2})}\\\\ {2({q_1}{q_2} + {q_0}{q_3})}&{q_0^2 - q_1^2 + q_2^2 - q_3^2}&{2({q_2}{q_3} - {q_0}{q_1})}\\\\ {2({q_1}{q_3} - {q_0}{q_2})}&{2({q_2}{q_3} + {q_0}{q_1})}&{q_0^2 - q_1^2 - q_2^2 + q_3^2} \\\\ \\end{array}} \\right) More info under http://en.wikipedia.org/wiki/Quaternion Examples -------- >>> r = quat.convert([0, 0, 0.1], to='rotmat') >>> r.shape (1, 9) >>> r.reshape((3,3)) array([[ 0.98 , -0.19899749, 0. ], [ 0.19899749, 0.98 , 0. ], [ 0. , 0. , 1. ]]) ''' if to == 'rotmat': q = unit_q(quat).T R = np.zeros((9, q.shape[1])) R[0] = q[0]**2 + q[1]**2 - q[2]**2 - q[3]**2 R[1] = 2*(q[1]*q[2] - q[0]*q[3]) R[2] = 2*(q[1]*q[3] + q[0]*q[2]) R[3] = 2*(q[1]*q[2] + q[0]*q[3]) R[4] = q[0]**2 - q[1]**2 + q[2]**2 - q[3]**2 R[5] = 2*(q[2]*q[3] - q[0]*q[1]) R[6] = 2*(q[1]*q[3] - q[0]*q[2]) R[7] = 2*(q[2]*q[3] + q[0]*q[1]) R[8] = q[0]**2 - q[1]**2 - q[2]**2 + q[3]**2 if R.shape[1] == 1: return np.reshape(R, (3,3)) else: return R.T elif to == 'Gibbs': q_0 = q_scalar(quat) # cos(alpha/2) gibbs = (q_vector(quat).T / q_0).T # tan = sin/cos return gibbs def deg2quat(inDeg): ''' Convert axis-angles or plain degree into the corresponding quaternion values. Can be used with a plain number or with an axis angle. Parameters ---------- inDeg : float or (N,3) quaternion magnitude or quaternion vectors. Returns ------- outQuat : float or array (N,3) number or quaternion vector. Notes ----- .. math:: | \\vec{q} | = sin(\\theta/2) More info under http://en.wikipedia.org/wiki/Quaternion Examples -------- >>> quat.deg2quat(array([[10,20,30], [20,30,40]])) array([[ 0.08715574, 0.17364818, 0.25881905], [ 0.17364818, 0.25881905, 0.34202014]]) >>> quat.deg2quat(10) 0.087155742747658166 ''' deg = (inDeg+180)%360-180 return np.sin(0.5 * deg * pi/180) def q_conj(q): ''' Conjugate quaternion Parameters ---------- q: array_like, shape ([3,4],) or (N,[3/4]) quaternion or quaternion vectors Returns ------- qconj : conjugate quaternion(s) Examples -------- >>> quat.q_conj([0,0,0.1]) array([ 0.99498744, -0. , -0. , -0.1 ]) >>> quat.q_conj([[cos(0.1),0,0,sin(0.1)], >>> [cos(0.2), 0, sin(0.2), 0]]) array([[ 0.99500417, -0. , -0. , -0.09983342], [ 0.98006658, -0. , -0.19866933, -0. ]]) ''' q = np.atleast_2d(q) if q.shape[1]==3: q = unit_q(q) qConj = q * np.r_[1, -1,-1,-1] if q.shape[0]==1: qConj=qConj.ravel() return qConj def q_inv(q): ''' Quaternion inversion Parameters ---------- q: array_like, shape ([3,4],) or (N,[3/4]) quaternion or quaternion vectors Returns ------- qinv : inverse quaternion(s) Notes ----- .. math:: q^{-1} = \\frac{q_0 - \\vec{q}}{|q|^2} More info under http://en.wikipedia.org/wiki/Quaternion Examples -------- >>> quat.q_inv([0,0,0.1]) array([-0., -0., -0.1]) >>> quat.q_inv([[cos(0.1),0,0,sin(0.1)], >>> [cos(0.2),0,sin(0.2),0]]) array([[ 0.99500417, -0. , -0. , -0.09983342], [ 0.98006658, -0. , -0.19866933, -0. ]]) ''' q = np.atleast_2d(q) if q.shape[1]==3: return -q else: qLength = np.sum(q**2, 1) qConj = q * np.r_[1, -1,-1,-1] return (qConj.T / qLength).T def q_mult(p,q): ''' Quaternion multiplication: Calculates the product of two quaternions r = p * q If one of both of the quaterions have only three columns, the scalar component is calculated such that the length of the quaternion is one. The lengths of the quaternions have to match, or one of the two quaternions has to have the length one. If both p and q only have 3 components, the returned quaternion also only has 3 components (i.e. the quaternion vector) Parameters ---------- p,q : array_like, shape ([3,4],) or (N,[3,4]) quaternions or quaternion vectors Returns ------- r : quaternion or quaternion vector (if both p and q are contain quaternion vectors). Notes ----- .. math:: q \\circ p = \\sum\\limits_{i=0}^3 {q_i I_i} * \\sum\\limits_{j=0}^3 \\ {p_j I_j} = (q_0 p_0 - \\vec{q} \\cdot \\vec{p}) + (q_0 \\vec{p} + p_0 \\ \\vec{q} + \\vec{q} \\times \\vec{p}) \\cdot \\vec{I} More info under http://en.wikipedia.org/wiki/Quaternion Examples -------- >>> p = [cos(0.2), 0, 0, sin(0.2)] >>> q = [[0, 0, 0.1], >>> [0, 0.1, 0]] >>> r = quat.q_mult(p,q) ''' flag3D = False p = np.atleast_2d(p) q = np.atleast_2d(q) if p.shape[1]==3 & q.shape[1]==3: flag3D = True if len(p) != len(q): assert (len(p)==1 or len(q)==1), \ 'Both arguments in the quaternion multiplication must have the same number of rows, unless one has only one row.' p = unit_q(p).T q = unit_q(q).T if np.prod(np.shape(p)) > np.prod(np.shape(q)): r=np.zeros(np.shape(p)) else: r=np.zeros(np.shape(q)) r[0] = p[0]*q[0] - p[1]*q[1] - p[2]*q[2] - p[3]*q[3] r[1] = p[1]*q[0] + p[0]*q[1] + p[2]*q[3] - p[3]*q[2] r[2] = p[2]*q[0] + p[0]*q[2] + p[3]*q[1] - p[1]*q[3] r[3] = p[3]*q[0] + p[0]*q[3] + p[1]*q[2] - p[2]*q[1] if flag3D: # for rotations > 180 deg r[:,r[0]<0] = -r[:,r[0]<0] r = r[1:] r = r.T return r def quat2deg(inQuat): '''Calculate the axis-angle corresponding to a given quaternion. Parameters ---------- inQuat: float, or array_like, shape ([3/4],) or (N,[3/4]) quaternion(s) or quaternion vector(s) Returns ------- axAng : corresponding axis angle(s) float, or shape (3,) or (N,3) Notes ----- .. math:: | \\vec{q} | = sin(\\theta/2) More info under http://en.wikipedia.org/wiki/Quaternion Examples -------- >>> quat.quat2deg(0.1) array([ 11.47834095]) >>> quat.quat2deg([0.1, 0.1, 0]) array([ 11.47834095, 11.47834095, 0. ]) >>> quat.quat2deg([cos(0.1), 0, sin(0.1), 0]) array([ 0. , 11.4591559, 0. ]) ''' return 2 * np.arcsin(q_vector(inQuat)) * 180 / pi def quat2seq(quats, seq='nautical'): ''' This function takes a quaternion, and calculates the corresponding angles for sequenctial rotations. Parameters ---------- quats : ndarray, nx4 input quaternions seq : string Has to be one the following: - Euler ... Rz * Rx * Rz - Fick ... Rz * Ry * Rx - nautical ... same as "Fick" - Helmholtz ... Ry * Rz * Rx Returns ------- sequence : ndarray, nx3 corresponding angles [deg] same sequence as in the rotation matrices Examples -------- >>> quat.quat2seq([0,0,0.1]) array([[ 11.47834095, -0. , 0. ]]) >>> quaternions = [[0,0,0.1], [0,0.2,0]] skin.quat.quat2seq(quaternions) array([[ 11.47834095, -0. , 0. ], [ 0. , 23.07391807, 0. ]]) >>> skin.quat.quat2seq(quaternions, 'nautical') array([[ 11.47834095, -0. , 0. ], [ 0. , 23.07391807, 0. ]]) >>> skin.quat.quat2seq(quaternions, 'Euler') array([[ 11.47834095, 0. , 0. ], [ 90. , 23.07391807, -90. ]]) ''' # Ensure that it also works for a single quaternion quats = np.atleast_2d(quats) # If only the quaternion vector is entered, extend it to a full unit quaternion if quats.shape[1] == 3: quats = unit_q(quats) if seq =='Fick' or seq =='nautical': R_zx = 2 * (quats[:,1]*quats[:,3] - quats[:,0]*quats[:,2]) R_yx = 2 * (quats[:,1]*quats[:,2] + quats[:,0]*quats[:,3]) R_zy = 2 * (quats[:,2]*quats[:,3] + quats[:,0]*quats[:,1]) phi = -np.arcsin(R_zx) theta = np.arcsin(R_yx / np.cos(phi)) psi = np.arcsin(R_zy / np.cos(phi)) sequence = np.column_stack((theta, phi, psi)) elif seq == 'Helmholtz': R_yx = 2 * (quats[:,1]*quats[:,2] + quats[:,0]*quats[:,3]) R_zx = 2 * (quats[:,1]*quats[:,3] - quats[:,0]*quats[:,2]) R_yz = 2 * (quats[:,2]*quats[:,3] - quats[:,0]*quats[:,1]) theta = np.arcsin(R_yx) phi = -np.arcsin(R_zx / np.cos(theta)) psi = -np.arcsin(R_yz / np.cos(theta)) sequence = np.column_stack((phi, theta, psi)) elif seq == 'Euler': Rs = convert(quats, to='rotmat').reshape((-1,3,3)) beta = np.arccos(Rs[:,2,2]) # special handling for (beta == 0) bz = beta == 0 # there the gamma-values are set to zero, since alpha/gamma is degenerated alpha = np.nan * np.ones_like(beta) gamma = np.nan * np.ones_like(beta) alpha[bz] = np.arcsin(Rs[bz,1,0]) gamma[bz] = 0 alpha[~bz] = np.arctan2(Rs[~bz,0,2], Rs[~bz,1,2]) gamma[~bz] = np.arctan2(Rs[~bz,2,0], Rs[~bz,2,1]) sequence = np.column_stack((alpha, beta, gamma)) else: raise ValueError('Input parameter {0} not known'.format(seq)) return np.rad2deg(sequence) def q_vector(inQuat): ''' Extract the quaternion vector from a full quaternion. Parameters ---------- inQuat : array_like, shape ([3,4],) or (N,[3,4]) quaternions or quaternion vectors. Returns ------- vect : array, shape (3,) or (N,3) corresponding quaternion vectors Notes ----- More info under http://en.wikipedia.org/wiki/Quaternion Examples -------- >>> quat.q_vector([[np.cos(0.2), 0, 0, np.sin(0.2)],[cos(0.1), 0, np.sin(0.1), 0]]) array([[ 0. , 0. , 0.19866933], [ 0. , 0.09983342, 0. ]]) ''' inQuat = np.atleast_2d(inQuat) if inQuat.shape[1] == 4: vect = inQuat[:,1:] else: vect = inQuat if np.min(vect.shape)==1: vect = vect.ravel() return vect def q_scalar(inQuat): ''' Extract the quaternion scalar from a full quaternion. Parameters ---------- inQuat : array_like, shape ([3,4],) or (N,[3,4]) quaternions or quaternion vectors. Returns ------- vect : array, shape (1,) or (N,1) Corresponding quaternion scalar. If the input is only the quaternion-vector, the scalar part for a unit quaternion is calculated and returned. Notes ----- More info under http://en.wikipedia.org/wiki/Quaternion Examples -------- >>> quat.q_scalar([[np.cos(0.2), 0, 0, np.sin(0.2)],[np.cos(0.1), 0, np.sin(0.1), 0]]) array([ 0.98006658, 0.99500417]) ''' inQuat = np.atleast_2d(inQuat) if inQuat.shape[1] == 4: scalar = inQuat[:,0] else: scalar = np.sqrt(1-np.linalg.norm(inQuat, axis=1)) if np.min(scalar.shape)==1: scalar = scalar.ravel() return scalar def unit_q(inData): ''' Utility function, which turns a quaternion vector into a unit quaternion. If the input is already a full quaternion, the output equals the input. Parameters ---------- inData : array_like, shape (3,) or (N,3) quaternions or quaternion vectors Returns ------- quats : array, shape (4,) or (N,4) corresponding unit quaternions. Notes ----- More info under http://en.wikipedia.org/wiki/Quaternion Examples -------- >>> quats = array([[0,0, sin(0.1)],[0, sin(0.2), 0]]) >>> quat.unit_q(quats) array([[ 0.99500417, 0. , 0. , 0.09983342], [ 0.98006658, 0. , 0.19866933, 0. ]]) ''' inData = np.atleast_2d(inData) (m,n) = inData.shape if (n!=3)&(n!=4): raise ValueError('Quaternion must have 3 or 4 columns') if n == 3: qLength = 1-np.sum(inData**2,1) numLimit = 1e-12 # Check for numerical problems if np.min(qLength) < -numLimit: raise ValueError('Quaternion is too long!') else: # Correct for numerical problems qLength[qLength<0] = 0 outData = np.hstack((np.c_[np.sqrt(qLength)], inData)) else: outData = inData return outData def calc_quat(omega, q0, rate, CStype): ''' Take an angular velocity (in rad/s), and convert it into the corresponding orientation quaternion. Parameters ---------- omega : array, shape (3,) or (N,3) angular velocity [rad/s]. q0 : array (3,) vector-part of quaternion (!!) rate : float sampling rate (in [Hz]) CStype: string coordinate_system, space-fixed ("sf") or body_fixed ("bf") Returns ------- quats : array, shape (N,4) unit quaternion vectors. Notes ----- 1) The output has the same length as the input. As a consequence, the last velocity vector is ignored. 2) For angular velocity with respect to space ("sf"), the orientation is given by .. math:: q(t) = \\Delta q(t_n) \\circ \\Delta q(t_{n-1}) \\circ ... \\circ \\Delta q(t_2) \\circ \\Delta q(t_1) \\circ q(t_0) .. math:: \\Delta \\vec{q_i} = \\vec{n(t)}\\sin (\\frac{\\Delta \\phi (t_i)}{2}) = \\frac{\\vec \\omega (t_i)}{\\left| {\\vec \\omega (t_i)} \\right|}\\sin \\left( \\frac{\\left| {\\vec \\omega ({t_i})} \\right|\\Delta t}{2} \\right) 3) For angular velocity with respect to the body ("bf"), the sequence of quaternions is inverted. 4) Take care that you choose a high enough sampling rate! Examples -------- >>> v0 = np.r_[0., 0., 100.] * np.pi/180. >>> omega = np.tile(v0, (1000,1)) >>> rate = 100 >>> out = quat.calc_quat(omega, [0., 0., 0.], rate, 'sf') array([[ 1. , 0. , 0. , 0. ], [ 0.99996192, 0. , 0. , 0.00872654], [ 0.9998477 , 0. , 0. , 0.01745241], ..., [-0.74895572, 0. , 0. , 0.66262005], [-0.75470958, 0. , 0. , 0.65605903], [-0.76040597, 0. , 0. , 0.64944805]]) ''' omega_05 = np.atleast_2d(omega).copy() # The following is (approximately) the quaternion-equivalent of the trapezoidal integration (cumtrapz) if omega_05.shape[1]>1: omega_05[:-1] = 0.5*(omega_05[:-1] + omega_05[1:]) omega_t = np.sqrt(np.sum(omega_05**2, 1)) omega_nonZero = omega_t>0 # initialize the quaternion q_delta = np.zeros(omega_05.shape) q_pos = np.zeros((len(omega_05),4)) q_pos[0,:] = unit_q(q0) # magnitude of position steps dq_total = np.sin(omega_t[omega_nonZero]/(2.*rate)) q_delta[omega_nonZero,:] = omega_05[omega_nonZero,:] * np.tile(dq_total/omega_t[omega_nonZero], (3,1)).T for ii in range(len(omega_05)-1): q1 = unit_q(q_delta[ii,:]) q2 = q_pos[ii,:] if CStype == 'sf': qm = q_mult(q1,q2) elif CStype == 'bf': qm = q_mult(q2,q1) else: print('I don''t know this type of coordinate system!') q_pos[ii+1,:] = qm return q_pos def calc_angvel(q, rate=1, winSize=5, order=2): ''' Take a quaternion, and convert it into the corresponding angular velocity Parameters ---------- q : array, shape (N,[3,4]) unit quaternion vectors. rate : float sampling rate (in [Hz]) winSize : integer window size for the calculation of the velocity. Has to be odd. order : integer Order of polynomial used by savgol to calculate the first derivative Returns ------- angvel : array, shape (3,) or (N,3) angular velocity [rad/s]. Notes ----- The angular velocity is given by .. math:: \\omega = 2 * \\frac{dq}{dt} \\circ q^{-1} Examples -------- >>> rate = 1000 >>> t = np.arange(0,10,1/rate) >>> x = 0.1 * np.sin(t) >>> y = 0.2 * np.sin(t) >>> z = np.zeros_like(t) array([[ 0.20000029, 0.40000057, 0. ], [ 0.19999989, 0.39999978, 0. ], [ 0.19999951, 0.39999901, 0. ]]) ....... ''' if np.mod(winSize, 2) != 1: raise ValueError('Window size must be odd!') numCols = q.shape[1] if numCols < 3 or numCols > 4: raise TypeError('quaternions must have 3 or 4 columns') # This has to be done: otherwise q_mult will "complete" dq_dt to be a unit # quaternion, resulting in wrong value if numCols == 3: q = unit_q(q) dq_dt = signal.savgol_filter(q, window_length=winSize, polyorder=order, deriv=1, delta=1./rate, axis=0) angVel = 2 * q_mult(dq_dt, q_inv(q)) return angVel[:,1:] if __name__=='__main__': '''These are some simple tests to see if the functions produce the proper output. More extensive tests are found in tests/test_quat.py''' a = np.r_[np.cos(0.1), 0,0,np.sin(0.1)] b = np.r_[np.cos(0.2), 0,np.sin(0.2),0] seq = quat2seq(np.vstack((a,b)), seq='Euler') print(seq) ''' from skinematics.vector import rotate_vector v0 = np.r_[0., 0., 100.] * np.pi/180. vel = np.tile(v0, (1000,1)) rate = 100 out = calc_quat(vel, [0., 0., 0.], rate, 'sf') rate = 1000 t = np.arange(0,10,1./rate) x = 0.1 * np.sin(t) y = 0.2 * np.sin(t) z = np.zeros_like(t) q = np.column_stack( (x,y,z) ) vel = calc_angvel(q, rate, 5, 2) qReturn = vel2quat(vel, q[0], rate, 'sf' ) plt.plot(q) plt.plot(qReturn[:,1:],'--') plt.show() q = Quaternion(np.array([0,0,10]), 'Fick') print(q) rm = q.export(to='rotmat') print(rm) q2 = Quaternion(rm, inType='rotmat') print(q2) a = np.r_[np.cos(0.1), 0,0,np.sin(0.1)] b = np.r_[np.cos(0.1),0,np.sin(0.1), 0] c = np.vstack((a,b)) d = np.r_[np.sin(0.1), 0, 0] e = np.r_[2, 0, np.sin(0.1), 0] print(q_mult(a,a)) print(q_mult(a,b)) print(q_mult(c,c)) print(q_mult(c,a)) print(q_mult(d,d)) print('The inverse of {0} is {1}'.format(a, q_inv(a))) print('The inverse of {0} is {1}'.format(d, q_inv(d))) print('The inverse of {0} is {1}'.format(e, q_inv(e))) print(q_mult(e, q_inv(e))) print(q_vector(a)) print('{0} is {1} degree'.format(a, quat2deg(a))) print('{0} is {1} degree'.format(c, quat2deg(c))) print(quat2deg(0.2)) x = np.r_[1,0,0] vNull = np.r_[0,0,0] print(rotate_vector(x, a)) v0 = [0., 0., 100.] vel = np.tile(v0, (1000,1)) rate = 100 out = vel2quat(vel, [0., 0., 0.], rate, 'sf') print(out[-1:]) plt.plot(out[:,1:4]) plt.show() print(deg2quat(15)) print(deg2quat(quat2deg(a))) q = np.array([[0, 0, np.sin(0.1)], [0, np.sin(0.01), 0]]) rMat = convert(q, to='rotmat) print(rMat[1].reshape((3,3))) qNew = rotmat2quat(rMat) print(qNew) q = Quaternion(np.array([0,0,0.5])) p = Quaternion(np.array([[0,0,0.5], [0,0,0.1]])) r = Quaternion([0,0,0.5]) print(p*q) print(q*3) print(q*pi) print(q/p) print(q/5) Fick = p.export('Fick') Q_fick = q.export('Fick') import pprint pprint.pprint(Fick) pprint.pprint(np.rad2deg(Fick)) p = Quaternion(np.array([[0,0,0.5], [0,0,0.1], [0,0,0.1]])) p[1:] = [[0,0,0],[0,0,0.01]] print(p) '''
30.817143
231
0.496693
678fd4a46c18aafa3d1334f9886ba7858f83bfd8
2,137
py
Python
beastx/modules/rename.py
Digasi123percy/Beast-X
cf2c47db6af0c4afaa3b51b76ef7a1a2f0e0bc81
[ "MIT" ]
11
2021-11-07T12:04:20.000Z
2022-03-10T10:32:59.000Z
beastx/modules/rename.py
Digasi123percy/Beast-X
cf2c47db6af0c4afaa3b51b76ef7a1a2f0e0bc81
[ "MIT" ]
null
null
null
beastx/modules/rename.py
Digasi123percy/Beast-X
cf2c47db6af0c4afaa3b51b76ef7a1a2f0e0bc81
[ "MIT" ]
114
2021-11-07T13:11:19.000Z
2022-03-31T02:00:04.000Z
import os import time from datetime import datetime from . import * thumb_image_path = Config.TMP_DOWNLOAD_DIRECTORY + "/thumb_image.jpg" @beast.on(beastx_cmd(pattern="rename (.*)")) async def _(event): if event.fwd_from: return thumb = None if os.path.exists(thumb_image_path): thumb = thumb_image_path await event.edit("⚡️`Rename and upload in progress, please wait!`⚡️") input_str = event.pattern_match.group(1) if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) if event.reply_to_msg_id: start = datetime.now() end = datetime.now() file_name = input_str reply_message = await event.get_reply_message() to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY downloaded_file_name = os.path.join(to_download_directory, file_name) downloaded_file_name = await borg.download_media( reply_message, downloaded_file_name, ) ms_one = (end - start).seconds if os.path.exists(downloaded_file_name): time.time() await borg.send_file( event.chat_id, downloaded_file_name, force_document=True, supports_streaming=False, allow_cache=False, reply_to=event.message.id, thumb=thumb, ) end_two = datetime.now() os.remove(downloaded_file_name) ms_two = (end_two - end).seconds await event.edit( "Downloaded in {} seconds. Uploaded in {} seconds.".format( ms_one, ms_two ) ) else: await event.edit("File Not Found {}".format(input_str)) else: await event.edit("Syntax // .rename file.name as reply to a Telegram media") CMD_HELP.update( { "rename": "**Rename**\ \n\n**Syntax : **`.rename <reply to filet> <new name>`\ \n**Usage :** replyed file is renamed with new name." } )
32.876923
85
0.578849
8e4e4ae632546635235b06c61cf698c2b75a07ea
62
py
Python
main.py
realmgame/hellow
40efb09cca484e7b80e226e4c870d501259c3f05
[ "Unlicense" ]
null
null
null
main.py
realmgame/hellow
40efb09cca484e7b80e226e4c870d501259c3f05
[ "Unlicense" ]
null
null
null
main.py
realmgame/hellow
40efb09cca484e7b80e226e4c870d501259c3f05
[ "Unlicense" ]
null
null
null
def main(): print("this") return {'hello world'} main()
12.4
26
0.580645
5ef5fea088f13ee90d0b433e65917db68e48a12d
3,147
py
Python
Part 2 - Classification/Section 2 - K-Nearest Neighbors (K-NN)/KNearestNeighbors(knn).py
rudrajit1729/Machine-Learning-Codes-And-Templates
f36e92e9e103fa96549596e38be4c5fa29b2765d
[ "MIT" ]
4
2020-03-28T13:46:21.000Z
2020-12-12T07:24:26.000Z
Part 2 - Classification/Section 2 - K-Nearest Neighbors (K-NN)/KNearestNeighbors(knn).py
rudrajit1729/Machine-Learning-Codes-And-Templates
f36e92e9e103fa96549596e38be4c5fa29b2765d
[ "MIT" ]
null
null
null
Part 2 - Classification/Section 2 - K-Nearest Neighbors (K-NN)/KNearestNeighbors(knn).py
rudrajit1729/Machine-Learning-Codes-And-Templates
f36e92e9e103fa96549596e38be4c5fa29b2765d
[ "MIT" ]
1
2020-05-10T01:34:28.000Z
2020-05-10T01:34:28.000Z
# K-Nearest Neighbors # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv("Social_Network_Ads.csv") X = dataset.iloc[:, [2, 3]].values y = dataset.iloc[:, 4].values # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Fitting K-NN to the Training set from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2) classifier.fit(X_train, y_train) # Predicting the Test set results y_pred = classifier.predict(X_test) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) #Applying K-Fold Cross Validation from sklearn.model_selection import cross_val_score accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1) accuracy = round(accuracies.mean()*100,2) std = round(accuracies.std()*100,2) acc_range = [round(accuracy-std,2),round(accuracy+std,2)] print("Accuracy : ", accuracy) print("Accuracy range : ", acc_range) # Visualising the Training set results from matplotlib.colors import ListedColormap X_set, y_set = X_train, y_train X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('K-NN(Training set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show() # Visualising the Test set results from matplotlib.colors import ListedColormap X_set, y_set = X_test, y_test X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('K-NN(Test set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show()
39.835443
106
0.659358
4f92f044fd6b3c4c7045ee850cb9a6a633278070
19,470
py
Python
localization_service/venv/lib/python3.5/site-packages/matplotlib/tests/test_legend.py
vladbragoi/indoor_localization_system
b98d278cbd6a2ff8dcc093631eed0605e9e3a35f
[ "Apache-2.0" ]
null
null
null
localization_service/venv/lib/python3.5/site-packages/matplotlib/tests/test_legend.py
vladbragoi/indoor_localization_system
b98d278cbd6a2ff8dcc093631eed0605e9e3a35f
[ "Apache-2.0" ]
null
null
null
localization_service/venv/lib/python3.5/site-packages/matplotlib/tests/test_legend.py
vladbragoi/indoor_localization_system
b98d278cbd6a2ff8dcc093631eed0605e9e3a35f
[ "Apache-2.0" ]
null
null
null
import collections import inspect import platform from unittest import mock import numpy as np import pytest from matplotlib.testing.decorators import image_comparison import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.transforms as mtransforms import matplotlib.collections as mcollections from matplotlib.legend_handler import HandlerTuple import matplotlib.legend as mlegend from matplotlib.cbook.deprecation import MatplotlibDeprecationWarning def test_legend_ordereddict(): # smoketest that ordereddict inputs work... X = np.random.randn(10) Y = np.random.randn(10) labels = ['a'] * 5 + ['b'] * 5 colors = ['r'] * 5 + ['g'] * 5 fig, ax = plt.subplots() for x, y, label, color in zip(X, Y, labels, colors): ax.scatter(x, y, label=label, c=color) handles, labels = ax.get_legend_handles_labels() legend = collections.OrderedDict(zip(labels, handles)) ax.legend(legend.values(), legend.keys(), loc='center left', bbox_to_anchor=(1, .5)) @image_comparison(baseline_images=['legend_auto1'], remove_text=True) def test_legend_auto1(): 'Test automatic legend placement' fig = plt.figure() ax = fig.add_subplot(111) x = np.arange(100) ax.plot(x, 50 - x, 'o', label='y=1') ax.plot(x, x - 50, 'o', label='y=-1') ax.legend(loc='best') @image_comparison(baseline_images=['legend_auto2'], remove_text=True) def test_legend_auto2(): 'Test automatic legend placement' fig = plt.figure() ax = fig.add_subplot(111) x = np.arange(100) b1 = ax.bar(x, x, align='edge', color='m') b2 = ax.bar(x, x[::-1], align='edge', color='g') ax.legend([b1[0], b2[0]], ['up', 'down'], loc='best') @image_comparison(baseline_images=['legend_auto3']) def test_legend_auto3(): 'Test automatic legend placement' fig = plt.figure() ax = fig.add_subplot(111) x = [0.9, 0.1, 0.1, 0.9, 0.9, 0.5] y = [0.95, 0.95, 0.05, 0.05, 0.5, 0.5] ax.plot(x, y, 'o-', label='line') ax.set_xlim(0.0, 1.0) ax.set_ylim(0.0, 1.0) ax.legend(loc='best') @image_comparison(baseline_images=['legend_various_labels'], remove_text=True) def test_various_labels(): # tests all sorts of label types fig = plt.figure() ax = fig.add_subplot(121) ax.plot(np.arange(4), 'o', label=1) ax.plot(np.linspace(4, 4.1), 'o', label='Développés') ax.plot(np.arange(4, 1, -1), 'o', label='__nolegend__') ax.legend(numpoints=1, loc='best') @image_comparison(baseline_images=['legend_labels_first'], extensions=['png'], remove_text=True) def test_labels_first(): # test labels to left of markers fig = plt.figure() ax = fig.add_subplot(111) ax.plot(np.arange(10), '-o', label=1) ax.plot(np.ones(10)*5, ':x', label="x") ax.plot(np.arange(20, 10, -1), 'd', label="diamond") ax.legend(loc='best', markerfirst=False) @image_comparison(baseline_images=['legend_multiple_keys'], extensions=['png'], remove_text=True) def test_multiple_keys(): # test legend entries with multiple keys fig = plt.figure() ax = fig.add_subplot(111) p1, = ax.plot([1, 2, 3], '-o') p2, = ax.plot([2, 3, 4], '-x') p3, = ax.plot([3, 4, 5], '-d') ax.legend([(p1, p2), (p2, p1), p3], ['two keys', 'pad=0', 'one key'], numpoints=1, handler_map={(p1, p2): HandlerTuple(ndivide=None), (p2, p1): HandlerTuple(ndivide=None, pad=0)}) @image_comparison(baseline_images=['rgba_alpha'], tol={'aarch64': 0.02}.get(platform.machine(), 0.0), extensions=['png'], remove_text=True) def test_alpha_rgba(): import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) ax.plot(range(10), lw=5) leg = plt.legend(['Longlabel that will go away'], loc='center') leg.legendPatch.set_facecolor([1, 0, 0, 0.5]) @image_comparison(baseline_images=['rcparam_alpha'], tol={'aarch64': 0.02}.get(platform.machine(), 0.0), extensions=['png'], remove_text=True) def test_alpha_rcparam(): import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) ax.plot(range(10), lw=5) with mpl.rc_context(rc={'legend.framealpha': .75}): leg = plt.legend(['Longlabel that will go away'], loc='center') # this alpha is going to be over-ridden by the rcparam with # sets the alpha of the patch to be non-None which causes the alpha # value of the face color to be discarded. This behavior may not be # ideal, but it is what it is and we should keep track of it changing leg.legendPatch.set_facecolor([1, 0, 0, 0.5]) @image_comparison(baseline_images=['fancy'], remove_text=True) def test_fancy(): # using subplot triggers some offsetbox functionality untested elsewhere plt.subplot(121) plt.scatter(np.arange(10), np.arange(10, 0, -1), label='XX\nXX') plt.plot([5] * 10, 'o--', label='XX') plt.errorbar(np.arange(10), np.arange(10), xerr=0.5, yerr=0.5, label='XX') plt.legend(loc="center left", bbox_to_anchor=[1.0, 0.5], ncol=2, shadow=True, title="My legend", numpoints=1) @image_comparison(baseline_images=['framealpha'], remove_text=True, tol={'aarch64': 0.02}.get(platform.machine(), 0.0)) def test_framealpha(): x = np.linspace(1, 100, 100) y = x plt.plot(x, y, label='mylabel', lw=10) plt.legend(framealpha=0.5) @image_comparison(baseline_images=['scatter_rc3', 'scatter_rc1'], remove_text=True) def test_rc(): # using subplot triggers some offsetbox functionality untested elsewhere plt.figure() ax = plt.subplot(121) ax.scatter(np.arange(10), np.arange(10, 0, -1), label='three') ax.legend(loc="center left", bbox_to_anchor=[1.0, 0.5], title="My legend") mpl.rcParams['legend.scatterpoints'] = 1 plt.figure() ax = plt.subplot(121) ax.scatter(np.arange(10), np.arange(10, 0, -1), label='one') ax.legend(loc="center left", bbox_to_anchor=[1.0, 0.5], title="My legend") @image_comparison(baseline_images=['legend_expand'], remove_text=True) def test_legend_expand(): 'Test expand mode' legend_modes = [None, "expand"] fig, axes_list = plt.subplots(len(legend_modes), 1) x = np.arange(100) for ax, mode in zip(axes_list, legend_modes): ax.plot(x, 50 - x, 'o', label='y=1') l1 = ax.legend(loc='upper left', mode=mode) ax.add_artist(l1) ax.plot(x, x - 50, 'o', label='y=-1') l2 = ax.legend(loc='right', mode=mode) ax.add_artist(l2) ax.legend(loc='lower left', mode=mode, ncol=2) @image_comparison(baseline_images=['hatching'], remove_text=True, style='default') def test_hatching(): fig, ax = plt.subplots() # Patches patch = plt.Rectangle((0, 0), 0.3, 0.3, hatch='xx', label='Patch\ndefault color\nfilled') ax.add_patch(patch) patch = plt.Rectangle((0.33, 0), 0.3, 0.3, hatch='||', edgecolor='C1', label='Patch\nexplicit color\nfilled') ax.add_patch(patch) patch = plt.Rectangle((0, 0.4), 0.3, 0.3, hatch='xx', fill=False, label='Patch\ndefault color\nunfilled') ax.add_patch(patch) patch = plt.Rectangle((0.33, 0.4), 0.3, 0.3, hatch='||', fill=False, edgecolor='C1', label='Patch\nexplicit color\nunfilled') ax.add_patch(patch) # Paths ax.fill_between([0, .15, .3], [.8, .8, .8], [.9, 1.0, .9], hatch='+', label='Path\ndefault color') ax.fill_between([.33, .48, .63], [.8, .8, .8], [.9, 1.0, .9], hatch='+', edgecolor='C2', label='Path\nexplicit color') ax.set_xlim(-0.01, 1.1) ax.set_ylim(-0.01, 1.1) ax.legend(handlelength=4, handleheight=4) def test_legend_remove(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) lines = ax.plot(range(10)) leg = fig.legend(lines, "test") leg.remove() assert fig.legends == [] leg = ax.legend("test") leg.remove() assert ax.get_legend() is None class TestLegendFunction(object): # Tests the legend function on the Axes and pyplot. def test_legend_handle_label(self): lines = plt.plot(range(10)) with mock.patch('matplotlib.legend.Legend') as Legend: plt.legend(lines, ['hello world']) Legend.assert_called_with(plt.gca(), lines, ['hello world']) def test_legend_no_args(self): lines = plt.plot(range(10), label='hello world') with mock.patch('matplotlib.legend.Legend') as Legend: plt.legend() Legend.assert_called_with(plt.gca(), lines, ['hello world']) def test_legend_label_args(self): lines = plt.plot(range(10), label='hello world') with mock.patch('matplotlib.legend.Legend') as Legend: plt.legend(['foobar']) Legend.assert_called_with(plt.gca(), lines, ['foobar']) def test_legend_three_args(self): lines = plt.plot(range(10), label='hello world') with mock.patch('matplotlib.legend.Legend') as Legend: plt.legend(lines, ['foobar'], loc='right') Legend.assert_called_with(plt.gca(), lines, ['foobar'], loc='right') def test_legend_handler_map(self): lines = plt.plot(range(10), label='hello world') with mock.patch('matplotlib.legend.' '_get_legend_handles_labels') as handles_labels: handles_labels.return_value = lines, ['hello world'] plt.legend(handler_map={'1': 2}) handles_labels.assert_called_with([plt.gca()], {'1': 2}) def test_kwargs(self): fig, ax = plt.subplots(1, 1) th = np.linspace(0, 2*np.pi, 1024) lns, = ax.plot(th, np.sin(th), label='sin', lw=5) lnc, = ax.plot(th, np.cos(th), label='cos', lw=5) with mock.patch('matplotlib.legend.Legend') as Legend: ax.legend(labels=('a', 'b'), handles=(lnc, lns)) Legend.assert_called_with(ax, (lnc, lns), ('a', 'b')) def test_warn_args_kwargs(self): fig, ax = plt.subplots(1, 1) th = np.linspace(0, 2*np.pi, 1024) lns, = ax.plot(th, np.sin(th), label='sin', lw=5) lnc, = ax.plot(th, np.cos(th), label='cos', lw=5) with mock.patch('warnings.warn') as warn: ax.legend((lnc, lns), labels=('a', 'b')) warn.assert_called_with("You have mixed positional and keyword " "arguments, some input may be " "discarded.") def test_parasite(self): from mpl_toolkits.axes_grid1 import host_subplot host = host_subplot(111) par = host.twinx() p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density") p2, = par.plot([0, 1, 2], [0, 3, 2], label="Temperature") with mock.patch('matplotlib.legend.Legend') as Legend: leg = plt.legend() Legend.assert_called_with(host, [p1, p2], ['Density', 'Temperature']) class TestLegendFigureFunction(object): # Tests the legend function for figure def test_legend_handle_label(self): fig, ax = plt.subplots() lines = ax.plot(range(10)) with mock.patch('matplotlib.legend.Legend') as Legend: fig.legend(lines, ['hello world']) Legend.assert_called_with(fig, lines, ['hello world']) def test_legend_no_args(self): fig, ax = plt.subplots() lines = ax.plot(range(10), label='hello world') with mock.patch('matplotlib.legend.Legend') as Legend: fig.legend() Legend.assert_called_with(fig, lines, ['hello world']) def test_legend_label_arg(self): fig, ax = plt.subplots() lines = ax.plot(range(10)) with mock.patch('matplotlib.legend.Legend') as Legend: fig.legend(['foobar']) Legend.assert_called_with(fig, lines, ['foobar']) def test_legend_label_three_args(self): fig, ax = plt.subplots() lines = ax.plot(range(10)) with mock.patch('matplotlib.legend.Legend') as Legend: fig.legend(lines, ['foobar'], 'right') Legend.assert_called_with(fig, lines, ['foobar'], 'right') def test_legend_label_three_args_pluskw(self): # test that third argument and loc= called together give # Exception fig, ax = plt.subplots() lines = ax.plot(range(10)) with pytest.raises(Exception): fig.legend(lines, ['foobar'], 'right', loc='left') def test_legend_kw_args(self): fig, axs = plt.subplots(1, 2) lines = axs[0].plot(range(10)) lines2 = axs[1].plot(np.arange(10) * 2.) with mock.patch('matplotlib.legend.Legend') as Legend: fig.legend(loc='right', labels=('a', 'b'), handles=(lines, lines2)) Legend.assert_called_with(fig, (lines, lines2), ('a', 'b'), loc='right') def test_warn_args_kwargs(self): fig, axs = plt.subplots(1, 2) lines = axs[0].plot(range(10)) lines2 = axs[1].plot(np.arange(10) * 2.) with mock.patch('warnings.warn') as warn: fig.legend((lines, lines2), labels=('a', 'b')) warn.assert_called_with("You have mixed positional and keyword " "arguments, some input may be " "discarded.") @image_comparison(baseline_images=['legend_stackplot'], extensions=['png']) def test_legend_stackplot(): '''test legend for PolyCollection using stackplot''' # related to #1341, #1943, and PR #3303 fig = plt.figure() ax = fig.add_subplot(111) x = np.linspace(0, 10, 10) y1 = 1.0 * x y2 = 2.0 * x + 1 y3 = 3.0 * x + 2 ax.stackplot(x, y1, y2, y3, labels=['y1', 'y2', 'y3']) ax.set_xlim((0, 10)) ax.set_ylim((0, 70)) ax.legend(loc='best') def test_cross_figure_patch_legend(): fig, ax = plt.subplots() fig2, ax2 = plt.subplots() brs = ax.bar(range(3), range(3)) fig2.legend(brs, 'foo') def test_nanscatter(): fig, ax = plt.subplots() h = ax.scatter([np.nan], [np.nan], marker="o", facecolor="r", edgecolor="r", s=3) ax.legend([h], ["scatter"]) fig, ax = plt.subplots() for color in ['red', 'green', 'blue']: n = 750 x, y = np.random.rand(2, n) scale = 200.0 * np.random.rand(n) ax.scatter(x, y, c=color, s=scale, label=color, alpha=0.3, edgecolors='none') ax.legend() ax.grid(True) def test_legend_repeatcheckok(): fig, ax = plt.subplots() ax.scatter(0.0, 1.0, color='k', marker='o', label='test') ax.scatter(0.5, 0.0, color='r', marker='v', label='test') hl = ax.legend() hand, lab = mlegend._get_legend_handles_labels([ax]) assert len(lab) == 2 fig, ax = plt.subplots() ax.scatter(0.0, 1.0, color='k', marker='o', label='test') ax.scatter(0.5, 0.0, color='k', marker='v', label='test') hl = ax.legend() hand, lab = mlegend._get_legend_handles_labels([ax]) assert len(lab) == 2 @image_comparison(baseline_images=['not_covering_scatter'], extensions=['png']) def test_not_covering_scatter(): colors = ['b', 'g', 'r'] for n in range(3): plt.scatter([n], [n], color=colors[n]) plt.legend(['foo', 'foo', 'foo'], loc='best') plt.gca().set_xlim(-0.5, 2.2) plt.gca().set_ylim(-0.5, 2.2) @image_comparison(baseline_images=['not_covering_scatter_transform'], extensions=['png']) def test_not_covering_scatter_transform(): # Offsets point to top left, the default auto position offset = mtransforms.Affine2D().translate(-20, 20) x = np.linspace(0, 30, 1000) plt.plot(x, x) plt.scatter([20], [10], transform=offset + plt.gca().transData) plt.legend(['foo', 'bar'], loc='best') def test_linecollection_scaled_dashes(): lines1 = [[(0, .5), (.5, 1)], [(.3, .6), (.2, .2)]] lines2 = [[[0.7, .2], [.8, .4]], [[.5, .7], [.6, .1]]] lines3 = [[[0.6, .2], [.8, .4]], [[.5, .7], [.1, .1]]] lc1 = mcollections.LineCollection(lines1, linestyles="--", lw=3) lc2 = mcollections.LineCollection(lines2, linestyles="-.") lc3 = mcollections.LineCollection(lines3, linestyles=":", lw=.5) fig, ax = plt.subplots() ax.add_collection(lc1) ax.add_collection(lc2) ax.add_collection(lc3) leg = ax.legend([lc1, lc2, lc3], ["line1", "line2", 'line 3']) h1, h2, h3 = leg.legendHandles for oh, lh in zip((lc1, lc2, lc3), (h1, h2, h3)): assert oh.get_linestyles()[0][1] == lh._dashSeq assert oh.get_linestyles()[0][0] == lh._dashOffset def test_handler_numpoints(): '''test legend handler with numponts less than or equal to 1''' # related to #6921 and PR #8478 fig, ax = plt.subplots() ax.plot(range(5), label='test') ax.legend(numpoints=0.5) def test_shadow_framealpha(): # Test if framealpha is activated when shadow is True # and framealpha is not explicitly passed''' fig, ax = plt.subplots() ax.plot(range(100), label="test") leg = ax.legend(shadow=True, facecolor='w') assert leg.get_frame().get_alpha() == 1 def test_legend_title_empty(): # test that if we don't set the legend title, that # it comes back as an empty string, and that it is not # visible: fig, ax = plt.subplots() ax.plot(range(10)) leg = ax.legend() assert leg.get_title().get_text() == "" assert leg.get_title().get_visible() is False def test_legend_proper_window_extent(): # test that legend returns the expected extent under various dpi... fig, ax = plt.subplots(dpi=100) ax.plot(range(10), label='Aardvark') leg = ax.legend() x01 = leg.get_window_extent(fig.canvas.get_renderer()).x0 fig, ax = plt.subplots(dpi=200) ax.plot(range(10), label='Aardvark') leg = ax.legend() x02 = leg.get_window_extent(fig.canvas.get_renderer()).x0 assert pytest.approx(x01*2, 0.1) == x02 def test_legend_title_fontsize(): # test the title_fontsize kwarg fig, ax = plt.subplots() ax.plot(range(10)) leg = ax.legend(title='Aardvark', title_fontsize=22) assert leg.get_title().get_fontsize() == 22 def test_get_set_draggable(): legend = plt.legend() assert not legend.get_draggable() legend.set_draggable(True) assert legend.get_draggable() legend.set_draggable(False) assert not legend.get_draggable() def test_draggable(): legend = plt.legend() with pytest.warns(MatplotlibDeprecationWarning): legend.draggable(True) assert legend.get_draggable() with pytest.warns(MatplotlibDeprecationWarning): legend.draggable(False) assert not legend.get_draggable() # test toggle with pytest.warns(MatplotlibDeprecationWarning): legend.draggable() assert legend.get_draggable() with pytest.warns(MatplotlibDeprecationWarning): legend.draggable() assert not legend.get_draggable() def test_alpha_handles(): x, n, hh = plt.hist([1, 2, 3], alpha=0.25, label='data', color='red') legend = plt.legend() for lh in legend.legendHandles: lh.set_alpha(1.0) assert lh.get_facecolor()[:-1] == hh[1].get_facecolor()[:-1] assert lh.get_edgecolor()[:-1] == hh[1].get_edgecolor()[:-1]
35.081081
79
0.608988
53f26eea0df0b38aa5260a340d2c38eac05fefa5
440
py
Python
rest/incoming-phone-numbers/list-get-example-2/list-get-example-2.5.x.py
shaileshn/api-snippets
08826972154634335378fed0edd2707d7f62b03b
[ "MIT" ]
2
2017-11-23T11:31:20.000Z
2018-01-22T04:14:02.000Z
rest/incoming-phone-numbers/list-get-example-2/list-get-example-2.5.x.py
berkus/twilio-api-snippets
beaa4e211044cb06daf9b73fb05ad6a7a948f879
[ "MIT" ]
null
null
null
rest/incoming-phone-numbers/list-get-example-2/list-get-example-2.5.x.py
berkus/twilio-api-snippets
beaa4e211044cb06daf9b73fb05ad6a7a948f879
[ "MIT" ]
1
2019-10-02T14:36:36.000Z
2019-10-02T14:36:36.000Z
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import TwilioRestClient # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = TwilioRestClient(account_sid, auth_token) # A list of number objects with the properties described above numbers = client.phone_numbers.list(phone_number="+14158675309")
40
72
0.825
36971932b0b2c5a897cf1641fd696fa3e683fc56
7,717
py
Python
tests/extension/thread_/ram_read_dataflow/test_thread_ram_read_dataflow.py
akmaru/veriloggen
74f998139e8cf613f7703fa4cffd571bbf069bbc
[ "Apache-2.0" ]
null
null
null
tests/extension/thread_/ram_read_dataflow/test_thread_ram_read_dataflow.py
akmaru/veriloggen
74f998139e8cf613f7703fa4cffd571bbf069bbc
[ "Apache-2.0" ]
null
null
null
tests/extension/thread_/ram_read_dataflow/test_thread_ram_read_dataflow.py
akmaru/veriloggen
74f998139e8cf613f7703fa4cffd571bbf069bbc
[ "Apache-2.0" ]
null
null
null
from __future__ import absolute_import from __future__ import print_function import veriloggen import thread_ram_read_dataflow expected_verilog = """ module test; reg CLK; reg RST; main uut ( .CLK(CLK), .RST(RST) ); initial begin $dumpfile("uut.vcd"); $dumpvars(0, uut, CLK, RST); end initial begin CLK = 0; forever begin #5 CLK = !CLK; end end initial begin RST = 0; #100; RST = 1; #100; RST = 0; #100000; $finish; end endmodule module main ( input CLK, input RST ); reg [14-1:0] myram_0_addr; wire [32-1:0] myram_0_rdata; reg [32-1:0] myram_0_wdata; reg myram_0_wenable; reg [14-1:0] myram_1_addr; wire [32-1:0] myram_1_rdata; reg [32-1:0] myram_1_wdata; reg myram_1_wenable; myram inst_myram ( .CLK(CLK), .myram_0_addr(myram_0_addr), .myram_0_rdata(myram_0_rdata), .myram_0_wdata(myram_0_wdata), .myram_0_wenable(myram_0_wenable), .myram_1_addr(myram_1_addr), .myram_1_rdata(myram_1_rdata), .myram_1_wdata(myram_1_wdata), .myram_1_wenable(myram_1_wenable) ); reg [32-1:0] fsm; localparam fsm_init = 0; reg [8-1:0] _tmp_0; reg _tmp_1; wire [32-1:0] _dataflow_counter_odata_1; wire _dataflow_counter_ovalid_1; wire _dataflow_counter_oready_1; assign _dataflow_counter_oready_1 = (_tmp_0 > 0) && !_tmp_1; reg _myram_cond_0_1; reg _tmp_2; reg _tmp_3; wire _tmp_4; wire _tmp_5; localparam _tmp_6 = 1; wire [_tmp_6-1:0] _tmp_7; assign _tmp_7 = (_tmp_4 || !_tmp_2) && (_tmp_5 || !_tmp_3); reg [_tmp_6-1:0] __tmp_7_1; wire signed [32-1:0] _tmp_8; reg signed [32-1:0] __tmp_8_1; assign _tmp_8 = (__tmp_7_1)? myram_1_rdata : __tmp_8_1; reg _tmp_9; reg _tmp_10; reg _tmp_11; reg _tmp_12; reg [7-1:0] _tmp_13; wire signed [32-1:0] _dataflow__variable_odata_3; wire _dataflow__variable_ovalid_3; wire _dataflow__variable_oready_3; assign _dataflow__variable_oready_3 = 1; wire [1-1:0] _dataflow__variable_odata_4; wire _dataflow__variable_ovalid_4; wire _dataflow__variable_oready_4; assign _dataflow__variable_oready_4 = 1; reg [32-1:0] sum; reg _seq_cond_0_1; always @(posedge CLK) begin if(RST) begin myram_1_wdata <= 0; myram_1_wenable <= 0; myram_0_addr <= 0; _tmp_0 <= 0; myram_0_wdata <= 0; myram_0_wenable <= 0; _tmp_1 <= 0; _myram_cond_0_1 <= 0; __tmp_7_1 <= 0; __tmp_8_1 <= 0; _tmp_12 <= 0; _tmp_2 <= 0; _tmp_3 <= 0; _tmp_10 <= 0; _tmp_11 <= 0; _tmp_9 <= 0; myram_1_addr <= 0; _tmp_13 <= 0; end else begin if(_myram_cond_0_1) begin myram_0_wenable <= 0; _tmp_1 <= 0; end myram_1_wdata <= 0; myram_1_wenable <= 0; if((fsm == 0) && (_tmp_0 == 0)) begin myram_0_addr <= -1; _tmp_0 <= 64; end if(_dataflow_counter_ovalid_1 && ((_tmp_0 > 0) && !_tmp_1) && (_tmp_0 > 0)) begin myram_0_addr <= myram_0_addr + 1; myram_0_wdata <= _dataflow_counter_odata_1; myram_0_wenable <= 1; _tmp_0 <= _tmp_0 - 1; end if(_dataflow_counter_ovalid_1 && ((_tmp_0 > 0) && !_tmp_1) && (_tmp_0 == 1)) begin _tmp_1 <= 1; end _myram_cond_0_1 <= 1; __tmp_7_1 <= _tmp_7; __tmp_8_1 <= _tmp_8; if((_tmp_4 || !_tmp_2) && (_tmp_5 || !_tmp_3) && _tmp_10) begin _tmp_12 <= 0; _tmp_2 <= 0; _tmp_3 <= 0; _tmp_10 <= 0; end if((_tmp_4 || !_tmp_2) && (_tmp_5 || !_tmp_3) && _tmp_9) begin _tmp_2 <= 1; _tmp_3 <= 1; _tmp_12 <= _tmp_11; _tmp_11 <= 0; _tmp_9 <= 0; _tmp_10 <= 1; end if((fsm == 3) && (_tmp_13 == 0) && !_tmp_11 && !_tmp_12) begin myram_1_addr <= 0; _tmp_13 <= 31; _tmp_9 <= 1; _tmp_11 <= 0; end if((_tmp_4 || !_tmp_2) && (_tmp_5 || !_tmp_3) && (_tmp_13 > 0)) begin myram_1_addr <= myram_1_addr + 1; _tmp_13 <= _tmp_13 - 1; _tmp_9 <= 1; _tmp_11 <= 0; end if((_tmp_4 || !_tmp_2) && (_tmp_5 || !_tmp_3) && (_tmp_13 == 1)) begin _tmp_11 <= 1; end end end assign _dataflow__variable_odata_3 = _tmp_8; assign _dataflow__variable_ovalid_3 = _tmp_2; assign _tmp_4 = 1 && _dataflow__variable_oready_3; assign _dataflow__variable_odata_4 = _tmp_12; assign _dataflow__variable_ovalid_4 = _tmp_3; assign _tmp_5 = 1 && _dataflow__variable_oready_4; reg [32-1:0] _dataflow_counter_data_1; reg _dataflow_counter_valid_1; wire _dataflow_counter_ready_1; assign _dataflow_counter_odata_1 = _dataflow_counter_data_1; assign _dataflow_counter_ovalid_1 = _dataflow_counter_valid_1; assign _dataflow_counter_ready_1 = _dataflow_counter_oready_1; always @(posedge CLK) begin if(RST) begin _dataflow_counter_data_1 <= -2'sd1; _dataflow_counter_valid_1 <= 0; end else begin if((_dataflow_counter_ready_1 || !_dataflow_counter_valid_1) && 1 && 1) begin _dataflow_counter_data_1 <= _dataflow_counter_data_1 + 1; end if(_dataflow_counter_valid_1 && _dataflow_counter_ready_1) begin _dataflow_counter_valid_1 <= 0; end if((_dataflow_counter_ready_1 || !_dataflow_counter_valid_1) && 1) begin _dataflow_counter_valid_1 <= 1; end end end localparam fsm_1 = 1; localparam fsm_2 = 2; localparam fsm_3 = 3; localparam fsm_4 = 4; localparam fsm_5 = 5; always @(posedge CLK) begin if(RST) begin fsm <= fsm_init; end else begin case(fsm) fsm_init: begin fsm <= fsm_1; end fsm_1: begin if(_tmp_1) begin fsm <= fsm_2; end end fsm_2: begin fsm <= fsm_3; end fsm_3: begin fsm <= fsm_4; end fsm_4: begin if(_tmp_12) begin fsm <= fsm_5; end end endcase end end always @(posedge CLK) begin if(RST) begin sum <= 0; _seq_cond_0_1 <= 0; end else begin if(_seq_cond_0_1) begin $display("sum=%d expected_sum=%d", sum, 496); end if(_dataflow__variable_ovalid_3) begin sum <= sum + _dataflow__variable_odata_3; end _seq_cond_0_1 <= _dataflow__variable_ovalid_3 && (_dataflow__variable_odata_4 == 1); end end endmodule module myram ( input CLK, input [14-1:0] myram_0_addr, output [32-1:0] myram_0_rdata, input [32-1:0] myram_0_wdata, input myram_0_wenable, input [14-1:0] myram_1_addr, output [32-1:0] myram_1_rdata, input [32-1:0] myram_1_wdata, input myram_1_wenable ); reg [14-1:0] myram_0_daddr; reg [14-1:0] myram_1_daddr; reg [32-1:0] mem [0:16384-1]; always @(posedge CLK) begin if(myram_0_wenable) begin mem[myram_0_addr] <= myram_0_wdata; end myram_0_daddr <= myram_0_addr; end assign myram_0_rdata = mem[myram_0_daddr]; always @(posedge CLK) begin if(myram_1_wenable) begin mem[myram_1_addr] <= myram_1_wdata; end myram_1_daddr <= myram_1_addr; end assign myram_1_rdata = mem[myram_1_daddr]; endmodule """ def test(): veriloggen.reset() test_module = thread_ram_read_dataflow.mkTest() code = test_module.to_verilog() from pyverilog.vparser.parser import VerilogParser from pyverilog.ast_code_generator.codegen import ASTCodeGenerator parser = VerilogParser() expected_ast = parser.parse(expected_verilog) codegen = ASTCodeGenerator() expected_code = codegen.visit(expected_ast) assert(expected_code == code)
23.671779
90
0.623429
d314720220fa87735419d8f1369a03b851789b6d
742
py
Python
kwiklib/dataio/tests/mock.py
fiath/test
b50898dafa90e93da48f573e0b3feb1bb6acd8de
[ "MIT", "BSD-3-Clause" ]
7
2015-01-20T13:55:51.000Z
2018-02-06T09:31:21.000Z
kwiklib/dataio/tests/mock.py
fiath/test
b50898dafa90e93da48f573e0b3feb1bb6acd8de
[ "MIT", "BSD-3-Clause" ]
6
2015-01-08T18:13:53.000Z
2016-06-22T09:53:53.000Z
kwiklib/dataio/tests/mock.py
fiath/test
b50898dafa90e93da48f573e0b3feb1bb6acd8de
[ "MIT", "BSD-3-Clause" ]
8
2015-01-22T22:57:19.000Z
2020-03-19T11:43:56.000Z
"""Create mock data""" # ----------------------------------------------------------------------------- # Imports # ----------------------------------------------------------------------------- import numpy as np from kwiklib.dataio.kwik_creation import * from kwiklib.dataio.experiment import create_experiment # ----------------------------------------------------------------------------- # Helper functions # ----------------------------------------------------------------------------- def randint(high): return np.random.randint(low=0, high=high) # ----------------------------------------------------------------------------- # Functions # -----------------------------------------------------------------------------
33.727273
79
0.260108
9ebe53ccb324f4b971540b338e79d946943082a4
1,465
py
Python
tests/post/steps/test_seccomp.py
n1603/metalk8s
2f337a435380102055d3725f0cc2b6165818e880
[ "Apache-2.0" ]
null
null
null
tests/post/steps/test_seccomp.py
n1603/metalk8s
2f337a435380102055d3725f0cc2b6165818e880
[ "Apache-2.0" ]
null
null
null
tests/post/steps/test_seccomp.py
n1603/metalk8s
2f337a435380102055d3725f0cc2b6165818e880
[ "Apache-2.0" ]
null
null
null
import os.path import yaml from kubernetes import client import pytest from pytest_bdd import scenario, when from tests import kube_utils from tests import utils @scenario("../features/seccomp.feature", "Running a Pod with the 'runtime/default' seccomp profile works") def test_seccomp(host): pass @when("we create a utils Pod with labels {'test': 'seccomp1'} " "and annotations " "{'seccomp.security.alpha.kubernetes.io/pod': 'runtime/default'}") def create_utils_pod(utils_pod): pass @pytest.fixture def utils_pod(k8s_client, utils_image): manifest_file = os.path.join( os.path.realpath(os.path.dirname(__file__)), "files", "utils.yaml" ) with open(manifest_file, encoding="utf-8") as fd: manifest = yaml.safe_load(fd) pod_name = 'test-seccomp1' manifest["spec"]["containers"][0]["image"] = utils_image manifest["metadata"]["name"] = pod_name manifest["metadata"]["annotations"] = { "seccomp.security.alpha.kubernetes.io/pod": "runtime/default", } manifest["metadata"]["labels"] = { "test": "seccomp1", } k8s_client.create_namespaced_pod(body=manifest, namespace='default') try: yield pod_name finally: k8s_client.delete_namespaced_pod( name=pod_name, namespace="default", body=client.V1DeleteOptions( grace_period_seconds=0, ), )
24.416667
75
0.642321
382895fffc465b74c027cebe685ec2ad78e751cb
1,007
py
Python
app/core/admin.py
LukaszMalucha/Data-Labs-with-Python-Tableau
75f2a7ad5cbd7dd22a04e20bdbe0172e669093c3
[ "MIT" ]
6
2018-09-25T18:37:14.000Z
2021-04-24T23:58:27.000Z
app/core/admin.py
LukaszMalucha/Data-Labs-with-Python-Tableau
75f2a7ad5cbd7dd22a04e20bdbe0172e669093c3
[ "MIT" ]
12
2020-01-08T11:56:11.000Z
2022-02-27T09:48:02.000Z
app/core/admin.py
LukaszMalucha/Data-Labs-with-Python-Tableau
75f2a7ad5cbd7dd22a04e20bdbe0172e669093c3
[ "MIT" ]
1
2019-08-17T04:33:11.000Z
2019-08-17T04:33:11.000Z
from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from core import models class UserAdmin(BaseUserAdmin): ordering = ['id'] list_display = ['email', 'name'] list_filter = ('is_active', 'is_staff', 'is_superuser') search_fields = ['email', 'name'] fieldsets = ( (None, {'fields': ('email', 'password')}), (('Personal Info'), {'fields': ('name',)}), (('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')}), (('Important dates'), {'fields': ('last_login',)})) # Page for adding new users add_fieldsets = ( (None, {'classes': ('wide',), 'fields': ('email', 'password1', 'password2')}),) class DataSkillModelAdmin(admin.ModelAdmin): list_display = ["dataskill", "percentage"] class Meta: model = models.DataSkill admin.site.register(models.User, UserAdmin) admin.site.register(models.MyProfile) admin.site.register(models.DataSkill, DataSkillModelAdmin)
30.515152
87
0.645482
6bd05531333ba99539c128a62ea028e2cc6c9a2b
9,291
py
Python
clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
#!/usr/bin/env python # #===- clang-tidy-diff.py - ClangTidy Diff Checker -----------*- python -*--===# # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # #===-----------------------------------------------------------------------===# r""" ClangTidy Diff Checker ====================== This script reads input from a unified diff, runs clang-tidy on all changed files and outputs clang-tidy warnings in changed lines only. This is useful to detect clang-tidy regressions in the lines touched by a specific patch. Example usage for git/svn users: git diff -U0 HEAD^ | clang-tidy-diff.py -p1 svn diff --diff-cmd=diff -x-U0 | \ clang-tidy-diff.py -fix -checks=-*,modernize-use-override """ import argparse import glob import json import multiprocessing import os import re import shutil import subprocess import sys import tempfile import threading import traceback try: import yaml except ImportError: yaml = None is_py2 = sys.version[0] == '2' if is_py2: import Queue as queue else: import queue as queue def run_tidy(task_queue, lock, timeout): watchdog = None while True: command = task_queue.get() try: proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if timeout is not None: watchdog = threading.Timer(timeout, proc.kill) watchdog.start() stdout, stderr = proc.communicate() with lock: sys.stdout.write(stdout.decode('utf-8') + '\n') sys.stdout.flush() if stderr: sys.stderr.write(stderr.decode('utf-8') + '\n') sys.stderr.flush() except Exception as e: with lock: sys.stderr.write('Failed: ' + str(e) + ': '.join(command) + '\n') finally: with lock: if not (timeout is None or watchdog is None): if not watchdog.is_alive(): sys.stderr.write('Terminated by timeout: ' + ' '.join(command) + '\n') watchdog.cancel() task_queue.task_done() def start_workers(max_tasks, tidy_caller, task_queue, lock, timeout): for _ in range(max_tasks): t = threading.Thread(target=tidy_caller, args=(task_queue, lock, timeout)) t.daemon = True t.start() def merge_replacement_files(tmpdir, mergefile): """Merge all replacement files in a directory into a single file""" # The fixes suggested by clang-tidy >= 4.0.0 are given under # the top level key 'Diagnostics' in the output yaml files mergekey = "Diagnostics" merged = [] for replacefile in glob.iglob(os.path.join(tmpdir, '*.yaml')): content = yaml.safe_load(open(replacefile, 'r')) if not content: continue # Skip empty files. merged.extend(content.get(mergekey, [])) if merged: # MainSourceFile: The key is required by the definition inside # include/clang/Tooling/ReplacementsYaml.h, but the value # is actually never used inside clang-apply-replacements, # so we set it to '' here. output = {'MainSourceFile': '', mergekey: merged} with open(mergefile, 'w') as out: yaml.safe_dump(output, out) else: # Empty the file: open(mergefile, 'w').close() def main(): parser = argparse.ArgumentParser(description= 'Run clang-tidy against changed files, and ' 'output diagnostics only for modified ' 'lines.') parser.add_argument('-clang-tidy-binary', metavar='PATH', default='clang-tidy', help='path to clang-tidy binary') parser.add_argument('-p', metavar='NUM', default=0, help='strip the smallest prefix containing P slashes') parser.add_argument('-regex', metavar='PATTERN', default=None, help='custom pattern selecting file paths to check ' '(case sensitive, overrides -iregex)') parser.add_argument('-iregex', metavar='PATTERN', default= r'.*\.(cpp|cc|c\+\+|cxx|c|cl|h|hpp|m|mm|inc)', help='custom pattern selecting file paths to check ' '(case insensitive, overridden by -regex)') parser.add_argument('-j', type=int, default=1, help='number of tidy instances to be run in parallel.') parser.add_argument('-timeout', type=int, default=None, help='timeout per each file in seconds.') parser.add_argument('-fix', action='store_true', default=False, help='apply suggested fixes') parser.add_argument('-checks', help='checks filter, when not specified, use clang-tidy ' 'default', default='') parser.add_argument('-use-color', action='store_true', help='Use colors in output') parser.add_argument('-path', dest='build_path', help='Path used to read a compile command database.') if yaml: parser.add_argument('-export-fixes', metavar='FILE', dest='export_fixes', help='Create a yaml file to store suggested fixes in, ' 'which can be applied with clang-apply-replacements.') parser.add_argument('-extra-arg', dest='extra_arg', action='append', default=[], help='Additional argument to append to the compiler ' 'command line.') parser.add_argument('-extra-arg-before', dest='extra_arg_before', action='append', default=[], help='Additional argument to prepend to the compiler ' 'command line.') parser.add_argument('-quiet', action='store_true', default=False, help='Run clang-tidy in quiet mode') clang_tidy_args = [] argv = sys.argv[1:] if '--' in argv: clang_tidy_args.extend(argv[argv.index('--'):]) argv = argv[:argv.index('--')] args = parser.parse_args(argv) # Extract changed lines for each file. filename = None lines_by_file = {} for line in sys.stdin: match = re.search('^\+\+\+\ \"?(.*?/){%s}([^ \t\n\"]*)' % args.p, line) if match: filename = match.group(2) if filename is None: continue if args.regex is not None: if not re.match('^%s$' % args.regex, filename): continue else: if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE): continue match = re.search('^@@.*\+(\d+)(,(\d+))?', line) if match: start_line = int(match.group(1)) line_count = 1 if match.group(3): line_count = int(match.group(3)) if line_count == 0: continue end_line = start_line + line_count - 1 lines_by_file.setdefault(filename, []).append([start_line, end_line]) if not any(lines_by_file): print("No relevant changes found.") sys.exit(0) max_task_count = args.j if max_task_count == 0: max_task_count = multiprocessing.cpu_count() max_task_count = min(len(lines_by_file), max_task_count) tmpdir = None if yaml and args.export_fixes: tmpdir = tempfile.mkdtemp() # Tasks for clang-tidy. task_queue = queue.Queue(max_task_count) # A lock for console output. lock = threading.Lock() # Run a pool of clang-tidy workers. start_workers(max_task_count, run_tidy, task_queue, lock, args.timeout) # Form the common args list. common_clang_tidy_args = [] if args.fix: common_clang_tidy_args.append('-fix') if args.checks != '': common_clang_tidy_args.append('-checks=' + args.checks) if args.quiet: common_clang_tidy_args.append('-quiet') if args.build_path is not None: common_clang_tidy_args.append('-p=%s' % args.build_path) if args.use_color: common_clang_tidy_args.append('--use-color') for arg in args.extra_arg: common_clang_tidy_args.append('-extra-arg=%s' % arg) for arg in args.extra_arg_before: common_clang_tidy_args.append('-extra-arg-before=%s' % arg) for name in lines_by_file: line_filter_json = json.dumps( [{"name": name, "lines": lines_by_file[name]}], separators=(',', ':')) # Run clang-tidy on files containing changes. command = [args.clang_tidy_binary] command.append('-line-filter=' + line_filter_json) if yaml and args.export_fixes: # Get a temporary file. We immediately close the handle so clang-tidy can # overwrite it. (handle, tmp_name) = tempfile.mkstemp(suffix='.yaml', dir=tmpdir) os.close(handle) command.append('-export-fixes=' + tmp_name) command.extend(common_clang_tidy_args) command.append(name) command.extend(clang_tidy_args) task_queue.put(command) # Wait for all threads to be done. task_queue.join() if yaml and args.export_fixes: print('Writing fixes to ' + args.export_fixes + ' ...') try: merge_replacement_files(tmpdir, args.export_fixes) except: sys.stderr.write('Error exporting fixes.\n') traceback.print_exc() if tmpdir: shutil.rmtree(tmpdir) if __name__ == '__main__': main()
33.908759
79
0.616618
6f397e66399ffd8f14a8d42129c509fef40b08c7
1,277
py
Python
grr/core/grr_response_core/lib/parsers/cron_file_parser.py
ahmednofal/grr
08a57f6873ee13f425d0106e4143663bc6dbdd60
[ "Apache-2.0" ]
null
null
null
grr/core/grr_response_core/lib/parsers/cron_file_parser.py
ahmednofal/grr
08a57f6873ee13f425d0106e4143663bc6dbdd60
[ "Apache-2.0" ]
null
null
null
grr/core/grr_response_core/lib/parsers/cron_file_parser.py
ahmednofal/grr
08a57f6873ee13f425d0106e4143663bc6dbdd60
[ "Apache-2.0" ]
2
2020-08-24T00:22:03.000Z
2020-11-14T08:34:43.000Z
#!/usr/bin/env python """Simple parsers for cron type files.""" from __future__ import absolute_import from __future__ import unicode_literals import crontab from grr_response_core.lib import parser from grr_response_core.lib import utils from grr_response_core.lib.rdfvalues import cronjobs as rdf_cronjobs class CronTabParser(parser.FileParser): """Parser for crontab files.""" output_types = ["CronTabFile"] supported_artifacts = ["LinuxCronTabs", "MacOSCronTabs"] def Parse(self, stat, file_object, knowledge_base): """Parse the crontab file.""" _ = knowledge_base entries = [] crondata = file_object.read() jobs = crontab.CronTab(tab=crondata) for job in jobs: entries.append( rdf_cronjobs.CronTabEntry( minute=utils.SmartStr(job.minute), hour=utils.SmartStr(job.hour), dayofmonth=utils.SmartStr(job.dom), month=utils.SmartStr(job.month), dayofweek=utils.SmartStr(job.dow), command=utils.SmartStr(job.command), comment=utils.SmartStr(job.comment))) try: source_urn = file_object.urn except AttributeError: source_urn = None yield rdf_cronjobs.CronTabFile(aff4path=source_urn, jobs=entries)
27.76087
69
0.688332
35ac13f82cfc6cf14b1a034ec44fd795ee4addc6
435
py
Python
mysite/app/migrations/0003_organisation_user_id.py
code-build-deploy/backend
8614a0e67f507944ad9ac759984acc8ddec28876
[ "MIT" ]
null
null
null
mysite/app/migrations/0003_organisation_user_id.py
code-build-deploy/backend
8614a0e67f507944ad9ac759984acc8ddec28876
[ "MIT" ]
null
null
null
mysite/app/migrations/0003_organisation_user_id.py
code-build-deploy/backend
8614a0e67f507944ad9ac759984acc8ddec28876
[ "MIT" ]
null
null
null
# Generated by Django 3.0.1 on 2019-12-27 15:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0002_auto_20191227_2030'), ] operations = [ migrations.AddField( model_name='organisation', name='user_id', field=models.CharField(default=0, max_length=512), preserve_default=False, ), ]
21.75
62
0.602299
5ad3ed11897d978e1e98cf86d08ccbb839a993ec
68
py
Python
test/code2of5.py
leo-b/elaphe
3cd075c8d7e2f587096715d4e7bc6ad8bd6df021
[ "BSD-2-Clause" ]
10
2017-05-18T01:33:31.000Z
2020-04-09T02:27:27.000Z
test/code2of5.py
leo-b/elaphe
3cd075c8d7e2f587096715d4e7bc6ad8bd6df021
[ "BSD-2-Clause" ]
14
2017-05-03T16:34:48.000Z
2022-02-25T19:07:43.000Z
test/code2of5.py
leo-b/elaphe
3cd075c8d7e2f587096715d4e7bc6ad8bd6df021
[ "BSD-2-Clause" ]
5
2017-07-12T19:38:24.000Z
2021-12-16T08:47:57.000Z
symbology = 'code2of5' cases = [ ('001.png', '01234567'), ]
13.6
28
0.529412
bb65a04f2ca6098988677aa5e7eed6d439bcffe2
517
py
Python
docs/version.py
UCLA-IRL/ndn-hydra
e01829253876ff6dbfd6dfaa92142eca08cd6705
[ "Apache-2.0" ]
2
2021-04-14T04:12:14.000Z
2021-04-23T02:28:49.000Z
docs/version.py
ZixuanZhong/hydra
e01829253876ff6dbfd6dfaa92142eca08cd6705
[ "Apache-2.0" ]
10
2021-07-03T18:29:26.000Z
2022-02-01T04:11:20.000Z
docs/version.py
ZixuanZhong/ndn-distributed-repo
e01829253876ff6dbfd6dfaa92142eca08cd6705
[ "Apache-2.0" ]
null
null
null
# ---------------------------------------------------------- # NDN Hydra Version # ---------------------------------------------------------- # @Project: NDN Hydra # @Date: 2021-01-25 # @Authors: Please check AUTHORS.rst # @Source-Code: https://github.com/UCLA-IRL/ndn-hydra # @Documentation: https://ndn-hydra.readthedocs.io/ # @Pip-Library: https://pypi.org/project/ndn-hydra/ # ---------------------------------------------------------- # Version of Hydra according to pip __version__ = "0.2.5"
39.769231
61
0.439072
15e19db95d0147ba42859ffd48f61c52c5b0df40
850
py
Python
sysinv/sysinv/sysinv/sysinv/tests/fake_policy.py
etaivan/stx-config
281e1f110973f96e077645fb01f67b646fc253cc
[ "Apache-2.0" ]
10
2020-02-07T18:57:44.000Z
2021-09-11T10:29:34.000Z
sysinv/sysinv/sysinv/sysinv/tests/fake_policy.py
etaivan/stx-config
281e1f110973f96e077645fb01f67b646fc253cc
[ "Apache-2.0" ]
1
2021-01-14T12:01:55.000Z
2021-01-14T12:01:55.000Z
sysinv/sysinv/sysinv/sysinv/tests/fake_policy.py
etaivan/stx-config
281e1f110973f96e077645fb01f67b646fc253cc
[ "Apache-2.0" ]
10
2020-10-13T08:37:46.000Z
2022-02-09T00:21:25.000Z
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 OpenStack Foundation # # 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. policy_data = """ { "admin_api": "role:admin", "admin_or_owner": "is_admin:True or project_id:%(project_id)s", "is_admin": "role:admin or role:administrator", "default": "rule:admin_or_owner" } """
32.692308
75
0.731765
446e5fcc1a11d1aeafd1b1179de3e0b06b812e60
3,477
py
Python
Med_Cabinet/data/StrainAPItoPG.py
RMDircio/Med_Cabinet_Data_Science
a8d33785a9bfe8d9beaa03c014c897d8d54a91b0
[ "MIT" ]
1
2020-08-04T08:29:15.000Z
2020-08-04T08:29:15.000Z
Med_Cabinet/data/StrainAPItoPG.py
RMDircio/Med_Cabinet_Data_Science
a8d33785a9bfe8d9beaa03c014c897d8d54a91b0
[ "MIT" ]
4
2020-06-19T03:49:01.000Z
2020-06-26T04:41:57.000Z
Med_Cabinet/data/StrainAPItoPG.py
RMDircio/Med_Cabinet_Data_Science
a8d33785a9bfe8d9beaa03c014c897d8d54a91b0
[ "MIT" ]
4
2020-06-17T03:21:25.000Z
2020-06-18T02:26:11.000Z
# StrainAPI.py # http://strains.evanbusse.com/index.html import os import requests import psycopg2 import json, sys from pprint import pprint from dotenv import load_dotenv from psycopg2 import connect, Error # Load contents of the .env file into the script's environment load_dotenv() # Connect to Elephant PG DB DB_NAME = os.getenv("DB_NAME") DB_USER = os.getenv("DB_USER") DB_PASSWORD = os.getenv("DB_PASSWORD") DB_HOST = os.getenv("DB_HOST") # Establish Elephant PG connection conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASSWORD, host=DB_HOST) print("CONNECTION:", conn) cur = conn.cursor() print("CURSOR:", cur) # Load Strain API Key from .env file and make API Get request from Strain API STRAIN_API_KEY = os.getenv("STRAIN_API_KEY") url = "http://strainapi.evanbusse.com/%s/strains/search/effect/EFFECT" % STRAIN_API_KEY response = requests.get(url) print(type(response)) #> <class 'requests.models.Response'> print(response.status_code) #> 200 print(type(response.text)) #> <class 'str'> dict_response = (response.text) # transforms the string response into a usable python datatype (list or dict) print(type(dict_response)) #> <class 'str'> # Output the results to the terminal #pprint(dict_response) # Use Python to read a JSON file record_list = json.loads(dict_response) # Evaluate the object returned by json.loads() to verify that it’s a list # and grab the first potential Postgres "record" if type(record_list) == list: first_record = record_list[0] # Use the Python dictionary’s keys() method to retrieve its “column” names in the form of a list # Get the column names from the first record columns = list(first_record.keys()) print ("\ncolumn names:", columns) # Create the Med_Cabinet Table cur.execute("CREATE TABLE Med_Cabinet(id INT, name VARCHAR, race VARCHAR, effect VARCHAR)") # Declare an SQL string for Postgres records table_name = "Med_Cabinet" sql_string = 'INSERT INTO {} '.format( table_name ) sql_string += "(" + ', '.join(columns) + ")\nVALUES " # Use Python to parse a JSON object # Enumerate over the record for i, record_dict in enumerate(record_list): # Iterate over the values of each record dict object values = [] for col_names, val in record_dict.items(): # Postgres strings must be enclosed with single quotes if type(val) == str: # Escape apostrophies with two single quotations val = val.replace("'", "''") val = "'" + val + "'" values += [ str(val) ] # Join the list of values and enclose record in parenthesis sql_string += "(" + ', '.join(values) + "),\n" # Remove the last comma and end statement with a semicolon sql_string = sql_string[:-2] + ";" # Output the results to the terminal #print ("\nSQL statement:") #print (sql_string) # Use psycopg2 to insert JSON data # Only attempt to execute SQL if cursor is valid if cur != None: try: cur.execute( sql_string ) conn.commit() print ('\nfinished INSERT INTO execution') except (Exception, Error) as error: print("\nexecute_sql() error:", error) conn.rollback() # Close the cursor and connection cur.close() conn.close() # If you want to remove all the inserted records from the Postgres table you can execute a # TRUNCATE TABLE table_name statement in ElephantSQL, followed by the table name, and all of the records will be deleted.
25.379562
125
0.700316
efa2275d2372695b1b93aff150047931c1513af6
2,018
py
Python
tests/unit/aws_interface/test_cloudwanderer_boto3_session.py
Sam-Martin/cloud-wanderer
1879f9bb150054be5bf33fd46a47414b4939529e
[ "MIT" ]
1
2020-12-07T10:37:41.000Z
2020-12-07T10:37:41.000Z
tests/unit/aws_interface/test_cloudwanderer_boto3_session.py
Sam-Martin/cloud-wanderer
1879f9bb150054be5bf33fd46a47414b4939529e
[ "MIT" ]
null
null
null
tests/unit/aws_interface/test_cloudwanderer_boto3_session.py
Sam-Martin/cloud-wanderer
1879f9bb150054be5bf33fd46a47414b4939529e
[ "MIT" ]
null
null
null
from unittest.mock import MagicMock from cloudwanderer.aws_interface import CloudWandererBoto3ClientConfig, CloudWandererBoto3Session def test_get_account_id_from_arg(): botocore_session = MagicMock() subject = CloudWandererBoto3Session(botocore_session=botocore_session, account_id="0123456789012") assert subject.get_account_id() == "0123456789012" botocore_session.create_client.assert_not_called() def test_get_account_id(): botocore_session = MagicMock() subject = CloudWandererBoto3Session( botocore_session=botocore_session, getter_client_config=CloudWandererBoto3ClientConfig(sts={"endpoint_url": "sts.eu-west-1.amazonaws.com"}), ) subject.get_account_id() botocore_session.create_client.assert_called_with( "sts", region_name=None, api_version=None, use_ssl=True, verify=None, endpoint_url="sts.eu-west-1.amazonaws.com", aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, config=None, ) def test_get_enabled_regions(): botocore_session = MagicMock() subject = CloudWandererBoto3Session( botocore_session=botocore_session, getter_client_config=CloudWandererBoto3ClientConfig(ec2={"endpoint_url": "ec2.eu-west-1.amazonaws.com"}), ) subject.get_enabled_regions() botocore_session.create_client.assert_called_with( "ec2", region_name=None, api_version=None, use_ssl=True, verify=None, endpoint_url="ec2.eu-west-1.amazonaws.com", aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, config=None, ) def test_get_enabled_regions_from_arg(): botocore_session = MagicMock() subject = CloudWandererBoto3Session(botocore_session=botocore_session, enabled_regions=["eu-west-1"]) assert subject.get_enabled_regions() == ["eu-west-1"] botocore_session.create_client.assert_not_called()
29.676471
113
0.721011
54b1aa82922e42a75ddd2b86beb0f2543ff0b3e8
3,717
py
Python
app.py
deobandana/SQLAlchemy-Challenge
dc50ac98a938a7f19b9e891610f00c3cfd31ae72
[ "ADSL" ]
null
null
null
app.py
deobandana/SQLAlchemy-Challenge
dc50ac98a938a7f19b9e891610f00c3cfd31ae72
[ "ADSL" ]
null
null
null
app.py
deobandana/SQLAlchemy-Challenge
dc50ac98a938a7f19b9e891610f00c3cfd31ae72
[ "ADSL" ]
null
null
null
from sqlalchemy import create_engine from sqlalchemy.orm import session from sqlalchemy.ext import automap from sqlalchemy import inspect from sqlalchemy import func import numpy as np from flask import Flask, jsonify engine = create_engine("sqlite:///hawaii.sqlite") Base = automap.automap_base() Base.prepare(engine, reflect = True) Measurement = Base.classes.measurement Station = Base.classes.station app = Flask(__name__) @app.route("/") def welcome(): return ( f"*****Welcome to Hawaii API*****<br/>" f"<br/>" f"Select The Available Routes :<br/>" f"********************************** <br/>" f"********************************** <br/>" f"For Precipitation Data :<br/>" f"/api/v1.0/precipitation<br/>" f"********************************** <br/>" f"For Station List :<br/>" f"/api/v1.0/stations<br/>" f"********************************** <br/>" f"For tobs for the previous year <br/>" f"/api/v1.0/tobs_MostActiveStation<br/>" f"********************************** <br/>" f"For TMIN, TAVG, and TMAX for all data >= Given Start Date <br/>" f"Replace Start Between Range 2016-08-23 to 2017-08-23 <br/>" f"/api/v1.0/start date<br/>" f"********************************** :<br/>" f"For TMIN, TAVG, and TMAX between Given range of date Including end Date <br/>" f"Replace Start and end Date Between range 2016-08-23 to 2017-08-23<br/>" f"/api/v1.0/start date/end date" ) @app.route("/api/v1.0/precipitation") def precipitation(): sess = session.Session(bind=engine) last_date_obs = sess.query(func.max(Measurement.date)).first() prcp_results = sess.query(Measurement.date, Measurement.prcp).\ filter((Measurement.date <= last_date_obs[0]) & (Measurement.date > "2016-08-23")).all() sess.close() prcp_list = [{"Date": date, "Prcp": prcp} for date, prcp in prcp_results] return jsonify(prcp_list) @app.route("/api/v1.0/stations") def stations(): sess = session.Session(bind=engine) results = sess.query(Station.station, Station.name).group_by(Station.station).all() sess.close() result_list = [{"Station": station, "Name": name} for station, name in results] return jsonify(result_list) @app.route("/api/v1.0/tobs_MostActiveStation") def tobs(): sess = session.Session(bind=engine) results = sess.query(Measurement.date, Measurement.tobs).\ filter(Measurement.date >= "2016-08-23").\ filter(Measurement.station == "USC00519281") sess.close() result_list = [{"Date": date, "Temp Obs": tobs} for date, tobs in results] return jsonify(result_list) @app.route("/api/v1.0/<start>") def temp_stats_v1(start): sess = session.Session(bind=engine) results = sess.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\ filter(Measurement.date >= start) sess.close() result_list = [{"Min Temp": tmin, "Max Temp": tmax, "Avg Temp": tavg} for tmin, tavg, tmax in results] return jsonify(result_list) @app.route("/api/v1.0/<start>/<end>") def temp_stats_v2(start, end): sess = session.Session(bind=engine) results = sess.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\ filter(Measurement.date >= start).\ filter(Measurement.date <= end).all() sess.close() result_list = [{"Min Temp": tmin, "Max Temp": tmax, "Avg Temp": tavg} for tmin, tavg, tmax in results] return jsonify(result_list) if __name__ == "__main__": app.run(debug=True)
34.416667
110
0.602098
ff0f168fb50f12c330ff817db43b179040a45860
9,260
py
Python
6.Graphs/DFS.py
qrzhang/Udacity_Data_Structure_Algorithms
5b65088884d93e7fcd53b7fcf888e378b514ba2a
[ "MIT" ]
null
null
null
6.Graphs/DFS.py
qrzhang/Udacity_Data_Structure_Algorithms
5b65088884d93e7fcd53b7fcf888e378b514ba2a
[ "MIT" ]
null
null
null
6.Graphs/DFS.py
qrzhang/Udacity_Data_Structure_Algorithms
5b65088884d93e7fcd53b7fcf888e378b514ba2a
[ "MIT" ]
null
null
null
""" DFS: Depth-First Search BFS: Breadth-First Search """ class Node(object): def __init__(self, value): self.value = value self.edges = [] self.visited = False class Edge(object): def __init__(self, value, node_from, node_to): self.value = value self.node_from = node_from self.node_to = node_to # You only need to change code with docs strings that have TODO. # Specifically: Graph.dfs_helper and Graph.bfs # New methods have been added to associate node numbers with names # Specifically: Graph.set_node_names # and the methods ending in "_names" which will print names instead # of node numbers class Graph(object): def __init__(self, nodes=None, edges=None): self.nodes = nodes or [] self.edges = edges or [] self.node_names = [] self._node_map = {} def set_node_names(self, names): """The Nth name in names should correspond to node number N. Node numbers are 0 based (starting at 0). """ self.node_names = list(names) def insert_node(self, new_node_val): "Insert a new node with value new_node_val" new_node = Node(new_node_val) self.nodes.append(new_node) self._node_map[new_node_val] = new_node return new_node def insert_edge(self, new_edge_val, node_from_val, node_to_val): "Insert a new edge, creating new nodes if necessary" nodes = {node_from_val: None, node_to_val: None} for node in self.nodes: if node.value in nodes: nodes[node.value] = node if all(nodes.values()): break for node_val in nodes: nodes[node_val] = nodes[node_val] or self.insert_node(node_val) node_from = nodes[node_from_val] node_to = nodes[node_to_val] new_edge = Edge(new_edge_val, node_from, node_to) node_from.edges.append(new_edge) node_to.edges.append(new_edge) self.edges.append(new_edge) def get_edge_list(self): """Return a list of triples that looks like this: (Edge Value, From Node, To Node)""" return [(e.value, e.node_from.value, e.node_to.value) for e in self.edges] def get_edge_list_names(self): """Return a list of triples that looks like this: (Edge Value, From Node Name, To Node Name)""" return [(edge.value, self.node_names[edge.node_from.value], self.node_names[edge.node_to.value]) for edge in self.edges] def get_adjacency_list(self): """Return a list of lists. The indecies of the outer list represent "from" nodes. Each section in the list will store a list of tuples that looks like this: (To Node, Edge Value)""" max_index = self.find_max_index() adjacency_list = [[] for _ in range(max_index)] for edg in self.edges: from_value, to_value = edg.node_from.value, edg.node_to.value adjacency_list[from_value].append((to_value, edg.value)) return [a or None for a in adjacency_list] # replace []'s with None def get_adjacency_list_names(self): """Each section in the list will store a list of tuples that looks like this: (To Node Name, Edge Value). Node names should come from the names set with set_node_names.""" adjacency_list = self.get_adjacency_list() def convert_to_names(pair, graph=self): node_number, value = pair return (graph.node_names[node_number], value) def map_conversion(adjacency_list_for_node): if adjacency_list_for_node is None: return None return map(convert_to_names, adjacency_list_for_node) return [map_conversion(adjacency_list_for_node) for adjacency_list_for_node in adjacency_list] def get_adjacency_matrix(self): """Return a matrix, or 2D list. Row numbers represent from nodes, column numbers represent to nodes. Store the edge values in each spot, and a 0 if no edge exists.""" max_index = self.find_max_index() adjacency_matrix = [[0] * (max_index) for _ in range(max_index)] for edg in self.edges: from_index, to_index = edg.node_from.value, edg.node_to.value adjacency_matrix[from_index][to_index] = edg.value return adjacency_matrix def find_max_index(self): """Return the highest found node number Or the length of the node names if set with set_node_names().""" if len(self.node_names) > 0: return len(self.node_names) max_index = -1 if len(self.nodes): for node in self.nodes: if node.value > max_index: max_index = node.value return max_index def find_node(self, node_number): "Return the node with value node_number or None" return self._node_map.get(node_number) def _clear_visited(self): for node in self.nodes: node.visited = False def dfs_helper(self, start_node): """TODO: Write the helper function for a recursive implementation of Depth First Search iterating through a node's edges. The output should be a list of numbers corresponding to the values of the traversed nodes. ARGUMENTS: start_node is the starting Node MODIFIES: the value of the visited property of nodes in self.nodes RETURN: a list of the traversed node values (integers). """ ret_list = [start_node.value] # Your code here return ret_list def dfs(self, start_node_num): """Outputs a list of numbers corresponding to the traversed nodes in a Depth First Search. ARGUMENTS: start_node_num is the starting node number (integer) MODIFIES: the value of the visited property of nodes in self.nodes RETURN: a list of the node values (integers).""" self._clear_visited() start_node = self.find_node(start_node_num) return self.dfs_helper(start_node) def dfs_names(self, start_node_num): """Return the results of dfs with numbers converted to names.""" return [self.node_names[num] for num in self.dfs(start_node_num)] def bfs(self, start_node_num): """TODO: Create an iterative implementation of Breadth First Search iterating through a node's edges. The output should be a list of numbers corresponding to the traversed nodes. ARGUMENTS: start_node_num is the node number (integer) MODIFIES: the value of the visited property of nodes in self.nodes RETURN: a list of the node values (integers).""" node = self.find_node(start_node_num) self._clear_visited() ret_list = [node.value] # Your code here return ret_list def bfs_names(self, start_node_num): """Return the results of bfs with numbers converted to names.""" return [self.node_names[num] for num in self.bfs(start_node_num)] graph = Graph() # You do not need to change anything below this line. # You only need to implement Graph.dfs_helper and Graph.bfs graph.set_node_names(('Mountain View', # 0 'San Francisco', # 1 'London', # 2 'Shanghai', # 3 'Berlin', # 4 'Sao Paolo', # 5 'Bangalore')) # 6 graph.insert_edge(51, 0, 1) # MV <-> SF graph.insert_edge(51, 1, 0) # SF <-> MV graph.insert_edge(9950, 0, 3) # MV <-> Shanghai graph.insert_edge(9950, 3, 0) # Shanghai <-> MV graph.insert_edge(10375, 0, 5) # MV <-> Sao Paolo graph.insert_edge(10375, 5, 0) # Sao Paolo <-> MV graph.insert_edge(9900, 1, 3) # SF <-> Shanghai graph.insert_edge(9900, 3, 1) # Shanghai <-> SF graph.insert_edge(9130, 1, 4) # SF <-> Berlin graph.insert_edge(9130, 4, 1) # Berlin <-> SF graph.insert_edge(9217, 2, 3) # London <-> Shanghai graph.insert_edge(9217, 3, 2) # Shanghai <-> London graph.insert_edge(932, 2, 4) # London <-> Berlin graph.insert_edge(932, 4, 2) # Berlin <-> London graph.insert_edge(9471, 2, 5) # London <-> Sao Paolo graph.insert_edge(9471, 5, 2) # Sao Paolo <-> London # (6) 'Bangalore' is intentionally disconnected (no edges) # for this problem and should produce None in the # Adjacency List, etc. import pprint pp = pprint.PrettyPrinter(indent=2) print(pp.pprint(graph.get_edge_list_names())) "Edge List" print(pp.pprint(graph.get_adjacency_list_names())) "\nAdjacency List" print(pp.pprint(graph.get_adjacency_matrix())) "\nAdjacency Matrix" print(pp.pprint(graph.dfs_names(2))) "\nDepth First Search" # Should print: # Depth First Search # ['London', 'Shanghai', 'Mountain View', 'San Francisco', 'Berlin', 'Sao Paolo'] print(pp.pprint(graph.bfs_names(2))) "\nBreadth First Search" # test error reporting # pp.pprint(['Sao Paolo', 'Mountain View', 'San Francisco', 'London', 'Shanghai', 'Berlin']) # Should print: # Breadth First Search # ['London', 'Shanghai', 'Berlin', 'Sao Paolo', 'Mountain View', 'San Francisco']
37.04
92
0.640173
f43f933aceb4b1341a1d461cfb6098eab4b7ff47
1,926
py
Python
ck_baidu_url_submit.py
wqdyteam/checkinpanel
69c591a2eed37b9b9f44aa4f940f57d070a19e4d
[ "MIT" ]
14
2021-11-15T02:56:51.000Z
2022-03-05T16:47:21.000Z
ck_baidu_url_submit.py
wqdyteam/checkinpanel
69c591a2eed37b9b9f44aa4f940f57d070a19e4d
[ "MIT" ]
null
null
null
ck_baidu_url_submit.py
wqdyteam/checkinpanel
69c591a2eed37b9b9f44aa4f940f57d070a19e4d
[ "MIT" ]
5
2021-11-04T09:54:08.000Z
2022-02-23T09:44:59.000Z
# -*- coding: utf-8 -*- """ cron: 32 7 * * * new Env('百度搜索资源平台'); """ from urllib import parse import requests from notify_mtr import send from utils import get_data class BaiduUrlSubmit: def __init__(self, check_items): self.check_items = check_items @staticmethod def url_submit(data_url: str, submit_url: str, times: int = 100) -> str: site = parse.parse_qs(parse.urlsplit(submit_url).query).get("site")[0] urls_data = requests.get(url=data_url) remain = 100000 success_count = 0 error_count = 0 for _ in range(times): try: response = requests.post(url=submit_url, data=urls_data) if response.json().get("success"): remain = response.json().get("remain") success_count += response.json().get("success") else: error_count += 1 except Exception as e: print(e) error_count += 1 msg = ( f"站点地址: {site}\n当天剩余的可推送 url 条数: {remain}\n成功推送的 url 条数: {success_count}\n" f"成功推送的 url 次数: {times - error_count}\n失败推送的 url 次数: {error_count}" ) return msg def main(self): msg_all = "" for check_item in self.check_items: data_url = check_item.get("data_url") submit_url = check_item.get("submit_url") times = int(check_item.get("times", 100)) if data_url and submit_url: msg = self.url_submit( data_url=data_url, submit_url=submit_url, times=times ) else: msg = "配置错误" msg_all += msg + "\n\n" return msg_all if __name__ == "__main__": data = get_data() _check_items = data.get("BAIDU", []) res = BaiduUrlSubmit(check_items=_check_items).main() send("百度搜索资源平台", res)
30.09375
87
0.550883
85d549ec14a2a2979676787d1a927602b136f998
5,811
py
Python
train.py
cptbtptp2333/style-token_tacotron2
8268a55d6a58fc722158ec360fc4f0b4bfbca7b1
[ "MIT" ]
60
2018-12-10T00:31:35.000Z
2022-03-10T18:24:01.000Z
train.py
cptbtptp2333/style-token_tacotron2
8268a55d6a58fc722158ec360fc4f0b4bfbca7b1
[ "MIT" ]
12
2019-04-16T10:33:04.000Z
2020-12-28T11:00:19.000Z
train.py
cptbtptp2333/style-token_tacotron2
8268a55d6a58fc722158ec360fc4f0b4bfbca7b1
[ "MIT" ]
22
2019-03-16T06:57:01.000Z
2021-05-25T01:13:15.000Z
import argparse import os from time import sleep import infolog import tensorflow as tf from hparams import hparams from infolog import log from tacotron.synthesize import tacotron_synthesize from tacotron.train import tacotron_train from wavenet_vocoder.train import wavenet_train log = infolog.log def save_seq(file, sequence, input_path): '''Save Tacotron-2 training state to disk. (To skip for future runs) ''' sequence = [str(int(s)) for s in sequence] + [input_path] with open(file, 'w') as f: f.write('|'.join(sequence)) def read_seq(file): '''Load Tacotron-2 training state from disk. (To skip if not first run) ''' if os.path.isfile(file): with open(file, 'r') as f: sequence = f.read().split('|') return [bool(int(s)) for s in sequence[:-1]], sequence[-1] else: return [0, 0, 0], '' def prepare_run(args): modified_hp = hparams.parse(args.hparams) os.environ['TF_CPP_MIN_LOG_LEVEL'] = str(args.tf_log_level) run_name = args.name or args.model log_dir = os.path.join(args.base_dir, 'logs-{}'.format(run_name)) os.makedirs(log_dir, exist_ok=True) infolog.init(os.path.join(log_dir, 'Terminal_train_log'), run_name, args.slack_url) return log_dir, modified_hp def train(args, log_dir, hparams): state_file = os.path.join(log_dir, 'state_log') #Get training states (taco_state, GTA_state, wave_state), input_path = read_seq(state_file) if not taco_state: log('\n#############################################################\n') log('Tacotron Train\n') log('###########################################################\n') checkpoint = tacotron_train(args, log_dir, hparams) tf.reset_default_graph() #Sleep 1/2 second to let previous graph close and avoid error messages while synthesis sleep(0.5) if checkpoint is None: raise('Error occured while training Tacotron, Exiting!') taco_state = 1 save_seq(state_file, [taco_state, GTA_state, wave_state], input_path) else: checkpoint = os.path.join(log_dir, 'taco_pretrained/') if not GTA_state: log('\n#############################################################\n') log('Tacotron GTA Synthesis\n') log('###########################################################\n') input_path = tacotron_synthesize(args, hparams, checkpoint) tf.reset_default_graph() #Sleep 1/2 second to let previous graph close and avoid error messages while Wavenet is training sleep(0.5) GTA_state = 1 save_seq(state_file, [taco_state, GTA_state, wave_state], input_path) else: input_path = os.path.join('tacotron_' + args.output_dir, 'gta', 'map.txt') if input_path == '' or input_path is None: raise RuntimeError('input_path has an unpleasant value -> {}'.format(input_path)) if not wave_state: log('\n#############################################################\n') log('Wavenet Train\n') log('###########################################################\n') checkpoint = wavenet_train(args, log_dir, hparams, input_path) if checkpoint is None: raise ('Error occured while training Wavenet, Exiting!') wave_state = 1 save_seq(state_file, [taco_state, GTA_state, wave_state], input_path) if wave_state and GTA_state and taco_state: log('TRAINING IS ALREADY COMPLETE!!') def main(): parser = argparse.ArgumentParser() parser.add_argument('--base_dir', default='') parser.add_argument('--hparams', default='', help='Hyperparameter overrides as a comma-separated list of name=value pairs') parser.add_argument('--tacotron_input', default='training_data/train.txt') parser.add_argument('--wavenet_input', default='tacotron_output/gta/map.txt') parser.add_argument('--name', help='Name of logging directory.') parser.add_argument('--model', default='Tacotron-2') parser.add_argument('--input_dir', default='training_data', help='folder to contain inputs sentences/targets') parser.add_argument('--output_dir', default='output', help='folder to contain synthesized mel spectrograms') parser.add_argument('--mode', default='synthesis', help='mode for synthesis of tacotron after training') parser.add_argument('--GTA', default='True', help='Ground truth aligned synthesis, defaults to True, only considered in Tacotron synthesis mode') parser.add_argument('--restore', type=bool, default=True, help='Set this to False to do a fresh training') parser.add_argument('--summary_interval', type=int, default=250, help='Steps between running summary ops') parser.add_argument('--embedding_interval', type=int, default=10000, help='Steps between updating embeddings projection visualization') parser.add_argument('--checkpoint_interval', type=int, default=5000, help='Steps between writing checkpoints') parser.add_argument('--eval_interval', type=int, default=10000, help='Steps between eval on test data') parser.add_argument('--tacotron_train_steps', type=int, default=400000, help='total number of tacotron training steps') parser.add_argument('--wavenet_train_steps', type=int, default=750000, help='total number of wavenet training steps') parser.add_argument('--tf_log_level', type=int, default=1, help='Tensorflow C++ log level.') parser.add_argument('--slack_url', default=None, help='slack webhook notification destination link') args = parser.parse_args() accepted_models = ['Tacotron', 'WaveNet', 'Tacotron-2'] if args.model not in accepted_models: raise ValueError('please enter a valid model to train: {}'.format(accepted_models)) log_dir, hparams = prepare_run(args) if args.model == 'Tacotron': tacotron_train(args, log_dir, hparams) elif args.model == 'WaveNet': wavenet_train(args, log_dir, hparams, args.wavenet_input) elif args.model == 'Tacotron-2': train(args, log_dir, hparams) else: raise ValueError('Model provided {} unknown! {}'.format(args.model, accepted_models)) if __name__ == '__main__': main()
41.805755
146
0.696266
5e81a4e894499dd793699c3c9f485cc86c3194e8
2,904
py
Python
experiments/task71/train_bert.py
manzar96/st7
8dac6fa3497e5a3594766a232a9e8436120e9563
[ "MIT" ]
null
null
null
experiments/task71/train_bert.py
manzar96/st7
8dac6fa3497e5a3594766a232a9e8436120e9563
[ "MIT" ]
null
null
null
experiments/task71/train_bert.py
manzar96/st7
8dac6fa3497e5a3594766a232a9e8436120e9563
[ "MIT" ]
null
null
null
import math import torch import torch.nn as nn from tqdm import tqdm from torch.optim import Adam from torch.utils.data import DataLoader from transformers import BertTokenizer, BertModel from core.data.dataset import Task71Dataset from core.data.collators import Task71aCollator from core.models.modules.heads import BertClassificationHead from core.trainers import BertTrainer from core.utils.parser import get_train_parser DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu' print(DEVICE) # get args from cmdline parser = get_train_parser() options = parser.parse_args() # make transforms using only bert tokenizer! tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') # CLS token will work as BOS token # tokenizer.bos_token = tokenizer.cls_token # SEP token will work as EOS token # tokenizer.eos_token = tokenizer.sep_token # load dataset dataset = Task71Dataset("train", tokenizer=tokenizer) train_dataset, val_dataset = torch.utils.data.random_split(dataset, [7200, 800], generator=torch.Generator().manual_seed(42)) collator_fn = Task71aCollator(device='cpu') train_loader = DataLoader(train_dataset, batch_size=options.batch_size, drop_last=False, shuffle=True, collate_fn=collator_fn) val_loader = DataLoader(val_dataset, batch_size=options.batch_size, drop_last=False, shuffle=True, collate_fn=collator_fn) # create model encoder = BertModel.from_pretrained('bert-base-uncased') # change config if you want # encoder.config.output_hidden_states = True model = BertClassificationHead(encoder, encoder.config.hidden_size, num_classes=2, drop=0.2) if options.modelckpt is not None: state_dict = torch.load(options.modelckpt,map_location='cpu') model.load_state_dict(state_dict) model.to(DEVICE) # params and optimizer numparams = sum([p.numel() for p in model.parameters()]) train_numparams = sum([p.numel() for p in model.parameters() if p.requires_grad]) print('Total Parameters: {}'.format(numparams)) print('Trainable Parameters: {}'.format(train_numparams)) optimizer = Adam( [p for p in model.parameters() if p.requires_grad], lr=options.lr, weight_decay=1e-6) criterion = nn.CrossEntropyLoss(ignore_index=-100) metrics = ['f1-score','accuracy'] import ipdb;ipdb.set_trace() # create trainer trainer = BertTrainer(model=model, optimizer=optimizer, criterion=criterion, metrics=metrics, checkpoint_max=True, checkpoint_with='f1-score', patience=5, scheduler=None, checkpoint_dir=options.ckpt, device=DEVICE) # train model trainer.fit(train_loader, val_loader, epochs=options.epochs)
35.851852
76
0.694559
5c2cf031380b5eeaab309d65dcbad54b010fc818
4,794
py
Python
Content/Networking/Route53/WorkloadManager/src/awsroute53/prerequiste_environments.py
saikirangurijal/cloudcentersuite
5fd1907fdd1c32a8a575e2671b6a9ed9f68f2875
[ "Apache-2.0" ]
8
2018-12-19T00:37:59.000Z
2020-07-16T15:05:40.000Z
Content/Networking/Route53/WorkloadManager/src/awsroute53/prerequiste_environments.py
saikirangurijal/cloudcentersuite
5fd1907fdd1c32a8a575e2671b6a9ed9f68f2875
[ "Apache-2.0" ]
2
2019-03-26T17:53:20.000Z
2019-11-26T15:26:00.000Z
Content/Networking/Route53/WorkloadManager/src/awsroute53/prerequiste_environments.py
saikirangurijal/cloudcentersuite
5fd1907fdd1c32a8a575e2671b6a9ed9f68f2875
[ "Apache-2.0" ]
9
2019-01-09T06:55:48.000Z
2019-11-27T17:55:03.000Z
"This method is used to get the details from user and assigning to domain creation json" import json,os import re,sys from util import print_error,print_log,print_result,write_error try: currentworkingdir = os.getcwd() filename = os.path.join(currentworkingdir, "createrecordset.json") print("filename is :",filename) with open(filename, 'r') as file: json_data = json.load(file) global json_data print(json_data) except IOError as ioerr: print_error(ioerr) write_error(ioerr) sys.exit(127) try: #Getting inputs from user for creaating sub domain and health check from environment variable. domainName = os.environ["DomainName"] subDomainName = os.environ["subDomainName"] dependents = os.environ.get('CliqrDependencies', "") if os.environ["IpAddress"]: IpAddress = os.environ["IpAddress"] else: if len(dependents) > 0: IpAddress = str(os.environ['CliqrTier_' + dependents + '_PUBLIC_IP']) print("my instances Ip address is : ===================>{}".format(IpAddress)) healthCheckport = os.environ["healthCheckport"] healthCheckpath = os.environ["healthCheckpath"] except Exception as er: print_error("Required parameter is missing .") print_error(er) sys.exit(127) def create_domain_json(): json_data["AdminContact"]["FirstName"] = "" json_data["AdminContact"]["LastName"] = "" json_data["AdminContact"]["ContactType"] = "" json_data["AdminContact"]["OrganizationName"] = "" json_data["AdminContact"]["AddressLine1"] = "" json_data["AdminContact"]["AddressLine2"] = "" json_data["AdminContact"]["City"] = "" json_data["AdminContact"]["PhoneNumber"] = "" json_data["AdminContact"]["State"] = "" json_data["AdminContact"]["CountryCode"] = "" json_data["AdminContact"]["ZipCode"] = "" json_data["AdminContact"]["Email"] = "" # json_data["AdminContact"]["FAX"] = "" json_data["RegistrantContact"]["FirstName"] = "" json_data["RegistrantContact"]["LastName"] = "" json_data["RegistrantContact"]["ContactType"] = "" json_data["RegistrantContact"]["OrganizationName"] = "" json_data["RegistrantContact"]["AddressLine1"] = "" json_data["RegistrantContact"]["AddressLine2"] = "" json_data["RegistrantContact"]["City"] = "" json_data["RegistrantContact"]["PhoneNumber"] = "" json_data["RegistrantContact"]["State"] = "" json_data["RegistrantContact"]["CountryCode"] = "" json_data["RegistrantContact"]["ZipCode"] = "" json_data["RegistrantContact"]["Email"] = "" # json_data["RegistrantContact"]["FAX"] = "" json_data["TechContact"]["FirstName"] = "" json_data["TechContact"]["LastName"] = "" json_data["TechContact"]["ContactType"] = "" json_data["TechContact"]["OrganizationName"] = "" json_data["TechContact"]["AddressLine1"] = "" json_data["TechContact"]["AddressLine2"] = "" json_data["TechContact"]["City"] = "" json_data["TechContact"]["PhoneNumber"] = "" json_data["TechContact"]["State"] = "" json_data["TechContact"]["CountryCode"] = "" json_data["TechContact"]["ZipCode"] = "" json_data["TechContact"]["Email"] = "" # json_data["TechContact"]["FAX"] = "" return json_data def create_record_set_json(): json_data["Changes"]["Changes"][0]["Action"] = "UPSERT" subName = subDomainName+"."+domainName print("subDomainName is :",subName) json_data["Changes"]["Changes"][0]["ResourceRecordSet"]["Name"] = subName json_data["Changes"]["Changes"][0]["ResourceRecordSet"]["TTL"] = 60 json_data["Changes"]["Changes"][0]["ResourceRecordSet"]["ResourceRecords"][0]["Value"] = IpAddress return json_data def delete_record_set_json(): json_data["Changes"]["Changes"][0]["Action"] = "DELETE" subName = subDomainName+"."+domainName print("subDomainName is :", subName) json_data["Changes"]["Changes"][0]["ResourceRecordSet"]["Name"] = subName json_data["Changes"]["Changes"][0]["ResourceRecordSet"]["TTL"] = 60 json_data["Changes"]["Changes"][0]["ResourceRecordSet"]["ResourceRecords"][0]["Value"] = IpAddress return json_data def create_healthcheck(): json_data["HealthCheckConfig"]["IPAddress"]= str(IpAddress) print(type(healthCheckport)) json_data["HealthCheckConfig"]["Port"]= int(healthCheckport) json_data["HealthCheckConfig"]["Type"]= "HTTP" json_data["HealthCheckConfig"]["FullyQualifiedDomainName"]=subDomainName+"."+domainName json_data["HealthCheckConfig"]["ResourcePath"]= healthCheckpath # json_data["HealthCheckConfig"]["ResourcePath"] = "/ui/auth/login", json_data["HealthCheckConfig"]["RequestInterval"]= 30 json_data["HealthCheckConfig"]["FailureThreshold"]= 5 return json_data
40.285714
102
0.666667
4b6f46ddc0a7f57d7f0688762801a66ba6de06ff
166
py
Python
allennlp_models/tagging/dataset_readers/conll2003.py
matt-peters/allennlp-models
cdd505ed539fdc2b82e4cc0a23eae4bfd3368e7e
[ "Apache-2.0" ]
402
2020-03-11T22:58:35.000Z
2022-03-29T09:05:27.000Z
allennlp_models/tagging/dataset_readers/conll2003.py
matt-peters/allennlp-models
cdd505ed539fdc2b82e4cc0a23eae4bfd3368e7e
[ "Apache-2.0" ]
116
2020-03-11T01:26:57.000Z
2022-03-25T13:03:56.000Z
allennlp_models/tagging/dataset_readers/conll2003.py
matt-peters/allennlp-models
cdd505ed539fdc2b82e4cc0a23eae4bfd3368e7e
[ "Apache-2.0" ]
140
2020-03-11T00:51:35.000Z
2022-03-29T09:05:36.000Z
from allennlp.data.dataset_readers.conll2003 import Conll2003DatasetReader # noqa: F401 # This component lives in the main repo because we need it there for tests.
41.5
88
0.813253
c832329cb4d2f91ef90f482f4db65dd1e6730f43
7,683
py
Python
Scripts/PredictandEvaluate/pred13.py
ankita-2015/Indian-Driving-Dataset-Semantic-Segmentation
8b8a9c9489c209c819bb46138d9b674b2dd085a5
[ "MIT" ]
null
null
null
Scripts/PredictandEvaluate/pred13.py
ankita-2015/Indian-Driving-Dataset-Semantic-Segmentation
8b8a9c9489c209c819bb46138d9b674b2dd085a5
[ "MIT" ]
null
null
null
Scripts/PredictandEvaluate/pred13.py
ankita-2015/Indian-Driving-Dataset-Semantic-Segmentation
8b8a9c9489c209c819bb46138d9b674b2dd085a5
[ "MIT" ]
null
null
null
import matplotlib.pyplot as plt import numpy as np import matplotlib.patches as mpatches import tensorflow as tf from glob import glob from tqdm import tqdm import pandas as pd import keras from tensorflow.keras import backend as k import gc import warnings warnings.filterwarnings('ignore') AUTOTUNE = tf.data.experimental.AUTOTUNE def convert_to_rgb(predi,_cmap={}): pred_image = np.zeros((predi.shape[0], predi.shape[1], 3),dtype=np.uint8) + 255 for i in np.unique(predi): pred_image[predi==i] = _cmap[i] return pred_image def plot_imgs(i,img,mask,pred=np.zeros((1024,1024,3)),cmap={},mask_labels={},label_iou={}): fig,(ax1,ax2,ax3, ax4) = plt.subplots(1,4,figsize=(20,4)) if img.shape[-1]==3: ax1.imshow(img) else: ax1.imshow(img,cmap=plt.get_cmap('gray')) ax1.axis('off') ax1.title.set_text(f"Input Image {i}") ax2.imshow(mask) ax2.axis('off') ax2.title.set_text(f"Ground truth {i}") ax3.imshow(pred) ax3.axis('off') ax3.title.set_text(f"Prediction {i}") dst = cv2.addWeighted(np.asarray(img*255.0,dtype=np.uint8),1,pred,0.5,0) ax4.imshow(dst) ax4.axis('off') patches = [ mpatches.Patch(color=np.array(cmap[i])/255.0, label="{:<15}:{:2.3f} ".format(mask_labels[i],label_iou[i])) for i in label_iou.keys()] plt.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0. ) # path = "xception/output_result" if not os.path.exists(path): os.mkdir(path) img_name = f"{i}.png" # fig.set_size_inches(25, 10) plt.savefig(f'{path}/{img_name}', dpi=100) # plt.show() plt.close(fig) def IoU(Yi,y_predi,mask_labels={}): ## mean Intersection over Union ## Mean IoU = TP/(FN + TP + FP) IoUs = [] precisions = [] recalls = [] f1_scores=[] f2_scores=[] # dice_scores = [] labels_iou = {} for c in mask_labels.keys(): TP = np.sum( (Yi == c)&(y_predi==c) ) FP = np.sum( (Yi != c)&(y_predi==c) ) FN = np.sum( (Yi == c)&(y_predi != c)) TN = np.sum( (Yi != c)&(y_predi != c)) IoU = TP/float(TP + FP + FN) precision = TP/float(TP + FP) recall = TP/float(TP + FN) beta= 1 f1_score = ((1+beta**2)*precision*recall)/float(beta**2*precision + recall) beta= 2 f2_score = ((1+beta**2)*precision*recall)/float(beta**2*precision + recall) # dice_score = (2*TP)/float(2*TP + FP + FN) if IoU > 0: # print("class {:2.0f} {:10}:\t TP= {:6.0f},\t FP= {:6.0f},\t FN= {:6.0f},\t TN= {:6.0f},\t IoU= {:6.3f}".format(c,mask_labels[c],TP,FP,FN,TN,IoU)) labels_iou[c] = IoU IoUs.append(IoU) precisions.append(precision) recalls.append(recall) f1_scores.append(f1_score) f2_scores.append(f2_score) # dice_scores.append(dice_score) mIoU = np.mean(IoUs) labels_iou[len(req_mask_labels)-1] = mIoU # print("Mean IoU: {:4.6f}".format(mIoU)) return labels_iou, [mIoU, np.mean(precisions),np.mean(recalls),np.mean(f1_scores), np.mean(f2_scores)] def parse_x_y(img_path,mask_path): image = tf.io.read_file(img_path) image = tf.image.decode_png(image, channels=3) image = tf.image.convert_image_dtype(image, tf.uint8) mask = tf.io.read_file(mask_path) mask = tf.image.decode_png(mask, channels=1) return {'image': image, 'segmentation_mask': mask} @tf.function def normalize(input_image: tf.Tensor, input_mask: tf.Tensor) -> tuple: input_image = tf.cast(input_image, tf.float32) / 255.0 return input_image, input_mask @tf.function def load_image_train(datapoint: dict) -> tuple: input_image = tf.image.resize(datapoint['image'], (512,512)) input_mask = tf.image.resize(datapoint['segmentation_mask'], IMG_SIZE,method='nearest') # if tf.random.uniform(()) > 0.5: # input_image = tf.image.flip_left_right(input_image) # input_mask = tf.image.flip_left_right(input_mask) input_image, input_mask = normalize(input_image, input_mask) input_mask = tf.one_hot(input_mask, 3) input_mask = tf.reshape(input_mask, (IMG_SIZE[0], IMG_SIZE[1], 3)) return input_image, input_mask columns=["Image_name", "mIoU", "Precision", "Recall", "F1-score(Dice-score)","F2-score"] def make_predictions(model, csv_path, test_images_folder_path, test_mask_folder_path): test_x = glob(test_images_folder_path) test_y = glob(test_mask_folder_path) test_x.sort() test_y.sort() test_dataset = tf.data.Dataset.from_tensor_slices((test_x,test_y)) test_dataset = test_dataset.map(parse_x_y) dataset = {"test": test_dataset} dataset['test'] = dataset['test'].map(load_image_train, num_parallel_calls=tf.data.experimental.AUTOTUNE ).batch(BATCH_SIZE) df = pd.DataFrame(columns=columns) for j in tqdm(range(0,len(test_x),BATCH_SIZE)): img, mask = next(iter(dataset['test'] )) y_pred = model.predict(img) k.clear_session() gc.collect() for i in range(BATCH_SIZE): maski = np.squeeze(np.argmax(mask[i], axis=-1)) y_predi = tf.image.resize(y_pred[i],IMG_SIZE ,method='nearest') y_predi = np.squeeze(np.argmax(y_predi, axis=-1)) label_iou, eval_=IoU(maski, y_predi, mask_labels=req_mask_labels) # input_img = img[i] input_img = tf.image.resize(img[i],IMG_SIZE ,method='nearest') ground_truth = np.squeeze(convert_to_rgb(maski, req_cmap)) prediction = np.squeeze(convert_to_rgb(y_predi, req_cmap)) plot_imgs(i+j+1,input_img, ground_truth, prediction,cmap=req_cmap,mask_labels=req_mask_labels,label_iou=label_iou) df = df.append(pd.Series([f"Image {i+j+1}",*eval_], index=columns), ignore_index=True) df.to_csv(csv_path,index=False) return df ## mobilenetv2 edge import tensorflow as tf import os import numpy as np import cv2 from segmentation_models.losses import cce_jaccard_loss, dice_loss, JaccardLoss from segmentation_models.metrics import iou_score, f1_score, precision, recall ls = dice_loss + cce_jaccard_loss metrics = [precision, recall, f1_score, iou_score] from tensorflow.keras.models import load_model import sys foldername = sys.argv[1] epoch_num = sys.argv[2] use_org_img_size = sys.argv[3] model = load_model(f'../../RESULTS/{foldername}/ckpt_path/{epoch_num}.h5', custom_objects={'dice_loss_plus_categorical_crossentropy_plus_jaccard_loss':ls, 'precision':precision, 'recall':recall, 'f1-score':f1_score, 'iou_score':iou_score}) path = f"../../RESULTS/{foldername}/output_result_BDD" csv_path = f"../../RESULTS/{foldername}/TestResult_{epoch_num}_BDD.csv" IDD_size = (1080,1920) BDD_size = (720,1280) CS_size = (1024,2048) if use_org_img_size=="True": IMG_SIZE = BDD_size else: IMG_SIZE = (512,512) BATCH_SIZE = 20 req_cmap = { 0: (0,0,0), # background 1: (255,0,0), # road 2: (0, 0, 255), #obstacle 3: (255,255,255) # miou label } req_mask_labels = { 0:"Background", 1:"Road", 2:"Obstacle", 3:"miou" } test_images_folder_path = "../../Dataset/BDD/Test/images/*" test_mask_folder_path="../../Dataset/BDD/Test/masks/*" df = make_predictions(model,csv_path, test_images_folder_path, test_mask_folder_path)
35.40553
179
0.626838
584810b3cee25463bd2772ebccac860189ba517d
3,425
py
Python
018-4Sum/solution01.py
Eroica-cpp/LeetCode
07276bd11558f3d0e32bec768b09e886de145f9e
[ "CC-BY-3.0", "MIT" ]
7
2015-05-05T22:21:30.000Z
2021-03-13T04:04:15.000Z
018-4Sum/solution01.py
Eroica-cpp/LeetCode
07276bd11558f3d0e32bec768b09e886de145f9e
[ "CC-BY-3.0", "MIT" ]
null
null
null
018-4Sum/solution01.py
Eroica-cpp/LeetCode
07276bd11558f3d0e32bec768b09e886de145f9e
[ "CC-BY-3.0", "MIT" ]
2
2018-12-26T08:13:25.000Z
2020-07-18T20:18:24.000Z
#!/usr/bin/python # ============================================================================== # Author: Tao Li (taoli@ucsd.edu) # Date: Jun 19, 2015 # Question: 018-4Sum # Link: https://leetcode.com/problems/4sum/ # ============================================================================== # Given an array S of n integers, are there elements a, b, c, and d in S such # that a + b + c + d = target? Find all unique quadruplets in the array which # gives the sum of target. # # Note: # Elements in a quadruplet (a,b,c,d) must be in non-descending order. # (ie, a <= b <= c <= d) # # The solution set must not contain duplicate quadruplets. # For example, given array S = {1 0 -1 0 -2 2}, and target = 0. # # A solution set is: # (-1, 0, 0, 1) # (-2, -1, 1, 2) # (-2, 0, 0, 2) # ============================================================================== # Method: Use "twoSum" method; enumerate the sum of any two numbers and store # them into a hash table, so four sum problem becomes a two sum problem # Time Complexity: O(n^2) # Space Complexity: O(n^2) # ============================================================================== class Solution: # @param {integer[]} nums # @param {integer} target # @return {integer[][]} def fourSum(self, nums, target): size = len(nums) nums.sort() twoSumDic = {} fourSumDic = {} counter = {} for i in xrange(size): counter[nums[i]] = counter.get(nums[i])+1 if counter.get(nums[i]) else 1 for j in xrange(i+1,size): if not twoSumDic.get(nums[i]+nums[j]): twoSumDic[nums[i]+nums[j]] = [[nums[i],nums[j]]] else: twoSumDic[nums[i]+nums[j]].append([nums[i],nums[j]]) keys = [] for key,val in twoSumDic.items(): times = 2 if len(val) >= 2 else 1 keys += [key] * times pairs = self.twoSum(keys, target) for pair in pairs: for i in twoSumDic[pair[0]]: for j in twoSumDic[pair[1]]: new = tuple(sorted(i+j)) flag = True for k in new: if new.count(k) > counter.get(k): flag = False break if flag and not fourSumDic.get(new): fourSumDic[new] = 1 return fourSumDic.keys() def twoSum(self, nums, target): size = len(nums) nums.sort() i, j = 0, size-1 res = [] while i < j: if nums[i]+nums[j] == target: res.append([nums[i], nums[j]]) i += 1 j -= 1 elif nums[i]+nums[j] > target: j -= 1 elif nums[i]+nums[j] < target: i += 1 return res if __name__ == '__main__': nums, target = [1,0,-1,0,-2,2], 0 nums, target = [-471,-434,-418,-395,-360,-357,-351,-342,-317,-315,-313,-273,-272,-249,-240,-216,-215,-214,-209,-198,-179,-164,-161,-141,-139,-131,-103,-97,-81,-64,-55,-29,11,40,40,45,64,87,95,101,115,121,149,185,230,230,232,251,266,274,277,287,300,325,334,335,340,383,389,426,426,427,457,471,494], 2705 nums, target = [1,1,1,1], 4 nums, target = [1,4,-3,0,0,0,5,0], 0 print Solution().fourSum(nums, target)
37.228261
306
0.458686
f2466dcdf27319adeea7443718bbf38b70a8fbbe
5,671
py
Python
lib/spack/spack/test/cmd/url.py
kkauder/spack
6ae8d5c380c1f42094b05d38be26b03650aafb39
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
2
2020-09-10T22:50:08.000Z
2021-01-12T22:18:54.000Z
lib/spack/spack/test/cmd/url.py
kkauder/spack
6ae8d5c380c1f42094b05d38be26b03650aafb39
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
17
2019-03-21T15:54:00.000Z
2022-03-29T19:34:28.000Z
lib/spack/spack/test/cmd/url.py
kkauder/spack
6ae8d5c380c1f42094b05d38be26b03650aafb39
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
2
2021-04-07T18:27:09.000Z
2022-03-31T22:52:38.000Z
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import re import sys import pytest import spack.repo from spack.url import UndetectableVersionError from spack.main import SpackCommand from spack.cmd.url import name_parsed_correctly, version_parsed_correctly from spack.cmd.url import url_summary url = SpackCommand('url') class MyPackage: def __init__(self, name, versions): self.name = name self.versions = versions def test_name_parsed_correctly(): # Expected True assert name_parsed_correctly(MyPackage('netcdf', []), 'netcdf') assert name_parsed_correctly(MyPackage('r-devtools', []), 'devtools') assert name_parsed_correctly(MyPackage('py-numpy', []), 'numpy') assert name_parsed_correctly(MyPackage('octave-splines', []), 'splines') assert name_parsed_correctly(MyPackage('th-data', []), 'TH.data') assert name_parsed_correctly( MyPackage('imagemagick', []), 'ImageMagick') # Expected False assert not name_parsed_correctly(MyPackage('', []), 'hdf5') assert not name_parsed_correctly(MyPackage('hdf5', []), '') assert not name_parsed_correctly(MyPackage('yaml-cpp', []), 'yamlcpp') assert not name_parsed_correctly(MyPackage('yamlcpp', []), 'yaml-cpp') assert not name_parsed_correctly(MyPackage('r-py-parser', []), 'parser') assert not name_parsed_correctly( MyPackage('oce', []), 'oce-0.18.0') def test_version_parsed_correctly(): # Expected True assert version_parsed_correctly(MyPackage('', ['1.2.3']), '1.2.3') assert version_parsed_correctly(MyPackage('', ['5.4a', '5.4b']), '5.4a') assert version_parsed_correctly(MyPackage('', ['5.4a', '5.4b']), '5.4b') assert version_parsed_correctly(MyPackage('', ['1.63.0']), '1_63_0') assert version_parsed_correctly(MyPackage('', ['0.94h']), '094h') # Expected False assert not version_parsed_correctly(MyPackage('', []), '1.2.3') assert not version_parsed_correctly(MyPackage('', ['1.2.3']), '') assert not version_parsed_correctly(MyPackage('', ['1.2.3']), '1.2.4') assert not version_parsed_correctly(MyPackage('', ['3.4a']), '3.4') assert not version_parsed_correctly(MyPackage('', ['3.4']), '3.4b') assert not version_parsed_correctly( MyPackage('', ['0.18.0']), 'oce-0.18.0') def test_url_parse(): url('parse', 'http://zlib.net/fossils/zlib-1.2.10.tar.gz') def test_url_with_no_version_fails(): # No version in URL with pytest.raises(UndetectableVersionError): url('parse', 'http://www.netlib.org/voronoi/triangle.zip') @pytest.mark.network @pytest.mark.skipif( sys.version_info < (2, 7), reason="Python 2.6 tests are run in a container, where " "networking is super slow" ) def test_url_list(): out = url('list') total_urls = len(out.split('\n')) # The following two options should not change the number of URLs printed. out = url('list', '--color', '--extrapolation') colored_urls = len(out.split('\n')) assert colored_urls == total_urls # The following options should print fewer URLs than the default. # If they print the same number of URLs, something is horribly broken. # If they say we missed 0 URLs, something is probably broken too. out = url('list', '--incorrect-name') incorrect_name_urls = len(out.split('\n')) assert 0 < incorrect_name_urls < total_urls out = url('list', '--incorrect-version') incorrect_version_urls = len(out.split('\n')) assert 0 < incorrect_version_urls < total_urls out = url('list', '--correct-name') correct_name_urls = len(out.split('\n')) assert 0 < correct_name_urls < total_urls out = url('list', '--correct-version') correct_version_urls = len(out.split('\n')) assert 0 < correct_version_urls < total_urls @pytest.mark.network @pytest.mark.skipif( sys.version_info < (2, 7), reason="Python 2.6 tests are run in a container, where " "networking is super slow" ) def test_url_summary(): """Test the URL summary command.""" # test url_summary, the internal function that does the work (total_urls, correct_names, correct_versions, name_count_dict, version_count_dict) = url_summary(None) assert (0 < correct_names <= sum(name_count_dict.values()) <= total_urls) assert (0 < correct_versions <= sum(version_count_dict.values()) <= total_urls) # make sure it agrees with the actual command. out = url('summary') out_total_urls = int( re.search(r'Total URLs found:\s*(\d+)', out).group(1)) assert out_total_urls == total_urls out_correct_names = int( re.search(r'Names correctly parsed:\s*(\d+)', out).group(1)) assert out_correct_names == correct_names out_correct_versions = int( re.search(r'Versions correctly parsed:\s*(\d+)', out).group(1)) assert out_correct_versions == correct_versions @pytest.mark.skipif( sys.version_info < (2, 7), reason="Python 2.6 tests are run in a container, where " "networking is super slow" ) def test_url_stats(capfd): with capfd.disabled(): output = url('stats') npkgs = '%d packages' % len(spack.repo.all_package_names()) assert npkgs in output assert 'url' in output assert 'git' in output assert 'schemes' in output assert 'versions' in output assert 'resources' in output
36.352564
78
0.662846
b1f33f5bd92d0e9fbcece6e1690377446be4d006
1,334
py
Python
dltb/util/helper.py
Petr-By/qtpyvis
0b9a151ee6b9a56b486c2bece9c1f03414629efc
[ "MIT" ]
3
2017-10-04T14:51:26.000Z
2017-10-22T09:35:50.000Z
dltb/util/helper.py
krumnack/qtpyvis
0b9a151ee6b9a56b486c2bece9c1f03414629efc
[ "MIT" ]
13
2017-11-26T10:05:00.000Z
2018-03-11T14:08:40.000Z
dltb/util/helper.py
krumnack/qtpyvis
0b9a151ee6b9a56b486c2bece9c1f03414629efc
[ "MIT" ]
2
2017-09-24T21:39:42.000Z
2017-10-04T15:29:54.000Z
"""Several commonly used general purpose functions, classes, decorators, and context managers, only based on Python standard libraries. """ # standard imports from contextlib import contextmanager from threading import Lock class classproperty1(property): """A docorator to mark a method as classproperty. This only allows for read access, it does not prevent overwriting. """ def __get__(self, cls, owner): # cls=None, owner=class of decorated method return classmethod(self.fget).__get__(None, owner)() class classproperty2(staticmethod): """Another way to define a classproperty docorator. This also only allows for read access, it does not prevent overwriting. """ def __get__(self, cls, owner): # cls=None, owner=class of decorated method return self.__func__(owner) classproperty = classproperty1 @contextmanager def nonblocking(lock: Lock): """A contextmanager that does something with the given `Lock`, but only if it is not currently locked. lock = threading.Lock() with nonblocking(lock): ... """ locked = lock.acquire(blocking=False) # if not locked: # raise RuntimeError("Lock cannot be acquired.") try: yield locked finally: if locked: lock.release()
25.653846
75
0.677661
4d3cda98f88d98373d76669a54ac74fd23dc82a6
129,087
py
Python
mne/viz/utils.py
mkoculak/mne-python
85bc0063c7582a4deb2e453ea6c41e49036254a4
[ "BSD-3-Clause" ]
null
null
null
mne/viz/utils.py
mkoculak/mne-python
85bc0063c7582a4deb2e453ea6c41e49036254a4
[ "BSD-3-Clause" ]
null
null
null
mne/viz/utils.py
mkoculak/mne-python
85bc0063c7582a4deb2e453ea6c41e49036254a4
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """Utility functions for plotting M/EEG data.""" # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Denis Engemann <denis.engemann@gmail.com> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # Eric Larson <larson.eric.d@gmail.com> # Mainak Jas <mainak@neuro.hut.fi> # Stefan Appelhoff <stefan.appelhoff@mailbox.org> # Clemens Brunner <clemens.brunner@gmail.com> # Daniel McCloy <dan.mccloy@gmail.com> # # License: Simplified BSD from contextlib import contextmanager from functools import partial import difflib import webbrowser import tempfile import math import numpy as np import platform from copy import deepcopy from distutils.version import LooseVersion from itertools import cycle import warnings from ..defaults import _handle_default from ..fixes import _get_status from ..io import show_fiff, Info from ..io.constants import FIFF from ..io.pick import (channel_type, channel_indices_by_type, pick_channels, _pick_data_channels, _DATA_CH_TYPES_SPLIT, _VALID_CHANNEL_TYPES, pick_types, pick_info, _picks_by_type, pick_channels_cov, _picks_to_idx, _contains_ch_type) from ..io.meas_info import create_info from ..rank import compute_rank from ..io.proj import setup_proj from ..utils import (verbose, get_config, set_config, warn, _check_ch_locs, _check_option, logger, fill_doc, _pl, _check_sphere) from ..selection import (read_selection, _SELECTIONS, _EEG_SELECTIONS, _divide_to_regions) from ..annotations import _sync_onset from ..transforms import apply_trans _channel_type_prettyprint = {'eeg': "EEG channel", 'grad': "Gradiometer", 'mag': "Magnetometer", 'seeg': "sEEG channel", 'eog': "EOG channel", 'ecg': "ECG sensor", 'emg': "EMG sensor", 'ecog': "ECoG channel", 'misc': "miscellaneous sensor"} def _setup_vmin_vmax(data, vmin, vmax, norm=False): """Handle vmin and vmax parameters for visualizing topomaps. For the normal use-case (when `vmin` and `vmax` are None), the parameter `norm` drives the computation. When norm=False, data is supposed to come from a mag and the output tuple (vmin, vmax) is symmetric range (-x, x) where x is the max(abs(data)). When norm=True (a.k.a. data is the L2 norm of a gradiometer pair) the output tuple corresponds to (0, x). Otherwise, vmin and vmax are callables that drive the operation. """ should_warn = False if vmax is None and vmin is None: vmax = np.abs(data).max() vmin = 0. if norm else -vmax if vmin == 0 and np.min(data) < 0: should_warn = True else: if callable(vmin): vmin = vmin(data) elif vmin is None: vmin = 0. if norm else np.min(data) if vmin == 0 and np.min(data) < 0: should_warn = True if callable(vmax): vmax = vmax(data) elif vmax is None: vmax = np.max(data) if should_warn: warn_msg = ("_setup_vmin_vmax output a (min={vmin}, max={vmax})" " range whereas the minimum of data is {data_min}") warn_val = {'vmin': vmin, 'vmax': vmax, 'data_min': np.min(data)} warn(warn_msg.format(**warn_val), UserWarning) return vmin, vmax def plt_show(show=True, fig=None, **kwargs): """Show a figure while suppressing warnings. Parameters ---------- show : bool Show the figure. fig : instance of Figure | None If non-None, use fig.show(). **kwargs : dict Extra arguments for :func:`matplotlib.pyplot.show`. """ from matplotlib import get_backend import matplotlib.pyplot as plt if show and get_backend() != 'agg': (fig or plt).show(**kwargs) def tight_layout(pad=1.2, h_pad=None, w_pad=None, fig=None): """Adjust subplot parameters to give specified padding. .. note:: For plotting please use this function instead of ``plt.tight_layout``. Parameters ---------- pad : float Padding between the figure edge and the edges of subplots, as a fraction of the font-size. h_pad : float Padding height between edges of adjacent subplots. Defaults to ``pad_inches``. w_pad : float Padding width between edges of adjacent subplots. Defaults to ``pad_inches``. fig : instance of Figure Figure to apply changes to. """ import matplotlib.pyplot as plt fig = plt.gcf() if fig is None else fig fig.canvas.draw() try: # see https://github.com/matplotlib/matplotlib/issues/2654 with warnings.catch_warnings(record=True) as ws: fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad) except Exception: try: with warnings.catch_warnings(record=True) as ws: fig.set_tight_layout(dict(pad=pad, h_pad=h_pad, w_pad=w_pad)) except Exception: warn('Matplotlib function "tight_layout" is not supported.' ' Skipping subplot adjustment.') return for w in ws: w_msg = str(w.message) if hasattr(w, 'message') else w.get_message() if not w_msg.startswith('This figure includes Axes'): warn(w_msg, w.category, 'matplotlib') def _check_delayed_ssp(container): """Handle interactive SSP selection.""" if container.proj is True or\ all(p['active'] for p in container.info['projs']): raise RuntimeError('Projs are already applied. Please initialize' ' the data with proj set to False.') elif len(container.info['projs']) < 1: raise RuntimeError('No projs found in evoked.') def _validate_if_list_of_axes(axes, obligatory_len=None): """Validate whether input is a list/array of axes.""" from matplotlib.axes import Axes if obligatory_len is not None and not isinstance(obligatory_len, int): raise ValueError('obligatory_len must be None or int, got %d', 'instead' % type(obligatory_len)) if not isinstance(axes, (list, np.ndarray)): raise ValueError('axes must be a list or numpy array of matplotlib ' 'axes objects, got %s instead.' % type(axes)) if isinstance(axes, np.ndarray) and axes.ndim > 1: raise ValueError('if input is a numpy array, it must be ' 'one-dimensional. The received numpy array has %d ' 'dimensions however. Try using ravel or flatten ' 'method of the array.' % axes.ndim) is_correct_type = np.array([isinstance(x, Axes) for x in axes]) if not np.all(is_correct_type): first_bad = np.where(np.logical_not(is_correct_type))[0][0] raise ValueError('axes must be a list or numpy array of matplotlib ' 'axes objects while one of the list elements is ' '%s.' % type(axes[first_bad])) if obligatory_len is not None and not len(axes) == obligatory_len: raise ValueError('axes must be a list/array of length %d, while the' ' length is %d' % (obligatory_len, len(axes))) def mne_analyze_colormap(limits=[5, 10, 15], format='mayavi'): """Return a colormap similar to that used by mne_analyze. Parameters ---------- limits : list (or array) of length 3 or 6 Bounds for the colormap, which will be mirrored across zero if length 3, or completely specified (and potentially asymmetric) if length 6. format : str Type of colormap to return. If 'matplotlib', will return a matplotlib.colors.LinearSegmentedColormap. If 'mayavi', will return an RGBA array of shape (256, 4). Returns ------- cmap : instance of colormap | array A teal->blue->gray->red->yellow colormap. See docstring of the 'format' argument for further details. Notes ----- For this will return a colormap that will display correctly for data that are scaled by the plotting function to span [-fmax, fmax]. Examples -------- The following code will plot a STC using standard MNE limits:: >>> colormap = mne.viz.mne_analyze_colormap(limits=[5, 10, 15]) # doctest: +SKIP >>> brain = stc.plot('fsaverage', 'inflated', 'rh', colormap) # doctest: +SKIP >>> brain.scale_data_colormap(fmin=-15, fmid=0, fmax=15, transparent=False) # doctest: +SKIP """ # noqa: E501 # Ensure limits is an array limits = np.asarray(limits, dtype='float') if len(limits) != 3 and len(limits) != 6: raise ValueError('limits must have 3 or 6 elements') if len(limits) == 3 and any(limits < 0.): raise ValueError('if 3 elements, limits must all be non-negative') if any(np.diff(limits) <= 0): raise ValueError('limits must be monotonically increasing') if format == 'matplotlib': from matplotlib import colors if len(limits) == 3: limits = (np.concatenate((-np.flipud(limits), limits)) + limits[-1]) / (2 * limits[-1]) else: limits = (limits - np.min(limits)) / np.max(limits - np.min(limits)) cdict = {'red': ((limits[0], 0.0, 0.0), (limits[1], 0.0, 0.0), (limits[2], 0.5, 0.5), (limits[3], 0.5, 0.5), (limits[4], 1.0, 1.0), (limits[5], 1.0, 1.0)), 'green': ((limits[0], 1.0, 1.0), (limits[1], 0.0, 0.0), (limits[2], 0.5, 0.5), (limits[3], 0.5, 0.5), (limits[4], 0.0, 0.0), (limits[5], 1.0, 1.0)), 'blue': ((limits[0], 1.0, 1.0), (limits[1], 1.0, 1.0), (limits[2], 0.5, 0.5), (limits[3], 0.5, 0.5), (limits[4], 0.0, 0.0), (limits[5], 0.0, 0.0)), 'alpha': ((limits[0], 1.0, 1.0), (limits[1], 1.0, 1.0), (limits[2], 0.0, 0.0), (limits[3], 0.0, 0.0), (limits[4], 1.0, 1.0), (limits[5], 1.0, 1.0)), } return colors.LinearSegmentedColormap('mne_analyze', cdict) elif format == 'mayavi': if len(limits) == 3: limits = np.concatenate((-np.flipud(limits), [0], limits)) /\ limits[-1] else: limits = np.concatenate((limits[:3], [0], limits[3:])) limits /= np.max(np.abs(limits)) r = np.array([0, 0, 0, 0, 1, 1, 1]) g = np.array([1, 0, 0, 0, 0, 0, 1]) b = np.array([1, 1, 1, 0, 0, 0, 0]) a = np.array([1, 1, 0, 0, 0, 1, 1]) xp = (np.arange(256) - 128) / 128.0 colormap = np.r_[[np.interp(xp, limits, 255 * c) for c in [r, g, b, a]]].T return colormap else: raise ValueError('format must be either matplotlib or mayavi') def _toggle_options(event, params): """Toggle options (projectors) dialog.""" import matplotlib.pyplot as plt if len(params['projs']) > 0: if params['fig_proj'] is None: _draw_proj_checkbox(event, params, draw_current_state=False) else: # turn off options dialog plt.close(params['fig_proj']) del params['proj_checks'] params['fig_proj'] = None @contextmanager def _events_off(obj): obj.eventson = False try: yield finally: obj.eventson = True def _toggle_proj(event, params, all_=False): """Perform operations when proj boxes clicked.""" # read options if possible if 'proj_checks' in params: bools = _get_status(params['proj_checks']) if all_: new_bools = [not all(bools)] * len(bools) with _events_off(params['proj_checks']): for bi, (old, new) in enumerate(zip(bools, new_bools)): if old != new: params['proj_checks'].set_active(bi) bools[bi] = new for bi, (b, p) in enumerate(zip(bools, params['projs'])): # see if they tried to deactivate an active one if not b and p['active']: bools[bi] = True else: proj = params.get('apply_proj', True) bools = [proj] * len(params['projs']) compute_proj = False if 'proj_bools' not in params: compute_proj = True elif not np.array_equal(bools, params['proj_bools']): compute_proj = True # if projectors changed, update plots if compute_proj is True: params['plot_update_proj_callback'](params, bools) def _get_help_text(params): """Customize help dialogs text.""" is_mac = platform.system() == 'Darwin' text, text2 = list(), list() text.append('(Shift +) ← : \n') text.append('(Shift +) → : \n') text.append('↓ : \n') text.append('↑ : \n') text.append('- : \n') text.append('+ or = : \n') if is_mac: text.append('fn + ← : \n') text.append('fn + → : \n') if 'fig_selection' not in params: text.append('fn + ↓ : \n') text.append('fn + ↑ : \n') else: text.append('Home : \n') text.append('End : \n') if 'fig_selection' not in params: text.append('Page down : \n') text.append('Page up : \n') text.append('z : \n') text.append('F11 : \n') text.append('? : \n') text.append('Esc : \n\n') text.append('Mouse controls\n') text.append('click on data :\n') text2.append('Navigate left\n') text2.append('Navigate right\n') text2.append('Scale down\n') text2.append('Scale up\n') text2.append('Toggle scrollbars\n') text2.append('Toggle full screen mode\n') text2.append('Open help box\n') text2.append('Quit\n\n\n') if 'raw' in params: text2.insert(4, 'Reduce the time shown per view\n') text2.insert(5, 'Increase the time shown per view\n') text.append('click elsewhere in the plot :\n') if 'ica' in params: text.append('click component name :\n') text2.insert(2, 'Navigate components down\n') text2.insert(3, 'Navigate components up\n') text2.insert(8, 'Reduce the number of components per view\n') text2.insert(9, 'Increase the number of components per view\n') text2.append('Mark bad channel\n') text2.append('Vertical line at a time instant\n') text2.append('Show topography for the component\n') else: text.append('click channel name :\n') text2.insert(2, 'Navigate channels down\n') text2.insert(3, 'Navigate channels up\n') text.insert(6, 'a : \n') text2.insert(6, 'Toggle annotation mode\n') text.insert(7, 'p : \n') text2.insert(7, 'Toggle snap to annotations on/off\n') text.insert(8, 'b : \n') text2.insert(8, 'Toggle butterfly plot on/off\n') text.insert(9, 'd : \n') text2.insert(9, 'Toggle remove DC on/off\n') text.insert(10, 's : \n') text2.insert(10, 'Toggle scale bars\n') if 'fig_selection' not in params: text2.insert(13, 'Reduce the number of channels per view\n') text2.insert(14, 'Increase the number of channels per view\n') text2.append('Mark bad channel\n') text2.append('Vertical line at a time instant\n') text2.append('Mark bad channel\n') elif 'epochs' in params: text.append('right click :\n') text2.insert(4, 'Reduce the number of epochs per view\n') text2.insert(5, 'Increase the number of epochs per view\n') if 'ica' in params: text.append('click component name :\n') text2.insert(2, 'Navigate components down\n') text2.insert(3, 'Navigate components up\n') text2.insert(8, 'Reduce the number of components per view\n') text2.insert(9, 'Increase the number of components per view\n') text2.append('Mark component for exclusion\n') text2.append('Vertical line at a time instant\n') text2.append('Show topography for the component\n') else: text.append('click channel name :\n') text.append('right click channel name :\n') text2.insert(2, 'Navigate channels down\n') text2.insert(3, 'Navigate channels up\n') text2.insert(8, 'Reduce the number of channels per view\n') text2.insert(9, 'Increase the number of channels per view\n') text.insert(10, 'b : \n') text2.insert(10, 'Toggle butterfly plot on/off\n') text.insert(11, 'h : \n') text2.insert(11, 'Show histogram of peak-to-peak values\n') text2.append('Mark bad epoch\n') text2.append('Vertical line at a time instant\n') text2.append('Mark bad channel\n') text2.append('Plot ERP/ERF image\n') text.append('middle click :\n') text2.append('Show channel name (butterfly plot)\n') text.insert(11, 'o : \n') text2.insert(11, 'View settings (orig. view only)\n') return ''.join(text), ''.join(text2) def _prepare_trellis(n_cells, ncols, nrows='auto', title=False, colorbar=False, size=1.3): import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec if n_cells == 1: nrows = ncols = 1 elif isinstance(ncols, int) and n_cells <= ncols: nrows, ncols = 1, n_cells else: if ncols == 'auto' and nrows == 'auto': nrows = math.floor(math.sqrt(n_cells)) ncols = math.ceil(n_cells / nrows) elif ncols == 'auto': ncols = math.ceil(n_cells / nrows) elif nrows == 'auto': nrows = math.ceil(n_cells / ncols) else: naxes = ncols * nrows if naxes < n_cells: raise ValueError("Cannot plot {} axes in a {} by {} " "figure.".format(n_cells, nrows, ncols)) if colorbar: ncols += 1 width = size * ncols height = (size + max(0, 0.1 * (4 - size))) * nrows + bool(title) * 0.5 height_ratios = None g_kwargs = {} figure_nobar(figsize=(width * 1.5, height * 1.5)) gs = GridSpec(nrows, ncols, height_ratios=height_ratios, **g_kwargs) axes = [] if colorbar: # exclude last axis of each row except top row, which is for colorbar exclude = set(range(2 * ncols - 1, nrows * ncols, ncols)) ax_idxs = sorted(set(range(nrows * ncols)) - exclude)[:n_cells + 1] else: ax_idxs = range(n_cells) for ax_idx in ax_idxs: axes.append(plt.subplot(gs[ax_idx])) fig = axes[0].get_figure() return fig, axes, ncols, nrows def _draw_proj_checkbox(event, params, draw_current_state=True): """Toggle options (projectors) dialog.""" from matplotlib import widgets projs = params['projs'] # turn on options dialog labels = [p['desc'] for p in projs] actives = ([p['active'] for p in projs] if draw_current_state else params.get('proj_bools', [params['apply_proj']] * len(projs))) width = max([4., max([len(p['desc']) for p in projs]) / 6.0 + 0.5]) height = (len(projs) + 1) / 6.0 + 1.5 fig_proj = figure_nobar(figsize=(width, height)) fig_proj.canvas.set_window_title('SSP projection vectors') offset = (1. / 6. / height) params['fig_proj'] = fig_proj # necessary for proper toggling ax_temp = fig_proj.add_axes((0, offset, 1, 0.8 - offset), frameon=False) ax_temp.set_title('Projectors marked with "X" are active') proj_checks = widgets.CheckButtons(ax_temp, labels=labels, actives=actives) # make edges around checkbox areas for rect in proj_checks.rectangles: rect.set_edgecolor('0.5') rect.set_linewidth(1.) # change already-applied projectors to red for ii, p in enumerate(projs): if p['active']: for x in proj_checks.lines[ii]: x.set_color('#ff0000') # make minimal size # pass key presses from option dialog over proj_checks.on_clicked(partial(_toggle_proj, params=params)) params['proj_checks'] = proj_checks fig_proj.canvas.mpl_connect('key_press_event', _key_press) # Toggle all ax_temp = fig_proj.add_axes((0, 0, 1, offset), frameon=False) proj_all = widgets.Button(ax_temp, 'Toggle all') proj_all.on_clicked(partial(_toggle_proj, params=params, all_=True)) params['proj_all'] = proj_all # this should work for non-test cases try: fig_proj.canvas.draw() plt_show(fig=fig_proj, warn=False) except Exception: pass def _simplify_float(label): # Heuristic to turn floats to ints where possible (e.g. -500.0 to -500) if isinstance(label, float) and np.isfinite(label) and \ float(str(label)) != round(label): label = round(label, 2) return label def _get_figsize_from_config(): """Get default / most recent figure size from config.""" figsize = get_config('MNE_BROWSE_RAW_SIZE') if figsize is not None: figsize = figsize.split(',') figsize = tuple([float(s) for s in figsize]) return figsize def _get_figsize_px(fig): """Get figure size in pixels.""" dpi_ratio = _get_dpi_ratio(fig) size = fig.get_size_inches() * fig.dpi / dpi_ratio return size def _get_dpi_ratio(fig): """Get DPI ratio (to handle hi-DPI screens).""" dpi_ratio = 1. for key in ('_dpi_ratio', '_device_scale'): dpi_ratio = getattr(fig.canvas, key, dpi_ratio) return dpi_ratio def _inch_to_rel_dist(fig, dim_inches, horiz=True): """Convert inches to figure-relative distances.""" fig_w_px, fig_h_px = _get_figsize_px(fig) w_or_h = fig_w_px if horiz else fig_h_px return dim_inches * fig.dpi / _get_dpi_ratio(fig) / w_or_h def _update_borders(params, new_width, new_height): """Update figure borders to maintain fixed size in inches/pixels.""" old_width, old_height = params['fig_size_px'] new_borders = dict() sides = ('left', 'right', 'bottom', 'top') for side in sides: horiz = side in ('left', 'right') ratio = (old_width / new_width) if horiz else (old_height / new_height) rel_dim = getattr(params['fig'].subplotpars, side) if side in ('right', 'top'): rel_dim = (1 - rel_dim) rel_dim = rel_dim * ratio if side in ('right', 'top'): rel_dim = (1 - rel_dim) new_borders[side] = rel_dim # zen mode adjustment params['zen_w_delta'] *= old_width / new_width params['zen_h_delta'] *= old_height / new_height # update params['fig'].subplots_adjust(**new_borders) def _toggle_scrollbars(params): """Show or hide scrollbars (A.K.A. zen mode) in mne_browse-style plots.""" if params.get('show_scrollbars', None) is not None: # grow/shrink main axes to take up space from/make room for scrollbars # can't use ax.set_position() because axes are locatable, so we have to # fake it with subplots_adjust should_show = not params['show_scrollbars'] sides = ('left', 'bottom', 'right', 'top') borders = {side: getattr(params['fig'].subplotpars, side) for side in sides} # if should_show, bottom margin moves up; right margin moves left borders['bottom'] += (1 if should_show else -1) * params['zen_h_delta'] borders['right'] += (-1 if should_show else 1) * params['zen_w_delta'] # squeeze a little more because we don't need space for "Time (s)" now v_delta = _inch_to_rel_dist(params['fig'], 0.16, horiz=False) borders['bottom'] += (1 if should_show else -1) * v_delta params['fig'].subplots_adjust(**borders) # show/hide for element in ('ax_hscroll', 'ax_vscroll', 'ax_button', 'ax_help'): if params.get('butterfly', False) and element == 'ax_vscroll': continue # sometimes we don't have a proj button (ax_button) if params.get(element, None) is not None: params[element].set_visible(should_show) params['show_scrollbars'] = should_show params['fig'].canvas.draw() def _prepare_mne_browse(params, xlabel): """Set up axes for mne_browse_* style raw/epochs/ICA plots.""" import matplotlib as mpl from mpl_toolkits.axes_grid1.axes_size import Fixed from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable fig = params['fig'] fig_w_px, fig_h_px = _get_figsize_px(fig) params['fig_size_px'] = fig_w_px, fig_h_px # store for on_resize callback # default sizes (inches) scroll_width = 0.25 hscroll_dist = 0.25 vscroll_dist = 0.1 l_border = 1. r_border = 0.1 b_border = 0.45 t_border = 0.25 help_width = scroll_width * 2 # default borders (figure-relative coordinates) fig.subplots_adjust( left=_inch_to_rel_dist(fig, l_border - vscroll_dist - help_width), right=1 - _inch_to_rel_dist(fig, r_border), bottom=_inch_to_rel_dist(fig, b_border, horiz=False), top=1 - _inch_to_rel_dist(fig, t_border, horiz=False) ) # Main axes must be a `subplot` for `subplots_adjust` to work (so user can # adjust margins). That's why we don't use the Divider class directly. ax = fig.add_subplot(1, 1, 1) div = make_axes_locatable(ax) ax_hscroll = div.append_axes(position='bottom', size=Fixed(scroll_width), pad=Fixed(hscroll_dist)) ax_vscroll = div.append_axes(position='right', size=Fixed(scroll_width), pad=Fixed(vscroll_dist)) # proj button (optionally) added later, but easiest to compute position now proj_button_pos = [ 1 - _inch_to_rel_dist(fig, r_border + scroll_width), # left _inch_to_rel_dist(fig, b_border, horiz=False), # bottom _inch_to_rel_dist(fig, scroll_width), # width _inch_to_rel_dist(fig, scroll_width, horiz=False) # height ] params['proj_button_pos'] = proj_button_pos params['proj_button_locator'] = div.new_locator(nx=2, ny=0) # initialize help button axes in the wrong spot... ax_help = div.append_axes(position='left', size=Fixed(help_width), pad=Fixed(vscroll_dist)) # ...then move it down by changing its locator, and make it a button. loc = div.new_locator(nx=0, ny=0) ax_help.set_axes_locator(loc) help_button = mpl.widgets.Button(ax_help, 'Help') help_button.on_clicked(partial(_onclick_help, params=params)) # style scrollbars ax_hscroll.get_yaxis().set_visible(False) ax_hscroll.set_xlabel(xlabel) ax_vscroll.set_axis_off() # store these so they can be modified elsewhere params['ax'] = ax params['ax_hscroll'] = ax_hscroll params['ax_vscroll'] = ax_vscroll params['ax_help'] = ax_help params['help_button'] = help_button # default key to close window params['close_key'] = 'escape' # add resize callback (it's the same for Raw/Epochs/ICA) callback_resize = partial(_resize_event, params=params) params['fig'].canvas.mpl_connect('resize_event', callback_resize) # zen mode fig.canvas.draw() # otherwise the get_position() calls are inaccurate params['zen_w_delta'] = (ax_vscroll.get_position().xmax - ax.get_position().xmax) params['zen_h_delta'] = (ax.get_position().ymin - ax_hscroll.get_position().ymin) if not params.get('show_scrollbars', True): # change to True so toggle func will do the right thing params['show_scrollbars'] = True _toggle_scrollbars(params) @verbose def compare_fiff(fname_1, fname_2, fname_out=None, show=True, indent=' ', read_limit=np.inf, max_str=30, verbose=None): """Compare the contents of two fiff files using diff and show_fiff. Parameters ---------- fname_1 : str First file to compare. fname_2 : str Second file to compare. fname_out : str | None Filename to store the resulting diff. If None, a temporary file will be created. show : bool If True, show the resulting diff in a new tab in a web browser. indent : str How to indent the lines. read_limit : int Max number of bytes of data to read from a tag. Can be np.inf to always read all data (helps test read completion). max_str : int Max number of characters of string representation to print for each tag's data. %(verbose)s Returns ------- fname_out : str The filename used for storing the diff. Could be useful for when a temporary file is used. """ file_1 = show_fiff(fname_1, output=list, indent=indent, read_limit=read_limit, max_str=max_str) file_2 = show_fiff(fname_2, output=list, indent=indent, read_limit=read_limit, max_str=max_str) diff = difflib.HtmlDiff().make_file(file_1, file_2, fname_1, fname_2) if fname_out is not None: f = open(fname_out, 'wb') else: f = tempfile.NamedTemporaryFile('wb', delete=False, suffix='.html') fname_out = f.name with f as fid: fid.write(diff.encode('utf-8')) if show is True: webbrowser.open_new_tab(fname_out) return fname_out def figure_nobar(*args, **kwargs): """Make matplotlib figure with no toolbar. Parameters ---------- *args : list Arguments to pass to :func:`matplotlib.pyplot.figure`. **kwargs : dict Keyword arguments to pass to :func:`matplotlib.pyplot.figure`. Returns ------- fig : instance of Figure The figure. """ from matplotlib import rcParams, pyplot as plt old_val = rcParams['toolbar'] try: rcParams['toolbar'] = 'none' fig = plt.figure(*args, **kwargs) # remove button press catchers (for toolbar) cbs = list(fig.canvas.callbacks.callbacks['key_press_event'].keys()) for key in cbs: fig.canvas.callbacks.disconnect(key) finally: rcParams['toolbar'] = old_val return fig def _resize_event(event, params): """Handle resize event for mne_browse-style plots (Raw/Epochs/ICA).""" size = ','.join([str(s) for s in params['fig'].get_size_inches()]) set_config('MNE_BROWSE_RAW_SIZE', size, set_env=False) new_width, new_height = _get_figsize_px(params['fig']) _update_borders(params, new_width, new_height) params['fig_size_px'] = (new_width, new_height) def _plot_raw_onscroll(event, params, len_channels=None): """Interpret scroll events.""" if 'fig_selection' in params: if params['butterfly']: return _change_channel_group(event.step, params) return if len_channels is None: len_channels = len(params['inds']) orig_start = params['ch_start'] if event.step < 0: params['ch_start'] = min(params['ch_start'] + params['n_channels'], len_channels - params['n_channels']) else: # event.key == 'up': params['ch_start'] = max(params['ch_start'] - params['n_channels'], 0) if orig_start != params['ch_start']: _channels_changed(params, len_channels) def _channels_changed(params, len_channels): """Deal with the vertical shift of the viewport.""" if params['ch_start'] + params['n_channels'] > len_channels: params['ch_start'] = len_channels - params['n_channels'] if params['ch_start'] < 0: params['ch_start'] = 0 params['plot_fun']() def _plot_raw_time(value, params): """Deal with changed time value.""" info = params['info'] max_times = params['n_times'] / float(info['sfreq']) + \ params['first_time'] - params['duration'] if value > max_times: value = params['n_times'] / float(info['sfreq']) + \ params['first_time'] - params['duration'] if value < params['first_time']: value = params['first_time'] if params['t_start'] != value: params['t_start'] = value params['hsel_patch'].set_x(value) def _radio_clicked(label, params): """Handle radio buttons in selection dialog.""" from .evoked import _rgb # First the selection dialog. labels = [label._text for label in params['fig_selection'].radio.labels] idx = labels.index(label) params['fig_selection'].radio._active_idx = idx channels = params['selections'][label] ax_topo = params['fig_selection'].get_axes()[1] types = np.array([], dtype=int) for this_type in _DATA_CH_TYPES_SPLIT: if this_type in params['types']: types = np.concatenate( [types, np.where(np.array(params['types']) == this_type)[0]]) colors = np.zeros((len(types), 4)) # alpha = 0 by default locs3d = np.array([ch['loc'][:3] for ch in params['info']['chs']]) x, y, z = locs3d.T color_vals = _rgb(x, y, z) for color_idx, pick in enumerate(types): if pick in channels: # set color and alpha = 1 colors[color_idx] = np.append(color_vals[pick], 1.) ax_topo.collections[0]._facecolors = colors params['fig_selection'].canvas.draw() if params['butterfly']: return # Then the plotting window. params['ax_vscroll'].set_visible(True) nchan = sum([len(params['selections'][label]) for label in labels[:idx]]) params['vsel_patch'].set_y(nchan) n_channels = len(channels) params['n_channels'] = n_channels params['inds'] = channels for line in params['lines'][n_channels:]: # To remove lines from view. line.set_xdata([]) line.set_ydata([]) if n_channels > 0: # Can be 0 with lasso selector. _setup_browser_offsets(params, n_channels) params['plot_fun']() def _get_active_radio_idx(radio): """Find out active radio button.""" labels = [label.get_text() for label in radio.labels] return labels.index(radio.value_selected) def _set_annotation_radio_button(idx, params): """Set active button.""" radio = params['fig_annotation'].radio for circle in radio.circles: circle.set_facecolor('white') radio.circles[idx].set_facecolor('#cccccc') _annotation_radio_clicked('', radio, params['ax'].selector) def _set_radio_button(idx, params): """Set radio button.""" # XXX: New version of matplotlib has this implemented for radio buttons, # This function is for compatibility with old versions of mpl. radio = params['fig_selection'].radio radio.circles[radio._active_idx].set_facecolor((1., 1., 1., 1.)) radio.circles[idx].set_facecolor((0., 0., 1., 1.)) _radio_clicked(radio.labels[idx]._text, params) def _change_channel_group(step, params): """Deal with change of channel group.""" radio = params['fig_selection'].radio idx = radio._active_idx if step < 0: if idx < len(radio.labels) - 1: _set_radio_button(idx + 1, params) elif idx > 0: _set_radio_button(idx - 1, params) def _handle_change_selection(event, params): """Handle clicks on vertical scrollbar using selections.""" radio = params['fig_selection'].radio ydata = event.ydata labels = [label._text for label in radio.labels] offset = 0 for idx, label in enumerate(labels): nchans = len(params['selections'][label]) offset += nchans if ydata < offset: _set_radio_button(idx, params) return def _plot_raw_onkey(event, params): """Interpret key presses.""" import matplotlib.pyplot as plt if event.key == params['close_key']: plt.close(params['fig']) if params['fig_annotation'] is not None: plt.close(params['fig_annotation']) elif event.key == 'down': if 'fig_selection' in params.keys(): _change_channel_group(-1, params) return elif params['butterfly']: return params['ch_start'] += params['n_channels'] _channels_changed(params, len(params['inds'])) elif event.key == 'up': if 'fig_selection' in params.keys(): _change_channel_group(1, params) return elif params['butterfly']: return params['ch_start'] -= params['n_channels'] _channels_changed(params, len(params['inds'])) elif event.key == 'right': value = params['t_start'] + params['duration'] / 4 _plot_raw_time(value, params) params['update_fun']() params['plot_fun']() elif event.key == 'shift+right': value = params['t_start'] + params['duration'] _plot_raw_time(value, params) params['update_fun']() params['plot_fun']() elif event.key == 'left': value = params['t_start'] - params['duration'] / 4 _plot_raw_time(value, params) params['update_fun']() params['plot_fun']() elif event.key == 'shift+left': value = params['t_start'] - params['duration'] _plot_raw_time(value, params) params['update_fun']() params['plot_fun']() elif event.key in ['+', '=']: params['scale_factor'] *= 1.1 params['plot_fun']() elif event.key == '-': params['scale_factor'] /= 1.1 params['plot_fun']() elif event.key == 'pageup' and 'fig_selection' not in params: n_channels = min(params['n_channels'] + 1, len(params['info']['chs'])) _setup_browser_offsets(params, n_channels) _channels_changed(params, len(params['inds'])) elif event.key == 'pagedown' and 'fig_selection' not in params: n_channels = params['n_channels'] - 1 if n_channels == 0: return _setup_browser_offsets(params, n_channels) if len(params['lines']) > n_channels: # remove line from view params['lines'][n_channels].set_xdata([]) params['lines'][n_channels].set_ydata([]) _channels_changed(params, len(params['inds'])) elif event.key == 'home': duration = params['duration'] - 1.0 if duration <= 0: return params['duration'] = duration params['hsel_patch'].set_width(params['duration']) params['update_fun']() params['plot_fun']() elif event.key == 'end': duration = params['duration'] + 1.0 if duration > params['raw'].times[-1]: duration = params['raw'].times[-1] params['duration'] = duration params['hsel_patch'].set_width(params['duration']) params['update_fun']() params['plot_fun']() elif event.key == '?': _onclick_help(event, params) elif event.key == 'f11': mng = plt.get_current_fig_manager() mng.full_screen_toggle() elif event.key == 'a': if 'ica' in params.keys(): return if params['fig_annotation'] is None: _setup_annotation_fig(params) else: params['fig_annotation'].canvas.close_event() elif event.key == 'b': _setup_butterfly(params) elif event.key == 'w': params['use_noise_cov'] = not params['use_noise_cov'] params['plot_update_proj_callback'](params, None) elif event.key == 'd': params['remove_dc'] = not params['remove_dc'] params['update_fun']() params['plot_fun']() elif event.key == 's': params['show_scalebars'] = not params['show_scalebars'] params['plot_fun']() elif event.key == 'p': params['snap_annotations'] = not params['snap_annotations'] # remove the line if present if not params['snap_annotations']: _on_hover(None, params) params['plot_fun']() elif event.key == 'z': # zen mode: remove scrollbars and buttons _toggle_scrollbars(params) def _setup_annotation_fig(params): """Initialize the annotation figure.""" import matplotlib.pyplot as plt from matplotlib.widgets import RadioButtons, SpanSelector, Button if params['fig_annotation'] is not None: params['fig_annotation'].canvas.close_event() annotations = params['raw'].annotations labels = list(set(annotations.description)) labels = np.union1d(labels, params['added_label']) fig = figure_nobar(figsize=(4.5, 2.75 + len(labels) * 0.75)) fig.patch.set_facecolor('white') len_labels = max(len(labels), 1) # can't pass fig=fig here on matplotlib 2.0.2, need to wait for an update ax = plt.subplot2grid((len_labels + 2, 2), (0, 0), rowspan=len_labels, colspan=2, frameon=False) ax.set_title('Labels') ax.set_aspect('equal') button_ax = plt.subplot2grid((len_labels + 2, 2), (len_labels, 1), rowspan=1, colspan=1) label_ax = plt.subplot2grid((len_labels + 2, 2), (len_labels, 0), rowspan=1, colspan=1) plt.axis('off') text_ax = plt.subplot2grid((len_labels + 2, 2), (len_labels + 1, 0), rowspan=1, colspan=2) text_ax.text(0.5, 0.9, 'Left click & drag - Create/modify annotation\n' 'Right click - Delete annotation\n' 'Letter/number keys - Add character\n' 'Backspace - Delete character\n' 'Esc - Close window/exit annotation mode', va='top', ha='center') plt.axis('off') annotations_closed = partial(_annotations_closed, params=params) fig.canvas.mpl_connect('close_event', annotations_closed) fig.canvas.set_window_title('Annotations') fig.radio = RadioButtons(ax, labels, activecolor='#cccccc') radius = 0.15 circles = fig.radio.circles for circle, label in zip(circles, fig.radio.labels): circle.set_edgecolor(params['segment_colors'][label.get_text()]) circle.set_linewidth(4) circle.set_radius(radius / (len(labels))) label.set_x(circle.center[0] + (radius + 0.1) / len(labels)) if len(fig.radio.circles) < 1: col = '#ff0000' else: col = circles[0].get_edgecolor() fig.canvas.mpl_connect('key_press_event', partial( _change_annotation_description, params=params)) fig.button = Button(button_ax, 'Add label') fig.label = label_ax.text(0.5, 0.5, '"BAD_"', va='center', ha='center') fig.button.on_clicked(partial(_onclick_new_label, params=params)) plt_show(fig=fig) params['fig_annotation'] = fig ax = params['ax'] cb_onselect = partial(_annotate_select, params=params) selector = SpanSelector(ax, cb_onselect, 'horizontal', minspan=.1, rectprops=dict(alpha=0.5, facecolor=col)) if len(labels) == 0: selector.active = False params['ax'].selector = selector hover_callback = partial(_on_hover, params=params) params['hover_callback'] = params['fig'].canvas.mpl_connect( 'motion_notify_event', hover_callback) radio_clicked = partial(_annotation_radio_clicked, radio=fig.radio, selector=selector) fig.radio.on_clicked(radio_clicked) def _onclick_new_label(event, params): """Add new description on button press.""" text = params['fig_annotation'].label.get_text()[1:-1] params['added_label'].append(text) _setup_annotation_colors(params) _setup_annotation_fig(params) idx = [label.get_text() for label in params['fig_annotation'].radio.labels].index(text) _set_annotation_radio_button(idx, params) def _mouse_click(event, params): """Handle mouse clicks.""" if event.button not in (1, 3): return if event.button == 3: # right click if params['fig_annotation'] is not None: # annotation mode raw = params['raw'] if any(c.contains(event)[0] for c in params['ax'].collections): xdata = event.xdata - params['first_time'] onset = _sync_onset(raw, raw.annotations.onset) ends = onset + raw.annotations.duration ann_idx = np.where((xdata > onset) & (xdata < ends))[0] raw.annotations.delete(ann_idx) # only first one deleted _remove_segment_line(params) _plot_annotations(raw, params) params['plot_fun']() elif event.inaxes == params['ax']: # hide green line _draw_vert_line(None, params, hide=True) else: # do nothing return else: if event.inaxes is None: # check if channel label is clicked if params['n_channels'] > 100: return ax = params['ax'] ylim = ax.get_ylim() pos = ax.transData.inverted().transform((event.x, event.y)) if pos[0] > params['t_start'] or pos[1] < 0 or pos[1] > ylim[0]: return params['label_click_fun'](pos) # vertical scrollbar changed elif event.inaxes == params['ax_vscroll']: if 'fig_selection' in params.keys(): _handle_change_selection(event, params) else: ch_start = max(int(event.ydata) - params['n_channels'] // 2, 0) if params['ch_start'] != ch_start: params['ch_start'] = ch_start params['plot_fun']() # horizontal scrollbar changed elif event.inaxes == params['ax_hscroll']: _plot_raw_time(event.xdata - params['duration'] / 2, params) params['update_fun']() params['plot_fun']() elif event.inaxes == params['ax']: params['pick_bads_fun'](event) def _handle_topomap_bads(ch_name, params): """Color channels in selection topomap when selecting bads.""" for t in _DATA_CH_TYPES_SPLIT: if t in params['types']: types = np.where(np.array(params['types']) == t)[0] break color_ind = np.where(np.array( params['info']['ch_names'])[types] == ch_name)[0] if len(color_ind) > 0: sensors = params['fig_selection'].axes[1].collections[0] this_color = sensors._edgecolors[color_ind][0] if all(this_color == [1., 0., 0., 1.]): # is red sensors._edgecolors[color_ind] = [0., 0., 0., 1.] else: # is black sensors._edgecolors[color_ind] = [1., 0., 0., 1.] params['fig_selection'].canvas.draw() def _find_channel_idx(ch_name, params): """Find all indices when using selections.""" indices = list() offset = 0 labels = [label._text for label in params['fig_selection'].radio.labels] for label in labels: if label == 'Custom': continue # Custom selection not included as it shifts the indices. selection = params['selections'][label] hits = np.where(np.array(params['raw'].ch_names)[selection] == ch_name) for idx in hits[0]: indices.append(offset + idx) offset += len(selection) return indices def _draw_vert_line(xdata, params, hide=False): """Draw vertical line.""" if not hide: params['ax_vertline'].set_xdata(xdata) params['ax_hscroll_vertline'].set_xdata(xdata) params['vertline_t'].set_text('%0.2f ' % xdata) params['ax_vertline'].set_visible(not hide) params['ax_hscroll_vertline'].set_visible(not hide) params['vertline_t'].set_visible(not hide) def _select_bads(event, params, bads): """Select bad channels onpick. Returns updated bads list.""" # trade-off, avoid selecting more than one channel when drifts are present # however for clean data don't click on peaks but on flat segments if params['butterfly']: _draw_vert_line(event.xdata, params) return bads lines = event.inaxes.lines for line in lines: ydata = line.get_ydata() if not isinstance(ydata, list) and not np.isnan(ydata).any(): if line.contains(event)[0]: # click on a signal: toggle bad this_chan = vars(line)['ch_name'] if this_chan in params['info']['ch_names']: if 'fig_selection' in params: ch_idx = _find_channel_idx(this_chan, params) _handle_topomap_bads(this_chan, params) else: ch_idx = [params['ch_start'] + lines.index(line)] if this_chan not in bads: bads.append(this_chan) color = params['bad_color'] line.set_zorder(-1) else: while this_chan in bads: bads.remove(this_chan) color = vars(line)['def_color'] line.set_zorder(0) line.set_color(color) for idx in ch_idx: params['ax_vscroll'].patches[idx].set_color(color) break else: # click in the background (not on a signal): set green line _draw_vert_line(event.xdata, params) return bads def _show_help(col1, col2, width, height): fig_help = figure_nobar(figsize=(width, height), dpi=80) fig_help.canvas.set_window_title('Help') ax = fig_help.add_subplot(111) celltext = [[c1, c2] for c1, c2 in zip(col1.strip().split("\n"), col2.strip().split("\n"))] table = ax.table(cellText=celltext, loc="center", cellLoc="left") table.auto_set_font_size(False) table.set_fontsize(12) ax.set_axis_off() for (row, col), cell in table.get_celld().items(): cell.set_edgecolor(None) # remove cell borders # right justify, following: # https://stackoverflow.com/questions/48210749/matplotlib-table-assign-different-text-alignments-to-different-columns?rq=1 # noqa: E501 if col == 0: cell._loc = 'right' fig_help.canvas.mpl_connect('key_press_event', _key_press) # this should work for non-test cases try: fig_help.canvas.draw() plt_show(fig=fig_help, warn=False) except Exception: pass def _onclick_help(event, params): """Draw help window.""" col1, col2 = _get_help_text(params) params['fig_help'] = _show_help( col1=col1, col2=col2, width=9, height=5, ) def _key_press(event): """Handle key press in dialog.""" import matplotlib.pyplot as plt if event.key == 'escape': plt.close(event.canvas.figure) def _setup_browser_offsets(params, n_channels): """Compute viewport height and adjust offsets.""" ylim = [n_channels * 2 + 1, 0] offset = ylim[0] / n_channels params['offsets'] = np.arange(n_channels) * offset + (offset / 2.) params['n_channels'] = n_channels params['ax'].set_yticks(params['offsets']) params['ax'].set_ylim(ylim) params['vsel_patch'].set_height(n_channels) line = params['ax_vertline'] line.set_data(line._x, np.array(params['ax'].get_ylim())) class ClickableImage(object): """Display an image so you can click on it and store x/y positions. Takes as input an image array (can be any array that works with imshow, but will work best with images. Displays the image and lets you click on it. Stores the xy coordinates of each click, so now you can superimpose something on top of it. Upon clicking, the x/y coordinate of the cursor will be stored in self.coords, which is a list of (x, y) tuples. Parameters ---------- imdata : ndarray The image that you wish to click on for 2-d points. **kwargs : dict Keyword arguments. Passed to ax.imshow. Notes ----- .. versionadded:: 0.9.0 """ def __init__(self, imdata, **kwargs): """Display the image for clicking.""" import matplotlib.pyplot as plt self.coords = [] self.imdata = imdata self.fig = plt.figure() self.ax = self.fig.add_subplot(111) self.ymax = self.imdata.shape[0] self.xmax = self.imdata.shape[1] self.im = self.ax.imshow(imdata, extent=(0, self.xmax, 0, self.ymax), picker=True, **kwargs) self.ax.axis('off') self.fig.canvas.mpl_connect('pick_event', self.onclick) plt_show(block=True) def onclick(self, event): """Handle Mouse clicks. Parameters ---------- event : matplotlib.backend_bases.Event The matplotlib object that we use to get x/y position. """ mouseevent = event.mouseevent self.coords.append((mouseevent.xdata, mouseevent.ydata)) def plot_clicks(self, **kwargs): """Plot the x/y positions stored in self.coords. Parameters ---------- **kwargs : dict Arguments are passed to imshow in displaying the bg image. """ import matplotlib.pyplot as plt if len(self.coords) == 0: raise ValueError('No coordinates found, make sure you click ' 'on the image that is first shown.') f, ax = plt.subplots() ax.imshow(self.imdata, extent=(0, self.xmax, 0, self.ymax), **kwargs) xlim, ylim = [ax.get_xlim(), ax.get_ylim()] xcoords, ycoords = zip(*self.coords) ax.scatter(xcoords, ycoords, c='#ff0000') ann_text = np.arange(len(self.coords)).astype(str) for txt, coord in zip(ann_text, self.coords): ax.annotate(txt, coord, fontsize=20, color='#ff0000') ax.set_xlim(xlim) ax.set_ylim(ylim) plt_show() def to_layout(self, **kwargs): """Turn coordinates into an MNE Layout object. Normalizes by the image you used to generate clicks Parameters ---------- **kwargs : dict Arguments are passed to generate_2d_layout. Returns ------- layout : instance of Layout The layout. """ from ..channels.layout import generate_2d_layout coords = np.array(self.coords) lt = generate_2d_layout(coords, bg_image=self.imdata, **kwargs) return lt def _fake_click(fig, ax, point, xform='ax', button=1, kind='press'): """Fake a click at a relative point within axes.""" if xform == 'ax': x, y = ax.transAxes.transform_point(point) elif xform == 'data': x, y = ax.transData.transform_point(point) else: assert xform == 'pix' x, y = point if kind == 'press': func = partial(fig.canvas.button_press_event, x=x, y=y, button=button) elif kind == 'release': func = partial(fig.canvas.button_release_event, x=x, y=y, button=button) elif kind == 'motion': func = partial(fig.canvas.motion_notify_event, x=x, y=y) func(guiEvent=None) def add_background_image(fig, im, set_ratios=None): """Add a background image to a plot. Adds the image specified in ``im`` to the figure ``fig``. This is generally meant to be done with topo plots, though it could work for any plot. .. note:: This modifies the figure and/or axes in place. Parameters ---------- fig : Figure The figure you wish to add a bg image to. im : array, shape (M, N, {3, 4}) A background image for the figure. This must be a valid input to `matplotlib.pyplot.imshow`. Defaults to None. set_ratios : None | str Set the aspect ratio of any axes in fig to the value in set_ratios. Defaults to None, which does nothing to axes. Returns ------- ax_im : instance of Axes Axes created corresponding to the image you added. Notes ----- .. versionadded:: 0.9.0 """ if im is None: # Don't do anything and return nothing return None if set_ratios is not None: for ax in fig.axes: ax.set_aspect(set_ratios) ax_im = fig.add_axes([0, 0, 1, 1], label='background') ax_im.imshow(im, aspect='auto') ax_im.set_zorder(-1) return ax_im def _find_peaks(evoked, npeaks): """Find peaks from evoked data. Returns ``npeaks`` biggest peaks as a list of time points. """ from scipy.signal import argrelmax gfp = evoked.data.std(axis=0) order = len(evoked.times) // 30 if order < 1: order = 1 peaks = argrelmax(gfp, order=order, axis=0)[0] if len(peaks) > npeaks: max_indices = np.argsort(gfp[peaks])[-npeaks:] peaks = np.sort(peaks[max_indices]) times = evoked.times[peaks] if len(times) == 0: times = [evoked.times[gfp.argmax()]] return times def _process_times(inst, use_times, n_peaks=None, few=False): """Return a list of times for topomaps.""" if isinstance(use_times, str): if use_times == 'interactive': use_times, n_peaks = 'peaks', 1 if use_times == 'peaks': if n_peaks is None: n_peaks = min(3 if few else 7, len(inst.times)) use_times = _find_peaks(inst, n_peaks) elif use_times == 'auto': if n_peaks is None: n_peaks = min(5 if few else 10, len(use_times)) use_times = np.linspace(inst.times[0], inst.times[-1], n_peaks) else: raise ValueError("Got an unrecognized method for `times`. Only " "'peaks', 'auto' and 'interactive' are supported " "(or directly passing numbers).") elif np.isscalar(use_times): use_times = [use_times] use_times = np.array(use_times, float) if use_times.ndim != 1: raise ValueError('times must be 1D, got %d dimensions' % use_times.ndim) if len(use_times) > 25: warn('More than 25 topomaps plots requested. This might take a while.') return use_times @verbose def plot_sensors(info, kind='topomap', ch_type=None, title=None, show_names=False, ch_groups=None, to_sphere=True, axes=None, block=False, show=True, sphere=None, verbose=None): """Plot sensors positions. Parameters ---------- info : instance of Info Info structure containing the channel locations. kind : str Whether to plot the sensors as 3d, topomap or as an interactive sensor selection dialog. Available options 'topomap', '3d', 'select'. If 'select', a set of channels can be selected interactively by using lasso selector or clicking while holding control key. The selected channels are returned along with the figure instance. Defaults to 'topomap'. ch_type : None | str The channel type to plot. Available options 'mag', 'grad', 'eeg', 'seeg', 'ecog', 'all'. If ``'all'``, all the available mag, grad, eeg, seeg and ecog channels are plotted. If None (default), then channels are chosen in the order given above. title : str | None Title for the figure. If None (default), equals to ``'Sensor positions (%%s)' %% ch_type``. show_names : bool | array of str Whether to display all channel names. If an array, only the channel names in the array are shown. Defaults to False. ch_groups : 'position' | array of shape (n_ch_groups, n_picks) | None Channel groups for coloring the sensors. If None (default), default coloring scheme is used. If 'position', the sensors are divided into 8 regions. See ``order`` kwarg of :func:`mne.viz.plot_raw`. If array, the channels are divided by picks given in the array. .. versionadded:: 0.13.0 to_sphere : bool Whether to project the 3d locations to a sphere. When False, the sensor array appears similar as to looking downwards straight above the subject's head. Has no effect when kind='3d'. Defaults to True. .. versionadded:: 0.14.0 axes : instance of Axes | instance of Axes3D | None Axes to draw the sensors to. If ``kind='3d'``, axes must be an instance of Axes3D. If None (default), a new axes will be created. .. versionadded:: 0.13.0 block : bool Whether to halt program execution until the figure is closed. Defaults to False. .. versionadded:: 0.13.0 show : bool Show figure if True. Defaults to True. %(topomap_sphere_auto)s %(verbose)s Returns ------- fig : instance of Figure Figure containing the sensor topography. selection : list A list of selected channels. Only returned if ``kind=='select'``. See Also -------- mne.viz.plot_layout Notes ----- This function plots the sensor locations from the info structure using matplotlib. For drawing the sensors using mayavi see :func:`mne.viz.plot_alignment`. .. versionadded:: 0.12.0 """ from .evoked import _rgb _check_option('kind', kind, ['topomap', '3d', 'select']) if not isinstance(info, Info): raise TypeError('info must be an instance of Info not %s' % type(info)) ch_indices = channel_indices_by_type(info) allowed_types = _DATA_CH_TYPES_SPLIT if ch_type is None: for this_type in allowed_types: if _contains_ch_type(info, this_type): ch_type = this_type break picks = ch_indices[ch_type] elif ch_type == 'all': picks = list() for this_type in allowed_types: picks += ch_indices[this_type] elif ch_type in allowed_types: picks = ch_indices[ch_type] else: raise ValueError("ch_type must be one of %s not %s!" % (allowed_types, ch_type)) if len(picks) == 0: raise ValueError('Could not find any channels of type %s.' % ch_type) chs = [info['chs'][pick] for pick in picks] if not _check_ch_locs(chs): raise RuntimeError('No valid channel positions found') dev_head_t = info['dev_head_t'] pos = np.empty((len(chs), 3)) for ci, ch in enumerate(chs): pos[ci] = ch['loc'][:3] if ch['coord_frame'] == FIFF.FIFFV_COORD_DEVICE: if dev_head_t is None: warn('dev_head_t is None, transforming MEG sensors to head ' 'coordinate frame using identity transform') dev_head_t = np.eye(4) pos[ci] = apply_trans(dev_head_t, pos[ci]) del dev_head_t ch_names = np.array([ch['ch_name'] for ch in chs]) bads = [idx for idx, name in enumerate(ch_names) if name in info['bads']] if ch_groups is None: def_colors = _handle_default('color') colors = ['red' if i in bads else def_colors[channel_type(info, pick)] for i, pick in enumerate(picks)] else: if ch_groups in ['position', 'selection']: if ch_groups == 'position': ch_groups = _divide_to_regions(info, add_stim=False) ch_groups = list(ch_groups.values()) else: ch_groups, color_vals = list(), list() for selection in _SELECTIONS + _EEG_SELECTIONS: channels = pick_channels( info['ch_names'], read_selection(selection, info=info)) ch_groups.append(channels) color_vals = np.ones((len(ch_groups), 4)) for idx, ch_group in enumerate(ch_groups): color_picks = [np.where(picks == ch)[0][0] for ch in ch_group if ch in picks] if len(color_picks) == 0: continue x, y, z = pos[color_picks].T color = np.mean(_rgb(x, y, z), axis=0) color_vals[idx, :3] = color # mean of spatial color else: import matplotlib.pyplot as plt colors = np.linspace(0, 1, len(ch_groups)) color_vals = [plt.cm.jet(colors[i]) for i in range(len(ch_groups))] if not isinstance(ch_groups, (np.ndarray, list)): raise ValueError("ch_groups must be None, 'position', " "'selection', or an array. Got %s." % ch_groups) colors = np.zeros((len(picks), 4)) for pick_idx, pick in enumerate(picks): for ind, value in enumerate(ch_groups): if pick in value: colors[pick_idx] = color_vals[ind] break title = 'Sensor positions (%s)' % ch_type if title is None else title fig = _plot_sensors(pos, info, picks, colors, bads, ch_names, title, show_names, axes, show, kind, block, to_sphere, sphere) if kind == 'select': return fig, fig.lasso.selection return fig def _onpick_sensor(event, fig, ax, pos, ch_names, show_names): """Pick a channel in plot_sensors.""" if event.mouseevent.key == 'control' and fig.lasso is not None: for ind in event.ind: fig.lasso.select_one(ind) return if show_names: return # channel names already visible ind = event.ind[0] # Just take the first sensor. ch_name = ch_names[ind] this_pos = pos[ind] # XXX: Bug in matplotlib won't allow setting the position of existing # text item, so we create a new one. ax.texts.pop(0) if len(this_pos) == 3: ax.text(this_pos[0], this_pos[1], this_pos[2], ch_name) else: ax.text(this_pos[0], this_pos[1], ch_name) fig.canvas.draw() def _close_event(event, fig): """Listen for sensor plotter close event.""" if getattr(fig, 'lasso', None) is not None: fig.lasso.disconnect() def _plot_sensors(pos, info, picks, colors, bads, ch_names, title, show_names, ax, show, kind, block, to_sphere, sphere): """Plot sensors.""" import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from .topomap import _get_pos_outlines, _draw_outlines sphere = _check_sphere(sphere, info) edgecolors = np.repeat('black', len(colors)) edgecolors[bads] = 'red' if ax is None: fig = plt.figure(figsize=(max(plt.rcParams['figure.figsize']),) * 2) if kind == '3d': Axes3D(fig) ax = fig.gca(projection='3d') else: ax = fig.add_subplot(111) else: fig = ax.get_figure() if kind == '3d': ax.text(0, 0, 0, '', zorder=1) ax.scatter(pos[:, 0], pos[:, 1], pos[:, 2], picker=True, c=colors, s=75, edgecolor=edgecolors, linewidth=2) ax.azim = 90 ax.elev = 0 ax.xaxis.set_label_text('x (m)') ax.yaxis.set_label_text('y (m)') ax.zaxis.set_label_text('z (m)') else: # kind in 'select', 'topomap' ax.text(0, 0, '', zorder=1) pos, outlines = _get_pos_outlines(info, picks, sphere, to_sphere=to_sphere) _draw_outlines(ax, outlines) pts = ax.scatter(pos[:, 0], pos[:, 1], picker=True, clip_on=False, c=colors, edgecolors=edgecolors, s=25, lw=2) if kind == 'select': fig.lasso = SelectFromCollection(ax, pts, ch_names) else: fig.lasso = None # Equal aspect for 3D looks bad, so only use for 2D ax.set(aspect='equal') fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None) ax.axis("off") # remove border around figure del sphere connect_picker = True if show_names: if isinstance(show_names, (list, np.ndarray)): # only given channels indices = [list(ch_names).index(name) for name in show_names] else: # all channels indices = range(len(pos)) for idx in indices: this_pos = pos[idx] if kind == '3d': ax.text(this_pos[0], this_pos[1], this_pos[2], ch_names[idx]) else: ax.text(this_pos[0] + 0.0025, this_pos[1], ch_names[idx], ha='left', va='center') connect_picker = (kind == 'select') if connect_picker: picker = partial(_onpick_sensor, fig=fig, ax=ax, pos=pos, ch_names=ch_names, show_names=show_names) fig.canvas.mpl_connect('pick_event', picker) fig.suptitle(title) closed = partial(_close_event, fig=fig) fig.canvas.mpl_connect('close_event', closed) plt_show(show, block=block) return fig def _compute_scalings(scalings, inst, remove_dc=False, duration=10): """Compute scalings for each channel type automatically. Parameters ---------- scalings : dict The scalings for each channel type. If any values are 'auto', this will automatically compute a reasonable scaling for that channel type. Any values that aren't 'auto' will not be changed. inst : instance of Raw or Epochs The data for which you want to compute scalings. If data is not preloaded, this will read a subset of times / epochs up to 100mb in size in order to compute scalings. remove_dc : bool Whether to remove the mean (DC) before calculating the scalings. If True, the mean will be computed and subtracted for short epochs in order to compensate not only for global mean offset, but also for slow drifts in the signals. duration : float If remove_dc is True, the mean will be computed and subtracted on segments of length ``duration`` seconds. Returns ------- scalings : dict A scalings dictionary with updated values """ from ..io.base import BaseRaw from ..epochs import BaseEpochs scalings = _handle_default('scalings_plot_raw', scalings) if not isinstance(inst, (BaseRaw, BaseEpochs)): raise ValueError('Must supply either Raw or Epochs') ch_types = channel_indices_by_type(inst.info) ch_types = {i_type: i_ixs for i_type, i_ixs in ch_types.items() if len(i_ixs) != 0} scalings = deepcopy(scalings) if inst.preload is False: if isinstance(inst, BaseRaw): # Load a window of data from the center up to 100mb in size n_times = 1e8 // (len(inst.ch_names) * 8) n_times = np.clip(n_times, 1, inst.n_times) n_secs = n_times / float(inst.info['sfreq']) time_middle = np.mean(inst.times) tmin = np.clip(time_middle - n_secs / 2., inst.times.min(), None) tmax = np.clip(time_middle + n_secs / 2., None, inst.times.max()) data = inst._read_segment(tmin, tmax) elif isinstance(inst, BaseEpochs): # Load a random subset of epochs up to 100mb in size n_epochs = 1e8 // (len(inst.ch_names) * len(inst.times) * 8) n_epochs = int(np.clip(n_epochs, 1, len(inst))) ixs_epochs = np.random.choice(range(len(inst)), n_epochs, False) inst = inst.copy()[ixs_epochs].load_data() else: data = inst._data if isinstance(inst, BaseEpochs): data = inst._data.swapaxes(0, 1).reshape([len(inst.ch_names), -1]) # Iterate through ch types and update scaling if ' auto' for key, value in scalings.items(): if key not in ch_types.keys(): continue if not (isinstance(value, str) and value == 'auto'): try: scalings[key] = float(value) except Exception: raise ValueError('scalings must be "auto" or float, got ' 'scalings[%r]=%r which could not be ' 'converted to float' % (key, value)) continue this_data = data[ch_types[key]] if remove_dc and (this_data.shape[1] / inst.info["sfreq"] >= duration): length = int(duration * inst.info["sfreq"]) # segment length # truncate data so that we can divide into segments of equal length this_data = this_data[:, :this_data.shape[1] // length * length] shape = this_data.shape # original shape this_data = this_data.T.reshape(-1, length, shape[0]) # segment this_data -= np.nanmean(this_data, 0) # subtract segment means this_data = this_data.T.reshape(shape) # reshape into original this_data = this_data.ravel() this_data = this_data[np.isfinite(this_data)] if this_data.size: iqr = np.diff(np.percentile(this_data, [25, 75]))[0] else: iqr = 1. scalings[key] = iqr return scalings def _setup_cmap(cmap, n_axes=1, norm=False): """Set color map interactivity.""" if cmap == 'interactive': cmap = ('Reds' if norm else 'RdBu_r', True) elif not isinstance(cmap, tuple): if cmap is None: cmap = 'Reds' if norm else 'RdBu_r' cmap = (cmap, False if n_axes > 2 else True) return cmap def _prepare_joint_axes(n_maps, figsize=None): """Prepare axes for topomaps and colorbar in joint plot figure. Parameters ---------- n_maps: int Number of topomaps to include in the figure figsize: tuple Figure size, see plt.figsize Returns ------- fig : matplotlib.figure.Figure Figure with initialized axes main_ax: matplotlib.axes._subplots.AxesSubplot Axes in which to put the main plot map_ax: list List of axes for each topomap cbar_ax: matplotlib.axes._subplots.AxesSubplot Axes for colorbar next to topomaps """ import matplotlib.pyplot as plt fig = plt.figure(figsize=figsize) main_ax = fig.add_subplot(212) ts = n_maps + 2 map_ax = [plt.subplot(4, ts, x + 2 + ts) for x in range(n_maps)] # Position topomap subplots on the second row, starting on the # second column cbar_ax = plt.subplot(4, 5 * (ts + 1), 10 * (ts + 1)) # Position colorbar at the very end of a more finely divided # second row of subplots return fig, main_ax, map_ax, cbar_ax class DraggableColorbar(object): """Enable interactive colorbar. See http://www.ster.kuleuven.be/~pieterd/python/html/plotting/interactive_colorbar.html """ # noqa: E501 def __init__(self, cbar, mappable): import matplotlib.pyplot as plt self.cbar = cbar self.mappable = mappable self.press = None self.cycle = sorted([i for i in dir(plt.cm) if hasattr(getattr(plt.cm, i), 'N')]) self.cycle += [mappable.get_cmap().name] self.index = self.cycle.index(mappable.get_cmap().name) self.lims = (self.cbar.norm.vmin, self.cbar.norm.vmax) self.connect() def connect(self): """Connect to all the events we need.""" self.cidpress = self.cbar.patch.figure.canvas.mpl_connect( 'button_press_event', self.on_press) self.cidrelease = self.cbar.patch.figure.canvas.mpl_connect( 'button_release_event', self.on_release) self.cidmotion = self.cbar.patch.figure.canvas.mpl_connect( 'motion_notify_event', self.on_motion) self.keypress = self.cbar.patch.figure.canvas.mpl_connect( 'key_press_event', self.key_press) self.scroll = self.cbar.patch.figure.canvas.mpl_connect( 'scroll_event', self.on_scroll) def on_press(self, event): """Handle button press.""" if event.inaxes != self.cbar.ax: return self.press = event.y def key_press(self, event): """Handle key press.""" # print(event.key) scale = self.cbar.norm.vmax - self.cbar.norm.vmin perc = 0.03 if event.key == 'down': self.index += 1 elif event.key == 'up': self.index -= 1 elif event.key == ' ': # space key resets scale self.cbar.norm.vmin = self.lims[0] self.cbar.norm.vmax = self.lims[1] elif event.key == '+': self.cbar.norm.vmin -= (perc * scale) * -1 self.cbar.norm.vmax += (perc * scale) * -1 elif event.key == '-': self.cbar.norm.vmin -= (perc * scale) * 1 self.cbar.norm.vmax += (perc * scale) * 1 elif event.key == 'pageup': self.cbar.norm.vmin -= (perc * scale) * 1 self.cbar.norm.vmax -= (perc * scale) * 1 elif event.key == 'pagedown': self.cbar.norm.vmin -= (perc * scale) * -1 self.cbar.norm.vmax -= (perc * scale) * -1 else: return if self.index < 0: self.index = len(self.cycle) - 1 elif self.index >= len(self.cycle): self.index = 0 cmap = self.cycle[self.index] self.cbar.mappable.set_cmap(cmap) self.cbar.draw_all() self.mappable.set_cmap(cmap) self.mappable.set_norm(self.cbar.norm) self.cbar.patch.figure.canvas.draw() def on_motion(self, event): """Handle mouse movements.""" if self.press is None: return if event.inaxes != self.cbar.ax: return yprev = self.press dy = event.y - yprev self.press = event.y scale = self.cbar.norm.vmax - self.cbar.norm.vmin perc = 0.03 if event.button == 1: self.cbar.norm.vmin -= (perc * scale) * np.sign(dy) self.cbar.norm.vmax -= (perc * scale) * np.sign(dy) elif event.button == 3: self.cbar.norm.vmin -= (perc * scale) * np.sign(dy) self.cbar.norm.vmax += (perc * scale) * np.sign(dy) self.cbar.draw_all() self.mappable.set_norm(self.cbar.norm) self.cbar.patch.figure.canvas.draw() def on_release(self, event): """Handle release.""" self.press = None self.mappable.set_norm(self.cbar.norm) self.cbar.patch.figure.canvas.draw() def on_scroll(self, event): """Handle scroll.""" scale = 1.1 if event.step < 0 else 1. / 1.1 self.cbar.norm.vmin *= scale self.cbar.norm.vmax *= scale self.cbar.draw_all() self.mappable.set_norm(self.cbar.norm) self.cbar.patch.figure.canvas.draw() class SelectFromCollection(object): """Select channels from a matplotlib collection using ``LassoSelector``. Selected channels are saved in the ``selection`` attribute. This tool highlights selected points by fading other points out (i.e., reducing their alpha values). Parameters ---------- ax : instance of Axes Axes to interact with. collection : instance of matplotlib collection Collection you want to select from. alpha_other : 0 <= float <= 1 To highlight a selection, this tool sets all selected points to an alpha value of 1 and non-selected points to ``alpha_other``. Defaults to 0.3. Notes ----- This tool selects collection objects based on their *origins* (i.e., ``offsets``). Emits mpl event 'lasso_event' when selection is ready. """ def __init__(self, ax, collection, ch_names, alpha_other=0.3): from matplotlib import __version__ if LooseVersion(__version__) < LooseVersion('1.2.1'): raise ImportError('Interactive selection not possible for ' 'matplotlib versions < 1.2.1. Upgrade ' 'matplotlib.') from matplotlib.widgets import LassoSelector self.canvas = ax.figure.canvas self.collection = collection self.ch_names = ch_names self.alpha_other = alpha_other self.xys = collection.get_offsets() self.Npts = len(self.xys) # Ensure that we have separate colors for each object self.fc = collection.get_facecolors() self.ec = collection.get_edgecolors() if len(self.fc) == 0: raise ValueError('Collection must have a facecolor') elif len(self.fc) == 1: self.fc = np.tile(self.fc, self.Npts).reshape(self.Npts, -1) self.ec = np.tile(self.ec, self.Npts).reshape(self.Npts, -1) self.fc[:, -1] = self.alpha_other # deselect in the beginning self.ec[:, -1] = self.alpha_other self.lasso = LassoSelector(ax, onselect=self.on_select, lineprops={'color': 'red', 'linewidth': .5}) self.selection = list() def on_select(self, verts): """Select a subset from the collection.""" from matplotlib.path import Path if len(verts) <= 3: # Seems to be a good way to exclude single clicks. return path = Path(verts) inds = np.nonzero([path.contains_point(xy) for xy in self.xys])[0] if self.canvas._key == 'control': # Appending selection. sels = [np.where(self.ch_names == c)[0][0] for c in self.selection] inters = set(inds) - set(sels) inds = list(inters.union(set(sels) - set(inds))) while len(self.selection) > 0: self.selection.pop(0) self.selection.extend(self.ch_names[inds]) self.fc[:, -1] = self.alpha_other self.fc[inds, -1] = 1 self.collection.set_facecolors(self.fc) self.ec[:, -1] = self.alpha_other self.ec[inds, -1] = 1 self.collection.set_edgecolors(self.ec) self.canvas.draw_idle() self.canvas.callbacks.process('lasso_event') def select_one(self, ind): """Select or deselect one sensor.""" ch_name = self.ch_names[ind] if ch_name in self.selection: sel_ind = self.selection.index(ch_name) self.selection.pop(sel_ind) this_alpha = self.alpha_other else: self.selection.append(ch_name) this_alpha = 1 self.fc[ind, -1] = this_alpha self.ec[ind, -1] = this_alpha self.collection.set_facecolors(self.fc) self.collection.set_edgecolors(self.ec) self.canvas.draw_idle() self.canvas.callbacks.process('lasso_event') def disconnect(self): """Disconnect the lasso selector.""" self.lasso.disconnect_events() self.fc[:, -1] = 1 self.ec[:, -1] = 1 self.collection.set_facecolors(self.fc) self.collection.set_edgecolors(self.ec) self.canvas.draw_idle() def _annotate_select(vmin, vmax, params): """Handle annotation span selector.""" raw = params['raw'] onset = _sync_onset(raw, vmin, True) - params['first_time'] duration = vmax - vmin active_idx = _get_active_radio_idx(params['fig_annotation'].radio) description = params['fig_annotation'].radio.labels[active_idx].get_text() _merge_annotations(onset, onset + duration, description, raw.annotations) _plot_annotations(params['raw'], params) params['plot_fun']() def _plot_annotations(raw, params): """Set up annotations for plotting in raw browser.""" while len(params['ax_hscroll'].collections) > 0: params['ax_hscroll'].collections.pop() segments = list() _setup_annotation_colors(params) for idx, annot in enumerate(raw.annotations): annot_start = _sync_onset(raw, annot['onset']) + params['first_time'] annot_end = annot_start + annot['duration'] segments.append([annot_start, annot_end]) params['ax_hscroll'].fill_betweenx( (0., 1.), annot_start, annot_end, alpha=0.3, color=params['segment_colors'][annot['description']]) # Do not adjust half a sample backward (even though this would make it # clearer what is included) because this breaks click-drag functionality params['segments'] = np.array(segments) def _get_color_list(annotations=False): """Get the current color list from matplotlib rcParams. Parameters ---------- annotations : boolean Has no influence on the function if false. If true, check if color "red" (#ff0000) is in the cycle and remove it. Returns ------- colors : list """ import matplotlib.pyplot as plt color_cycle = plt.rcParams.get('axes.prop_cycle') if not color_cycle: # Use deprecated color_cycle to avoid KeyErrors in environments # with Python 2.7 and Matplotlib < 1.5 # this will already be a list colors = plt.rcParams.get('axes.color_cycle') else: # we were able to use the prop_cycle. Now just convert to list colors = color_cycle.by_key()['color'] # If we want annotations, red is reserved ... remove if present if annotations and '#ff0000' in colors: colors.remove('#ff0000') return colors def _setup_annotation_colors(params): """Set up colors for annotations.""" raw = params['raw'] segment_colors = params.get('segment_colors', dict()) # sort the segments by start time ann_order = raw.annotations.onset.argsort(axis=0) descriptions = raw.annotations.description[ann_order] color_keys = np.union1d(descriptions, params['added_label']) color_cycle = cycle(_get_color_list(annotations=True)) # no red for key, color in segment_colors.items(): if color != '#ff0000' and key in color_keys: next(color_cycle) for idx, key in enumerate(color_keys): if key in segment_colors: continue elif key.lower().startswith('bad') or key.lower().startswith('edge'): segment_colors[key] = '#ff0000' else: segment_colors[key] = next(color_cycle) params['segment_colors'] = segment_colors def _annotations_closed(event, params): """Clean up on annotation dialog close.""" import matplotlib.pyplot as plt plt.close(params['fig_annotation']) if params['ax'].selector is not None: params['ax'].selector.disconnect_events() params['ax'].selector = None params['fig_annotation'] = None if params['segment_line'] is not None: params['segment_line'].remove() params['segment_line'] = None params['fig'].canvas.mpl_disconnect(params['hover_callback']) params['fig_annotation'] = None params['fig'].canvas.draw() def _on_hover(event, params): """Handle hover event.""" if not params["snap_annotations"]: # don't snap to annotations _remove_segment_line(params) return from matplotlib.patheffects import Stroke, Normal if (event.button is not None or event.inaxes != params['ax'] or event.xdata is None): return for coll in params['ax'].collections: if coll.contains(event)[0]: path = coll.get_paths() assert len(path) == 1 path = path[0] color = coll.get_edgecolors()[0] mn = path.vertices[:, 0].min() mx = path.vertices[:, 0].max() # left/right line x = mn if abs(event.xdata - mn) < abs(event.xdata - mx) else mx mask = path.vertices[:, 0] == x ylim = params['ax'].get_ylim() def drag_callback(x0): path.vertices[mask, 0] = x0 if params['segment_line'] is None: modify_callback = partial(_annotation_modify, params=params) line = params['ax'].plot([x, x], ylim, color=color, linewidth=2., picker=True)[0] line.set_pickradius(5.) dl = DraggableLine(line, modify_callback, drag_callback) params['segment_line'] = dl else: params['segment_line'].set_x(x) params['segment_line'].drag_callback = drag_callback line = params['segment_line'].line pe = [Stroke(linewidth=4, foreground=color, alpha=0.5), Normal()] line.set_path_effects(pe if line.contains(event)[0] else pe[1:]) params['ax'].selector.active = False params['fig'].canvas.draw() return _remove_segment_line(params) def _remove_segment_line(params): """Remove annotation line from the view.""" if params['segment_line'] is not None: params['segment_line'].remove() params['segment_line'] = None params['ax'].selector.active = True def _annotation_modify(old_x, new_x, params): """Modify annotation.""" raw = params['raw'] segment = np.array(np.where(params['segments'] == old_x)) if segment.shape[1] == 0: return annotations = params['raw'].annotations idx = [segment[0][0], segment[1][0]] onset = _sync_onset(raw, params['segments'][idx[0]][0], True) ann_idx = np.where(annotations.onset == onset - params['first_time'])[0] if idx[1] == 0: # start of annotation onset = _sync_onset(raw, new_x, True) - params['first_time'] duration = annotations.duration[ann_idx] + old_x - new_x else: # end of annotation onset = annotations.onset[ann_idx] duration = _sync_onset(raw, new_x, True) - onset - params['first_time'] if duration < 0: onset += duration duration *= -1. _merge_annotations(onset, onset + duration, annotations.description[ann_idx], annotations, ann_idx) _plot_annotations(params['raw'], params) _remove_segment_line(params) params['plot_fun']() def _merge_annotations(start, stop, description, annotations, current=()): """Handle drawn annotations.""" ends = annotations.onset + annotations.duration idx = np.intersect1d(np.where(ends >= start)[0], np.where(annotations.onset <= stop)[0]) idx = np.intersect1d(idx, np.where(annotations.description == description)[0]) new_idx = np.setdiff1d(idx, current) # don't include modified annotation end = max(np.append((annotations.onset[new_idx] + annotations.duration[new_idx]), stop)) onset = min(np.append(annotations.onset[new_idx], start)) duration = end - onset annotations.delete(idx) annotations.append(onset, duration, description) def _change_annotation_description(event, params): """Handle keys in annotation dialog.""" import matplotlib.pyplot as plt fig = event.canvas.figure text = fig.label.get_text()[1:-1] if event.key == 'backspace': text = text[:-1] elif event.key == 'escape': plt.close(fig) return elif event.key == 'enter': _onclick_new_label(event, params) elif len(event.key) > 1 or event.key == ';': # ignore modifier keys return else: text = text + event.key fig.label.set_text('"' + text + '"') fig.canvas.draw() def _annotation_radio_clicked(label, radio, selector): """Handle annotation radio buttons.""" idx = _get_active_radio_idx(radio) color = radio.circles[idx].get_edgecolor() selector.rect.set_color(color) selector.rectprops.update(dict(facecolor=color)) def _setup_butterfly(params): """Set butterfly view of raw plotter.""" from .raw import _setup_browser_selection if 'ica' in params: return butterfly = not params['butterfly'] ax = params['ax'] params['butterfly'] = butterfly if butterfly: types = np.array(params['types'])[params['orig_inds']] if params['group_by'] in ['type', 'original']: inds = params['inds'] labels = [t for t in _DATA_CH_TYPES_SPLIT + ('eog', 'ecg') if t in types] + ['misc'] last_yval = 5 * (len(labels) + 1) ticks = np.arange(5, last_yval, 5) offs = {l: t for (l, t) in zip(labels, ticks)} params['offsets'] = np.zeros(len(params['types'])) for ind in inds: params['offsets'][ind] = offs.get(params['types'][ind], last_yval - 5) # in case there were no non-data channels, skip the final row if (last_yval - 5) not in params['offsets']: ticks = ticks[:-1] labels = labels[:-1] last_yval -= 5 ax.set_yticks(ticks) params['ax'].set_ylim(last_yval, 0) ax.set_yticklabels(labels) else: if 'selections' not in params: params['selections'] = _setup_browser_selection( params['raw'], 'position', selector=False) sels = params['selections'] selections = _SELECTIONS[1:] # Vertex not used if ('Misc' in sels and len(sels['Misc']) > 0): selections += ['Misc'] if params['group_by'] == 'selection' and 'eeg' in types: for sel in _EEG_SELECTIONS: if sel in sels: selections += [sel] picks = list() for selection in selections: picks.append(sels.get(selection, list())) labels = ax.yaxis.get_ticklabels() for label in labels: label.set_visible(True) ylim = (5. * len(picks), 0.) ax.set_ylim(ylim) offset = ylim[0] / (len(picks) + 1) # ensure the last is not included ticks = np.arange(0, ylim[0] - offset / 2., offset) ax.set_yticks(ticks) offsets = np.zeros(len(params['types'])) for group_idx, group in enumerate(picks): for idx, pick in enumerate(group): offsets[pick] = offset * (group_idx + 1) params['inds'] = params['orig_inds'].copy() params['offsets'] = offsets ax.set_yticklabels( [''] + selections, color='black', rotation=45, va='top') else: params['inds'] = params['orig_inds'].copy() if 'fig_selection' not in params: for idx in np.arange(params['n_channels'], len(params['lines'])): params['lines'][idx].set_xdata([]) params['lines'][idx].set_ydata([]) _setup_browser_offsets(params, max([params['n_channels'], 1])) if 'fig_selection' in params: radio = params['fig_selection'].radio active_idx = _get_active_radio_idx(radio) _radio_clicked(radio.labels[active_idx]._text, params) # For now, italics only work in non-grouped mode _set_ax_label_style(ax, params, italicize=not butterfly) params['ax_vscroll'].set_visible(not butterfly) params['plot_fun']() def _connection_line(x, fig, sourceax, targetax, y=1., y_source_transform="transAxes"): """Connect source and target plots with a line. Connect source and target plots with a line, such as time series (source) and topolots (target). Primarily used for plot_joint functions. """ from matplotlib.lines import Line2D trans_fig = fig.transFigure trans_fig_inv = fig.transFigure.inverted() xt, yt = trans_fig_inv.transform(targetax.transAxes.transform([.5, 0.])) xs, _ = trans_fig_inv.transform(sourceax.transData.transform([x, 0.])) _, ys = trans_fig_inv.transform(getattr(sourceax, y_source_transform ).transform([0., y])) return Line2D((xt, xs), (yt, ys), transform=trans_fig, color='grey', linestyle='-', linewidth=1.5, alpha=.66, zorder=1, clip_on=False) class DraggableLine(object): """Custom matplotlib line for moving around by drag and drop. Parameters ---------- line : instance of matplotlib Line2D Line to add interactivity to. callback : function Callback to call when line is released. """ def __init__(self, line, modify_callback, drag_callback): self.line = line self.press = None self.x0 = line.get_xdata()[0] self.modify_callback = modify_callback self.drag_callback = drag_callback self.cidpress = self.line.figure.canvas.mpl_connect( 'button_press_event', self.on_press) self.cidrelease = self.line.figure.canvas.mpl_connect( 'button_release_event', self.on_release) self.cidmotion = self.line.figure.canvas.mpl_connect( 'motion_notify_event', self.on_motion) def set_x(self, x): """Repoisition the line.""" self.line.set_xdata([x, x]) self.x0 = x def on_press(self, event): """Store button press if on top of the line.""" if event.inaxes != self.line.axes or not self.line.contains(event)[0]: return x0 = self.line.get_xdata() y0 = self.line.get_ydata() self.press = x0, y0, event.xdata, event.ydata def on_motion(self, event): """Move the line on drag.""" if self.press is None: return if event.inaxes != self.line.axes: return x0, y0, xpress, ypress = self.press dx = event.xdata - xpress self.line.set_xdata(x0 + dx) self.drag_callback((x0 + dx)[0]) self.line.figure.canvas.draw() def on_release(self, event): """Handle release.""" if event.inaxes != self.line.axes or self.press is None: return self.press = None self.line.figure.canvas.draw() self.modify_callback(self.x0, event.xdata) self.x0 = event.xdata def remove(self): """Remove the line.""" self.line.figure.canvas.mpl_disconnect(self.cidpress) self.line.figure.canvas.mpl_disconnect(self.cidrelease) self.line.figure.canvas.mpl_disconnect(self.cidmotion) self.line.figure.axes[0].lines.remove(self.line) def _setup_ax_spines(axes, vlines, xmin, xmax, ymin, ymax, invert_y=False, unit=None, truncate_xaxis=True, truncate_yaxis=True, skip_axlabel=False, hline=True): # don't show zero line if it coincides with x-axis (even if hline=True) if hline and ymin != 0.: axes.spines['top'].set_position('zero') else: axes.spines['top'].set_visible(False) # the axes can become very small with topo plotting. This prevents the # x-axis from shrinking to length zero if truncate_xaxis=True, by adding # new ticks that are nice round numbers close to (but less extreme than) # xmin and xmax vlines = [] if vlines is None else vlines xticks = _trim_ticks(axes.get_xticks(), xmin, xmax) xticks = np.array(sorted(set([x for x in xticks] + vlines))) if len(xticks) < 2: def log_fix(tval): exp = np.log10(np.abs(tval)) return np.sign(tval) * 10 ** (np.fix(exp) - (exp < 0)) xlims = np.array([xmin, xmax]) temp_ticks = log_fix(xlims) closer_idx = np.argmin(np.abs(xlims - temp_ticks)) further_idx = np.argmax(np.abs(xlims - temp_ticks)) start_stop = [temp_ticks[closer_idx], xlims[further_idx]] step = np.sign(np.diff(start_stop)) * np.max(np.abs(temp_ticks)) tts = np.arange(*start_stop, step) xticks = np.array(sorted(xticks + [tts[0], tts[-1]])) axes.set_xticks(xticks) # y-axis is simpler yticks = _trim_ticks(axes.get_yticks(), ymin, ymax) axes.set_yticks(yticks) # truncation case 1: truncate both if truncate_xaxis and truncate_yaxis: axes.spines['bottom'].set_bounds(*xticks[[0, -1]]) axes.spines['left'].set_bounds(*yticks[[0, -1]]) # case 2: truncate only x (only right side; connect to y at left) elif truncate_xaxis: xbounds = np.array(axes.get_xlim()) xbounds[1] = axes.get_xticks()[-1] axes.spines['bottom'].set_bounds(*xbounds) # case 3: truncate only y (only top; connect to x at bottom) elif truncate_yaxis: ybounds = np.array(axes.get_ylim()) if invert_y: ybounds[0] = axes.get_yticks()[0] else: ybounds[1] = axes.get_yticks()[-1] axes.spines['left'].set_bounds(*ybounds) # handle axis labels if skip_axlabel: axes.set_yticklabels([''] * len(yticks)) axes.set_xticklabels([''] * len(xticks)) else: if unit is not None: axes.set_ylabel(unit, rotation=90) axes.set_xlabel('Time (s)') # plot vertical lines if vlines: _ymin, _ymax = axes.get_ylim() axes.vlines(vlines, _ymax, _ymin, linestyles='--', colors='k', linewidth=1., zorder=1) # invert? if invert_y: axes.invert_yaxis() # changes we always make: axes.tick_params(direction='out') axes.tick_params(right=False) axes.spines['right'].set_visible(False) axes.spines['left'].set_zorder(0) def _handle_decim(info, decim, lowpass): """Handle decim parameter for plotters.""" from ..evoked import _check_decim from ..utils import _ensure_int if isinstance(decim, str) and decim == 'auto': lp = info['sfreq'] if info['lowpass'] is None else info['lowpass'] lp = min(lp, info['sfreq'] if lowpass is None else lowpass) info['lowpass'] = lp decim = max(int(info['sfreq'] / (lp * 3) + 1e-6), 1) decim = _ensure_int(decim, 'decim', must_be='an int or "auto"') if decim <= 0: raise ValueError('decim must be "auto" or a positive integer, got %s' % (decim,)) decim = _check_decim(info, decim, 0)[0] data_picks = _pick_data_channels(info, exclude=()) return decim, data_picks def _setup_plot_projector(info, noise_cov, proj=True, use_noise_cov=True, nave=1): from ..cov import compute_whitener projector = np.eye(len(info['ch_names'])) whitened_ch_names = [] if noise_cov is not None and use_noise_cov: # any channels in noise_cov['bads'] but not in info['bads'] get # set to nan, which means that they are not plotted. data_picks = _pick_data_channels(info, with_ref_meg=False, exclude=()) data_names = {info['ch_names'][pick] for pick in data_picks} # these can be toggled by the user bad_names = set(info['bads']) # these can't in standard pipelines be enabled (we always take the # union), so pretend they're not in cov at all cov_names = ((set(noise_cov['names']) & set(info['ch_names'])) - set(noise_cov['bads'])) # Actually compute the whitener only using the difference whiten_names = cov_names - bad_names whiten_picks = pick_channels(info['ch_names'], whiten_names) whiten_info = pick_info(info, whiten_picks) rank = _triage_rank_sss(whiten_info, [noise_cov])[1][0] whitener, whitened_ch_names = compute_whitener( noise_cov, whiten_info, rank=rank, verbose=False) whitener *= np.sqrt(nave) # proper scaling for Evoked data assert set(whitened_ch_names) == whiten_names projector[whiten_picks, whiten_picks[:, np.newaxis]] = whitener # Now we need to change the set of "whitened" channels to include # all data channel names so that they are properly italicized. whitened_ch_names = data_names # We would need to set "bad_picks" to identity to show the traces # (but in gray), but here we don't need to because "projector" # starts out as identity. So all that is left to do is take any # *good* data channels that are not in the noise cov to be NaN nan_names = data_names - (bad_names | cov_names) # XXX conditional necessary because of annoying behavior of # pick_channels where an empty list means "all"! if len(nan_names) > 0: nan_picks = pick_channels(info['ch_names'], nan_names) projector[nan_picks] = np.nan elif proj: projector, _ = setup_proj(info, add_eeg_ref=False, verbose=False) return projector, whitened_ch_names def _set_ax_label_style(ax, params, italicize=True): import matplotlib.text for tick in params['ax'].get_yaxis().get_major_ticks(): for text in tick.get_children(): if isinstance(text, matplotlib.text.Text): whitened = text.get_text() in params['whitened_ch_names'] whitened = whitened and italicize text.set_style('italic' if whitened else 'normal') def _check_sss(info): """Check SSS history in info.""" ch_used = [ch for ch in _DATA_CH_TYPES_SPLIT if _contains_ch_type(info, ch)] has_meg = 'mag' in ch_used and 'grad' in ch_used has_sss = (has_meg and len(info['proc_history']) > 0 and info['proc_history'][0].get('max_info') is not None) return ch_used, has_meg, has_sss def _triage_rank_sss(info, covs, rank=None, scalings=None): rank = dict() if rank is None else rank scalings = _handle_default('scalings_cov_rank', scalings) # Only look at good channels picks = _pick_data_channels(info, with_ref_meg=False, exclude='bads') info = pick_info(info, picks) ch_used, has_meg, has_sss = _check_sss(info) if has_sss: if 'mag' in rank or 'grad' in rank: raise ValueError('When using SSS, pass "meg" to set the rank ' '(separate rank values for "mag" or "grad" are ' 'meaningless).') elif 'meg' in rank: raise ValueError('When not using SSS, pass separate rank values ' 'for "mag" and "grad" (do not use "meg").') picks_list = _picks_by_type(info, meg_combined=has_sss) if has_sss: # reduce ch_used to combined mag grad ch_used = list(zip(*picks_list))[0] # order pick list by ch_used (required for compat with plot_evoked) picks_list = [x for x, y in sorted(zip(picks_list, ch_used))] n_ch_used = len(ch_used) # make sure we use the same rank estimates for GFP and whitening picks_list2 = [k for k in picks_list] # add meg picks if needed. if has_meg: # append ("meg", picks_meg) picks_list2 += _picks_by_type(info, meg_combined=True) rank_list = [] # rank dict for each cov for cov in covs: # We need to add the covariance projectors, compute the projector, # and apply it, just like we will do in prepare_noise_cov, otherwise # we risk the rank estimates being incorrect (i.e., if the projectors # do not match). info_proj = info.copy() info_proj['projs'] += cov['projs'] this_rank = {} # assemble rank dict for this cov, such that we have meg for ch_type, this_picks in picks_list2: # if we have already estimates / values for mag/grad but not # a value for meg, combine grad and mag. if ('mag' in this_rank and 'grad' in this_rank and 'meg' not in rank): this_rank['meg'] = this_rank['mag'] + this_rank['grad'] # and we're done here break if rank.get(ch_type) is None: ch_names = [info['ch_names'][pick] for pick in this_picks] this_C = pick_channels_cov(cov, ch_names) this_estimated_rank = compute_rank( this_C, scalings=scalings, info=info_proj)[ch_type] this_rank[ch_type] = this_estimated_rank elif rank.get(ch_type) is not None: this_rank[ch_type] = rank[ch_type] rank_list.append(this_rank) return n_ch_used, rank_list, picks_list, has_sss def _match_proj_type(proj, ch_names): """See if proj should be counted.""" proj_ch_names = proj['data']['col_names'] select = any(kk in ch_names for kk in proj_ch_names) return select def _check_cov(noise_cov, info): """Check the noise_cov for whitening and issue an SSS warning.""" from ..cov import read_cov, Covariance if noise_cov is None: return None if isinstance(noise_cov, str): noise_cov = read_cov(noise_cov) if not isinstance(noise_cov, Covariance): raise TypeError('noise_cov must be a str or Covariance, got %s' % (type(noise_cov),)) if _check_sss(info)[2]: # has_sss warn('Data have been processed with SSS, which changes the relative ' 'scaling of magnetometers and gradiometers when viewing data ' 'whitened by a noise covariance') return noise_cov def _set_title_multiple_electrodes(title, combine, ch_names, max_chans=6, all=False, ch_type=None): """Prepare a title string for multiple electrodes.""" if title is None: title = ", ".join(ch_names[:max_chans]) ch_type = _channel_type_prettyprint.get(ch_type, ch_type) if ch_type is None: ch_type = "sensor" if len(ch_names) > 1: ch_type += "s" if all is True and isinstance(combine, str): combine = combine.capitalize() title = "{} of {} {}".format( combine, len(ch_names), ch_type) elif len(ch_names) > max_chans and combine != "gfp": logger.info("More than {} channels, truncating title ...".format( max_chans)) title += ", ...\n({} of {} {})".format( combine, len(ch_names), ch_type,) return title def _check_time_unit(time_unit, times): if not isinstance(time_unit, str): raise TypeError('time_unit must be str, got %s' % (type(time_unit),)) if time_unit == 's': pass elif time_unit == 'ms': times = 1e3 * times else: raise ValueError("time_unit must be 's' or 'ms', got %r" % time_unit) return time_unit, times def _plot_masked_image(ax, data, times, mask=None, yvals=None, cmap="RdBu_r", vmin=None, vmax=None, ylim=None, mask_style="both", mask_alpha=.25, mask_cmap="Greys", yscale="linear"): """Plot a potentially masked (evoked, TFR, ...) 2D image.""" from matplotlib import ticker, __version__ as mpl_version if mask_style is None and mask is not None: mask_style = "both" # default draw_mask = mask_style in {"both", "mask"} draw_contour = mask_style in {"both", "contour"} if cmap is None: mask_cmap = cmap # mask param check and preparation if draw_mask is None: if mask is not None: draw_mask = True else: draw_mask = False if draw_contour is None: if mask is not None: draw_contour = True else: draw_contour = False if mask is None: if draw_mask: warn("`mask` is None, not masking the plot ...") draw_mask = False if draw_contour: warn("`mask` is None, not adding contour to the plot ...") draw_contour = False if draw_mask: if mask.shape != data.shape: raise ValueError( "The mask must have the same shape as the data, " "i.e., %s, not %s" % (data.shape, mask.shape)) if draw_contour and yscale == "log": warn("Cannot draw contours with linear yscale yet ...") if yvals is None: # for e.g. Evoked images yvals = np.arange(data.shape[0]) # else, if TFR plot, yvals will be freqs # test yscale if yscale == 'log' and not yvals[0] > 0: raise ValueError('Using log scale for frequency axis requires all your' ' frequencies to be positive (you cannot include' ' the DC component (0 Hz) in the TFR).') if len(yvals) < 2 or yvals[0] == 0: yscale = 'linear' elif yscale != 'linear': ratio = yvals[1:] / yvals[:-1] if yscale == 'auto': if yvals[0] > 0 and np.allclose(ratio, ratio[0]): yscale = 'log' else: yscale = 'linear' # https://github.com/matplotlib/matplotlib/pull/9477 if yscale == "log" and mpl_version == "2.1.0": warn("With matplotlib version 2.1.0, lines may not show up in " "`AverageTFR.plot_joint`. Upgrade to a more recent version.") if yscale == "log": # pcolormesh for log scale # compute bounds between time samples time_diff = np.diff(times) / 2. if len(times) > 1 else [0.0005] time_lims = np.concatenate([[times[0] - time_diff[0]], times[:-1] + time_diff, [times[-1] + time_diff[-1]]]) log_yvals = np.concatenate([[yvals[0] / ratio[0]], yvals, [yvals[-1] * ratio[0]]]) yval_lims = np.sqrt(log_yvals[:-1] * log_yvals[1:]) # construct a time-yvaluency bounds grid time_mesh, yval_mesh = np.meshgrid(time_lims, yval_lims) if mask is not None: ax.pcolormesh(time_mesh, yval_mesh, data, cmap=mask_cmap, vmin=vmin, vmax=vmax, alpha=mask_alpha) im = ax.pcolormesh(time_mesh, yval_mesh, np.ma.masked_where(~mask, data), cmap=cmap, vmin=vmin, vmax=vmax, alpha=1) else: im = ax.pcolormesh(time_mesh, yval_mesh, data, cmap=cmap, vmin=vmin, vmax=vmax) if ylim is None: ylim = yval_lims[[0, -1]] if yscale == 'log': ax.set_yscale('log') ax.get_yaxis().set_major_formatter(ticker.ScalarFormatter()) ax.yaxis.set_minor_formatter(ticker.NullFormatter()) # get rid of minor ticks ax.yaxis.set_minor_locator(ticker.NullLocator()) tick_vals = yvals[np.unique(np.linspace( 0, len(yvals) - 1, 12).round().astype('int'))] ax.set_yticks(tick_vals) else: # imshow for linear because the y ticks are nicer # and the masked areas look better dt = np.median(np.diff(times)) / 2. if len(times) > 1 else 0.1 dy = np.median(np.diff(yvals)) / 2. if len(yvals) > 1 else 0.5 extent = [times[0] - dt, times[-1] + dt, yvals[0] - dy, yvals[-1] + dy] im_args = dict(interpolation='nearest', origin='lower', extent=extent, aspect='auto', vmin=vmin, vmax=vmax) if draw_mask: ax.imshow(data, alpha=mask_alpha, cmap=mask_cmap, **im_args) im = ax.imshow( np.ma.masked_where(~mask, data), cmap=cmap, **im_args) else: ax.imshow(data, cmap=cmap, **im_args) # see #6481 im = ax.imshow(data, cmap=cmap, **im_args) if draw_contour and np.unique(mask).size == 2: big_mask = np.kron(mask, np.ones((10, 10))) ax.contour(big_mask, colors=["k"], extent=extent, linewidths=[.75], corner_mask=False, antialiased=False, levels=[.5]) time_lims = [extent[0], extent[1]] if ylim is None: ylim = [extent[2], extent[3]] ax.set_xlim(time_lims[0], time_lims[-1]) ax.set_ylim(ylim) if (draw_mask or draw_contour) and mask is not None: if mask.all(): t_end = ", all points masked)" else: fraction = 1 - (np.float64(mask.sum()) / np.float64(mask.size)) t_end = ", %0.3g%% of points masked)" % (fraction * 100,) else: t_end = ")" return im, t_end @fill_doc def _make_combine_callable(combine): """Convert None or string values of ``combine`` into callables. Params ------ %(combine)s If callable, the callable must accept one positional input (data of shape ``(n_epochs, n_channels, n_times)`` or ``(n_evokeds, n_channels, n_times)``) and return an :class:`array <numpy.ndarray>` of shape ``(n_epochs, n_times)`` or ``(n_evokeds, n_times)``. """ if combine is None: combine = partial(np.squeeze, axis=1) elif isinstance(combine, str): combine_dict = {key: partial(getattr(np, key), axis=1) for key in ('mean', 'median', 'std')} combine_dict['gfp'] = lambda data: np.sqrt((data ** 2).mean(axis=1)) try: combine = combine_dict[combine] except KeyError: raise ValueError('"combine" must be None, a callable, or one of ' '"mean", "median", "std", or "gfp"; got {}' ''.format(combine)) return combine def center_cmap(cmap, vmin, vmax, name="cmap_centered"): """Center given colormap (ranging from vmin to vmax) at value 0. Parameters ---------- cmap : matplotlib.colors.Colormap The colormap to center around 0. vmin : float Minimum value in the data to map to the lower end of the colormap. vmax : float Maximum value in the data to map to the upper end of the colormap. name : str Name of the new colormap. Defaults to 'cmap_centered'. Returns ------- cmap_centered : matplotlib.colors.Colormap The new colormap centered around 0. Notes ----- This function can be used in situations where vmin and vmax are not symmetric around zero. Normally, this results in the value zero not being mapped to white anymore in many colormaps. Using this function, the value zero will be mapped to white even for asymmetric positive and negative value ranges. Note that this could also be achieved by re-normalizing a given colormap by subclassing matplotlib.colors.Normalize as described here: https://matplotlib.org/users/colormapnorms.html#custom-normalization-two-linear-ranges """ # noqa: E501 from matplotlib.colors import LinearSegmentedColormap vzero = abs(vmin) / float(vmax - vmin) index_old = np.linspace(0, 1, cmap.N) index_new = np.hstack([np.linspace(0, vzero, cmap.N // 2, endpoint=False), np.linspace(vzero, 1, cmap.N // 2)]) colors = "red", "green", "blue", "alpha" cdict = {name: [] for name in colors} for old, new in zip(index_old, index_new): for color, name in zip(cmap(old), colors): cdict[name].append((new, color, color)) return LinearSegmentedColormap(name, cdict) def _set_psd_plot_params(info, proj, picks, ax, area_mode): """Set PSD plot params.""" import matplotlib.pyplot as plt _check_option('area_mode', area_mode, [None, 'std', 'range']) _user_picked = picks is not None picks = _picks_to_idx(info, picks) # XXX this could be refactored more with e.g., plot_evoked # XXX when it's refactored, Report._render_raw will need to be updated titles = _handle_default('titles', None) units = _handle_default('units', None) scalings = _handle_default('scalings', None) picks_list = list() titles_list = list() units_list = list() scalings_list = list() allowed_ch_types = (_VALID_CHANNEL_TYPES if _user_picked else _DATA_CH_TYPES_SPLIT) for name in allowed_ch_types: kwargs = dict(meg=False, ref_meg=False, exclude=[]) if name in ('mag', 'grad'): kwargs['meg'] = name elif name in ('fnirs_cw_amplitude', 'fnirs_od', 'hbo', 'hbr'): kwargs['fnirs'] = name else: kwargs[name] = True these_picks = pick_types(info, **kwargs) these_picks = np.intersect1d(these_picks, picks) if len(these_picks) > 0: picks_list.append(these_picks) titles_list.append(titles[name]) units_list.append(units[name]) scalings_list.append(scalings[name]) if len(picks_list) == 0: raise RuntimeError('No data channels found') if ax is not None: if isinstance(ax, plt.Axes): ax = [ax] if len(ax) != len(picks_list): raise ValueError('For this dataset with picks=None %s axes ' 'must be supplied, got %s' % (len(picks_list), len(ax))) ax_list = ax del picks fig = None if ax is None: fig, ax_list = plt.subplots(len(picks_list), 1, sharex=True, squeeze=False) ax_list = list(ax_list[:, 0]) else: fig = ax_list[0].get_figure() # make_label decides if ylabel and titles are displayed make_label = len(ax_list) == len(fig.axes) # Plot Frequency [Hz] xlabel on the last axis xlabels_list = [False] * len(picks_list) xlabels_list[-1] = True return (fig, picks_list, titles_list, units_list, scalings_list, ax_list, make_label, xlabels_list) def _convert_psds(psds, dB, estimate, scaling, unit, ch_names=None, first_dim='channel'): """Convert PSDs to dB (if necessary) and appropriate units. The following table summarizes the relationship between the value of parameters ``dB`` and ``estimate``, and the type of plot and corresponding units. | dB | estimate | plot | units | |-------+-------------+------+-------------------| | True | 'power' | PSD | amp**2/Hz (dB) | | True | 'amplitude' | ASD | amp/sqrt(Hz) (dB) | | True | 'auto' | PSD | amp**2/Hz (dB) | | False | 'power' | PSD | amp**2/Hz | | False | 'amplitude' | ASD | amp/sqrt(Hz) | | False | 'auto' | ASD | amp/sqrt(Hz) | where amp are the units corresponding to the variable, as specified by ``unit``. """ _check_option('first_dim', first_dim, ['channel', 'epoch']) where = np.where(psds.min(1) <= 0)[0] if len(where) > 0: # Construct a helpful error message, depending on whether the first # dimension of `psds` are channels or epochs. if dB: bad_value = 'Infinite' else: bad_value = 'Zero' if first_dim == 'channel': bads = ', '.join(ch_names[ii] for ii in where) else: bads = ', '.join(str(ii) for ii in where) msg = "{bad_value} value in PSD for {first_dim}{pl} {bads}.".format( bad_value=bad_value, first_dim=first_dim, bads=bads, pl=_pl(where)) if first_dim == 'channel': msg += '\nThese channels might be dead.' warn(msg, UserWarning) if estimate == 'auto': estimate = 'power' if dB else 'amplitude' if estimate == 'amplitude': np.sqrt(psds, out=psds) psds *= scaling ylabel = r'$\mathrm{%s/\sqrt{Hz}}$' % unit else: psds *= scaling * scaling if '/' in unit: unit = '(%s)' % unit ylabel = r'$\mathrm{%s²/Hz}$' % unit if dB: np.log10(np.maximum(psds, np.finfo(float).tiny), out=psds) psds *= 10 ylabel += r'$\ \mathrm{(dB)}$' return ylabel def _check_psd_fmax(inst, fmax): """Make sure requested fmax does not exceed Nyquist frequency.""" if np.isfinite(fmax) and (fmax > inst.info['sfreq'] / 2): raise ValueError('Requested fmax ({} Hz) must not exceed one half ' 'the sampling frequency of the data ({}).' .format(fmax, 0.5 * inst.info['sfreq'])) def _plot_psd(inst, fig, freqs, psd_list, picks_list, titles_list, units_list, scalings_list, ax_list, make_label, color, area_mode, area_alpha, dB, estimate, average, spatial_colors, xscale, line_alpha, sphere, xlabels_list): # helper function for plot_raw_psd and plot_epochs_psd from matplotlib.ticker import ScalarFormatter from .evoked import _plot_lines sphere = _check_sphere(sphere, inst.info) _check_option('xscale', xscale, ('log', 'linear')) for key, ls in zip(['lowpass', 'highpass', 'line_freq'], ['--', '--', '-.']): if inst.info[key] is not None: for ax in ax_list: ax.axvline(inst.info[key], color='k', linestyle=ls, alpha=0.25, linewidth=2, zorder=2) if line_alpha is None: line_alpha = 1.0 if average else 0.75 line_alpha = float(line_alpha) ylabels = list() for ii, (psd, picks, title, ax, scalings, units) in enumerate(zip( psd_list, picks_list, titles_list, ax_list, scalings_list, units_list)): ylabel = _convert_psds(psd, dB, estimate, scalings, units, [inst.ch_names[pi] for pi in picks]) ylabels.append(ylabel) del ylabel if average: # mean across channels psd_mean = np.mean(psd, axis=0) if area_mode == 'std': # std across channels psd_std = np.std(psd, axis=0) hyp_limits = (psd_mean - psd_std, psd_mean + psd_std) elif area_mode == 'range': hyp_limits = (np.min(psd, axis=0), np.max(psd, axis=0)) else: # area_mode is None hyp_limits = None ax.plot(freqs, psd_mean, color=color, alpha=line_alpha, linewidth=0.5) if hyp_limits is not None: ax.fill_between(freqs, hyp_limits[0], y2=hyp_limits[1], facecolor=color, alpha=area_alpha) if not average: picks = np.concatenate(picks_list) psd_list = np.concatenate(psd_list) types = np.array(inst.get_channel_types(picks=picks)) # Needed because the data do not match the info anymore. info = create_info([inst.ch_names[p] for p in picks], inst.info['sfreq'], types) info['chs'] = [inst.info['chs'][p] for p in picks] valid_channel_types = [ 'mag', 'grad', 'eeg', 'csd', 'seeg', 'eog', 'ecg', 'emg', 'dipole', 'gof', 'bio', 'ecog', 'hbo', 'hbr', 'misc', 'fnirs_cw_amplitude', 'fnirs_od'] ch_types_used = list() for this_type in valid_channel_types: if this_type in types: ch_types_used.append(this_type) assert len(ch_types_used) == len(ax_list) unit = '' units = {t: yl for t, yl in zip(ch_types_used, ylabels)} titles = {c: t for c, t in zip(ch_types_used, titles_list)} picks = np.arange(len(psd_list)) if not spatial_colors: spatial_colors = color _plot_lines(psd_list, info, picks, fig, ax_list, spatial_colors, unit, units=units, scalings=None, hline=None, gfp=False, types=types, zorder='std', xlim=(freqs[0], freqs[-1]), ylim=None, times=freqs, bad_ch_idx=[], titles=titles, ch_types_used=ch_types_used, selectable=True, psd=True, line_alpha=line_alpha, nave=None, time_unit='ms', sphere=sphere) for ii, (ax, xlabel) in enumerate(zip(ax_list, xlabels_list)): ax.grid(True, linestyle=':') if xscale == 'log': ax.set(xscale='log') ax.set(xlim=[freqs[1] if freqs[0] == 0 else freqs[0], freqs[-1]]) ax.get_xaxis().set_major_formatter(ScalarFormatter()) else: # xscale == 'linear' ax.set(xlim=(freqs[0], freqs[-1])) if make_label: ax.set(ylabel=ylabels[ii], title=titles_list[ii]) if xlabel: ax.set_xlabel('Frequency (Hz)') if make_label: fig.subplots_adjust(left=.1, bottom=.1, right=.9, top=.9, wspace=0.3, hspace=0.5) return fig def _trim_ticks(ticks, _min, _max): """Remove ticks that are more extreme than the given limits.""" keep = np.where(np.logical_and(ticks >= _min, ticks <= _max)) return ticks[keep]
39.355793
144
0.59501
31b3bcde14e1cdc94b0db7fdae3ab6af301ddcda
12,770
py
Python
dolphintracker/singlecam_tracker/singlecam_tracker.py
UmSenhorQualquer/d-track
7a7e1cc54176452235731d4ba232545af6e01afc
[ "MIT" ]
1
2021-12-24T07:35:07.000Z
2021-12-24T07:35:07.000Z
dolphintracker/singlecam_tracker/singlecam_tracker.py
UmSenhorQualquer/d-track
7a7e1cc54176452235731d4ba232545af6e01afc
[ "MIT" ]
null
null
null
dolphintracker/singlecam_tracker/singlecam_tracker.py
UmSenhorQualquer/d-track
7a7e1cc54176452235731d4ba232545af6e01afc
[ "MIT" ]
null
null
null
import pyforms from pyforms import BaseWidget from pyforms.controls import ControlText from pyforms.controls import ControlProgress from pyforms.controls import ControlSlider from pyforms.controls import ControlButton from pyforms.controls import ControlPlayer from pyforms.controls import ControlFile from pyforms.controls import ControlCombo from pyforms.controls import ControlBoundingSlider from pyforms.controls import ControlCheckBox from pyforms.utils import tools import os, cv2, shutil, numpy as np, csv from dolphintracker.singlecam_tracker.camera_filter.FindDolphin import FilterAllPool from dolphintracker.singlecam_tracker.pool_camera import PoolCamera from py3dengine.utils.WavefrontOBJFormat.WavefrontOBJReader import WavefrontOBJReader from py3dengine.scenes.Scene import Scene class SingleCamTracker(BaseWidget): def __init__(self): super(SingleCamTracker,self).__init__('Dolphin tracker') self.set_margin(5) self._sceneFile = ControlFile('Scene file') self._video = ControlFile('Video') self._debug = ControlCheckBox('Debug', default=False) self._camera = ControlCombo('Camera', enabled=False) self._player = ControlPlayer('Image') self._range = ControlBoundingSlider('Frames to analyse', default=[0, 100], enabled=False) self._blockSize1 = ControlSlider('Thresh block size', default=193, minimum=2, maximum=1001) self._cValue1 = ControlSlider('Thresh C value', default=284, minimum=0, maximum=500) self._blockSize2 = ControlSlider('Thresh block size', default=463, minimum=2, maximum=1001) self._cValue2 = ControlSlider('Thresh C value', default=289, minimum=0, maximum=500) self._blockSize3 = ControlSlider('Thresh block size', default=910, minimum=2, maximum=1001) self._cValue3 = ControlSlider('Thresh C value', default=288, minimum=0, maximum=500) self._exc_btn = ControlButton('Run') self._progress = ControlProgress('Progress', visible=False) self.formset = [ '_video', '_range', ('_sceneFile', '_camera', '_debug'), ('_blockSize1', '_cValue1'), ('_blockSize2', '_cValue2'), ('_blockSize3', '_cValue3'), '_player', '_exc_btn', '_progress' ] self.has_progress = True self._video.changed_event = self.__video_changed_evt self._player.process_frame_event = self.__process_frame_evt self._sceneFile.changed_event = self.__scene_changed_evt self._blockSize1.changed_event = self._player.refresh self._blockSize2.changed_event = self._player.refresh self._blockSize3.changed_event = self._player.refresh self._cValue1.changed_event = self._player.refresh self._cValue2.changed_event = self._player.refresh self._cValue3.changed_event = self._player.refresh self._exc_btn.value = self.execute """ self._sceneFile.value = '/home/ricardo/Downloads/golfinhos/2013.11.23_10.59_scene.obj' self._video.value = '/home/ricardo/Downloads/golfinhos/2013.11.23_10.59_Entrada.MP4' self._range.value = [9000, self._range.max] """ def __scene_changed_evt(self): if self._sceneFile.value: self._camera.enabled = True world = WavefrontOBJReader(self._sceneFile.value) scene = Scene() scene.objects = world.objects scene.cameras = world.cameras self._camera.clear() for cam in scene.cameras: self._camera.add_item(cam.name) else: self._camera.enabled = False def __video_changed_evt(self): self._player.value = self._video.value head, tail = os.path.split(self._video.value) filename, extention = os.path.splitext(tail) if self._video.value: self._range.enabled = True self._range.max = self._player.max self._range.value = self._range.value[0], self._player.max else: self._range.enabled = False def __process_frame_evt(self, frame): b, g, r = cv2.split(frame) thresh = g blockSize = self._blockSize1.value if (blockSize % 2)==0: blockSize+=1 res1 = cv2.adaptiveThreshold(thresh,255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, blockSize, self._cValue1.value-255) #res1 = cv2.bitwise_and(thresh, res1) #res1[res1>140] = 0; #res1[res1>0] = 255 #res1 = cv2.erode( res1, kernel=cv2.getStructuringElement( cv2.MORPH_RECT, (3,3) ), iterations=1 ) #res1 = cv2.dilate( res1, kernel=cv2.getStructuringElement( cv2.MORPH_RECT, (5,5) ), iterations=2 ) blockSize = self._blockSize2.value if (blockSize % 2)==0: blockSize+=1 res2 = cv2.adaptiveThreshold(thresh,255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, blockSize, self._cValue2.value-255) #res2 = cv2.bitwise_and(thresh, res2) #res2[res2>160] = 0; #res2[res2>0] = 255 #res2 = cv2.erode( res2, kernel=cv2.getStructuringElement( cv2.MORPH_RECT, (3,3) ), iterations=1 ) #res2 = cv2.dilate( res2, kernel=cv2.getStructuringElement( cv2.MORPH_RECT, (5,5) ), iterations=2 ) blockSize = self._blockSize3.value if (blockSize % 2)==0: blockSize+=1 res3 = cv2.adaptiveThreshold(thresh,255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, blockSize, self._cValue3.value-255) #res3 = cv2.bitwise_and(thresh, res3) #res3[res3>100] = 0; #res3[res3>0] = 255 #res3 = cv2.erode( res3, kernel=cv2.getStructuringElement( cv2.MORPH_RECT, (3,3) ), iterations=1 ) #res3 = cv2.dilate( res3, kernel=cv2.getStructuringElement( cv2.MORPH_RECT, (5,5) ), iterations=2 ) resImg = cv2.merge((res1, res2, res3)) #resImg[resImg==0] = 255 #res = np.zeros_like(resImg) + 255 #resImg = cv2.bitwise_and(res, resImg) return [frame, resImg] @property def output_videofile(self): head, tail = os.path.split(self._video.value) filename, extention = os.path.splitext(tail) return "{0}_out.avi".format(filename) @property def output_csvfile(self): head, tail = os.path.split(self._video.value) filename, extention = os.path.splitext(tail) return "{0}_out.csv".format(filename) def execute(self): if not os.path.exists('output'): os.makedirs('output') VIDEO_FILE = self._video.value VIDEO_OUT_FILE = self.output_videofile SCENE_FILE = self._sceneFile.value FIRST_FRAME, LAST_FRAME = self._range.value CAMERA = self._camera.value self._exc_btn.enabled = False self._blockSize1.enabled = False self._blockSize2.enabled = False self._blockSize3.enabled = False self._cValue1.enabled = False self._cValue2.enabled = False self._cValue3.enabled = False self._sceneFile.enabled = False self._video.enabled = False self._range.enabled = False self._camera.enabled = False world = WavefrontOBJReader(SCENE_FILE) scene = Scene() scene.objects = world.objects scene.cameras = world.cameras filterCamera1 = FilterAllPool() filterCamera1._param_tb_block_size = self._blockSize1.value if (self._blockSize1.value % 2)!=0 else (self._blockSize1.value+1) filterCamera1._param_tb_c = self._cValue1.value filterCamera2 = FilterAllPool() filterCamera2._param_tb_block_size = self._blockSize2.value if (self._blockSize2.value % 2)!=0 else (self._blockSize2.value+1) filterCamera2._param_tb_c = self._cValue2.value filterCamera3 = FilterAllPool() filterCamera3._param_tb_block_size = self._blockSize3.value if (self._blockSize3.value % 2)!=0 else (self._blockSize3.value+1) filterCamera3._param_tb_c = self._cValue3.value self._progress.show() self._progress.max = LAST_FRAME-FIRST_FRAME self._progress.min = 0 print("CAMERA",CAMERA, 'FRAMES RANGE', self._range.value) camera = PoolCamera( VIDEO_FILE, CAMERA, scene, ['Pool'], [filterCamera1, filterCamera2, filterCamera3], self._range.value ) camera.frame_index = FIRST_FRAME self.max_progress = camera.totalFrames-FIRST_FRAME OUT_IMG_WIDTH = camera.img_width // 3 OUT_IMG_HEIGHT = camera.img_height // 3 if self._debug.value: fourcc = cv2.VideoWriter_fourcc('M','J','P','G') outvideofile = os.path.join('output',VIDEO_OUT_FILE) outVideo = cv2.VideoWriter( outvideofile,fourcc, camera.fps, (OUT_IMG_WIDTH,OUT_IMG_HEIGHT) ) else: outVideo = None csvfile = open( os.path.join( 'output', self.output_csvfile ), 'w') spamwriter = csv.writer(csvfile, delimiter=';',quotechar='|',quoting=csv.QUOTE_MINIMAL) count = 0 point = None while True: frameIndex = camera.frame_index res = camera.read() if not res: break if frameIndex>LAST_FRAME: break blobs = camera.process() """ frame = camera.originalFrame.copy() f, axarr = plt.subplots(len(blobs), sharex=True) plt.xlim([0,256]) for i, blob in enumerate(blobs): if blob==None: continue p1, p2 = blob._bounding cut_x, cut_y, cut_xx, cut_yy = p1[0]-30, p1[1]-30, p2[0]+30, p2[1]+30 if cut_x<0: cut_x=0 if cut_y<0: cut_y=0 if cut_xx>frame.shape[1]: cut_xx=frame.shape[1] if cut_yy>frame.shape[0]: cut_yy=frame.shape[0] img = frame[cut_y:cut_yy, cut_x:cut_xx] cv2.imshow('camera'+str(i), img) color = ('b','g','r') for j,col in enumerate(color): histr = cv2.calcHist([img],[j],None,[256],[0,256]) axarr[i].plot(histr,color = col) """ for i, b in enumerate(blobs): if b!=None: b.draw(camera.originalFrame, color=camera._colors[i] ) row2save = [frameIndex] for blob in blobs: row2save += (list(blob._centroid)+[blob._area]) if blob!=None else [None, None,None] spamwriter.writerow(row2save) img = cv2.resize(camera.originalFrame, (OUT_IMG_WIDTH,OUT_IMG_HEIGHT)) cv2.putText(img, str(frameIndex), (20, 50), cv2.FONT_HERSHEY_PLAIN, 1.0, (255,255,255), thickness=2, lineType=cv2.LINE_AA) cv2.putText(img, str(frameIndex), (20, 50), cv2.FONT_HERSHEY_PLAIN, 1.0, (0,0,0), thickness=1, lineType=cv2.LINE_AA) if outVideo: outVideo.write(img) self._player.image = img count +=1 self._progress.value = count csvfile.close() if outVideo: outVideo.release() self._progress.hide() self._exc_btn.enabled = True self._blockSize1.enabled = True self._blockSize2.enabled = True self._blockSize3.enabled = True self._cValue1.enabled = True self._cValue2.enabled = True self._cValue3.enabled = True self._sceneFile.enabled = True self._video.enabled = True self._range.enabled = True self._camera.enabled = True ################################################################################################################## ################################################################################################################## ################################################################################################################## def main(): pyforms.start_app( SingleCamTracker, geometry=(100,100, 800, 700) ) if __name__ == "__main__": main()
38.81459
134
0.581911
9e0610deed281f15b184fa071649b1a8490bc625
7,604
py
Python
Lib/asyncio/taskgroups.py
dignissimus/cpython
17357108732c731d6ed4f2bd123ee6ba1ff6891b
[ "0BSD" ]
1
2021-11-05T12:29:12.000Z
2021-11-05T12:29:12.000Z
Lib/asyncio/taskgroups.py
dignissimus/cpython
17357108732c731d6ed4f2bd123ee6ba1ff6891b
[ "0BSD" ]
2
2021-12-01T15:01:15.000Z
2022-02-24T06:16:48.000Z
Lib/asyncio/taskgroups.py
sthagen/python-cpython
dfd438dfb2a0e299cd6ab166f203dfe9740868ae
[ "0BSD" ]
null
null
null
# Adapted with permission from the EdgeDB project. __all__ = ["TaskGroup"] from . import events from . import exceptions from . import tasks class TaskGroup: def __init__(self): self._entered = False self._exiting = False self._aborting = False self._loop = None self._parent_task = None self._parent_cancel_requested = False self._tasks = set() self._errors = [] self._base_error = None self._on_completed_fut = None def __repr__(self): info = [''] if self._tasks: info.append(f'tasks={len(self._tasks)}') if self._errors: info.append(f'errors={len(self._errors)}') if self._aborting: info.append('cancelling') elif self._entered: info.append('entered') info_str = ' '.join(info) return f'<TaskGroup{info_str}>' async def __aenter__(self): if self._entered: raise RuntimeError( f"TaskGroup {self!r} has been already entered") self._entered = True if self._loop is None: self._loop = events.get_running_loop() self._parent_task = tasks.current_task(self._loop) if self._parent_task is None: raise RuntimeError( f'TaskGroup {self!r} cannot determine the parent task') return self async def __aexit__(self, et, exc, tb): self._exiting = True propagate_cancellation_error = None if (exc is not None and self._is_base_error(exc) and self._base_error is None): self._base_error = exc if et is not None: if et is exceptions.CancelledError: if self._parent_cancel_requested and not self._parent_task.uncancel(): # Do nothing, i.e. swallow the error. pass else: propagate_cancellation_error = exc if not self._aborting: # Our parent task is being cancelled: # # async with TaskGroup() as g: # g.create_task(...) # await ... # <- CancelledError # # or there's an exception in "async with": # # async with TaskGroup() as g: # g.create_task(...) # 1 / 0 # self._abort() # We use while-loop here because "self._on_completed_fut" # can be cancelled multiple times if our parent task # is being cancelled repeatedly (or even once, when # our own cancellation is already in progress) while self._tasks: if self._on_completed_fut is None: self._on_completed_fut = self._loop.create_future() try: await self._on_completed_fut except exceptions.CancelledError as ex: if not self._aborting: # Our parent task is being cancelled: # # async def wrapper(): # async with TaskGroup() as g: # g.create_task(foo) # # "wrapper" is being cancelled while "foo" is # still running. propagate_cancellation_error = ex self._abort() self._on_completed_fut = None assert not self._tasks if self._base_error is not None: raise self._base_error if propagate_cancellation_error is not None: # The wrapping task was cancelled; since we're done with # closing all child tasks, just propagate the cancellation # request now. raise propagate_cancellation_error if et is not None and et is not exceptions.CancelledError: self._errors.append(exc) if self._errors: # Exceptions are heavy objects that can have object # cycles (bad for GC); let's not keep a reference to # a bunch of them. errors = self._errors self._errors = None me = BaseExceptionGroup('unhandled errors in a TaskGroup', errors) raise me from None def create_task(self, coro, *, name=None, context=None): if not self._entered: raise RuntimeError(f"TaskGroup {self!r} has not been entered") if self._exiting and not self._tasks: raise RuntimeError(f"TaskGroup {self!r} is finished") if context is None: task = self._loop.create_task(coro) else: task = self._loop.create_task(coro, context=context) tasks._set_task_name(task, name) task.add_done_callback(self._on_task_done) self._tasks.add(task) return task # Since Python 3.8 Tasks propagate all exceptions correctly, # except for KeyboardInterrupt and SystemExit which are # still considered special. def _is_base_error(self, exc: BaseException) -> bool: assert isinstance(exc, BaseException) return isinstance(exc, (SystemExit, KeyboardInterrupt)) def _abort(self): self._aborting = True for t in self._tasks: if not t.done(): t.cancel() def _on_task_done(self, task): self._tasks.discard(task) if self._on_completed_fut is not None and not self._tasks: if not self._on_completed_fut.done(): self._on_completed_fut.set_result(True) if task.cancelled(): return exc = task.exception() if exc is None: return self._errors.append(exc) if self._is_base_error(exc) and self._base_error is None: self._base_error = exc if self._parent_task.done(): # Not sure if this case is possible, but we want to handle # it anyways. self._loop.call_exception_handler({ 'message': f'Task {task!r} has errored out but its parent ' f'task {self._parent_task} is already completed', 'exception': exc, 'task': task, }) return if not self._aborting and not self._parent_cancel_requested: # If parent task *is not* being cancelled, it means that we want # to manually cancel it to abort whatever is being run right now # in the TaskGroup. But we want to mark parent task as # "not cancelled" later in __aexit__. Example situation that # we need to handle: # # async def foo(): # try: # async with TaskGroup() as g: # g.create_task(crash_soon()) # await something # <- this needs to be canceled # # by the TaskGroup, e.g. # # foo() needs to be cancelled # except Exception: # # Ignore any exceptions raised in the TaskGroup # pass # await something_else # this line has to be called # # after TaskGroup is finished. self._abort() self._parent_cancel_requested = True self._parent_task.cancel()
35.203704
86
0.538401
3f2d08e094a6d3421e8049070499375fa1b8653f
13,000
py
Python
instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py
ericmustin/opentelemetry-python-contrib
308369004c71a8d07c18560ac1fb46049a0a8105
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py
ericmustin/opentelemetry-python-contrib
308369004c71a8d07c18560ac1fb46049a0a8105
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py
ericmustin/opentelemetry-python-contrib
308369004c71a8d07c18560ac1fb46049a0a8105
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
# Copyright The OpenTelemetry Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import unittest import unittest.mock as mock import wsgiref.util as wsgiref_util from urllib.parse import urlsplit import opentelemetry.instrumentation.wsgi as otel_wsgi from opentelemetry import trace as trace_api from opentelemetry.test.wsgitestutil import WsgiTestBase from opentelemetry.trace import StatusCode class Response: def __init__(self): self.iter = iter([b"*"]) self.close_calls = 0 def __iter__(self): return self def __next__(self): return next(self.iter) def close(self): self.close_calls += 1 def simple_wsgi(environ, start_response): assert isinstance(environ, dict) start_response("200 OK", [("Content-Type", "text/plain")]) return [b"*"] def create_iter_wsgi(response): def iter_wsgi(environ, start_response): assert isinstance(environ, dict) start_response("200 OK", [("Content-Type", "text/plain")]) return response return iter_wsgi def create_gen_wsgi(response): def gen_wsgi(environ, start_response): result = create_iter_wsgi(response)(environ, start_response) yield from result getattr(result, "close", lambda: None)() return gen_wsgi def error_wsgi(environ, start_response): assert isinstance(environ, dict) try: raise ValueError except ValueError: exc_info = sys.exc_info() start_response("200 OK", [("Content-Type", "text/plain")], exc_info) exc_info = None return [b"*"] def error_wsgi_unhandled(environ, start_response): assert isinstance(environ, dict) raise ValueError class TestWsgiApplication(WsgiTestBase): def validate_response( self, response, error=None, span_name="HTTP GET", http_method="GET", span_attributes=None, response_headers=None, ): while True: try: value = next(response) self.assertEqual(value, b"*") except StopIteration: break expected_headers = [("Content-Type", "text/plain")] if response_headers: expected_headers.extend(response_headers) self.assertEqual(self.status, "200 OK") self.assertEqual(self.response_headers, expected_headers) if error: self.assertIs(self.exc_info[0], error) self.assertIsInstance(self.exc_info[1], error) self.assertIsNotNone(self.exc_info[2]) else: self.assertIsNone(self.exc_info) span_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(span_list), 1) self.assertEqual(span_list[0].name, span_name) self.assertEqual(span_list[0].kind, trace_api.SpanKind.SERVER) expected_attributes = { "http.server_name": "127.0.0.1", "http.scheme": "http", "net.host.port": 80, "http.host": "127.0.0.1", "http.flavor": "1.0", "http.url": "http://127.0.0.1/", "http.status_code": 200, } expected_attributes.update(span_attributes or {}) if http_method is not None: expected_attributes["http.method"] = http_method self.assertEqual(span_list[0].attributes, expected_attributes) def test_basic_wsgi_call(self): app = otel_wsgi.OpenTelemetryMiddleware(simple_wsgi) response = app(self.environ, self.start_response) self.validate_response(response) def test_hooks(self): hook_headers = ( "hook_attr", "hello otel", ) def request_hook(span, environ): span.update_name("name from hook") def response_hook(span, environ, status_code, response_headers): span.set_attribute("hook_attr", "hello world") response_headers.append(hook_headers) app = otel_wsgi.OpenTelemetryMiddleware( simple_wsgi, request_hook, response_hook ) response = app(self.environ, self.start_response) self.validate_response( response, span_name="name from hook", span_attributes={"hook_attr": "hello world"}, response_headers=(hook_headers,), ) def test_wsgi_not_recording(self): mock_tracer = mock.Mock() mock_span = mock.Mock() mock_span.is_recording.return_value = False mock_tracer.start_span.return_value = mock_span with mock.patch("opentelemetry.trace.get_tracer") as tracer: tracer.return_value = mock_tracer app = otel_wsgi.OpenTelemetryMiddleware(simple_wsgi) # pylint: disable=W0612 response = app(self.environ, self.start_response) # noqa: F841 self.assertFalse(mock_span.is_recording()) self.assertTrue(mock_span.is_recording.called) self.assertFalse(mock_span.set_attribute.called) self.assertFalse(mock_span.set_status.called) def test_wsgi_iterable(self): original_response = Response() iter_wsgi = create_iter_wsgi(original_response) app = otel_wsgi.OpenTelemetryMiddleware(iter_wsgi) response = app(self.environ, self.start_response) # Verify that start_response has been called self.assertTrue(self.status) self.validate_response(response) # Verify that close has been called exactly once self.assertEqual(1, original_response.close_calls) def test_wsgi_generator(self): original_response = Response() gen_wsgi = create_gen_wsgi(original_response) app = otel_wsgi.OpenTelemetryMiddleware(gen_wsgi) response = app(self.environ, self.start_response) # Verify that start_response has not been called self.assertIsNone(self.status) self.validate_response(response) # Verify that close has been called exactly once self.assertEqual(original_response.close_calls, 1) def test_wsgi_exc_info(self): app = otel_wsgi.OpenTelemetryMiddleware(error_wsgi) response = app(self.environ, self.start_response) self.validate_response(response, error=ValueError) def test_wsgi_internal_error(self): app = otel_wsgi.OpenTelemetryMiddleware(error_wsgi_unhandled) self.assertRaises(ValueError, app, self.environ, self.start_response) span_list = self.memory_exporter.get_finished_spans() self.assertEqual(len(span_list), 1) self.assertEqual( span_list[0].status.status_code, StatusCode.ERROR, ) def test_default_span_name_missing_request_method(self): """Test that default span_names with missing request method.""" self.environ.pop("REQUEST_METHOD") app = otel_wsgi.OpenTelemetryMiddleware(simple_wsgi) response = app(self.environ, self.start_response) self.validate_response(response, span_name="HTTP", http_method=None) class TestWsgiAttributes(unittest.TestCase): def setUp(self): self.environ = {} wsgiref_util.setup_testing_defaults(self.environ) self.span = mock.create_autospec(trace_api.Span, spec_set=True) def test_request_attributes(self): self.environ["QUERY_STRING"] = "foo=bar" attrs = otel_wsgi.collect_request_attributes(self.environ) self.assertDictEqual( attrs, { "http.method": "GET", "http.host": "127.0.0.1", "http.url": "http://127.0.0.1/?foo=bar", "net.host.port": 80, "http.scheme": "http", "http.server_name": "127.0.0.1", "http.flavor": "1.0", }, ) def validate_url(self, expected_url, raw=False, has_host=True): parts = urlsplit(expected_url) expected = { "http.scheme": parts.scheme, "net.host.port": parts.port or (80 if parts.scheme == "http" else 443), "http.server_name": parts.hostname, # Not true in the general case, but for all tests. } if raw: expected["http.target"] = expected_url.split(parts.netloc, 1)[1] else: expected["http.url"] = expected_url if has_host: expected["http.host"] = parts.hostname attrs = otel_wsgi.collect_request_attributes(self.environ) self.assertGreaterEqual( attrs.items(), expected.items(), expected_url + " expected." ) def test_request_attributes_with_partial_raw_uri(self): self.environ["RAW_URI"] = "/#top" self.validate_url("http://127.0.0.1/#top", raw=True) def test_request_attributes_with_partial_raw_uri_and_nonstandard_port( self, ): self.environ["RAW_URI"] = "/?" del self.environ["HTTP_HOST"] self.environ["SERVER_PORT"] = "8080" self.validate_url("http://127.0.0.1:8080/?", raw=True, has_host=False) def test_https_uri_port(self): del self.environ["HTTP_HOST"] self.environ["SERVER_PORT"] = "443" self.environ["wsgi.url_scheme"] = "https" self.validate_url("https://127.0.0.1/", has_host=False) self.environ["SERVER_PORT"] = "8080" self.validate_url("https://127.0.0.1:8080/", has_host=False) self.environ["SERVER_PORT"] = "80" self.validate_url("https://127.0.0.1:80/", has_host=False) def test_http_uri_port(self): del self.environ["HTTP_HOST"] self.environ["SERVER_PORT"] = "80" self.environ["wsgi.url_scheme"] = "http" self.validate_url("http://127.0.0.1/", has_host=False) self.environ["SERVER_PORT"] = "8080" self.validate_url("http://127.0.0.1:8080/", has_host=False) self.environ["SERVER_PORT"] = "443" self.validate_url("http://127.0.0.1:443/", has_host=False) def test_request_attributes_with_nonstandard_port_and_no_host(self): del self.environ["HTTP_HOST"] self.environ["SERVER_PORT"] = "8080" self.validate_url("http://127.0.0.1:8080/", has_host=False) self.environ["SERVER_PORT"] = "443" self.validate_url("http://127.0.0.1:443/", has_host=False) def test_request_attributes_with_conflicting_nonstandard_port(self): self.environ[ "HTTP_HOST" ] += ":8080" # Note that we do not correct SERVER_PORT expected = { "http.host": "127.0.0.1:8080", "http.url": "http://127.0.0.1:8080/", "net.host.port": 80, } self.assertGreaterEqual( otel_wsgi.collect_request_attributes(self.environ).items(), expected.items(), ) def test_request_attributes_with_faux_scheme_relative_raw_uri(self): self.environ["RAW_URI"] = "//127.0.0.1/?" self.validate_url("http://127.0.0.1//127.0.0.1/?", raw=True) def test_request_attributes_pathless(self): self.environ["RAW_URI"] = "" expected = {"http.target": ""} self.assertGreaterEqual( otel_wsgi.collect_request_attributes(self.environ).items(), expected.items(), ) def test_request_attributes_with_full_request_uri(self): self.environ["HTTP_HOST"] = "127.0.0.1:8080" self.environ["REQUEST_METHOD"] = "CONNECT" self.environ[ "REQUEST_URI" ] = "127.0.0.1:8080" # Might happen in a CONNECT request expected = { "http.host": "127.0.0.1:8080", "http.target": "127.0.0.1:8080", } self.assertGreaterEqual( otel_wsgi.collect_request_attributes(self.environ).items(), expected.items(), ) def test_http_user_agent_attribute(self): self.environ["HTTP_USER_AGENT"] = "test-useragent" expected = {"http.user_agent": "test-useragent"} self.assertGreaterEqual( otel_wsgi.collect_request_attributes(self.environ).items(), expected.items(), ) def test_response_attributes(self): otel_wsgi.add_response_attributes(self.span, "404 Not Found", {}) expected = (mock.call("http.status_code", 404),) self.assertEqual(self.span.set_attribute.call_count, len(expected)) self.span.set_attribute.assert_has_calls(expected, any_order=True) if __name__ == "__main__": unittest.main()
35.616438
99
0.638
51e396741e42f0b8f9daec8436d679fba77cb508
6,327
py
Python
tests/accelerators/test_dp.py
Flash-321/pytorch-lightning
cdb6f979a062a639a6d709a0e1915a07d5ed50f6
[ "Apache-2.0" ]
3
2021-05-06T11:31:20.000Z
2021-05-21T10:37:03.000Z
tests/accelerators/test_dp.py
Flash-321/pytorch-lightning
cdb6f979a062a639a6d709a0e1915a07d5ed50f6
[ "Apache-2.0" ]
null
null
null
tests/accelerators/test_dp.py
Flash-321/pytorch-lightning
cdb6f979a062a639a6d709a0e1915a07d5ed50f6
[ "Apache-2.0" ]
null
null
null
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest import torch import torch.nn.functional as F from torch.utils.data import DataLoader import pytorch_lightning as pl import tests.helpers.pipelines as tpipes import tests.helpers.utils as tutils from pytorch_lightning import Trainer from pytorch_lightning.callbacks import EarlyStopping from pytorch_lightning.core import memory from pytorch_lightning.utilities.exceptions import MisconfigurationException from tests.helpers import BoringModel, RandomDataset from tests.helpers.datamodules import ClassifDataModule from tests.helpers.runif import RunIf from tests.helpers.simple_models import ClassificationModel class CustomClassificationModelDP(ClassificationModel): def _step(self, batch, batch_idx): x, y = batch logits = self(x) return {"logits": logits, "y": y} def training_step(self, batch, batch_idx): out = self._step(batch, batch_idx) loss = F.cross_entropy(out["logits"], out["y"]) return loss def validation_step(self, batch, batch_idx): return self._step(batch, batch_idx) def test_step(self, batch, batch_idx): return self._step(batch, batch_idx) def validation_step_end(self, outputs): self.log("val_acc", self.valid_acc(outputs["logits"], outputs["y"])) def test_step_end(self, outputs): self.log("test_acc", self.test_acc(outputs["logits"], outputs["y"])) @RunIf(min_gpus=2) def test_multi_gpu_early_stop_dp(tmpdir): """Make sure DDP works. with early stopping""" tutils.set_random_master_port() dm = ClassifDataModule() model = CustomClassificationModelDP() trainer_options = dict( default_root_dir=tmpdir, callbacks=[EarlyStopping(monitor="val_acc")], max_epochs=50, limit_train_batches=10, limit_val_batches=10, gpus=[0, 1], accelerator="dp", ) tpipes.run_model_test(trainer_options, model, dm) @RunIf(min_gpus=2) def test_multi_gpu_model_dp(tmpdir): tutils.set_random_master_port() trainer_options = dict( default_root_dir=tmpdir, max_epochs=1, limit_train_batches=10, limit_val_batches=10, gpus=[0, 1], accelerator="dp", progress_bar_refresh_rate=0, ) model = BoringModel() tpipes.run_model_test(trainer_options, model) # test memory helper functions memory.get_memory_profile("min_max") class ReductionTestModel(BoringModel): def train_dataloader(self): return DataLoader(RandomDataset(32, 64), batch_size=2) def val_dataloader(self): return DataLoader(RandomDataset(32, 64), batch_size=2) def test_dataloader(self): return DataLoader(RandomDataset(32, 64), batch_size=2) def add_outputs(self, output, device): output.update( { "reduce_int": torch.tensor(device.index, dtype=torch.int, device=device), "reduce_float": torch.tensor(device.index, dtype=torch.float, device=device), } ) def training_step(self, batch, batch_idx): output = super().training_step(batch, batch_idx) self.add_outputs(output, batch.device) return output def validation_step(self, batch, batch_idx): output = super().validation_step(batch, batch_idx) self.add_outputs(output, batch.device) return output def test_step(self, batch, batch_idx): output = super().test_step(batch, batch_idx) self.add_outputs(output, batch.device) return output def training_epoch_end(self, outputs): assert outputs[0]["loss"].shape == torch.Size([]) assert outputs[0]["reduce_int"].item() == 0 # mean([0, 1]) = 0 assert outputs[0]["reduce_float"].item() == 0.5 # mean([0., 1.]) = 0.5 def test_dp_raise_exception_with_batch_transfer_hooks(tmpdir, monkeypatch): """ Test that an exception is raised when overriding batch_transfer_hooks in DP model. """ monkeypatch.setattr("torch.cuda.device_count", lambda: 2) class CustomModel(BoringModel): def transfer_batch_to_device(self, batch, device): batch = batch.to(device) return batch trainer_options = dict(default_root_dir=tmpdir, max_steps=7, gpus=[0, 1], accelerator="dp") trainer = Trainer(**trainer_options) model = CustomModel() with pytest.raises(MisconfigurationException, match=r"Overriding `transfer_batch_to_device` is not .* in DP"): trainer.fit(model) class CustomModel(BoringModel): def on_before_batch_transfer(self, batch, dataloader_idx): batch += 1 return batch trainer = Trainer(**trainer_options) model = CustomModel() with pytest.raises(MisconfigurationException, match=r"Overriding `on_before_batch_transfer` is not .* in DP"): trainer.fit(model) class CustomModel(BoringModel): def on_after_batch_transfer(self, batch, dataloader_idx): batch += 1 return batch trainer = Trainer(**trainer_options) model = CustomModel() with pytest.raises(MisconfigurationException, match=r"Overriding `on_after_batch_transfer` is not .* in DP"): trainer.fit(model) @RunIf(min_gpus=2) def test_dp_training_step_dict(tmpdir): """This test verifies that dp properly reduces dictionaries""" model = ReductionTestModel() model.training_step_end = None model.validation_step_end = None model.test_step_end = None trainer = pl.Trainer( default_root_dir=tmpdir, max_epochs=1, limit_train_batches=1, limit_val_batches=1, limit_test_batches=1, gpus=2, accelerator="dp", ) trainer.fit(model)
31.954545
114
0.690691
b552b11724819f28df8b789906a814e10df21db9
18,844
py
Python
colour/models/tests/test_cam02_ucs.py
rift-labs-developer/colour
15112dbe824aab0f21447e0db4a046a28a06f43a
[ "BSD-3-Clause" ]
null
null
null
colour/models/tests/test_cam02_ucs.py
rift-labs-developer/colour
15112dbe824aab0f21447e0db4a046a28a06f43a
[ "BSD-3-Clause" ]
null
null
null
colour/models/tests/test_cam02_ucs.py
rift-labs-developer/colour
15112dbe824aab0f21447e0db4a046a28a06f43a
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """ Defines the unit tests for the :mod:`colour.models.cam02_ucs` module. """ import numpy as np import unittest from itertools import permutations from colour.appearance import (CAM_KWARGS_CIECAM02_sRGB, VIEWING_CONDITIONS_CIECAM02, XYZ_to_CIECAM02) from colour.models.cam02_ucs import ( COEFFICIENTS_UCS_LUO2006, JMh_CIECAM02_to_UCS_Luo2006, UCS_Luo2006_to_JMh_CIECAM02, XYZ_to_UCS_Luo2006, UCS_Luo2006_to_XYZ) from colour.models import (JMh_CIECAM02_to_CAM02LCD, CAM02LCD_to_JMh_CIECAM02, JMh_CIECAM02_to_CAM02SCD, CAM02SCD_to_JMh_CIECAM02, JMh_CIECAM02_to_CAM02UCS, CAM02UCS_to_JMh_CIECAM02, XYZ_to_CAM02LCD, CAM02LCD_to_XYZ, XYZ_to_CAM02SCD, CAM02SCD_to_XYZ, XYZ_to_CAM02UCS, CAM02UCS_to_XYZ) from colour.utilities import domain_range_scale, ignore_numpy_errors __author__ = 'Colour Developers' __copyright__ = 'Copyright (C) 2013-2021 - Colour Developers' __license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause' __maintainer__ = 'Colour Developers' __email__ = 'colour-developers@colour-science.org' __status__ = 'Production' __all__ = [ 'TestJMh_CIECAM02_to_UCS_Luo2006', 'TestUCS_Luo2006_to_JMh_CIECAM02', 'TestXYZ_to_UCS_Luo2006', 'TestUCS_Luo2006_to_XYZ' ] class TestJMh_CIECAM02_to_UCS_Luo2006(unittest.TestCase): """ Defines :func:`colour.models.cam02_ucs.JMh_CIECAM02_to_UCS_Luo2006` definition unit tests methods. """ def setUp(self): """ Initialises common tests attributes. """ XYZ = np.array([19.01, 20.00, 21.78]) XYZ_w = np.array([95.05, 100.00, 108.88]) L_A = 318.31 Y_b = 20.0 surround = VIEWING_CONDITIONS_CIECAM02['Average'] specification = XYZ_to_CIECAM02(XYZ, XYZ_w, L_A, Y_b, surround) self._JMh = np.array( [specification.J, specification.M, specification.h]) def test_JMh_CIECAM02_to_UCS_Luo2006(self): """ Tests :func:`colour.models.cam02_ucs.JMh_CIECAM02_to_UCS_Luo2006` definition. """ np.testing.assert_almost_equal( JMh_CIECAM02_to_UCS_Luo2006(self._JMh, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), np.array([54.90433134, -0.08450395, -0.06854831]), decimal=7) np.testing.assert_almost_equal( JMh_CIECAM02_to_UCS_Luo2006(self._JMh, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), JMh_CIECAM02_to_CAM02LCD(self._JMh), decimal=7) np.testing.assert_almost_equal( JMh_CIECAM02_to_UCS_Luo2006(self._JMh, COEFFICIENTS_UCS_LUO2006['CAM02-SCD']), np.array([54.90433134, -0.08436178, -0.06843298]), decimal=7) np.testing.assert_almost_equal( JMh_CIECAM02_to_UCS_Luo2006(self._JMh, COEFFICIENTS_UCS_LUO2006['CAM02-SCD']), JMh_CIECAM02_to_CAM02SCD(self._JMh), decimal=7) np.testing.assert_almost_equal( JMh_CIECAM02_to_UCS_Luo2006(self._JMh, COEFFICIENTS_UCS_LUO2006['CAM02-UCS']), np.array([54.90433134, -0.08442362, -0.06848314]), decimal=7) np.testing.assert_almost_equal( JMh_CIECAM02_to_UCS_Luo2006(self._JMh, COEFFICIENTS_UCS_LUO2006['CAM02-UCS']), JMh_CIECAM02_to_CAM02UCS(self._JMh), decimal=7) def test_n_dimensional_JMh_CIECAM02_to_UCS_Luo2006(self): """ Tests :func:`colour.models.cam02_ucs.JMh_CIECAM02_to_UCS_Luo2006` definition n-dimensional support. """ JMh = self._JMh Jpapbp = JMh_CIECAM02_to_UCS_Luo2006( JMh, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']) JMh = np.tile(JMh, (6, 1)) Jpapbp = np.tile(Jpapbp, (6, 1)) np.testing.assert_almost_equal( JMh_CIECAM02_to_UCS_Luo2006(JMh, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), Jpapbp, decimal=7) JMh = np.reshape(JMh, (2, 3, 3)) Jpapbp = np.reshape(Jpapbp, (2, 3, 3)) np.testing.assert_almost_equal( JMh_CIECAM02_to_UCS_Luo2006(JMh, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), Jpapbp, decimal=7) def test_domain_range_scale_JMh_CIECAM02_to_UCS_Luo2006(self): """ Tests :func:`colour.models.cam02_ucs.JMh_CIECAM02_to_UCS_Luo2006` definition domain and range scale support. """ JMh = self._JMh Jpapbp = JMh_CIECAM02_to_UCS_Luo2006( JMh, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']) d_r = (('reference', 1, 1), (1, np.array([0.01, 0.01, 1 / 360]), 0.01), (100, np.array([1, 1, 1 / 3.6]), 1)) for scale, factor_a, factor_b in d_r: with domain_range_scale(scale): np.testing.assert_almost_equal( JMh_CIECAM02_to_UCS_Luo2006( JMh * factor_a, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), Jpapbp * factor_b, decimal=7) @ignore_numpy_errors def test_nan_JMh_CIECAM02_to_UCS_Luo2006(self): """ Tests :func:`colour.models.cam02_ucs.JMh_CIECAM02_to_UCS_Luo2006` definition nan support. """ cases = [-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan] cases = set(permutations(cases * 3, r=3)) for case in cases: JMh = np.array(case) JMh_CIECAM02_to_UCS_Luo2006(JMh, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']) class TestUCS_Luo2006_to_JMh_CIECAM02(unittest.TestCase): """ Defines :func:`colour.models.cam02_ucs.UCS_Luo2006_to_JMh_CIECAM02` definition unit tests methods. """ def test_UCS_Luo2006_to_JMh_CIECAM02(self): """ Tests :func:`colour.models.cam02_ucs.UCS_Luo2006_to_JMh_CIECAM02` definition. """ np.testing.assert_almost_equal( UCS_Luo2006_to_JMh_CIECAM02( np.array([54.90433134, -0.08442362, -0.06848314]), COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), np.array([41.73109113, 0.10873867, 219.04843202]), decimal=7) np.testing.assert_almost_equal( UCS_Luo2006_to_JMh_CIECAM02( np.array([54.90433134, -0.08442362, -0.06848314]), COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), CAM02LCD_to_JMh_CIECAM02( np.array([54.90433134, -0.08442362, -0.06848314])), decimal=7) np.testing.assert_almost_equal( UCS_Luo2006_to_JMh_CIECAM02( np.array([54.90433134, -0.08442362, -0.06848314]), COEFFICIENTS_UCS_LUO2006['CAM02-SCD']), np.array([41.73109113, 0.10892212, 219.04843202]), decimal=7) np.testing.assert_almost_equal( UCS_Luo2006_to_JMh_CIECAM02( np.array([54.90433134, -0.08442362, -0.06848314]), COEFFICIENTS_UCS_LUO2006['CAM02-SCD']), CAM02SCD_to_JMh_CIECAM02( np.array([54.90433134, -0.08442362, -0.06848314])), decimal=7) np.testing.assert_almost_equal( UCS_Luo2006_to_JMh_CIECAM02( np.array([54.90433134, -0.08442362, -0.06848314]), COEFFICIENTS_UCS_LUO2006['CAM02-UCS']), np.array([41.73109113, 0.10884218, 219.04843202]), decimal=7) np.testing.assert_almost_equal( UCS_Luo2006_to_JMh_CIECAM02( np.array([54.90433134, -0.08442362, -0.06848314]), COEFFICIENTS_UCS_LUO2006['CAM02-UCS']), CAM02UCS_to_JMh_CIECAM02( np.array([54.90433134, -0.08442362, -0.06848314])), decimal=7) def test_n_dimensional_UCS_Luo2006_to_JMh_CIECAM02(self): """ Tests :func:`colour.models.cam02_ucs.UCS_Luo2006_to_JMh_CIECAM02` definition n-dimensional support. """ Jpapbp = np.array([54.90433134, -0.08442362, -0.06848314]) JMh = UCS_Luo2006_to_JMh_CIECAM02( Jpapbp, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']) Jpapbp = np.tile(Jpapbp, (6, 1)) JMh = np.tile(JMh, (6, 1)) np.testing.assert_almost_equal( UCS_Luo2006_to_JMh_CIECAM02(Jpapbp, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), JMh, decimal=7) Jpapbp = np.reshape(Jpapbp, (2, 3, 3)) JMh = np.reshape(JMh, (2, 3, 3)) np.testing.assert_almost_equal( UCS_Luo2006_to_JMh_CIECAM02(Jpapbp, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), JMh, decimal=7) def test_domain_range_scale_UCS_Luo2006_to_JMh_CIECAM02(self): """ Tests :func:`colour.models.cam02_ucs.UCS_Luo2006_to_JMh_CIECAM02` definition domain and range scale support. """ Jpapbp = np.array([54.90433134, -0.08442362, -0.06848314]) JMh = UCS_Luo2006_to_JMh_CIECAM02( Jpapbp, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']) d_r = (('reference', 1, 1), (1, 0.01, np.array([0.01, 0.01, 1 / 360])), (100, 1, np.array([1, 1, 1 / 3.6]))) for scale, factor_a, factor_b in d_r: with domain_range_scale(scale): np.testing.assert_almost_equal( UCS_Luo2006_to_JMh_CIECAM02( Jpapbp * factor_a, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), JMh * factor_b, decimal=7) @ignore_numpy_errors def test_nan_UCS_Luo2006_to_JMh_CIECAM02(self): """ Tests :func:`colour.models.cam02_ucs.UCS_Luo2006_to_JMh_CIECAM02` definition nan support. """ cases = [-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan] cases = set(permutations(cases * 3, r=3)) for case in cases: Jpapbp = np.array(case) UCS_Luo2006_to_JMh_CIECAM02(Jpapbp, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']) class TestXYZ_to_UCS_Luo2006(unittest.TestCase): """ Defines :func:`colour.models.cam02_ucs.XYZ_to_UCS_Luo2006` definition unit tests methods. """ def test_XYZ_to_UCS_Luo2006(self): """ Tests :func:`colour.models.cam02_ucs.XYZ_to_UCS_Luo2006` definition. """ np.testing.assert_almost_equal( XYZ_to_UCS_Luo2006( np.array([0.20654008, 0.12197225, 0.05136952]), COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), np.array([46.61386154, 39.35760236, 15.96730435]), decimal=7) np.testing.assert_almost_equal( XYZ_to_UCS_Luo2006( np.array([0.20654008, 0.12197225, 0.05136952]), COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), XYZ_to_CAM02LCD(np.array([0.20654008, 0.12197225, 0.05136952])), decimal=7) np.testing.assert_almost_equal( XYZ_to_UCS_Luo2006( np.array([0.20654008, 0.12197225, 0.05136952]), COEFFICIENTS_UCS_LUO2006['CAM02-SCD']), np.array([46.61386154, 25.62879882, 10.39755489]), decimal=7) np.testing.assert_almost_equal( XYZ_to_UCS_Luo2006( np.array([0.20654008, 0.12197225, 0.05136952]), COEFFICIENTS_UCS_LUO2006['CAM02-SCD']), XYZ_to_CAM02SCD(np.array([0.20654008, 0.12197225, 0.05136952])), decimal=7) np.testing.assert_almost_equal( XYZ_to_UCS_Luo2006( np.array([0.20654008, 0.12197225, 0.05136952]), COEFFICIENTS_UCS_LUO2006['CAM02-UCS']), np.array([46.61386154, 29.88310013, 12.12351683]), decimal=7) np.testing.assert_almost_equal( XYZ_to_UCS_Luo2006( np.array([0.20654008, 0.12197225, 0.05136952]), COEFFICIENTS_UCS_LUO2006['CAM02-UCS']), XYZ_to_CAM02UCS(np.array([0.20654008, 0.12197225, 0.05136952])), decimal=7) def test_n_dimensional_XYZ_to_UCS_Luo2006(self): """ Tests :func:`colour.models.cam02_ucs.XYZ_to_UCS_Luo2006` definition n-dimensional support. """ XYZ = np.array([0.20654008, 0.12197225, 0.05136952]) Jpapbp = XYZ_to_UCS_Luo2006(XYZ, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']) XYZ = np.tile(XYZ, (6, 1)) Jpapbp = np.tile(Jpapbp, (6, 1)) np.testing.assert_almost_equal( XYZ_to_UCS_Luo2006(XYZ, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), Jpapbp, decimal=7) XYZ = np.reshape(XYZ, (2, 3, 3)) Jpapbp = np.reshape(Jpapbp, (2, 3, 3)) np.testing.assert_almost_equal( XYZ_to_UCS_Luo2006(XYZ, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), Jpapbp, decimal=7) def test_domain_range_scale_XYZ_to_UCS_Luo2006(self): """ Tests :func:`colour.models.cam02_ucs.XYZ_to_UCS_Luo2006` definition domain and range scale support. """ XYZ = np.array([0.20654008, 0.12197225, 0.05136952]) XYZ_w = CAM_KWARGS_CIECAM02_sRGB['XYZ_w'] / 100 Jpapbp = XYZ_to_UCS_Luo2006(XYZ, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']) d_r = (('reference', 1, 1), (1, 1, 0.01), (100, 100, 1)) for scale, factor_a, factor_b in d_r: with domain_range_scale(scale): np.testing.assert_almost_equal( XYZ_to_UCS_Luo2006( XYZ * factor_a, COEFFICIENTS_UCS_LUO2006['CAM02-LCD'], XYZ_w=XYZ_w * factor_a), Jpapbp * factor_b, decimal=7) @ignore_numpy_errors def test_nan_XYZ_to_UCS_Luo2006(self): """ Tests :func:`colour.models.cam02_ucs.XYZ_to_UCS_Luo2006` definition nan support. """ cases = [-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan] cases = set(permutations(cases * 3, r=3)) for case in cases: XYZ = np.array(case) XYZ_to_UCS_Luo2006(XYZ, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']) class TestUCS_Luo2006_to_XYZ(unittest.TestCase): """ Defines :func:`colour.models.cam02_ucs.UCS_Luo2006_to_XYZ` definition unit tests methods. """ def test_UCS_Luo2006_to_XYZ(self): """ Tests :func:`colour.models.cam02_ucs.UCS_Luo2006_to_XYZ` definition. """ np.testing.assert_almost_equal( UCS_Luo2006_to_XYZ( np.array([46.61386154, 39.35760236, 15.96730435]), COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), np.array([0.20654008, 0.12197225, 0.05136952]), decimal=7) np.testing.assert_almost_equal( UCS_Luo2006_to_XYZ( np.array([46.61386154, 39.35760236, 15.96730435]), COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), CAM02LCD_to_XYZ(np.array([46.61386154, 39.35760236, 15.96730435])), decimal=7) np.testing.assert_almost_equal( UCS_Luo2006_to_XYZ( np.array([46.61386154, 39.35760236, 15.96730435]), COEFFICIENTS_UCS_LUO2006['CAM02-SCD']), np.array([0.28264475, 0.11036927, 0.00824593]), decimal=7) np.testing.assert_almost_equal( UCS_Luo2006_to_XYZ( np.array([46.61386154, 39.35760236, 15.96730435]), COEFFICIENTS_UCS_LUO2006['CAM02-SCD']), CAM02SCD_to_XYZ(np.array([46.61386154, 39.35760236, 15.96730435])), decimal=7) np.testing.assert_almost_equal( UCS_Luo2006_to_XYZ( np.array([46.61386154, 39.35760236, 15.96730435]), COEFFICIENTS_UCS_LUO2006['CAM02-UCS']), np.array([0.24229809, 0.11573005, 0.02517649]), decimal=7) np.testing.assert_almost_equal( UCS_Luo2006_to_XYZ( np.array([46.61386154, 39.35760236, 15.96730435]), COEFFICIENTS_UCS_LUO2006['CAM02-UCS']), CAM02UCS_to_XYZ(np.array([46.61386154, 39.35760236, 15.96730435])), decimal=7) def test_n_dimensional_UCS_Luo2006_to_XYZ(self): """ Tests :func:`colour.models.cam02_ucs.UCS_Luo2006_to_XYZ` definition n-dimensional support. """ Jpapbp = np.array([46.61386154, 39.35760236, 15.96730435]) XYZ = UCS_Luo2006_to_XYZ(Jpapbp, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']) Jpapbp = np.tile(Jpapbp, (6, 1)) XYZ = np.tile(XYZ, (6, 1)) np.testing.assert_almost_equal( UCS_Luo2006_to_XYZ(Jpapbp, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), XYZ, decimal=7) Jpapbp = np.reshape(Jpapbp, (2, 3, 3)) XYZ = np.reshape(XYZ, (2, 3, 3)) np.testing.assert_almost_equal( UCS_Luo2006_to_XYZ(Jpapbp, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']), XYZ, decimal=7) def test_domain_range_scale_UCS_Luo2006_to_XYZ(self): """ Tests :func:`colour.models.cam02_ucs.UCS_Luo2006_to_XYZ` definition domain and range scale support. """ Jpapbp = np.array([46.61386154, 39.35760236, 15.96730435]) XYZ = UCS_Luo2006_to_XYZ(Jpapbp, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']) XYZ_w = CAM_KWARGS_CIECAM02_sRGB['XYZ_w'] / 100 d_r = (('reference', 1, 1, 1), (1, 0.01, 1, 1), (100, 1, 100, 100)) for scale, factor_a, factor_b, factor_c in d_r: with domain_range_scale(scale): np.testing.assert_almost_equal( UCS_Luo2006_to_XYZ( Jpapbp * factor_a, COEFFICIENTS_UCS_LUO2006['CAM02-LCD'], XYZ_w=XYZ_w * factor_c), XYZ * factor_b, decimal=7) @ignore_numpy_errors def test_nan_UCS_Luo2006_to_XYZ(self): """ Tests :func:`colour.models.cam02_ucs.UCS_Luo2006_to_XYZ` definition nan support. """ cases = [-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan] cases = set(permutations(cases * 3, r=3)) for case in cases: Jpapbp = np.array(case) UCS_Luo2006_to_XYZ(Jpapbp, COEFFICIENTS_UCS_LUO2006['CAM02-LCD']) if __name__ == '__main__': unittest.main()
37.537849
79
0.587773
5ec93ca3d97724bbe63ee549127cb96055b692b8
118,235
py
Python
python/pyspark/pandas/tests/test_groupby.py
almogtavor/spark
78e6263cce949843c07c821356ea58c4c568ccdc
[ "BSD-2-Clause", "Apache-2.0", "CC0-1.0", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-05-09T14:37:19.000Z
2020-05-09T14:37:19.000Z
python/pyspark/pandas/tests/test_groupby.py
akshatb1/spark
80f6fe2f6de16cef706bcb4ea2f9233131c5e767
[ "BSD-2-Clause", "Apache-2.0", "CC0-1.0", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
python/pyspark/pandas/tests/test_groupby.py
akshatb1/spark
80f6fe2f6de16cef706bcb4ea2f9233131c5e767
[ "BSD-2-Clause", "Apache-2.0", "CC0-1.0", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import unittest import inspect from distutils.version import LooseVersion from itertools import product import numpy as np import pandas as pd from pyspark import pandas as ps from pyspark.pandas.config import option_context from pyspark.pandas.exceptions import PandasNotImplementedError, DataError from pyspark.pandas.missing.groupby import ( MissingPandasLikeDataFrameGroupBy, MissingPandasLikeSeriesGroupBy, ) from pyspark.pandas.groupby import is_multi_agg_with_relabel from pyspark.testing.pandasutils import PandasOnSparkTestCase, TestUtils # This is used in run-tests.py to discover the slow test. See more in the doc of # _discover_python_unittests of dev/sparktestsupport/modules.py is_slow_test = True class GroupByTest(PandasOnSparkTestCase, TestUtils): def test_groupby_simple(self): pdf = pd.DataFrame( { "a": [1, 2, 6, 4, 4, 6, 4, 3, 7], "b": [4, 2, 7, 3, 3, 1, 1, 1, 2], "c": [4, 2, 7, 3, None, 1, 1, 1, 2], "d": list("abcdefght"), }, index=[0, 1, 3, 5, 6, 8, 9, 9, 9], ) psdf = ps.from_pandas(pdf) for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values("a").reset_index(drop=True) self.assert_eq( sort(psdf.groupby("a", as_index=as_index).sum()), sort(pdf.groupby("a", as_index=as_index).sum()), ) self.assert_eq( sort(psdf.groupby("a", as_index=as_index).b.sum()), sort(pdf.groupby("a", as_index=as_index).b.sum()), ) self.assert_eq( sort(psdf.groupby("a", as_index=as_index)["b"].sum()), sort(pdf.groupby("a", as_index=as_index)["b"].sum()), ) self.assert_eq( sort(psdf.groupby("a", as_index=as_index)[["b", "c"]].sum()), sort(pdf.groupby("a", as_index=as_index)[["b", "c"]].sum()), ) self.assert_eq( sort(psdf.groupby("a", as_index=as_index)[[]].sum()), sort(pdf.groupby("a", as_index=as_index)[[]].sum()), ) self.assert_eq( sort(psdf.groupby("a", as_index=as_index)["c"].sum()), sort(pdf.groupby("a", as_index=as_index)["c"].sum()), ) self.assert_eq( psdf.groupby("a").a.sum().sort_index(), pdf.groupby("a").a.sum().sort_index() ) self.assert_eq( psdf.groupby("a")["a"].sum().sort_index(), pdf.groupby("a")["a"].sum().sort_index() ) self.assert_eq( psdf.groupby("a")[["a"]].sum().sort_index(), pdf.groupby("a")[["a"]].sum().sort_index() ) self.assert_eq( psdf.groupby("a")[["a", "c"]].sum().sort_index(), pdf.groupby("a")[["a", "c"]].sum().sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b).sum().sort_index(), pdf.a.groupby(pdf.b).sum().sort_index() ) for axis in [0, "index"]: self.assert_eq( psdf.groupby("a", axis=axis).a.sum().sort_index(), pdf.groupby("a", axis=axis).a.sum().sort_index(), ) self.assert_eq( psdf.groupby("a", axis=axis)["a"].sum().sort_index(), pdf.groupby("a", axis=axis)["a"].sum().sort_index(), ) self.assert_eq( psdf.groupby("a", axis=axis)[["a"]].sum().sort_index(), pdf.groupby("a", axis=axis)[["a"]].sum().sort_index(), ) self.assert_eq( psdf.groupby("a", axis=axis)[["a", "c"]].sum().sort_index(), pdf.groupby("a", axis=axis)[["a", "c"]].sum().sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b, axis=axis).sum().sort_index(), pdf.a.groupby(pdf.b, axis=axis).sum().sort_index(), ) self.assertRaises(ValueError, lambda: psdf.groupby("a", as_index=False).a) self.assertRaises(ValueError, lambda: psdf.groupby("a", as_index=False)["a"]) self.assertRaises(ValueError, lambda: psdf.groupby("a", as_index=False)[["a"]]) self.assertRaises(ValueError, lambda: psdf.groupby("a", as_index=False)[["a", "c"]]) self.assertRaises(KeyError, lambda: psdf.groupby("z", as_index=False)[["a", "c"]]) self.assertRaises(KeyError, lambda: psdf.groupby(["z"], as_index=False)[["a", "c"]]) self.assertRaises(TypeError, lambda: psdf.a.groupby(psdf.b, as_index=False)) self.assertRaises(NotImplementedError, lambda: psdf.groupby("a", axis=1)) self.assertRaises(NotImplementedError, lambda: psdf.groupby("a", axis="columns")) self.assertRaises(ValueError, lambda: psdf.groupby("a", "b")) self.assertRaises(TypeError, lambda: psdf.a.groupby(psdf.a, psdf.b)) # we can't use column name/names as a parameter `by` for `SeriesGroupBy`. self.assertRaises(KeyError, lambda: psdf.a.groupby(by="a")) self.assertRaises(KeyError, lambda: psdf.a.groupby(by=["a", "b"])) self.assertRaises(KeyError, lambda: psdf.a.groupby(by=("a", "b"))) # we can't use DataFrame as a parameter `by` for `DataFrameGroupBy`/`SeriesGroupBy`. self.assertRaises(ValueError, lambda: psdf.groupby(psdf)) self.assertRaises(ValueError, lambda: psdf.a.groupby(psdf)) self.assertRaises(ValueError, lambda: psdf.a.groupby((psdf,))) # non-string names pdf = pd.DataFrame( { 10: [1, 2, 6, 4, 4, 6, 4, 3, 7], 20: [4, 2, 7, 3, 3, 1, 1, 1, 2], 30: [4, 2, 7, 3, None, 1, 1, 1, 2], 40: list("abcdefght"), }, index=[0, 1, 3, 5, 6, 8, 9, 9, 9], ) psdf = ps.from_pandas(pdf) for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values(10).reset_index(drop=True) self.assert_eq( sort(psdf.groupby(10, as_index=as_index).sum()), sort(pdf.groupby(10, as_index=as_index).sum()), ) self.assert_eq( sort(psdf.groupby(10, as_index=as_index)[20].sum()), sort(pdf.groupby(10, as_index=as_index)[20].sum()), ) self.assert_eq( sort(psdf.groupby(10, as_index=as_index)[[20, 30]].sum()), sort(pdf.groupby(10, as_index=as_index)[[20, 30]].sum()), ) def test_groupby_multiindex_columns(self): pdf = pd.DataFrame( { (10, "a"): [1, 2, 6, 4, 4, 6, 4, 3, 7], (10, "b"): [4, 2, 7, 3, 3, 1, 1, 1, 2], (20, "c"): [4, 2, 7, 3, None, 1, 1, 1, 2], (30, "d"): list("abcdefght"), }, index=[0, 1, 3, 5, 6, 8, 9, 9, 9], ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby((10, "a")).sum().sort_index(), pdf.groupby((10, "a")).sum().sort_index() ) self.assert_eq( psdf.groupby((10, "a"), as_index=False) .sum() .sort_values((10, "a")) .reset_index(drop=True), pdf.groupby((10, "a"), as_index=False) .sum() .sort_values((10, "a")) .reset_index(drop=True), ) self.assert_eq( psdf.groupby((10, "a"))[[(20, "c")]].sum().sort_index(), pdf.groupby((10, "a"))[[(20, "c")]].sum().sort_index(), ) # TODO: a pandas bug? # expected = pdf.groupby((10, "a"))[(20, "c")].sum().sort_index() expected = pd.Series( [4.0, 2.0, 1.0, 4.0, 8.0, 2.0], name=(20, "c"), index=pd.Index([1, 2, 3, 4, 6, 7], name=(10, "a")), ) self.assert_eq(psdf.groupby((10, "a"))[(20, "c")].sum().sort_index(), expected) if ( LooseVersion(pd.__version__) >= LooseVersion("1.0.4") and LooseVersion(pd.__version__) != LooseVersion("1.1.3") and LooseVersion(pd.__version__) != LooseVersion("1.1.4") ): self.assert_eq( psdf[(20, "c")].groupby(psdf[(10, "a")]).sum().sort_index(), pdf[(20, "c")].groupby(pdf[(10, "a")]).sum().sort_index(), ) else: # Due to pandas bugs resolved in 1.0.4, re-introduced in 1.1.3 and resolved in 1.1.5 self.assert_eq(psdf[(20, "c")].groupby(psdf[(10, "a")]).sum().sort_index(), expected) def test_split_apply_combine_on_series(self): pdf = pd.DataFrame( { "a": [1, 2, 6, 4, 4, 6, 4, 3, 7], "b": [4, 2, 7, 3, 3, 1, 1, 1, 2], "c": [4, 2, 7, 3, None, 1, 1, 1, 2], "d": list("abcdefght"), }, index=[0, 1, 3, 5, 6, 8, 9, 9, 9], ) psdf = ps.from_pandas(pdf) funcs = [ ((True, False), ["sum", "min", "max", "count", "first", "last"]), ((True, True), ["mean"]), ((False, False), ["var", "std"]), ] funcs = [(check_exact, almost, f) for (check_exact, almost), fs in funcs for f in fs] for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values(list(df.columns)).reset_index(drop=True) for check_exact, almost, func in funcs: for kkey, pkey in [("b", "b"), (psdf.b, pdf.b)]: with self.subTest(as_index=as_index, func=func, key=pkey): if as_index is True or func != "std": self.assert_eq( sort(getattr(psdf.groupby(kkey, as_index=as_index).a, func)()), sort(getattr(pdf.groupby(pkey, as_index=as_index).a, func)()), check_exact=check_exact, almost=almost, ) self.assert_eq( sort(getattr(psdf.groupby(kkey, as_index=as_index), func)()), sort(getattr(pdf.groupby(pkey, as_index=as_index), func)()), check_exact=check_exact, almost=almost, ) else: # seems like a pandas' bug for as_index=False and func == "std"? self.assert_eq( sort(getattr(psdf.groupby(kkey, as_index=as_index).a, func)()), sort(pdf.groupby(pkey, as_index=True).a.std().reset_index()), check_exact=check_exact, almost=almost, ) self.assert_eq( sort(getattr(psdf.groupby(kkey, as_index=as_index), func)()), sort(pdf.groupby(pkey, as_index=True).std().reset_index()), check_exact=check_exact, almost=almost, ) for kkey, pkey in [(psdf.b + 1, pdf.b + 1), (psdf.copy().b, pdf.copy().b)]: with self.subTest(as_index=as_index, func=func, key=pkey): self.assert_eq( sort(getattr(psdf.groupby(kkey, as_index=as_index).a, func)()), sort(getattr(pdf.groupby(pkey, as_index=as_index).a, func)()), check_exact=check_exact, almost=almost, ) self.assert_eq( sort(getattr(psdf.groupby(kkey, as_index=as_index), func)()), sort(getattr(pdf.groupby(pkey, as_index=as_index), func)()), check_exact=check_exact, almost=almost, ) for check_exact, almost, func in funcs: for i in [0, 4, 7]: with self.subTest(as_index=as_index, func=func, i=i): self.assert_eq( sort(getattr(psdf.groupby(psdf.b > i, as_index=as_index).a, func)()), sort(getattr(pdf.groupby(pdf.b > i, as_index=as_index).a, func)()), check_exact=check_exact, almost=almost, ) self.assert_eq( sort(getattr(psdf.groupby(psdf.b > i, as_index=as_index), func)()), sort(getattr(pdf.groupby(pdf.b > i, as_index=as_index), func)()), check_exact=check_exact, almost=almost, ) for check_exact, almost, func in funcs: for kkey, pkey in [ (psdf.b, pdf.b), (psdf.b + 1, pdf.b + 1), (psdf.copy().b, pdf.copy().b), (psdf.b.rename(), pdf.b.rename()), ]: with self.subTest(func=func, key=pkey): self.assert_eq( getattr(psdf.a.groupby(kkey), func)().sort_index(), getattr(pdf.a.groupby(pkey), func)().sort_index(), check_exact=check_exact, almost=almost, ) self.assert_eq( getattr((psdf.a + 1).groupby(kkey), func)().sort_index(), getattr((pdf.a + 1).groupby(pkey), func)().sort_index(), check_exact=check_exact, almost=almost, ) self.assert_eq( getattr((psdf.b + 1).groupby(kkey), func)().sort_index(), getattr((pdf.b + 1).groupby(pkey), func)().sort_index(), check_exact=check_exact, almost=almost, ) self.assert_eq( getattr(psdf.a.rename().groupby(kkey), func)().sort_index(), getattr(pdf.a.rename().groupby(pkey), func)().sort_index(), check_exact=check_exact, almost=almost, ) def test_aggregate(self): pdf = pd.DataFrame( {"A": [1, 1, 2, 2], "B": [1, 2, 3, 4], "C": [0.362, 0.227, 1.267, -0.562]} ) psdf = ps.from_pandas(pdf) for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values(list(df.columns)).reset_index(drop=True) for kkey, pkey in [("A", "A"), (psdf.A, pdf.A)]: with self.subTest(as_index=as_index, key=pkey): self.assert_eq( sort(psdf.groupby(kkey, as_index=as_index).agg("sum")), sort(pdf.groupby(pkey, as_index=as_index).agg("sum")), ) self.assert_eq( sort(psdf.groupby(kkey, as_index=as_index).agg({"B": "min", "C": "sum"})), sort(pdf.groupby(pkey, as_index=as_index).agg({"B": "min", "C": "sum"})), ) self.assert_eq( sort( psdf.groupby(kkey, as_index=as_index).agg( {"B": ["min", "max"], "C": "sum"} ) ), sort( pdf.groupby(pkey, as_index=as_index).agg( {"B": ["min", "max"], "C": "sum"} ) ), ) if as_index: self.assert_eq( sort(psdf.groupby(kkey, as_index=as_index).agg(["sum"])), sort(pdf.groupby(pkey, as_index=as_index).agg(["sum"])), ) else: # seems like a pandas' bug for as_index=False and func_or_funcs is list? self.assert_eq( sort(psdf.groupby(kkey, as_index=as_index).agg(["sum"])), sort(pdf.groupby(pkey, as_index=True).agg(["sum"]).reset_index()), ) for kkey, pkey in [(psdf.A + 1, pdf.A + 1), (psdf.copy().A, pdf.copy().A)]: with self.subTest(as_index=as_index, key=pkey): self.assert_eq( sort(psdf.groupby(kkey, as_index=as_index).agg("sum")), sort(pdf.groupby(pkey, as_index=as_index).agg("sum")), ) self.assert_eq( sort(psdf.groupby(kkey, as_index=as_index).agg({"B": "min", "C": "sum"})), sort(pdf.groupby(pkey, as_index=as_index).agg({"B": "min", "C": "sum"})), ) self.assert_eq( sort( psdf.groupby(kkey, as_index=as_index).agg( {"B": ["min", "max"], "C": "sum"} ) ), sort( pdf.groupby(pkey, as_index=as_index).agg( {"B": ["min", "max"], "C": "sum"} ) ), ) self.assert_eq( sort(psdf.groupby(kkey, as_index=as_index).agg(["sum"])), sort(pdf.groupby(pkey, as_index=as_index).agg(["sum"])), ) expected_error_message = ( r"aggs must be a dict mapping from column name to aggregate functions " r"\(string or list of strings\)." ) with self.assertRaisesRegex(ValueError, expected_error_message): psdf.groupby("A", as_index=as_index).agg(0) # multi-index columns columns = pd.MultiIndex.from_tuples([(10, "A"), (10, "B"), (20, "C")]) pdf.columns = columns psdf.columns = columns for as_index in [True, False]: stats_psdf = psdf.groupby((10, "A"), as_index=as_index).agg( {(10, "B"): "min", (20, "C"): "sum"} ) stats_pdf = pdf.groupby((10, "A"), as_index=as_index).agg( {(10, "B"): "min", (20, "C"): "sum"} ) self.assert_eq( stats_psdf.sort_values(by=[(10, "B"), (20, "C")]).reset_index(drop=True), stats_pdf.sort_values(by=[(10, "B"), (20, "C")]).reset_index(drop=True), ) stats_psdf = psdf.groupby((10, "A")).agg({(10, "B"): ["min", "max"], (20, "C"): "sum"}) stats_pdf = pdf.groupby((10, "A")).agg({(10, "B"): ["min", "max"], (20, "C"): "sum"}) self.assert_eq( stats_psdf.sort_values( by=[(10, "B", "min"), (10, "B", "max"), (20, "C", "sum")] ).reset_index(drop=True), stats_pdf.sort_values( by=[(10, "B", "min"), (10, "B", "max"), (20, "C", "sum")] ).reset_index(drop=True), ) # non-string names pdf.columns = [10, 20, 30] psdf.columns = [10, 20, 30] for as_index in [True, False]: stats_psdf = psdf.groupby(10, as_index=as_index).agg({20: "min", 30: "sum"}) stats_pdf = pdf.groupby(10, as_index=as_index).agg({20: "min", 30: "sum"}) self.assert_eq( stats_psdf.sort_values(by=[20, 30]).reset_index(drop=True), stats_pdf.sort_values(by=[20, 30]).reset_index(drop=True), ) stats_psdf = psdf.groupby(10).agg({20: ["min", "max"], 30: "sum"}) stats_pdf = pdf.groupby(10).agg({20: ["min", "max"], 30: "sum"}) self.assert_eq( stats_psdf.sort_values(by=[(20, "min"), (20, "max"), (30, "sum")]).reset_index( drop=True ), stats_pdf.sort_values(by=[(20, "min"), (20, "max"), (30, "sum")]).reset_index( drop=True ), ) def test_aggregate_func_str_list(self): # this is test for cases where only string or list is assigned pdf = pd.DataFrame( { "kind": ["cat", "dog", "cat", "dog"], "height": [9.1, 6.0, 9.5, 34.0], "weight": [7.9, 7.5, 9.9, 198.0], } ) psdf = ps.from_pandas(pdf) agg_funcs = ["max", "min", ["min", "max"]] for aggfunc in agg_funcs: # Since in Koalas groupby, the order of rows might be different # so sort on index to ensure they have same output sorted_agg_psdf = psdf.groupby("kind").agg(aggfunc).sort_index() sorted_agg_pdf = pdf.groupby("kind").agg(aggfunc).sort_index() self.assert_eq(sorted_agg_psdf, sorted_agg_pdf) # test on multi index column case pdf = pd.DataFrame( {"A": [1, 1, 2, 2], "B": [1, 2, 3, 4], "C": [0.362, 0.227, 1.267, -0.562]} ) psdf = ps.from_pandas(pdf) columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B"), ("Y", "C")]) pdf.columns = columns psdf.columns = columns for aggfunc in agg_funcs: sorted_agg_psdf = psdf.groupby(("X", "A")).agg(aggfunc).sort_index() sorted_agg_pdf = pdf.groupby(("X", "A")).agg(aggfunc).sort_index() self.assert_eq(sorted_agg_psdf, sorted_agg_pdf) @unittest.skipIf(pd.__version__ < "0.25.0", "not supported before pandas 0.25.0") def test_aggregate_relabel(self): # this is to test named aggregation in groupby pdf = pd.DataFrame({"group": ["a", "a", "b", "b"], "A": [0, 1, 2, 3], "B": [5, 6, 7, 8]}) psdf = ps.from_pandas(pdf) # different agg column, same function agg_pdf = pdf.groupby("group").agg(a_max=("A", "max"), b_max=("B", "max")).sort_index() agg_psdf = psdf.groupby("group").agg(a_max=("A", "max"), b_max=("B", "max")).sort_index() self.assert_eq(agg_pdf, agg_psdf) # same agg column, different functions agg_pdf = pdf.groupby("group").agg(b_max=("B", "max"), b_min=("B", "min")).sort_index() agg_psdf = psdf.groupby("group").agg(b_max=("B", "max"), b_min=("B", "min")).sort_index() self.assert_eq(agg_pdf, agg_psdf) # test on NamedAgg agg_pdf = ( pdf.groupby("group").agg(b_max=pd.NamedAgg(column="B", aggfunc="max")).sort_index() ) agg_psdf = ( psdf.groupby("group").agg(b_max=ps.NamedAgg(column="B", aggfunc="max")).sort_index() ) self.assert_eq(agg_psdf, agg_pdf) # test on NamedAgg multi columns aggregation agg_pdf = ( pdf.groupby("group") .agg( b_max=pd.NamedAgg(column="B", aggfunc="max"), b_min=pd.NamedAgg(column="B", aggfunc="min"), ) .sort_index() ) agg_psdf = ( psdf.groupby("group") .agg( b_max=ps.NamedAgg(column="B", aggfunc="max"), b_min=ps.NamedAgg(column="B", aggfunc="min"), ) .sort_index() ) self.assert_eq(agg_psdf, agg_pdf) def test_dropna(self): pdf = pd.DataFrame( {"A": [None, 1, None, 1, 2], "B": [1, 2, 3, None, None], "C": [4, 5, 6, 7, None]} ) psdf = ps.from_pandas(pdf) # pd.DataFrame.groupby with dropna parameter is implemented since pandas 1.1.0 if LooseVersion(pd.__version__) >= LooseVersion("1.1.0"): for dropna in [True, False]: for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values("A").reset_index(drop=True) self.assert_eq( sort(psdf.groupby("A", as_index=as_index, dropna=dropna).std()), sort(pdf.groupby("A", as_index=as_index, dropna=dropna).std()), ) self.assert_eq( sort(psdf.groupby("A", as_index=as_index, dropna=dropna).B.std()), sort(pdf.groupby("A", as_index=as_index, dropna=dropna).B.std()), ) self.assert_eq( sort(psdf.groupby("A", as_index=as_index, dropna=dropna)["B"].std()), sort(pdf.groupby("A", as_index=as_index, dropna=dropna)["B"].std()), ) self.assert_eq( sort( psdf.groupby("A", as_index=as_index, dropna=dropna).agg( {"B": "min", "C": "std"} ) ), sort( pdf.groupby("A", as_index=as_index, dropna=dropna).agg( {"B": "min", "C": "std"} ) ), ) for dropna in [True, False]: for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values(["A", "B"]).reset_index(drop=True) self.assert_eq( sort( psdf.groupby(["A", "B"], as_index=as_index, dropna=dropna).agg( {"C": ["min", "std"]} ) ), sort( pdf.groupby(["A", "B"], as_index=as_index, dropna=dropna).agg( {"C": ["min", "std"]} ) ), almost=True, ) # multi-index columns columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B"), ("Y", "C")]) pdf.columns = columns psdf.columns = columns for dropna in [True, False]: for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values(("X", "A")).reset_index(drop=True) sorted_stats_psdf = sort( psdf.groupby(("X", "A"), as_index=as_index, dropna=dropna).agg( {("X", "B"): "min", ("Y", "C"): "std"} ) ) sorted_stats_pdf = sort( pdf.groupby(("X", "A"), as_index=as_index, dropna=dropna).agg( {("X", "B"): "min", ("Y", "C"): "std"} ) ) self.assert_eq(sorted_stats_psdf, sorted_stats_pdf) else: # Testing dropna=True (pandas default behavior) for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values("A").reset_index(drop=True) self.assert_eq( sort(psdf.groupby("A", as_index=as_index, dropna=True)["B"].min()), sort(pdf.groupby("A", as_index=as_index)["B"].min()), ) if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values(["A", "B"]).reset_index(drop=True) self.assert_eq( sort( psdf.groupby(["A", "B"], as_index=as_index, dropna=True).agg( {"C": ["min", "std"]} ) ), sort(pdf.groupby(["A", "B"], as_index=as_index).agg({"C": ["min", "std"]})), almost=True, ) # Testing dropna=False index = pd.Index([1.0, 2.0, np.nan], name="A") expected = pd.Series([2.0, np.nan, 1.0], index=index, name="B") result = psdf.groupby("A", as_index=True, dropna=False)["B"].min().sort_index() self.assert_eq(expected, result) expected = pd.DataFrame({"A": [1.0, 2.0, np.nan], "B": [2.0, np.nan, 1.0]}) result = ( psdf.groupby("A", as_index=False, dropna=False)["B"] .min() .sort_values("A") .reset_index(drop=True) ) self.assert_eq(expected, result) index = pd.MultiIndex.from_tuples( [(1.0, 2.0), (1.0, None), (2.0, None), (None, 1.0), (None, 3.0)], names=["A", "B"] ) expected = pd.DataFrame( { ("C", "min"): [5.0, 7.0, np.nan, 4.0, 6.0], ("C", "std"): [np.nan, np.nan, np.nan, np.nan, np.nan], }, index=index, ) result = ( psdf.groupby(["A", "B"], as_index=True, dropna=False) .agg({"C": ["min", "std"]}) .sort_index() ) self.assert_eq(expected, result) expected = pd.DataFrame( { ("A", ""): [1.0, 1.0, 2.0, np.nan, np.nan], ("B", ""): [2.0, np.nan, np.nan, 1.0, 3.0], ("C", "min"): [5.0, 7.0, np.nan, 4.0, 6.0], ("C", "std"): [np.nan, np.nan, np.nan, np.nan, np.nan], } ) result = ( psdf.groupby(["A", "B"], as_index=False, dropna=False) .agg({"C": ["min", "std"]}) .sort_values(["A", "B"]) .reset_index(drop=True) ) self.assert_eq(expected, result) def test_describe(self): # support for numeric type, not support for string type yet datas = [] datas.append({"a": [1, 1, 3], "b": [4, 5, 6], "c": [7, 8, 9]}) datas.append({"a": [-1, -1, -3], "b": [-4, -5, -6], "c": [-7, -8, -9]}) datas.append({"a": [0, 0, 0], "b": [0, 0, 0], "c": [0, 8, 0]}) # it is okay if string type column as a group key datas.append({"a": ["a", "a", "c"], "b": [4, 5, 6], "c": [7, 8, 9]}) percentiles = [0.25, 0.5, 0.75] formatted_percentiles = ["25%", "50%", "75%"] non_percentile_stats = ["count", "mean", "std", "min", "max"] for data in datas: pdf = pd.DataFrame(data) psdf = ps.from_pandas(pdf) describe_pdf = pdf.groupby("a").describe().sort_index() describe_psdf = psdf.groupby("a").describe().sort_index() # since the result of percentile columns are slightly difference from pandas, # we should check them separately: non-percentile columns & percentile columns # 1. Check that non-percentile columns are equal. agg_cols = [col.name for col in psdf.groupby("a")._agg_columns] self.assert_eq( describe_psdf.drop(list(product(agg_cols, formatted_percentiles))), describe_pdf.drop(columns=formatted_percentiles, level=1), check_exact=False, ) # 2. Check that percentile columns are equal. # The interpolation argument is yet to be implemented in Koalas. quantile_pdf = pdf.groupby("a").quantile(percentiles, interpolation="nearest") quantile_pdf = quantile_pdf.unstack(level=1).astype(float) self.assert_eq( describe_psdf.drop(list(product(agg_cols, non_percentile_stats))), quantile_pdf.rename(columns="{:.0%}".format, level=1), ) # not support for string type yet datas = [] datas.append({"a": ["a", "a", "c"], "b": ["d", "e", "f"], "c": ["g", "h", "i"]}) datas.append({"a": ["a", "a", "c"], "b": [4, 0, 1], "c": ["g", "h", "i"]}) for data in datas: pdf = pd.DataFrame(data) psdf = ps.from_pandas(pdf) self.assertRaises( NotImplementedError, lambda: psdf.groupby("a").describe().sort_index() ) # multi-index columns pdf = pd.DataFrame({("x", "a"): [1, 1, 3], ("x", "b"): [4, 5, 6], ("y", "c"): [7, 8, 9]}) psdf = ps.from_pandas(pdf) describe_pdf = pdf.groupby(("x", "a")).describe().sort_index() describe_psdf = psdf.groupby(("x", "a")).describe().sort_index() # 1. Check that non-percentile columns are equal. agg_column_labels = [col._column_label for col in psdf.groupby(("x", "a"))._agg_columns] self.assert_eq( describe_psdf.drop( [ tuple(list(label) + [s]) for label, s in product(agg_column_labels, formatted_percentiles) ] ), describe_pdf.drop(columns=formatted_percentiles, level=2), check_exact=False, ) # 2. Check that percentile columns are equal. # The interpolation argument is yet to be implemented in Koalas. quantile_pdf = pdf.groupby(("x", "a")).quantile(percentiles, interpolation="nearest") quantile_pdf = quantile_pdf.unstack(level=1).astype(float) self.assert_eq( describe_psdf.drop( [ tuple(list(label) + [s]) for label, s in product(agg_column_labels, non_percentile_stats) ] ), quantile_pdf.rename(columns="{:.0%}".format, level=2), ) def test_aggregate_relabel_multiindex(self): pdf = pd.DataFrame({"A": [0, 1, 2, 3], "B": [5, 6, 7, 8], "group": ["a", "a", "b", "b"]}) pdf.columns = pd.MultiIndex.from_tuples([("y", "A"), ("y", "B"), ("x", "group")]) psdf = ps.from_pandas(pdf) if LooseVersion(pd.__version__) < LooseVersion("1.0.0"): agg_pdf = pd.DataFrame( {"a_max": [1, 3]}, index=pd.Index(["a", "b"], name=("x", "group")) ) elif LooseVersion(pd.__version__) >= LooseVersion("1.0.0"): agg_pdf = pdf.groupby(("x", "group")).agg(a_max=(("y", "A"), "max")).sort_index() agg_psdf = psdf.groupby(("x", "group")).agg(a_max=(("y", "A"), "max")).sort_index() self.assert_eq(agg_pdf, agg_psdf) # same column, different methods if LooseVersion(pd.__version__) < LooseVersion("1.0.0"): agg_pdf = pd.DataFrame( {"a_max": [1, 3], "a_min": [0, 2]}, index=pd.Index(["a", "b"], name=("x", "group")) ) elif LooseVersion(pd.__version__) >= LooseVersion("1.0.0"): agg_pdf = ( pdf.groupby(("x", "group")) .agg(a_max=(("y", "A"), "max"), a_min=(("y", "A"), "min")) .sort_index() ) agg_psdf = ( psdf.groupby(("x", "group")) .agg(a_max=(("y", "A"), "max"), a_min=(("y", "A"), "min")) .sort_index() ) self.assert_eq(agg_pdf, agg_psdf) # different column, different methods if LooseVersion(pd.__version__) < LooseVersion("1.0.0"): agg_pdf = pd.DataFrame( {"a_max": [6, 8], "a_min": [0, 2]}, index=pd.Index(["a", "b"], name=("x", "group")) ) elif LooseVersion(pd.__version__) >= LooseVersion("1.0.0"): agg_pdf = ( pdf.groupby(("x", "group")) .agg(a_max=(("y", "B"), "max"), a_min=(("y", "A"), "min")) .sort_index() ) agg_psdf = ( psdf.groupby(("x", "group")) .agg(a_max=(("y", "B"), "max"), a_min=(("y", "A"), "min")) .sort_index() ) self.assert_eq(agg_pdf, agg_psdf) def test_all_any(self): pdf = pd.DataFrame( { "A": [1, 1, 2, 2, 3, 3, 4, 4, 5, 5], "B": [True, True, True, False, False, False, None, True, None, False], } ) psdf = ps.from_pandas(pdf) for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values("A").reset_index(drop=True) self.assert_eq( sort(psdf.groupby("A", as_index=as_index).all()), sort(pdf.groupby("A", as_index=as_index).all()), ) self.assert_eq( sort(psdf.groupby("A", as_index=as_index).any()), sort(pdf.groupby("A", as_index=as_index).any()), ) self.assert_eq( sort(psdf.groupby("A", as_index=as_index).all()).B, sort(pdf.groupby("A", as_index=as_index).all()).B, ) self.assert_eq( sort(psdf.groupby("A", as_index=as_index).any()).B, sort(pdf.groupby("A", as_index=as_index).any()).B, ) self.assert_eq( psdf.B.groupby(psdf.A).all().sort_index(), pdf.B.groupby(pdf.A).all().sort_index() ) self.assert_eq( psdf.B.groupby(psdf.A).any().sort_index(), pdf.B.groupby(pdf.A).any().sort_index() ) # multi-index columns columns = pd.MultiIndex.from_tuples([("X", "A"), ("Y", "B")]) pdf.columns = columns psdf.columns = columns for as_index in [True, False]: if as_index: sort = lambda df: df.sort_index() else: sort = lambda df: df.sort_values(("X", "A")).reset_index(drop=True) self.assert_eq( sort(psdf.groupby(("X", "A"), as_index=as_index).all()), sort(pdf.groupby(("X", "A"), as_index=as_index).all()), ) self.assert_eq( sort(psdf.groupby(("X", "A"), as_index=as_index).any()), sort(pdf.groupby(("X", "A"), as_index=as_index).any()), ) def test_raises(self): psdf = ps.DataFrame( {"a": [1, 2, 6, 4, 4, 6, 4, 3, 7], "b": [4, 2, 7, 3, 3, 1, 1, 1, 2]}, index=[0, 1, 3, 5, 6, 8, 9, 9, 9], ) # test raises with incorrect key self.assertRaises(ValueError, lambda: psdf.groupby([])) self.assertRaises(KeyError, lambda: psdf.groupby("x")) self.assertRaises(KeyError, lambda: psdf.groupby(["a", "x"])) self.assertRaises(KeyError, lambda: psdf.groupby("a")["x"]) self.assertRaises(KeyError, lambda: psdf.groupby("a")["b", "x"]) self.assertRaises(KeyError, lambda: psdf.groupby("a")[["b", "x"]]) def test_nunique(self): pdf = pd.DataFrame( {"a": [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], "b": [2, 2, 2, 3, 3, 4, 4, 5, 5, 5]} ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("a").agg({"b": "nunique"}).sort_index(), pdf.groupby("a").agg({"b": "nunique"}).sort_index(), ) if LooseVersion(pd.__version__) < LooseVersion("1.1.0"): expected = ps.DataFrame({"b": [2, 2]}, index=pd.Index([0, 1], name="a")) self.assert_eq(psdf.groupby("a").nunique().sort_index(), expected) self.assert_eq( psdf.groupby("a").nunique(dropna=False).sort_index(), expected, ) else: self.assert_eq( psdf.groupby("a").nunique().sort_index(), pdf.groupby("a").nunique().sort_index() ) self.assert_eq( psdf.groupby("a").nunique(dropna=False).sort_index(), pdf.groupby("a").nunique(dropna=False).sort_index(), ) self.assert_eq( psdf.groupby("a")["b"].nunique().sort_index(), pdf.groupby("a")["b"].nunique().sort_index(), ) self.assert_eq( psdf.groupby("a")["b"].nunique(dropna=False).sort_index(), pdf.groupby("a")["b"].nunique(dropna=False).sort_index(), ) nunique_psdf = psdf.groupby("a", as_index=False).agg({"b": "nunique"}) nunique_pdf = pdf.groupby("a", as_index=False).agg({"b": "nunique"}) self.assert_eq( nunique_psdf.sort_values(["a", "b"]).reset_index(drop=True), nunique_pdf.sort_values(["a", "b"]).reset_index(drop=True), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("y", "b")]) pdf.columns = columns psdf.columns = columns if LooseVersion(pd.__version__) < LooseVersion("1.1.0"): expected = ps.DataFrame({("y", "b"): [2, 2]}, index=pd.Index([0, 1], name=("x", "a"))) self.assert_eq( psdf.groupby(("x", "a")).nunique().sort_index(), expected, ) self.assert_eq( psdf.groupby(("x", "a")).nunique(dropna=False).sort_index(), expected, ) else: self.assert_eq( psdf.groupby(("x", "a")).nunique().sort_index(), pdf.groupby(("x", "a")).nunique().sort_index(), ) self.assert_eq( psdf.groupby(("x", "a")).nunique(dropna=False).sort_index(), pdf.groupby(("x", "a")).nunique(dropna=False).sort_index(), ) def test_unique(self): for pdf in [ pd.DataFrame( {"a": [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], "b": [2, 2, 2, 3, 3, 4, 4, 5, 5, 5]} ), pd.DataFrame( { "a": [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], "b": ["w", "w", "w", "x", "x", "y", "y", "z", "z", "z"], } ), ]: with self.subTest(pdf=pdf): psdf = ps.from_pandas(pdf) actual = psdf.groupby("a")["b"].unique().sort_index().to_pandas() expect = pdf.groupby("a")["b"].unique().sort_index() self.assert_eq(len(actual), len(expect)) for act, exp in zip(actual, expect): self.assertTrue(sorted(act) == sorted(exp)) def test_value_counts(self): pdf = pd.DataFrame({"A": [1, 2, 2, 3, 3, 3], "B": [1, 1, 2, 3, 3, 3]}, columns=["A", "B"]) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("A")["B"].value_counts().sort_index(), pdf.groupby("A")["B"].value_counts().sort_index(), ) self.assert_eq( psdf.groupby("A")["B"].value_counts(sort=True, ascending=False).sort_index(), pdf.groupby("A")["B"].value_counts(sort=True, ascending=False).sort_index(), ) self.assert_eq( psdf.groupby("A")["B"].value_counts(sort=True, ascending=True).sort_index(), pdf.groupby("A")["B"].value_counts(sort=True, ascending=True).sort_index(), ) self.assert_eq( psdf.B.rename().groupby(psdf.A).value_counts().sort_index(), pdf.B.rename().groupby(pdf.A).value_counts().sort_index(), ) self.assert_eq( psdf.B.groupby(psdf.A.rename()).value_counts().sort_index(), pdf.B.groupby(pdf.A.rename()).value_counts().sort_index(), ) self.assert_eq( psdf.B.rename().groupby(psdf.A.rename()).value_counts().sort_index(), pdf.B.rename().groupby(pdf.A.rename()).value_counts().sort_index(), ) def test_size(self): pdf = pd.DataFrame({"A": [1, 2, 2, 3, 3, 3], "B": [1, 1, 2, 3, 3, 3]}) psdf = ps.from_pandas(pdf) self.assert_eq(psdf.groupby("A").size().sort_index(), pdf.groupby("A").size().sort_index()) self.assert_eq( psdf.groupby("A")["B"].size().sort_index(), pdf.groupby("A")["B"].size().sort_index() ) self.assert_eq( psdf.groupby("A")[["B"]].size().sort_index(), pdf.groupby("A")[["B"]].size().sort_index(), ) self.assert_eq( psdf.groupby(["A", "B"]).size().sort_index(), pdf.groupby(["A", "B"]).size().sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("X", "A"), ("Y", "B")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("X", "A")).size().sort_index(), pdf.groupby(("X", "A")).size().sort_index(), ) self.assert_eq( psdf.groupby([("X", "A"), ("Y", "B")]).size().sort_index(), pdf.groupby([("X", "A"), ("Y", "B")]).size().sort_index(), ) def test_diff(self): pdf = pd.DataFrame( { "a": [1, 2, 3, 4, 5, 6] * 3, "b": [1, 1, 2, 3, 5, 8] * 3, "c": [1, 4, 9, 16, 25, 36] * 3, } ) psdf = ps.from_pandas(pdf) self.assert_eq(psdf.groupby("b").diff().sort_index(), pdf.groupby("b").diff().sort_index()) self.assert_eq( psdf.groupby(["a", "b"]).diff().sort_index(), pdf.groupby(["a", "b"]).diff().sort_index(), ) self.assert_eq( psdf.groupby(["b"])["a"].diff().sort_index(), pdf.groupby(["b"])["a"].diff().sort_index(), ) self.assert_eq( psdf.groupby(["b"])[["a", "b"]].diff().sort_index(), pdf.groupby(["b"])[["a", "b"]].diff().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).diff().sort_index(), pdf.groupby(pdf.b // 5).diff().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].diff().sort_index(), pdf.groupby(pdf.b // 5)["a"].diff().sort_index(), ) self.assert_eq(psdf.groupby("b").diff().sum(), pdf.groupby("b").diff().sum().astype(int)) self.assert_eq(psdf.groupby(["b"])["a"].diff().sum(), pdf.groupby(["b"])["a"].diff().sum()) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).diff().sort_index(), pdf.groupby(("x", "b")).diff().sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).diff().sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).diff().sort_index(), ) def test_rank(self): pdf = pd.DataFrame( { "a": [1, 2, 3, 4, 5, 6] * 3, "b": [1, 1, 2, 3, 5, 8] * 3, "c": [1, 4, 9, 16, 25, 36] * 3, }, index=np.random.rand(6 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq(psdf.groupby("b").rank().sort_index(), pdf.groupby("b").rank().sort_index()) self.assert_eq( psdf.groupby(["a", "b"]).rank().sort_index(), pdf.groupby(["a", "b"]).rank().sort_index(), ) self.assert_eq( psdf.groupby(["b"])["a"].rank().sort_index(), pdf.groupby(["b"])["a"].rank().sort_index(), ) self.assert_eq( psdf.groupby(["b"])[["a", "c"]].rank().sort_index(), pdf.groupby(["b"])[["a", "c"]].rank().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).rank().sort_index(), pdf.groupby(pdf.b // 5).rank().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].rank().sort_index(), pdf.groupby(pdf.b // 5)["a"].rank().sort_index(), ) self.assert_eq(psdf.groupby("b").rank().sum(), pdf.groupby("b").rank().sum()) self.assert_eq(psdf.groupby(["b"])["a"].rank().sum(), pdf.groupby(["b"])["a"].rank().sum()) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).rank().sort_index(), pdf.groupby(("x", "b")).rank().sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).rank().sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).rank().sort_index(), ) def test_cumcount(self): pdf = pd.DataFrame( { "a": [1, 2, 3, 4, 5, 6] * 3, "b": [1, 1, 2, 3, 5, 8] * 3, "c": [1, 4, 9, 16, 25, 36] * 3, }, index=np.random.rand(6 * 3), ) psdf = ps.from_pandas(pdf) for ascending in [True, False]: self.assert_eq( psdf.groupby("b").cumcount(ascending=ascending).sort_index(), pdf.groupby("b").cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.groupby(["a", "b"]).cumcount(ascending=ascending).sort_index(), pdf.groupby(["a", "b"]).cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.groupby(["b"])["a"].cumcount(ascending=ascending).sort_index(), pdf.groupby(["b"])["a"].cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.groupby(["b"])[["a", "c"]].cumcount(ascending=ascending).sort_index(), pdf.groupby(["b"])[["a", "c"]].cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).cumcount(ascending=ascending).sort_index(), pdf.groupby(pdf.b // 5).cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].cumcount(ascending=ascending).sort_index(), pdf.groupby(pdf.b // 5)["a"].cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.groupby("b").cumcount(ascending=ascending).sum(), pdf.groupby("b").cumcount(ascending=ascending).sum(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b).cumcount(ascending=ascending).sort_index(), pdf.a.rename().groupby(pdf.b).cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).cumcount(ascending=ascending).sort_index(), pdf.a.groupby(pdf.b.rename()).cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).cumcount(ascending=ascending).sort_index(), pdf.a.rename().groupby(pdf.b.rename()).cumcount(ascending=ascending).sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns for ascending in [True, False]: self.assert_eq( psdf.groupby(("x", "b")).cumcount(ascending=ascending).sort_index(), pdf.groupby(("x", "b")).cumcount(ascending=ascending).sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).cumcount(ascending=ascending).sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).cumcount(ascending=ascending).sort_index(), ) def test_cummin(self): pdf = pd.DataFrame( { "a": [1, 2, 3, 4, 5, 6] * 3, "b": [1, 1, 2, 3, 5, 8] * 3, "c": [1, 4, 9, 16, 25, 36] * 3, }, index=np.random.rand(6 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("b").cummin().sort_index(), pdf.groupby("b").cummin().sort_index() ) self.assert_eq( psdf.groupby(["a", "b"]).cummin().sort_index(), pdf.groupby(["a", "b"]).cummin().sort_index(), ) self.assert_eq( psdf.groupby(["b"])["a"].cummin().sort_index(), pdf.groupby(["b"])["a"].cummin().sort_index(), ) self.assert_eq( psdf.groupby(["b"])[["a", "c"]].cummin().sort_index(), pdf.groupby(["b"])[["a", "c"]].cummin().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).cummin().sort_index(), pdf.groupby(pdf.b // 5).cummin().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].cummin().sort_index(), pdf.groupby(pdf.b // 5)["a"].cummin().sort_index(), ) self.assert_eq( psdf.groupby("b").cummin().sum().sort_index(), pdf.groupby("b").cummin().sum().sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b).cummin().sort_index(), pdf.a.rename().groupby(pdf.b).cummin().sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).cummin().sort_index(), pdf.a.groupby(pdf.b.rename()).cummin().sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).cummin().sort_index(), pdf.a.rename().groupby(pdf.b.rename()).cummin().sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).cummin().sort_index(), pdf.groupby(("x", "b")).cummin().sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).cummin().sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).cummin().sort_index(), ) psdf = ps.DataFrame([["a"], ["b"], ["c"]], columns=["A"]) self.assertRaises(DataError, lambda: psdf.groupby(["A"]).cummin()) psdf = ps.DataFrame([[1, "a"], [2, "b"], [3, "c"]], columns=["A", "B"]) self.assertRaises(DataError, lambda: psdf.groupby(["A"])["B"].cummin()) def test_cummax(self): pdf = pd.DataFrame( { "a": [1, 2, 3, 4, 5, 6] * 3, "b": [1, 1, 2, 3, 5, 8] * 3, "c": [1, 4, 9, 16, 25, 36] * 3, }, index=np.random.rand(6 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("b").cummax().sort_index(), pdf.groupby("b").cummax().sort_index() ) self.assert_eq( psdf.groupby(["a", "b"]).cummax().sort_index(), pdf.groupby(["a", "b"]).cummax().sort_index(), ) self.assert_eq( psdf.groupby(["b"])["a"].cummax().sort_index(), pdf.groupby(["b"])["a"].cummax().sort_index(), ) self.assert_eq( psdf.groupby(["b"])[["a", "c"]].cummax().sort_index(), pdf.groupby(["b"])[["a", "c"]].cummax().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).cummax().sort_index(), pdf.groupby(pdf.b // 5).cummax().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].cummax().sort_index(), pdf.groupby(pdf.b // 5)["a"].cummax().sort_index(), ) self.assert_eq( psdf.groupby("b").cummax().sum().sort_index(), pdf.groupby("b").cummax().sum().sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b).cummax().sort_index(), pdf.a.rename().groupby(pdf.b).cummax().sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).cummax().sort_index(), pdf.a.groupby(pdf.b.rename()).cummax().sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).cummax().sort_index(), pdf.a.rename().groupby(pdf.b.rename()).cummax().sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).cummax().sort_index(), pdf.groupby(("x", "b")).cummax().sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).cummax().sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).cummax().sort_index(), ) psdf = ps.DataFrame([["a"], ["b"], ["c"]], columns=["A"]) self.assertRaises(DataError, lambda: psdf.groupby(["A"]).cummax()) psdf = ps.DataFrame([[1, "a"], [2, "b"], [3, "c"]], columns=["A", "B"]) self.assertRaises(DataError, lambda: psdf.groupby(["A"])["B"].cummax()) def test_cumsum(self): pdf = pd.DataFrame( { "a": [1, 2, 3, 4, 5, 6] * 3, "b": [1, 1, 2, 3, 5, 8] * 3, "c": [1, 4, 9, 16, 25, 36] * 3, }, index=np.random.rand(6 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("b").cumsum().sort_index(), pdf.groupby("b").cumsum().sort_index() ) self.assert_eq( psdf.groupby(["a", "b"]).cumsum().sort_index(), pdf.groupby(["a", "b"]).cumsum().sort_index(), ) self.assert_eq( psdf.groupby(["b"])["a"].cumsum().sort_index(), pdf.groupby(["b"])["a"].cumsum().sort_index(), ) self.assert_eq( psdf.groupby(["b"])[["a", "c"]].cumsum().sort_index(), pdf.groupby(["b"])[["a", "c"]].cumsum().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).cumsum().sort_index(), pdf.groupby(pdf.b // 5).cumsum().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].cumsum().sort_index(), pdf.groupby(pdf.b // 5)["a"].cumsum().sort_index(), ) self.assert_eq( psdf.groupby("b").cumsum().sum().sort_index(), pdf.groupby("b").cumsum().sum().sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b).cumsum().sort_index(), pdf.a.rename().groupby(pdf.b).cumsum().sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).cumsum().sort_index(), pdf.a.groupby(pdf.b.rename()).cumsum().sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).cumsum().sort_index(), pdf.a.rename().groupby(pdf.b.rename()).cumsum().sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).cumsum().sort_index(), pdf.groupby(("x", "b")).cumsum().sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).cumsum().sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).cumsum().sort_index(), ) psdf = ps.DataFrame([["a"], ["b"], ["c"]], columns=["A"]) self.assertRaises(DataError, lambda: psdf.groupby(["A"]).cumsum()) psdf = ps.DataFrame([[1, "a"], [2, "b"], [3, "c"]], columns=["A", "B"]) self.assertRaises(DataError, lambda: psdf.groupby(["A"])["B"].cumsum()) def test_cumprod(self): pdf = pd.DataFrame( { "a": [1, 2, -3, 4, -5, 6] * 3, "b": [1, 1, 2, 3, 5, 8] * 3, "c": [1, 0, 9, 16, 25, 36] * 3, }, index=np.random.rand(6 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("b").cumprod().sort_index(), pdf.groupby("b").cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.groupby(["a", "b"]).cumprod().sort_index(), pdf.groupby(["a", "b"]).cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.groupby(["b"])["a"].cumprod().sort_index(), pdf.groupby(["b"])["a"].cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.groupby(["b"])[["a", "c"]].cumprod().sort_index(), pdf.groupby(["b"])[["a", "c"]].cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.groupby(psdf.b // 3).cumprod().sort_index(), pdf.groupby(pdf.b // 3).cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.groupby(psdf.b // 3)["a"].cumprod().sort_index(), pdf.groupby(pdf.b // 3)["a"].cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.groupby("b").cumprod().sum().sort_index(), pdf.groupby("b").cumprod().sum().sort_index(), check_exact=False, ) self.assert_eq( psdf.a.rename().groupby(psdf.b).cumprod().sort_index(), pdf.a.rename().groupby(pdf.b).cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).cumprod().sort_index(), pdf.a.groupby(pdf.b.rename()).cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).cumprod().sort_index(), pdf.a.rename().groupby(pdf.b.rename()).cumprod().sort_index(), check_exact=False, ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).cumprod().sort_index(), pdf.groupby(("x", "b")).cumprod().sort_index(), check_exact=False, ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).cumprod().sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).cumprod().sort_index(), check_exact=False, ) psdf = ps.DataFrame([["a"], ["b"], ["c"]], columns=["A"]) self.assertRaises(DataError, lambda: psdf.groupby(["A"]).cumprod()) psdf = ps.DataFrame([[1, "a"], [2, "b"], [3, "c"]], columns=["A", "B"]) self.assertRaises(DataError, lambda: psdf.groupby(["A"])["B"].cumprod()) def test_nsmallest(self): pdf = pd.DataFrame( { "a": [1, 1, 1, 2, 2, 2, 3, 3, 3] * 3, "b": [1, 2, 2, 2, 3, 3, 3, 4, 4] * 3, "c": [1, 2, 2, 2, 3, 3, 3, 4, 4] * 3, "d": [1, 2, 2, 2, 3, 3, 3, 4, 4] * 3, }, index=np.random.rand(9 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby(["a"])["b"].nsmallest(1).sort_values(), pdf.groupby(["a"])["b"].nsmallest(1).sort_values(), ) self.assert_eq( psdf.groupby(["a"])["b"].nsmallest(2).sort_index(), pdf.groupby(["a"])["b"].nsmallest(2).sort_index(), ) self.assert_eq( (psdf.b * 10).groupby(psdf.a).nsmallest(2).sort_index(), (pdf.b * 10).groupby(pdf.a).nsmallest(2).sort_index(), ) self.assert_eq( psdf.b.rename().groupby(psdf.a).nsmallest(2).sort_index(), pdf.b.rename().groupby(pdf.a).nsmallest(2).sort_index(), ) self.assert_eq( psdf.b.groupby(psdf.a.rename()).nsmallest(2).sort_index(), pdf.b.groupby(pdf.a.rename()).nsmallest(2).sort_index(), ) self.assert_eq( psdf.b.rename().groupby(psdf.a.rename()).nsmallest(2).sort_index(), pdf.b.rename().groupby(pdf.a.rename()).nsmallest(2).sort_index(), ) with self.assertRaisesRegex(ValueError, "nsmallest do not support multi-index now"): psdf.set_index(["a", "b"]).groupby(["c"])["d"].nsmallest(1) def test_nlargest(self): pdf = pd.DataFrame( { "a": [1, 1, 1, 2, 2, 2, 3, 3, 3] * 3, "b": [1, 2, 2, 2, 3, 3, 3, 4, 4] * 3, "c": [1, 2, 2, 2, 3, 3, 3, 4, 4] * 3, "d": [1, 2, 2, 2, 3, 3, 3, 4, 4] * 3, }, index=np.random.rand(9 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby(["a"])["b"].nlargest(1).sort_values(), pdf.groupby(["a"])["b"].nlargest(1).sort_values(), ) self.assert_eq( psdf.groupby(["a"])["b"].nlargest(2).sort_index(), pdf.groupby(["a"])["b"].nlargest(2).sort_index(), ) self.assert_eq( (psdf.b * 10).groupby(psdf.a).nlargest(2).sort_index(), (pdf.b * 10).groupby(pdf.a).nlargest(2).sort_index(), ) self.assert_eq( psdf.b.rename().groupby(psdf.a).nlargest(2).sort_index(), pdf.b.rename().groupby(pdf.a).nlargest(2).sort_index(), ) self.assert_eq( psdf.b.groupby(psdf.a.rename()).nlargest(2).sort_index(), pdf.b.groupby(pdf.a.rename()).nlargest(2).sort_index(), ) self.assert_eq( psdf.b.rename().groupby(psdf.a.rename()).nlargest(2).sort_index(), pdf.b.rename().groupby(pdf.a.rename()).nlargest(2).sort_index(), ) with self.assertRaisesRegex(ValueError, "nlargest do not support multi-index now"): psdf.set_index(["a", "b"]).groupby(["c"])["d"].nlargest(1) def test_fillna(self): pdf = pd.DataFrame( { "A": [1, 1, 2, 2] * 3, "B": [2, 4, None, 3] * 3, "C": [None, None, None, 1] * 3, "D": [0, 1, 5, 4] * 3, } ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("A").fillna(0).sort_index(), pdf.groupby("A").fillna(0).sort_index() ) self.assert_eq( psdf.groupby("A")["C"].fillna(0).sort_index(), pdf.groupby("A")["C"].fillna(0).sort_index(), ) self.assert_eq( psdf.groupby("A")[["C"]].fillna(0).sort_index(), pdf.groupby("A")[["C"]].fillna(0).sort_index(), ) self.assert_eq( psdf.groupby("A").fillna(method="bfill").sort_index(), pdf.groupby("A").fillna(method="bfill").sort_index(), ) self.assert_eq( psdf.groupby("A")["C"].fillna(method="bfill").sort_index(), pdf.groupby("A")["C"].fillna(method="bfill").sort_index(), ) self.assert_eq( psdf.groupby("A")[["C"]].fillna(method="bfill").sort_index(), pdf.groupby("A")[["C"]].fillna(method="bfill").sort_index(), ) self.assert_eq( psdf.groupby("A").fillna(method="ffill").sort_index(), pdf.groupby("A").fillna(method="ffill").sort_index(), ) self.assert_eq( psdf.groupby("A")["C"].fillna(method="ffill").sort_index(), pdf.groupby("A")["C"].fillna(method="ffill").sort_index(), ) self.assert_eq( psdf.groupby("A")[["C"]].fillna(method="ffill").sort_index(), pdf.groupby("A")[["C"]].fillna(method="ffill").sort_index(), ) self.assert_eq( psdf.groupby(psdf.A // 5).fillna(method="bfill").sort_index(), pdf.groupby(pdf.A // 5).fillna(method="bfill").sort_index(), ) self.assert_eq( psdf.groupby(psdf.A // 5)["C"].fillna(method="bfill").sort_index(), pdf.groupby(pdf.A // 5)["C"].fillna(method="bfill").sort_index(), ) self.assert_eq( psdf.groupby(psdf.A // 5)[["C"]].fillna(method="bfill").sort_index(), pdf.groupby(pdf.A // 5)[["C"]].fillna(method="bfill").sort_index(), ) self.assert_eq( psdf.groupby(psdf.A // 5).fillna(method="ffill").sort_index(), pdf.groupby(pdf.A // 5).fillna(method="ffill").sort_index(), ) self.assert_eq( psdf.groupby(psdf.A // 5)["C"].fillna(method="ffill").sort_index(), pdf.groupby(pdf.A // 5)["C"].fillna(method="ffill").sort_index(), ) self.assert_eq( psdf.groupby(psdf.A // 5)[["C"]].fillna(method="ffill").sort_index(), pdf.groupby(pdf.A // 5)[["C"]].fillna(method="ffill").sort_index(), ) self.assert_eq( psdf.C.rename().groupby(psdf.A).fillna(0).sort_index(), pdf.C.rename().groupby(pdf.A).fillna(0).sort_index(), ) self.assert_eq( psdf.C.groupby(psdf.A.rename()).fillna(0).sort_index(), pdf.C.groupby(pdf.A.rename()).fillna(0).sort_index(), ) self.assert_eq( psdf.C.rename().groupby(psdf.A.rename()).fillna(0).sort_index(), pdf.C.rename().groupby(pdf.A.rename()).fillna(0).sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B"), ("Y", "C"), ("Z", "D")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("X", "A")).fillna(0).sort_index(), pdf.groupby(("X", "A")).fillna(0).sort_index(), ) self.assert_eq( psdf.groupby(("X", "A")).fillna(method="bfill").sort_index(), pdf.groupby(("X", "A")).fillna(method="bfill").sort_index(), ) self.assert_eq( psdf.groupby(("X", "A")).fillna(method="ffill").sort_index(), pdf.groupby(("X", "A")).fillna(method="ffill").sort_index(), ) def test_ffill(self): idx = np.random.rand(4 * 3) pdf = pd.DataFrame( { "A": [1, 1, 2, 2] * 3, "B": [2, 4, None, 3] * 3, "C": [None, None, None, 1] * 3, "D": [0, 1, 5, 4] * 3, }, index=idx, ) psdf = ps.from_pandas(pdf) if LooseVersion(pd.__version__) <= LooseVersion("0.24.2"): self.assert_eq( psdf.groupby("A").ffill().sort_index(), pdf.groupby("A").ffill().sort_index().drop("A", 1), ) self.assert_eq( psdf.groupby("A")[["B"]].ffill().sort_index(), pdf.groupby("A")[["B"]].ffill().sort_index().drop("A", 1), ) else: self.assert_eq( psdf.groupby("A").ffill().sort_index(), pdf.groupby("A").ffill().sort_index() ) self.assert_eq( psdf.groupby("A")[["B"]].ffill().sort_index(), pdf.groupby("A")[["B"]].ffill().sort_index(), ) self.assert_eq( psdf.groupby("A")["B"].ffill().sort_index(), pdf.groupby("A")["B"].ffill().sort_index() ) self.assert_eq( psdf.groupby("A")["B"].ffill()[idx[6]], pdf.groupby("A")["B"].ffill()[idx[6]] ) # multi-index columns columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B"), ("Y", "C"), ("Z", "D")]) pdf.columns = columns psdf.columns = columns if LooseVersion(pd.__version__) <= LooseVersion("0.24.2"): self.assert_eq( psdf.groupby(("X", "A")).ffill().sort_index(), pdf.groupby(("X", "A")).ffill().sort_index().drop(("X", "A"), 1), ) else: self.assert_eq( psdf.groupby(("X", "A")).ffill().sort_index(), pdf.groupby(("X", "A")).ffill().sort_index(), ) def test_bfill(self): idx = np.random.rand(4 * 3) pdf = pd.DataFrame( { "A": [1, 1, 2, 2] * 3, "B": [2, 4, None, 3] * 3, "C": [None, None, None, 1] * 3, "D": [0, 1, 5, 4] * 3, }, index=idx, ) psdf = ps.from_pandas(pdf) if LooseVersion(pd.__version__) <= LooseVersion("0.24.2"): self.assert_eq( psdf.groupby("A").bfill().sort_index(), pdf.groupby("A").bfill().sort_index().drop("A", 1), ) self.assert_eq( psdf.groupby("A")[["B"]].bfill().sort_index(), pdf.groupby("A")[["B"]].bfill().sort_index().drop("A", 1), ) else: self.assert_eq( psdf.groupby("A").bfill().sort_index(), pdf.groupby("A").bfill().sort_index() ) self.assert_eq( psdf.groupby("A")[["B"]].bfill().sort_index(), pdf.groupby("A")[["B"]].bfill().sort_index(), ) self.assert_eq( psdf.groupby("A")["B"].bfill().sort_index(), pdf.groupby("A")["B"].bfill().sort_index(), ) self.assert_eq( psdf.groupby("A")["B"].bfill()[idx[6]], pdf.groupby("A")["B"].bfill()[idx[6]] ) # multi-index columns columns = pd.MultiIndex.from_tuples([("X", "A"), ("X", "B"), ("Y", "C"), ("Z", "D")]) pdf.columns = columns psdf.columns = columns if LooseVersion(pd.__version__) <= LooseVersion("0.24.2"): self.assert_eq( psdf.groupby(("X", "A")).bfill().sort_index(), pdf.groupby(("X", "A")).bfill().sort_index().drop(("X", "A"), 1), ) else: self.assert_eq( psdf.groupby(("X", "A")).bfill().sort_index(), pdf.groupby(("X", "A")).bfill().sort_index(), ) @unittest.skipIf(pd.__version__ < "0.24.0", "not supported before pandas 0.24.0") def test_shift(self): pdf = pd.DataFrame( { "a": [1, 1, 2, 2, 3, 3] * 3, "b": [1, 1, 2, 2, 3, 4] * 3, "c": [1, 4, 9, 16, 25, 36] * 3, }, index=np.random.rand(6 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("a").shift().sort_index(), pdf.groupby("a").shift().sort_index() ) # TODO: seems like a pandas' bug when fill_value is not None? # self.assert_eq(psdf.groupby(['a', 'b']).shift(periods=-1, fill_value=0).sort_index(), # pdf.groupby(['a', 'b']).shift(periods=-1, fill_value=0).sort_index()) self.assert_eq( psdf.groupby(["b"])["a"].shift().sort_index(), pdf.groupby(["b"])["a"].shift().sort_index(), ) self.assert_eq( psdf.groupby(["a", "b"])["c"].shift().sort_index(), pdf.groupby(["a", "b"])["c"].shift().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).shift().sort_index(), pdf.groupby(pdf.b // 5).shift().sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].shift().sort_index(), pdf.groupby(pdf.b // 5)["a"].shift().sort_index(), ) # TODO: known pandas' bug when fill_value is not None pandas>=1.0.0 # https://github.com/pandas-dev/pandas/issues/31971#issue-565171762 if LooseVersion(pd.__version__) < LooseVersion("1.0.0"): self.assert_eq( psdf.groupby(["b"])[["a", "c"]].shift(periods=-1, fill_value=0).sort_index(), pdf.groupby(["b"])[["a", "c"]].shift(periods=-1, fill_value=0).sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b).shift().sort_index(), pdf.a.rename().groupby(pdf.b).shift().sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).shift().sort_index(), pdf.a.groupby(pdf.b.rename()).shift().sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).shift().sort_index(), pdf.a.rename().groupby(pdf.b.rename()).shift().sort_index(), ) self.assert_eq(psdf.groupby("a").shift().sum(), pdf.groupby("a").shift().sum().astype(int)) self.assert_eq( psdf.a.rename().groupby(psdf.b).shift().sum(), pdf.a.rename().groupby(pdf.b).shift().sum(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "a")).shift().sort_index(), pdf.groupby(("x", "a")).shift().sort_index(), ) # TODO: seems like a pandas' bug when fill_value is not None? # self.assert_eq(psdf.groupby([('x', 'a'), ('x', 'b')]).shift(periods=-1, # fill_value=0).sort_index(), # pdf.groupby([('x', 'a'), ('x', 'b')]).shift(periods=-1, # fill_value=0).sort_index()) def test_apply(self): pdf = pd.DataFrame( {"a": [1, 2, 3, 4, 5, 6], "b": [1, 1, 2, 3, 5, 8], "c": [1, 4, 9, 16, 25, 36]}, columns=["a", "b", "c"], ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("b").apply(lambda x: x + x.min()).sort_index(), pdf.groupby("b").apply(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby("b").apply(len).sort_index(), pdf.groupby("b").apply(len).sort_index(), ) self.assert_eq( psdf.groupby("b")["a"] .apply(lambda x, y, z: x + x.min() + y * z, 10, z=20) .sort_index(), pdf.groupby("b")["a"].apply(lambda x, y, z: x + x.min() + y * z, 10, z=20).sort_index(), ) self.assert_eq( psdf.groupby("b")[["a"]].apply(lambda x: x + x.min()).sort_index(), pdf.groupby("b")[["a"]].apply(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(["a", "b"]) .apply(lambda x, y, z: x + x.min() + y + z, 1, z=2) .sort_index(), pdf.groupby(["a", "b"]).apply(lambda x, y, z: x + x.min() + y + z, 1, z=2).sort_index(), ) self.assert_eq( psdf.groupby(["b"])["c"].apply(lambda x: 1).sort_index(), pdf.groupby(["b"])["c"].apply(lambda x: 1).sort_index(), ) self.assert_eq( psdf.groupby(["b"])["c"].apply(len).sort_index(), pdf.groupby(["b"])["c"].apply(len).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).apply(lambda x: x + x.min()).sort_index(), pdf.groupby(pdf.b // 5).apply(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].apply(lambda x: x + x.min()).sort_index(), pdf.groupby(pdf.b // 5)["a"].apply(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)[["a"]].apply(lambda x: x + x.min()).sort_index(), pdf.groupby(pdf.b // 5)[["a"]].apply(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)[["a"]].apply(len).sort_index(), pdf.groupby(pdf.b // 5)[["a"]].apply(len).sort_index(), almost=True, ) self.assert_eq( psdf.a.rename().groupby(psdf.b).apply(lambda x: x + x.min()).sort_index(), pdf.a.rename().groupby(pdf.b).apply(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).apply(lambda x: x + x.min()).sort_index(), pdf.a.groupby(pdf.b.rename()).apply(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).apply(lambda x: x + x.min()).sort_index(), pdf.a.rename().groupby(pdf.b.rename()).apply(lambda x: x + x.min()).sort_index(), ) with self.assertRaisesRegex(TypeError, "int object is not callable"): psdf.groupby("b").apply(1) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).apply(lambda x: 1).sort_index(), pdf.groupby(("x", "b")).apply(lambda x: 1).sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).apply(lambda x: x + x.min()).sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).apply(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(("x", "b")).apply(len).sort_index(), pdf.groupby(("x", "b")).apply(len).sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).apply(len).sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).apply(len).sort_index(), ) def test_apply_without_shortcut(self): with option_context("compute.shortcut_limit", 0): self.test_apply() def test_apply_negative(self): def func(_) -> ps.Series[int]: return pd.Series([1]) with self.assertRaisesRegex(TypeError, "Series as a return type hint at frame groupby"): ps.range(10).groupby("id").apply(func) def test_apply_with_new_dataframe(self): pdf = pd.DataFrame( {"timestamp": [0.0, 0.5, 1.0, 0.0, 0.5], "car_id": ["A", "A", "A", "B", "B"]} ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("car_id").apply(lambda _: pd.DataFrame({"column": [0.0]})).sort_index(), pdf.groupby("car_id").apply(lambda _: pd.DataFrame({"column": [0.0]})).sort_index(), ) self.assert_eq( psdf.groupby("car_id") .apply(lambda df: pd.DataFrame({"mean": [df["timestamp"].mean()]})) .sort_index(), pdf.groupby("car_id") .apply(lambda df: pd.DataFrame({"mean": [df["timestamp"].mean()]})) .sort_index(), ) # dataframe with 1000+ records pdf = pd.DataFrame( { "timestamp": [0.0, 0.5, 1.0, 0.0, 0.5] * 300, "car_id": ["A", "A", "A", "B", "B"] * 300, } ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("car_id").apply(lambda _: pd.DataFrame({"column": [0.0]})).sort_index(), pdf.groupby("car_id").apply(lambda _: pd.DataFrame({"column": [0.0]})).sort_index(), ) self.assert_eq( psdf.groupby("car_id") .apply(lambda df: pd.DataFrame({"mean": [df["timestamp"].mean()]})) .sort_index(), pdf.groupby("car_id") .apply(lambda df: pd.DataFrame({"mean": [df["timestamp"].mean()]})) .sort_index(), ) def test_apply_with_new_dataframe_without_shortcut(self): with option_context("compute.shortcut_limit", 0): self.test_apply_with_new_dataframe() def test_apply_key_handling(self): pdf = pd.DataFrame( {"d": [1.0, 1.0, 1.0, 2.0, 2.0, 2.0], "v": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]} ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("d").apply(sum).sort_index(), pdf.groupby("d").apply(sum).sort_index() ) with ps.option_context("compute.shortcut_limit", 1): self.assert_eq( psdf.groupby("d").apply(sum).sort_index(), pdf.groupby("d").apply(sum).sort_index() ) def test_apply_with_side_effect(self): pdf = pd.DataFrame( {"d": [1.0, 1.0, 1.0, 2.0, 2.0, 2.0], "v": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]} ) psdf = ps.from_pandas(pdf) acc = ps.utils.default_session().sparkContext.accumulator(0) def sum_with_acc_frame(x) -> ps.DataFrame[np.float64, np.float64]: nonlocal acc acc += 1 return np.sum(x) actual = psdf.groupby("d").apply(sum_with_acc_frame).sort_index() actual.columns = ["d", "v"] self.assert_eq(actual, pdf.groupby("d").apply(sum).sort_index().reset_index(drop=True)) self.assert_eq(acc.value, 2) def sum_with_acc_series(x) -> np.float64: nonlocal acc acc += 1 return np.sum(x) self.assert_eq( psdf.groupby("d")["v"].apply(sum_with_acc_series).sort_index(), pdf.groupby("d")["v"].apply(sum).sort_index().reset_index(drop=True), ) self.assert_eq(acc.value, 4) def test_transform(self): pdf = pd.DataFrame( {"a": [1, 2, 3, 4, 5, 6], "b": [1, 1, 2, 3, 5, 8], "c": [1, 4, 9, 16, 25, 36]}, columns=["a", "b", "c"], ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("b").transform(lambda x: x + x.min()).sort_index(), pdf.groupby("b").transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby("b")["a"].transform(lambda x: x + x.min()).sort_index(), pdf.groupby("b")["a"].transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby("b")[["a"]].transform(lambda x: x + x.min()).sort_index(), pdf.groupby("b")[["a"]].transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(["a", "b"]).transform(lambda x: x + x.min()).sort_index(), pdf.groupby(["a", "b"]).transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(["b"])["c"].transform(lambda x: x + x.min()).sort_index(), pdf.groupby(["b"])["c"].transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5).transform(lambda x: x + x.min()).sort_index(), pdf.groupby(pdf.b // 5).transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)["a"].transform(lambda x: x + x.min()).sort_index(), pdf.groupby(pdf.b // 5)["a"].transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby(psdf.b // 5)[["a"]].transform(lambda x: x + x.min()).sort_index(), pdf.groupby(pdf.b // 5)[["a"]].transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b).transform(lambda x: x + x.min()).sort_index(), pdf.a.rename().groupby(pdf.b).transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).transform(lambda x: x + x.min()).sort_index(), pdf.a.groupby(pdf.b.rename()).transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).transform(lambda x: x + x.min()).sort_index(), pdf.a.rename().groupby(pdf.b.rename()).transform(lambda x: x + x.min()).sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).transform(lambda x: x + x.min()).sort_index(), pdf.groupby(("x", "b")).transform(lambda x: x + x.min()).sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]).transform(lambda x: x + x.min()).sort_index(), pdf.groupby([("x", "a"), ("x", "b")]).transform(lambda x: x + x.min()).sort_index(), ) def test_transform_without_shortcut(self): with option_context("compute.shortcut_limit", 0): self.test_transform() def test_filter(self): pdf = pd.DataFrame( {"a": [1, 2, 3, 4, 5, 6], "b": [1, 1, 2, 3, 5, 8], "c": [1, 4, 9, 16, 25, 36]}, columns=["a", "b", "c"], ) psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("b").filter(lambda x: any(x.a == 2)).sort_index(), pdf.groupby("b").filter(lambda x: any(x.a == 2)).sort_index(), ) self.assert_eq( psdf.groupby("b")["a"].filter(lambda x: any(x == 2)).sort_index(), pdf.groupby("b")["a"].filter(lambda x: any(x == 2)).sort_index(), ) self.assert_eq( psdf.groupby("b")[["a"]].filter(lambda x: any(x.a == 2)).sort_index(), pdf.groupby("b")[["a"]].filter(lambda x: any(x.a == 2)).sort_index(), ) self.assert_eq( psdf.groupby(["a", "b"]).filter(lambda x: any(x.a == 2)).sort_index(), pdf.groupby(["a", "b"]).filter(lambda x: any(x.a == 2)).sort_index(), ) self.assert_eq( psdf.groupby(psdf["b"] // 5).filter(lambda x: any(x.a == 2)).sort_index(), pdf.groupby(pdf["b"] // 5).filter(lambda x: any(x.a == 2)).sort_index(), ) self.assert_eq( psdf.groupby(psdf["b"] // 5)["a"].filter(lambda x: any(x == 2)).sort_index(), pdf.groupby(pdf["b"] // 5)["a"].filter(lambda x: any(x == 2)).sort_index(), ) self.assert_eq( psdf.groupby(psdf["b"] // 5)[["a"]].filter(lambda x: any(x.a == 2)).sort_index(), pdf.groupby(pdf["b"] // 5)[["a"]].filter(lambda x: any(x.a == 2)).sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b).filter(lambda x: any(x == 2)).sort_index(), pdf.a.rename().groupby(pdf.b).filter(lambda x: any(x == 2)).sort_index(), ) self.assert_eq( psdf.a.groupby(psdf.b.rename()).filter(lambda x: any(x == 2)).sort_index(), pdf.a.groupby(pdf.b.rename()).filter(lambda x: any(x == 2)).sort_index(), ) self.assert_eq( psdf.a.rename().groupby(psdf.b.rename()).filter(lambda x: any(x == 2)).sort_index(), pdf.a.rename().groupby(pdf.b.rename()).filter(lambda x: any(x == 2)).sort_index(), ) with self.assertRaisesRegex(TypeError, "int object is not callable"): psdf.groupby("b").filter(1) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( psdf.groupby(("x", "b")).filter(lambda x: any(x[("x", "a")] == 2)).sort_index(), pdf.groupby(("x", "b")).filter(lambda x: any(x[("x", "a")] == 2)).sort_index(), ) self.assert_eq( psdf.groupby([("x", "a"), ("x", "b")]) .filter(lambda x: any(x[("x", "a")] == 2)) .sort_index(), pdf.groupby([("x", "a"), ("x", "b")]) .filter(lambda x: any(x[("x", "a")] == 2)) .sort_index(), ) def test_idxmax(self): pdf = pd.DataFrame( {"a": [1, 1, 2, 2, 3] * 3, "b": [1, 2, 3, 4, 5] * 3, "c": [5, 4, 3, 2, 1] * 3} ) psdf = ps.from_pandas(pdf) self.assert_eq( pdf.groupby(["a"]).idxmax().sort_index(), psdf.groupby(["a"]).idxmax().sort_index() ) self.assert_eq( pdf.groupby(["a"]).idxmax(skipna=False).sort_index(), psdf.groupby(["a"]).idxmax(skipna=False).sort_index(), ) self.assert_eq( pdf.groupby(["a"])["b"].idxmax().sort_index(), psdf.groupby(["a"])["b"].idxmax().sort_index(), ) self.assert_eq( pdf.b.rename().groupby(pdf.a).idxmax().sort_index(), psdf.b.rename().groupby(psdf.a).idxmax().sort_index(), ) self.assert_eq( pdf.b.groupby(pdf.a.rename()).idxmax().sort_index(), psdf.b.groupby(psdf.a.rename()).idxmax().sort_index(), ) self.assert_eq( pdf.b.rename().groupby(pdf.a.rename()).idxmax().sort_index(), psdf.b.rename().groupby(psdf.a.rename()).idxmax().sort_index(), ) with self.assertRaisesRegex(ValueError, "idxmax only support one-level index now"): psdf.set_index(["a", "b"]).groupby(["c"]).idxmax() # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( pdf.groupby(("x", "a")).idxmax().sort_index(), psdf.groupby(("x", "a")).idxmax().sort_index(), ) self.assert_eq( pdf.groupby(("x", "a")).idxmax(skipna=False).sort_index(), psdf.groupby(("x", "a")).idxmax(skipna=False).sort_index(), ) def test_idxmin(self): pdf = pd.DataFrame( {"a": [1, 1, 2, 2, 3] * 3, "b": [1, 2, 3, 4, 5] * 3, "c": [5, 4, 3, 2, 1] * 3} ) psdf = ps.from_pandas(pdf) self.assert_eq( pdf.groupby(["a"]).idxmin().sort_index(), psdf.groupby(["a"]).idxmin().sort_index() ) self.assert_eq( pdf.groupby(["a"]).idxmin(skipna=False).sort_index(), psdf.groupby(["a"]).idxmin(skipna=False).sort_index(), ) self.assert_eq( pdf.groupby(["a"])["b"].idxmin().sort_index(), psdf.groupby(["a"])["b"].idxmin().sort_index(), ) self.assert_eq( pdf.b.rename().groupby(pdf.a).idxmin().sort_index(), psdf.b.rename().groupby(psdf.a).idxmin().sort_index(), ) self.assert_eq( pdf.b.groupby(pdf.a.rename()).idxmin().sort_index(), psdf.b.groupby(psdf.a.rename()).idxmin().sort_index(), ) self.assert_eq( pdf.b.rename().groupby(pdf.a.rename()).idxmin().sort_index(), psdf.b.rename().groupby(psdf.a.rename()).idxmin().sort_index(), ) with self.assertRaisesRegex(ValueError, "idxmin only support one-level index now"): psdf.set_index(["a", "b"]).groupby(["c"]).idxmin() # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( pdf.groupby(("x", "a")).idxmin().sort_index(), psdf.groupby(("x", "a")).idxmin().sort_index(), ) self.assert_eq( pdf.groupby(("x", "a")).idxmin(skipna=False).sort_index(), psdf.groupby(("x", "a")).idxmin(skipna=False).sort_index(), ) def test_head(self): pdf = pd.DataFrame( { "a": [1, 1, 1, 1, 2, 2, 2, 3, 3, 3] * 3, "b": [2, 3, 1, 4, 6, 9, 8, 10, 7, 5] * 3, "c": [3, 5, 2, 5, 1, 2, 6, 4, 3, 6] * 3, }, index=np.random.rand(10 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( pdf.groupby("a").head(2).sort_index(), psdf.groupby("a").head(2).sort_index() ) self.assert_eq( pdf.groupby("a").head(-2).sort_index(), psdf.groupby("a").head(-2).sort_index() ) self.assert_eq( pdf.groupby("a").head(100000).sort_index(), psdf.groupby("a").head(100000).sort_index() ) self.assert_eq( pdf.groupby("a")["b"].head(2).sort_index(), psdf.groupby("a")["b"].head(2).sort_index() ) self.assert_eq( pdf.groupby("a")["b"].head(-2).sort_index(), psdf.groupby("a")["b"].head(-2).sort_index(), ) self.assert_eq( pdf.groupby("a")["b"].head(100000).sort_index(), psdf.groupby("a")["b"].head(100000).sort_index(), ) self.assert_eq( pdf.groupby("a")[["b"]].head(2).sort_index(), psdf.groupby("a")[["b"]].head(2).sort_index(), ) self.assert_eq( pdf.groupby("a")[["b"]].head(-2).sort_index(), psdf.groupby("a")[["b"]].head(-2).sort_index(), ) self.assert_eq( pdf.groupby("a")[["b"]].head(100000).sort_index(), psdf.groupby("a")[["b"]].head(100000).sort_index(), ) self.assert_eq( pdf.groupby(pdf.a // 2).head(2).sort_index(), psdf.groupby(psdf.a // 2).head(2).sort_index(), ) self.assert_eq( pdf.groupby(pdf.a // 2)["b"].head(2).sort_index(), psdf.groupby(psdf.a // 2)["b"].head(2).sort_index(), ) self.assert_eq( pdf.groupby(pdf.a // 2)[["b"]].head(2).sort_index(), psdf.groupby(psdf.a // 2)[["b"]].head(2).sort_index(), ) self.assert_eq( pdf.b.rename().groupby(pdf.a).head(2).sort_index(), psdf.b.rename().groupby(psdf.a).head(2).sort_index(), ) self.assert_eq( pdf.b.groupby(pdf.a.rename()).head(2).sort_index(), psdf.b.groupby(psdf.a.rename()).head(2).sort_index(), ) self.assert_eq( pdf.b.rename().groupby(pdf.a.rename()).head(2).sort_index(), psdf.b.rename().groupby(psdf.a.rename()).head(2).sort_index(), ) # multi-index midx = pd.MultiIndex( [["x", "y"], ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]], [[0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], ) pdf = pd.DataFrame( { "a": [1, 1, 1, 1, 2, 2, 2, 3, 3, 3], "b": [2, 3, 1, 4, 6, 9, 8, 10, 7, 5], "c": [3, 5, 2, 5, 1, 2, 6, 4, 3, 6], }, columns=["a", "b", "c"], index=midx, ) psdf = ps.from_pandas(pdf) self.assert_eq( pdf.groupby("a").head(2).sort_index(), psdf.groupby("a").head(2).sort_index() ) self.assert_eq( pdf.groupby("a").head(-2).sort_index(), psdf.groupby("a").head(-2).sort_index() ) self.assert_eq( pdf.groupby("a").head(100000).sort_index(), psdf.groupby("a").head(100000).sort_index() ) self.assert_eq( pdf.groupby("a")["b"].head(2).sort_index(), psdf.groupby("a")["b"].head(2).sort_index() ) self.assert_eq( pdf.groupby("a")["b"].head(-2).sort_index(), psdf.groupby("a")["b"].head(-2).sort_index(), ) self.assert_eq( pdf.groupby("a")["b"].head(100000).sort_index(), psdf.groupby("a")["b"].head(100000).sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( pdf.groupby(("x", "a")).head(2).sort_index(), psdf.groupby(("x", "a")).head(2).sort_index(), ) self.assert_eq( pdf.groupby(("x", "a")).head(-2).sort_index(), psdf.groupby(("x", "a")).head(-2).sort_index(), ) self.assert_eq( pdf.groupby(("x", "a")).head(100000).sort_index(), psdf.groupby(("x", "a")).head(100000).sort_index(), ) def test_missing(self): psdf = ps.DataFrame({"a": [1, 2, 3, 4, 5, 6, 7, 8, 9]}) # DataFrameGroupBy functions missing_functions = inspect.getmembers( MissingPandasLikeDataFrameGroupBy, inspect.isfunction ) unsupported_functions = [ name for (name, type_) in missing_functions if type_.__name__ == "unsupported_function" ] for name in unsupported_functions: with self.assertRaisesRegex( PandasNotImplementedError, "method.*GroupBy.*{}.*not implemented( yet\\.|\\. .+)".format(name), ): getattr(psdf.groupby("a"), name)() deprecated_functions = [ name for (name, type_) in missing_functions if type_.__name__ == "deprecated_function" ] for name in deprecated_functions: with self.assertRaisesRegex( PandasNotImplementedError, "method.*GroupBy.*{}.*is deprecated".format(name) ): getattr(psdf.groupby("a"), name)() # SeriesGroupBy functions missing_functions = inspect.getmembers(MissingPandasLikeSeriesGroupBy, inspect.isfunction) unsupported_functions = [ name for (name, type_) in missing_functions if type_.__name__ == "unsupported_function" ] for name in unsupported_functions: with self.assertRaisesRegex( PandasNotImplementedError, "method.*GroupBy.*{}.*not implemented( yet\\.|\\. .+)".format(name), ): getattr(psdf.a.groupby(psdf.a), name)() deprecated_functions = [ name for (name, type_) in missing_functions if type_.__name__ == "deprecated_function" ] for name in deprecated_functions: with self.assertRaisesRegex( PandasNotImplementedError, "method.*GroupBy.*{}.*is deprecated".format(name) ): getattr(psdf.a.groupby(psdf.a), name)() # DataFrameGroupBy properties missing_properties = inspect.getmembers( MissingPandasLikeDataFrameGroupBy, lambda o: isinstance(o, property) ) unsupported_properties = [ name for (name, type_) in missing_properties if type_.fget.__name__ == "unsupported_property" ] for name in unsupported_properties: with self.assertRaisesRegex( PandasNotImplementedError, "property.*GroupBy.*{}.*not implemented( yet\\.|\\. .+)".format(name), ): getattr(psdf.groupby("a"), name) deprecated_properties = [ name for (name, type_) in missing_properties if type_.fget.__name__ == "deprecated_property" ] for name in deprecated_properties: with self.assertRaisesRegex( PandasNotImplementedError, "property.*GroupBy.*{}.*is deprecated".format(name) ): getattr(psdf.groupby("a"), name) # SeriesGroupBy properties missing_properties = inspect.getmembers( MissingPandasLikeSeriesGroupBy, lambda o: isinstance(o, property) ) unsupported_properties = [ name for (name, type_) in missing_properties if type_.fget.__name__ == "unsupported_property" ] for name in unsupported_properties: with self.assertRaisesRegex( PandasNotImplementedError, "property.*GroupBy.*{}.*not implemented( yet\\.|\\. .+)".format(name), ): getattr(psdf.a.groupby(psdf.a), name) deprecated_properties = [ name for (name, type_) in missing_properties if type_.fget.__name__ == "deprecated_property" ] for name in deprecated_properties: with self.assertRaisesRegex( PandasNotImplementedError, "property.*GroupBy.*{}.*is deprecated".format(name) ): getattr(psdf.a.groupby(psdf.a), name) @staticmethod def test_is_multi_agg_with_relabel(): assert is_multi_agg_with_relabel(a="max") is False assert is_multi_agg_with_relabel(a_min=("a", "max"), a_max=("a", "min")) is True def test_get_group(self): pdf = pd.DataFrame( [ ("falcon", "bird", 389.0), ("parrot", "bird", 24.0), ("lion", "mammal", 80.5), ("monkey", "mammal", np.nan), ], columns=["name", "class", "max_speed"], index=[0, 2, 3, 1], ) pdf.columns.name = "Koalas" psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby("class").get_group("bird"), pdf.groupby("class").get_group("bird"), ) self.assert_eq( psdf.groupby("class")["name"].get_group("mammal"), pdf.groupby("class")["name"].get_group("mammal"), ) self.assert_eq( psdf.groupby("class")[["name"]].get_group("mammal"), pdf.groupby("class")[["name"]].get_group("mammal"), ) self.assert_eq( psdf.groupby(["class", "name"]).get_group(("mammal", "lion")), pdf.groupby(["class", "name"]).get_group(("mammal", "lion")), ) self.assert_eq( psdf.groupby(["class", "name"])["max_speed"].get_group(("mammal", "lion")), pdf.groupby(["class", "name"])["max_speed"].get_group(("mammal", "lion")), ) self.assert_eq( psdf.groupby(["class", "name"])[["max_speed"]].get_group(("mammal", "lion")), pdf.groupby(["class", "name"])[["max_speed"]].get_group(("mammal", "lion")), ) self.assert_eq( (psdf.max_speed + 1).groupby(psdf["class"]).get_group("mammal"), (pdf.max_speed + 1).groupby(pdf["class"]).get_group("mammal"), ) self.assert_eq( psdf.groupby("max_speed").get_group(80.5), pdf.groupby("max_speed").get_group(80.5), ) self.assertRaises(KeyError, lambda: psdf.groupby("class").get_group("fish")) self.assertRaises(TypeError, lambda: psdf.groupby("class").get_group(["bird", "mammal"])) self.assertRaises(KeyError, lambda: psdf.groupby("class")["name"].get_group("fish")) self.assertRaises( TypeError, lambda: psdf.groupby("class")["name"].get_group(["bird", "mammal"]) ) self.assertRaises( KeyError, lambda: psdf.groupby(["class", "name"]).get_group(("lion", "mammal")) ) self.assertRaises(ValueError, lambda: psdf.groupby(["class", "name"]).get_group(("lion",))) self.assertRaises( ValueError, lambda: psdf.groupby(["class", "name"]).get_group(("mammal",)) ) self.assertRaises(ValueError, lambda: psdf.groupby(["class", "name"]).get_group("mammal")) # MultiIndex columns pdf.columns = pd.MultiIndex.from_tuples([("A", "name"), ("B", "class"), ("C", "max_speed")]) pdf.columns.names = ["Hello", "Koalas"] psdf = ps.from_pandas(pdf) self.assert_eq( psdf.groupby(("B", "class")).get_group("bird"), pdf.groupby(("B", "class")).get_group("bird"), ) self.assert_eq( psdf.groupby(("B", "class"))[[("A", "name")]].get_group("mammal"), pdf.groupby(("B", "class"))[[("A", "name")]].get_group("mammal"), ) self.assert_eq( psdf.groupby([("B", "class"), ("A", "name")]).get_group(("mammal", "lion")), pdf.groupby([("B", "class"), ("A", "name")]).get_group(("mammal", "lion")), ) self.assert_eq( psdf.groupby([("B", "class"), ("A", "name")])[[("C", "max_speed")]].get_group( ("mammal", "lion") ), pdf.groupby([("B", "class"), ("A", "name")])[[("C", "max_speed")]].get_group( ("mammal", "lion") ), ) self.assert_eq( (psdf[("C", "max_speed")] + 1).groupby(psdf[("B", "class")]).get_group("mammal"), (pdf[("C", "max_speed")] + 1).groupby(pdf[("B", "class")]).get_group("mammal"), ) self.assert_eq( psdf.groupby(("C", "max_speed")).get_group(80.5), pdf.groupby(("C", "max_speed")).get_group(80.5), ) self.assertRaises(KeyError, lambda: psdf.groupby(("B", "class")).get_group("fish")) self.assertRaises( TypeError, lambda: psdf.groupby(("B", "class")).get_group(["bird", "mammal"]) ) self.assertRaises( KeyError, lambda: psdf.groupby(("B", "class"))[("A", "name")].get_group("fish") ) self.assertRaises( KeyError, lambda: psdf.groupby([("B", "class"), ("A", "name")]).get_group(("lion", "mammal")), ) self.assertRaises( ValueError, lambda: psdf.groupby([("B", "class"), ("A", "name")]).get_group(("lion",)), ) self.assertRaises( ValueError, lambda: psdf.groupby([("B", "class"), ("A", "name")]).get_group(("mammal",)) ) self.assertRaises( ValueError, lambda: psdf.groupby([("B", "class"), ("A", "name")]).get_group("mammal") ) def test_median(self): psdf = ps.DataFrame( { "a": [1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0], "b": [2.0, 3.0, 1.0, 4.0, 6.0, 9.0, 8.0, 10.0, 7.0, 5.0], "c": [3.0, 5.0, 2.0, 5.0, 1.0, 2.0, 6.0, 4.0, 3.0, 6.0], }, columns=["a", "b", "c"], index=[7, 2, 4, 1, 3, 4, 9, 10, 5, 6], ) # DataFrame expected_result = ps.DataFrame( {"b": [2.0, 8.0, 7.0], "c": [3.0, 2.0, 4.0]}, index=pd.Index([1.0, 2.0, 3.0], name="a") ) self.assert_eq(expected_result, psdf.groupby("a").median().sort_index()) # Series expected_result = ps.Series( [2.0, 8.0, 7.0], name="b", index=pd.Index([1.0, 2.0, 3.0], name="a") ) self.assert_eq(expected_result, psdf.groupby("a")["b"].median().sort_index()) with self.assertRaisesRegex(TypeError, "accuracy must be an integer; however"): psdf.groupby("a").median(accuracy="a") def test_tail(self): pdf = pd.DataFrame( { "a": [1, 1, 1, 1, 2, 2, 2, 3, 3, 3] * 3, "b": [2, 3, 1, 4, 6, 9, 8, 10, 7, 5] * 3, "c": [3, 5, 2, 5, 1, 2, 6, 4, 3, 6] * 3, }, index=np.random.rand(10 * 3), ) psdf = ps.from_pandas(pdf) self.assert_eq( pdf.groupby("a").tail(2).sort_index(), psdf.groupby("a").tail(2).sort_index() ) self.assert_eq( pdf.groupby("a").tail(-2).sort_index(), psdf.groupby("a").tail(-2).sort_index() ) self.assert_eq( pdf.groupby("a").tail(100000).sort_index(), psdf.groupby("a").tail(100000).sort_index() ) self.assert_eq( pdf.groupby("a")["b"].tail(2).sort_index(), psdf.groupby("a")["b"].tail(2).sort_index() ) self.assert_eq( pdf.groupby("a")["b"].tail(-2).sort_index(), psdf.groupby("a")["b"].tail(-2).sort_index(), ) self.assert_eq( pdf.groupby("a")["b"].tail(100000).sort_index(), psdf.groupby("a")["b"].tail(100000).sort_index(), ) self.assert_eq( pdf.groupby("a")[["b"]].tail(2).sort_index(), psdf.groupby("a")[["b"]].tail(2).sort_index(), ) self.assert_eq( pdf.groupby("a")[["b"]].tail(-2).sort_index(), psdf.groupby("a")[["b"]].tail(-2).sort_index(), ) self.assert_eq( pdf.groupby("a")[["b"]].tail(100000).sort_index(), psdf.groupby("a")[["b"]].tail(100000).sort_index(), ) self.assert_eq( pdf.groupby(pdf.a // 2).tail(2).sort_index(), psdf.groupby(psdf.a // 2).tail(2).sort_index(), ) self.assert_eq( pdf.groupby(pdf.a // 2)["b"].tail(2).sort_index(), psdf.groupby(psdf.a // 2)["b"].tail(2).sort_index(), ) self.assert_eq( pdf.groupby(pdf.a // 2)[["b"]].tail(2).sort_index(), psdf.groupby(psdf.a // 2)[["b"]].tail(2).sort_index(), ) self.assert_eq( pdf.b.rename().groupby(pdf.a).tail(2).sort_index(), psdf.b.rename().groupby(psdf.a).tail(2).sort_index(), ) self.assert_eq( pdf.b.groupby(pdf.a.rename()).tail(2).sort_index(), psdf.b.groupby(psdf.a.rename()).tail(2).sort_index(), ) self.assert_eq( pdf.b.rename().groupby(pdf.a.rename()).tail(2).sort_index(), psdf.b.rename().groupby(psdf.a.rename()).tail(2).sort_index(), ) # multi-index midx = pd.MultiIndex( [["x", "y"], ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]], [[0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], ) pdf = pd.DataFrame( { "a": [1, 1, 1, 1, 2, 2, 2, 3, 3, 3], "b": [2, 3, 1, 4, 6, 9, 8, 10, 7, 5], "c": [3, 5, 2, 5, 1, 2, 6, 4, 3, 6], }, columns=["a", "b", "c"], index=midx, ) psdf = ps.from_pandas(pdf) self.assert_eq( pdf.groupby("a").tail(2).sort_index(), psdf.groupby("a").tail(2).sort_index() ) self.assert_eq( pdf.groupby("a").tail(-2).sort_index(), psdf.groupby("a").tail(-2).sort_index() ) self.assert_eq( pdf.groupby("a").tail(100000).sort_index(), psdf.groupby("a").tail(100000).sort_index() ) self.assert_eq( pdf.groupby("a")["b"].tail(2).sort_index(), psdf.groupby("a")["b"].tail(2).sort_index() ) self.assert_eq( pdf.groupby("a")["b"].tail(-2).sort_index(), psdf.groupby("a")["b"].tail(-2).sort_index(), ) self.assert_eq( pdf.groupby("a")["b"].tail(100000).sort_index(), psdf.groupby("a")["b"].tail(100000).sort_index(), ) # multi-index columns columns = pd.MultiIndex.from_tuples([("x", "a"), ("x", "b"), ("y", "c")]) pdf.columns = columns psdf.columns = columns self.assert_eq( pdf.groupby(("x", "a")).tail(2).sort_index(), psdf.groupby(("x", "a")).tail(2).sort_index(), ) self.assert_eq( pdf.groupby(("x", "a")).tail(-2).sort_index(), psdf.groupby(("x", "a")).tail(-2).sort_index(), ) self.assert_eq( pdf.groupby(("x", "a")).tail(100000).sort_index(), psdf.groupby(("x", "a")).tail(100000).sort_index(), ) def test_ddof(self): pdf = pd.DataFrame( { "a": [1, 1, 1, 1, 2, 2, 2, 3, 3, 3] * 3, "b": [2, 3, 1, 4, 6, 9, 8, 10, 7, 5] * 3, "c": [3, 5, 2, 5, 1, 2, 6, 4, 3, 6] * 3, }, index=np.random.rand(10 * 3), ) psdf = ps.from_pandas(pdf) for ddof in (0, 1): # std self.assert_eq( pdf.groupby("a").std(ddof=ddof).sort_index(), psdf.groupby("a").std(ddof=ddof).sort_index(), check_exact=False, ) self.assert_eq( pdf.groupby("a")["b"].std(ddof=ddof).sort_index(), psdf.groupby("a")["b"].std(ddof=ddof).sort_index(), check_exact=False, ) # var self.assert_eq( pdf.groupby("a").var(ddof=ddof).sort_index(), psdf.groupby("a").var(ddof=ddof).sort_index(), check_exact=False, ) self.assert_eq( pdf.groupby("a")["b"].var(ddof=ddof).sort_index(), psdf.groupby("a")["b"].var(ddof=ddof).sort_index(), check_exact=False, ) if __name__ == "__main__": from pyspark.pandas.tests.test_groupby import * # noqa: F401 try: import xmlrunner # type: ignore[import] testRunner = xmlrunner.XMLTestRunner(output="target/test-reports", verbosity=2) except ImportError: testRunner = None unittest.main(testRunner=testRunner, verbosity=2)
41.153846
100
0.480315
0363a50381fc11dbf75302da96ccf43f9afe5768
1,486
py
Python
IO_server/db2.py
gurkslask/hamcwebc
8abbe47cdd58972072d6088b63e1c368a63bb4af
[ "BSD-3-Clause" ]
null
null
null
IO_server/db2.py
gurkslask/hamcwebc
8abbe47cdd58972072d6088b63e1c368a63bb4af
[ "BSD-3-Clause" ]
null
null
null
IO_server/db2.py
gurkslask/hamcwebc
8abbe47cdd58972072d6088b63e1c368a63bb4af
[ "BSD-3-Clause" ]
null
null
null
"""Database connections.""" from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from models import Sensor, SensorTimeData import paho.mqtt.client as mqtt def put_sql(name, value): """Connect to sql and put in values.""" session = Session() sensor = session.query(Sensor).filter(Sensor.name == name).first() print(sensor) if sensor: """Make timesensor post.""" time_data = SensorTimeData(data=value) sensor.timedata = sensor.timedata + [time_data] session.add(time_data) sensor.value = value session.add(sensor) else: sensor(name=name, value=value) session.add(sensor) session.commit() session.close() def on_connect(client, userdata, flags, rc): """Subscribe on connect.""" client.subscribe('kgrund/fukt') client.subscribe('kgrund/temp') client.subscribe('VS1/VS1_GT1') client.subscribe('VS1/VS1_GT2') client.subscribe('VS1/VS1_GT3') def on_message(client, userdata, msg): """Connect to sql on connect.""" topic = msg.topic.replace('/', '_') payload = float(msg.payload) put_sql(topic, payload) if __name__ == '__main__': client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message engine = create_engine('postgresql://alex:bit@192.168.1.19:5432/alex') Session = sessionmaker(bind=engine) client.connect_async('192.168.1.19', 1883, 60) client.loop_forever()
26.070175
74
0.668237
fe9ebc8725c8839496fee05a6ccca0ffdc005669
4,224
py
Python
storm_kit/gym/kdl_parser.py
maxspahn/storm
cf056514659cab9c5c7ac9d850eae7c56a660726
[ "MIT" ]
68
2021-04-27T21:10:11.000Z
2022-03-23T23:13:45.000Z
storm_kit/gym/kdl_parser.py
maxspahn/storm
cf056514659cab9c5c7ac9d850eae7c56a660726
[ "MIT" ]
3
2021-07-06T11:04:32.000Z
2022-01-13T07:57:43.000Z
storm_kit/gym/kdl_parser.py
maxspahn/storm
cf056514659cab9c5c7ac9d850eae7c56a660726
[ "MIT" ]
16
2021-04-28T02:50:45.000Z
2022-01-13T13:35:43.000Z
#!/usr/bin/env python # # MIT License # # Copyright (c) 2020-2021 NVIDIA CORPORATION. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE.# import numpy as np import PyKDL as kdl from urdf_parser_py.urdf import Robot def euler_to_quat(r, p, y): sr, sp, sy = np.sin(r/2.0), np.sin(p/2.0), np.sin(y/2.0) cr, cp, cy = np.cos(r/2.0), np.cos(p/2.0), np.cos(y/2.0) return [sr*cp*cy - cr*sp*sy, cr*sp*cy + sr*cp*sy, cr*cp*sy - sr*sp*cy, cr*cp*cy + sr*sp*sy] def urdf_pose_to_kdl_frame(pose): pos = [0., 0., 0.] rot = [0., 0., 0.] if pose is not None: if pose.position is not None: pos = pose.position if pose.rotation is not None: rot = pose.rotation return kdl.Frame(kdl.Rotation.Quaternion(*euler_to_quat(*rot)), kdl.Vector(*pos)) def urdf_joint_to_kdl_joint(jnt): origin_frame = urdf_pose_to_kdl_frame(jnt.origin) if jnt.joint_type == 'fixed': return kdl.Joint(jnt.name, kdl.Joint.Fixed) axis = kdl.Vector(*jnt.axis) if jnt.joint_type == 'revolute': return kdl.Joint(jnt.name, origin_frame.p, origin_frame.M * axis, kdl.Joint.RotAxis) if jnt.joint_type == 'continuous': return kdl.Joint(jnt.name, origin_frame.p, origin_frame.M * axis, kdl.Joint.RotAxis) if jnt.joint_type == 'prismatic': return kdl.Joint(jnt.name, origin_frame.p, origin_frame.M * axis, kdl.Joint.TransAxis) print ("Unknown joint type: %s." % jnt.joint_type) return kdl.Joint(jnt.name, kdl.Joint.Fixed) # TODO: currently unknown joints are set as fixed def urdf_inertial_to_kdl_rbi(i): origin = urdf_pose_to_kdl_frame(i.origin) rbi = kdl.RigidBodyInertia(i.mass, origin.p, kdl.RotationalInertia(i.inertia.ixx, i.inertia.iyy, i.inertia.izz, i.inertia.ixy, i.inertia.ixz, i.inertia.iyz)) return origin.M * rbi ## # Returns a PyKDL.Tree generated from a urdf_parser_py.urdf.URDF object. def kdl_tree_from_urdf_model(urdf): root = urdf.get_root() tree = kdl.Tree(root) def add_children_to_tree(parent): if parent in urdf.child_map: for joint, child_name in urdf.child_map[parent]: child = urdf.link_map[child_name] if child.inertial is not None: kdl_inert = urdf_inertial_to_kdl_rbi(child.inertial) else: kdl_inert = kdl.RigidBodyInertia() kdl_jnt = urdf_joint_to_kdl_joint(urdf.joint_map[joint]) kdl_origin = urdf_pose_to_kdl_frame(urdf.joint_map[joint].origin) kdl_sgm = kdl.Segment(child_name, kdl_jnt, kdl_origin, kdl_inert) tree.addSegment(kdl_sgm, parent) add_children_to_tree(child_name) add_children_to_tree(root) return tree
43.102041
97
0.613636
8f1f6dbd27d94429f012e1c38e7027972a2479a0
1,246
py
Python
tests/test_mass_matrix.py
AdrienCorenflos/blackjax
e3204e17d3833be73d6f703dbb33b68b1431e629
[ "Apache-2.0" ]
null
null
null
tests/test_mass_matrix.py
AdrienCorenflos/blackjax
e3204e17d3833be73d6f703dbb33b68b1431e629
[ "Apache-2.0" ]
null
null
null
tests/test_mass_matrix.py
AdrienCorenflos/blackjax
e3204e17d3833be73d6f703dbb33b68b1431e629
[ "Apache-2.0" ]
null
null
null
import jax import numpy as np import pytest from blackjax.adaptation.mass_matrix import mass_matrix_adaptation @pytest.mark.parametrize("n_dim", [1, 3]) @pytest.mark.parametrize("is_mass_matrix_diagonal", [True, False]) def test_welford_adaptation(n_dim, is_mass_matrix_diagonal): num_samples = 3_000 # Generate samples from a multivariate normal distribution whose # covariance matrix we are going to try to recover. np.random.seed(0) mu = np.random.randn(n_dim) a = np.random.randn(n_dim, n_dim) cov = np.matmul(a.T, a) samples = np.random.multivariate_normal(mu, cov, num_samples) init, update, final = mass_matrix_adaptation(is_mass_matrix_diagonal) update_step = lambda state, sample: (update(state, sample), None) mm_state = init(n_dim) mm_state, _ = jax.lax.scan(update_step, mm_state, samples) mm_state = final(mm_state) estimated_cov = mm_state.inverse_mass_matrix if is_mass_matrix_diagonal: if n_dim == 1: np.testing.assert_allclose(estimated_cov, cov.squeeze(), rtol=1e-1) else: np.testing.assert_allclose(estimated_cov, np.diagonal(cov), rtol=1e-1) else: np.testing.assert_allclose(estimated_cov, cov, rtol=1e-1)
33.675676
82
0.718299
6e71959a2c611ab904dab93c8db8be0cc3f994ac
1,314
py
Python
tests/test_kmeans.py
rmaestre/ml-code-lectures
9cdc5e8552da10c30dca531ba6eaff41f0689713
[ "MIT" ]
2
2022-03-28T13:42:07.000Z
2022-03-28T13:42:12.000Z
tests/test_kmeans.py
rmaestre/ml-code-lectures
9cdc5e8552da10c30dca531ba6eaff41f0689713
[ "MIT" ]
null
null
null
tests/test_kmeans.py
rmaestre/ml-code-lectures
9cdc5e8552da10c30dca531ba6eaff41f0689713
[ "MIT" ]
1
2022-03-03T08:36:52.000Z
2022-03-03T08:36:52.000Z
import numpy as np from ml.datasets.blobs import Blobs from ml.models.kmeans import Kmeans def get_data(): dataset = Blobs() X, y = dataset.generate( n_samples=100, n_centers=3, random_state=1234, cluster_std=[1.2, 2.4, 2.0] ) return X, y def test_init(): X, _ = get_data() kmeans = Kmeans() kmeans.fit(X, n_centers=3, n_iterations=3) # Assert centroids length assert len(kmeans.centroids) == 3 # Assert not None centroids for centroid in kmeans.centroids: assert centroid is not None # Assert centroid has value for coord in centroid: assert coord != 0.0 def test_distance(): X, _ = get_data() kmeans = Kmeans() kmeans.fit(X, n_centers=3, n_iterations=3) # Get one feature distances = kmeans.distance(X[0], kmeans.centroids) assert distances.shape[0] == 3 assert distances[0] != distances[1] assert distances[0] != distances[2] assert distances[1] != distances[2] def test_predict(): X, _ = get_data() kmeans = Kmeans() kmeans.fit(X, n_centers=3, n_iterations=3) y_hats = kmeans.predict(X) # Same y_hats length tha X assert y_hats.shape[0] == X.shape[0] # Labels are the same than the centroids number assert np.unique(y_hats).shape[0] == 3
23.052632
82
0.64003
1d78a3b31b2e3f7463eb3c8a98e15b2b4febc308
17,058
py
Python
resources/usr/lib/python2.7/dist-packages/numpy/distutils/command/config.py
edawson/parliament2
2632aa3484ef64c9539c4885026b705b737f6d1e
[ "Apache-2.0" ]
null
null
null
resources/usr/lib/python2.7/dist-packages/numpy/distutils/command/config.py
edawson/parliament2
2632aa3484ef64c9539c4885026b705b737f6d1e
[ "Apache-2.0" ]
null
null
null
resources/usr/lib/python2.7/dist-packages/numpy/distutils/command/config.py
edawson/parliament2
2632aa3484ef64c9539c4885026b705b737f6d1e
[ "Apache-2.0" ]
1
2020-05-28T23:01:44.000Z
2020-05-28T23:01:44.000Z
# Added Fortran compiler support to config. Currently useful only for # try_compile call. try_run works but is untested for most of Fortran # compilers (they must define linker_exe first). # Pearu Peterson import os, signal import warnings import sys from distutils.command.config import config as old_config from distutils.command.config import LANG_EXT from distutils import log from distutils.file_util import copy_file from distutils.ccompiler import CompileError, LinkError import distutils from numpy.distutils.exec_command import exec_command from numpy.distutils.mingw32ccompiler import generate_manifest from numpy.distutils.command.autodist import check_inline, check_compiler_gcc4 from numpy.distutils.compat import get_exception LANG_EXT['f77'] = '.f' LANG_EXT['f90'] = '.f90' class config(old_config): old_config.user_options += [ ('fcompiler=', None, "specify the Fortran compiler type"), ] def initialize_options(self): self.fcompiler = None old_config.initialize_options(self) def try_run(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c"): warnings.warn("\n+++++++++++++++++++++++++++++++++++++++++++++++++\n" \ "Usage of try_run is deprecated: please do not \n" \ "use it anymore, and avoid configuration checks \n" \ "involving running executable on the target machine.\n" \ "+++++++++++++++++++++++++++++++++++++++++++++++++\n", DeprecationWarning) return old_config.try_run(self, body, headers, include_dirs, libraries, library_dirs, lang) def _check_compiler (self): old_config._check_compiler(self) from numpy.distutils.fcompiler import FCompiler, new_fcompiler if sys.platform == 'win32' and self.compiler.compiler_type == 'msvc': # XXX: hack to circumvent a python 2.6 bug with msvc9compiler: # initialize call query_vcvarsall, which throws an IOError, and # causes an error along the way without much information. We try to # catch it here, hoping it is early enough, and print an helpful # message instead of Error: None. if not self.compiler.initialized: try: self.compiler.initialize() except IOError: e = get_exception() msg = """\ Could not initialize compiler instance: do you have Visual Studio installed ? If you are trying to build with mingw, please use python setup.py build -c mingw32 instead ). If you have Visual Studio installed, check it is correctly installed, and the right version (VS 2008 for python 2.6, VS 2003 for 2.5, etc...). Original exception was: %s, and the Compiler class was %s ============================================================================""" \ % (e, self.compiler.__class__.__name__) print ("""\ ============================================================================""") raise distutils.errors.DistutilsPlatformError(msg) if not isinstance(self.fcompiler, FCompiler): self.fcompiler = new_fcompiler(compiler=self.fcompiler, dry_run=self.dry_run, force=1, c_compiler=self.compiler) if self.fcompiler is not None: self.fcompiler.customize(self.distribution) if self.fcompiler.get_version(): self.fcompiler.customize_cmd(self) self.fcompiler.show_customization() def _wrap_method(self,mth,lang,args): from distutils.ccompiler import CompileError from distutils.errors import DistutilsExecError save_compiler = self.compiler if lang in ['f77','f90']: self.compiler = self.fcompiler try: ret = mth(*((self,)+args)) except (DistutilsExecError,CompileError): msg = str(get_exception()) self.compiler = save_compiler raise CompileError self.compiler = save_compiler return ret def _compile (self, body, headers, include_dirs, lang): return self._wrap_method(old_config._compile,lang, (body, headers, include_dirs, lang)) def _link (self, body, headers, include_dirs, libraries, library_dirs, lang): if self.compiler.compiler_type=='msvc': libraries = (libraries or [])[:] library_dirs = (library_dirs or [])[:] if lang in ['f77','f90']: lang = 'c' # always use system linker when using MSVC compiler if self.fcompiler: for d in self.fcompiler.library_dirs or []: # correct path when compiling in Cygwin but with # normal Win Python if d.startswith('/usr/lib'): s,o = exec_command(['cygpath', '-w', d], use_tee=False) if not s: d = o library_dirs.append(d) for libname in self.fcompiler.libraries or []: if libname not in libraries: libraries.append(libname) for libname in libraries: if libname.startswith('msvc'): continue fileexists = False for libdir in library_dirs or []: libfile = os.path.join(libdir,'%s.lib' % (libname)) if os.path.isfile(libfile): fileexists = True break if fileexists: continue # make g77-compiled static libs available to MSVC fileexists = False for libdir in library_dirs: libfile = os.path.join(libdir,'lib%s.a' % (libname)) if os.path.isfile(libfile): # copy libname.a file to name.lib so that MSVC linker # can find it libfile2 = os.path.join(libdir,'%s.lib' % (libname)) copy_file(libfile, libfile2) self.temp_files.append(libfile2) fileexists = True break if fileexists: continue log.warn('could not find library %r in directories %s' \ % (libname, library_dirs)) elif self.compiler.compiler_type == 'mingw32': generate_manifest(self) return self._wrap_method(old_config._link,lang, (body, headers, include_dirs, libraries, library_dirs, lang)) def check_header(self, header, include_dirs=None, library_dirs=None, lang='c'): self._check_compiler() return self.try_compile( "/* we need a dummy line to make distutils happy */", [header], include_dirs) def check_decl(self, symbol, headers=None, include_dirs=None): self._check_compiler() body = """ int main() { #ifndef %s (void) %s; #endif ; return 0; }""" % (symbol, symbol) return self.try_compile(body, headers, include_dirs) def check_macro_true(self, symbol, headers=None, include_dirs=None): self._check_compiler() body = """ int main() { #if %s #else #error false or undefined macro #endif ; return 0; }""" % (symbol,) return self.try_compile(body, headers, include_dirs) def check_type(self, type_name, headers=None, include_dirs=None, library_dirs=None): """Check type availability. Return True if the type can be compiled, False otherwise""" self._check_compiler() # First check the type can be compiled body = r""" int main() { if ((%(name)s *) 0) return 0; if (sizeof (%(name)s)) return 0; } """ % {'name': type_name} st = False try: try: self._compile(body % {'type': type_name}, headers, include_dirs, 'c') st = True except distutils.errors.CompileError: st = False finally: self._clean() return st def check_type_size(self, type_name, headers=None, include_dirs=None, library_dirs=None, expected=None): """Check size of a given type.""" self._check_compiler() # First check the type can be compiled body = r""" typedef %(type)s npy_check_sizeof_type; int main () { static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) >= 0)]; test_array [0] = 0 ; return 0; } """ self._compile(body % {'type': type_name}, headers, include_dirs, 'c') self._clean() if expected: body = r""" typedef %(type)s npy_check_sizeof_type; int main () { static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) == %(size)s)]; test_array [0] = 0 ; return 0; } """ for size in expected: try: self._compile(body % {'type': type_name, 'size': size}, headers, include_dirs, 'c') self._clean() return size except CompileError: pass # this fails to *compile* if size > sizeof(type) body = r""" typedef %(type)s npy_check_sizeof_type; int main () { static int test_array [1 - 2 * !(((long) (sizeof (npy_check_sizeof_type))) <= %(size)s)]; test_array [0] = 0 ; return 0; } """ # The principle is simple: we first find low and high bounds of size # for the type, where low/high are looked up on a log scale. Then, we # do a binary search to find the exact size between low and high low = 0 mid = 0 while True: try: self._compile(body % {'type': type_name, 'size': mid}, headers, include_dirs, 'c') self._clean() break except CompileError: #log.info("failure to test for bound %d" % mid) low = mid + 1 mid = 2 * mid + 1 high = mid # Binary search: while low != high: mid = (high - low) // 2 + low try: self._compile(body % {'type': type_name, 'size': mid}, headers, include_dirs, 'c') self._clean() high = mid except CompileError: low = mid + 1 return low def check_func(self, func, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=False, call=False, call_args=None): # clean up distutils's config a bit: add void to main(), and # return a value. self._check_compiler() body = [] if decl: body.append("int %s (void);" % func) # Handle MSVC intrinsics: force MS compiler to make a function call. # Useful to test for some functions when built with optimization on, to # avoid build error because the intrinsic and our 'fake' test # declaration do not match. body.append("#ifdef _MSC_VER") body.append("#pragma function(%s)" % func) body.append("#endif") body.append("int main (void) {") if call: if call_args is None: call_args = '' body.append(" %s(%s);" % (func, call_args)) else: body.append(" %s;" % func) body.append(" return 0;") body.append("}") body = '\n'.join(body) + "\n" return self.try_link(body, headers, include_dirs, libraries, library_dirs) def check_funcs_once(self, funcs, headers=None, include_dirs=None, libraries=None, library_dirs=None, decl=False, call=False, call_args=None): """Check a list of functions at once. This is useful to speed up things, since all the functions in the funcs list will be put in one compilation unit. Arguments --------- funcs: seq list of functions to test include_dirs : seq list of header paths libraries : seq list of libraries to link the code snippet to libraru_dirs : seq list of library paths decl : dict for every (key, value), the declaration in the value will be used for function in key. If a function is not in the dictionay, no declaration will be used. call : dict for every item (f, value), if the value is True, a call will be done to the function f. """ self._check_compiler() body = [] if decl: for f, v in decl.items(): if v: body.append("int %s (void);" % f) # Handle MS intrinsics. See check_func for more info. body.append("#ifdef _MSC_VER") for func in funcs: body.append("#pragma function(%s)" % func) body.append("#endif") body.append("int main (void) {") if call: for f in funcs: if f in call and call[f]: if not (call_args and f in call_args and call_args[f]): args = '' else: args = call_args[f] body.append(" %s(%s);" % (f, args)) else: body.append(" %s;" % f) else: for f in funcs: body.append(" %s;" % f) body.append(" return 0;") body.append("}") body = '\n'.join(body) + "\n" return self.try_link(body, headers, include_dirs, libraries, library_dirs) def check_inline(self): """Return the inline keyword recognized by the compiler, empty string otherwise.""" return check_inline(self) def check_compiler_gcc4(self): """Return True if the C compiler is gcc >= 4.""" return check_compiler_gcc4(self) def get_output(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c"): """Try to compile, link to an executable, and run a program built from 'body' and 'headers'. Returns the exit status code of the program and its output. """ warnings.warn("\n+++++++++++++++++++++++++++++++++++++++++++++++++\n" \ "Usage of get_output is deprecated: please do not \n" \ "use it anymore, and avoid configuration checks \n" \ "involving running executable on the target machine.\n" \ "+++++++++++++++++++++++++++++++++++++++++++++++++\n", DeprecationWarning) from distutils.ccompiler import CompileError, LinkError self._check_compiler() exitcode, output = 255, '' try: grabber = GrabStdout() try: src, obj, exe = self._link(body, headers, include_dirs, libraries, library_dirs, lang) grabber.restore() except: output = grabber.data grabber.restore() raise exe = os.path.join('.', exe) exitstatus, output = exec_command(exe, execute_in='.') if hasattr(os, 'WEXITSTATUS'): exitcode = os.WEXITSTATUS(exitstatus) if os.WIFSIGNALED(exitstatus): sig = os.WTERMSIG(exitstatus) log.error('subprocess exited with signal %d' % (sig,)) if sig == signal.SIGINT: # control-C raise KeyboardInterrupt else: exitcode = exitstatus log.info("success!") except (CompileError, LinkError): log.info("failure.") self._clean() return exitcode, output class GrabStdout(object): def __init__(self): self.sys_stdout = sys.stdout self.data = '' sys.stdout = self def write (self, data): self.sys_stdout.write(data) self.data += data def flush (self): self.sys_stdout.flush() def restore(self): sys.stdout = self.sys_stdout
37.002169
108
0.525091
2538455d8f0eb0afe85cdeef8cdeec88afd88082
1,332
py
Python
bicycleparking/serializers.py
bikespace/bikespace
abd05b0232b5ef14bcc5abf64cfd2ef6141938c8
[ "MIT" ]
3
2019-01-25T23:04:12.000Z
2019-05-28T18:46:30.000Z
bicycleparking/serializers.py
bikespace/bikespace
abd05b0232b5ef14bcc5abf64cfd2ef6141938c8
[ "MIT" ]
12
2020-02-11T23:24:06.000Z
2022-02-10T08:04:25.000Z
bicycleparking/serializers.py
bikespace/bikespace
abd05b0232b5ef14bcc5abf64cfd2ef6141938c8
[ "MIT" ]
1
2019-01-25T23:08:34.000Z
2019-01-25T23:08:34.000Z
# MIT License # Copyright 2017,Code 4 Canada # written by and for the bicycle parking project, a joint project of # Civic Tech Toronto, Cycle Toronto, Code 4 Canada, and the # City of Toronto # # Created 2017 # Purpose define serializers for endpoints # # Modified 2018 05 30 # Purpose add location endpoint serializer # from rest_framework import serializers from django.contrib.postgres.fields import JSONField from bicycleparking.models import SurveyAnswer from bicycleparking.models import Picture from bicycleparking.models import BetaComments class SurveyAnswerSerializer (serializers.ModelSerializer) : class Meta: model = SurveyAnswer fields = ('latitude', 'longitude', 'survey') class BetaCommentSerializer (serializers.ModelSerializer) : class Meta: model = BetaComments fields = ("comment",) class LocationDataSerializer (serializers.Serializer) : """Serializes data to the Location object.""" latitude = serializers.FloatField (min_value = -90, max_value = 90) longitude = serializers.FloatField (min_value = -180, max_value = 180) def create(self, validated_data): return Comment (validated_data ['latitude'], validated_data ['longitude']) def update(self, instance, validated_data): instance.update (validated_data) return instance
30.272727
79
0.746246
d46ae3d2db36925be865e72e29e7eaa95e0d9e12
6,404
py
Python
tests/app/service/test_service_data_retention_rest.py
cds-snc/notifier-api
90b385ec49efbaee7e607516fc7d9f08991af813
[ "MIT" ]
41
2019-11-28T16:58:41.000Z
2022-01-28T21:11:16.000Z
tests/app/service/test_service_data_retention_rest.py
cds-snc/notification-api
b1c1064f291eb860b494c3fa65ac256ad70bf47c
[ "MIT" ]
1,083
2019-07-08T12:57:24.000Z
2022-03-08T18:53:40.000Z
tests/app/service/test_service_data_retention_rest.py
cds-snc/notifier-api
90b385ec49efbaee7e607516fc7d9f08991af813
[ "MIT" ]
9
2020-01-24T19:56:43.000Z
2022-01-27T21:36:53.000Z
import json import uuid from app.models import ServiceDataRetention from tests import create_authorization_header from tests.app.db import create_service_data_retention def test_get_service_data_retention(client, sample_service): sms_data_retention = create_service_data_retention(service=sample_service) email_data_retention = create_service_data_retention(service=sample_service, notification_type="email", days_of_retention=10) letter_data_retention = create_service_data_retention( service=sample_service, notification_type="letter", days_of_retention=30 ) response = client.get( "/service/{}/data-retention".format(str(sample_service.id)), headers=[("Content-Type", "application/json"), create_authorization_header()], ) assert response.status_code == 200 json_response = json.loads(response.get_data(as_text=True)) assert len(json_response) == 3 assert json_response[0] == email_data_retention.serialize() assert json_response[1] == sms_data_retention.serialize() assert json_response[2] == letter_data_retention.serialize() def test_get_service_data_retention_returns_empty_list(client, sample_service): response = client.get( "/service/{}/data-retention".format(str(sample_service.id)), headers=[("Content-Type", "application/json"), create_authorization_header()], ) assert response.status_code == 200 assert len(json.loads(response.get_data(as_text=True))) == 0 def test_get_data_retention_for_service_notification_type(client, sample_service): data_retention = create_service_data_retention(service=sample_service) response = client.get( "/service/{}/data-retention/notification-type/{}".format(sample_service.id, "sms"), headers=[("Content-Type", "application/json"), create_authorization_header()], ) assert response.status_code == 200 assert json.loads(response.get_data(as_text=True)) == data_retention.serialize() def test_get_service_data_retention_by_id(client, sample_service): sms_data_retention = create_service_data_retention(service=sample_service) create_service_data_retention(service=sample_service, notification_type="email", days_of_retention=10) create_service_data_retention(service=sample_service, notification_type="letter", days_of_retention=30) response = client.get( "/service/{}/data-retention/{}".format(str(sample_service.id), sms_data_retention.id), headers=[("Content-Type", "application/json"), create_authorization_header()], ) assert response.status_code == 200 assert json.loads(response.get_data(as_text=True)) == sms_data_retention.serialize() def test_get_service_data_retention_by_id_returns_none_when_no_data_retention_exists(client, sample_service): response = client.get( "/service/{}/data-retention/{}".format(str(sample_service.id), uuid.uuid4()), headers=[("Content-Type", "application/json"), create_authorization_header()], ) assert response.status_code == 200 assert json.loads(response.get_data(as_text=True)) == {} def test_create_service_data_retention(client, sample_service): data = {"notification_type": "sms", "days_of_retention": 3} response = client.post( "/service/{}/data-retention".format(str(sample_service.id)), headers=[("Content-Type", "application/json"), create_authorization_header()], data=json.dumps(data), ) assert response.status_code == 201 json_resp = json.loads(response.get_data(as_text=True))["result"] results = ServiceDataRetention.query.all() assert len(results) == 1 data_retention = results[0] assert json_resp == data_retention.serialize() def test_create_service_data_retention_returns_400_when_notification_type_is_invalid( client, ): data = {"notification_type": "unknown", "days_of_retention": 3} response = client.post( "/service/{}/data-retention".format(str(uuid.uuid4())), headers=[("Content-Type", "application/json"), create_authorization_header()], data=json.dumps(data), ) json_resp = json.loads(response.get_data(as_text=True)) assert response.status_code == 400 assert json_resp["errors"][0]["error"] == "ValidationError" assert json_resp["errors"][0]["message"] == "notification_type unknown is not one of [sms, letter, email]" def test_create_service_data_retention_returns_400_when_data_retention_for_notification_type_already_exists( client, sample_service ): create_service_data_retention(service=sample_service) data = {"notification_type": "sms", "days_of_retention": 3} response = client.post( "/service/{}/data-retention".format(str(uuid.uuid4())), headers=[("Content-Type", "application/json"), create_authorization_header()], data=json.dumps(data), ) assert response.status_code == 400 json_resp = json.loads(response.get_data(as_text=True)) assert json_resp["result"] == "error" assert json_resp["message"] == "Service already has data retention for sms notification type" def test_modify_service_data_retention(client, sample_service): data_retention = create_service_data_retention(service=sample_service) data = {"days_of_retention": 3} response = client.post( "/service/{}/data-retention/{}".format(sample_service.id, data_retention.id), headers=[("Content-Type", "application/json"), create_authorization_header()], data=json.dumps(data), ) assert response.status_code == 204 assert response.get_data(as_text=True) == "" def test_modify_service_data_retention_returns_400_when_data_retention_does_not_exist(client, sample_service): data = {"days_of_retention": 3} response = client.post( "/service/{}/data-retention/{}".format(sample_service.id, uuid.uuid4()), headers=[("Content-Type", "application/json"), create_authorization_header()], data=json.dumps(data), ) assert response.status_code == 404 def test_modify_service_data_retention_returns_400_when_data_is_invalid(client): data = {"bad_key": 3} response = client.post( "/service/{}/data-retention/{}".format(uuid.uuid4(), uuid.uuid4()), headers=[("Content-Type", "application/json"), create_authorization_header()], data=json.dumps(data), ) assert response.status_code == 400
43.27027
129
0.731418
e95d1ccf0d72356e9f36243de504e04decabfddf
165,901
py
Python
siliconcompiler/core.py
hohe/siliconcompiler
497f272c87c8f247dcd29db76c8d6ed0c0939e50
[ "Apache-2.0" ]
null
null
null
siliconcompiler/core.py
hohe/siliconcompiler
497f272c87c8f247dcd29db76c8d6ed0c0939e50
[ "Apache-2.0" ]
null
null
null
siliconcompiler/core.py
hohe/siliconcompiler
497f272c87c8f247dcd29db76c8d6ed0c0939e50
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 Silicon Compiler Authors. All Rights Reserved. import argparse import base64 import time import datetime import multiprocessing import tarfile import traceback import asyncio from subprocess import run, PIPE import os import pathlib import sys import gzip import re import json import logging import hashlib import shutil import copy import importlib import textwrap import math import pandas import yaml import graphviz import time import uuid import shlex import platform import getpass import distro import netifaces import webbrowser from jinja2 import Environment, FileSystemLoader from pathlib import Path from timeit import default_timer as timer from siliconcompiler.client import * from siliconcompiler.schema import * from siliconcompiler.scheduler import _deferstep from siliconcompiler import utils from siliconcompiler import _metadata class Chip: """Object for configuring and executing hardware design flows. This is the main object used for configuration, data, and execution within the SiliconCompiler platform. Args: design (string): Name of the top level chip design module. Examples: >>> siliconcompiler.Chip(design="top") Creates a chip object with name "top". """ ########################################################################### def __init__(self, design=None, loglevel="INFO"): # Local variables self.scroot = os.path.dirname(os.path.abspath(__file__)) self.cwd = os.getcwd() self.error = 0 self.cfg = schema_cfg() self.cfghistory = {} # The 'status' dictionary can be used to store ephemeral config values. # Its contents will not be saved, and can be set by parent scripts # such as a web server or supervisor process. Currently supported keys: # * 'jobhash': A hash or UUID which can identify jobs in a larger system. # * 'remote_cfg': Dictionary containing remote server configurations # (address, credentials, etc.) # * 'slurm_account': User account ID in a connected slurm HPC cluster. # * 'slurm_partition': Name of the partition in which a task should run # on a connected slurm HPC cluster. # * 'watchdog': Activity-monitoring semaphore for jobs scheduled on an # HPC cluster; expects a 'threading.Event'-like object. # * 'max_fs_bytes': A limit on how much disk space a job is allowed # to consume in a connected HPC cluster's storage. self.status = {} self.builtin = ['minimum','maximum', 'nop', 'mux', 'join', 'verify'] # We set 'design' and 'loglevel' directly in the config dictionary # because of a chicken-and-egg problem: self.set() relies on the logger, # but the logger relies on these values. self.cfg['design']['value'] = design self.cfg['loglevel']['value'] = loglevel # We set scversion directly because it has its 'lock' flag set by default. self.cfg['version']['sc']['value'] = _metadata.version self._init_logger() self._loaded_modules = { 'flows': [], 'pdks': [], 'libs': [] } ########################################################################### def _init_logger(self, step=None, index=None): self.logger = logging.getLogger(uuid.uuid4().hex) # Don't propagate log messages to "root" handler (we get duplicate # messages without this) # TODO: this prevents us from being able to capture logs with pytest: # we should revisit it self.logger.propagate = False loglevel = self.get('loglevel') jobname = self.get('jobname') if jobname == None: jobname = '---' if step == None: step = '---' if index == None: index = '-' run_info = '%-7s | %-12s | %-3s' % (jobname, step, index) if loglevel=='DEBUG': logformat = '| %(levelname)-7s | %(funcName)-10s | %(lineno)-4s | ' + run_info + ' | %(message)s' else: logformat = '| %(levelname)-7s | ' + run_info + ' | %(message)s' handler = logging.StreamHandler() formatter = logging.Formatter(logformat) handler.setFormatter(formatter) # Clear any existing handlers so we don't end up with duplicate messages # if repeat calls to _init_logger are made if len(self.logger.handlers) > 0: self.logger.handlers.clear() self.logger.addHandler(handler) self.logger.setLevel(loglevel) ########################################################################### def _deinit_logger(self): self.logger = None ########################################################################### def create_cmdline(self, progname, description=None, switchlist=[]): """Creates an SC command line interface. Exposes parameters in the SC schema as command line switches, simplifying creation of SC apps with a restricted set of schema parameters exposed at the command line. The order of command line switch settings parsed from the command line is as follows: 1. design 2. loglevel 3. mode 4. arg_step 5. fpga_partname 6. load_target('target') 7. read_manifest([cfg]) 8. all other switches The cmdline interface is implemented using the Python argparse package and the following use restrictions apply. * Help is accessed with the '-h' switch. * Arguments that include spaces must be enclosed with double quotes. * List parameters are entered individually. (ie. -y libdir1 -y libdir2) * For parameters with Boolean types, the switch implies "true". * Special characters (such as '-') must be enclosed in double quotes. * Compiler compatible switches include: -D, -I, -O{0,1,2,3} * Verilog legacy switch formats are supported: +libext+, +incdir+ Args: progname (str): Name of program to be executed. description (str): Short program description. switchlist (list of str): List of SC parameter switches to expose at the command line. By default all SC schema switches are available. Parameter switches should be entered without '-', based on the parameter 'switch' field in the 'schema'. Examples: >>> chip.create_cmdline(progname='sc-show',switchlist=['source','cfg']) Creates a command line interface for 'sc-show' app. """ # Argparse parser = argparse.ArgumentParser(prog=progname, prefix_chars='-+', formatter_class=argparse.RawDescriptionHelpFormatter, description=description) # Get all keys from global dictionary or override at command line allkeys = self.getkeys() # Iterate over all keys to add parser argument for key in allkeys: #Fetch fields from leaf cell helpstr = self.get(*key, field='shorthelp') typestr = self.get(*key, field='type') #Switch field fully describes switch format switch = self.get(*key, field='switch') if switch is None: switches = [] elif isinstance(switch, list): switches = switch else: switches = [switch] switchstrs = [] dest = None for switch in switches: switchmatch = re.match(r'(-[\w_]+)\s+(.*)', switch) gccmatch = re.match(r'(-[\w_]+)(.*)', switch) plusmatch = re.match(r'(\+[\w_\+]+)(.*)', switch) if switchmatch: switchstr = switchmatch.group(1) if re.search('_', switchstr): this_dest = re.sub('-','',switchstr) else: this_dest = key[0] elif gccmatch: switchstr = gccmatch.group(1) this_dest = key[0] elif plusmatch: switchstr = plusmatch.group(1) this_dest = key[0] switchstrs.append(switchstr) if dest is None: dest = this_dest elif dest != this_dest: raise ValueError('Destination for each switch in list must match') #Four switch types (source, scalar, list, bool) if ('source' not in key) & ((switchlist == []) | (dest in switchlist)): if typestr == 'bool': parser.add_argument(*switchstrs, metavar='', dest=dest, action='store_const', const="true", help=helpstr, default=argparse.SUPPRESS) #list type arguments elif re.match(r'\[', typestr): #all the rest parser.add_argument(*switchstrs, metavar='', dest=dest, action='append', help=helpstr, default=argparse.SUPPRESS) else: #all the rest parser.add_argument(*switchstrs, metavar='', dest=dest, help=helpstr, default=argparse.SUPPRESS) #Preprocess sys.argv to enable linux commandline switch formats #(gcc, verilator, etc) scargs = [] # Iterate from index 1, otherwise we end up with script name as a # 'source' positional argument for item in sys.argv[1:]: #Split switches with one character and a number after (O0,O1,O2) opt = re.match(r'(\-\w)(\d+)', item) #Split assign switches (-DCFG_ASIC=1) assign = re.search(r'(\-\w)(\w+\=\w+)', item) #Split plusargs (+incdir+/path) plusarg = re.search(r'(\+\w+\+)(.*)', item) if opt: scargs.append(opt.group(1)) scargs.append(opt.group(2)) elif plusarg: scargs.append(plusarg.group(1)) scargs.append(plusarg.group(2)) elif assign: scargs.append(assign.group(1)) scargs.append(assign.group(2)) else: scargs.append(item) # exit on version check if '-version' in scargs: print(_metadata.version) sys.exit(0) # Required positional source file argument if ((switchlist == []) & (not '-cfg' in scargs)) | ('source' in switchlist) : parser.add_argument('source', nargs='*', help=self.get('source', field='shorthelp')) #Grab argument from pre-process sysargs #print(scargs) cmdargs = vars(parser.parse_args(scargs)) #print(cmdargs) #sys.exit() # Print banner print(_metadata.banner) print("Authors:", ", ".join(_metadata.authors)) print("Version:", _metadata.version, "\n") print("-"*80) os.environ["COLUMNS"] = '80' # 1. set design name (override default) if 'design' in cmdargs.keys(): self.name = cmdargs['design'] # 2. set loglevel if set at command line if 'loglevel' in cmdargs.keys(): self.logger.setLevel(cmdargs['loglevel']) # 3. read in target if set if 'target' in cmdargs.keys(): if 'mode' in cmdargs.keys(): self.set('mode', cmdargs['mode'], clobber=True) if 'techarg' in cmdargs.keys(): print("NOT IMPLEMENTED") sys.exit() if 'flowarg' in cmdargs.keys(): print("NOT IMPLEMENTED") sys.exit() if 'arg_step' in cmdargs.keys(): self.set('arg', 'step', cmdargs['arg_step'], clobber=True) if 'fpga_partname' in cmdargs.keys(): self.set('fpga', 'partname', cmdargs['fpga_partname'], clobber=True) # running target command self.load_target(cmdargs['target']) # 4. read in all cfg files if 'cfg' in cmdargs.keys(): for item in cmdargs['cfg']: self.read_manifest(item, clobber=True, clear=True) # insert all parameters in dictionary self.logger.info('Setting commandline arguments') allkeys = self.getkeys() for key, val in cmdargs.items(): # Unifying around no underscores for now keylist = key.split('_') orderhash = {} # Find keypath with matching keys for keypath in allkeys: match = True for item in keylist: if item in keypath: orderhash[item] = keypath.index(item) else: match = False if match: chosenpath = keypath break # Turn everything into a list for uniformity if isinstance(val, list): val_list = val else: val_list = [val] for item in val_list: #space used to separate values! extrakeys = item.split(' ') for i in range(len(extrakeys)): # look for the first default statement # "delete' default in temp list by setting to None if 'default' in chosenpath: next_default = chosenpath.index('default') orderhash[extrakeys[i]] = next_default chosenpath[next_default] = None else: # Creating a sorted list based on key placement args = list(dict(sorted(orderhash.items(), key=lambda orderhash: orderhash[1]))) # Adding data value args = args + [extrakeys[i]] # Set/add value based on type #Check that keypath is valid if self.valid(*args[:-1], quiet=True): if re.match(r'\[', self.get(*args[:-1], field='type')): self.add(*args) else: self.set(*args, clobber=True) else: self.set(*args, clobber=True) ######################################################################### def find_function(self, modulename, funcname, moduletype=None): ''' Returns a function attribute from a module on disk. Searches the SC root directory and the 'scpath' parameter for the modulename provided and imports the module if found. If the funcname provided is found in the module, a callable function attribute is returned, otherwise None is returned. The function assumes the following directory structure: * tools/modulename/modulename.py * flows/modulename.py * pdks/modulname.py If the moduletype is None, the module paths are search in the order: 'targets'->'flows'->'tools'->'pdks'->'libs'): Supported functions include: * targets (make_docs, setup) * pdks (make_docs, setup) * flows (make_docs, setup) * tools (make_docs, setup, check_version, runtime_options, pre_process, post_process) * libs (make_docs, setup) Args: modulename (str): Name of module to import. funcname (str): Name of the function to find within the module. moduletype (str): Type of module (flows, pdks, libs, targets). Examples: >>> setup_pdk = chip.find_function('freepdk45', 'setup', 'pdks') >>> setup_pdk() Imports the freepdk45 module and runs the setup_pdk function ''' # module search path depends on modtype if moduletype is None: for item in ('targets', 'flows', 'pdks', 'libs'): relpath = f"{item}/{modulename}.py" fullpath = self._find_sc_file(relpath, missing_ok=True) if fullpath: break; elif moduletype in ('targets','flows', 'pdks', 'libs'): fullpath = self._find_sc_file(f"{moduletype}/{modulename}.py", missing_ok=True) elif moduletype in ('tools'): fullpath = self._find_sc_file(f"{moduletype}/{modulename}/{modulename}.py", missing_ok=True) else: self.logger.error(f"Illegal module type '{moduletype}'.") self.error = 1 return # try loading module if found if fullpath: if moduletype == 'tools': self.logger.debug(f"Loading function '{funcname}' from module '{modulename}'") else: self.logger.info(f"Loading function '{funcname}' from module '{modulename}'") try: spec = importlib.util.spec_from_file_location(modulename, fullpath) imported = importlib.util.module_from_spec(spec) spec.loader.exec_module(imported) if hasattr(imported, funcname): function = getattr(imported, funcname) else: function = None return function except: traceback.print_exc() self.logger.error(f"Module setup failed for '{modulename}'") self.error = 1 ########################################################################## def load_target(self, name): """ Loads a target module and runs the setup() function. The function searches the $SCPATH for targets/<name>.py and runs the setup function in that module if found. Args: name (str): Module name flow (str): Target flow to Examples: >>> chip.load_target('freepdk45_demo') Loads the 'freepdk45_demo' target """ self.set('target', name) func = self.find_function(name, 'setup', 'targets') if func is not None: func(self) else: self.logger.error(f'Module {name} not found.') sys.exit(1) ########################################################################## def load_pdk(self, name): """ Loads a PDK module and runs the setup() function. The function searches the $SCPATH for pdks/<name>.py and runs the setup function in that module if found. Args: name (str): Module name Examples: >>> chip.load_pdk('freepdk45_pdk') Loads the 'freepdk45' pdk """ func = self.find_function(name, 'setup', 'pdks') if func is not None: self._loaded_modules['pdks'].append(name) func(self) else: self.logger.error(f'Module {name} not found.') sys.exit(1) ########################################################################## def load_flow(self, name): """ Loads a flow module and runs the setup() function. The function searches the $SCPATH for flows/<name>.py and runs the setup function in that module if found. Args: name (str): Module name Examples: >>> chip.load_flow('asicflow') Loads the 'asicflow' flow """ func = self.find_function(name, 'setup', 'flows') if func is not None: self._loaded_modules['flows'].append(name) func(self) else: self.logger.error(f'Module {name} not found.') sys.exit(1) ########################################################################## def load_lib(self, name): """ Loads a library module and runs the setup() function. The function searches the $SCPATH for libs/<name>.py and runs the setup function in that module if found. Args: name (str): Module name Examples: >>> chip.load_lib('nangate45') Loads the 'nangate45' library """ func = self.find_function(name, 'setup', 'libs') if func is not None: self._loaded_modules['libs'].append(name) func(self) else: self.logger.error(f'Module {name} not found.') sys.exit(1) ########################################################################### def list_metrics(self): ''' Returns a list of all metrics in the schema. ''' return self.getkeys('metric','default','default') ########################################################################### def help(self, *keypath): """ Returns a schema parameter description. Args: *keypath(str): Keypath to parameter. Returns: A formatted multi-line help paragraph for the parameter provided. Examples: >>> print(chip.help('asic','diearea')) Displays help information about the 'asic, diearea' parameter """ self.logger.debug('Fetching help for %s', keypath) #Fetch Values description = self.get(*keypath, field='shorthelp') typestr = self.get(*keypath, field='type') switchstr = str(self.get(*keypath, field='switch')) defstr = str(self.get(*keypath, field='defvalue')) requirement = str(self.get(*keypath, field='require')) helpstr = self.get(*keypath, field='help') example = self.get(*keypath, field='example') #Removing multiple spaces and newlines helpstr = helpstr.rstrip() helpstr = helpstr.replace("\n", "") helpstr = ' '.join(helpstr.split()) for idx, item in enumerate(example): example[idx] = ' '.join(item.split()) example[idx] = example[idx].replace(", ", ",") #Wrap text para = textwrap.TextWrapper(width=60) para_list = para.wrap(text=helpstr) #Full Doc String fullstr = ("-"*80 + "\nDescription: " + description + "\nSwitch: " + switchstr + "\nType: " + typestr + "\nRequirement: " + requirement + "\nDefault: " + defstr + "\nExamples: " + example[0] + "\n " + example[1] + "\nHelp: " + para_list[0] + "\n") for line in para_list[1:]: fullstr = (fullstr + " "*13 + line.lstrip() + "\n") return fullstr ########################################################################### def valid(self, *args, valid_keypaths=None, quiet=True, default_valid=False): """ Checks validity of a keypath. Checks the validity of a parameter keypath and returns True if the keypath is valid and False if invalid. Args: keypath(list str): Variable length schema key list. valid_keypaths (list of list): List of valid keypaths as lists. If None, check against all keypaths in the schema. quiet (bool): If True, don't display warnings for invalid keypaths. Returns: Boolean indicating validity of keypath. Examples: >>> check = chip.valid('design') Returns True. >>> check = chip.valid('blah') Returns False. """ keypathstr = ','.join(args) keylist = list(args) if default_valid: default = 'default' else: default = None if valid_keypaths is None: valid_keypaths = self.getkeys() # Look for a full match with default playing wild card for valid_keypath in valid_keypaths: if len(keylist) != len(valid_keypath): continue ok = True for i in range(len(keylist)): if valid_keypath[i] not in (keylist[i], default): ok = False break if ok: return True # Match not found if not quiet: self.logger.warning(f"Keypath [{keypathstr}] is not valid") return False ########################################################################### def get(self, *keypath, field='value', job=None, cfg=None): """ Returns a schema parameter field. Returns a schema parameter filed based on the keypath and value provided in the ``*args``. The returned type is consistent with the type field of the parameter. Fetching parameters with empty or undefined value files returns None for scalar types and [] (empty list) for list types. Accessing a non-existent keypath produces a logger error message and raises the Chip object error flag. Args: keypath(list str): Variable length schema key list. field(str): Parameter field to fetch. job (str): Jobname to use for dictionary access in place of the current active jobname. cfg(dict): Alternate dictionary to access in place of the default chip object schema dictionary. Returns: Value found for the keypath and field provided. Examples: >>> foundry = chip.get('pdk', 'foundry') Returns the name of the foundry from the PDK. """ if cfg is None: if job is not None: cfg = self.cfghistory[job] else: cfg = self.cfg keypathstr = ','.join(keypath) self.logger.debug(f"Reading from [{keypathstr}]. Field = '{field}'") return self._search(cfg, keypathstr, *keypath, field=field, mode='get') ########################################################################### def getkeys(self, *keypath, cfg=None): """ Returns a list of schema dictionary keys. Searches the schema for the keypath provided and returns a list of keys found, excluding the generic 'default' key. Accessing a non-existent keypath produces a logger error message and raises the Chip object error flag. Args: keypath(list str): Variable length ordered schema key list cfg(dict): Alternate dictionary to access in place of self.cfg Returns: List of keys found for the keypath provided. Examples: >>> keylist = chip.getkeys('pdk') Returns all keys for the 'pdk' keypath. >>> keylist = chip.getkeys() Returns all list of all keypaths in the schema. """ if cfg is None: cfg = self.cfg if len(list(keypath)) > 0: keypathstr = ','.join(keypath) self.logger.debug('Getting schema parameter keys for: %s', keypathstr) keys = list(self._search(cfg, keypathstr, *keypath, mode='getkeys')) if 'default' in keys: keys.remove('default') else: self.logger.debug('Getting all schema parameter keys.') keys = list(self._allkeys(cfg)) return keys ########################################################################### def getdict(self, *keypath, cfg=None): """ Returns a schema dictionary. Searches the schema for the keypath provided and returns a complete dictionary. Accessing a non-existent keypath produces a logger error message and raises the Chip object error flag. Args: keypath(list str): Variable length ordered schema key list cfg(dict): Alternate dictionary to access in place of self.cfg Returns: A schema dictionary Examples: >>> pdk = chip.getdict('pdk') Returns the complete dictionary found for the keypath 'pdk' """ if cfg is None: cfg = self.cfg if len(list(keypath)) > 0: keypathstr = ','.join(keypath) self.logger.debug('Getting cfg for: %s', keypathstr) localcfg = self._search(cfg, keypathstr, *keypath, mode='getcfg') return copy.deepcopy(localcfg) ########################################################################### def set(self, *args, field='value', clobber=True, cfg=None): ''' Sets a schema parameter field. Sets a schema parameter field based on the keypath and value provided in the ``*args``. New schema dictionaries are automatically created for keypaths that overlap with 'default' dictionaries. The write action is ignored if the parameter value is non-empty and the clobber option is set to False. The value provided must agree with the dictionary parameter 'type'. Accessing a non-existent keypath or providing a value that disagrees with the parameter type produces a logger error message and raises the Chip object error flag. Args: args (list): Parameter keypath followed by a value to set. field (str): Parameter field to set. clobber (bool): Existing value is overwritten if True. cfg(dict): Alternate dictionary to access in place of self.cfg Examples: >>> chip.set('design', 'top') Sets the name of the design to 'top' ''' if cfg is None: cfg = self.cfg # Verify that all keys are strings for key in args[:-1]: if not isinstance(key,str): self.logger.error(f"Key [{key}] is not a string [{args}]") keypathstr = ','.join(args[:-1]) all_args = list(args) # Special case to ensure loglevel is updated ASAP if len(args) == 2 and args[0] == 'loglevel' and field == 'value': self.logger.setLevel(args[1]) self.logger.debug(f"Setting [{keypathstr}] to {args[-1]}") return self._search(cfg, keypathstr, *all_args, field=field, mode='set', clobber=clobber) ########################################################################### def add(self, *args, cfg=None, field='value'): ''' Adds item(s) to a schema parameter list. Adds item(s) to schema parameter list based on the keypath and value provided in the ``*args``. New schema dictionaries are automatically created for keypaths that overlap with 'default' dictionaries. The value provided must agree with the dictionary parameter 'type'. Accessing a non-existent keypath, providing a value that disagrees with the parameter type, or using add with a scalar parameter produces a logger error message and raises the Chip object error flag. Args: args (list): Parameter keypath followed by a value to add. cfg(dict): Alternate dictionary to access in place of self.cfg field (str): Parameter field to set. Examples: >>> chip.add('source', 'hello.v') Adds the file 'hello.v' to the list of sources. ''' if cfg is None: cfg = self.cfg # Verify that all keys are strings for key in args[:-1]: if not isinstance(key,str): self.logger.error(f"Key [{key}] is not a string [{args}]") keypathstr = ','.join(args[:-1]) all_args = list(args) self.logger.debug(f'Appending value {args[-1]} to [{keypathstr}]') return self._search(cfg, keypathstr, *all_args, field=field, mode='add') ########################################################################### def _allkeys(self, cfg, keys=None, keylist=None): ''' Returns list of all keypaths in the schema. ''' if keys is None: keylist = [] keys = [] for k in cfg: newkeys = keys.copy() newkeys.append(k) if 'defvalue' in cfg[k]: keylist.append(newkeys) else: self._allkeys(cfg[k], keys=newkeys, keylist=keylist) return keylist ########################################################################### def _search(self, cfg, keypath, *args, field='value', mode='get', clobber=True): ''' Internal recursive function that searches the Chip schema for a match to the combination of *args and fields supplied. The function is used to set and get data within the dictionary. Args: cfg(dict): The cfg schema to search keypath (str): Concatenated keypath used for error logging. args (str): Keypath/value variable list used for access field(str): Leaf cell field to access. mode(str): Action (set/get/add/getkeys/getkeys) clobber(bool): Specifies to clobber (for set action) ''' all_args = list(args) param = all_args[0] val = all_args[-1] empty = [None, 'null', [], 'false'] #set/add leaf cell (all_args=(param,val)) if (mode in ('set', 'add')) & (len(all_args) == 2): # clean error if key not found if (not param in cfg) & (not 'default' in cfg): self.logger.error(f"Set/Add keypath [{keypath}] does not exist.") self.error = 1 else: # making an 'instance' of default if not found if (not param in cfg) & ('default' in cfg): cfg[param] = copy.deepcopy(cfg['default']) list_type =bool(re.match(r'\[', cfg[param]['type'])) # copying over defvalue if value doesn't exist if 'value' not in cfg[param]: cfg[param]['value'] = copy.deepcopy(cfg[param]['defvalue']) # checking for illegal fields if not field in cfg[param] and (field != 'value'): self.logger.error(f"Field '{field}' for keypath [{keypath}]' is not a valid field.") self.error = 1 # check legality of value if field == 'value': (type_ok,type_error) = self._typecheck(cfg[param], param, val) if not type_ok: self.logger.error("%s", type_error) self.error = 1 # converting python True/False to lower case string if (field == 'value') and (cfg[param]['type'] == 'bool'): if val == True: val = "true" elif val == False: val = "false" # checking if value has been set if field not in cfg[param]: selval = cfg[param]['defvalue'] else: selval = cfg[param]['value'] # updating values if cfg[param]['lock'] == "true": self.logger.debug("Ignoring {mode}{} to [{keypath}]. Lock bit is set.") elif (mode == 'set'): if (selval in empty) | clobber: if field in ('copy', 'lock'): # boolean fields if val is True: cfg[param][field] = "true" elif val is False: cfg[param][field] = "false" else: self.logger.error(f'{field} must be set to boolean.') self.error = 1 elif field in ('filehash', 'date', 'author', 'signature'): if isinstance(val, list): cfg[param][field] = val else: cfg[param][field] = [val] elif (not list_type) & (val is None): cfg[param][field] = None elif (not list_type) & (not isinstance(val, list)): cfg[param][field] = str(val) elif list_type & (not isinstance(val, list)): cfg[param][field] = [str(val)] elif list_type & isinstance(val, list): if re.search(r'\(', cfg[param]['type']): cfg[param][field] = list(map(str,val)) else: cfg[param][field] = val else: self.logger.error(f"Assigning list to scalar for [{keypath}]") self.error = 1 else: self.logger.debug(f"Ignoring set() to [{keypath}], value already set. Use clobber=true to override.") elif (mode == 'add'): if field in ('filehash', 'date', 'author', 'signature'): cfg[param][field].append(str(val)) elif field in ('copy', 'lock'): self.logger.error(f"Illegal use of add() for scalar field {field}.") self.error = 1 elif list_type & (not isinstance(val, list)): cfg[param][field].append(str(val)) elif list_type & isinstance(val, list): cfg[param][field].extend(val) else: self.logger.error(f"Illegal use of add() for scalar parameter [{keypath}].") self.error = 1 return cfg[param][field] #get leaf cell (all_args=param) elif len(all_args) == 1: if not param in cfg: self.error = 1 self.logger.error(f"Get keypath [{keypath}] does not exist.") elif mode == 'getcfg': return cfg[param] elif mode == 'getkeys': return cfg[param].keys() else: if not (field in cfg[param]) and (field!='value'): self.error = 1 self.logger.error(f"Field '{field}' not found for keypath [{keypath}]") elif field == 'value': #Select default if no value has been set if field not in cfg[param]: selval = cfg[param]['defvalue'] else: selval = cfg[param]['value'] #check for list if bool(re.match(r'\[', cfg[param]['type'])): sctype = re.sub(r'[\[\]]', '', cfg[param]['type']) return_list = [] if selval is None: return None for item in selval: if sctype == 'int': return_list.append(int(item)) elif sctype == 'float': return_list.append(float(item)) elif sctype == '(str,str)': if isinstance(item,tuple): return_list.append(item) else: tuplestr = re.sub(r'[\(\)\'\s]','',item) return_list.append(tuple(tuplestr.split(','))) elif sctype == '(float,float)': if isinstance(item,tuple): return_list.append(item) else: tuplestr = re.sub(r'[\(\)\s]','',item) return_list.append(tuple(map(float, tuplestr.split(',')))) else: return_list.append(item) return return_list else: if selval is None: # Unset scalar of any type scalar = None elif cfg[param]['type'] == "int": #print(selval, type(selval)) scalar = int(float(selval)) elif cfg[param]['type'] == "float": scalar = float(selval) elif cfg[param]['type'] == "bool": scalar = (selval == 'true') elif re.match(r'\(', cfg[param]['type']): tuplestr = re.sub(r'[\(\)\s]','',selval) scalar = tuple(map(float, tuplestr.split(','))) else: scalar = selval return scalar #all non-value fields are strings (or lists of strings) else: if cfg[param][field] == 'true': return True elif cfg[param][field] == 'false': return False else: return cfg[param][field] #if not leaf cell descend tree else: ##copying in default tree for dynamic trees if not param in cfg and 'default' in cfg: cfg[param] = copy.deepcopy(cfg['default']) elif not param in cfg: self.error = 1 self.logger.error(f"Get keypath [{keypath}] does not exist.") return None all_args.pop(0) return self._search(cfg[param], keypath, *all_args, field=field, mode=mode, clobber=clobber) ########################################################################### def _prune(self, cfg, top=True, keeplists=False): ''' Internal recursive function that creates a local copy of the Chip schema (cfg) with only essential non-empty parameters retained. ''' # create a local copy of dict if top: localcfg = copy.deepcopy(cfg) else: localcfg = cfg #10 should be enough for anyone... maxdepth = 10 i = 0 #Prune when the default & value are set to the following if keeplists: empty = ("null", None) else: empty = ("null", None, []) # When at top of tree loop maxdepth times to make sure all stale # branches have been removed, not elegant, but stupid-simple # "good enough" while i < maxdepth: #Loop through all keys starting at the top for k in list(localcfg.keys()): #removing all default/template keys # reached a default subgraph, delete it if k == 'default': del localcfg[k] # reached leaf-cell elif 'help' in localcfg[k].keys(): del localcfg[k]['help'] elif 'example' in localcfg[k].keys(): del localcfg[k]['example'] elif 'defvalue' in localcfg[k].keys(): if localcfg[k]['defvalue'] in empty: if 'value' in localcfg[k].keys(): if localcfg[k]['value'] in empty: del localcfg[k] else: del localcfg[k] #removing stale branches elif not localcfg[k]: localcfg.pop(k) #keep traversing tree else: self._prune(cfg=localcfg[k], top=False, keeplists=keeplists) if top: i += 1 else: break return localcfg ########################################################################### def _find_sc_file(self, filename, missing_ok=False): """ Returns the absolute path for the filename provided. Searches the SC root directory and the 'scpath' parameter for the filename provided and returns the absolute path. If no valid absolute path is found during the search, None is returned. Shell variables ('$' followed by strings consisting of numbers, underscores, and digits) are replaced with the variable value. Args: filename (str): Relative or absolute filename. Returns: Returns absolute path of 'filename' if found, otherwise returns None. Examples: >>> chip._find_sc_file('flows/asicflow.py') Returns the absolute path based on the sc installation directory. """ # Replacing environment variables filename = self._resolve_env_vars(filename) # If we have a path relative to our cwd or an abs path, pass-through here if os.path.exists(os.path.abspath(filename)): return os.path.abspath(filename) # Otherwise, search relative to scpaths scpaths = [self.scroot, self.cwd] scpaths.extend(self.get('scpath')) if 'SCPATH' in os.environ: scpaths.extend(os.environ['SCPATH'].split(os.pathsep)) searchdirs = ', '.join(scpaths) self.logger.debug(f"Searching for file {filename} in {searchdirs}") result = None for searchdir in scpaths: if not os.path.isabs(searchdir): searchdir = os.path.join(self.cwd, searchdir) abspath = os.path.abspath(os.path.join(searchdir, filename)) if os.path.exists(abspath): result = abspath break if result is None and not missing_ok: self.error = 1 self.logger.error(f"File {filename} was not found") return result ########################################################################### def find_files(self, *keypath, cfg=None, missing_ok=False): """ Returns absolute paths to files or directories based on the keypath provided. By default, this function first checks if the keypath provided has its `copy` parameter set to True. If so, it returns paths to the files in the build directory. Otherwise, it resolves these files based on the current working directory and SC path. The keypath provided must point to a schema parameter of type file, dir, or lists of either. Otherwise, it will trigger an error. Args: keypath (list str): Variable length schema key list. cfg (dict): Alternate dictionary to access in place of the default chip object schema dictionary. Returns: If keys points to a scalar entry, returns an absolute path to that file/directory, or None if not found. It keys points to a list entry, returns a list of either the absolute paths or None for each entry, depending on whether it is found. Examples: >>> chip.find_files('source') Returns a list of absolute paths to source files, as specified in the schema. """ if cfg is None: cfg = self.cfg copyall = self.get('copyall', cfg=cfg) paramtype = self.get(*keypath, field='type', cfg=cfg) if 'file' in paramtype: copy = self.get(*keypath, field='copy', cfg=cfg) else: copy = False if 'file' not in paramtype and 'dir' not in paramtype: self.logger.error('Can only call find_files on file or dir types') self.error = 1 return None is_list = bool(re.match(r'\[', paramtype)) paths = self.get(*keypath, cfg=cfg) # Convert to list if we have scalar if not is_list: paths = [paths] result = [] # Special case where we're looking to find tool outputs: check the # output directory and return those files directly if keypath[0] == 'eda' and keypath[2] in ('input', 'output', 'report'): step = keypath[3] index = keypath[4] if keypath[2] == 'report': io = "" else: io = keypath[2] + 's' iodir = os.path.join(self._getworkdir(step=step, index=index), io) for path in paths: abspath = os.path.join(iodir, path) if os.path.isfile(abspath): result.append(abspath) return result for path in paths: if (copyall or copy) and ('file' in paramtype): name = self._get_imported_filename(path) abspath = os.path.join(self._getworkdir(step='import'), 'outputs', name) if os.path.isfile(abspath): # if copy is True and file is found in import outputs, # continue. Otherwise, fall through to _find_sc_file (the # file may not have been gathered in imports yet) result.append(abspath) continue result.append(self._find_sc_file(path, missing_ok=missing_ok)) # Convert back to scalar if that was original type if not is_list: return result[0] return result ########################################################################### def find_result(self, filetype, step, jobname='job0', index='0'): """ Returns the absolute path of a compilation result. Utility function that returns the absolute path to a results file based on the provided arguments. The result directory structure is: <dir>/<design>/<jobname>/<step>/<index>/outputs/<design>.filetype Args: filetype (str): File extension (.v, .def, etc) step (str): Task step name ('syn', 'place', etc) jobname (str): Jobid directory name index (str): Task index Returns: Returns absolute path to file. Examples: >>> manifest_filepath = chip.find_result('.vg', 'syn') Returns the absolute path to the manifest. """ workdir = self._getworkdir(jobname, step, index) design = self.get('design') filename = f"{workdir}/outputs/{design}.{filetype}" self.logger.debug("Finding result %s", filename) if os.path.isfile(filename): return filename else: self.error = 1 return None ########################################################################### def _abspath(self, cfg): ''' Internal function that goes through provided dictionary and resolves all relative paths where required. ''' for keypath in self.getkeys(cfg=cfg): paramtype = self.get(*keypath, cfg=cfg, field='type') value = self.get(*keypath, cfg=cfg) if value: #only do something if type is file or dir if 'file' in paramtype or 'dir' in paramtype: abspaths = self.find_files(*keypath, cfg=cfg, missing_ok=True) self.set(*keypath, abspaths, cfg=cfg) ########################################################################### def _print_csv(self, cfg, file=None): allkeys = self.getkeys(cfg=cfg) for key in allkeys: keypath = f'"{",".join(key)}"' value = self.get(*key, cfg=cfg) if isinstance(value,list): for item in value: print(f"{keypath},{item}", file=file) else: print(f"{keypath},{value}", file=file) ########################################################################### def _print_tcl(self, cfg, file=None, prefix=""): ''' Prints out schema as TCL dictionary ''' allkeys = self.getkeys(cfg=cfg) for key in allkeys: typestr = self.get(*key, cfg=cfg, field='type') value = self.get(*key, cfg=cfg) # everything becomes a list # convert None to empty list if value is None: alist = [] elif bool(re.match(r'\[', typestr)): alist = value elif typestr == "bool" and value: alist = ["true"] elif typestr == "bool" and not value: alist = ["false"] else: alist = [value] #replace $VAR with env(VAR) for tcl for i, val in enumerate(alist): m = re.match(r'\$(\w+)(.*)', str(val)) if m: alist[i] = ('$env(' + m.group(1) + ')' + m.group(2)) #create a TCL dict keystr = ' '.join(key) valstr = ' '.join(map(str, alist)).replace(';', '\\;') outstr = f"{prefix} {keystr} [list {valstr}]\n" #print out all nom default values if 'default' not in key: print(outstr, file=file) ########################################################################### def merge_manifest(self, cfg, job=None, clobber=True, clear=True, check=False): """ Merges an external manifest with the current compilation manifest. All value fields in the provided schema dictionary are merged into the current chip object. Dictionaries with non-existent keypath produces a logger error message and raises the Chip object error flag. Args: job (str): Specifies non-default job to merge into clear (bool): If True, disables append operations for list type clobber (bool): If True, overwrites existing parameter value check (bool): If True, checks the validity of each key Examples: >>> chip.merge_manifest('my.pkg.json') Merges all parameters in my.pk.json into the Chip object """ if job is not None: # fill ith default schema before populating self.cfghistory[job] = schema_cfg() dst = self.cfghistory[job] else: dst = self.cfg for keylist in self.getkeys(cfg=cfg): #only read in valid keypaths without 'default' key_valid = True if check: key_valid = self.valid(*keylist, quiet=False, default_valid=True) if key_valid and 'default' not in keylist: # update value, handling scalars vs. lists typestr = self.get(*keylist, cfg=cfg, field='type') val = self.get(*keylist, cfg=cfg) arg = keylist.copy() arg.append(val) if bool(re.match(r'\[', typestr)) & bool(not clear): self.add(*arg, cfg=dst) else: self.set(*arg, cfg=dst, clobber=clobber) # update other fields that a user might modify for field in self.getdict(*keylist, cfg=cfg).keys(): if field in ('value', 'switch', 'type', 'require', 'defvalue', 'shorthelp', 'example', 'help'): # skip these fields (value handled above, others are static) continue v = self.get(*keylist, cfg=cfg, field=field) self.set(*keylist, v, cfg=dst, field=field) ########################################################################### def _keypath_empty(self, key): ''' Utility function to check key for an empty list. ''' emptylist = ("null", None, []) value = self.get(*key) defvalue = self.get(*key, field='defvalue') value_empty = (defvalue in emptylist) and (value in emptylist) return value_empty ########################################################################### def _check_files(self): allowed_paths = [os.path.join(self.cwd, self.get('dir'))] allowed_paths.extend(os.environ['SC_VALID_PATHS'].split(os.pathsep)) for keypath in self.getkeys(): if 'default' in keypath: continue paramtype = self.get(*keypath, field='type') #only do something if type is file or dir if 'file' in paramtype or 'dir' in paramtype: if self.get(*keypath) is None: # skip unset values (some directories are None by default) continue abspaths = self.find_files(*keypath, missing_ok=True) if not isinstance(abspaths, list): abspaths = [abspaths] for abspath in abspaths: ok = False if abspath is not None: for allowed_path in allowed_paths: if os.path.commonpath([abspath, allowed_path]) == allowed_path: ok = True continue if not ok: self.logger.error(f'Keypath {keypath} contains path(s) ' 'that do not exist or resolve to files outside of ' 'allowed directories.') return False return True ########################################################################### def check_filepaths(self): ''' Verifies that paths to all files in manifest are valid. ''' allkeys = self.getkeys() for keypath in allkeys: allpaths = [] paramtype = self.get(*keypath, field='type') if 'file' in paramtype or 'dir' in paramtype: if 'dir' not in keypath and self.get(*keypath): allpaths = list(self.get(*keypath)) for path in allpaths: #check for env var m = re.match(r'\$(\w+)(.*)', path) if m: prefix_path = os.environ[m.group(1)] path = prefix_path + m.group(2) file_error = 'file' in paramtype and not os.path.isfile(path) dir_error = 'dir' in paramtype and not os.path.isdir(path) if file_error or dir_error: self.logger.error(f"Paramater {keypath} path {path} is invalid") self.error = 1 ########################################################################### def check_manifest(self): ''' Verifies the integrity of the pre-run compilation manifest. Checks the validity of the current schema manifest in memory to ensure that the design has been properly set up prior to running compilation. The function is called inside the run() function but can also be called separately. Checks performed by the check_manifest() function include: * Has a flowgraph been defined? * Does the manifest satisfy the schema requirement field settings? * Are all flowgraph input names legal step/index pairs? * Are the tool parameter setting requirements met? Returns: Returns True if the manifest is valid, else returns False. Examples: >>> manifest_ok = chip.check_manifest() Returns True of the Chip object dictionary checks out. ''' flow = self.get('flow') steplist = self.get('steplist') if not steplist: steplist = self.list_steps() #1. Checking that flowgraph is legal if flow not in self.getkeys('flowgraph'): self.error = 1 self.logger.error(f"flowgraph {flow} not defined.") legal_steps = self.getkeys('flowgraph',flow) if 'import' not in legal_steps: self.error = 1 self.logger.error("Flowgraph doesn't contain import step.") #2. Check libary names for item in self.get('asic', 'logiclib'): if item not in self.getkeys('library'): self.error = 1 self.logger.error(f"Target library {item} not found.") #3. Check requirements list allkeys = self.getkeys() for key in allkeys: keypath = ",".join(key) if 'default' not in key: key_empty = self._keypath_empty(key) requirement = self.get(*key, field='require') if key_empty and (str(requirement) == 'all'): self.error = 1 self.logger.error(f"Global requirement missing for [{keypath}].") elif key_empty and (str(requirement) == self.get('mode')): self.error = 1 self.logger.error(f"Mode requirement missing for [{keypath}].") #4. Check per tool parameter requirements (when tool exists) for step in steplist: for index in self.getkeys('flowgraph', flow, step): tool = self.get('flowgraph', flow, step, index, 'tool') if (tool not in self.builtin) and (tool in self.getkeys('eda')): # checking that requirements are set if self.valid('eda', tool, 'require', step, index): all_required = self.get('eda', tool, 'require', step, index) for item in all_required: keypath = item.split(',') if self._keypath_empty(keypath): self.error = 1 self.logger.error(f"Value empty for [{keypath}] for {tool}.") if self._keypath_empty(['eda', tool, 'exe']): self.error = 1 self.logger.error(f'Executable not specified for tool {tool}') if 'SC_VALID_PATHS' in os.environ: if not self._check_files(): self.error = 1 if not self._check_flowgraph_io(): self.error = 1 # Dynamic checks # We only perform these if arg, step and arg, index are set. # We don't check inputs for skip all # TODO: Need to add skip step step = self.get('arg', 'step') index = self.get('arg', 'index') if step and index and not self.get('skip', 'all'): tool = self.get('flowgraph', flow, step, index, 'tool') if self.valid('eda', tool, 'input', step, index): required_inputs = self.get('eda', tool, 'input', step, index) else: required_inputs = [] input_dir = os.path.join(self._getworkdir(step=step, index=index), 'inputs') for filename in required_inputs: path = os.path.join(input_dir, filename) if not os.path.isfile(path): self.logger.error(f'Required input {filename} not received for {step}{index}.') self.error = 1 if (not tool in self.builtin) and self.valid('eda', tool, 'require', step, index): all_required = self.get('eda', tool, 'require', step, index) for item in all_required: keypath = item.split(',') paramtype = self.get(*keypath, field='type') if ('file' in paramtype) or ('dir' in paramtype): abspath = self.find_files(*keypath) if abspath is None or (isinstance(abspath, list) and None in abspath): self.logger.error(f"Required file keypath {keypath} can't be resolved.") self.error = 1 return self.error ########################################################################### def _gather_outputs(self, step, index): '''Return set of filenames that are guaranteed to be in outputs directory after a successful run of step/index.''' flow = self.get('flow') tool = self.get('flowgraph', flow, step, index, 'tool') outputs = set() if tool in self.builtin: in_tasks = self.get('flowgraph', flow, step, index, 'input') in_task_outputs = [self._gather_outputs(*task) for task in in_tasks] if tool in ('minimum', 'maximum'): if len(in_task_outputs) > 0: outputs = in_task_outputs[0].intersection(*in_task_outputs[1:]) elif tool in ('join', 'nop'): if len(in_task_outputs) > 0: outputs = in_task_outputs[0].union(*in_task_outputs[1:]) else: # TODO: logic should be added here when mux/verify builtins are implemented. self.logger.error(f'Builtin {tool} not yet implemented') else: # Not builtin tool if self.valid('eda', tool, 'output', step, index): outputs = set(self.get('eda', tool, 'output', step, index)) else: outputs = set() if step == 'import': imports = {self._get_imported_filename(p) for p in self._collect_paths()} outputs.update(imports) return outputs ########################################################################### def _check_flowgraph_io(self): '''Check if flowgraph is valid in terms of input and output files. Returns True if valid, False otherwise. ''' flow = self.get('flow') steplist = self.get('steplist') if not steplist: steplist = self.list_steps() if len(steplist) < 2: return True for step in steplist: for index in self.getkeys('flowgraph', flow, step): # For each task, check input requirements. tool = self.get('flowgraph', flow, step, index, 'tool') if tool in self.builtin: # We can skip builtins since they don't have any particular # input requirements -- they just pass through what they # receive. continue # Get files we receive from input tasks. in_tasks = self.get('flowgraph', flow, step, index, 'input') if len(in_tasks) > 1: self.logger.error(f'Tool task {step}{index} has more than one input task.') elif len(in_tasks) > 0: in_step, in_index = in_tasks[0] if in_step not in steplist: # If we're not running the input step, the required # inputs need to already be copied into the build # directory. jobname = self.get('jobname') if self.valid('jobinput', jobname, step, index): in_job = self.get('jobinput', jobname, step, index) else: in_job = jobname workdir = self._getworkdir(jobname=in_job, step=in_step, index=in_index) in_step_out_dir = os.path.join(workdir, 'outputs') inputs = set(os.listdir(in_step_out_dir)) else: inputs = self._gather_outputs(in_step, in_index) else: inputs = set() if self.valid('eda', tool, 'input', step, index): requirements = self.get('eda', tool, 'input', step, index) else: requirements = [] for requirement in requirements: if requirement not in inputs: self.logger.error(f'Invalid flow: {step}{index} will ' f'not receive required input {requirement}.') return False return True ########################################################################### def read_manifest(self, filename, job=None, clear=True, clobber=True): """ Reads a manifest from disk and merges it with the current compilation manifest. The file format read is determined by the filename suffix. Currently json (*.json) and yaml(*.yaml) formats are supported. Args: filename (filepath): Path to a manifest file to be loaded. job (str): Specifies non-default job to merge into. clear (bool): If True, disables append operations for list type. clobber (bool): If True, overwrites existing parameter value. Examples: >>> chip.read_manifest('mychip.json') Loads the file mychip.json into the current Chip object. """ abspath = os.path.abspath(filename) self.logger.debug('Reading manifest %s', abspath) #Read arguments from file based on file type with open(abspath, 'r') as f: if abspath.endswith('.json'): localcfg = json.load(f) elif abspath.endswith('.yaml') | abspath.endswith('.yml'): localcfg = yaml.load(f, Loader=yaml.SafeLoader) else: self.error = 1 self.logger.error('Illegal file format. Only json/yaml supported') f.close() #Merging arguments with the Chip configuration self.merge_manifest(localcfg, job=job, clear=clear, clobber=clobber) ########################################################################### def write_manifest(self, filename, prune=True, abspath=False, job=None): ''' Writes the compilation manifest to a file. The write file format is determined by the filename suffix. Currently json (*.json), yaml (*.yaml), tcl (*.tcl), and (*.csv) formats are supported. Args: filename (filepath): Output filepath prune (bool): If True, essential non-empty parameters from the the Chip object schema are written to the output file. abspath (bool): If set to True, then all schema filepaths are resolved to absolute filepaths. Examples: >>> chip.write_manifest('mydump.json') Prunes and dumps the current chip manifest into mydump.json ''' filepath = os.path.abspath(filename) self.logger.debug('Writing manifest to %s', filepath) if not os.path.exists(os.path.dirname(filepath)): os.makedirs(os.path.dirname(filepath)) if prune: self.logger.debug('Pruning dictionary before writing file %s', filepath) # Keep empty lists to simplify TCL coding if filepath.endswith('.tcl'): keeplists = True else: keeplists = False cfgcopy = self._prune(self.cfg, keeplists=keeplists) else: cfgcopy = copy.deepcopy(self.cfg) # resolve absolute paths if abspath: self._abspath(cfgcopy) # TODO: fix #remove long help (adds no value) #allkeys = self.getkeys(cfg=cfgcopy) #for key in allkeys: # self.set(*key, "...", cfg=cfgcopy, field='help') # format specific dumping with open(filepath, 'w') as f: if filepath.endswith('.json'): print(json.dumps(cfgcopy, indent=4, sort_keys=True), file=f) elif filepath.endswith('.yaml') | filepath.endswith('yml'): print(yaml.dump(cfgcopy, Dumper=YamlIndentDumper, default_flow_style=False), file=f) elif filepath.endswith('.core'): cfgfuse = self._dump_fusesoc(cfgcopy) print("CAPI=2:", file=f) print(yaml.dump(cfgfuse, Dumper=YamlIndentDumper, default_flow_style=False), file=f) elif filepath.endswith('.tcl'): print("#############################################", file=f) print("#!!!! AUTO-GENERATED FILE. DO NOT EDIT!!!!!!", file=f) print("#############################################", file=f) self._print_tcl(cfgcopy, prefix="dict set sc_cfg", file=f) elif filepath.endswith('.csv'): self._print_csv(cfgcopy, file=f) else: self.logger.error('File format not recognized %s', filepath) self.error = 1 ########################################################################### def check_checklist(self, standard, item=None): ''' Check an item in checklist. Checks the status of an item in the checklist for the standard provided. If the item is unspecified, all items are checked. The function relies on the checklist 'criteria' parameter and 'step' parameter to check for the existence of report filess and a passing metric based criteria. Checklist items with empty 'report' values or unmet criteria result in error messages and raising the error flag. Args: standard(str): Standard to check. item(str): Item to check from standard. Returns: Status of item check. Examples: >>> status = chip.check_checklist('iso9000', 'd000') Returns status. ''' if item is None: items = self.getkeys('checklist', standard) else: items = [item] flow = self.get('flow') global_check = True for item in items: step = self.get('checklist', standard, item, 'step') index = self.get('checklist', standard, item, 'index') all_criteria = self.get('checklist', standard, item, 'criteria') report_ok = False criteria_ok = True # manual if step not in self.getkeys('flowgraph',flow): #criteria not used, so always ok criteria_ok = True if len(self.getkeys('checklist',standard, item, 'report')) <2: self.logger.error(f"No report found for {item}") report_ok = False else: tool = self.get('flowgraph', flow, step, index, 'tool') # copy report paths over to checklsit for reptype in self.getkeys('eda', tool, 'report', step, index): report_ok = True report = self.get('eda', tool, 'report', step, index, reptype) self.set('checklist', standard, item, 'report', reptype, report) # quantifiable checklist criteria for criteria in all_criteria: m = re.match(r'(\w+)([\>\=\<]+)(\w+)', criteria) if not m: self.logger.error(f"Illegal checklist criteria: {criteria}") return False elif m.group(1) not in self.getkeys('metric', step, index): self.logger.error(f"Critera must use legal metrics only: {criteria}") return False else: param = m.group(1) op = m.group(2) goal = str(m.group(3)) value = str(self.get('metric', step, index, param, 'real')) criteria_ok = self._safecompare(value, op, goal) #item check if not report_ok: self.logger.error(f"Report missing for checklist: {standard} {item}") global_check = False self.error = 1 elif not criteria_ok: self.logger.error(f"Criteria check failed for checklist: {standard} {item}") global_check = False self.error = 1 return global_check ########################################################################### def read_file(self, filename, step='import', index='0'): ''' Read file defined in schema. (WIP) ''' return(0) ########################################################################### def package(self, filename, prune=True): ''' Create sanitized project package. (WIP) The SiliconCompiler project is filtered and exported as a JSON file. If the prune option is set to True, then all metrics, records and results are pruned from the package file. Args: filename (filepath): Output filepath prune (bool): If True, only essential source parameters are included in the package. Examples: >>> chip.package('package.json') Write project information to 'package.json' ''' return(0) ########################################################################### def publish(self, filename): ''' Publishes package to registry. (WIP) The filename is uploaed to a central package registry based on the the user credentials found in ~/.sc/credentials. Args: filename (filepath): Package filename Examples: >>> chip.publish('hello.json') Publish hello.json to central repository. ''' return(0) ########################################################################### def _dump_fusesoc(self, cfg): ''' Internal function for dumping core information from chip object. ''' fusesoc = {} toplevel = self.get('design', cfg=cfg) if self.get('name'): name = self.get('name', cfg=cfg) else: name = toplevel version = self.get('projversion', cfg=cfg) # Basic information fusesoc['name'] = f"{name}:{version}" fusesoc['description'] = self.get('description', cfg=cfg) fusesoc['filesets'] = {} # RTL #TODO: place holder fix with pre-processor list files = [] for item in self.get('source', cfg=cfg): files.append(item) fusesoc['filesets']['rtl'] = {} fusesoc['filesets']['rtl']['files'] = files fusesoc['filesets']['rtl']['depend'] = {} fusesoc['filesets']['rtl']['file_type'] = {} # Constraints files = [] for item in self.get('constraint', cfg=cfg): files.append(item) fusesoc['filesets']['constraints'] = {} fusesoc['filesets']['constraints']['files'] = files # Default Target fusesoc['targets'] = {} fusesoc['targets']['default'] = { 'filesets' : ['rtl', 'constraints', 'tb'], 'toplevel' : toplevel } return fusesoc ########################################################################### def write_flowgraph(self, filename, flow=None, fillcolor='#ffffff', fontcolor='#000000', fontsize='14', border=True, landscape=False): '''Renders and saves the compilation flowgraph to a file. The chip object flowgraph is traversed to create a graphviz (\*.dot) file comprised of node, edges, and labels. The dot file is a graphical representation of the flowgraph useful for validating the correctness of the execution flow graph. The dot file is then converted to the appropriate picture or drawing format based on the filename suffix provided. Supported output render formats include png, svg, gif, pdf and a few others. For more information about the graphviz project, see see https://graphviz.org/ Args: filename (filepath): Output filepath flow (str): Name of flowgraph to render fillcolor(str): Node fill RGB color hex value fontcolor (str): Node font RGB color hex value fontsize (str): Node text font size border (bool): Enables node border if True landscape (bool): Renders graph in landscape layout if True Examples: >>> chip.write_flowgraph('mydump.png') Renders the object flowgraph and writes the result to a png file. ''' filepath = os.path.abspath(filename) self.logger.debug('Writing flowgraph to file %s', filepath) fileroot, ext = os.path.splitext(filepath) fileformat = ext.replace(".", "") if flow is None: flow = self.get('flow') # controlling border width if border: penwidth = '1' else: penwidth = '0' # controlling graph direction if landscape: rankdir = 'LR' else: rankdir = 'TB' dot = graphviz.Digraph(format=fileformat) dot.graph_attr['rankdir'] = rankdir dot.attr(bgcolor='transparent') for step in self.getkeys('flowgraph',flow): irange = 0 for index in self.getkeys('flowgraph', flow, step): irange = irange +1 for i in range(irange): index = str(i) node = step+index # create step node tool = self.get('flowgraph', flow, step, index, 'tool') if tool in self.builtin: labelname = step elif tool is not None: labelname = f"{step}{index}\n({tool})" else: labelname = f"{step}{index}" dot.node(node, label=labelname, bordercolor=fontcolor, style='filled', fontcolor=fontcolor, fontsize=fontsize, ordering="in", penwidth=penwidth, fillcolor=fillcolor) # get inputs all_inputs = [] for in_step, in_index in self.get('flowgraph', flow, step, index, 'input'): all_inputs.append(in_step + in_index) for item in all_inputs: dot.edge(item, node) dot.render(filename=fileroot, cleanup=True) ######################################################################## def _collect_paths(self): ''' Returns list of paths to files that will be collected by import step. See docstring for _collect() for more details. ''' paths = [] copyall = self.get('copyall') allkeys = self.getkeys() for key in allkeys: leaftype = self.get(*key, field='type') if re.search('file', leaftype): copy = self.get(*key, field='copy') value = self.get(*key) if copyall or copy: for item in value: paths.append(item) return paths ######################################################################## def _collect(self, step, index, active): ''' Collects files found in the configuration dictionary and places them in inputs/. The function only copies in files that have the 'copy' field set as true. If 'copyall' is set to true, then all files are copied in. 1. indexing like in run, job1 2. chdir package 3. run tool to collect files, pickle file in output/design.v 4. copy in rest of the files below 5. record files read in to schema ''' indir = 'inputs' flow = self.get('flow') if not os.path.exists(indir): os.makedirs(indir) self.logger.info('Collecting input sources') for path in self._collect_paths(): filename = self._get_imported_filename(path) abspath = self._find_sc_file(path) if abspath: self.logger.info(f"Copying {abspath} to '{indir}' directory") shutil.copy(abspath, os.path.join(indir, filename)) else: self._haltstep(step, index, active) outdir = 'outputs' if not os.path.exists(outdir): os.makedirs(outdir) # Logic to make links from outputs/ to inputs/, skipping anything that # will be output by the tool as well as the manifest. We put this here # so that tools used for the import stage don't have to duplicate this # logic. We skip this logic for 'join'-based single-step imports, since # 'join' does the copy for us. tool = self.get('flowgraph', flow, step, index, 'tool') if tool not in self.builtin: if self.valid('eda', tool, 'output', step, index): outputs = self.get('eda', tool, 'output', step, index) else: outputs = [] design = self.get('design') ignore = outputs + [f'{design}.pkg.json'] utils.copytree(indir, outdir, dirs_exist_ok=True, link=True, ignore=ignore) elif tool not in ('join', 'nop'): self.error = 1 self.logger.error(f'Invalid import step builtin {tool}. Must be tool or join.') ########################################################################### def archive(self, step=None, index=None, all_files=False): '''Archive a job directory. Creates a single compressed archive (.tgz) based on the design, jobname, and flowgraph in the current chip manifest. Individual steps and/or indices can be archived based on argumnets specified. By default, all steps and indices in the flowgraph are archived. By default, only the outputs directory content and the log file are archived. Args: step(str): Step to archive. index (str): Index to archive all_files (bool): If True, all files are archived. ''' jobname = self.get('jobname') design = self.get('design') buildpath = self.get('dir') if step: steplist = [step] elif self.get('arg', 'step'): steplist = [self.get('arg', 'step')] elif self.get('steplist'): steplist = self.get('steplist') else: steplist = self.list_steps() if step: archive_name = f"{design}_{jobname}_{step}.tgz" else: archive_name = f"{design}_{jobname}.tgz" with tarfile.open(archive_name, "w:gz") as tar: for step in steplist: if index: indexlist = [index] else: indexlist = self.getkeys('flowgraph', flow, step) for item in indexlist: basedir = os.path.join(buildpath, design, jobname, step, item) if all_files: tar.add(os.path.abspath(basedir), arcname=basedir) else: outdir = os.path.join(basedir,'outputs') logfile = os.path.join(basedir, step+'.log') tar.add(os.path.abspath(outdir), arcname=outdir) if os.path.isfile(logfile): tar.add(os.path.abspath(logfile), arcname=logfile) ########################################################################### def hash_files(self, *keypath, algo='sha256', update=True): '''Generates hash values for a list of parameter files. Generates a a hash value for each file found in the keypath. If the update variable is True, the has values are recorded in the 'filehash' field of the parameter, following the order dictated by the files within the 'values' parameter field. Files are located using the find_files() function. The file hash calculation is performed basd on the 'algo' setting. Supported algorithms include SHA1, SHA224, SHA256, SHA384, SHA512, and MD5. Args: *keypath(str): Keypath to parameter. algo (str): Algorithm to use for file hash calculation update (bool): If True, the hash values are recorded in the chip object manifest. Returns: A list of hash values. Examples: >>> hashlist = hash_files('sources') Hashlist gets list of hash values computed from 'sources' files. ''' keypathstr = ','.join(keypath) #TODO: Insert into find_files? if 'file' not in self.get(*keypath, field='type'): self.logger.error(f"Illegal attempt to hash non-file parameter [{keypathstr}].") self.error = 1 else: filelist = self.find_files(*keypath) #cycle through all paths hashlist = [] if filelist: self.logger.info(f'Computing hash value for [{keypathstr}]') for filename in filelist: if os.path.isfile(filename): #TODO: Implement algo selection hashobj = hashlib.sha256() with open(filename, "rb") as f: for byte_block in iter(lambda: f.read(4096), b""): hashobj.update(byte_block) hash_value = hashobj.hexdigest() hashlist.append(hash_value) else: self.error = 1 self.logger.info(f"Internal hashing error, file not found") # compare previous hash to new hash oldhash = self.get(*keypath,field='filehash') for i,item in enumerate(oldhash): if item != hashlist[i]: self.logger.error(f"Hash mismatch for [{keypath}]") self.error = 1 self.set(*keypath, hashlist, field='filehash', clobber=True) ########################################################################### def audit_manifest(self): '''Verifies the integrity of the post-run compilation manifest. Checks the integrity of the chip object implementation flow after the run() function has been completed. Errors, warnings, and debug messages are reported through the logger object. Audit checks performed include: * Time stamps * File modifications * Error and warning policy * IP and design origin * User access * License terms * Version checks Returns: Returns True if the manifest has integrity, else returns False. Example: >>> chip.audit_manifest() Audits the Chip object manifest and returns 0 if successful. ''' return 0 ########################################################################### def calc_area(self): '''Calculates the area of a rectilinear diearea. Uses the shoelace formulate to calculate the design area using the (x,y) point tuples from the 'diearea' parameter. If only diearea paramater only contains two points, then the first and second point must be the lower left and upper right points of the rectangle. (Ref: https://en.wikipedia.org/wiki/Shoelace_formula) Returns: Design area (float). Examples: >>> area = chip.calc_area() ''' vertices = self.get('asic', 'diearea') if len(vertices) == 2: width = vertices[1][0] - vertices[0][0] height = vertices[1][1] - vertices[0][1] area = width * height else: area = 0.0 for i in range(len(vertices)): j = (i + 1) % len(vertices) area += vertices[i][0] * vertices[j][1] area -= vertices[j][0] * vertices[i][1] area = abs(area) / 2 return area ########################################################################### def calc_yield(self, model='poisson'): '''Calculates raw die yield. Calculates the raw yield of the design as a function of design area and d0 defect density. Calculation can be done based on the poisson model (default) or the murphy model. The die area and the d0 parameters are taken from the chip dictionary. * Poisson model: dy = exp(-area * d0/100). * Murphy model: dy = ((1-exp(-area * d0/100))/(area * d0/100))^2. Args: model (string): Model to use for calculation (poisson or murphy) Returns: Design yield percentage (float). Examples: >>> yield = chip.calc_yield() Yield variable gets yield value based on the chip manifest. ''' d0 = self.get('pdk', 'd0') diearea = self.calc_area() if model == 'poisson': dy = math.exp(-diearea * d0/100) elif model == 'murphy': dy = ((1-math.exp(-diearea * d0/100))/(diearea * d0/100))**2 return dy ########################################################################## def calc_dpw(self): '''Calculates dies per wafer. Calculates the gross dies per wafer based on the design area, wafersize, wafer edge margin, and scribe lines. The calculation is done by starting at the center of the wafer and placing as many complete design footprints as possible within a legal placement area. Returns: Number of gross dies per wafer (int). Examples: >>> dpw = chip.calc_dpw() Variable dpw gets gross dies per wafer value based on the chip manifest. ''' #PDK information wafersize = self.get('pdk', 'wafersize') edgemargin = self.get('pdk', 'edgemargin') hscribe = self.get('pdk', 'hscribe') vscribe = self.get('pdk', 'vscribe') #Design parameters diesize = self.get('asic', 'diesize').split() diewidth = (diesize[2] - diesize[0])/1000 dieheight = (diesize[3] - diesize[1])/1000 #Derived parameters radius = wafersize/2 -edgemargin stepwidth = (diewidth + hscribe) stepheight = (dieheight + vscribe) #Raster dies out from center until you touch edge margin #Work quadrant by quadrant dies = 0 for quad in ('q1', 'q2', 'q3', 'q4'): x = 0 y = 0 if quad == "q1": xincr = stepwidth yincr = stepheight elif quad == "q2": xincr = -stepwidth yincr = stepheight elif quad == "q3": xincr = -stepwidth yincr = -stepheight elif quad == "q4": xincr = stepwidth yincr = -stepheight #loop through all y values from center while math.hypot(0, y) < radius: y = y + yincr while math.hypot(x, y) < radius: x = x + xincr dies = dies + 1 x = 0 return int(dies) ########################################################################### def grep(self, args, line): """ Emulates the Unix grep command on a string. Emulates the behavior of the Unix grep command that is etched into our muscle memory. Partially implemented, not all features supported. The function returns None if no match is found. Args: arg (string): Command line arguments for grep command line (string): Line to process Returns: Result of grep command (string). """ # Quick return if input is None if line is None: return None # Partial list of supported grep options options = { '-v' : False, # Invert the sense of matching '-i' : False, # Ignore case distinctions in patterns and data '-E' : False, # Interpret PATTERNS as extended regular expressions. '-e' : False, # Safe interpretation of pattern starting with "-" '-x' : False, # Select only matches that exactly match the whole line. '-o' : False, # Print only the match parts of a matching line '-w' : False} # Select only lines containing matches that form whole words. # Split into repeating switches and everything else match = re.match(r'\s*((?:\-\w\s)*)(.*)', args) pattern = match.group(2) # Split space separated switch string into list switches = match.group(1).strip().split(' ') # Find special -e switch update the pattern for i in range(len(switches)): if switches[i] == "-e": if i != (len(switches)): pattern = ' '.join(switches[i+1:]) + " " + pattern switches = switches[0:i+1] break options["-e"] = True elif switches[i] in options.keys(): options[switches[i]] = True elif switches[i] !='': print("ERROR",switches[i]) #REGEX #TODO: add all the other optinos match = re.search(rf"({pattern})", line) if bool(match) == bool(options["-v"]): return None else: return line ########################################################################### def check_logfile(self, jobname=None, step=None, index='0', logfile=None, display=True): ''' Checks logfile for patterns found in the 'regex' parameter. Reads the content of the step's log file and compares the content found in step 'regex' parameter. The matches are stored in the file 'reports/<design>.<suffix>' in the run directory. The matches are printed to STDOUT if display is set to True. Args: step (str): Task step name ('syn', 'place', etc) jobname (str): Jobid directory name index (str): Task index display (bool): If True, printes matches to STDOUT. Examples: >>> chip.check_logfile('place') Searches for regex matches in the place logfile. ''' # Using manifest to get defaults flow = self.get('flow') design = self.get('design') if jobname is None: jobname = self.get('jobname') if logfile is None: logfile = f"{step}.log" if step is None: step = self.get('arg', 'step') if index is None: index = self.getkeys('flowgraph', flow, step)[0] tool = self.get('flowgraph', flow, step, index, 'tool') # Creating local dictionary (for speed) # self.get is slow checks = {} regex_list = [] if self.valid('eda', tool, 'regex', step, index, 'default'): regex_list = self.getkeys('eda', tool, 'regex', step, index) for suffix in regex_list: checks[suffix] = {} checks[suffix]['report'] = open(f"{step}.{suffix}", "w") checks[suffix]['args'] = self.get('eda', tool, 'regex', step, index, suffix) # Looping through patterns for each line with open(logfile) as f: for line in f: for suffix in checks: string = line for item in checks[suffix]['args']: if string is None: break else: string = self.grep(item, string) if string is not None: #always print to file print(string.strip(), file=checks[suffix]['report']) #selectively print to display if display: self.logger.info(string.strip()) ########################################################################### def summary(self, steplist=None, show_all_indices=False): ''' Prints a summary of the compilation manifest. Metrics from the flowgraph steps, or steplist parameter if defined, are printed out on a per step basis. All metrics from the metric dictionary with weights set in the flowgraph dictionary are printed out. Args: show_all_indices (bool): If True, displays metrics for all indices of each step. If False, displays metrics only for winning indices. Examples: >>> chip.summary() Prints out a summary of the run to stdout. ''' # display whole flowgraph if no steplist specified flow = self.get('flow') if not steplist: steplist = self.list_steps() #only report tool based steps functions for step in steplist: if self.get('flowgraph',flow, step,'0','tool') in self.builtin: index = steplist.index(step) del steplist[index] # job directory jobdir = self._getworkdir() # Custom reporting modes paramlist = [] for item in self.getkeys('param'): paramlist.append(item+"="+self.get('param',item)) if paramlist: paramstr = ', '.join(paramlist) else: paramstr = "None" info_list = ["SUMMARY:\n", "design : " + self.get('design'), "params : " + paramstr, "jobdir : "+ jobdir, ] if self.get('mode') == 'asic': info_list.extend(["foundry : " + self.get('pdk', 'foundry'), "process : " + self.get('pdk', 'process'), "targetlibs : "+" ".join(self.get('asic', 'logiclib'))]) elif self.get('mode') == 'fpga': info_list.extend(["partname : "+self.get('fpga','partname')]) info = '\n'.join(info_list) print("-"*135) print(info, "\n") # Stepping through all steps/indices and printing out metrics data = [] #Creating Header header = [] indices_to_show = {} colwidth = 8 for step in steplist: if show_all_indices: indices_to_show[step] = self.getkeys('flowgraph', flow, step) else: # Default for last step in list (could be tool or function) indices_to_show[step] = ['0'] # Find winning index for index in self.getkeys('flowgraph', flow, step): stepindex = step + index for i in self.getkeys('flowstatus'): for j in self.getkeys('flowstatus',i): for in_step, in_index in self.get('flowstatus',i,j,'select'): if (in_step + in_index) == stepindex: indices_to_show[step] = index # header for data frame for step in steplist: for index in indices_to_show[step]: header.append(f'{step}{index}'.center(colwidth)) # figure out which metrics have non-zero weights metric_list = [] for step in steplist: for metric in self.getkeys('metric','default','default'): if metric in self.getkeys('flowgraph', flow, step, '0', 'weight'): if self.get('flowgraph', flow, step, '0', 'weight', metric) is not None: if metric not in metric_list: metric_list.append(metric) # print out all metrics metrics = [] for metric in metric_list: metrics.append(" " + metric) row = [] for step in steplist: for index in indices_to_show[step]: value = None if 'real' in self.getkeys('metric', step, index, metric): value = self.get('metric', step, index, metric, 'real') if value is None: value = 'ERR' else: value = str(value) row.append(" " + value.center(colwidth)) data.append(row) pandas.set_option('display.max_rows', 500) pandas.set_option('display.max_columns', 500) pandas.set_option('display.width', 100) df = pandas.DataFrame(data, metrics, header) print(df.to_string()) print("-"*135) # Create a report for the Chip object which can be viewed in a web browser. # Place report files in the build's root directory. web_dir = os.path.join(self.get('dir'), self.get('design'), self.get('jobname')) if os.path.isdir(web_dir): # Gather essential variables. templ_dir = os.path.join(self.scroot, 'templates', 'report') flow = self.get('flow') flow_steps = steplist flow_tasks = {} for step in flow_steps: flow_tasks[step] = self.getkeys('flowgraph', flow, step) # Copy Bootstrap JS/CSS shutil.copyfile(os.path.join(templ_dir, 'bootstrap.min.js'), os.path.join(web_dir, 'bootstrap.min.js')) shutil.copyfile(os.path.join(templ_dir, 'bootstrap.min.css'), os.path.join(web_dir, 'bootstrap.min.css')) # Call 'show()' to generate a low-res PNG of the design. results_gds = self.find_result('gds', step='export') if results_gds: self.show(results_gds, ['-rd', 'screenshot=1', '-rd', 'scr_w=1024', '-rd', 'scr_h=1024', '-z']) # Generate results page by passing the Chip manifest into the Jinja2 template. env = Environment(loader=FileSystemLoader(templ_dir)) results_page = os.path.join(web_dir, 'report.html') with open(results_page, 'w') as wf: wf.write(env.get_template('sc_report.j2').render( manifest = self.cfg, metric_keys = metric_list, metrics = self.cfg['metric'], tasks = flow_tasks, results_fn = results_gds )) # Try to open the results page in a browser, only if '-nodisplay' is not set. if not self.get('nodisplay'): try: webbrowser.get(results_page) except webbrowser.Error: # Python 'webbrowser' module includes a limited number of popular defaults. # Depending on the platform, the user may have defined their own with $BROWSER. if 'BROWSER' in os.environ: subprocess.run([os.environ['BROWSER'], results_page]) else: self.logger.warning('Unable to open results page in web browser:\n' + os.path.abspath(os.path.join(web_dir, "report.html"))) ########################################################################### def list_steps(self, flow=None): ''' Returns an ordered list of flowgraph steps. All step keys from the flowgraph dictionary are collected and the distance from the root node (ie. without any inputs defined) is measured for each step. The step list is then sorted based on the distance from root and returned. Returns: A list of steps sorted by distance from the root node. Example: >>> steplist = chip.list_steps() Variable steplist gets list of steps sorted by distance from root. ''' if flow is None: flow = self.get('flow') #Get length of paths from step to root depth = {} for step in self.getkeys('flowgraph', flow): depth[step] = 0 for path in self._allpaths(self.cfg, flow, step, str(0)): if len(list(path)) > depth[step]: depth[step] = len(path) #Sort steps based on path lenghts sorted_dict = dict(sorted(depth.items(), key=lambda depth: depth[1])) return list(sorted_dict.keys()) ########################################################################### def _allpaths(self, cfg, flow, step, index, path=None): '''Recursive helper for finding all paths from provided step, index to root node(s) with no inputs. Returns a list of lists. ''' if path is None: path = [] inputs = self.get('flowgraph', flow, step, index, 'input', cfg=cfg) if not self.get('flowgraph', flow, step, index, 'input', cfg=cfg): return [path] else: allpaths = [] for in_step, in_index in inputs: newpath = path.copy() newpath.append(in_step + in_index) allpaths.extend(self._allpaths(cfg, flow, in_step, in_index, path=newpath)) return allpaths ########################################################################### def clock(self, *, name, pin, period, jitter=0): """ Clock configuration helper function. A utility function for setting all parameters associated with a single clock definition in the schema. The method modifies the following schema parameters: ['clock', name, 'pin'] ['clock', name, 'period'] ['clock', name, 'jitter'] Args: name (str): Clock reference name. pin (str): Full hiearchical path to clk pin. period (float): Clock period specified in ns. jitter (float): Clock jitter specified in ns. Examples: >>> chip.clock(name='clk', pin='clk, period=1.0) Create a clock namedd 'clk' with a 1.0ns period. """ self.set('clock', name, 'pin', pin) self.set('clock', name, 'period', period) self.set('clock', name, 'jitter', jitter) ########################################################################### def node(self, flow, step, tool, index=0): ''' Creates a flowgraph node. Creates a flowgraph node by binding a tool to a task. A task is defined as the combination of a step and index. A tool can be an external exeuctable or one of the built in functions in the SiliconCompiler framework). Built in functions include: minimum, maximum, join, mux, verify. The method modifies the following schema parameters: ['flowgraph', flow, step, index, 'tool', tool] ['flowgraph', flow, step, index, 'weight', metric] Args: flow (str): Flow name step (str): Task step name tool (str): Tool (or builtin function) to associate with task. index (int): Task index Examples: >>> chip.node('asicflow', 'place', 'openroad', index=0) Creates a task with step='place' and index=0 and binds it to the 'openroad' tool. ''' # bind tool to node self.set('flowgraph', flow, step, str(index), 'tool', tool) # set default weights for metric in self.getkeys('metric', 'default', 'default'): self.set('flowgraph', flow, step, str(index), 'weight', metric, 0) ########################################################################### def edge(self, flow, tail, head, tail_index=0, head_index=0): ''' Creates a directed edge from a tail node to a head node. Connects the output of a tail node with the input of a head node by setting the 'input' field of the head node in the schema flowgraph. The method modifies the following parameters: ['flowgraph', flow, head, str(head_index), 'input'] Args: flow (str): Name of flow tail (str): Name of tail node head (str): Name of head node tail_index (int): Index of tail node to connect head_index (int): Index of head node to connect Examples: >>> chip.edge('place', 'cts') Creates a directed edge from place to cts. ''' self.add('flowgraph', flow, head, str(head_index), 'input', (tail, str(tail_index))) ########################################################################### def join(self, *tasks): ''' Merges outputs from a list of input tasks. Args: tasks(list): List of input tasks specified as (step,index) tuples. Returns: Input list Examples: >>> select = chip.join([('lvs','0'), ('drc','0')]) Select gets the list [('lvs','0'), ('drc','0')] ''' tasklist = list(tasks) sel_inputs = tasklist # no score for join, so just return 0 return sel_inputs ########################################################################### def nop(self, *task): ''' A no-operation that passes inputs to outputs. Args: task(list): Input task specified as a (step,index) tuple. Returns: Input task Examples: >>> select = chip.nop(('lvs','0')) Select gets the tuple [('lvs',0')] ''' return list(task) ########################################################################### def minimum(self, *tasks): ''' Selects the task with the minimum metric score from a list of inputs. Sequence of operation: 1. Check list of input tasks to see if all metrics meets goals 2. Check list of input tasks to find global min/max for each metric 3. Select MIN value if all metrics are met. 4. Normalize the min value as sel = (val - MIN) / (MAX - MIN) 5. Return normalized value and task name Meeting metric goals takes precedence over compute metric scores. Only goals with values set and metrics with weights set are considered in the calculation. Args: tasks(list): List of input tasks specified as (step,index) tuples. Returns: tuple containing - score (float): Minimum score - task (tuple): Task with minimum score Examples: >>> (score, task) = chip.minimum([('place','0'),('place','1')]) ''' return self._minmax(*tasks, op="minimum") ########################################################################### def maximum(self, *tasks): ''' Selects the task with the maximum metric score from a list of inputs. Sequence of operation: 1. Check list of input tasks to see if all metrics meets goals 2. Check list of input tasks to find global min/max for each metric 3. Select MAX value if all metrics are met. 4. Normalize the min value as sel = (val - MIN) / (MAX - MIN) 5. Return normalized value and task name Meeting metric goals takes precedence over compute metric scores. Only goals with values set and metrics with weights set are considered in the calculation. Args: tasks(list): List of input tasks specified as (step,index) tuples. Returns: tuple containing - score (float): Maximum score. - task (tuple): Task with minimum score Examples: >>> (score, task) = chip.maximum([('place','0'),('place','1')]) ''' return self._minmax(*tasks, op="maximum") ########################################################################### def _minmax(self, *steps, op="minimum", **selector): ''' Shared function used for min and max calculation. ''' if op not in ('minimum', 'maximum'): raise ValueError('Invalid op') flow = self.get('flow') steplist = list(steps) # Keeping track of the steps/indexes that have goals met failed = {} for step, index in steplist: if step not in failed: failed[step] = {} failed[step][index] = False if self.get('flowstatus', step, index, 'error'): failed[step][index] = True else: for metric in self.getkeys('metric', step, index): if 'goal' in self.getkeys('metric', step, index, metric): goal = self.get('metric', step, index, metric, 'goal') real = self.get('metric', step, index, metric, 'real') if abs(real) > goal: self.logger.warning(f"Step {step}{index} failed " f"because it didn't meet goals for '{metric}' " "metric.") failed[step][index] = True # Calculate max/min values for each metric max_val = {} min_val = {} for metric in self.getkeys('flowgraph', flow, step, '0', 'weight'): max_val[metric] = 0 min_val[metric] = float("inf") for step, index in steplist: if not failed[step][index]: real = self.get('metric', step, index, metric, 'real') max_val[metric] = max(max_val[metric], real) min_val[metric] = min(min_val[metric], real) # Select the minimum index best_score = float('inf') if op == 'minimum' else float('-inf') winner = None for step, index in steplist: if failed[step][index]: continue score = 0.0 for metric in self.getkeys('flowgraph', flow, step, index, 'weight'): weight = self.get('flowgraph', flow, step, index, 'weight', metric) if not weight: # skip if weight is 0 or None continue real = self.get('metric', step, index, metric, 'real') if not (max_val[metric] - min_val[metric]) == 0: scaled = (real - min_val[metric]) / (max_val[metric] - min_val[metric]) else: scaled = max_val[metric] score = score + scaled * weight if ((op == 'minimum' and score < best_score) or (op == 'maximum' and score > best_score)): best_score = score winner = (step,index) return (best_score, winner) ########################################################################### def verify(self, *tasks, **assertion): ''' Tests an assertion on a list of input tasks. The provided steplist is verified to ensure that all assertions are True. If any of the assertions fail, False is returned. Assertions are passed in as kwargs, with the key being a metric and the value being a number and an optional conditional operator. The allowed conditional operators are: >, <, >=, <= Args: *steps (str): List of steps to verify **assertion (str='str'): Assertion to check on metric Returns: True if all assertions hold True for all steps. Example: >>> pass = chip.verify(['drc','lvs'], errors=0) Pass is True if the error metrics in the drc, lvs steps is 0. ''' #TODO: implement return True ########################################################################### def mux(self, *tasks, **selector): ''' Selects a task from a list of inputs. The selector criteria provided is used to create a custom function for selecting the best step/index pair from the inputs. Metrics and weights are passed in and used to select the step/index based on the minimum or maximum score depending on the 'op' argument. The function can be used to bypass the flows weight functions for the purpose of conditional flow execution and verification. Args: *steps (str): List of steps to verify **selector: Key value selection criteria. Returns: True if all assertions hold True for all steps. Example: >>> sel_stepindex = chip.mux(['route'], wirelength=0) Selects the routing stepindex with the shortest wirelength. ''' #TODO: modify the _minmax function to feed in alternate weight path return None ########################################################################### def _runtask_safe(self, step, index, active, error): try: self._init_logger(step, index) except: traceback.print_exc() print(f"Uncaught exception while initializing logger for step {step}") self.error = 1 self._haltstep(step, index, active, log=False) try: self._runtask(step, index, active, error) except SystemExit: # calling sys.exit() in _haltstep triggers a "SystemExit" # exception, but we can ignore these -- if we call sys.exit(), we've # already handled the error. pass except: traceback.print_exc() self.logger.error(f"Uncaught exception while running step {step}.") self.error = 1 self._haltstep(step, index, active) ########################################################################### def _runtask(self, step, index, active, error): ''' Private per step run method called by run(). The method takes in a step string and index string to indicated what to run. Execution state coordinated through the active/error multiprocessing Manager dicts. Execution flow: T1. Wait in loop until all previous steps/indexes have completed T2. Start wall timer T3. Defer job to compute node if using job scheduler T4. Set up working directory + chdir T5. Merge manifests from all input dependancies T6. Write manifest to input directory for convenience T7. Reset all metrics to 0 (consider removing) T8. Select inputs T9. Copy data from previous step outputs into inputs T10. Copy reference script directory T11. Check manifest T12. Run pre_process() function T13. Set environment variables T14. Check EXE version T15. Save manifest as TCL/YAML T16. Start CPU timer T17. Run EXE T18. stop CPU timer T19. Run post_process() T20. Check log file T21. Hash all task files T22. Stop Wall timer T23. Make a task record T24. Save manifest to disk T25. Clean up T26. chdir T27. clear error/active bits and return control to run() Note that since _runtask occurs in its own process with a separate address space, any changes made to the `self` object will not be reflected in the parent. We rely on reading/writing the chip manifest to the filesystem to communicate updates between processes. ''' ################## # Shared parameters (long function!) design = self.get('design') flow = self.get('flow') tool = self.get('flowgraph', flow, step, index, 'tool') quiet = self.get('quiet') and (step not in self.get('bkpt')) ################## # 1. Wait loop self.logger.info('Waiting for inputs...') while True: # Checking that there are no pending jobs pending = 0 for in_step, in_index in self.get('flowgraph', flow, step, index, 'input'): pending = pending + active[in_step + in_index] # beak out of loop when no all inputs are done if not pending: break # Short sleep time.sleep(0.1) ################## # 2. Start wall timer wall_start = time.time() ################## # 3. Defer job to compute node # If the job is configured to run on a cluster, collect the schema # and send it to a compute node for deferred execution. # (Run the initial 'import' stage[s] locally) wall_start = time.time() if self.get('jobscheduler') and \ self.get('flowgraph', flow, step, index, 'input'): # Note: The _deferstep method blocks until the compute node # finishes processing this step, and it sets the active/error bits. _deferstep(self, step, index, active, error) return ################## # 4. Directory setup # support for sharing data across jobs job = self.get('jobname') in_job = job if job in self.getkeys('jobinput'): if step in self.getkeys('jobinput',job): if index in self.getkeys('jobinput',job,step): in_job = self.get('jobinput', job, step, index) workdir = self._getworkdir(step=step,index=index) cwd = os.getcwd() if os.path.isdir(workdir): shutil.rmtree(workdir) os.makedirs(workdir, exist_ok=True) os.chdir(workdir) os.makedirs('outputs', exist_ok=True) os.makedirs('reports', exist_ok=True) ################## # 5. Merge manifests from all input dependancies all_inputs = [] if not self.get('remote'): for in_step, in_index in self.get('flowgraph', flow, step, index, 'input'): index_error = error[in_step + in_index] self.set('flowstatus', in_step, in_index, 'error', index_error) if not index_error: cfgfile = f"../../../{in_job}/{in_step}/{in_index}/outputs/{design}.pkg.json" self.read_manifest(cfgfile, clobber=False) ################## # 6. Write manifest prior to step running into inputs self.set('arg', 'step', None, clobber=True) self.set('arg', 'index', None, clobber=True) os.makedirs('inputs', exist_ok=True) #self.write_manifest(f'inputs/{design}.pkg.json') ################## # 7. Reset metrics to zero # TODO: There should be no need for this, but need to fix # without it we need to be more careful with flows to make sure # things like the builtin functions don't look at None values for metric in self.getkeys('metric', 'default', 'default'): self.set('metric', step, index, metric, 'real', 0) ################## # 8. Select inputs args = self.get('flowgraph', flow, step, index, 'args') inputs = self.get('flowgraph', flow, step, index, 'input') sel_inputs = [] score = 0 if tool in self.builtin: self.logger.info(f"Running built in task '{tool}'") # Figure out which inputs to select if tool == 'minimum': (score, sel_inputs) = self.minimum(*inputs) elif tool == "maximum": (score, sel_inputs) = self.maximum(*inputs) elif tool == "mux": (score, sel_inputs) = self.mux(*inputs, selector=args) elif tool == "join": sel_inputs = self.join(*inputs) elif tool == "verify": if not self.verify(*inputs, assertion=args): self._haltstep(step, index, active) else: sel_inputs = self.get('flowgraph', flow, step, index, 'input') if sel_inputs == None: self.logger.error(f'No inputs selected after running {tool}') self._haltstep(step, index, active) self.set('flowstatus', step, index, 'select', sel_inputs) ################## # 9. Copy (link) output data from previous steps if step == 'import': self._collect(step, index, active) if not self.get('flowgraph', flow, step, index,'input'): all_inputs = [] elif not self.get('flowstatus', step, index, 'select'): all_inputs = self.get('flowgraph', flow, step, index,'input') else: all_inputs = self.get('flowstatus', step, index, 'select') for in_step, in_index in all_inputs: if self.get('flowstatus', in_step, in_index, 'error') == 1: self.logger.error(f'Halting step due to previous error in {in_step}{in_index}') self._haltstep(step, index, active) # Skip copying pkg.json files here, since we write the current chip # configuration into inputs/{design}.pkg.json earlier in _runstep. utils.copytree(f"../../../{in_job}/{in_step}/{in_index}/outputs", 'inputs/', dirs_exist_ok=True, ignore=[f'{design}.pkg.json'], link=True) ################## # 10. Copy Reference Scripts if tool not in self.builtin: if self.get('eda', tool, 'copy'): refdir = self.find_files('eda', tool, 'refdir', step, index) utils.copytree(refdir, ".", dirs_exist_ok=True) ################## # 11. Check manifest self.set('arg', 'step', step, clobber=True) self.set('arg', 'index', index, clobber=True) if not self.get('skip', 'check'): if self.check_manifest(): self.logger.error(f"Fatal error in check_manifest()! See previous errors.") self._haltstep(step, index, active) ################## # 12. Run preprocess step for tool if tool not in self.builtin: func = self.find_function(tool, "pre_process", 'tools') if func: func(self) if self.error: self.logger.error(f"Pre-processing failed for '{tool}'") self._haltstep(step, index, active) ################## # 13. Set environment variables # License file configuration. for item in self.getkeys('eda', tool, 'licenseserver'): license_file = self.get('eda', tool, 'licenseserver', item) if license_file: os.environ[item] = ':'.join(license_file) # Tool-specific environment variables for this task. if (step in self.getkeys('eda', tool, 'environment')) and \ (index in self.getkeys('eda', tool, 'environment', step)): for item in self.getkeys('eda', tool, 'environment', step, index): os.environ[item] = self.get('eda', tool, 'environment', step, index, item) ################## # 14. Check exe version vercheck = self.get('vercheck') veropt = self.get('eda', tool, 'vswitch') exe = self._getexe(tool) version = None if (veropt is not None) and (exe is not None): cmdlist = [exe] cmdlist.extend(veropt) proc = subprocess.run(cmdlist, stdout=PIPE, stderr=subprocess.STDOUT, universal_newlines=True) parse_version = self.find_function(tool, 'parse_version', 'tools') if parse_version is None: self.logger.error(f'{tool} does not implement parse_version.') self._haltstep(step, index, active) version = parse_version(proc.stdout) self.logger.info(f"Checking executable. Tool '{exe}' found with version '{version}'") if vercheck: allowed_versions = self.get('eda', tool, 'version') if allowed_versions and version not in allowed_versions: allowedstr = ', '.join(allowed_versions) self.logger.error(f"Version check failed for {tool}. Check installation.") self.logger.error(f"Found version {version}, expected one of [{allowedstr}].") self._haltstep(step, index, active) ################## # 15. Write manifest (tool interface) (Don't move this!) suffix = self.get('eda', tool, 'format') if suffix: pruneopt = bool(suffix!='tcl') self.write_manifest(f"sc_manifest.{suffix}", prune=pruneopt, abspath=True) ################## # 16. Start CPU Timer self.logger.debug(f"Starting executable") cpu_start = time.time() ################## # 17. Run executable (or copy inputs to outputs for builtin functions) if tool in self.builtin: utils.copytree(f"inputs", 'outputs', dirs_exist_ok=True, link=True) elif not self.get('skip', 'all'): cmdlist = self._makecmd(tool, step, index) cmdstr = ' '.join(cmdlist) self.logger.info("Running in %s", workdir) self.logger.info('%s', cmdstr) timeout = self.get('flowgraph', flow, step, index, 'timeout') logfile = step + '.log' with open(logfile, 'w') as log_writer, open(logfile, 'r') as log_reader: # Use separate reader/writer file objects as hack to display # live output in non-blocking way, so we can monitor the # timeout. Based on https://stackoverflow.com/a/18422264. cmd_start_time = time.time() proc = subprocess.Popen(cmdlist, stdout=log_writer, stderr=subprocess.STDOUT) while proc.poll() is None: # Loop until process terminates if not quiet: sys.stdout.write(log_reader.read()) if timeout is not None and time.time() - cmd_start_time > timeout: self.logger.error(f'Step timed out after {timeout} seconds') proc.terminate() self._haltstep(step, index, active) time.sleep(0.1) # Read the remaining if not quiet: sys.stdout.write(log_reader.read()) if proc.returncode != 0: self.logger.warning('Command failed. See log file %s', os.path.abspath(logfile)) if not self.get('eda', tool, 'continue'): self._haltstep(step, index, active) ################## # 18. Capture cpu runtime cpu_end = time.time() cputime = round((cpu_end - cpu_start),2) self.set('metric',step, index, 'exetime', 'real', cputime) ################## # 19. Post process (could fail) post_error = 0 if (tool not in self.builtin) and (not self.get('skip', 'all')) : func = self.find_function(tool, 'post_process', 'tools') if func: post_error = func(self) if post_error: self.logger.error('Post-processing check failed') self._haltstep(step, index, active) ################## # 20. Check log file (must be after post-process) if (tool not in self.builtin) and (not self.get('skip', 'all')) : self.check_logfile(step=step, index=index, display=not quiet) ################## # 21. Hash files if self.get('hash') and (tool not in self.builtin): # hash all outputs self.hash_files('eda', tool, 'output', step, index) # hash all requirements if self.valid('eda', tool, 'require', step, index, quiet=True): for item in self.get('eda', tool, 'require', step, index): args = item.split(',') if 'file' in self.get(*args, field='type'): self.hash_files(*args) ################## # 22. Capture wall runtime wall_end = time.time() walltime = round((wall_end - wall_start),2) self.set('metric',step, index, 'tasktime', 'real', walltime) ################## # 23. Make a record if tracking is enabled if self.get('track'): self._make_record(job, step, index, wall_start, wall_end, version) ################## # 24. Save a successful manifest self.set('flowstatus', step, str(index), 'error', 0) self.set('arg', 'step', None, clobber=True) self.set('arg', 'index', None, clobber=True) self.write_manifest("outputs/" + self.get('design') +'.pkg.json') ################## # 25. Clean up non-essential files if self.get('clean'): self.logger.error('Self clean not implemented') ################## # 26. return to original directory os.chdir(cwd) ################## # 27. clearing active and error bits # !!Do not move this code!! error[step + str(index)] = 0 active[step + str(index)] = 0 ########################################################################### def _haltstep(self, step, index, active, log=True): if log: self.logger.error(f"Halting step '{step}' index '{index}' due to errors.") active[step + str(index)] = 0 sys.exit(1) ########################################################################### def run(self): ''' Executes tasks in a flowgraph. The run function sets up tools and launches runs for every index in a step defined by a steplist. The steplist is taken from the schema steplist parameter if defined, otherwise the steplist is defined as the list of steps within the schema flowgraph dictionary. Before starting the process, tool modules are loaded and setup up for each step and index based on on the schema eda dictionary settings. Once the tools have been set up, the manifest is checked using the check_manifest() function and files in the manifest are hashed based on the 'hashmode' schema setting. Once launched, each process waits for preceding steps to complete, as defined by the flowgraph 'inputs' parameter. Once a all inputs are ready, previous steps are checked for errors before the process entered a local working directory and starts to run a tool or to execute a built in Chip function. Fatal errors within a step/index process cause all subsequent processes to exit before start, returning control to the the main program which can then exit. Examples: >>> run() Runs the execution flow defined by the flowgraph dictionary. ''' flow = self.get('flow') if not flow in self.getkeys('flowgraph'): # If not a pre-loaded flow, we'll assume that 'flow' specifies a # single-step tool run with flow being the name of the tool. Set up # a basic flowgraph for this tool with a no-op import and default # weights. tool = flow step = self.get('arg', 'step') if step is None: self.logger.error('arg, step must be specified for single tool flow.') self.set('flowgraph', flow, step, '0', 'tool', tool) self.set('flowgraph', flow, step, '0', 'weight', 'errors', 0) self.set('flowgraph', flow, step, '0', 'weight', 'warnings', 0) self.set('flowgraph', flow, step, '0', 'weight', 'runtime', 0) if step != 'import': self.set('flowgraph', flow, step, '0', 'input', ('import','0')) self.set('flowgraph', flow, 'import', '0', 'tool', 'nop') self.set('arg', 'step', None) # Run steps if set, otherwise run whole graph if self.get('arg', 'step'): steplist = [self.get('arg', 'step')] elif self.get('steplist'): steplist = self.get('steplist') else: steplist = self.list_steps() # If no step(list) was specified, the whole flow is being run # start-to-finish. Delete the build dir to clear stale results. cur_job_dir = f'{self.get("dir")}/{self.get("design")}/'\ f'{self.get("jobname")}' if os.path.isdir(cur_job_dir): shutil.rmtree(cur_job_dir) # List of indices to run per step. Precomputing this ensures we won't # have any problems if [arg, index] gets clobbered, and reduces logic # repetition. indexlist = {} for step in steplist: if self.get('arg', 'index'): indexlist[step] = [self.get('arg', 'index')] elif self.get('indexlist'): indexlist[step] = self.get('indexlist') else: indexlist[step] = self.getkeys('flowgraph', flow, step) # Set env variables for envvar in self.getkeys('env'): val = self.get('env', envvar) os.environ[envvar] = val # Remote workflow: Dispatch the Chip to a remote server for processing. if self.get('remote'): # Load the remote storage config into the status dictionary. if self.get('credentials'): # Use the provided remote credentials file. cfg_file = self.get('credentials')[-1] cfg_dir = os.path.dirname(cfg_file) else: # Use the default config file path. cfg_dir = os.path.join(Path.home(), '.sc') cfg_file = os.path.join(cfg_dir, 'credentials') if (not os.path.isdir(cfg_dir)) or (not os.path.isfile(cfg_file)): self.logger.error('Could not find remote server configuration - please run "sc-configure" and enter your server address and credentials.') sys.exit(1) with open(cfg_file, 'r') as cfgf: self.status['remote_cfg'] = json.loads(cfgf.read()) if (not 'address' in self.status['remote_cfg']): self.logger.error('Improperly formatted remote server configuration - please run "sc-configure" and enter your server address and credentials.') sys.exit(1) # Pre-process: Run an 'import' stage locally, and upload the # in-progress build directory to the remote server. # Data is encrypted if user / key were specified. # run remote process remote_preprocess(self) # Run the job on the remote server, and wait for it to finish. remote_run(self) # Fetch results (and delete the job's data from the server). fetch_results(self) else: manager = multiprocessing.Manager() error = manager.dict() active = manager.dict() # Launch a thread for eact step in flowgraph # Use a shared even for errors # Use a manager.dict for keeping track of active processes # (one unqiue dict entry per process), # Set up tools and processes for step in self.getkeys('flowgraph', flow): for index in self.getkeys('flowgraph', flow, step): stepstr = step + index if step in steplist and index in indexlist[step]: self.set('flowstatus', step, str(index), 'error', 1) error[stepstr] = self.get('flowstatus', step, str(index), 'error') active[stepstr] = 1 # Setting up tool is optional tool = self.get('flowgraph', flow, step, index, 'tool') if tool not in self.builtin: self.set('arg','step', step) self.set('arg','index', index) func = self.find_function(tool, 'setup', 'tools') if func is None: self.logger.error(f'setup() not found for tool {tool}') sys.exit(1) func(self) # Need to clear index, otherwise we will skip # setting up other indices. Clear step for good # measure. self.set('arg','step', None) self.set('arg','index', None) else: self.set('flowstatus', step, str(index), 'error', 0) error[stepstr] = self.get('flowstatus', step, str(index), 'error') active[stepstr] = 0 # Implement auto-update of jobincrement try: alljobs = os.listdir(self.get('dir') + "/" + self.get('design')) if self.get('jobincr'): jobid = 0 for item in alljobs: m = re.match(self.get('jobname')+r'(\d+)', item) if m: jobid = max(jobid, int(m.group(1))) self.set('jobid', str(jobid + 1)) except: pass # Check validity of setup self.logger.info("Checking manifest before running.") if not self.get('skip', 'check'): self.check_manifest() # Check if there were errors before proceeding with run if self.error: self.logger.error(f"Check failed. See previous errors.") sys.exit() # Create all processes processes = [] for step in steplist: for index in indexlist[step]: processes.append(multiprocessing.Process(target=self._runtask_safe, args=(step, index, active, error,))) # We have to deinit the chip's logger before spawning the processes # since the logger object is not serializable. _runtask_safe will # reinitialize the logger in each new process, and we reinitialize # the primary chip's logger after the processes complete. self._deinit_logger() # Start all processes for p in processes: p.start() # Mandatory process cleanup for p in processes: p.join() self._init_logger() # Make a clean exit if one of the steps failed halt = 0 for step in steplist: index_error = 1 for index in indexlist[step]: stepstr = step + index index_error = index_error & error[stepstr] halt = halt + index_error if halt: self.logger.error('Run() failed, exiting! See previous errors.') sys.exit(1) # Clear scratchpad args since these are checked on run() entry self.set('arg', 'step', None, clobber=True) self.set('arg', 'index', None, clobber=True) # Merge cfg back from last executed runsteps. # Note: any information generated in steps that do not merge into the # last step will not be picked up in this chip object. laststep = steplist[-1] last_step_failed = True for index in indexlist[laststep]: lastdir = self._getworkdir(step=laststep, index=index) # This no-op listdir operation is important for ensuring we have a # consistent view of the filesystem when dealing with NFS. Without # this, this thread is often unable to find the final manifest of # runs performed on job schedulers, even if they completed # successfully. Inspired by: https://stackoverflow.com/a/70029046. os.listdir(os.path.dirname(lastdir)) lastcfg = f"{lastdir}/outputs/{self.get('design')}.pkg.json" if os.path.isfile(lastcfg): last_step_failed = False local_dir = self.get('dir') self.read_manifest(lastcfg, clobber=True, clear=True) self.set('dir', local_dir) if last_step_failed: # Hack to find first failed step by checking for presence of output # manifests. failed_step = laststep for step in steplist[:-1]: step_has_cfg = False for index in indexlist[step]: stepdir = self._getworkdir(step=step, index=index) cfg = f"{stepdir}/outputs/{self.get('design')}.pkg.json" if os.path.isfile(cfg): step_has_cfg = True break if not step_has_cfg: failed_step = step break stepdir = self._getworkdir(step=failed_step)[:-1] self.logger.error(f'Run() failed on step {failed_step}, exiting! ' f'See logs in {stepdir} for error details.') sys.exit(1) # Store run in history self.cfghistory[self.get('jobname')] = copy.deepcopy(self.cfg) ########################################################################### def show(self, filename=None, extra_options=[]): ''' Opens a graphical viewer for the filename provided. The show function opens the filename specified using a viewer tool selected based on the file suffix and the 'showtool' schema setup. The 'showtool' parameter binds tools with file suffixes, enabling the automated dynamic loading of tool setup functions from siliconcompiler.tools.<tool>/<tool>.py. Display settings and technology settings for viewing the file are read from the in-memory chip object schema settings. All temporary render and display files are saved in the <build_dir>/_show directory. The show() command can also be used to display content from an SC schema .json filename provided. In this case, the SC schema is converted to html and displayed as a 'dashboard' in the browser. Filenames with .gz and .zip extensions are automatically unpacked before being displayed. Args: filename: Name of file to display Examples: >>> show('build/oh_add/job0/export/0/outputs/oh_add.gds') Displays gds file with a viewer assigned by 'showtool' >>> show('build/oh_add/job0/export/0/outputs/oh_add.pkg.json') Displays manifest in the browser ''' self.logger.info("Showing file %s", filename) # Finding lasts layout if no argument specified if filename is None: design = self.get('design') laststep = self.list_steps()[-1] lastindex = '0' lastdir = self._getworkdir(step=laststep, index=lastindex) gds_file= f"{lastdir}/outputs/{design}.gds" def_file = f"{lastdir}/outputs/{design}.def" if os.path.isfile(gds_file): filename = gds_file elif os.path.isfile(def_file): filename = def_file # Parsing filepath filepath = os.path.abspath(filename) basename = os.path.basename(filepath) localfile = basename.replace(".gz","") filetype = os.path.splitext(localfile)[1].lower().replace(".","") #Check that file exists if not os.path.isfile(filepath): self.logger.error(f"Invalid filepath {filepath}.") return 1 # Opening file from temp directory cwd = os.getcwd() showdir = self.get('dir') + "/_show" os.makedirs(showdir, exist_ok=True) os.chdir(showdir) # Uncompress file if necessary if os.path.splitext(filepath)[1].lower() == ".gz": with gzip.open(filepath, 'rb') as f_in: with open(localfile, 'wb') as f_out: shutil.copyfileobj(f_in, f_out) else: shutil.copy(filepath, localfile) #Figure out which tool to use for opening data if filetype in self.getkeys('showtool'): # Using env variable and manifest to pass arguments os.environ['SC_FILENAME'] = localfile self.write_manifest("sc_manifest.tcl", abspath=True) self.write_manifest("sc_manifest.json", abspath=True) # Setting up tool tool = self.get('showtool', filetype) step = 'show'+filetype index = "0" self.set('arg', 'step', step) self.set('arg', 'index', index) setup_tool = self.find_function(tool, 'setup', 'tools') setup_tool(self, mode='show') if extra_options: # Options must be pre-pended so that the input filename remains valid. cur_opts = self.get('eda', tool, 'option', step, index) self.set('eda', tool, 'option', step, index, extra_options + cur_opts, clobber=True) exe = self._getexe(tool) if shutil.which(exe) is None: self.logger.error(f'Executable {exe} not found.') success = False else: # Running command cmdlist = self._makecmd(tool, step, index) proc = subprocess.run(cmdlist) success = proc.returncode == 0 else: self.logger.error(f"Filetype '{filetype}' not set up in 'showtool' parameter.") success = False # Returning to original directory os.chdir(cwd) return success ############################################################################ # Chip helper Functions ############################################################################ def _typecheck(self, cfg, leafkey, value): ''' Schema type checking ''' ok = True valuetype = type(value) errormsg = "" if (not re.match(r'\[',cfg['type'])) & (valuetype==list): errormsg = "Value must be scalar." ok = False # Iterate over list else: # Create list for iteration if valuetype == list: valuelist = value else: valuelist = [value] # Make type python compatible cfgtype = re.sub(r'[\[\]]', '', cfg['type']) for item in valuelist: valuetype = type(item) if (cfgtype != valuetype.__name__): tupletype = re.match(r'\([\w\,]+\)',cfgtype) #TODO: check tuples! if tupletype: pass elif cfgtype == 'bool': if not item in ['true', 'false']: errormsg = "Valid boolean values are True/False/'true'/'false'" ok = False elif cfgtype == 'file': pass elif cfgtype == 'dir': pass elif (cfgtype == 'float'): try: float(item) except: errormsg = "Type mismatch. Cannot cast item to float." ok = False elif (cfgtype == 'int'): try: int(item) except: errormsg = "Type mismatch. Cannot cast item to int." ok = False elif item is not None: errormsg = "Type mismach." ok = False # Logger message if type(value) == list: printvalue = ','.join(map(str, value)) else: printvalue = str(value) errormsg = (errormsg + " Key=" + str(leafkey) + ", Expected Type=" + cfg['type'] + ", Entered Type=" + valuetype.__name__ + ", Value=" + printvalue) return (ok, errormsg) ####################################### def _getexe(self, tool): path = self.get('eda', tool, 'path') exe = self.get('eda', tool, 'exe') if exe is None: return None if path: exe_with_path = os.path.join(path, exe) else: exe_with_path = exe fullexe = self._resolve_env_vars(exe_with_path) return fullexe ####################################### def _makecmd(self, tool, step, index): ''' Constructs a subprocess run command based on eda tool setup. Creates a replay.sh command in current directory. ''' fullexe = self._getexe(tool) options = [] is_posix = ('win' not in sys.platform) for option in self.get('eda', tool, 'option', step, index): options.extend(shlex.split(option, posix=is_posix)) # Add scripts files if self.valid('eda', tool, 'script', step, index): scripts = self.find_files('eda', tool, 'script', step, index) else: scripts = [] cmdlist = [fullexe] logfile = step + ".log" cmdlist.extend(options) cmdlist.extend(scripts) runtime_options = self.find_function(tool, 'runtime_options', 'tools') if runtime_options: #print(runtime_options(self)) for option in runtime_options(self): cmdlist.extend(shlex.split(option, posix=is_posix)) #create replay file with open('replay.sh', 'w') as f: print('#!/bin/bash\n', ' '.join(cmdlist), file=f) os.chmod("replay.sh", 0o755) return cmdlist ####################################### def _get_cloud_region(self): # TODO: add logic to figure out if we're running on a remote cluster and # extract the region in a provider-specific way. return 'local' ####################################### def _make_record(self, job, step, index, start, end, toolversion): ''' Records provenance details for a runstep. ''' start_date = datetime.datetime.fromtimestamp(start).strftime('%Y-%m-%d %H:%M:%S') end_date = datetime.datetime.fromtimestamp(end).strftime('%Y-%m-%d %H:%M:%S') userid = getpass.getuser() self.set('record', job, step, index, 'userid', userid) scversion = self.get('version', 'sc') self.set('record', job, step, index, 'version', 'sc', scversion) if toolversion: self.set('record', job, step, index, 'version', 'tool', toolversion) self.set('record', job, step, index, 'starttime', start_date) self.set('record', job, step, index, 'endtime', end_date) machine = platform.node() self.set('record', job, step, index, 'machine', machine) self.set('record', job, step, index, 'region', self._get_cloud_region()) try: gateways = netifaces.gateways() ipaddr, interface = gateways['default'][netifaces.AF_INET] macaddr = netifaces.ifaddresses(interface)[netifaces.AF_LINK][0]['addr'] self.set('record', job, step, index, 'ipaddr', ipaddr) self.set('record', job, step, index, 'macaddr', macaddr) except KeyError: self.logger.warning('Could not find default network interface info') system = platform.system() if system == 'Darwin': lower_sys_name = 'macos' else: lower_sys_name = system.lower() self.set('record', job, step, index, 'platform', lower_sys_name) if system == 'Linux': distro_name = distro.id() self.set('record', job, step, index, 'distro', distro_name) if system == 'Darwin': osversion, _, _ = platform.mac_ver() elif system == 'Linux': osversion = distro.version() else: osversion = platform.release() self.set('record', job, step, index, 'version', 'os', osversion) if system == 'Linux': kernelversion = platform.release() elif system == 'Windows': kernelversion = platform.version() elif system == 'Darwin': kernelversion = platform.release() else: kernelversion = None if kernelversion: self.set('record', job, step, index, 'version', 'kernel', kernelversion) arch = platform.machine() self.set('record', job, step, index, 'arch', arch) ####################################### def _safecompare(self, value, op, goal): # supported relational oprations # >, >=, <=, <. ==, != if op == ">": return(bool(value>goal)) elif op == ">=": return(bool(value>=goal)) elif op == "<": return(bool(value<goal)) elif op == "<=": return(bool(value<=goal)) elif op == "==": return(bool(value==goal)) elif op == "!=": return(bool(value!=goal)) else: self.error = 1 self.logger.error(f"Illegal comparison operation {op}") ####################################### def _getworkdir(self, jobname=None, step=None, index='0'): '''Create a step directory with absolute path ''' if jobname is None: jobname = self.get('jobname') dirlist =[self.cwd, self.get('dir'), self.get('design'), jobname] # Return jobdirectory if no step defined # Return index 0 by default if step is not None: dirlist.append(step) dirlist.append(index) return os.path.join(*dirlist) ####################################### def _resolve_env_vars(self, filepath): resolved_path = os.path.expandvars(filepath) # variables that don't exist in environment get ignored by `expandvars`, # but we can do our own error checking to ensure this doesn't result in # silent bugs envvars = re.findall(r'\$(\w+)', resolved_path) for var in envvars: self.logger.warning(f'Variable {var} in {filepath} not defined in environment') return resolved_path ####################################### def _get_imported_filename(self, pathstr): ''' Utility to map collected file to an unambigious name based on its path. The mapping looks like: path/to/file.ext => file_<md5('path/to/file.ext')>.ext ''' path = pathlib.Path(pathstr) ext = ''.join(path.suffixes) # strip off all file suffixes to get just the bare name while path.suffix: path = pathlib.Path(path.stem) filename = str(path) pathhash = hashlib.sha1(pathstr.encode('utf-8')).hexdigest() return f'{filename}_{pathhash}{ext}' ############################################################################### # Package Customization classes ############################################################################### class YamlIndentDumper(yaml.Dumper): def increase_indent(self, flow=False, indentless=False): return super(YamlIndentDumper, self).increase_indent(flow, False)
39.537893
160
0.51509