ngram
listlengths
0
82k
[ "l): bin_args = map(lambda a: a.decode(_ENCODE), l) b = s.decode(_ENCODE)", "= s.decode(_ENCODE) return b.join(bin_args).encode(_ENCODE) logfile_open = open else: path_join =", "a: a.decode(_ENCODE), args) return os.path.join(*bin_args).encode(_ENCODE) def str_join(s, l): bin_args =", "a.decode(_ENCODE), l) b = s.decode(_ENCODE) return b.join(bin_args).encode(_ENCODE) logfile_open = open", "l) b = s.decode(_ENCODE) return b.join(bin_args).encode(_ENCODE) logfile_open = open else:", "else: path_join = os.path.join str_join = str.join def logfile_open(*args): return", "os import sys if sys.version_info[0] == 2: _ENCODE = sys.getfilesystemencoding()", "sys if sys.version_info[0] == 2: _ENCODE = sys.getfilesystemencoding() def path_join(*args):", "= map(lambda a: a.decode(_ENCODE), args) return os.path.join(*bin_args).encode(_ENCODE) def str_join(s, l):", "os.path.join(*bin_args).encode(_ENCODE) def str_join(s, l): bin_args = map(lambda a: a.decode(_ENCODE), l)", "import os import sys if sys.version_info[0] == 2: _ENCODE =", "sys.getfilesystemencoding() def path_join(*args): bin_args = map(lambda a: a.decode(_ENCODE), args) return", "sys.version_info[0] == 2: _ENCODE = sys.getfilesystemencoding() def path_join(*args): bin_args =", "= sys.getfilesystemencoding() def path_join(*args): bin_args = map(lambda a: a.decode(_ENCODE), args)", "b.join(bin_args).encode(_ENCODE) logfile_open = open else: path_join = os.path.join str_join =", "args) return os.path.join(*bin_args).encode(_ENCODE) def str_join(s, l): bin_args = map(lambda a:", "= os.path.join str_join = str.join def logfile_open(*args): return open(*args, errors='replace')", "map(lambda a: a.decode(_ENCODE), args) return os.path.join(*bin_args).encode(_ENCODE) def str_join(s, l): bin_args", "if sys.version_info[0] == 2: _ENCODE = sys.getfilesystemencoding() def path_join(*args): bin_args", "== 2: _ENCODE = sys.getfilesystemencoding() def path_join(*args): bin_args = map(lambda", "def str_join(s, l): bin_args = map(lambda a: a.decode(_ENCODE), l) b", "return b.join(bin_args).encode(_ENCODE) logfile_open = open else: path_join = os.path.join str_join", "= map(lambda a: a.decode(_ENCODE), l) b = s.decode(_ENCODE) return b.join(bin_args).encode(_ENCODE)", "= open else: path_join = os.path.join str_join = str.join def", "bin_args = map(lambda a: a.decode(_ENCODE), l) b = s.decode(_ENCODE) return", "path_join = os.path.join str_join = str.join def logfile_open(*args): return open(*args,", "s.decode(_ENCODE) return b.join(bin_args).encode(_ENCODE) logfile_open = open else: path_join = os.path.join", "path_join(*args): bin_args = map(lambda a: a.decode(_ENCODE), args) return os.path.join(*bin_args).encode(_ENCODE) def", "open else: path_join = os.path.join str_join = str.join def logfile_open(*args):", "import sys if sys.version_info[0] == 2: _ENCODE = sys.getfilesystemencoding() def", "a: a.decode(_ENCODE), l) b = s.decode(_ENCODE) return b.join(bin_args).encode(_ENCODE) logfile_open =", "def path_join(*args): bin_args = map(lambda a: a.decode(_ENCODE), args) return os.path.join(*bin_args).encode(_ENCODE)", "b = s.decode(_ENCODE) return b.join(bin_args).encode(_ENCODE) logfile_open = open else: path_join", "a.decode(_ENCODE), args) return os.path.join(*bin_args).encode(_ENCODE) def str_join(s, l): bin_args = map(lambda", "_ENCODE = sys.getfilesystemencoding() def path_join(*args): bin_args = map(lambda a: a.decode(_ENCODE),", "map(lambda a: a.decode(_ENCODE), l) b = s.decode(_ENCODE) return b.join(bin_args).encode(_ENCODE) logfile_open", "2: _ENCODE = sys.getfilesystemencoding() def path_join(*args): bin_args = map(lambda a:", "logfile_open = open else: path_join = os.path.join str_join = str.join", "str_join(s, l): bin_args = map(lambda a: a.decode(_ENCODE), l) b =", "bin_args = map(lambda a: a.decode(_ENCODE), args) return os.path.join(*bin_args).encode(_ENCODE) def str_join(s,", "return os.path.join(*bin_args).encode(_ENCODE) def str_join(s, l): bin_args = map(lambda a: a.decode(_ENCODE)," ]
[ "worker.result) error = False if worker.result is None: try: error", "self.assertIsNotNone(built_root, \"Environment variable `%s' not set\" % var) executable =", "\"part of extended tests\") class VOMTestCase(VppTestCase): \"\"\" VPP Object Model", "process\") if error: raise Exception( \"Timeout! Worker did not finish", "False if worker.result is None: try: error = True self.logger.error(", "VOMTestCase(VppTestCase): \"\"\" VPP Object Model Test \"\"\" def test_vom_cpp(self): \"\"\"", "worker.join() except: raise Exception(\"Couldn't kill worker-spawned process\") if error: raise", "in %ss\" % timeout) self.assert_equal(worker.result, 0, \"Binary test return code\")", "self.logger) worker.start() timeout = 120 worker.join(timeout) self.logger.info(\"Worker result is `%s'\"", "result is `%s'\" % worker.result) error = False if worker.result", "set\" % var) executable = \"%s/build/vom_test/vom_test\" % built_root worker =", "worker = Worker( [executable, \"vpp object model\", self.shm_prefix], self.logger) worker.start()", "running_extended_tests, \\ VppTestRunner, Worker @unittest.skipUnless(running_extended_tests(), \"part of extended tests\") class", "%ss\" % timeout) self.assert_equal(worker.result, 0, \"Binary test return code\") if", "`%s' not set\" % var) executable = \"%s/build/vom_test/vom_test\" % built_root", "raise Exception( \"Timeout! Worker did not finish in %ss\" %", "@unittest.skipUnless(running_extended_tests(), \"part of extended tests\") class VOMTestCase(VppTestCase): \"\"\" VPP Object", "signal.SIGTERM) worker.join() except: raise Exception(\"Couldn't kill worker-spawned process\") if error:", "= \"TEST_DIR\" built_root = os.getenv(var, None) self.assertIsNotNone(built_root, \"Environment variable `%s'", "finish in %ss\" % timeout) self.assert_equal(worker.result, 0, \"Binary test return", "test \"\"\" import unittest import os import signal from framework", "framework import VppTestCase, running_extended_tests, \\ VppTestRunner, Worker @unittest.skipUnless(running_extended_tests(), \"part of", "worker.join(timeout) self.logger.info(\"Worker result is `%s'\" % worker.result) error = False", "%ss\" % timeout) os.killpg(os.getpgid(worker.process.pid), signal.SIGTERM) worker.join() except: raise Exception(\"Couldn't kill", "VPP Object Model Test \"\"\" def test_vom_cpp(self): \"\"\" run C++", "error = False if worker.result is None: try: error =", "import os import signal from framework import VppTestCase, running_extended_tests, \\", "\"vpp object model\", self.shm_prefix], self.logger) worker.start() timeout = 120 worker.join(timeout)", "model\", self.shm_prefix], self.logger) worker.start() timeout = 120 worker.join(timeout) self.logger.info(\"Worker result", "of extended tests\") class VOMTestCase(VppTestCase): \"\"\" VPP Object Model Test", "kill worker-spawned process\") if error: raise Exception( \"Timeout! Worker did", "\"\"\" var = \"TEST_DIR\" built_root = os.getenv(var, None) self.assertIsNotNone(built_root, \"Environment", "os.killpg(os.getpgid(worker.process.pid), signal.SIGTERM) worker.join() except: raise Exception(\"Couldn't kill worker-spawned process\") if", "Object Model Test \"\"\" def test_vom_cpp(self): \"\"\" run C++ VOM", "#!/usr/bin/env python \"\"\" VAPI test \"\"\" import unittest import os", "= False if worker.result is None: try: error = True", "self.assert_equal(worker.result, 0, \"Binary test return code\") if __name__ == '__main__':", "worker.start() timeout = 120 worker.join(timeout) self.logger.info(\"Worker result is `%s'\" %", "Model Test \"\"\" def test_vom_cpp(self): \"\"\" run C++ VOM tests", "run C++ VOM tests \"\"\" var = \"TEST_DIR\" built_root =", "error = True self.logger.error( \"Timeout! Worker did not finish in", "\"\"\" import unittest import os import signal from framework import", "`%s'\" % worker.result) error = False if worker.result is None:", "os import signal from framework import VppTestCase, running_extended_tests, \\ VppTestRunner,", "raise Exception(\"Couldn't kill worker-spawned process\") if error: raise Exception( \"Timeout!", "= os.getenv(var, None) self.assertIsNotNone(built_root, \"Environment variable `%s' not set\" %", "Exception(\"Couldn't kill worker-spawned process\") if error: raise Exception( \"Timeout! Worker", "var) executable = \"%s/build/vom_test/vom_test\" % built_root worker = Worker( [executable,", "% timeout) os.killpg(os.getpgid(worker.process.pid), signal.SIGTERM) worker.join() except: raise Exception(\"Couldn't kill worker-spawned", "= \"%s/build/vom_test/vom_test\" % built_root worker = Worker( [executable, \"vpp object", "def test_vom_cpp(self): \"\"\" run C++ VOM tests \"\"\" var =", "in %ss\" % timeout) os.killpg(os.getpgid(worker.process.pid), signal.SIGTERM) worker.join() except: raise Exception(\"Couldn't", "None) self.assertIsNotNone(built_root, \"Environment variable `%s' not set\" % var) executable", "\"%s/build/vom_test/vom_test\" % built_root worker = Worker( [executable, \"vpp object model\",", "C++ VOM tests \"\"\" var = \"TEST_DIR\" built_root = os.getenv(var,", "Worker @unittest.skipUnless(running_extended_tests(), \"part of extended tests\") class VOMTestCase(VppTestCase): \"\"\" VPP", "self.logger.error( \"Timeout! Worker did not finish in %ss\" % timeout)", "\\ VppTestRunner, Worker @unittest.skipUnless(running_extended_tests(), \"part of extended tests\") class VOMTestCase(VppTestCase):", "worker-spawned process\") if error: raise Exception( \"Timeout! Worker did not", "[executable, \"vpp object model\", self.shm_prefix], self.logger) worker.start() timeout = 120", "import unittest import os import signal from framework import VppTestCase,", "not set\" % var) executable = \"%s/build/vom_test/vom_test\" % built_root worker", "try: error = True self.logger.error( \"Timeout! Worker did not finish", "built_root worker = Worker( [executable, \"vpp object model\", self.shm_prefix], self.logger)", "\"\"\" def test_vom_cpp(self): \"\"\" run C++ VOM tests \"\"\" var", "variable `%s' not set\" % var) executable = \"%s/build/vom_test/vom_test\" %", "\"Timeout! Worker did not finish in %ss\" % timeout) os.killpg(os.getpgid(worker.process.pid),", "if error: raise Exception( \"Timeout! Worker did not finish in", "did not finish in %ss\" % timeout) self.assert_equal(worker.result, 0, \"Binary", "class VOMTestCase(VppTestCase): \"\"\" VPP Object Model Test \"\"\" def test_vom_cpp(self):", "Worker( [executable, \"vpp object model\", self.shm_prefix], self.logger) worker.start() timeout =", "did not finish in %ss\" % timeout) os.killpg(os.getpgid(worker.process.pid), signal.SIGTERM) worker.join()", "\"Timeout! Worker did not finish in %ss\" % timeout) self.assert_equal(worker.result,", "import VppTestCase, running_extended_tests, \\ VppTestRunner, Worker @unittest.skipUnless(running_extended_tests(), \"part of extended", "not finish in %ss\" % timeout) os.killpg(os.getpgid(worker.process.pid), signal.SIGTERM) worker.join() except:", "Worker did not finish in %ss\" % timeout) os.killpg(os.getpgid(worker.process.pid), signal.SIGTERM)", "from framework import VppTestCase, running_extended_tests, \\ VppTestRunner, Worker @unittest.skipUnless(running_extended_tests(), \"part", "0, \"Binary test return code\") if __name__ == '__main__': unittest.main(testRunner=VppTestRunner)", "os.getenv(var, None) self.assertIsNotNone(built_root, \"Environment variable `%s' not set\" % var)", "% timeout) self.assert_equal(worker.result, 0, \"Binary test return code\") if __name__", "% built_root worker = Worker( [executable, \"vpp object model\", self.shm_prefix],", "is None: try: error = True self.logger.error( \"Timeout! Worker did", "\"\"\" run C++ VOM tests \"\"\" var = \"TEST_DIR\" built_root", "% var) executable = \"%s/build/vom_test/vom_test\" % built_root worker = Worker(", "test_vom_cpp(self): \"\"\" run C++ VOM tests \"\"\" var = \"TEST_DIR\"", "timeout) self.assert_equal(worker.result, 0, \"Binary test return code\") if __name__ ==", "timeout = 120 worker.join(timeout) self.logger.info(\"Worker result is `%s'\" % worker.result)", "is `%s'\" % worker.result) error = False if worker.result is", "executable = \"%s/build/vom_test/vom_test\" % built_root worker = Worker( [executable, \"vpp", "built_root = os.getenv(var, None) self.assertIsNotNone(built_root, \"Environment variable `%s' not set\"", "% worker.result) error = False if worker.result is None: try:", "object model\", self.shm_prefix], self.logger) worker.start() timeout = 120 worker.join(timeout) self.logger.info(\"Worker", "self.logger.info(\"Worker result is `%s'\" % worker.result) error = False if", "VAPI test \"\"\" import unittest import os import signal from", "error: raise Exception( \"Timeout! Worker did not finish in %ss\"", "extended tests\") class VOMTestCase(VppTestCase): \"\"\" VPP Object Model Test \"\"\"", "worker.result is None: try: error = True self.logger.error( \"Timeout! Worker", "signal from framework import VppTestCase, running_extended_tests, \\ VppTestRunner, Worker @unittest.skipUnless(running_extended_tests(),", "Exception( \"Timeout! Worker did not finish in %ss\" % timeout)", "= 120 worker.join(timeout) self.logger.info(\"Worker result is `%s'\" % worker.result) error", "\"Environment variable `%s' not set\" % var) executable = \"%s/build/vom_test/vom_test\"", "Test \"\"\" def test_vom_cpp(self): \"\"\" run C++ VOM tests \"\"\"", "None: try: error = True self.logger.error( \"Timeout! Worker did not", "\"\"\" VPP Object Model Test \"\"\" def test_vom_cpp(self): \"\"\" run", "= Worker( [executable, \"vpp object model\", self.shm_prefix], self.logger) worker.start() timeout", "tests\") class VOMTestCase(VppTestCase): \"\"\" VPP Object Model Test \"\"\" def", "\"TEST_DIR\" built_root = os.getenv(var, None) self.assertIsNotNone(built_root, \"Environment variable `%s' not", "except: raise Exception(\"Couldn't kill worker-spawned process\") if error: raise Exception(", "not finish in %ss\" % timeout) self.assert_equal(worker.result, 0, \"Binary test", "= True self.logger.error( \"Timeout! Worker did not finish in %ss\"", "VOM tests \"\"\" var = \"TEST_DIR\" built_root = os.getenv(var, None)", "import signal from framework import VppTestCase, running_extended_tests, \\ VppTestRunner, Worker", "finish in %ss\" % timeout) os.killpg(os.getpgid(worker.process.pid), signal.SIGTERM) worker.join() except: raise", "VppTestRunner, Worker @unittest.skipUnless(running_extended_tests(), \"part of extended tests\") class VOMTestCase(VppTestCase): \"\"\"", "python \"\"\" VAPI test \"\"\" import unittest import os import", "if worker.result is None: try: error = True self.logger.error( \"Timeout!", "Worker did not finish in %ss\" % timeout) self.assert_equal(worker.result, 0,", "True self.logger.error( \"Timeout! Worker did not finish in %ss\" %", "timeout) os.killpg(os.getpgid(worker.process.pid), signal.SIGTERM) worker.join() except: raise Exception(\"Couldn't kill worker-spawned process\")", "\"\"\" VAPI test \"\"\" import unittest import os import signal", "var = \"TEST_DIR\" built_root = os.getenv(var, None) self.assertIsNotNone(built_root, \"Environment variable", "self.shm_prefix], self.logger) worker.start() timeout = 120 worker.join(timeout) self.logger.info(\"Worker result is", "120 worker.join(timeout) self.logger.info(\"Worker result is `%s'\" % worker.result) error =", "unittest import os import signal from framework import VppTestCase, running_extended_tests,", "tests \"\"\" var = \"TEST_DIR\" built_root = os.getenv(var, None) self.assertIsNotNone(built_root,", "VppTestCase, running_extended_tests, \\ VppTestRunner, Worker @unittest.skipUnless(running_extended_tests(), \"part of extended tests\")" ]
[ "'we': 'We', 'fr': 'Fr', 'th': 'Th', 'sa': 'Sa', 'su': 'Su',", "'Sa', 'su': 'Su', } class TescoSpider(scrapy.Spider): name = \"tesco\" allowed_domains", "store['location']['id'], 'name': store['location']['name'], 'addr_full': addr_full, 'city': store['location']['contact']['address']['town'], 'state': '', 'country':'United", "'Th', 'sa': 'Sa', 'su': 'Su', } class TescoSpider(scrapy.Spider): name =", "TescoSpider(scrapy.Spider): name = \"tesco\" allowed_domains = [\"tescolocation.api.tesco.com\"] def store_hours(self, store_hours):", "'ref': store['location']['id'], 'name': store['location']['name'], 'addr_full': addr_full, 'city': store['location']['contact']['address']['town'], 'state': '',", "and 'close' in value): if(value['isOpen']=='true'): clean_time = clean_time + DAYS[key]+'", "def store_hours(self, store_hours): clean_time='' for key, value in store_hours.items(): if('isOpen'", "'tu': 'Tu', 'we': 'We', 'fr': 'Fr', 'th': 'Th', 'sa': 'Sa',", "in store['location']['contact']['address']['lines']: addr_full=addr_full+' '+add['text'] properties = { 'ref': store['location']['id'], 'name':", "stores: addr_full='' for add in store['location']['contact']['address']['lines']: addr_full=addr_full+' '+add['text'] properties =", "'th': 'Th', 'sa': 'Sa', 'su': 'Su', } class TescoSpider(scrapy.Spider): name", "'mo': 'Mo', 'tu': 'Tu', 'we': 'We', 'fr': 'Fr', 'th': 'Th',", "'sa': 'Sa', 'su': 'Su', } class TescoSpider(scrapy.Spider): name = \"tesco\"", "method='GET', headers=headers, callback=self.parse ) def parse(self, response): data = json.loads(response.body_as_unicode())", "import inputoutput DAYS = { 'mo': 'Mo', 'tu': 'Tu', 'we':", "def start_requests(self): url = 'https://tescolocation.api.tesco.com/v3/locations/search?offset=0&limit=1000000&sort=near:%2251.499207299999995,-0.08800609999999999%22&filter=category:Store%20AND%20isoCountryCode:x-uk&fields=name,geo,openingHours,altIds.branchNumber,contact' headers = { 'Accept-Language': 'en-US,en;q=0.9',", "store['location']['contact']['address']['lines']: addr_full=addr_full+' '+add['text'] properties = { 'ref': store['location']['id'], 'name': store['location']['name'],", "in value and 'close' in value): if(value['isOpen']=='true'): clean_time = clean_time", "*/*; q=0.01', 'Referer': 'https://www.kfc.com/store-locator?query=90210', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest', 'x-appkey':'store-locator-web-cde'", "= clean_time + DAYS[key]+' '+'Closed'+';' return clean_time def start_requests(self): url", "in stores: addr_full='' for add in store['location']['contact']['address']['lines']: addr_full=addr_full+' '+add['text'] properties", "store['location']['contact']['address']['town'], 'state': '', 'country':'United Kingdom', 'postcode': store['location']['contact']['address']['postcode'], 'lat': store['location']['geo']['coordinates']['latitude'], 'lon':", "clean_time = clean_time + DAYS[key]+' '+value['open'][0:2]+':'+value['open'][2:]+'-'+value['close'][0:2]+':'+value['close'][2:]+';' else: clean_time = clean_time", "else: clean_time = clean_time + DAYS[key]+' '+'Closed'+';' return clean_time def", "DAYS[key]+' '+value['open'][0:2]+':'+value['open'][2:]+'-'+value['close'][0:2]+':'+value['close'][2:]+';' else: clean_time = clean_time + DAYS[key]+' '+'Closed'+';' return", "'city': store['location']['contact']['address']['town'], 'state': '', 'country':'United Kingdom', 'postcode': store['location']['contact']['address']['postcode'], 'lat': store['location']['geo']['coordinates']['latitude'],", "scrapy.http.FormRequest( url=url, method='GET', headers=headers, callback=self.parse ) def parse(self, response): data", "for key, value in store_hours.items(): if('isOpen' in value and 'open'", "'phone': store['location']['contact']['phoneNumbers'][0]['number'], } opening_hours = self.store_hours(store['location']['openingHours'][0]['standardOpeningHours']) if opening_hours: properties['opening_hours'] =", "stores = data['results'] for store in stores: addr_full='' for add", "clean_time + DAYS[key]+' '+value['open'][0:2]+':'+value['open'][2:]+'-'+value['close'][0:2]+':'+value['close'][2:]+';' else: clean_time = clean_time + DAYS[key]+'", "'Accept': 'application/json, text/javascript, */*; q=0.01', 'Referer': 'https://www.kfc.com/store-locator?query=90210', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',", "store['location']['geo']['coordinates']['latitude'], 'lon': store['location']['geo']['coordinates']['longitude'], 'phone': store['location']['contact']['phoneNumbers'][0]['number'], } opening_hours = self.store_hours(store['location']['openingHours'][0]['standardOpeningHours']) if", "'https://tescolocation.api.tesco.com/v3/locations/search?offset=0&limit=1000000&sort=near:%2251.499207299999995,-0.08800609999999999%22&filter=category:Store%20AND%20isoCountryCode:x-uk&fields=name,geo,openingHours,altIds.branchNumber,contact' headers = { 'Accept-Language': 'en-US,en;q=0.9', 'Origin': 'https://www.tesco.com', 'Accept-Encoding': 'gzip,", "} class TescoSpider(scrapy.Spider): name = \"tesco\" allowed_domains = [\"tescolocation.api.tesco.com\"] def", "inputoutput DAYS = { 'mo': 'Mo', 'tu': 'Tu', 'we': 'We',", "= clean_time + DAYS[key]+' '+value['open'][0:2]+':'+value['open'][2:]+'-'+value['close'][0:2]+':'+value['close'][2:]+';' else: clean_time = clean_time +", "'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest', 'x-appkey':'store-locator-web-cde' } yield scrapy.http.FormRequest( url=url, method='GET',", "json import re import scrapy from locations.hourstudy import inputoutput DAYS", "url = 'https://tescolocation.api.tesco.com/v3/locations/search?offset=0&limit=1000000&sort=near:%2251.499207299999995,-0.08800609999999999%22&filter=category:Store%20AND%20isoCountryCode:x-uk&fields=name,geo,openingHours,altIds.branchNumber,contact' headers = { 'Accept-Language': 'en-US,en;q=0.9', 'Origin': 'https://www.tesco.com',", "'en-US,en;q=0.9', 'Origin': 'https://www.tesco.com', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': 'application/json, text/javascript,", "value and 'open' in value and 'close' in value): if(value['isOpen']=='true'):", "'lat': store['location']['geo']['coordinates']['latitude'], 'lon': store['location']['geo']['coordinates']['longitude'], 'phone': store['location']['contact']['phoneNumbers'][0]['number'], } opening_hours = self.store_hours(store['location']['openingHours'][0]['standardOpeningHours'])", "class TescoSpider(scrapy.Spider): name = \"tesco\" allowed_domains = [\"tescolocation.api.tesco.com\"] def store_hours(self,", "key, value in store_hours.items(): if('isOpen' in value and 'open' in", "'+value['open'][0:2]+':'+value['open'][2:]+'-'+value['close'][0:2]+':'+value['close'][2:]+';' else: clean_time = clean_time + DAYS[key]+' '+'Closed'+';' return clean_time", "properties['opening_hours'] = opening_hours raw = store['location']['openingHours'][0]['standardOpeningHours'] formatted = opening_hours yield", "properties = { 'ref': store['location']['id'], 'name': store['location']['name'], 'addr_full': addr_full, 'city':", "'open' in value and 'close' in value): if(value['isOpen']=='true'): clean_time =", "data = json.loads(response.body_as_unicode()) stores = data['results'] for store in stores:", "clean_time + DAYS[key]+' '+'Closed'+';' return clean_time def start_requests(self): url =", "'XMLHttpRequest', 'x-appkey':'store-locator-web-cde' } yield scrapy.http.FormRequest( url=url, method='GET', headers=headers, callback=self.parse )", "if('isOpen' in value and 'open' in value and 'close' in", "value and 'close' in value): if(value['isOpen']=='true'): clean_time = clean_time +", "import re import scrapy from locations.hourstudy import inputoutput DAYS =", "and 'open' in value and 'close' in value): if(value['isOpen']=='true'): clean_time", "= 'https://tescolocation.api.tesco.com/v3/locations/search?offset=0&limit=1000000&sort=near:%2251.499207299999995,-0.08800609999999999%22&filter=category:Store%20AND%20isoCountryCode:x-uk&fields=name,geo,openingHours,altIds.branchNumber,contact' headers = { 'Accept-Language': 'en-US,en;q=0.9', 'Origin': 'https://www.tesco.com', 'Accept-Encoding':", "store['location']['name'], 'addr_full': addr_full, 'city': store['location']['contact']['address']['town'], 'state': '', 'country':'United Kingdom', 'postcode':", "'addr_full': addr_full, 'city': store['location']['contact']['address']['town'], 'state': '', 'country':'United Kingdom', 'postcode': store['location']['contact']['address']['postcode'],", "'state': '', 'country':'United Kingdom', 'postcode': store['location']['contact']['address']['postcode'], 'lat': store['location']['geo']['coordinates']['latitude'], 'lon': store['location']['geo']['coordinates']['longitude'],", "'lon': store['location']['geo']['coordinates']['longitude'], 'phone': store['location']['contact']['phoneNumbers'][0]['number'], } opening_hours = self.store_hours(store['location']['openingHours'][0]['standardOpeningHours']) if opening_hours:", "raw = store['location']['openingHours'][0]['standardOpeningHours'] formatted = opening_hours yield inputoutput(raw,formatted) # yield", "scrapy from locations.hourstudy import inputoutput DAYS = { 'mo': 'Mo',", "import json import re import scrapy from locations.hourstudy import inputoutput", "{ 'Accept-Language': 'en-US,en;q=0.9', 'Origin': 'https://www.tesco.com', 'Accept-Encoding': 'gzip, deflate, br', 'Accept':", "from locations.hourstudy import inputoutput DAYS = { 'mo': 'Mo', 'tu':", "'+add['text'] properties = { 'ref': store['location']['id'], 'name': store['location']['name'], 'addr_full': addr_full,", "'Su', } class TescoSpider(scrapy.Spider): name = \"tesco\" allowed_domains = [\"tescolocation.api.tesco.com\"]", "'name': store['location']['name'], 'addr_full': addr_full, 'city': store['location']['contact']['address']['town'], 'state': '', 'country':'United Kingdom',", "= { 'mo': 'Mo', 'tu': 'Tu', 'we': 'We', 'fr': 'Fr',", "'https://www.tesco.com', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': 'application/json, text/javascript, */*; q=0.01',", "opening_hours: properties['opening_hours'] = opening_hours raw = store['location']['openingHours'][0]['standardOpeningHours'] formatted = opening_hours", "'gzip, deflate, br', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Referer': 'https://www.kfc.com/store-locator?query=90210',", "= { 'ref': store['location']['id'], 'name': store['location']['name'], 'addr_full': addr_full, 'city': store['location']['contact']['address']['town'],", "DAYS[key]+' '+'Closed'+';' return clean_time def start_requests(self): url = 'https://tescolocation.api.tesco.com/v3/locations/search?offset=0&limit=1000000&sort=near:%2251.499207299999995,-0.08800609999999999%22&filter=category:Store%20AND%20isoCountryCode:x-uk&fields=name,geo,openingHours,altIds.branchNumber,contact' headers", "'X-Requested-With': 'XMLHttpRequest', 'x-appkey':'store-locator-web-cde' } yield scrapy.http.FormRequest( url=url, method='GET', headers=headers, callback=self.parse", "<reponame>bealbrown/allhours<filename>locations/spiders/tesco.py import json import re import scrapy from locations.hourstudy import", "{ 'ref': store['location']['id'], 'name': store['location']['name'], 'addr_full': addr_full, 'city': store['location']['contact']['address']['town'], 'state':", "'close' in value): if(value['isOpen']=='true'): clean_time = clean_time + DAYS[key]+' '+value['open'][0:2]+':'+value['open'][2:]+'-'+value['close'][0:2]+':'+value['close'][2:]+';'", "= data['results'] for store in stores: addr_full='' for add in", "store['location']['geo']['coordinates']['longitude'], 'phone': store['location']['contact']['phoneNumbers'][0]['number'], } opening_hours = self.store_hours(store['location']['openingHours'][0]['standardOpeningHours']) if opening_hours: properties['opening_hours']", "store_hours): clean_time='' for key, value in store_hours.items(): if('isOpen' in value", "'Mo', 'tu': 'Tu', 'we': 'We', 'fr': 'Fr', 'th': 'Th', 'sa':", "q=0.01', 'Referer': 'https://www.kfc.com/store-locator?query=90210', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest', 'x-appkey':'store-locator-web-cde' }", "'su': 'Su', } class TescoSpider(scrapy.Spider): name = \"tesco\" allowed_domains =", "def parse(self, response): data = json.loads(response.body_as_unicode()) stores = data['results'] for", "} yield scrapy.http.FormRequest( url=url, method='GET', headers=headers, callback=self.parse ) def parse(self,", "deflate, br', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Referer': 'https://www.kfc.com/store-locator?query=90210', 'Content-Type':", "if opening_hours: properties['opening_hours'] = opening_hours raw = store['location']['openingHours'][0]['standardOpeningHours'] formatted =", "'+'Closed'+';' return clean_time def start_requests(self): url = 'https://tescolocation.api.tesco.com/v3/locations/search?offset=0&limit=1000000&sort=near:%2251.499207299999995,-0.08800609999999999%22&filter=category:Store%20AND%20isoCountryCode:x-uk&fields=name,geo,openingHours,altIds.branchNumber,contact' headers =", "= store['location']['openingHours'][0]['standardOpeningHours'] formatted = opening_hours yield inputoutput(raw,formatted) # yield inputoutput(**properties)", "text/javascript, */*; q=0.01', 'Referer': 'https://www.kfc.com/store-locator?query=90210', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest',", "= self.store_hours(store['location']['openingHours'][0]['standardOpeningHours']) if opening_hours: properties['opening_hours'] = opening_hours raw = store['location']['openingHours'][0]['standardOpeningHours']", "'Fr', 'th': 'Th', 'sa': 'Sa', 'su': 'Su', } class TescoSpider(scrapy.Spider):", "in value): if(value['isOpen']=='true'): clean_time = clean_time + DAYS[key]+' '+value['open'][0:2]+':'+value['open'][2:]+'-'+value['close'][0:2]+':'+value['close'][2:]+';' else:", "headers=headers, callback=self.parse ) def parse(self, response): data = json.loads(response.body_as_unicode()) stores", "= json.loads(response.body_as_unicode()) stores = data['results'] for store in stores: addr_full=''", "'Accept-Language': 'en-US,en;q=0.9', 'Origin': 'https://www.tesco.com', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': 'application/json,", "} opening_hours = self.store_hours(store['location']['openingHours'][0]['standardOpeningHours']) if opening_hours: properties['opening_hours'] = opening_hours raw", "'https://www.kfc.com/store-locator?query=90210', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest', 'x-appkey':'store-locator-web-cde' } yield scrapy.http.FormRequest(", "'postcode': store['location']['contact']['address']['postcode'], 'lat': store['location']['geo']['coordinates']['latitude'], 'lon': store['location']['geo']['coordinates']['longitude'], 'phone': store['location']['contact']['phoneNumbers'][0]['number'], } opening_hours", "br', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Referer': 'https://www.kfc.com/store-locator?query=90210', 'Content-Type': 'application/x-www-form-urlencoded;", "opening_hours raw = store['location']['openingHours'][0]['standardOpeningHours'] formatted = opening_hours yield inputoutput(raw,formatted) #", "{ 'mo': 'Mo', 'tu': 'Tu', 'we': 'We', 'fr': 'Fr', 'th':", "return clean_time def start_requests(self): url = 'https://tescolocation.api.tesco.com/v3/locations/search?offset=0&limit=1000000&sort=near:%2251.499207299999995,-0.08800609999999999%22&filter=category:Store%20AND%20isoCountryCode:x-uk&fields=name,geo,openingHours,altIds.branchNumber,contact' headers = {", "callback=self.parse ) def parse(self, response): data = json.loads(response.body_as_unicode()) stores =", "value in store_hours.items(): if('isOpen' in value and 'open' in value", "'', 'country':'United Kingdom', 'postcode': store['location']['contact']['address']['postcode'], 'lat': store['location']['geo']['coordinates']['latitude'], 'lon': store['location']['geo']['coordinates']['longitude'], 'phone':", "store in stores: addr_full='' for add in store['location']['contact']['address']['lines']: addr_full=addr_full+' '+add['text']", "for add in store['location']['contact']['address']['lines']: addr_full=addr_full+' '+add['text'] properties = { 'ref':", "in store_hours.items(): if('isOpen' in value and 'open' in value and", "import scrapy from locations.hourstudy import inputoutput DAYS = { 'mo':", "re import scrapy from locations.hourstudy import inputoutput DAYS = {", "= \"tesco\" allowed_domains = [\"tescolocation.api.tesco.com\"] def store_hours(self, store_hours): clean_time='' for", "[\"tescolocation.api.tesco.com\"] def store_hours(self, store_hours): clean_time='' for key, value in store_hours.items():", "data['results'] for store in stores: addr_full='' for add in store['location']['contact']['address']['lines']:", "yield scrapy.http.FormRequest( url=url, method='GET', headers=headers, callback=self.parse ) def parse(self, response):", "for store in stores: addr_full='' for add in store['location']['contact']['address']['lines']: addr_full=addr_full+'", "self.store_hours(store['location']['openingHours'][0]['standardOpeningHours']) if opening_hours: properties['opening_hours'] = opening_hours raw = store['location']['openingHours'][0]['standardOpeningHours'] formatted", "'We', 'fr': 'Fr', 'th': 'Th', 'sa': 'Sa', 'su': 'Su', }", "Kingdom', 'postcode': store['location']['contact']['address']['postcode'], 'lat': store['location']['geo']['coordinates']['latitude'], 'lon': store['location']['geo']['coordinates']['longitude'], 'phone': store['location']['contact']['phoneNumbers'][0]['number'], }", "response): data = json.loads(response.body_as_unicode()) stores = data['results'] for store in", "'Accept-Encoding': 'gzip, deflate, br', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Referer':", "parse(self, response): data = json.loads(response.body_as_unicode()) stores = data['results'] for store", "clean_time def start_requests(self): url = 'https://tescolocation.api.tesco.com/v3/locations/search?offset=0&limit=1000000&sort=near:%2251.499207299999995,-0.08800609999999999%22&filter=category:Store%20AND%20isoCountryCode:x-uk&fields=name,geo,openingHours,altIds.branchNumber,contact' headers = { 'Accept-Language':", "'Tu', 'we': 'We', 'fr': 'Fr', 'th': 'Th', 'sa': 'Sa', 'su':", "'x-appkey':'store-locator-web-cde' } yield scrapy.http.FormRequest( url=url, method='GET', headers=headers, callback=self.parse ) def", "in value and 'open' in value and 'close' in value):", "opening_hours = self.store_hours(store['location']['openingHours'][0]['standardOpeningHours']) if opening_hours: properties['opening_hours'] = opening_hours raw =", "start_requests(self): url = 'https://tescolocation.api.tesco.com/v3/locations/search?offset=0&limit=1000000&sort=near:%2251.499207299999995,-0.08800609999999999%22&filter=category:Store%20AND%20isoCountryCode:x-uk&fields=name,geo,openingHours,altIds.branchNumber,contact' headers = { 'Accept-Language': 'en-US,en;q=0.9', 'Origin':", "store_hours(self, store_hours): clean_time='' for key, value in store_hours.items(): if('isOpen' in", "store['location']['contact']['phoneNumbers'][0]['number'], } opening_hours = self.store_hours(store['location']['openingHours'][0]['standardOpeningHours']) if opening_hours: properties['opening_hours'] = opening_hours", "'country':'United Kingdom', 'postcode': store['location']['contact']['address']['postcode'], 'lat': store['location']['geo']['coordinates']['latitude'], 'lon': store['location']['geo']['coordinates']['longitude'], 'phone': store['location']['contact']['phoneNumbers'][0]['number'],", "value): if(value['isOpen']=='true'): clean_time = clean_time + DAYS[key]+' '+value['open'][0:2]+':'+value['open'][2:]+'-'+value['close'][0:2]+':'+value['close'][2:]+';' else: clean_time", "store['location']['contact']['address']['postcode'], 'lat': store['location']['geo']['coordinates']['latitude'], 'lon': store['location']['geo']['coordinates']['longitude'], 'phone': store['location']['contact']['phoneNumbers'][0]['number'], } opening_hours =", "\"tesco\" allowed_domains = [\"tescolocation.api.tesco.com\"] def store_hours(self, store_hours): clean_time='' for key,", "add in store['location']['contact']['address']['lines']: addr_full=addr_full+' '+add['text'] properties = { 'ref': store['location']['id'],", "charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest', 'x-appkey':'store-locator-web-cde' } yield scrapy.http.FormRequest( url=url, method='GET', headers=headers,", "url=url, method='GET', headers=headers, callback=self.parse ) def parse(self, response): data =", "headers = { 'Accept-Language': 'en-US,en;q=0.9', 'Origin': 'https://www.tesco.com', 'Accept-Encoding': 'gzip, deflate,", "addr_full=addr_full+' '+add['text'] properties = { 'ref': store['location']['id'], 'name': store['location']['name'], 'addr_full':", "clean_time = clean_time + DAYS[key]+' '+'Closed'+';' return clean_time def start_requests(self):", "store_hours.items(): if('isOpen' in value and 'open' in value and 'close'", "'fr': 'Fr', 'th': 'Th', 'sa': 'Sa', 'su': 'Su', } class", "'application/json, text/javascript, */*; q=0.01', 'Referer': 'https://www.kfc.com/store-locator?query=90210', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With':", "= opening_hours raw = store['location']['openingHours'][0]['standardOpeningHours'] formatted = opening_hours yield inputoutput(raw,formatted)", ") def parse(self, response): data = json.loads(response.body_as_unicode()) stores = data['results']", "+ DAYS[key]+' '+value['open'][0:2]+':'+value['open'][2:]+'-'+value['close'][0:2]+':'+value['close'][2:]+';' else: clean_time = clean_time + DAYS[key]+' '+'Closed'+';'", "allowed_domains = [\"tescolocation.api.tesco.com\"] def store_hours(self, store_hours): clean_time='' for key, value", "if(value['isOpen']=='true'): clean_time = clean_time + DAYS[key]+' '+value['open'][0:2]+':'+value['open'][2:]+'-'+value['close'][0:2]+':'+value['close'][2:]+';' else: clean_time =", "'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest', 'x-appkey':'store-locator-web-cde' } yield scrapy.http.FormRequest( url=url,", "DAYS = { 'mo': 'Mo', 'tu': 'Tu', 'we': 'We', 'fr':", "name = \"tesco\" allowed_domains = [\"tescolocation.api.tesco.com\"] def store_hours(self, store_hours): clean_time=''", "'Origin': 'https://www.tesco.com', 'Accept-Encoding': 'gzip, deflate, br', 'Accept': 'application/json, text/javascript, */*;", "clean_time='' for key, value in store_hours.items(): if('isOpen' in value and", "locations.hourstudy import inputoutput DAYS = { 'mo': 'Mo', 'tu': 'Tu',", "= [\"tescolocation.api.tesco.com\"] def store_hours(self, store_hours): clean_time='' for key, value in", "addr_full='' for add in store['location']['contact']['address']['lines']: addr_full=addr_full+' '+add['text'] properties = {", "= { 'Accept-Language': 'en-US,en;q=0.9', 'Origin': 'https://www.tesco.com', 'Accept-Encoding': 'gzip, deflate, br',", "json.loads(response.body_as_unicode()) stores = data['results'] for store in stores: addr_full='' for", "addr_full, 'city': store['location']['contact']['address']['town'], 'state': '', 'country':'United Kingdom', 'postcode': store['location']['contact']['address']['postcode'], 'lat':", "+ DAYS[key]+' '+'Closed'+';' return clean_time def start_requests(self): url = 'https://tescolocation.api.tesco.com/v3/locations/search?offset=0&limit=1000000&sort=near:%2251.499207299999995,-0.08800609999999999%22&filter=category:Store%20AND%20isoCountryCode:x-uk&fields=name,geo,openingHours,altIds.branchNumber,contact'", "'Referer': 'https://www.kfc.com/store-locator?query=90210', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest', 'x-appkey':'store-locator-web-cde' } yield" ]
[ "# plain Column objects (in new_cols) + metadata (in mixin_cols).", "Table, QTable, has_info_class from astropy.units.quantity import QuantityInfo __construct_mixin_classes = ('astropy.time.core.Time',", "= col for ii, name in enumerate(colnames): if ii >=", "x], names=['sc', 'x']) >>> represent_mixins_as_columns(tbl) <Table length=2> sc.ra sc.dec sc.obstime.jd1", "in an output table consisting purely of plain ``Column`` or", "imply serialization. Starting with version 3.1, the non-mixin ``MaskedColumn`` can", "else col_attr data_attrs = [key for key in ordered_keys if", "nontrivial in (('unit', lambda x: x not in (None, '')),", "no quantity subclasses are in the output then output as", "used in the representation to contain the name (and possible", "needed to serialize ``col`` in an output table consisting purely", "attr, value in info.items(): if attr not in obj_attrs: setattr(mixin.info,", "manipulating the object like a Table but without the actual", "{}) if len(data_attrs_map) == 1: # col is the first", "not None, None), ('description', lambda x: x is not None,", "from copy import deepcopy from collections import OrderedDict from astropy.utils.data_info", "instance ascii.read(file, format='ecsv') doesn't specify an # output class and", "one or more plain ``~astropy.table.Column`` objects and returns a new", "if relevant [DON'T store] # - format: possibly irrelevant but", "with no update to ``meta``. Parameters ---------- tbl : `~astropy.table.Table`", "this happens in a real table then all other columns", "``tbl`` Examples -------- >>> from astropy.table import Table, represent_mixins_as_columns >>>", "tbl.meta: return tbl meta = tbl.meta.copy() mixin_cols = meta.pop('__serialized_columns__') out", "in the table. \"\"\" pass def _represent_mixin_as_column(col, name, new_cols, mixin_cols,", "not obj_attrs or col.__class__ in exclude_classes: new_cols.append(col) return # Subtlety", "in the output then output as Table. # For instance", "is a used in the representation to contain the name", "``mixin_cols`` dict is updated with required attributes and information to", "For serialized columns the ``mixin_cols`` dict is updated with required", "Quantity or data # for MaskedColumn) if data_attr == col.info._represent_as_dict_primary_data:", "is serialized as a column in the table. Normally contains", "the ``serialize_method`` and ``serialize_context`` context variables. For instance a ``MaskedColumn``", "= obj_attrs.pop('__info__', {}) if len(data_attrs_map) == 1: # col is", "return the original table. if not mixin_cols: return tbl meta", "qualified class name obj_attrs['__class__'] = col.__module__ + '.' + col.__class__.__name__", "_represent_mixin_as_column(data, new_name, new_cols, obj_attrs) obj_attrs[data_attr] = SerializedColumn(obj_attrs.pop(new_name)) # Strip out", "the name of the column in the table. \"\"\" pass", "and ``jd2`` arrays from a ``Time`` column). For serialized columns", "astropy.table import Table, represent_mixins_as_columns >>> from astropy.time import Time >>>", "info[attr] = col_attr info['name'] = new_name col = _construct_mixin_from_obj_attrs_and_info(obj_attrs, info)", "\"coord.ra\") and # data_attr is the object attribute name (e.g.", "------- 1.0 3.0 2451180.0 -0.25 100.0 2.0 4.0 2451545.0 0.0", "just return the original table. if not mixin_cols: return tbl", "tuple of classes Exclude any mixin columns which are instannces", "split columns. This function is used by astropy I/O when", "new_name, obj_attrs in mixin_cols.items(): _construct_mixin_from_columns(new_name, obj_attrs, out) # If no", "the object determine if any transformation is required and may", "Starting with version 3.1, the non-mixin ``MaskedColumn`` can also be", "an issue with constructing MaskedColumn, where the encoded Column components", "name obj_attrs['__class__'] = col.__module__ + '.' + col.__class__.__name__ mixin_cols[name] =", "# Strip out from info any attributes defined by the", "for Quantity or data # for MaskedColumn) if data_attr ==", "val, out) data_attrs_map[name] = name for name in data_attrs_map.values(): del", "but can also be serialized as separate data and mask", "if key in obj_attrs and getattr(obj_attrs[key], 'shape', ())[:1] == col.shape[:1]]", "Exclude any mixin columns which are instannces of any classes", "tables to ECSV, FITS, HDF5 formats. Note that if the", "and \"value\", respectively. for name, data_attr in data_attrs_map.items(): col =", "None), ('description', lambda x: x is not None, None), ('meta',", "SerializedColumn): if 'name' in val: data_attrs_map[val['name']] = name else: _construct_mixin_from_columns(name,", "data_attrs_map[val['name']] = name else: _construct_mixin_from_columns(name, val, out) data_attrs_map[name] = name", "# New column name combines the old name and attribute", "in val: data_attrs_map[val['name']] = name else: _construct_mixin_from_columns(name, val, out) data_attrs_map[name]", "no update to ``meta``. Parameters ---------- tbl : `~astropy.table.Table` or", "x not in (None, '')), ('format', lambda x: x is", "# recurse. This will define obj_attrs[new_name]. _represent_mixin_as_column(data, new_name, new_cols, obj_attrs)", "not desirable. \"\"\" def add_column(self, col, index=0): colnames = self.colnames", "``__serialized_columns__`` which provides additional information needed to construct the original", "when writing tables to ECSV, FITS, HDF5 formats. Note that", "full Table. More pressing, there is an issue with constructing", "represented by one or more data columns. In earlier versions", "FITS, but can also be serialized as separate data and", "normal column. if not obj_attrs or col.__class__ in exclude_classes: new_cols.append(col)", "function docstring above) # or explicitly specified as excluded, then", "None), ('meta', lambda x: x, None)): col_attr = getattr(col.info, attr)", "mixin_cols[name] = obj_attrs def represent_mixins_as_columns(tbl, exclude_classes=()): \"\"\"Represent input Table ``tbl``", "float64 float64 float64 float64 ------- ------- -------------- -------------- ------- 1.0", "x, None)): col_attr = getattr(col.info, attr) if nontrivial(col_attr): info[attr] =", "``serialize_method`` and ``serialize_context`` context variables. For instance a ``MaskedColumn`` may", "in tbl.meta: return tbl meta = tbl.meta.copy() mixin_cols = meta.pop('__serialized_columns__')", "name of the column in the table. \"\"\" pass def", "100.0 2.0 4.0 2451545.0 0.0 200.0 \"\"\" # Dict of", "transformation is required and may depend on the ``serialize_method`` and", "Normally contains the single key ``name`` with the name of", "deg float64 float64 float64 float64 float64 ------- ------- -------------- --------------", "'.' + col.__class__.__name__ mixin_cols[name] = obj_attrs def represent_mixins_as_columns(tbl, exclude_classes=()): \"\"\"Represent", "mixin info attributes. The basic list of such # attributes", "The new column names are formed as ``<column_name>.<component>``, e.g. ``sc.ra``", "``Time`` column). For serialized columns the ``mixin_cols`` dict is updated", "sc = SkyCoord([1, 2], [3, 4], unit='deg', obstime=obstime) >>> tbl", "basic list of such # attributes is: 'name', 'unit', 'dtype',", "# the _construct_from_col method. Prevent accidentally running # untrusted code", "version 3.1, the non-mixin ``MaskedColumn`` can also be serialized. \"\"\"", "represent_mixins_as_columns(tbl) <Table length=2> sc.ra sc.dec sc.obstime.jd1 sc.obstime.jd2 x deg deg", "dict that is a used in the representation to contain", "def _construct_mixin_from_obj_attrs_and_info(obj_attrs, info): cls_full_name = obj_attrs.pop('__class__') # If this is", "[DO store] # - description: DO store # - meta:", "in enumerate(colnames): if ii >= index: self.move_to_end(name) @property def colnames(self):", "there is an issue with constructing MaskedColumn, where the encoded", "x is not None), ('description', lambda x: x is not", "output table. For plain Column objects # this will just", "not in tbl.meta: return tbl meta = tbl.meta.copy() mixin_cols =", "data from serialized columns (e.g. ``jd1`` and ``jd2`` arrays from", "column; in that case, use info # stored on the", "minimal table class that # represents the table file. has_quantities", "a real table then all other columns are immediately Masked", "cls_name = re.match(r'(.+)\\.(\\w+)', cls_full_name).groups() module = import_module(mod_name) cls = getattr(module,", "col.info._represent_as_dict() ordered_keys = col.info._represent_as_dict_attrs # If serialization is not required", "a supported class then import the class and run #", "is not None, None), ('meta', lambda x: x, None)): col_attr", "re from copy import deepcopy from collections import OrderedDict from", "is not None), ('description', lambda x: x is not None),", "ECSV, FITS, HDF5 formats. Note that if the table does", "return list(self.keys()) def itercols(self): return self.values() def _construct_mixin_from_columns(new_name, obj_attrs, out):", "data_attr == col.info._represent_as_dict_primary_data: new_name = name else: new_name = name", "Note that if the table does not include any mixin", "cls_full_name not in __construct_mixin_classes: raise ValueError('unsupported class for construct {}'.format(cls_full_name))", "a parent attribute # - dtype: captured in plain Column", "tbl = Table([sc, x], names=['sc', 'x']) >>> represent_mixins_as_columns(tbl) <Table length=2>", "return out def _construct_mixin_from_obj_attrs_and_info(obj_attrs, info): cls_full_name = obj_attrs.pop('__class__') # If", "info # stored on the column. for attr, nontrivial in", "= [key for key in ordered_keys if key in obj_attrs", "200.0] >>> obstime = Time([1999.0, 2000.0], format='jyear') >>> sc =", "just be the original column object. new_cols = [] #", "created then just return the original table. if not mixin_cols:", "code of \"mixin\" to imply serialization. Starting with version 3.1,", "excluded, then treat as a normal column. if not obj_attrs", "stored directly to FITS, but can also be serialized as", "splitting, as shown in the example below. The new column", "\"value\", respectively. for name, data_attr in data_attrs_map.items(): col = out[name]", "astropy classes. if cls_full_name not in __construct_mixin_classes: raise ValueError('unsupported class", "For instance ascii.read(file, format='ecsv') doesn't specify an # output class", "info.items(): if attr in cls.info.attrs_from_parent: obj_attrs[attr] = value mixin =", "object like a Table but without the actual overhead for", "obj_attrs in mixin_cols.items(): _construct_mixin_from_columns(new_name, obj_attrs, out) # If no quantity", "list of such # attributes is: 'name', 'unit', 'dtype', 'format',", "Go through table columns and represent each column as one", "from astropy.coordinates import SkyCoord >>> x = [100.0, 200.0] >>>", "[key for key in ordered_keys if key in obj_attrs and", "from importlib import import_module import re from copy import deepcopy", "itercols(self): return self.values() def _construct_mixin_from_columns(new_name, obj_attrs, out): data_attrs_map = {}", "relevant [DON'T store] # - format: possibly irrelevant but settable", "above) # or explicitly specified as excluded, then treat as", "filled in place by _represent_mixin_as_column(). mixin_cols = {} # List", "were serialized, hence the use within this code of \"mixin\"", "data or an array-like attribute) that is serialized as a", "# - format: possibly irrelevant but settable post-object creation [DO", "does not include any mixin columns then the original table", "and attribute # (e.g. skycoord.ra, skycoord.dec).unless it is the primary", "in ``tbl`` to one or more plain ``~astropy.table.Column`` objects and", "None, None), ('description', lambda x: x is not None, None),", "and returns a new Table. A single mixin column may", "DON'T store if this is a parent attribute # -", "not has_info_class(data, MixinInfo): new_cols.append(Column(data, name=new_name, **info)) obj_attrs[data_attr] = SerializedColumn({'name': new_name})", "obj_attrs[data_attr] # New column name combines the old name and", "= {} for name, val in obj_attrs.items(): if isinstance(val, SerializedColumn):", "for fully representing the column. This includes the possibility of", "def itercols(self): return self.values() def _construct_mixin_from_columns(new_name, obj_attrs, out): data_attrs_map =", "serialized columns the ``mixin_cols`` dict is updated with required attributes", "4.0 2451545.0 0.0 200.0 \"\"\" # Dict of metadata for", "())[:1] == col.shape[:1]] for data_attr in data_attrs: data = obj_attrs[data_attr]", "but settable post-object creation [DO store] # - description: DO", "if this is a parent attribute # - dtype: captured", "running # untrusted code by only importing known astropy classes.", "represent mixins as Columns exclude_classes : tuple of classes Exclude", "attr in cls.info.attrs_from_parent: obj_attrs[attr] = value mixin = cls.info._construct_from_dict(obj_attrs) for", "in plain Column if relevant [DON'T store] # - format:", "mixin attribute (either primary data or an array-like attribute) that", "actual overhead for a full Table. More pressing, there is", "components as needed for fully representing the column. This includes", "class for construct {}'.format(cls_full_name)) mod_name, cls_name = re.match(r'(.+)\\.(\\w+)', cls_full_name).groups() module", "`~astropy.table.MaskedColumn` objects. This function represents any mixin columns like `~astropy.time.Time`", "exclude_classes : tuple of classes Exclude any mixin columns which", "attr, value in info.items(): if attr in cls.info.attrs_from_parent: obj_attrs[attr] =", "new_cols, mixin_cols, exclude_classes=exclude_classes) # If no metadata was created then", "columns then the original table is returned with no update", "updated columns, or else the original input ``tbl`` Examples --------", "formed as ``<column_name>.<component>``, e.g. ``sc.ra`` for a `~astropy.coordinates.SkyCoord` column named", "sc.ra sc.dec sc.obstime.jd1 sc.obstime.jd2 x deg deg float64 float64 float64", "table does not include any mixin columns then the original", "Prevent accidentally running # untrusted code by only importing known", "key in ordered_keys if key in obj_attrs and getattr(obj_attrs[key], 'shape',", "attribute # - dtype: captured in plain Column if relevant", "This will define obj_attrs[new_name]. _represent_mixin_as_column(data, new_name, new_cols, obj_attrs) obj_attrs[data_attr] =", "as excluded, then treat as a normal column. if not", "info) for a mixin attribute (either primary data or an", "old name and attribute # (e.g. skycoord.ra, skycoord.dec).unless it is", "other columns are immediately Masked and a warning is issued.", "for new_name, obj_attrs in mixin_cols.items(): _construct_mixin_from_columns(new_name, obj_attrs, out) # If", "case, use info # stored on the column. for attr,", "from info any attributes defined by the parent for attr", "index=idx) def _construct_mixins_from_columns(tbl): if '__serialized_columns__' not in tbl.meta: return tbl", "objects. This function represents any mixin columns like `~astropy.time.Time` in", "plain ``~astropy.table.Column`` objects and returns a new Table. A single", "without the actual overhead for a full Table. More pressing,", "obj_attrs['__info__'] = info # Store the fully qualified class name", "obj_attrs and getattr(obj_attrs[key], 'shape', ())[:1] == col.shape[:1]] for data_attr in", "classes. if cls_full_name not in __construct_mixin_classes: raise ValueError('unsupported class for", "in obj_attrs: setattr(mixin.info, attr, value) return mixin class _TableLite(OrderedDict): \"\"\"", "exclude_classes=()): \"\"\"Carry out processing needed to serialize ``col`` in an", "'astropy.coordinates.distances.Distance', 'astropy.coordinates.earth.EarthLocation', 'astropy.coordinates.sky_coordinate.SkyCoord', 'astropy.table.table.NdarrayMixin', 'astropy.table.column.MaskedColumn') class SerializedColumn(dict): \"\"\" Subclass of", "format: possibly irrelevant but settable post-object creation [DO store] #", "the output table. For plain Column objects # this will", "Column objects # this will just be the original column", "add new column idx = min(out.colnames.index(name) for name in data_attrs_map)", "out.itercols()) out_cls = QTable if has_quantities else Table return out_cls(list(out.values()),", "(and possible other info) for a mixin attribute (either primary", "then just return the original table. if not mixin_cols: return", "mixin columns were serialized, hence the use within this code", ">>> obstime = Time([1999.0, 2000.0], format='jyear') >>> sc = SkyCoord([1,", "name, val in obj_attrs.items(): if isinstance(val, SerializedColumn): if 'name' in", "for a `~astropy.coordinates.SkyCoord` column named ``sc``. In addition to splitting", "info.items(): if attr not in obj_attrs: setattr(mixin.info, attr, value) return", "in __construct_mixin_classes: raise ValueError('unsupported class for construct {}'.format(cls_full_name)) mod_name, cls_name", "getattr(col.info, attr) if nontrivial(col_attr): info[attr] = col_attr info['name'] = new_name", "array-like attribute) that is serialized as a column in the", "+ '.' + data_attr if not has_info_class(data, MixinInfo): new_cols.append(Column(data, name=new_name,", "class name obj_attrs['__class__'] = col.__module__ + '.' + col.__class__.__name__ mixin_cols[name]", "into a MaskedColumn. When this happens in a real table", "are in the output then output as Table. # For", "mask) are turned into a MaskedColumn. When this happens in", "Examples -------- >>> from astropy.table import Table, represent_mixins_as_columns >>> from", "data_attrs = [key for key in ordered_keys if key in", "('meta', lambda x: x)): col_attr = getattr(col.info, attr) if nontrivial(col_attr):", "for name in data_attrs_map) # Name is the column name", "the original mixin columns from the split columns. This function", "This allows manipulating the object like a Table but without", "- meta: DO store info = {} for attr, nontrivial,", "self.move_to_end(name) @property def colnames(self): return list(self.keys()) def itercols(self): return self.values()", "importing known astropy classes. if cls_full_name not in __construct_mixin_classes: raise", "lambda x: x)): col_attr = getattr(col.info, attr) if nontrivial(col_attr): info[attr]", "table. Table mixin columns are always serialized and get represented", "mixin_cols.items(): _construct_mixin_from_columns(new_name, obj_attrs, out) # If no quantity subclasses are", "attribute name (e.g. \"ra\"). A different # example would be", "both plain columns from the original table and plain columns", "or subclass Table to represent mixins as Columns exclude_classes :", "is required and may depend on the ``serialize_method`` and ``serialize_context``", "attr in col.info.attrs_from_parent: if attr in info: del info[attr] if", "('meta', lambda x: x, None)): col_attr = getattr(col.info, attr) if", "directly [DON'T store] # - unit: DON'T store if this", "import deepcopy from collections import OrderedDict from astropy.utils.data_info import MixinInfo", "'description', 'meta'. # - name: handled directly [DON'T store] #", "from the original table and plain columns that represent data", "= import_module(mod_name) cls = getattr(module, cls_name) for attr, value in", "recurse. This will define obj_attrs[new_name]. _represent_mixin_as_column(data, new_name, new_cols, obj_attrs) obj_attrs[data_attr]", "contain the name (and possible other info) for a mixin", "= col.__module__ + '.' + col.__class__.__name__ mixin_cols[name] = obj_attrs def", "\"\"\" Minimal table-like object for _construct_mixin_from_columns. This allows manipulating the", "+ metadata (in mixin_cols). for col in tbl.itercols(): _represent_mixin_as_column(col, col.info.name,", "'astropy.units.quantity.Quantity', 'astropy.coordinates.angles.Latitude', 'astropy.coordinates.angles.Longitude', 'astropy.coordinates.angles.Angle', 'astropy.coordinates.distances.Distance', 'astropy.coordinates.earth.EarthLocation', 'astropy.coordinates.sky_coordinate.SkyCoord', 'astropy.table.table.NdarrayMixin', 'astropy.table.column.MaskedColumn') class", "the name (and possible other info) for a mixin attribute", "in data_attrs_map) # Name is the column name in the", "= col del out[name] info = obj_attrs.pop('__info__', {}) if len(data_attrs_map)", "column. This includes the possibility of recursive splitting, as shown", "single mixin column may be split into multiple column components", "formatted time object that would have (e.g.) # \"time_col\" and", "obj_attrs[new_name]. _represent_mixin_as_column(data, new_name, new_cols, obj_attrs) obj_attrs[data_attr] = SerializedColumn(obj_attrs.pop(new_name)) # Strip", "passed as a persistent list). This includes both plain columns", "split into multiple column components as needed for fully representing", "column (e.g. value for Quantity or data # for MaskedColumn)", "MaskedColumn. When this happens in a real table then all", "For instance a ``MaskedColumn`` may be stored directly to FITS,", "None and x != '', str), ('format', lambda x: x", "'astropy.coordinates.angles.Longitude', 'astropy.coordinates.angles.Angle', 'astropy.coordinates.distances.Distance', 'astropy.coordinates.earth.EarthLocation', 'astropy.coordinates.sky_coordinate.SkyCoord', 'astropy.table.table.NdarrayMixin', 'astropy.table.column.MaskedColumn') class SerializedColumn(dict): \"\"\"", "list(self.keys()) def itercols(self): return self.values() def _construct_mixin_from_columns(new_name, obj_attrs, out): data_attrs_map", "class that # represents the table file. has_quantities = any(isinstance(col.info,", "'name' in val: data_attrs_map[val['name']] = name else: _construct_mixin_from_columns(name, val, out)", "obj_attrs or col.__class__ in exclude_classes: new_cols.append(col) return # Subtlety here", "with constructing MaskedColumn, where the encoded Column components (data, mask)", "represent_mixins_as_columns >>> from astropy.time import Time >>> from astropy.coordinates import", "index: self.move_to_end(name) @property def colnames(self): return list(self.keys()) def itercols(self): return", "any transformation is required and may depend on the ``serialize_method``", "represents the table file. has_quantities = any(isinstance(col.info, QuantityInfo) for col", "[100.0, 200.0] >>> obstime = Time([1999.0, 2000.0], format='jyear') >>> sc", "1: # col is the first and only serialized column;", "``sc``. In addition to splitting columns, this function updates the", "dict named ``__serialized_columns__`` which provides additional information needed to construct", "columns and represent each column as one or more #", "turned into a MaskedColumn. When this happens in a real", "= obj_attrs.pop('__class__') # If this is a supported class then", "x: x is not None and x != '', str),", "class and run # the _construct_from_col method. Prevent accidentally running", "as Table. # For instance ascii.read(file, format='ecsv') doesn't specify an", "def represent_mixins_as_columns(tbl, exclude_classes=()): \"\"\"Represent input Table ``tbl`` using only `~astropy.table.Column`", "to splitting columns, this function updates the table ``meta`` dictionary", "This function represents any mixin columns like `~astropy.time.Time` in ``tbl``", "self[col.info.name] = col for ii, name in enumerate(colnames): if ii", "a mixin attribute (either primary data or an array-like attribute)", "\"mixin\" to imply serialization. Starting with version 3.1, the non-mixin", "= name else: _construct_mixin_from_columns(name, val, out) data_attrs_map[name] = name for", "then import the class and run # the _construct_from_col method.", "mixin column may be split into multiple column components as", "obj_attrs[name] # Get the index where to add new column", "MaskedColumn) if data_attr == col.info._represent_as_dict_primary_data: new_name = name else: new_name", "+ data_attr if not has_info_class(data, MixinInfo): new_cols.append(Column(data, name=new_name, **info)) obj_attrs[data_attr]", "This includes both plain columns from the original table and", "columns. This function is used by astropy I/O when writing", "writing tables to ECSV, FITS, HDF5 formats. Note that if", "function represents any mixin columns like `~astropy.time.Time` in ``tbl`` to", "\"\"\" pass def _represent_mixin_as_column(col, name, new_cols, mixin_cols, exclude_classes=()): \"\"\"Carry out", "info = obj_attrs.pop('__info__', {}) if len(data_attrs_map) == 1: # col", "# List of columns for the output table. For plain", "= SerializedColumn(obj_attrs.pop(new_name)) # Strip out from info any attributes defined", "column object. new_cols = [] # Go through table columns", "purely of plain ``Column`` or ``MaskedColumn`` columns. This relies on", "Table ``tbl`` using only `~astropy.table.Column` or `~astropy.table.MaskedColumn` objects. This function", "= col.info._represent_as_dict() ordered_keys = col.info._represent_as_dict_attrs # If serialization is not", "within this code of \"mixin\" to imply serialization. Starting with", "return tbl meta = tbl.meta.copy() mixin_cols = meta.pop('__serialized_columns__') out =", "in cls.info.attrs_from_parent: obj_attrs[attr] = value mixin = cls.info._construct_from_dict(obj_attrs) for attr,", "# - name: handled directly [DON'T store] # - unit:", "data and mask columns. This function builds up a list", "ValueError('unsupported class for construct {}'.format(cls_full_name)) mod_name, cls_name = re.match(r'(.+)\\.(\\w+)', cls_full_name).groups()", "are immediately Masked and a warning is issued. This is", "import_module(mod_name) cls = getattr(module, cls_name) for attr, value in info.items():", "in (('unit', lambda x: x not in (None, '')), ('format',", "def _construct_mixins_from_columns(tbl): if '__serialized_columns__' not in tbl.meta: return tbl meta", "with required attributes and information to subsequently reconstruct the table.", "a formatted time object that would have (e.g.) # \"time_col\"", "serialized, hence the use within this code of \"mixin\" to", "obj_attrs, out): data_attrs_map = {} for name, val in obj_attrs.items():", "'astropy.coordinates.sky_coordinate.SkyCoord', 'astropy.table.table.NdarrayMixin', 'astropy.table.column.MaskedColumn') class SerializedColumn(dict): \"\"\" Subclass of dict that", "variables. For instance a ``MaskedColumn`` may be stored directly to", "= deepcopy(tbl.meta) meta['__serialized_columns__'] = mixin_cols out = Table(new_cols, meta=meta, copy=False)", "in the tuple Returns ------- tbl : `~astropy.table.Table` New Table", "`~astropy.table.Table` New Table with updated columns, or else the original", "2.0 4.0 2451545.0 0.0 200.0 \"\"\" # Dict of metadata", "meta['__serialized_columns__'] = mixin_cols out = Table(new_cols, meta=meta, copy=False) return out", "Strip out from info any attributes defined by the parent", "will just be the original column object. new_cols = []", "is not None and x != '', str), ('format', lambda", "the original input ``tbl`` Examples -------- >>> from astropy.table import", "2451180.0 -0.25 100.0 2.0 4.0 2451545.0 0.0 200.0 \"\"\" #", "for name, val in obj_attrs.items(): if isinstance(val, SerializedColumn): if 'name'", "the table. Normally contains the single key ``name`` with the", "immediately Masked and a warning is issued. This is not", ">>> from astropy.coordinates import SkyCoord >>> x = [100.0, 200.0]", "to ``meta``. Parameters ---------- tbl : `~astropy.table.Table` or subclass Table", "col.info.name, new_cols, mixin_cols, exclude_classes=exclude_classes) # If no metadata was created", "del info[attr] if info: obj_attrs['__info__'] = info # Store the", "is handling mixin info attributes. The basic list of such", "col_attr = getattr(col.info, attr) if nontrivial(col_attr): info[attr] = col_attr info['name']", "table consisting purely of plain ``Column`` or ``MaskedColumn`` columns. This", "this is a supported class then import the class and", "define obj_attrs[new_name]. _represent_mixin_as_column(data, new_name, new_cols, obj_attrs) obj_attrs[data_attr] = SerializedColumn(obj_attrs.pop(new_name)) #", "xform else col_attr data_attrs = [key for key in ordered_keys", "2451545.0 0.0 200.0 \"\"\" # Dict of metadata for serializing", "# For instance ascii.read(file, format='ecsv') doesn't specify an # output", "for _construct_mixin_from_columns. This allows manipulating the object like a Table", "(data, mask) are turned into a MaskedColumn. When this happens", "out = _TableLite(tbl.columns) for new_name, obj_attrs in mixin_cols.items(): _construct_mixin_from_columns(new_name, obj_attrs,", "determine if any transformation is required and may depend on", "columns like `~astropy.time.Time` in ``tbl`` to one or more plain", "the column. This includes the possibility of recursive splitting, as", "col is the first and only serialized column; in that", "-------------- ------- 1.0 3.0 2451180.0 -0.25 100.0 2.0 4.0 2451545.0", "# Get the index where to add new column idx", "returns a new Table. A single mixin column may be", "(('unit', lambda x: x not in (None, '')), ('format', lambda", ": `~astropy.table.Table` or subclass Table to represent mixins as Columns", "that is a used in the representation to contain the", "be a formatted time object that would have (e.g.) #", "# Store the fully qualified class name obj_attrs['__class__'] = col.__module__", "index=0): colnames = self.colnames self[col.info.name] = col for ii, name", "obj_attrs def represent_mixins_as_columns(tbl, exclude_classes=()): \"\"\"Represent input Table ``tbl`` using only", "format='ecsv') doesn't specify an # output class and should return", "del obj_attrs[name] # Get the index where to add new", "or else the original input ``tbl`` Examples -------- >>> from", "name. # Gets filled in place by _represent_mixin_as_column(). mixin_cols =", "store] # - format: possibly irrelevant but settable post-object creation", "time object that would have (e.g.) # \"time_col\" and \"value\",", "column names are formed as ``<column_name>.<component>``, e.g. ``sc.ra`` for a", "be serialized. \"\"\" obj_attrs = col.info._represent_as_dict() ordered_keys = col.info._represent_as_dict_attrs #", "and information to subsequently reconstruct the table. Table mixin columns", "named ``__serialized_columns__`` which provides additional information needed to construct the", "value in info.items(): if attr in cls.info.attrs_from_parent: obj_attrs[attr] = value", "components (data, mask) are turned into a MaskedColumn. When this", "== col.info._represent_as_dict_primary_data: new_name = name else: new_name = name +", "\"\"\" obj_attrs = col.info._represent_as_dict() ordered_keys = col.info._represent_as_dict_attrs # If serialization", "using only `~astropy.table.Column` or `~astropy.table.MaskedColumn` objects. This function represents any", "mixin columns are always serialized and get represented by one", "always serialized and get represented by one or more data", "data_attr is the object attribute name (e.g. \"ra\"). A different", "is not desirable. \"\"\" def add_column(self, col, index=0): colnames =", "dict is updated with required attributes and information to subsequently", "SerializedColumn(dict): \"\"\" Subclass of dict that is a used in", "mixin_cols: return tbl meta = deepcopy(tbl.meta) meta['__serialized_columns__'] = mixin_cols out", "# or explicitly specified as excluded, then treat as a", "`~astropy.time.Time` in ``tbl`` to one or more plain ``~astropy.table.Column`` objects", "table ``meta`` dictionary to include a dict named ``__serialized_columns__`` which", "exclude_classes=exclude_classes) # If no metadata was created then just return", "else: # recurse. This will define obj_attrs[new_name]. _represent_mixin_as_column(data, new_name, new_cols,", "be stored directly to FITS, but can also be serialized", "# attribute for the column (e.g. value for Quantity or", "MaskedColumn, where the encoded Column components (data, mask) are turned", ": `~astropy.table.Table` New Table with updated columns, or else the", "_construct_from_col method. Prevent accidentally running # untrusted code by only", "# Gets filled in place by _represent_mixin_as_column(). mixin_cols = {}", "out processing needed to serialize ``col`` in an output table", "ascii.read(file, format='ecsv') doesn't specify an # output class and should", "the use within this code of \"mixin\" to imply serialization.", "specified as excluded, then treat as a normal column. if", "colnames = self.colnames self[col.info.name] = col for ii, name in", "in (('unit', lambda x: x is not None and x", "Get the index where to add new column idx =", "or `~astropy.table.MaskedColumn` objects. This function represents any mixin columns like", "attributes. The basic list of such # attributes is: 'name',", "post-object creation [DO store] # - description: DO store #", "- dtype: captured in plain Column if relevant [DON'T store]", "obj_attrs[data_attr] = SerializedColumn({'name': new_name}) else: # recurse. This will define", "col del out[name] info = obj_attrs.pop('__info__', {}) if len(data_attrs_map) ==", "This relies on the object determine if any transformation is", "[DON'T store] # - format: possibly irrelevant but settable post-object", "Name is the column name in the table (e.g. \"coord.ra\")", "QTable if has_quantities else Table return out_cls(list(out.values()), names=out.colnames, copy=False, meta=meta)", "copy=False) return out def _construct_mixin_from_obj_attrs_and_info(obj_attrs, info): cls_full_name = obj_attrs.pop('__class__') #", "store] # - unit: DON'T store if this is a", "HDF5 formats. Note that if the table does not include", "import_module import re from copy import deepcopy from collections import", "'meta'. # - name: handled directly [DON'T store] # -", "the first and only serialized column; in that case, use", "= col.info._represent_as_dict_attrs # If serialization is not required (see function", "= [] # Go through table columns and represent each", "obj_attrs[attr] = value mixin = cls.info._construct_from_dict(obj_attrs) for attr, value in", "each column, keyed by column name. # Gets filled in", "if any transformation is required and may depend on the", "function updates the table ``meta`` dictionary to include a dict", "respectively. for name, data_attr in data_attrs_map.items(): col = out[name] obj_attrs[data_attr]", "format='jyear') >>> sc = SkyCoord([1, 2], [3, 4], unit='deg', obstime=obstime)", "out[name] obj_attrs[data_attr] = col del out[name] info = obj_attrs.pop('__info__', {})", "or ``MaskedColumn`` columns. This relies on the object determine if", "table. Normally contains the single key ``name`` with the name", "``sc.ra`` for a `~astropy.coordinates.SkyCoord` column named ``sc``. In addition to", "skycoord.ra, skycoord.dec).unless it is the primary data # attribute for", "import the class and run # the _construct_from_col method. Prevent", "tbl.itercols(): _represent_mixin_as_column(col, col.info.name, new_cols, mixin_cols, exclude_classes=exclude_classes) # If no metadata", "('format', lambda x: x is not None), ('description', lambda x:", "attr, value) return mixin class _TableLite(OrderedDict): \"\"\" Minimal table-like object", "_construct_mixins_from_columns(tbl): if '__serialized_columns__' not in tbl.meta: return tbl meta =", "the table (e.g. \"coord.ra\") and # data_attr is the object", "= any(isinstance(col.info, QuantityInfo) for col in out.itercols()) out_cls = QTable", "= Table([sc, x], names=['sc', 'x']) >>> represent_mixins_as_columns(tbl) <Table length=2> sc.ra", "any attributes defined by the parent for attr in col.info.attrs_from_parent:", "pass def _represent_mixin_as_column(col, name, new_cols, mixin_cols, exclude_classes=()): \"\"\"Carry out processing", "any mixin columns then the original table is returned with", "None), ('meta', lambda x: x)): col_attr = getattr(col.info, attr) if", "is issued. This is not desirable. \"\"\" def add_column(self, col,", "deg deg float64 float64 float64 float64 float64 ------- ------- --------------", "depend on the ``serialize_method`` and ``serialize_context`` context variables. For instance", "a list of plain columns in the ``new_cols`` arg (which", "'astropy.table.column.MaskedColumn') class SerializedColumn(dict): \"\"\" Subclass of dict that is a", "an # output class and should return the minimal table", "2000.0], format='jyear') >>> sc = SkyCoord([1, 2], [3, 4], unit='deg',", "column may be split into multiple column components as needed", "for serializing each column, keyed by column name. # Gets", "-0.25 100.0 2.0 4.0 2451545.0 0.0 200.0 \"\"\" # Dict", "store # - meta: DO store info = {} for", "the table file. has_quantities = any(isinstance(col.info, QuantityInfo) for col in", "-------- >>> from astropy.table import Table, represent_mixins_as_columns >>> from astropy.time", "class _TableLite(OrderedDict): \"\"\" Minimal table-like object for _construct_mixin_from_columns. This allows", "column name combines the old name and attribute # (e.g.", "supported class then import the class and run # the", "ordered_keys = col.info._represent_as_dict_attrs # If serialization is not required (see", "the original table is returned with no update to ``meta``.", "if xform else col_attr data_attrs = [key for key in", "_construct_mixin_from_columns. This allows manipulating the object like a Table but", "# example would be a formatted time object that would", "attr not in obj_attrs: setattr(mixin.info, attr, value) return mixin class", "represent data from serialized columns (e.g. ``jd1`` and ``jd2`` arrays", "for a mixin attribute (either primary data or an array-like", "object determine if any transformation is required and may depend", "Dict of metadata for serializing each column, keyed by column", "\"\"\"Carry out processing needed to serialize ``col`` in an output", "description: DO store # - meta: DO store info =", "col, index=0): colnames = self.colnames self[col.info.name] = col for ii,", "table (e.g. \"coord.ra\") and # data_attr is the object attribute", "{} for attr, nontrivial, xform in (('unit', lambda x: x", "data # attribute for the column (e.g. value for Quantity", "value mixin = cls.info._construct_from_dict(obj_attrs) for attr, value in info.items(): if", "return mixin class _TableLite(OrderedDict): \"\"\" Minimal table-like object for _construct_mixin_from_columns.", "and should return the minimal table class that # represents", "New column name combines the old name and attribute #", "parent for attr in col.info.attrs_from_parent: if attr in info: del", "= QTable if has_quantities else Table return out_cls(list(out.values()), names=out.colnames, copy=False,", "attr) if nontrivial(col_attr): info[attr] = xform(col_attr) if xform else col_attr", "have (e.g.) # \"time_col\" and \"value\", respectively. for name, data_attr", "table class that # represents the table file. has_quantities =", "If no quantity subclasses are in the output then output", "min(out.colnames.index(name) for name in data_attrs_map) # Name is the column", "attribute for the column (e.g. value for Quantity or data", "that case, use info # stored on the column. for", "or more data columns. In earlier versions of the code", "columns (e.g. ``jd1`` and ``jd2`` arrays from a ``Time`` column).", "for col in out.itercols()) out_cls = QTable if has_quantities else", "a `~astropy.coordinates.SkyCoord` column named ``sc``. In addition to splitting columns,", "= [100.0, 200.0] >>> obstime = Time([1999.0, 2000.0], format='jyear') >>>", "data_attrs_map.items(): col = out[name] obj_attrs[data_attr] = col del out[name] info", "@property def colnames(self): return list(self.keys()) def itercols(self): return self.values() def", "docstring above) # or explicitly specified as excluded, then treat", "column named ``sc``. In addition to splitting columns, this function", "table. For plain Column objects # this will just be", "'', str), ('format', lambda x: x is not None, None),", "the column in the table. \"\"\" pass def _represent_mixin_as_column(col, name,", "_construct_mixin_from_obj_attrs_and_info(obj_attrs, info) out.add_column(col, index=idx) def _construct_mixins_from_columns(tbl): if '__serialized_columns__' not in", "sc.dec sc.obstime.jd1 sc.obstime.jd2 x deg deg float64 float64 float64 float64", "happens in a real table then all other columns are", "return self.values() def _construct_mixin_from_columns(new_name, obj_attrs, out): data_attrs_map = {} for", "then treat as a normal column. if not obj_attrs or", "{}'.format(cls_full_name)) mod_name, cls_name = re.match(r'(.+)\\.(\\w+)', cls_full_name).groups() module = import_module(mod_name) cls", "__construct_mixin_classes = ('astropy.time.core.Time', 'astropy.time.core.TimeDelta', 'astropy.units.quantity.Quantity', 'astropy.coordinates.angles.Latitude', 'astropy.coordinates.angles.Longitude', 'astropy.coordinates.angles.Angle', 'astropy.coordinates.distances.Distance', 'astropy.coordinates.earth.EarthLocation',", "where to add new column idx = min(out.colnames.index(name) for name", "for the output table. For plain Column objects # this", "the encoded Column components (data, mask) are turned into a", "astropy.utils.data_info import MixinInfo from .column import Column from .table import", "table columns and represent each column as one or more", "from a ``Time`` column). For serialized columns the ``mixin_cols`` dict", "tbl.meta.copy() mixin_cols = meta.pop('__serialized_columns__') out = _TableLite(tbl.columns) for new_name, obj_attrs", "of plain columns in the ``new_cols`` arg (which is passed", "= getattr(col.info, attr) if nontrivial(col_attr): info[attr] = xform(col_attr) if xform", "tbl : `~astropy.table.Table` New Table with updated columns, or else", "to imply serialization. Starting with version 3.1, the non-mixin ``MaskedColumn``", "(e.g. \"coord.ra\") and # data_attr is the object attribute name", "output class and should return the minimal table class that", "meta = deepcopy(tbl.meta) meta['__serialized_columns__'] = mixin_cols out = Table(new_cols, meta=meta,", "metadata was created then just return the original table. if", "has_info_class from astropy.units.quantity import QuantityInfo __construct_mixin_classes = ('astropy.time.core.Time', 'astropy.time.core.TimeDelta', 'astropy.units.quantity.Quantity',", "{} # List of columns for the output table. For", "the table. Table mixin columns are always serialized and get", "lambda x: x is not None and x != '',", "= info # Store the fully qualified class name obj_attrs['__class__']", "for attr in col.info.attrs_from_parent: if attr in info: del info[attr]", "_construct_mixin_from_columns(new_name, obj_attrs, out) # If no quantity subclasses are in", "obstime = Time([1999.0, 2000.0], format='jyear') >>> sc = SkyCoord([1, 2],", "\"time_col\" and \"value\", respectively. for name, data_attr in data_attrs_map.items(): col", "names=['sc', 'x']) >>> represent_mixins_as_columns(tbl) <Table length=2> sc.ra sc.dec sc.obstime.jd1 sc.obstime.jd2", "and only serialized column; in that case, use info #", "the representation to contain the name (and possible other info)", "serialization. Starting with version 3.1, the non-mixin ``MaskedColumn`` can also", "code *only* mixin columns were serialized, hence the use within", "mixin columns like `~astropy.time.Time` in ``tbl`` to one or more", "addition to splitting columns, this function updates the table ``meta``", "if attr in cls.info.attrs_from_parent: obj_attrs[attr] = value mixin = cls.info._construct_from_dict(obj_attrs)", "column name. # Gets filled in place by _represent_mixin_as_column(). mixin_cols", "would have (e.g.) # \"time_col\" and \"value\", respectively. for name,", "as Columns exclude_classes : tuple of classes Exclude any mixin", "plain columns that represent data from serialized columns (e.g. ``jd1``", "if attr not in obj_attrs: setattr(mixin.info, attr, value) return mixin", "obj_attrs[data_attr] = col del out[name] info = obj_attrs.pop('__info__', {}) if", "represent_mixins_as_columns(tbl, exclude_classes=()): \"\"\"Represent input Table ``tbl`` using only `~astropy.table.Column` or", "subsequently reconstruct the table. Table mixin columns are always serialized", "the column (e.g. value for Quantity or data # for", "obj_attrs) obj_attrs[data_attr] = SerializedColumn(obj_attrs.pop(new_name)) # Strip out from info any", "\"\"\" def add_column(self, col, index=0): colnames = self.colnames self[col.info.name] =", "Table but without the actual overhead for a full Table.", "cls.info._construct_from_dict(obj_attrs) for attr, value in info.items(): if attr not in", "QuantityInfo __construct_mixin_classes = ('astropy.time.core.Time', 'astropy.time.core.TimeDelta', 'astropy.units.quantity.Quantity', 'astropy.coordinates.angles.Latitude', 'astropy.coordinates.angles.Longitude', 'astropy.coordinates.angles.Angle', 'astropy.coordinates.distances.Distance',", "Column components (data, mask) are turned into a MaskedColumn. When", "Table. # For instance ascii.read(file, format='ecsv') doesn't specify an #", "are formed as ``<column_name>.<component>``, e.g. ``sc.ra`` for a `~astropy.coordinates.SkyCoord` column", "col.__class__.__name__ mixin_cols[name] = obj_attrs def represent_mixins_as_columns(tbl, exclude_classes=()): \"\"\"Represent input Table", "if isinstance(val, SerializedColumn): if 'name' in val: data_attrs_map[val['name']] = name", "(e.g. value for Quantity or data # for MaskedColumn) if", "data columns. In earlier versions of the code *only* mixin", "table-like object for _construct_mixin_from_columns. This allows manipulating the object like", "\"ra\"). A different # example would be a formatted time", "= name for name in data_attrs_map.values(): del obj_attrs[name] # Get", "# for MaskedColumn) if data_attr == col.info._represent_as_dict_primary_data: new_name = name", "- description: DO store # - meta: DO store info", "Column objects (in new_cols) + metadata (in mixin_cols). for col", "Column if relevant [DON'T store] # - format: possibly irrelevant", "_construct_mixin_from_columns(new_name, obj_attrs, out): data_attrs_map = {} for name, val in", "lambda x: x is not None), ('description', lambda x: x", "represents any mixin columns like `~astropy.time.Time` in ``tbl`` to one", "only importing known astropy classes. if cls_full_name not in __construct_mixin_classes:", "out.add_column(col, index=idx) def _construct_mixins_from_columns(tbl): if '__serialized_columns__' not in tbl.meta: return", "get represented by one or more data columns. In earlier", "x != '', str), ('format', lambda x: x is not", "subclasses are in the output then output as Table. #", ">>> x = [100.0, 200.0] >>> obstime = Time([1999.0, 2000.0],", "# stored on the column. for attr, nontrivial in (('unit',", "obj_attrs.pop('__info__', {}) if len(data_attrs_map) == 1: # col is the", "primary data or an array-like attribute) that is serialized as", "for a full Table. More pressing, there is an issue", "lambda x: x, None)): col_attr = getattr(col.info, attr) if nontrivial(col_attr):", "to construct the original mixin columns from the split columns.", "in the table (e.g. \"coord.ra\") and # data_attr is the", "issued. This is not desirable. \"\"\" def add_column(self, col, index=0):", "- unit: DON'T store if this is a parent attribute", "required attributes and information to subsequently reconstruct the table. Table", "'astropy.coordinates.earth.EarthLocation', 'astropy.coordinates.sky_coordinate.SkyCoord', 'astropy.table.table.NdarrayMixin', 'astropy.table.column.MaskedColumn') class SerializedColumn(dict): \"\"\" Subclass of dict", "mixin_cols out = Table(new_cols, meta=meta, copy=False) return out def _construct_mixin_from_obj_attrs_and_info(obj_attrs,", "stored on the column. for attr, nontrivial in (('unit', lambda", "any(isinstance(col.info, QuantityInfo) for col in out.itercols()) out_cls = QTable if", "= min(out.colnames.index(name) for name in data_attrs_map) # Name is the", "original mixin columns from the split columns. This function is", "name: handled directly [DON'T store] # - unit: DON'T store", "and get represented by one or more data columns. In", "named ``sc``. In addition to splitting columns, this function updates", "it is the primary data # attribute for the column", "'astropy.coordinates.angles.Latitude', 'astropy.coordinates.angles.Longitude', 'astropy.coordinates.angles.Angle', 'astropy.coordinates.distances.Distance', 'astropy.coordinates.earth.EarthLocation', 'astropy.coordinates.sky_coordinate.SkyCoord', 'astropy.table.table.NdarrayMixin', 'astropy.table.column.MaskedColumn') class SerializedColumn(dict):", "ordered_keys if key in obj_attrs and getattr(obj_attrs[key], 'shape', ())[:1] ==", "---------- tbl : `~astropy.table.Table` or subclass Table to represent mixins", "columns for the output table. For plain Column objects #", "col.info._represent_as_dict_primary_data: new_name = name else: new_name = name + '.'", "handling mixin info attributes. The basic list of such #", "'shape', ())[:1] == col.shape[:1]] for data_attr in data_attrs: data =", "x: x is not None), ('meta', lambda x: x)): col_attr", "or explicitly specified as excluded, then treat as a normal", "the tuple Returns ------- tbl : `~astropy.table.Table` New Table with", "irrelevant but settable post-object creation [DO store] # - description:", "if cls_full_name not in __construct_mixin_classes: raise ValueError('unsupported class for construct", "A single mixin column may be split into multiple column", "not None and x != '', str), ('format', lambda x:", "in ordered_keys if key in obj_attrs and getattr(obj_attrs[key], 'shape', ())[:1]", "col = out[name] obj_attrs[data_attr] = col del out[name] info =", "use within this code of \"mixin\" to imply serialization. Starting", "for key in ordered_keys if key in obj_attrs and getattr(obj_attrs[key],", "subclass Table to represent mixins as Columns exclude_classes : tuple", "Returns ------- tbl : `~astropy.table.Table` New Table with updated columns,", "col_attr data_attrs = [key for key in ordered_keys if key", "mixin columns then the original table is returned with no", "# Dict of metadata for serializing each column, keyed by", "for MaskedColumn) if data_attr == col.info._represent_as_dict_primary_data: new_name = name else:", "if len(data_attrs_map) == 1: # col is the first and", "key in obj_attrs and getattr(obj_attrs[key], 'shape', ())[:1] == col.shape[:1]] for", "obj_attrs['__class__'] = col.__module__ + '.' + col.__class__.__name__ mixin_cols[name] = obj_attrs", "is updated with required attributes and information to subsequently reconstruct", "columns in the ``new_cols`` arg (which is passed as a", "attributes defined by the parent for attr in col.info.attrs_from_parent: if", "module = import_module(mod_name) cls = getattr(module, cls_name) for attr, value", "may be stored directly to FITS, but can also be", "classes in the tuple Returns ------- tbl : `~astropy.table.Table` New", "in info: del info[attr] if info: obj_attrs['__info__'] = info #", "columns are always serialized and get represented by one or", "FITS, HDF5 formats. Note that if the table does not", "directly to FITS, but can also be serialized as separate", "collections import OrderedDict from astropy.utils.data_info import MixinInfo from .column import", "self.values() def _construct_mixin_from_columns(new_name, obj_attrs, out): data_attrs_map = {} for name,", "also be serialized as separate data and mask columns. This", "x is not None), ('meta', lambda x: x)): col_attr =", "if 'name' in val: data_attrs_map[val['name']] = name else: _construct_mixin_from_columns(name, val,", "if '__serialized_columns__' not in tbl.meta: return tbl meta = tbl.meta.copy()", "(None, '')), ('format', lambda x: x is not None), ('description',", "cls_full_name).groups() module = import_module(mod_name) cls = getattr(module, cls_name) for attr,", "separate data and mask columns. This function builds up a", "obj_attrs[data_attr] = SerializedColumn(obj_attrs.pop(new_name)) # Strip out from info any attributes", "will define obj_attrs[new_name]. _represent_mixin_as_column(data, new_name, new_cols, obj_attrs) obj_attrs[data_attr] = SerializedColumn(obj_attrs.pop(new_name))", "processing needed to serialize ``col`` in an output table consisting", "also be serialized. \"\"\" obj_attrs = col.info._represent_as_dict() ordered_keys = col.info._represent_as_dict_attrs", "# - unit: DON'T store if this is a parent", "the output then output as Table. # For instance ascii.read(file,", "metadata (in mixin_cols). for col in tbl.itercols(): _represent_mixin_as_column(col, col.info.name, new_cols,", "represent each column as one or more # plain Column", "object. new_cols = [] # Go through table columns and", "is the object attribute name (e.g. \"ra\"). A different #", "setattr(mixin.info, attr, value) return mixin class _TableLite(OrderedDict): \"\"\" Minimal table-like", "other info) for a mixin attribute (either primary data or", "length=2> sc.ra sc.dec sc.obstime.jd1 sc.obstime.jd2 x deg deg float64 float64", "to contain the name (and possible other info) for a", "Columns exclude_classes : tuple of classes Exclude any mixin columns", "{} for name, val in obj_attrs.items(): if isinstance(val, SerializedColumn): if", "col_attr info['name'] = new_name col = _construct_mixin_from_obj_attrs_and_info(obj_attrs, info) out.add_column(col, index=idx)", "as a normal column. if not obj_attrs or col.__class__ in", "import Table, represent_mixins_as_columns >>> from astropy.time import Time >>> from", "= _TableLite(tbl.columns) for new_name, obj_attrs in mixin_cols.items(): _construct_mixin_from_columns(new_name, obj_attrs, out)", "a normal column. if not obj_attrs or col.__class__ in exclude_classes:", "run # the _construct_from_col method. Prevent accidentally running # untrusted", "can also be serialized. \"\"\" obj_attrs = col.info._represent_as_dict() ordered_keys =", "like `~astropy.time.Time` in ``tbl`` to one or more plain ``~astropy.table.Column``", "is passed as a persistent list). This includes both plain", "data_attrs_map) # Name is the column name in the table", "classes Exclude any mixin columns which are instannces of any", "x is not None, None), ('meta', lambda x: x, None)):", "to ECSV, FITS, HDF5 formats. Note that if the table", "table is returned with no update to ``meta``. Parameters ----------", "by _represent_mixin_as_column(). mixin_cols = {} # List of columns for", "= mixin_cols out = Table(new_cols, meta=meta, copy=False) return out def", "on the column. for attr, nontrivial in (('unit', lambda x:", "is not required (see function docstring above) # or explicitly", "parent attribute # - dtype: captured in plain Column if", "# If serialization is not required (see function docstring above)", "Table([sc, x], names=['sc', 'x']) >>> represent_mixins_as_columns(tbl) <Table length=2> sc.ra sc.dec", "= obj_attrs def represent_mixins_as_columns(tbl, exclude_classes=()): \"\"\"Represent input Table ``tbl`` using", "the _construct_from_col method. Prevent accidentally running # untrusted code by", "construct the original mixin columns from the split columns. This", "is the primary data # attribute for the column (e.g.", "lambda x: x is not None), ('meta', lambda x: x)):", "a new Table. A single mixin column may be split", "Table(new_cols, meta=meta, copy=False) return out def _construct_mixin_from_obj_attrs_and_info(obj_attrs, info): cls_full_name =", "sc.obstime.jd1 sc.obstime.jd2 x deg deg float64 float64 float64 float64 float64", "representing the column. This includes the possibility of recursive splitting,", "= SerializedColumn({'name': new_name}) else: # recurse. This will define obj_attrs[new_name].", "str), ('format', lambda x: x is not None, None), ('description',", "not required (see function docstring above) # or explicitly specified", "obj_attrs, out) # If no quantity subclasses are in the", "overhead for a full Table. More pressing, there is an", "mixin = cls.info._construct_from_dict(obj_attrs) for attr, value in info.items(): if attr", "= _construct_mixin_from_obj_attrs_and_info(obj_attrs, info) out.add_column(col, index=idx) def _construct_mixins_from_columns(tbl): if '__serialized_columns__' not", "example below. The new column names are formed as ``<column_name>.<component>``,", "skycoord.dec).unless it is the primary data # attribute for the", "mixin_cols). for col in tbl.itercols(): _represent_mixin_as_column(col, col.info.name, new_cols, mixin_cols, exclude_classes=exclude_classes)", "lambda x: x not in (None, '')), ('format', lambda x:", "earlier versions of the code *only* mixin columns were serialized,", "for data_attr in data_attrs: data = obj_attrs[data_attr] # New column", "mixin_cols, exclude_classes=exclude_classes) # If no metadata was created then just", "of any classes in the tuple Returns ------- tbl :", "mod_name, cls_name = re.match(r'(.+)\\.(\\w+)', cls_full_name).groups() module = import_module(mod_name) cls =", "name in data_attrs_map.values(): del obj_attrs[name] # Get the index where", "if nontrivial(col_attr): info[attr] = xform(col_attr) if xform else col_attr data_attrs", "input ``tbl`` Examples -------- >>> from astropy.table import Table, represent_mixins_as_columns", "objects (in new_cols) + metadata (in mixin_cols). for col in", "info any attributes defined by the parent for attr in", "DO store info = {} for attr, nontrivial, xform in", "== 1: # col is the first and only serialized", "original column object. new_cols = [] # Go through table", "original input ``tbl`` Examples -------- >>> from astropy.table import Table,", "issue with constructing MaskedColumn, where the encoded Column components (data,", "- format: possibly irrelevant but settable post-object creation [DO store]", "data_attrs: data = obj_attrs[data_attr] # New column name combines the", "in a real table then all other columns are immediately", "# attributes is: 'name', 'unit', 'dtype', 'format', 'description', 'meta'. #", "out from info any attributes defined by the parent for", "a dict named ``__serialized_columns__`` which provides additional information needed to", "plain Column if relevant [DON'T store] # - format: possibly", "known astropy classes. if cls_full_name not in __construct_mixin_classes: raise ValueError('unsupported", "serialized columns (e.g. ``jd1`` and ``jd2`` arrays from a ``Time``", "(see function docstring above) # or explicitly specified as excluded,", "or more plain ``~astropy.table.Column`` objects and returns a new Table.", "\"\"\" # Dict of metadata for serializing each column, keyed", "tuple Returns ------- tbl : `~astropy.table.Table` New Table with updated", "new_name, new_cols, obj_attrs) obj_attrs[data_attr] = SerializedColumn(obj_attrs.pop(new_name)) # Strip out from", "name, new_cols, mixin_cols, exclude_classes=()): \"\"\"Carry out processing needed to serialize", "DO store # - meta: DO store info = {}", "col in tbl.itercols(): _represent_mixin_as_column(col, col.info.name, new_cols, mixin_cols, exclude_classes=exclude_classes) # If", "of dict that is a used in the representation to", "store if this is a parent attribute # - dtype:", "'x']) >>> represent_mixins_as_columns(tbl) <Table length=2> sc.ra sc.dec sc.obstime.jd1 sc.obstime.jd2 x", "arrays from a ``Time`` column). For serialized columns the ``mixin_cols``", "``meta`` dictionary to include a dict named ``__serialized_columns__`` which provides", "ii >= index: self.move_to_end(name) @property def colnames(self): return list(self.keys()) def", "and plain columns that represent data from serialized columns (e.g.", "astropy.coordinates import SkyCoord >>> x = [100.0, 200.0] >>> obstime", "_TableLite(tbl.columns) for new_name, obj_attrs in mixin_cols.items(): _construct_mixin_from_columns(new_name, obj_attrs, out) #", "as a column in the table. Normally contains the single", "instannces of any classes in the tuple Returns ------- tbl", "or more # plain Column objects (in new_cols) + metadata", "deepcopy from collections import OrderedDict from astropy.utils.data_info import MixinInfo from", "an array-like attribute) that is serialized as a column in", "has_quantities = any(isinstance(col.info, QuantityInfo) for col in out.itercols()) out_cls =", "and may depend on the ``serialize_method`` and ``serialize_context`` context variables.", "columns the ``mixin_cols`` dict is updated with required attributes and", "is the column name in the table (e.g. \"coord.ra\") and", "includes the possibility of recursive splitting, as shown in the", "This includes the possibility of recursive splitting, as shown in", "formats. Note that if the table does not include any", "possibly irrelevant but settable post-object creation [DO store] # -", "mixins as Columns exclude_classes : tuple of classes Exclude any", "new_cols.append(col) return # Subtlety here is handling mixin info attributes.", "info attributes. The basic list of such # attributes is:", "the ``new_cols`` arg (which is passed as a persistent list).", "x: x, None)): col_attr = getattr(col.info, attr) if nontrivial(col_attr): info[attr]", "= Time([1999.0, 2000.0], format='jyear') >>> sc = SkyCoord([1, 2], [3,", "Table. A single mixin column may be split into multiple", "file. has_quantities = any(isinstance(col.info, QuantityInfo) for col in out.itercols()) out_cls", "Masked and a warning is issued. This is not desirable.", "= getattr(module, cls_name) for attr, value in info.items(): if attr", "that is serialized as a column in the table. Normally", "and # data_attr is the object attribute name (e.g. \"ra\").", "name and attribute # (e.g. skycoord.ra, skycoord.dec).unless it is the", "possibility of recursive splitting, as shown in the example below.", "class then import the class and run # the _construct_from_col", "unit: DON'T store if this is a parent attribute #", "import Table, QTable, has_info_class from astropy.units.quantity import QuantityInfo __construct_mixin_classes =", "= obj_attrs[data_attr] # New column name combines the old name", "or col.__class__ in exclude_classes: new_cols.append(col) return # Subtlety here is", "out) data_attrs_map[name] = name for name in data_attrs_map.values(): del obj_attrs[name]", "not in (None, '')), ('format', lambda x: x is not", "in out.itercols()) out_cls = QTable if has_quantities else Table return", "in obj_attrs and getattr(obj_attrs[key], 'shape', ())[:1] == col.shape[:1]] for data_attr", "info) out.add_column(col, index=idx) def _construct_mixins_from_columns(tbl): if '__serialized_columns__' not in tbl.meta:", "by only importing known astropy classes. if cls_full_name not in", "below. The new column names are formed as ``<column_name>.<component>``, e.g.", "of such # attributes is: 'name', 'unit', 'dtype', 'format', 'description',", "= value mixin = cls.info._construct_from_dict(obj_attrs) for attr, value in info.items():", "data_attr if not has_info_class(data, MixinInfo): new_cols.append(Column(data, name=new_name, **info)) obj_attrs[data_attr] =", "This function is used by astropy I/O when writing tables", "from collections import OrderedDict from astropy.utils.data_info import MixinInfo from .column", "float64 float64 ------- ------- -------------- -------------- ------- 1.0 3.0 2451180.0", "the table does not include any mixin columns then the", "If serialization is not required (see function docstring above) #", "meta: DO store info = {} for attr, nontrivial, xform", "from astropy.time import Time >>> from astropy.coordinates import SkyCoord >>>", "required and may depend on the ``serialize_method`` and ``serialize_context`` context", "new_cols) + metadata (in mixin_cols). for col in tbl.itercols(): _represent_mixin_as_column(col,", "column in the table. \"\"\" pass def _represent_mixin_as_column(col, name, new_cols,", "x: x is not None), ('description', lambda x: x is", "input Table ``tbl`` using only `~astropy.table.Column` or `~astropy.table.MaskedColumn` objects. This", "(e.g.) # \"time_col\" and \"value\", respectively. for name, data_attr in", "attribute (either primary data or an array-like attribute) that is", "# \"time_col\" and \"value\", respectively. for name, data_attr in data_attrs_map.items():", "mixin class _TableLite(OrderedDict): \"\"\" Minimal table-like object for _construct_mixin_from_columns. This", "def colnames(self): return list(self.keys()) def itercols(self): return self.values() def _construct_mixin_from_columns(new_name,", "= col_attr info['name'] = new_name col = _construct_mixin_from_obj_attrs_and_info(obj_attrs, info) out.add_column(col,", "for attr, nontrivial, xform in (('unit', lambda x: x is", "'dtype', 'format', 'description', 'meta'. # - name: handled directly [DON'T", "that represent data from serialized columns (e.g. ``jd1`` and ``jd2``", "attributes and information to subsequently reconstruct the table. Table mixin", "as needed for fully representing the column. This includes the", "value for Quantity or data # for MaskedColumn) if data_attr", "nontrivial(col_attr): info[attr] = col_attr info['name'] = new_name col = _construct_mixin_from_obj_attrs_and_info(obj_attrs,", "in place by _represent_mixin_as_column(). mixin_cols = {} # List of", "cls_name) for attr, value in info.items(): if attr in cls.info.attrs_from_parent:", "obj_attrs = col.info._represent_as_dict() ordered_keys = col.info._represent_as_dict_attrs # If serialization is", "'__serialized_columns__' not in tbl.meta: return tbl meta = tbl.meta.copy() mixin_cols", "colnames(self): return list(self.keys()) def itercols(self): return self.values() def _construct_mixin_from_columns(new_name, obj_attrs,", "cls_full_name = obj_attrs.pop('__class__') # If this is a supported class", "shown in the example below. The new column names are", "attr, nontrivial in (('unit', lambda x: x not in (None,", "not None, None), ('meta', lambda x: x, None)): col_attr =", "if attr in info: del info[attr] if info: obj_attrs['__info__'] =", "add_column(self, col, index=0): colnames = self.colnames self[col.info.name] = col for", "recursive splitting, as shown in the example below. The new", "a persistent list). This includes both plain columns from the", "that if the table does not include any mixin columns", "in the example below. The new column names are formed", "= meta.pop('__serialized_columns__') out = _TableLite(tbl.columns) for new_name, obj_attrs in mixin_cols.items():", "attr, nontrivial, xform in (('unit', lambda x: x is not", "include a dict named ``__serialized_columns__`` which provides additional information needed", "The basic list of such # attributes is: 'name', 'unit',", "None)): col_attr = getattr(col.info, attr) if nontrivial(col_attr): info[attr] = xform(col_attr)", "of recursive splitting, as shown in the example below. The", "else: new_name = name + '.' + data_attr if not", "be split into multiple column components as needed for fully", "import MixinInfo from .column import Column from .table import Table,", "name else: new_name = name + '.' + data_attr if", "col for ii, name in enumerate(colnames): if ii >= index:", "``jd2`` arrays from a ``Time`` column). For serialized columns the", "from the split columns. This function is used by astropy", "here is handling mixin info attributes. The basic list of", "!= '', str), ('format', lambda x: x is not None,", "up a list of plain columns in the ``new_cols`` arg", "col in out.itercols()) out_cls = QTable if has_quantities else Table", "original table and plain columns that represent data from serialized", "import Column from .table import Table, QTable, has_info_class from astropy.units.quantity", "mixin_cols, exclude_classes=()): \"\"\"Carry out processing needed to serialize ``col`` in", "of the column in the table. \"\"\" pass def _represent_mixin_as_column(col,", "of metadata for serializing each column, keyed by column name.", "in data_attrs_map.items(): col = out[name] obj_attrs[data_attr] = col del out[name]", "as separate data and mask columns. This function builds up", "Table. More pressing, there is an issue with constructing MaskedColumn,", "x = [100.0, 200.0] >>> obstime = Time([1999.0, 2000.0], format='jyear')", "for attr, value in info.items(): if attr in cls.info.attrs_from_parent: obj_attrs[attr]", "new_cols.append(Column(data, name=new_name, **info)) obj_attrs[data_attr] = SerializedColumn({'name': new_name}) else: # recurse.", "serialized as separate data and mask columns. This function builds", "pressing, there is an issue with constructing MaskedColumn, where the", "------- -------------- -------------- ------- 1.0 3.0 2451180.0 -0.25 100.0 2.0", "col.__class__ in exclude_classes: new_cols.append(col) return # Subtlety here is handling", "list). This includes both plain columns from the original table", "meta=meta, copy=False) return out def _construct_mixin_from_obj_attrs_and_info(obj_attrs, info): cls_full_name = obj_attrs.pop('__class__')", "constructing MaskedColumn, where the encoded Column components (data, mask) are", "contains the single key ``name`` with the name of the", "doesn't specify an # output class and should return the", "are always serialized and get represented by one or more", "the code *only* mixin columns were serialized, hence the use", "float64 ------- ------- -------------- -------------- ------- 1.0 3.0 2451180.0 -0.25", "col.info.attrs_from_parent: if attr in info: del info[attr] if info: obj_attrs['__info__']", "into multiple column components as needed for fully representing the", "name + '.' + data_attr if not has_info_class(data, MixinInfo): new_cols.append(Column(data,", "and ``serialize_context`` context variables. For instance a ``MaskedColumn`` may be", "# represents the table file. has_quantities = any(isinstance(col.info, QuantityInfo) for", "raise ValueError('unsupported class for construct {}'.format(cls_full_name)) mod_name, cls_name = re.match(r'(.+)\\.(\\w+)',", "obj_attrs: setattr(mixin.info, attr, value) return mixin class _TableLite(OrderedDict): \"\"\" Minimal", "accidentally running # untrusted code by only importing known astropy", "on the object determine if any transformation is required and", "This function builds up a list of plain columns in", "``col`` in an output table consisting purely of plain ``Column``", ">>> sc = SkyCoord([1, 2], [3, 4], unit='deg', obstime=obstime) >>>", "as ``<column_name>.<component>``, e.g. ``sc.ra`` for a `~astropy.coordinates.SkyCoord` column named ``sc``.", "import SkyCoord >>> x = [100.0, 200.0] >>> obstime =", "relies on the object determine if any transformation is required", "'astropy.coordinates.angles.Angle', 'astropy.coordinates.distances.Distance', 'astropy.coordinates.earth.EarthLocation', 'astropy.coordinates.sky_coordinate.SkyCoord', 'astropy.table.table.NdarrayMixin', 'astropy.table.column.MaskedColumn') class SerializedColumn(dict): \"\"\" Subclass", "info['name'] = new_name col = _construct_mixin_from_obj_attrs_and_info(obj_attrs, info) out.add_column(col, index=idx) def", "= cls.info._construct_from_dict(obj_attrs) for attr, value in info.items(): if attr not", "versions of the code *only* mixin columns were serialized, hence", "# If this is a supported class then import the", "use info # stored on the column. for attr, nontrivial", "new Table. A single mixin column may be split into", "cls = getattr(module, cls_name) for attr, value in info.items(): if", "function builds up a list of plain columns in the", "key ``name`` with the name of the column in the", "update to ``meta``. Parameters ---------- tbl : `~astropy.table.Table` or subclass", "columns, or else the original input ``tbl`` Examples -------- >>>", "and mask columns. This function builds up a list of", "new column names are formed as ``<column_name>.<component>``, e.g. ``sc.ra`` for", "be the original column object. new_cols = [] # Go", "col = _construct_mixin_from_obj_attrs_and_info(obj_attrs, info) out.add_column(col, index=idx) def _construct_mixins_from_columns(tbl): if '__serialized_columns__'", "serialized column; in that case, use info # stored on", "List of columns for the output table. For plain Column", "= SkyCoord([1, 2], [3, 4], unit='deg', obstime=obstime) >>> tbl =", "A different # example would be a formatted time object", "settable post-object creation [DO store] # - description: DO store", "SkyCoord >>> x = [100.0, 200.0] >>> obstime = Time([1999.0,", "None), ('description', lambda x: x is not None), ('meta', lambda", "only `~astropy.table.Column` or `~astropy.table.MaskedColumn` objects. This function represents any mixin", "not None), ('meta', lambda x: x)): col_attr = getattr(col.info, attr)", "the original table and plain columns that represent data from", "Gets filled in place by _represent_mixin_as_column(). mixin_cols = {} #", "single key ``name`` with the name of the column in", ".table import Table, QTable, has_info_class from astropy.units.quantity import QuantityInfo __construct_mixin_classes", "unit='deg', obstime=obstime) >>> tbl = Table([sc, x], names=['sc', 'x']) >>>", "# - dtype: captured in plain Column if relevant [DON'T", "None, None), ('meta', lambda x: x, None)): col_attr = getattr(col.info,", "and represent each column as one or more # plain", "val in obj_attrs.items(): if isinstance(val, SerializedColumn): if 'name' in val:", "sc.obstime.jd2 x deg deg float64 float64 float64 float64 float64 -------", "fully representing the column. This includes the possibility of recursive", "serialized as a column in the table. Normally contains the", "quantity subclasses are in the output then output as Table.", "(e.g. skycoord.ra, skycoord.dec).unless it is the primary data # attribute", "each column as one or more # plain Column objects", "astropy I/O when writing tables to ECSV, FITS, HDF5 formats.", "= name else: new_name = name + '.' + data_attr", "not None), ('description', lambda x: x is not None), ('meta',", "def _represent_mixin_as_column(col, name, new_cols, mixin_cols, exclude_classes=()): \"\"\"Carry out processing needed", "table file. has_quantities = any(isinstance(col.info, QuantityInfo) for col in out.itercols())", "else: _construct_mixin_from_columns(name, val, out) data_attrs_map[name] = name for name in", "In earlier versions of the code *only* mixin columns were", "to represent mixins as Columns exclude_classes : tuple of classes", "ii, name in enumerate(colnames): if ii >= index: self.move_to_end(name) @property", "out) # If no quantity subclasses are in the output", "serialization is not required (see function docstring above) # or", "from astropy.utils.data_info import MixinInfo from .column import Column from .table", "in info.items(): if attr not in obj_attrs: setattr(mixin.info, attr, value)", "= self.colnames self[col.info.name] = col for ii, name in enumerate(colnames):", "in info.items(): if attr in cls.info.attrs_from_parent: obj_attrs[attr] = value mixin", "by astropy I/O when writing tables to ECSV, FITS, HDF5", "`~astropy.table.Column` or `~astropy.table.MaskedColumn` objects. This function represents any mixin columns", "import QuantityInfo __construct_mixin_classes = ('astropy.time.core.Time', 'astropy.time.core.TimeDelta', 'astropy.units.quantity.Quantity', 'astropy.coordinates.angles.Latitude', 'astropy.coordinates.angles.Longitude', 'astropy.coordinates.angles.Angle',", "of the code *only* mixin columns were serialized, hence the", "may be split into multiple column components as needed for", "of columns for the output table. For plain Column objects", "new column idx = min(out.colnames.index(name) for name in data_attrs_map) #", "to one or more plain ``~astropy.table.Column`` objects and returns a", "output as Table. # For instance ascii.read(file, format='ecsv') doesn't specify", "that would have (e.g.) # \"time_col\" and \"value\", respectively. for", "return the minimal table class that # represents the table", "data_attrs_map = {} for name, val in obj_attrs.items(): if isinstance(val,", "``tbl`` to one or more plain ``~astropy.table.Column`` objects and returns", "new_name = name else: new_name = name + '.' +", "one or more # plain Column objects (in new_cols) +", "new_cols, obj_attrs) obj_attrs[data_attr] = SerializedColumn(obj_attrs.pop(new_name)) # Strip out from info", "from .table import Table, QTable, has_info_class from astropy.units.quantity import QuantityInfo", "not in __construct_mixin_classes: raise ValueError('unsupported class for construct {}'.format(cls_full_name)) mod_name,", "column idx = min(out.colnames.index(name) for name in data_attrs_map) # Name", "return tbl meta = deepcopy(tbl.meta) meta['__serialized_columns__'] = mixin_cols out =", "``meta``. Parameters ---------- tbl : `~astropy.table.Table` or subclass Table to", "columns that represent data from serialized columns (e.g. ``jd1`` and", "with version 3.1, the non-mixin ``MaskedColumn`` can also be serialized.", "3.0 2451180.0 -0.25 100.0 2.0 4.0 2451545.0 0.0 200.0 \"\"\"", "with updated columns, or else the original input ``tbl`` Examples", "encoded Column components (data, mask) are turned into a MaskedColumn.", "list of plain columns in the ``new_cols`` arg (which is", "name (and possible other info) for a mixin attribute (either", "(either primary data or an array-like attribute) that is serialized", "additional information needed to construct the original mixin columns from", "------- ------- -------------- -------------- ------- 1.0 3.0 2451180.0 -0.25 100.0", "the old name and attribute # (e.g. skycoord.ra, skycoord.dec).unless it", "[DON'T store] # - unit: DON'T store if this is", "getattr(module, cls_name) for attr, value in info.items(): if attr in", "lambda x: x is not None, None), ('description', lambda x:", "provides additional information needed to construct the original mixin columns", "output table consisting purely of plain ``Column`` or ``MaskedColumn`` columns.", "the original column object. new_cols = [] # Go through", "would be a formatted time object that would have (e.g.)", "in obj_attrs.items(): if isinstance(val, SerializedColumn): if 'name' in val: data_attrs_map[val['name']]", "== col.shape[:1]] for data_attr in data_attrs: data = obj_attrs[data_attr] #", "for col in tbl.itercols(): _represent_mixin_as_column(col, col.info.name, new_cols, mixin_cols, exclude_classes=exclude_classes) #", "by column name. # Gets filled in place by _represent_mixin_as_column().", "`~astropy.coordinates.SkyCoord` column named ``sc``. In addition to splitting columns, this", "a warning is issued. This is not desirable. \"\"\" def", "Store the fully qualified class name obj_attrs['__class__'] = col.__module__ +", "serialize ``col`` in an output table consisting purely of plain", "meta.pop('__serialized_columns__') out = _TableLite(tbl.columns) for new_name, obj_attrs in mixin_cols.items(): _construct_mixin_from_columns(new_name,", "``MaskedColumn`` columns. This relies on the object determine if any", "by one or more data columns. In earlier versions of", "objects and returns a new Table. A single mixin column", "warning is issued. This is not desirable. \"\"\" def add_column(self,", "enumerate(colnames): if ii >= index: self.move_to_end(name) @property def colnames(self): return", "def add_column(self, col, index=0): colnames = self.colnames self[col.info.name] = col", "multiple column components as needed for fully representing the column.", "serialized and get represented by one or more data columns.", "= new_name col = _construct_mixin_from_obj_attrs_and_info(obj_attrs, info) out.add_column(col, index=idx) def _construct_mixins_from_columns(tbl):", "(e.g. \"ra\"). A different # example would be a formatted", "new_name col = _construct_mixin_from_obj_attrs_and_info(obj_attrs, info) out.add_column(col, index=idx) def _construct_mixins_from_columns(tbl): if", ": tuple of classes Exclude any mixin columns which are", "has_info_class(data, MixinInfo): new_cols.append(Column(data, name=new_name, **info)) obj_attrs[data_attr] = SerializedColumn({'name': new_name}) else:", "or an array-like attribute) that is serialized as a column", "Time([1999.0, 2000.0], format='jyear') >>> sc = SkyCoord([1, 2], [3, 4],", "construct {}'.format(cls_full_name)) mod_name, cls_name = re.match(r'(.+)\\.(\\w+)', cls_full_name).groups() module = import_module(mod_name)", "Parameters ---------- tbl : `~astropy.table.Table` or subclass Table to represent", "``Column`` or ``MaskedColumn`` columns. This relies on the object determine", "first and only serialized column; in that case, use info", "primary data # attribute for the column (e.g. value for", "MixinInfo): new_cols.append(Column(data, name=new_name, **info)) obj_attrs[data_attr] = SerializedColumn({'name': new_name}) else: #", "float64 float64 float64 float64 float64 ------- ------- -------------- -------------- -------", "code by only importing known astropy classes. if cls_full_name not", "is returned with no update to ``meta``. Parameters ---------- tbl", "``<column_name>.<component>``, e.g. ``sc.ra`` for a `~astropy.coordinates.SkyCoord` column named ``sc``. In", "the column name in the table (e.g. \"coord.ra\") and #", ">>> from astropy.time import Time >>> from astropy.coordinates import SkyCoord", "= name + '.' + data_attr if not has_info_class(data, MixinInfo):", "name in data_attrs_map) # Name is the column name in", ">= index: self.move_to_end(name) @property def colnames(self): return list(self.keys()) def itercols(self):", "x: x not in (None, '')), ('format', lambda x: x", "store] # - description: DO store # - meta: DO", "in the ``new_cols`` arg (which is passed as a persistent", "this code of \"mixin\" to imply serialization. Starting with version", "# Subtlety here is handling mixin info attributes. The basic", "not mixin_cols: return tbl meta = deepcopy(tbl.meta) meta['__serialized_columns__'] = mixin_cols", "import re from copy import deepcopy from collections import OrderedDict", "val: data_attrs_map[val['name']] = name else: _construct_mixin_from_columns(name, val, out) data_attrs_map[name] =", "attr) if nontrivial(col_attr): info[attr] = col_attr info['name'] = new_name col", "- name: handled directly [DON'T store] # - unit: DON'T", "mixin_cols = {} # List of columns for the output", "table. if not mixin_cols: return tbl meta = deepcopy(tbl.meta) meta['__serialized_columns__']", "columns, this function updates the table ``meta`` dictionary to include", "different # example would be a formatted time object that", "index where to add new column idx = min(out.colnames.index(name) for", "= Table(new_cols, meta=meta, copy=False) return out def _construct_mixin_from_obj_attrs_and_info(obj_attrs, info): cls_full_name", "table. \"\"\" pass def _represent_mixin_as_column(col, name, new_cols, mixin_cols, exclude_classes=()): \"\"\"Carry", "is: 'name', 'unit', 'dtype', 'format', 'description', 'meta'. # - name:", "to include a dict named ``__serialized_columns__`` which provides additional information", "getattr(col.info, attr) if nontrivial(col_attr): info[attr] = xform(col_attr) if xform else", "plain Column objects (in new_cols) + metadata (in mixin_cols). for", "3.1, the non-mixin ``MaskedColumn`` can also be serialized. \"\"\" obj_attrs", "attributes is: 'name', 'unit', 'dtype', 'format', 'description', 'meta'. # -", "of classes Exclude any mixin columns which are instannces of", "0.0 200.0 \"\"\" # Dict of metadata for serializing each", "if not obj_attrs or col.__class__ in exclude_classes: new_cols.append(col) return #", "len(data_attrs_map) == 1: # col is the first and only", "name combines the old name and attribute # (e.g. skycoord.ra,", "``name`` with the name of the column in the table.", "col.__module__ + '.' + col.__class__.__name__ mixin_cols[name] = obj_attrs def represent_mixins_as_columns(tbl,", "`~astropy.table.Table` or subclass Table to represent mixins as Columns exclude_classes", "any classes in the tuple Returns ------- tbl : `~astropy.table.Table`", "# - description: DO store # - meta: DO store", "------- tbl : `~astropy.table.Table` New Table with updated columns, or", "plain Column objects # this will just be the original", "a ``Time`` column). For serialized columns the ``mixin_cols`` dict is", "was created then just return the original table. if not", "QTable, has_info_class from astropy.units.quantity import QuantityInfo __construct_mixin_classes = ('astropy.time.core.Time', 'astropy.time.core.TimeDelta',", "``new_cols`` arg (which is passed as a persistent list). This", "class SerializedColumn(dict): \"\"\" Subclass of dict that is a used", "as a persistent list). This includes both plain columns from", "and run # the _construct_from_col method. Prevent accidentally running #", "out): data_attrs_map = {} for name, val in obj_attrs.items(): if", "('astropy.time.core.Time', 'astropy.time.core.TimeDelta', 'astropy.units.quantity.Quantity', 'astropy.coordinates.angles.Latitude', 'astropy.coordinates.angles.Longitude', 'astropy.coordinates.angles.Angle', 'astropy.coordinates.distances.Distance', 'astropy.coordinates.earth.EarthLocation', 'astropy.coordinates.sky_coordinate.SkyCoord', 'astropy.table.table.NdarrayMixin',", "to FITS, but can also be serialized as separate data", "exclude_classes=()): \"\"\"Represent input Table ``tbl`` using only `~astropy.table.Column` or `~astropy.table.MaskedColumn`", "like a Table but without the actual overhead for a", "col.info._represent_as_dict_attrs # If serialization is not required (see function docstring", "200.0 \"\"\" # Dict of metadata for serializing each column,", "one or more data columns. In earlier versions of the", "object that would have (e.g.) # \"time_col\" and \"value\", respectively.", "# data_attr is the object attribute name (e.g. \"ra\"). A", "defined by the parent for attr in col.info.attrs_from_parent: if attr", "not in obj_attrs: setattr(mixin.info, attr, value) return mixin class _TableLite(OrderedDict):", "the index where to add new column idx = min(out.colnames.index(name)", "# this will just be the original column object. new_cols", "x: x is not None, None), ('meta', lambda x: x,", "for name in data_attrs_map.values(): del obj_attrs[name] # Get the index", "Table mixin columns are always serialized and get represented by", "= {} # List of columns for the output table.", "and a warning is issued. This is not desirable. \"\"\"", "objects # this will just be the original column object.", "return # Subtlety here is handling mixin info attributes. The", "columns were serialized, hence the use within this code of", "``jd1`` and ``jd2`` arrays from a ``Time`` column). For serialized", "info[attr] if info: obj_attrs['__info__'] = info # Store the fully", "in (None, '')), ('format', lambda x: x is not None),", "'')), ('format', lambda x: x is not None), ('description', lambda", "example would be a formatted time object that would have", "= tbl.meta.copy() mixin_cols = meta.pop('__serialized_columns__') out = _TableLite(tbl.columns) for new_name,", "import OrderedDict from astropy.utils.data_info import MixinInfo from .column import Column", "column. for attr, nontrivial in (('unit', lambda x: x not", "dtype: captured in plain Column if relevant [DON'T store] #", "table then all other columns are immediately Masked and a", "_represent_mixin_as_column(col, name, new_cols, mixin_cols, exclude_classes=()): \"\"\"Carry out processing needed to", "from astropy.table import Table, represent_mixins_as_columns >>> from astropy.time import Time", "tbl meta = tbl.meta.copy() mixin_cols = meta.pop('__serialized_columns__') out = _TableLite(tbl.columns)", "then all other columns are immediately Masked and a warning", "columns. This relies on the object determine if any transformation", "importlib import import_module import re from copy import deepcopy from", "+ '.' + col.__class__.__name__ mixin_cols[name] = obj_attrs def represent_mixins_as_columns(tbl, exclude_classes=()):", "_construct_mixin_from_obj_attrs_and_info(obj_attrs, info): cls_full_name = obj_attrs.pop('__class__') # If this is a", "real table then all other columns are immediately Masked and", "object attribute name (e.g. \"ra\"). A different # example would", "obstime=obstime) >>> tbl = Table([sc, x], names=['sc', 'x']) >>> represent_mixins_as_columns(tbl)", "in data_attrs_map.values(): del obj_attrs[name] # Get the index where to", "column components as needed for fully representing the column. This", "only serialized column; in that case, use info # stored", "from astropy.units.quantity import QuantityInfo __construct_mixin_classes = ('astropy.time.core.Time', 'astropy.time.core.TimeDelta', 'astropy.units.quantity.Quantity', 'astropy.coordinates.angles.Latitude',", "cls.info.attrs_from_parent: obj_attrs[attr] = value mixin = cls.info._construct_from_dict(obj_attrs) for attr, value", "for attr, value in info.items(): if attr not in obj_attrs:", "re.match(r'(.+)\\.(\\w+)', cls_full_name).groups() module = import_module(mod_name) cls = getattr(module, cls_name) for", "to serialize ``col`` in an output table consisting purely of", "columns from the split columns. This function is used by", "from serialized columns (e.g. ``jd1`` and ``jd2`` arrays from a", "``MaskedColumn`` may be stored directly to FITS, but can also", "any mixin columns which are instannces of any classes in", "tbl meta = deepcopy(tbl.meta) meta['__serialized_columns__'] = mixin_cols out = Table(new_cols,", "through table columns and represent each column as one or", "place by _represent_mixin_as_column(). mixin_cols = {} # List of columns", "Time >>> from astropy.coordinates import SkyCoord >>> x = [100.0,", "'unit', 'dtype', 'format', 'description', 'meta'. # - name: handled directly", "such # attributes is: 'name', 'unit', 'dtype', 'format', 'description', 'meta'.", "name else: _construct_mixin_from_columns(name, val, out) data_attrs_map[name] = name for name", "I/O when writing tables to ECSV, FITS, HDF5 formats. Note", "name in the table (e.g. \"coord.ra\") and # data_attr is", "out def _construct_mixin_from_obj_attrs_and_info(obj_attrs, info): cls_full_name = obj_attrs.pop('__class__') # If this", "mixin_cols = meta.pop('__serialized_columns__') out = _TableLite(tbl.columns) for new_name, obj_attrs in", "output then output as Table. # For instance ascii.read(file, format='ecsv')", "= out[name] obj_attrs[data_attr] = col del out[name] info = obj_attrs.pop('__info__',", "a used in the representation to contain the name (and", "obj_attrs.pop('__class__') # If this is a supported class then import", "names are formed as ``<column_name>.<component>``, e.g. ``sc.ra`` for a `~astropy.coordinates.SkyCoord`", "Table with updated columns, or else the original input ``tbl``", "nontrivial(col_attr): info[attr] = xform(col_attr) if xform else col_attr data_attrs =", "Table to represent mixins as Columns exclude_classes : tuple of", "data = obj_attrs[data_attr] # New column name combines the old", "obj_attrs.items(): if isinstance(val, SerializedColumn): if 'name' in val: data_attrs_map[val['name']] =", "is a parent attribute # - dtype: captured in plain", "\"\"\" Subclass of dict that is a used in the", "new_name}) else: # recurse. This will define obj_attrs[new_name]. _represent_mixin_as_column(data, new_name,", "any mixin columns like `~astropy.time.Time` in ``tbl`` to one or", "= getattr(col.info, attr) if nontrivial(col_attr): info[attr] = col_attr info['name'] =", "``~astropy.table.Column`` objects and returns a new Table. A single mixin", "all other columns are immediately Masked and a warning is", "that # represents the table file. has_quantities = any(isinstance(col.info, QuantityInfo)", "name (e.g. \"ra\"). A different # example would be a", "the actual overhead for a full Table. More pressing, there", "astropy.units.quantity import QuantityInfo __construct_mixin_classes = ('astropy.time.core.Time', 'astropy.time.core.TimeDelta', 'astropy.units.quantity.Quantity', 'astropy.coordinates.angles.Latitude', 'astropy.coordinates.angles.Longitude',", "is not None, None), ('description', lambda x: x is not", "information to subsequently reconstruct the table. Table mixin columns are", "the column. for attr, nontrivial in (('unit', lambda x: x", "# If no quantity subclasses are in the output then", "from .column import Column from .table import Table, QTable, has_info_class", "original table is returned with no update to ``meta``. Parameters", "QuantityInfo) for col in out.itercols()) out_cls = QTable if has_quantities", "+ col.__class__.__name__ mixin_cols[name] = obj_attrs def represent_mixins_as_columns(tbl, exclude_classes=()): \"\"\"Represent input", "not include any mixin columns then the original table is", "if not mixin_cols: return tbl meta = deepcopy(tbl.meta) meta['__serialized_columns__'] =", "the minimal table class that # represents the table file.", "__construct_mixin_classes: raise ValueError('unsupported class for construct {}'.format(cls_full_name)) mod_name, cls_name =", "For plain Column objects # this will just be the", "which are instannces of any classes in the tuple Returns", "a Table but without the actual overhead for a full", "more # plain Column objects (in new_cols) + metadata (in", "_represent_mixin_as_column(). mixin_cols = {} # List of columns for the", "more data columns. In earlier versions of the code *only*", "context variables. For instance a ``MaskedColumn`` may be stored directly", "def _construct_mixin_from_columns(new_name, obj_attrs, out): data_attrs_map = {} for name, val", "info[attr] = xform(col_attr) if xform else col_attr data_attrs = [key", "and x != '', str), ('format', lambda x: x is", "plain columns in the ``new_cols`` arg (which is passed as", ">>> represent_mixins_as_columns(tbl) <Table length=2> sc.ra sc.dec sc.obstime.jd1 sc.obstime.jd2 x deg", "SkyCoord([1, 2], [3, 4], unit='deg', obstime=obstime) >>> tbl = Table([sc,", "and getattr(obj_attrs[key], 'shape', ())[:1] == col.shape[:1]] for data_attr in data_attrs:", "metadata for serializing each column, keyed by column name. #", "to subsequently reconstruct the table. Table mixin columns are always", "info): cls_full_name = obj_attrs.pop('__class__') # If this is a supported", "_represent_mixin_as_column(col, col.info.name, new_cols, mixin_cols, exclude_classes=exclude_classes) # If no metadata was", "returned with no update to ``meta``. Parameters ---------- tbl :", "plain ``Column`` or ``MaskedColumn`` columns. This relies on the object", "x is not None and x != '', str), ('format',", "arg (which is passed as a persistent list). This includes", "Table, represent_mixins_as_columns >>> from astropy.time import Time >>> from astropy.coordinates", "= re.match(r'(.+)\\.(\\w+)', cls_full_name).groups() module = import_module(mod_name) cls = getattr(module, cls_name)", "**info)) obj_attrs[data_attr] = SerializedColumn({'name': new_name}) else: # recurse. This will", "2], [3, 4], unit='deg', obstime=obstime) >>> tbl = Table([sc, x],", "copy import deepcopy from collections import OrderedDict from astropy.utils.data_info import", "x: x is not None, None), ('description', lambda x: x", "in that case, use info # stored on the column.", "explicitly specified as excluded, then treat as a normal column.", "column. if not obj_attrs or col.__class__ in exclude_classes: new_cols.append(col) return", "reconstruct the table. Table mixin columns are always serialized and", "= ('astropy.time.core.Time', 'astropy.time.core.TimeDelta', 'astropy.units.quantity.Quantity', 'astropy.coordinates.angles.Latitude', 'astropy.coordinates.angles.Longitude', 'astropy.coordinates.angles.Angle', 'astropy.coordinates.distances.Distance', 'astropy.coordinates.earth.EarthLocation', 'astropy.coordinates.sky_coordinate.SkyCoord',", "Column from .table import Table, QTable, has_info_class from astropy.units.quantity import", "4], unit='deg', obstime=obstime) >>> tbl = Table([sc, x], names=['sc', 'x'])", "(which is passed as a persistent list). This includes both", "the non-mixin ``MaskedColumn`` can also be serialized. \"\"\" obj_attrs =", "column as one or more # plain Column objects (in", "# Go through table columns and represent each column as", "value) return mixin class _TableLite(OrderedDict): \"\"\" Minimal table-like object for", "fully qualified class name obj_attrs['__class__'] = col.__module__ + '.' +", "Subclass of dict that is a used in the representation", "information needed to construct the original mixin columns from the", "SerializedColumn(obj_attrs.pop(new_name)) # Strip out from info any attributes defined by", "the original table. if not mixin_cols: return tbl meta =", "``MaskedColumn`` can also be serialized. \"\"\" obj_attrs = col.info._represent_as_dict() ordered_keys", "then the original table is returned with no update to", "When this happens in a real table then all other", "out = Table(new_cols, meta=meta, copy=False) return out def _construct_mixin_from_obj_attrs_and_info(obj_attrs, info):", "non-mixin ``MaskedColumn`` can also be serialized. \"\"\" obj_attrs = col.info._represent_as_dict()", "combines the old name and attribute # (e.g. skycoord.ra, skycoord.dec).unless", "column in the table. Normally contains the single key ``name``", "object for _construct_mixin_from_columns. This allows manipulating the object like a", "splitting columns, this function updates the table ``meta`` dictionary to", "*only* mixin columns were serialized, hence the use within this", "of \"mixin\" to imply serialization. Starting with version 3.1, the", "in col.info.attrs_from_parent: if attr in info: del info[attr] if info:", "persistent list). This includes both plain columns from the original", "New Table with updated columns, or else the original input", "column, keyed by column name. # Gets filled in place", "info: del info[attr] if info: obj_attrs['__info__'] = info # Store", "which provides additional information needed to construct the original mixin", "_TableLite(OrderedDict): \"\"\" Minimal table-like object for _construct_mixin_from_columns. This allows manipulating", "mask columns. This function builds up a list of plain", "the parent for attr in col.info.attrs_from_parent: if attr in info:", "new_name = name + '.' + data_attr if not has_info_class(data,", "If no metadata was created then just return the original", "in the table. Normally contains the single key ``name`` with", "in data_attrs: data = obj_attrs[data_attr] # New column name combines", "info # Store the fully qualified class name obj_attrs['__class__'] =", "``tbl`` using only `~astropy.table.Column` or `~astropy.table.MaskedColumn` objects. This function represents", "in the representation to contain the name (and possible other", "If this is a supported class then import the class", "is the first and only serialized column; in that case,", "the split columns. This function is used by astropy I/O", ".column import Column from .table import Table, QTable, has_info_class from", "the table ``meta`` dictionary to include a dict named ``__serialized_columns__``", "a column in the table. Normally contains the single key", "astropy.time import Time >>> from astropy.coordinates import SkyCoord >>> x", "class and should return the minimal table class that #", "serializing each column, keyed by column name. # Gets filled", "is not None), ('meta', lambda x: x)): col_attr = getattr(col.info,", "be serialized as separate data and mask columns. This function", "name for name in data_attrs_map.values(): del obj_attrs[name] # Get the", "# col is the first and only serialized column; in", "idx = min(out.colnames.index(name) for name in data_attrs_map) # Name is", "serialized. \"\"\" obj_attrs = col.info._represent_as_dict() ordered_keys = col.info._represent_as_dict_attrs # If", "(('unit', lambda x: x is not None and x !=", "then output as Table. # For instance ascii.read(file, format='ecsv') doesn't", "info = {} for attr, nontrivial, xform in (('unit', lambda", "if ii >= index: self.move_to_end(name) @property def colnames(self): return list(self.keys())", "as shown in the example below. The new column names", "new_cols = [] # Go through table columns and represent", "= xform(col_attr) if xform else col_attr data_attrs = [key for", "column). For serialized columns the ``mixin_cols`` dict is updated with", "# - meta: DO store info = {} for attr,", "x deg deg float64 float64 float64 float64 float64 ------- -------", "method. Prevent accidentally running # untrusted code by only importing", "required (see function docstring above) # or explicitly specified as", "name, data_attr in data_attrs_map.items(): col = out[name] obj_attrs[data_attr] = col", "where the encoded Column components (data, mask) are turned into", "can also be serialized as separate data and mask columns.", "column name in the table (e.g. \"coord.ra\") and # data_attr", "(in new_cols) + metadata (in mixin_cols). for col in tbl.itercols():", "xform(col_attr) if xform else col_attr data_attrs = [key for key", "# untrusted code by only importing known astropy classes. if", "_construct_mixin_from_columns(name, val, out) data_attrs_map[name] = name for name in data_attrs_map.values():", "import Time >>> from astropy.coordinates import SkyCoord >>> x =", "plain columns from the original table and plain columns that", "is an issue with constructing MaskedColumn, where the encoded Column", ">>> from astropy.table import Table, represent_mixins_as_columns >>> from astropy.time import", "instance a ``MaskedColumn`` may be stored directly to FITS, but", "[3, 4], unit='deg', obstime=obstime) >>> tbl = Table([sc, x], names=['sc',", "col.shape[:1]] for data_attr in data_attrs: data = obj_attrs[data_attr] # New", "with the name of the column in the table. \"\"\"", "the fully qualified class name obj_attrs['__class__'] = col.__module__ + '.'", "out_cls = QTable if has_quantities else Table return out_cls(list(out.values()), names=out.colnames,", "treat as a normal column. if not obj_attrs or col.__class__", "Subtlety here is handling mixin info attributes. The basic list", "the primary data # attribute for the column (e.g. value", "untrusted code by only importing known astropy classes. if cls_full_name", "a full Table. More pressing, there is an issue with", "of plain ``Column`` or ``MaskedColumn`` columns. This relies on the", "the object like a Table but without the actual overhead", "info: obj_attrs['__info__'] = info # Store the fully qualified class", "in exclude_classes: new_cols.append(col) return # Subtlety here is handling mixin", "# If no metadata was created then just return the", "as one or more # plain Column objects (in new_cols)", "More pressing, there is an issue with constructing MaskedColumn, where", "SerializedColumn({'name': new_name}) else: # recurse. This will define obj_attrs[new_name]. _represent_mixin_as_column(data,", "(in mixin_cols). for col in tbl.itercols(): _represent_mixin_as_column(col, col.info.name, new_cols, mixin_cols,", "self.colnames self[col.info.name] = col for ii, name in enumerate(colnames): if", "creation [DO store] # - description: DO store # -", "x)): col_attr = getattr(col.info, attr) if nontrivial(col_attr): info[attr] = col_attr", "else the original input ``tbl`` Examples -------- >>> from astropy.table", "= {} for attr, nontrivial, xform in (('unit', lambda x:", "table and plain columns that represent data from serialized columns", "x: x)): col_attr = getattr(col.info, attr) if nontrivial(col_attr): info[attr] =", ">>> tbl = Table([sc, x], names=['sc', 'x']) >>> represent_mixins_as_columns(tbl) <Table", "# output class and should return the minimal table class", "'.' + data_attr if not has_info_class(data, MixinInfo): new_cols.append(Column(data, name=new_name, **info))", "needed for fully representing the column. This includes the possibility", "this is a parent attribute # - dtype: captured in", "e.g. ``sc.ra`` for a `~astropy.coordinates.SkyCoord` column named ``sc``. In addition", "updates the table ``meta`` dictionary to include a dict named", "but without the actual overhead for a full Table. More", "original table. if not mixin_cols: return tbl meta = deepcopy(tbl.meta)", "attr in info: del info[attr] if info: obj_attrs['__info__'] = info", "out[name] info = obj_attrs.pop('__info__', {}) if len(data_attrs_map) == 1: #", "includes both plain columns from the original table and plain", "builds up a list of plain columns in the ``new_cols``", "data_attrs_map[name] = name for name in data_attrs_map.values(): del obj_attrs[name] #", "nontrivial, xform in (('unit', lambda x: x is not None", "new_cols, mixin_cols, exclude_classes=()): \"\"\"Carry out processing needed to serialize ``col``", "the example below. The new column names are formed as", "exclude_classes: new_cols.append(col) return # Subtlety here is handling mixin info", "the class and run # the _construct_from_col method. Prevent accidentally", "consisting purely of plain ``Column`` or ``MaskedColumn`` columns. This relies", "function is used by astropy I/O when writing tables to", "data_attr in data_attrs_map.items(): col = out[name] obj_attrs[data_attr] = col del", "more plain ``~astropy.table.Column`` objects and returns a new Table. A", "data # for MaskedColumn) if data_attr == col.info._represent_as_dict_primary_data: new_name =", "<Table length=2> sc.ra sc.dec sc.obstime.jd1 sc.obstime.jd2 x deg deg float64", "``serialize_context`` context variables. For instance a ``MaskedColumn`` may be stored", "by the parent for attr in col.info.attrs_from_parent: if attr in", "('format', lambda x: x is not None, None), ('description', lambda", "# Name is the column name in the table (e.g.", "captured in plain Column if relevant [DON'T store] # -", "columns from the original table and plain columns that represent", "updated with required attributes and information to subsequently reconstruct the", "columns which are instannces of any classes in the tuple", "handled directly [DON'T store] # - unit: DON'T store if", "('description', lambda x: x is not None), ('meta', lambda x:", "attribute) that is serialized as a column in the table.", "if the table does not include any mixin columns then", "the ``mixin_cols`` dict is updated with required attributes and information", "This is not desirable. \"\"\" def add_column(self, col, index=0): colnames", "# (e.g. skycoord.ra, skycoord.dec).unless it is the primary data #", "xform in (('unit', lambda x: x is not None and", "'name', 'unit', 'dtype', 'format', 'description', 'meta'. # - name: handled", "1.0 3.0 2451180.0 -0.25 100.0 2.0 4.0 2451545.0 0.0 200.0", "should return the minimal table class that # represents the", "meta = tbl.meta.copy() mixin_cols = meta.pop('__serialized_columns__') out = _TableLite(tbl.columns) for", "in tbl.itercols(): _represent_mixin_as_column(col, col.info.name, new_cols, mixin_cols, exclude_classes=exclude_classes) # If no", "a ``MaskedColumn`` may be stored directly to FITS, but can", "MixinInfo from .column import Column from .table import Table, QTable,", "('description', lambda x: x is not None, None), ('meta', lambda", "tbl : `~astropy.table.Table` or subclass Table to represent mixins as", "dictionary to include a dict named ``__serialized_columns__`` which provides additional", "'astropy.table.table.NdarrayMixin', 'astropy.table.column.MaskedColumn') class SerializedColumn(dict): \"\"\" Subclass of dict that is", "x is not None, None), ('description', lambda x: x is", "the possibility of recursive splitting, as shown in the example", "is used by astropy I/O when writing tables to ECSV,", "OrderedDict from astropy.utils.data_info import MixinInfo from .column import Column from", "columns. In earlier versions of the code *only* mixin columns", "lambda x: x is not None, None), ('meta', lambda x:", "this will just be the original column object. new_cols =", "the table. \"\"\" pass def _represent_mixin_as_column(col, name, new_cols, mixin_cols, exclude_classes=()):", "needed to construct the original mixin columns from the split", "allows manipulating the object like a Table but without the", "'format', 'description', 'meta'. # - name: handled directly [DON'T store]", "float64 float64 float64 ------- ------- -------------- -------------- ------- 1.0 3.0", "or data # for MaskedColumn) if data_attr == col.info._represent_as_dict_primary_data: new_name", "specify an # output class and should return the minimal", "value in info.items(): if attr not in obj_attrs: setattr(mixin.info, attr,", "'astropy.time.core.TimeDelta', 'astropy.units.quantity.Quantity', 'astropy.coordinates.angles.Latitude', 'astropy.coordinates.angles.Longitude', 'astropy.coordinates.angles.Angle', 'astropy.coordinates.distances.Distance', 'astropy.coordinates.earth.EarthLocation', 'astropy.coordinates.sky_coordinate.SkyCoord', 'astropy.table.table.NdarrayMixin', 'astropy.table.column.MaskedColumn')", "the single key ``name`` with the name of the column", "mixin columns from the split columns. This function is used", "deepcopy(tbl.meta) meta['__serialized_columns__'] = mixin_cols out = Table(new_cols, meta=meta, copy=False) return", "\"\"\"Represent input Table ``tbl`` using only `~astropy.table.Column` or `~astropy.table.MaskedColumn` objects.", "is a supported class then import the class and run", "may depend on the ``serialize_method`` and ``serialize_context`` context variables. For", "[] # Go through table columns and represent each column", "columns. This function builds up a list of plain columns", "for attr, nontrivial in (('unit', lambda x: x not in", "del out[name] info = obj_attrs.pop('__info__', {}) if len(data_attrs_map) == 1:", "getattr(obj_attrs[key], 'shape', ())[:1] == col.shape[:1]] for data_attr in data_attrs: data", "keyed by column name. # Gets filled in place by", "In addition to splitting columns, this function updates the table", "name=new_name, **info)) obj_attrs[data_attr] = SerializedColumn({'name': new_name}) else: # recurse. This", "if not has_info_class(data, MixinInfo): new_cols.append(Column(data, name=new_name, **info)) obj_attrs[data_attr] = SerializedColumn({'name':", "attribute # (e.g. skycoord.ra, skycoord.dec).unless it is the primary data", "for name, data_attr in data_attrs_map.items(): col = out[name] obj_attrs[data_attr] =", "if nontrivial(col_attr): info[attr] = col_attr info['name'] = new_name col =", "if info: obj_attrs['__info__'] = info # Store the fully qualified", "for ii, name in enumerate(colnames): if ii >= index: self.move_to_end(name)", "col_attr = getattr(col.info, attr) if nontrivial(col_attr): info[attr] = xform(col_attr) if", "an output table consisting purely of plain ``Column`` or ``MaskedColumn``", "no metadata was created then just return the original table.", "are turned into a MaskedColumn. When this happens in a", "representation to contain the name (and possible other info) for", "data_attr in data_attrs: data = obj_attrs[data_attr] # New column name", "data_attrs_map.values(): del obj_attrs[name] # Get the index where to add", "(e.g. ``jd1`` and ``jd2`` arrays from a ``Time`` column). For", "import import_module import re from copy import deepcopy from collections", "if data_attr == col.info._represent_as_dict_primary_data: new_name = name else: new_name =", "name in enumerate(colnames): if ii >= index: self.move_to_end(name) @property def", "for the column (e.g. value for Quantity or data #", "the object attribute name (e.g. \"ra\"). A different # example", "include any mixin columns then the original table is returned", "isinstance(val, SerializedColumn): if 'name' in val: data_attrs_map[val['name']] = name else:", "on the ``serialize_method`` and ``serialize_context`` context variables. For instance a", "this function updates the table ``meta`` dictionary to include a", "columns are immediately Masked and a warning is issued. This", "mixin columns which are instannces of any classes in the", "possible other info) for a mixin attribute (either primary data", "hence the use within this code of \"mixin\" to imply", "Minimal table-like object for _construct_mixin_from_columns. This allows manipulating the object", "in mixin_cols.items(): _construct_mixin_from_columns(new_name, obj_attrs, out) # If no quantity subclasses", "used by astropy I/O when writing tables to ECSV, FITS,", "to add new column idx = min(out.colnames.index(name) for name in", "desirable. \"\"\" def add_column(self, col, index=0): colnames = self.colnames self[col.info.name]", "store info = {} for attr, nontrivial, xform in (('unit',", "are instannces of any classes in the tuple Returns -------", "-------------- -------------- ------- 1.0 3.0 2451180.0 -0.25 100.0 2.0 4.0", "a MaskedColumn. When this happens in a real table then", "for construct {}'.format(cls_full_name)) mod_name, cls_name = re.match(r'(.+)\\.(\\w+)', cls_full_name).groups() module =" ]
[ "F = par day = 0 amountRise = U currH", "False infinity = 1 << 30 def solve(par): H, U,", "[] def parallel(self): self.getInput() p = Pool(4) millis1 = int(round(time.time()", "= 0 while True: amountRise = U * (1 -", "% (day + 1) currH -= D if currH <", "millis1)) self.makeOutput() def makeOutput(self): for test in range(self.numOfTests): self.fOut.write(\"Case #%d:", "U currH = 0 while True: amountRise = U *", "0: break self.numOfTests += 1 self.input.append((H, U, D, F)) def", "day %d' % (day + 1) currH -= D if", "self.fOut.close() if __name__ == '__main__': solver = Solver() if parallelSolve:", "class Solver: def getInput(self): self.input = [] self.numOfTests = 0", "__name__ == '__main__': solver = Solver() if parallelSolve: solver.parallel() else:", "def sequential(self): self.getInput() millis1 = int(round(time.time() * 1000)) for i", "self.fIn.readline().strip().split()) if H == 0: break self.numOfTests += 1 self.input.append((H,", "open('input.txt') self.fOut = open('output.txt', 'w') self.results = [] def parallel(self):", "+ 1) currH -= D if currH < 0: return", "- 0.01 * F * day) currH += amountRise if", "D, F = par day = 0 amountRise = U", "True: H, U, D, F = map(int, self.fIn.readline().strip().split()) if H", "1) day += 1 class Solver: def getInput(self): self.input =", "Jun 18, 2013 @author: <NAME> All rights reserved. ''' import", "(test + 1, self.results[test])) self.fIn.close() self.fOut.close() if __name__ == '__main__':", "amountRise = U * (1 - 0.01 * F *", "multiprocessing.pool import Pool parallelSolve = False infinity = 1 <<", "0: return 'failure on day %d' % (day + 1)", "U, D, F = map(int, self.fIn.readline().strip().split()) if H == 0:", "+= 1 self.input.append((H, U, D, F)) def __init__(self): self.fIn =", "= int(round(time.time() * 1000)) self.results = p.map(solve, self.input) millis2 =", "= map(int, self.fIn.readline().strip().split()) if H == 0: break self.numOfTests +=", "in milliseconds: %d \" % (millis2 - millis1)) self.makeOutput() def", "def makeOutput(self): for test in range(self.numOfTests): self.fOut.write(\"Case #%d: %s\\n\" %", "self.fOut = open('output.txt', 'w') self.results = [] def parallel(self): self.getInput()", "D, F)) def __init__(self): self.fIn = open('input.txt') self.fOut = open('output.txt',", "i in self.input: self.results.append(solve(i)) millis2 = int(round(time.time() * 1000)) print(\"Time", "if __name__ == '__main__': solver = Solver() if parallelSolve: solver.parallel()", "day = 0 amountRise = U currH = 0 while", "= open('input.txt') self.fOut = open('output.txt', 'w') self.results = [] def", "= U * (1 - 0.01 * F * day)", "- millis1)) self.makeOutput() def sequential(self): self.getInput() millis1 = int(round(time.time() *", "test in range(self.numOfTests): self.fOut.write(\"Case #%d: %s\\n\" % (test + 1,", "amountRise if currH > H: return 'success on day %d'", "amountRise = U currH = 0 while True: amountRise =", "== 0: break self.numOfTests += 1 self.input.append((H, U, D, F))", "U, D, F = par day = 0 amountRise =", "if currH < 0: return 'failure on day %d' %", "(day + 1) currH -= D if currH < 0:", "p = Pool(4) millis1 = int(round(time.time() * 1000)) self.results =", "self.input = [] self.numOfTests = 0 while True: H, U,", "self.fIn.close() self.fOut.close() if __name__ == '__main__': solver = Solver() if", "%s\\n\" % (test + 1, self.results[test])) self.fIn.close() self.fOut.close() if __name__", "self.getInput() p = Pool(4) millis1 = int(round(time.time() * 1000)) self.results", "self.input: self.results.append(solve(i)) millis2 = int(round(time.time() * 1000)) print(\"Time in milliseconds:", "in range(self.numOfTests): self.fOut.write(\"Case #%d: %s\\n\" % (test + 1, self.results[test]))", "int(round(time.time() * 1000)) for i in self.input: self.results.append(solve(i)) millis2 =", "currH = 0 while True: amountRise = U * (1", "reserved. ''' import time from multiprocessing.pool import Pool parallelSolve =", "1) currH -= D if currH < 0: return 'failure", "All rights reserved. ''' import time from multiprocessing.pool import Pool", "on day %d' % (day + 1) day += 1", "[] self.numOfTests = 0 while True: H, U, D, F", "self.numOfTests = 0 while True: H, U, D, F =", "millis2 = int(round(time.time() * 1000)) print(\"Time in milliseconds: %d \"", "millis1)) self.makeOutput() def sequential(self): self.getInput() millis1 = int(round(time.time() * 1000))", "break self.numOfTests += 1 self.input.append((H, U, D, F)) def __init__(self):", "time from multiprocessing.pool import Pool parallelSolve = False infinity =", "= par day = 0 amountRise = U currH =", "* (1 - 0.01 * F * day) currH +=", "F = map(int, self.fIn.readline().strip().split()) if H == 0: break self.numOfTests", "range(self.numOfTests): self.fOut.write(\"Case #%d: %s\\n\" % (test + 1, self.results[test])) self.fIn.close()", "30 def solve(par): H, U, D, F = par day", "1000)) self.results = p.map(solve, self.input) millis2 = int(round(time.time() * 1000))", "0.01 * F * day) currH += amountRise if currH", "%d' % (day + 1) day += 1 class Solver:", "= U currH = 0 while True: amountRise = U", "U * (1 - 0.01 * F * day) currH", "if currH > H: return 'success on day %d' %", "1 self.input.append((H, U, D, F)) def __init__(self): self.fIn = open('input.txt')", "self.input.append((H, U, D, F)) def __init__(self): self.fIn = open('input.txt') self.fOut", "+= amountRise if currH > H: return 'success on day", "print(\"Time in milliseconds: %d \" % (millis2 - millis1)) self.makeOutput()", "import Pool parallelSolve = False infinity = 1 << 30", "= Pool(4) millis1 = int(round(time.time() * 1000)) self.results = p.map(solve,", "self.makeOutput() def sequential(self): self.getInput() millis1 = int(round(time.time() * 1000)) for", "* 1000)) for i in self.input: self.results.append(solve(i)) millis2 = int(round(time.time()", "makeOutput(self): for test in range(self.numOfTests): self.fOut.write(\"Case #%d: %s\\n\" % (test", "= 0 amountRise = U currH = 0 while True:", "= int(round(time.time() * 1000)) print(\"Time in milliseconds: %d \" %", "millis1 = int(round(time.time() * 1000)) for i in self.input: self.results.append(solve(i))", "H, U, D, F = par day = 0 amountRise", "self.results = p.map(solve, self.input) millis2 = int(round(time.time() * 1000)) print(\"Time", "for i in self.input: self.results.append(solve(i)) millis2 = int(round(time.time() * 1000))", "= 1 << 30 def solve(par): H, U, D, F", "= p.map(solve, self.input) millis2 = int(round(time.time() * 1000)) print(\"Time in", "2013 @author: <NAME> All rights reserved. ''' import time from", "1 << 30 def solve(par): H, U, D, F =", "%d \" % (millis2 - millis1)) self.makeOutput() def sequential(self): self.getInput()", "self.getInput() millis1 = int(round(time.time() * 1000)) for i in self.input:", "+ 1, self.results[test])) self.fIn.close() self.fOut.close() if __name__ == '__main__': solver", "open('output.txt', 'w') self.results = [] def parallel(self): self.getInput() p =", "milliseconds: %d \" % (millis2 - millis1)) self.makeOutput() def makeOutput(self):", "return 'success on day %d' % (day + 1) currH", "F * day) currH += amountRise if currH > H:", "infinity = 1 << 30 def solve(par): H, U, D,", "import time from multiprocessing.pool import Pool parallelSolve = False infinity", "for test in range(self.numOfTests): self.fOut.write(\"Case #%d: %s\\n\" % (test +", "on day %d' % (day + 1) currH -= D", "@author: <NAME> All rights reserved. ''' import time from multiprocessing.pool", "0 while True: amountRise = U * (1 - 0.01", "= [] def parallel(self): self.getInput() p = Pool(4) millis1 =", "currH < 0: return 'failure on day %d' % (day", "solve(par): H, U, D, F = par day = 0", "* day) currH += amountRise if currH > H: return", "getInput(self): self.input = [] self.numOfTests = 0 while True: H,", "(millis2 - millis1)) self.makeOutput() def makeOutput(self): for test in range(self.numOfTests):", "'w') self.results = [] def parallel(self): self.getInput() p = Pool(4)", "1, self.results[test])) self.fIn.close() self.fOut.close() if __name__ == '__main__': solver =", "def solve(par): H, U, D, F = par day =", "while True: amountRise = U * (1 - 0.01 *", "return 'failure on day %d' % (day + 1) day", "self.fOut.write(\"Case #%d: %s\\n\" % (test + 1, self.results[test])) self.fIn.close() self.fOut.close()", "= [] self.numOfTests = 0 while True: H, U, D,", "self.input) millis2 = int(round(time.time() * 1000)) print(\"Time in milliseconds: %d", "par day = 0 amountRise = U currH = 0", "= 0 while True: H, U, D, F = map(int,", "''' import time from multiprocessing.pool import Pool parallelSolve = False", "F)) def __init__(self): self.fIn = open('input.txt') self.fOut = open('output.txt', 'w')", "p.map(solve, self.input) millis2 = int(round(time.time() * 1000)) print(\"Time in milliseconds:", "parallel(self): self.getInput() p = Pool(4) millis1 = int(round(time.time() * 1000))", "on Jun 18, 2013 @author: <NAME> All rights reserved. '''", "%d' % (day + 1) currH -= D if currH", "self.numOfTests += 1 self.input.append((H, U, D, F)) def __init__(self): self.fIn", "millis1 = int(round(time.time() * 1000)) self.results = p.map(solve, self.input) millis2", "0 amountRise = U currH = 0 while True: amountRise", "Pool parallelSolve = False infinity = 1 << 30 def", "day += 1 class Solver: def getInput(self): self.input = []", "sequential(self): self.getInput() millis1 = int(round(time.time() * 1000)) for i in", "H == 0: break self.numOfTests += 1 self.input.append((H, U, D,", "'success on day %d' % (day + 1) currH -=", "'failure on day %d' % (day + 1) day +=", "self.fIn = open('input.txt') self.fOut = open('output.txt', 'w') self.results = []", "U, D, F)) def __init__(self): self.fIn = open('input.txt') self.fOut =", "\" % (millis2 - millis1)) self.makeOutput() def sequential(self): self.getInput() millis1", "% (millis2 - millis1)) self.makeOutput() def sequential(self): self.getInput() millis1 =", "= int(round(time.time() * 1000)) for i in self.input: self.results.append(solve(i)) millis2", "% (day + 1) day += 1 class Solver: def", "<< 30 def solve(par): H, U, D, F = par", "H: return 'success on day %d' % (day + 1)", "* F * day) currH += amountRise if currH >", "> H: return 'success on day %d' % (day +", "True: amountRise = U * (1 - 0.01 * F", "if H == 0: break self.numOfTests += 1 self.input.append((H, U,", "#%d: %s\\n\" % (test + 1, self.results[test])) self.fIn.close() self.fOut.close() if", "% (millis2 - millis1)) self.makeOutput() def makeOutput(self): for test in", "''' Created on Jun 18, 2013 @author: <NAME> All rights", "1 class Solver: def getInput(self): self.input = [] self.numOfTests =", "-= D if currH < 0: return 'failure on day", "def __init__(self): self.fIn = open('input.txt') self.fOut = open('output.txt', 'w') self.results", "%d \" % (millis2 - millis1)) self.makeOutput() def makeOutput(self): for", "< 0: return 'failure on day %d' % (day +", "- millis1)) self.makeOutput() def makeOutput(self): for test in range(self.numOfTests): self.fOut.write(\"Case", "D if currH < 0: return 'failure on day %d'", "self.results = [] def parallel(self): self.getInput() p = Pool(4) millis1", "while True: H, U, D, F = map(int, self.fIn.readline().strip().split()) if", "D, F = map(int, self.fIn.readline().strip().split()) if H == 0: break", "self.results.append(solve(i)) millis2 = int(round(time.time() * 1000)) print(\"Time in milliseconds: %d", "\" % (millis2 - millis1)) self.makeOutput() def makeOutput(self): for test", "1000)) print(\"Time in milliseconds: %d \" % (millis2 - millis1))", "map(int, self.fIn.readline().strip().split()) if H == 0: break self.numOfTests += 1", "+ 1) day += 1 class Solver: def getInput(self): self.input", "def parallel(self): self.getInput() p = Pool(4) millis1 = int(round(time.time() *", "from multiprocessing.pool import Pool parallelSolve = False infinity = 1", "currH -= D if currH < 0: return 'failure on", "self.makeOutput() def makeOutput(self): for test in range(self.numOfTests): self.fOut.write(\"Case #%d: %s\\n\"", "% (test + 1, self.results[test])) self.fIn.close() self.fOut.close() if __name__ ==", "Pool(4) millis1 = int(round(time.time() * 1000)) self.results = p.map(solve, self.input)", "+= 1 class Solver: def getInput(self): self.input = [] self.numOfTests", "* 1000)) self.results = p.map(solve, self.input) millis2 = int(round(time.time() *", "= False infinity = 1 << 30 def solve(par): H,", "__init__(self): self.fIn = open('input.txt') self.fOut = open('output.txt', 'w') self.results =", "self.results[test])) self.fIn.close() self.fOut.close() if __name__ == '__main__': solver = Solver()", "H, U, D, F = map(int, self.fIn.readline().strip().split()) if H ==", "<NAME> All rights reserved. ''' import time from multiprocessing.pool import", "= open('output.txt', 'w') self.results = [] def parallel(self): self.getInput() p", "== '__main__': solver = Solver() if parallelSolve: solver.parallel() else: solver.sequential()", "18, 2013 @author: <NAME> All rights reserved. ''' import time", "(millis2 - millis1)) self.makeOutput() def sequential(self): self.getInput() millis1 = int(round(time.time()", "def getInput(self): self.input = [] self.numOfTests = 0 while True:", "1000)) for i in self.input: self.results.append(solve(i)) millis2 = int(round(time.time() *", "rights reserved. ''' import time from multiprocessing.pool import Pool parallelSolve", "Solver: def getInput(self): self.input = [] self.numOfTests = 0 while", "0 while True: H, U, D, F = map(int, self.fIn.readline().strip().split())", "(day + 1) day += 1 class Solver: def getInput(self):", "int(round(time.time() * 1000)) self.results = p.map(solve, self.input) millis2 = int(round(time.time()", "day %d' % (day + 1) day += 1 class", "in self.input: self.results.append(solve(i)) millis2 = int(round(time.time() * 1000)) print(\"Time in", "* 1000)) print(\"Time in milliseconds: %d \" % (millis2 -", "Created on Jun 18, 2013 @author: <NAME> All rights reserved.", "milliseconds: %d \" % (millis2 - millis1)) self.makeOutput() def sequential(self):", "(1 - 0.01 * F * day) currH += amountRise", "day) currH += amountRise if currH > H: return 'success", "currH += amountRise if currH > H: return 'success on", "currH > H: return 'success on day %d' % (day", "parallelSolve = False infinity = 1 << 30 def solve(par):", "int(round(time.time() * 1000)) print(\"Time in milliseconds: %d \" % (millis2" ]
[ "lambda text, mask: util.get_final_encoder_states(text, mask, bidirectional=True) initializer(self) @overrides def forward(self,", "(default = None) Metadata containing the original tokenization of the", "metadata : ``List[Dict[str, Any]]``, optional, (default = None) Metadata containing", "float]: metric_dict = {} sum_f1 = 0.0 for name, metric", "self.loss(logits, label) output_dict[\"loss\"] = loss # compute F1 per label", "``TextField`` label : torch.IntTensor, optional (default = None) From a", "text : Dict[str, torch.LongTensor] From a ``TextField`` label : torch.IntTensor,", "def __init__(self, vocab: Vocabulary, text_field_embedder: TextFieldEmbedder, text_encoder: Seq2SeqEncoder, classifier_feedforward: FeedForward,", "num_labels)`` representing unnormalised log probabilities of the label. label_probs :", "metric_val[0] metric_dict[name + '_R'] = metric_val[1] metric_dict[name + '_F1'] =", "label for i in range(self.num_classes): metric = self.label_f1_metrics[self.vocab.get_token_from_index(index=i, namespace=\"labels\")] metric(class_probs,", "metric = self.label_f1_metrics[self.vocab.get_token_from_index(index=i, namespace=\"labels\")] metric(class_probs, label) self.label_accuracy(logits, label) return output_dict", "label) output_dict[\"loss\"] = loss # compute F1 per label for", "mask: util.get_final_encoder_states(text, mask, bidirectional=True) initializer(self) @overrides def forward(self, text: Dict[str,", "not None: loss = self.loss(logits, label) output_dict[\"loss\"] = loss #", "get_metrics(self, reset: bool = False) -> Dict[str, float]: metric_dict =", "Any]] = None) -> Dict[str, torch.Tensor]: \"\"\" Parameters ---------- text", "None: loss = self.loss(logits, label) output_dict[\"loss\"] = loss # compute", "vocab: Vocabulary, text_field_embedder: TextFieldEmbedder, text_encoder: Seq2SeqEncoder, classifier_feedforward: FeedForward, verbose_metrics: False,", "states 4) Final feedforward layer Optimized with CrossEntropyLoss. Evaluated with", "metric_val = metric.get_metric(reset) if self.verbose_metrics: metric_dict[name + '_P'] = metric_val[0]", "from allennlp.training.metrics import CategoricalAccuracy, F1Measure from overrides import overrides @Model.register(\"text_classifier\")", "if label is not None: loss = self.loss(logits, label) output_dict[\"loss\"]", "= self.loss(logits, label) output_dict[\"loss\"] = loss # compute F1 per", "shape ``(batch_size, num_labels)`` representing probabilities of the label. loss :", "None: super(TextClassifier, self).__init__(vocab, regularizer) self.text_field_embedder = text_field_embedder self.num_classes = self.vocab.get_vocab_size(\"labels\")", "-> Dict[str, torch.Tensor]: \"\"\" Parameters ---------- text : Dict[str, torch.LongTensor]", "basic text classifier: 1) Embed tokens using `text_field_embedder` 2) Seq2SeqEncoder,", "mask, bidirectional=True) initializer(self) @overrides def forward(self, text: Dict[str, torch.LongTensor], label:", "class_probs = F.softmax(logits, dim=1) output_dict = {\"logits\": logits} if label", "self.text_field_embedder(text) mask = util.get_text_field_mask(text) encoded_text = self.text_encoder(embedded_text, mask) pooled =", "sum_f1 += metric_val[2] names = list(self.label_f1_metrics.keys()) total_len = len(names) average_f1", "Optional, List, Any import torch import torch.nn.functional as F from", "label) return output_dict @overrides def decode(self, output_dict: Dict[str, torch.Tensor]) ->", "from allennlp.nn import InitializerApplicator, RegularizerApplicator from allennlp.nn import util from", "F1Measure from overrides import overrides @Model.register(\"text_classifier\") class TextClassifier(Model): \"\"\" Implements", "the first and last encoder states 4) Final feedforward layer", "self.pool(encoded_text, mask) ff_hidden = self.classifier_feedforward(pooled) logits = self.prediction_layer(ff_hidden) class_probs =", "Evaluated with CategoricalAccuracy & F1. \"\"\" def __init__(self, vocab: Vocabulary,", "import FeedForward, TextFieldEmbedder, Seq2SeqEncoder from allennlp.nn import InitializerApplicator, RegularizerApplicator from", "for i in range(self.num_classes): metric = self.label_f1_metrics[self.vocab.get_token_from_index(index=i, namespace=\"labels\")] metric(class_probs, label)", "overrides @Model.register(\"text_classifier\") class TextClassifier(Model): \"\"\" Implements a basic text classifier:", "\"\"\" Parameters ---------- text : Dict[str, torch.LongTensor] From a ``TextField``", "mask) pooled = self.pool(encoded_text, mask) ff_hidden = self.classifier_feedforward(pooled) logits =", "of the label. loss : torch.FloatTensor, optional A scalar loss", "regularizer) self.text_field_embedder = text_field_embedder self.num_classes = self.vocab.get_vocab_size(\"labels\") self.text_encoder = text_encoder", "InitializerApplicator = InitializerApplicator(), regularizer: Optional[RegularizerApplicator] = None, ) -> None:", "allennlp.modules import FeedForward, TextFieldEmbedder, Seq2SeqEncoder from allennlp.nn import InitializerApplicator, RegularizerApplicator", "from allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.modules", ", self.num_classes) self.label_accuracy = CategoricalAccuracy() self.label_f1_metrics = {} self.verbose_metrics =", "label : torch.IntTensor, optional (default = None) From a ``LabelField``", "range(self.num_classes): metric = self.label_f1_metrics[self.vocab.get_token_from_index(index=i, namespace=\"labels\")] metric(class_probs, label) self.label_accuracy(logits, label) return", "Dict[str, torch.LongTensor], label: torch.IntTensor = None, metadata: List[Dict[str, Any]] =", "containing the original tokenization of the premise and hypothesis with", "# compute F1 per label for i in range(self.num_classes): metric", "self.vocab.get_vocab_size(\"labels\") self.text_encoder = text_encoder self.classifier_feedforward = classifier_feedforward self.prediction_layer = torch.nn.Linear(self.classifier_feedforward.get_output_dim()", "class TextClassifier(Model): \"\"\" Implements a basic text classifier: 1) Embed", "namespace=\"labels\")] = F1Measure(positive_label=i) self.loss = torch.nn.CrossEntropyLoss() self.pool = lambda text,", "dim=1) output_dict = {\"logits\": logits} if label is not None:", ": torch.FloatTensor A tensor of shape ``(batch_size, num_labels)`` representing unnormalised", "label) self.label_accuracy(logits, label) return output_dict @overrides def decode(self, output_dict: Dict[str,", "output_dict = {\"logits\": logits} if label is not None: loss", "+ '_P'] = metric_val[0] metric_dict[name + '_R'] = metric_val[1] metric_dict[name", "= metric_val[0] metric_dict[name + '_R'] = metric_val[1] metric_dict[name + '_F1']", "names = list(self.label_f1_metrics.keys()) total_len = len(names) average_f1 = sum_f1 /", "Dict[str, torch.Tensor]: \"\"\" Parameters ---------- text : Dict[str, torch.LongTensor] From", "label. label_probs : torch.FloatTensor A tensor of shape ``(batch_size, num_labels)``", "= torch.nn.Linear(self.classifier_feedforward.get_output_dim() , self.num_classes) self.label_accuracy = CategoricalAccuracy() self.label_f1_metrics = {}", "metric.get_metric(reset) if self.verbose_metrics: metric_dict[name + '_P'] = metric_val[0] metric_dict[name +", "label. loss : torch.FloatTensor, optional A scalar loss to be", "metric_val[2] sum_f1 += metric_val[2] names = list(self.label_f1_metrics.keys()) total_len = len(names)", "torch.Tensor]: \"\"\" Parameters ---------- text : Dict[str, torch.LongTensor] From a", "logits} if label is not None: loss = self.loss(logits, label)", "self.prediction_layer(ff_hidden) class_probs = F.softmax(logits, dim=1) output_dict = {\"logits\": logits} if", "'_P'] = metric_val[0] metric_dict[name + '_R'] = metric_val[1] metric_dict[name +", "Implements a basic text classifier: 1) Embed tokens using `text_field_embedder`", "False, initializer: InitializerApplicator = InitializerApplicator(), regularizer: Optional[RegularizerApplicator] = None, )", "= {\"logits\": logits} if label is not None: loss =", "'_F1'] = metric_val[2] sum_f1 += metric_val[2] names = list(self.label_f1_metrics.keys()) total_len", "metric_val[2] names = list(self.label_f1_metrics.keys()) total_len = len(names) average_f1 = sum_f1", "CategoricalAccuracy() self.label_f1_metrics = {} self.verbose_metrics = verbose_metrics for i in", "= F.softmax(logits, dim=1) output_dict = {\"logits\": logits} if label is", "respectively. Returns ------- An output dictionary consisting of: label_logits :", "return output_dict def get_metrics(self, reset: bool = False) -> Dict[str,", "= metric_val[1] metric_dict[name + '_F1'] = metric_val[2] sum_f1 += metric_val[2]", "import Vocabulary from allennlp.models.model import Model from allennlp.modules import FeedForward,", "Optimized with CrossEntropyLoss. Evaluated with CategoricalAccuracy & F1. \"\"\" def", "= metric.get_metric(reset) if self.verbose_metrics: metric_dict[name + '_P'] = metric_val[0] metric_dict[name", "= loss # compute F1 per label for i in", "class_probabilities return output_dict def get_metrics(self, reset: bool = False) ->", "{\"logits\": logits} if label is not None: loss = self.loss(logits,", "Returns ------- An output dictionary consisting of: label_logits : torch.FloatTensor", "representing probabilities of the label. loss : torch.FloatTensor, optional A", "label_logits : torch.FloatTensor A tensor of shape ``(batch_size, num_labels)`` representing", "output_dict @overrides def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:", "None) From a ``LabelField`` metadata : ``List[Dict[str, Any]]``, optional, (default", "in self.label_f1_metrics.items(): metric_val = metric.get_metric(reset) if self.verbose_metrics: metric_dict[name + '_P']", "dim=-1) output_dict['class_probs'] = class_probabilities return output_dict def get_metrics(self, reset: bool", "label_probs : torch.FloatTensor A tensor of shape ``(batch_size, num_labels)`` representing", "mask = util.get_text_field_mask(text) encoded_text = self.text_encoder(embedded_text, mask) pooled = self.pool(encoded_text,", ": torch.FloatTensor, optional A scalar loss to be optimised. \"\"\"", "torch.nn.functional as F from allennlp.data import Vocabulary from allennlp.models.model import", "= text_field_embedder self.num_classes = self.vocab.get_vocab_size(\"labels\") self.text_encoder = text_encoder self.classifier_feedforward =", "= None) Metadata containing the original tokenization of the premise", "self.text_field_embedder = text_field_embedder self.num_classes = self.vocab.get_vocab_size(\"labels\") self.text_encoder = text_encoder self.classifier_feedforward", "Dict[str, float]: metric_dict = {} sum_f1 = 0.0 for name,", "\"\"\" def __init__(self, vocab: Vocabulary, text_field_embedder: TextFieldEmbedder, text_encoder: Seq2SeqEncoder, classifier_feedforward:", "in range(self.num_classes): metric = self.label_f1_metrics[self.vocab.get_token_from_index(index=i, namespace=\"labels\")] metric(class_probs, label) self.label_accuracy(logits, label)", "metadata: List[Dict[str, Any]] = None) -> Dict[str, torch.Tensor]: \"\"\" Parameters", "bidirectional=True) initializer(self) @overrides def forward(self, text: Dict[str, torch.LongTensor], label: torch.IntTensor", "self.verbose_metrics = verbose_metrics for i in range(self.num_classes): self.label_f1_metrics[vocab.get_token_from_index(index=i, namespace=\"labels\")] =", "torch.FloatTensor A tensor of shape ``(batch_size, num_labels)`` representing probabilities of", "len(names) average_f1 = sum_f1 / total_len metric_dict['average_F1'] = average_f1 metric_dict['accuracy']", "__init__(self, vocab: Vocabulary, text_field_embedder: TextFieldEmbedder, text_encoder: Seq2SeqEncoder, classifier_feedforward: FeedForward, verbose_metrics:", "encoder states 4) Final feedforward layer Optimized with CrossEntropyLoss. Evaluated", "optional, (default = None) Metadata containing the original tokenization of", "pooled = self.pool(encoded_text, mask) ff_hidden = self.classifier_feedforward(pooled) logits = self.prediction_layer(ff_hidden)", "from allennlp.models.model import Model from allennlp.modules import FeedForward, TextFieldEmbedder, Seq2SeqEncoder", "InitializerApplicator(), regularizer: Optional[RegularizerApplicator] = None, ) -> None: super(TextClassifier, self).__init__(vocab,", "import Dict, Optional, List, Any import torch import torch.nn.functional as", "{} self.verbose_metrics = verbose_metrics for i in range(self.num_classes): self.label_f1_metrics[vocab.get_token_from_index(index=i, namespace=\"labels\")]", "None) -> Dict[str, torch.Tensor]: \"\"\" Parameters ---------- text : Dict[str,", "``(batch_size, num_labels)`` representing probabilities of the label. loss : torch.FloatTensor,", "Optional[RegularizerApplicator] = None, ) -> None: super(TextClassifier, self).__init__(vocab, regularizer) self.text_field_embedder", "{} sum_f1 = 0.0 for name, metric in self.label_f1_metrics.items(): metric_val", "torch.IntTensor, optional (default = None) From a ``LabelField`` metadata :", "None, metadata: List[Dict[str, Any]] = None) -> Dict[str, torch.Tensor]: \"\"\"", "self.verbose_metrics: metric_dict[name + '_P'] = metric_val[0] metric_dict[name + '_R'] =", "TextFieldEmbedder, text_encoder: Seq2SeqEncoder, classifier_feedforward: FeedForward, verbose_metrics: False, initializer: InitializerApplicator =", "last encoder states 4) Final feedforward layer Optimized with CrossEntropyLoss.", "ff_hidden = self.classifier_feedforward(pooled) logits = self.prediction_layer(ff_hidden) class_probs = F.softmax(logits, dim=1)", "= self.text_field_embedder(text) mask = util.get_text_field_mask(text) encoded_text = self.text_encoder(embedded_text, mask) pooled", "self.label_accuracy(logits, label) return output_dict @overrides def decode(self, output_dict: Dict[str, torch.Tensor])", "logits = self.prediction_layer(ff_hidden) class_probs = F.softmax(logits, dim=1) output_dict = {\"logits\":", "is not None: loss = self.loss(logits, label) output_dict[\"loss\"] = loss", "self.loss = torch.nn.CrossEntropyLoss() self.pool = lambda text, mask: util.get_final_encoder_states(text, mask,", "optional (default = None) From a ``LabelField`` metadata : ``List[Dict[str,", "Seq2SeqEncoder, e.g. BiLSTM 3) Append the first and last encoder", "InitializerApplicator, RegularizerApplicator from allennlp.nn import util from allennlp.training.metrics import CategoricalAccuracy,", "FeedForward, verbose_metrics: False, initializer: InitializerApplicator = InitializerApplicator(), regularizer: Optional[RegularizerApplicator] =", "torch.FloatTensor A tensor of shape ``(batch_size, num_labels)`` representing unnormalised log", "torch.LongTensor] From a ``TextField`` label : torch.IntTensor, optional (default =", "encoded_text = self.text_encoder(embedded_text, mask) pooled = self.pool(encoded_text, mask) ff_hidden =", "embedded_text = self.text_field_embedder(text) mask = util.get_text_field_mask(text) encoded_text = self.text_encoder(embedded_text, mask)", "output_dict def get_metrics(self, reset: bool = False) -> Dict[str, float]:", "From a ``TextField`` label : torch.IntTensor, optional (default = None)", "Vocabulary, text_field_embedder: TextFieldEmbedder, text_encoder: Seq2SeqEncoder, classifier_feedforward: FeedForward, verbose_metrics: False, initializer:", "0.0 for name, metric in self.label_f1_metrics.items(): metric_val = metric.get_metric(reset) if", "Dict[str, torch.Tensor]: class_probabilities = F.softmax(output_dict['logits'], dim=-1) output_dict['class_probs'] = class_probabilities return", "= {} sum_f1 = 0.0 for name, metric in self.label_f1_metrics.items():", "= classifier_feedforward self.prediction_layer = torch.nn.Linear(self.classifier_feedforward.get_output_dim() , self.num_classes) self.label_accuracy = CategoricalAccuracy()", "3) Append the first and last encoder states 4) Final", "original tokenization of the premise and hypothesis with 'premise_tokens' and", "with 'premise_tokens' and 'hypothesis_tokens' keys respectively. Returns ------- An output", "self.label_accuracy = CategoricalAccuracy() self.label_f1_metrics = {} self.verbose_metrics = verbose_metrics for", "optional A scalar loss to be optimised. \"\"\" embedded_text =", "= self.prediction_layer(ff_hidden) class_probs = F.softmax(logits, dim=1) output_dict = {\"logits\": logits}", "probabilities of the label. label_probs : torch.FloatTensor A tensor of", "decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: class_probabilities = F.softmax(output_dict['logits'],", "typing import Dict, Optional, List, Any import torch import torch.nn.functional", "to be optimised. \"\"\" embedded_text = self.text_field_embedder(text) mask = util.get_text_field_mask(text)", "= self.classifier_feedforward(pooled) logits = self.prediction_layer(ff_hidden) class_probs = F.softmax(logits, dim=1) output_dict", "if self.verbose_metrics: metric_dict[name + '_P'] = metric_val[0] metric_dict[name + '_R']", "``LabelField`` metadata : ``List[Dict[str, Any]]``, optional, (default = None) Metadata", "allennlp.nn import util from allennlp.training.metrics import CategoricalAccuracy, F1Measure from overrides", "2) Seq2SeqEncoder, e.g. BiLSTM 3) Append the first and last", "output_dict['class_probs'] = class_probabilities return output_dict def get_metrics(self, reset: bool =", "= metric_val[2] sum_f1 += metric_val[2] names = list(self.label_f1_metrics.keys()) total_len =", "from typing import Dict, Optional, List, Any import torch import", "and last encoder states 4) Final feedforward layer Optimized with", "mask) ff_hidden = self.classifier_feedforward(pooled) logits = self.prediction_layer(ff_hidden) class_probs = F.softmax(logits,", "= 0.0 for name, metric in self.label_f1_metrics.items(): metric_val = metric.get_metric(reset)", "self.label_f1_metrics[self.vocab.get_token_from_index(index=i, namespace=\"labels\")] metric(class_probs, label) self.label_accuracy(logits, label) return output_dict @overrides def", "a ``LabelField`` metadata : ``List[Dict[str, Any]]``, optional, (default = None)", "allennlp.training.metrics import CategoricalAccuracy, F1Measure from overrides import overrides @Model.register(\"text_classifier\") class", "self.prediction_layer = torch.nn.Linear(self.classifier_feedforward.get_output_dim() , self.num_classes) self.label_accuracy = CategoricalAccuracy() self.label_f1_metrics =", "import overrides @Model.register(\"text_classifier\") class TextClassifier(Model): \"\"\" Implements a basic text", "forward(self, text: Dict[str, torch.LongTensor], label: torch.IntTensor = None, metadata: List[Dict[str,", "= verbose_metrics for i in range(self.num_classes): self.label_f1_metrics[vocab.get_token_from_index(index=i, namespace=\"labels\")] = F1Measure(positive_label=i)", "return output_dict @overrides def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str,", "= self.text_encoder(embedded_text, mask) pooled = self.pool(encoded_text, mask) ff_hidden = self.classifier_feedforward(pooled)", "torch import torch.nn.functional as F from allennlp.data import Vocabulary from", "= lambda text, mask: util.get_final_encoder_states(text, mask, bidirectional=True) initializer(self) @overrides def", "allennlp.models.model import Model from allennlp.modules import FeedForward, TextFieldEmbedder, Seq2SeqEncoder from", "tokenization of the premise and hypothesis with 'premise_tokens' and 'hypothesis_tokens'", "\"\"\" Implements a basic text classifier: 1) Embed tokens using", "= list(self.label_f1_metrics.keys()) total_len = len(names) average_f1 = sum_f1 / total_len", "text_field_embedder self.num_classes = self.vocab.get_vocab_size(\"labels\") self.text_encoder = text_encoder self.classifier_feedforward = classifier_feedforward", "4) Final feedforward layer Optimized with CrossEntropyLoss. Evaluated with CategoricalAccuracy", "import torch.nn.functional as F from allennlp.data import Vocabulary from allennlp.models.model", "a ``TextField`` label : torch.IntTensor, optional (default = None) From", "@overrides def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: class_probabilities", "1) Embed tokens using `text_field_embedder` 2) Seq2SeqEncoder, e.g. BiLSTM 3)", "text_encoder: Seq2SeqEncoder, classifier_feedforward: FeedForward, verbose_metrics: False, initializer: InitializerApplicator = InitializerApplicator(),", "classifier: 1) Embed tokens using `text_field_embedder` 2) Seq2SeqEncoder, e.g. BiLSTM", "tensor of shape ``(batch_size, num_labels)`` representing unnormalised log probabilities of", "from allennlp.modules import FeedForward, TextFieldEmbedder, Seq2SeqEncoder from allennlp.nn import InitializerApplicator,", "+ '_R'] = metric_val[1] metric_dict[name + '_F1'] = metric_val[2] sum_f1", "of: label_logits : torch.FloatTensor A tensor of shape ``(batch_size, num_labels)``", "A tensor of shape ``(batch_size, num_labels)`` representing probabilities of the", "'premise_tokens' and 'hypothesis_tokens' keys respectively. Returns ------- An output dictionary", "Any]]``, optional, (default = None) Metadata containing the original tokenization", "self.num_classes = self.vocab.get_vocab_size(\"labels\") self.text_encoder = text_encoder self.classifier_feedforward = classifier_feedforward self.prediction_layer", "Model from allennlp.modules import FeedForward, TextFieldEmbedder, Seq2SeqEncoder from allennlp.nn import", ": ``List[Dict[str, Any]]``, optional, (default = None) Metadata containing the", "self.label_f1_metrics.items(): metric_val = metric.get_metric(reset) if self.verbose_metrics: metric_dict[name + '_P'] =", "bool = False) -> Dict[str, float]: metric_dict = {} sum_f1", "sum_f1 = 0.0 for name, metric in self.label_f1_metrics.items(): metric_val =", "TextFieldEmbedder, Seq2SeqEncoder from allennlp.nn import InitializerApplicator, RegularizerApplicator from allennlp.nn import", "of the premise and hypothesis with 'premise_tokens' and 'hypothesis_tokens' keys", "list(self.label_f1_metrics.keys()) total_len = len(names) average_f1 = sum_f1 / total_len metric_dict['average_F1']", "TextClassifier(Model): \"\"\" Implements a basic text classifier: 1) Embed tokens", "metric_val[1] metric_dict[name + '_F1'] = metric_val[2] sum_f1 += metric_val[2] names", "e.g. BiLSTM 3) Append the first and last encoder states", "= len(names) average_f1 = sum_f1 / total_len metric_dict['average_F1'] = average_f1", "False) -> Dict[str, float]: metric_dict = {} sum_f1 = 0.0", "initializer: InitializerApplicator = InitializerApplicator(), regularizer: Optional[RegularizerApplicator] = None, ) ->", "Any import torch import torch.nn.functional as F from allennlp.data import", "Parameters ---------- text : Dict[str, torch.LongTensor] From a ``TextField`` label", "`text_field_embedder` 2) Seq2SeqEncoder, e.g. BiLSTM 3) Append the first and", "import InitializerApplicator, RegularizerApplicator from allennlp.nn import util from allennlp.training.metrics import", "class_probabilities = F.softmax(output_dict['logits'], dim=-1) output_dict['class_probs'] = class_probabilities return output_dict def", "scalar loss to be optimised. \"\"\" embedded_text = self.text_field_embedder(text) mask", "= False) -> Dict[str, float]: metric_dict = {} sum_f1 =", "output_dict[\"loss\"] = loss # compute F1 per label for i", "tensor of shape ``(batch_size, num_labels)`` representing probabilities of the label.", "first and last encoder states 4) Final feedforward layer Optimized", "self.pool = lambda text, mask: util.get_final_encoder_states(text, mask, bidirectional=True) initializer(self) @overrides", "loss # compute F1 per label for i in range(self.num_classes):", "initializer(self) @overrides def forward(self, text: Dict[str, torch.LongTensor], label: torch.IntTensor =", "keys respectively. Returns ------- An output dictionary consisting of: label_logits", "namespace=\"labels\")] metric(class_probs, label) self.label_accuracy(logits, label) return output_dict @overrides def decode(self,", "optimised. \"\"\" embedded_text = self.text_field_embedder(text) mask = util.get_text_field_mask(text) encoded_text =", "a basic text classifier: 1) Embed tokens using `text_field_embedder` 2)", "-> Dict[str, torch.Tensor]: class_probabilities = F.softmax(output_dict['logits'], dim=-1) output_dict['class_probs'] = class_probabilities", "torch.nn.Linear(self.classifier_feedforward.get_output_dim() , self.num_classes) self.label_accuracy = CategoricalAccuracy() self.label_f1_metrics = {} self.verbose_metrics", "+ '_F1'] = metric_val[2] sum_f1 += metric_val[2] names = list(self.label_f1_metrics.keys())", "Embed tokens using `text_field_embedder` 2) Seq2SeqEncoder, e.g. BiLSTM 3) Append", "= None, ) -> None: super(TextClassifier, self).__init__(vocab, regularizer) self.text_field_embedder =", "reset: bool = False) -> Dict[str, float]: metric_dict = {}", "self.label_f1_metrics[vocab.get_token_from_index(index=i, namespace=\"labels\")] = F1Measure(positive_label=i) self.loss = torch.nn.CrossEntropyLoss() self.pool = lambda", "torch.Tensor]) -> Dict[str, torch.Tensor]: class_probabilities = F.softmax(output_dict['logits'], dim=-1) output_dict['class_probs'] =", "of shape ``(batch_size, num_labels)`` representing unnormalised log probabilities of the", "= self.pool(encoded_text, mask) ff_hidden = self.classifier_feedforward(pooled) logits = self.prediction_layer(ff_hidden) class_probs", "Dict, Optional, List, Any import torch import torch.nn.functional as F", "Seq2SeqEncoder, classifier_feedforward: FeedForward, verbose_metrics: False, initializer: InitializerApplicator = InitializerApplicator(), regularizer:", "def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: class_probabilities =", "def get_metrics(self, reset: bool = False) -> Dict[str, float]: metric_dict", "with CrossEntropyLoss. Evaluated with CategoricalAccuracy & F1. \"\"\" def __init__(self,", "text_encoder self.classifier_feedforward = classifier_feedforward self.prediction_layer = torch.nn.Linear(self.classifier_feedforward.get_output_dim() , self.num_classes) self.label_accuracy", "metric_dict[name + '_R'] = metric_val[1] metric_dict[name + '_F1'] = metric_val[2]", "F from allennlp.data import Vocabulary from allennlp.models.model import Model from", "text classifier: 1) Embed tokens using `text_field_embedder` 2) Seq2SeqEncoder, e.g.", "for name, metric in self.label_f1_metrics.items(): metric_val = metric.get_metric(reset) if self.verbose_metrics:", "text_field_embedder: TextFieldEmbedder, text_encoder: Seq2SeqEncoder, classifier_feedforward: FeedForward, verbose_metrics: False, initializer: InitializerApplicator", "loss to be optimised. \"\"\" embedded_text = self.text_field_embedder(text) mask =", "range(self.num_classes): self.label_f1_metrics[vocab.get_token_from_index(index=i, namespace=\"labels\")] = F1Measure(positive_label=i) self.loss = torch.nn.CrossEntropyLoss() self.pool =", "import util from allennlp.training.metrics import CategoricalAccuracy, F1Measure from overrides import", "label is not None: loss = self.loss(logits, label) output_dict[\"loss\"] =", "self.classifier_feedforward = classifier_feedforward self.prediction_layer = torch.nn.Linear(self.classifier_feedforward.get_output_dim() , self.num_classes) self.label_accuracy =", "loss = self.loss(logits, label) output_dict[\"loss\"] = loss # compute F1", "@overrides def forward(self, text: Dict[str, torch.LongTensor], label: torch.IntTensor = None,", "= F1Measure(positive_label=i) self.loss = torch.nn.CrossEntropyLoss() self.pool = lambda text, mask:", "self).__init__(vocab, regularizer) self.text_field_embedder = text_field_embedder self.num_classes = self.vocab.get_vocab_size(\"labels\") self.text_encoder =", "Dict[str, torch.LongTensor] From a ``TextField`` label : torch.IntTensor, optional (default", "self.classifier_feedforward(pooled) logits = self.prediction_layer(ff_hidden) class_probs = F.softmax(logits, dim=1) output_dict =", "---------- text : Dict[str, torch.LongTensor] From a ``TextField`` label :", "premise and hypothesis with 'premise_tokens' and 'hypothesis_tokens' keys respectively. Returns", "Metadata containing the original tokenization of the premise and hypothesis", "representing unnormalised log probabilities of the label. label_probs : torch.FloatTensor", "classifier_feedforward self.prediction_layer = torch.nn.Linear(self.classifier_feedforward.get_output_dim() , self.num_classes) self.label_accuracy = CategoricalAccuracy() self.label_f1_metrics", "F1 per label for i in range(self.num_classes): metric = self.label_f1_metrics[self.vocab.get_token_from_index(index=i,", "hypothesis with 'premise_tokens' and 'hypothesis_tokens' keys respectively. Returns ------- An", "the original tokenization of the premise and hypothesis with 'premise_tokens'", "= None) From a ``LabelField`` metadata : ``List[Dict[str, Any]]``, optional,", "and 'hypothesis_tokens' keys respectively. Returns ------- An output dictionary consisting", "torch.IntTensor = None, metadata: List[Dict[str, Any]] = None) -> Dict[str,", "output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: class_probabilities = F.softmax(output_dict['logits'], dim=-1)", "List[Dict[str, Any]] = None) -> Dict[str, torch.Tensor]: \"\"\" Parameters ----------", "in range(self.num_classes): self.label_f1_metrics[vocab.get_token_from_index(index=i, namespace=\"labels\")] = F1Measure(positive_label=i) self.loss = torch.nn.CrossEntropyLoss() self.pool", "probabilities of the label. loss : torch.FloatTensor, optional A scalar", "= {} self.verbose_metrics = verbose_metrics for i in range(self.num_classes): self.label_f1_metrics[vocab.get_token_from_index(index=i,", ") -> None: super(TextClassifier, self).__init__(vocab, regularizer) self.text_field_embedder = text_field_embedder self.num_classes", "util.get_text_field_mask(text) encoded_text = self.text_encoder(embedded_text, mask) pooled = self.pool(encoded_text, mask) ff_hidden", "i in range(self.num_classes): metric = self.label_f1_metrics[self.vocab.get_token_from_index(index=i, namespace=\"labels\")] metric(class_probs, label) self.label_accuracy(logits,", "and hypothesis with 'premise_tokens' and 'hypothesis_tokens' keys respectively. Returns -------", "= torch.nn.CrossEntropyLoss() self.pool = lambda text, mask: util.get_final_encoder_states(text, mask, bidirectional=True)", "'_R'] = metric_val[1] metric_dict[name + '_F1'] = metric_val[2] sum_f1 +=", "metric in self.label_f1_metrics.items(): metric_val = metric.get_metric(reset) if self.verbose_metrics: metric_dict[name +", "import torch import torch.nn.functional as F from allennlp.data import Vocabulary", "An output dictionary consisting of: label_logits : torch.FloatTensor A tensor", "of shape ``(batch_size, num_labels)`` representing probabilities of the label. loss", "F1Measure(positive_label=i) self.loss = torch.nn.CrossEntropyLoss() self.pool = lambda text, mask: util.get_final_encoder_states(text,", "Append the first and last encoder states 4) Final feedforward", "total_len = len(names) average_f1 = sum_f1 / total_len metric_dict['average_F1'] =", "= InitializerApplicator(), regularizer: Optional[RegularizerApplicator] = None, ) -> None: super(TextClassifier,", "= self.label_f1_metrics[self.vocab.get_token_from_index(index=i, namespace=\"labels\")] metric(class_probs, label) self.label_accuracy(logits, label) return output_dict @overrides", "label: torch.IntTensor = None, metadata: List[Dict[str, Any]] = None) ->", "import Model from allennlp.modules import FeedForward, TextFieldEmbedder, Seq2SeqEncoder from allennlp.nn", "None, ) -> None: super(TextClassifier, self).__init__(vocab, regularizer) self.text_field_embedder = text_field_embedder", "num_labels)`` representing probabilities of the label. loss : torch.FloatTensor, optional", "util from allennlp.training.metrics import CategoricalAccuracy, F1Measure from overrides import overrides", "= text_encoder self.classifier_feedforward = classifier_feedforward self.prediction_layer = torch.nn.Linear(self.classifier_feedforward.get_output_dim() , self.num_classes)", "layer Optimized with CrossEntropyLoss. Evaluated with CategoricalAccuracy & F1. \"\"\"", "= self.vocab.get_vocab_size(\"labels\") self.text_encoder = text_encoder self.classifier_feedforward = classifier_feedforward self.prediction_layer =", "self.label_f1_metrics = {} self.verbose_metrics = verbose_metrics for i in range(self.num_classes):", "text: Dict[str, torch.LongTensor], label: torch.IntTensor = None, metadata: List[Dict[str, Any]]", "(default = None) From a ``LabelField`` metadata : ``List[Dict[str, Any]]``,", "metric_dict[name + '_P'] = metric_val[0] metric_dict[name + '_R'] = metric_val[1]", "& F1. \"\"\" def __init__(self, vocab: Vocabulary, text_field_embedder: TextFieldEmbedder, text_encoder:", "@Model.register(\"text_classifier\") class TextClassifier(Model): \"\"\" Implements a basic text classifier: 1)", "= CategoricalAccuracy() self.label_f1_metrics = {} self.verbose_metrics = verbose_metrics for i", "import CategoricalAccuracy, F1Measure from overrides import overrides @Model.register(\"text_classifier\") class TextClassifier(Model):", "output dictionary consisting of: label_logits : torch.FloatTensor A tensor of", "FeedForward, TextFieldEmbedder, Seq2SeqEncoder from allennlp.nn import InitializerApplicator, RegularizerApplicator from allennlp.nn", "\"\"\" embedded_text = self.text_field_embedder(text) mask = util.get_text_field_mask(text) encoded_text = self.text_encoder(embedded_text,", "torch.FloatTensor, optional A scalar loss to be optimised. \"\"\" embedded_text", "= F.softmax(output_dict['logits'], dim=-1) output_dict['class_probs'] = class_probabilities return output_dict def get_metrics(self,", "= sum_f1 / total_len metric_dict['average_F1'] = average_f1 metric_dict['accuracy'] = self.label_accuracy.get_metric(reset)", "CategoricalAccuracy, F1Measure from overrides import overrides @Model.register(\"text_classifier\") class TextClassifier(Model): \"\"\"", "= util.get_text_field_mask(text) encoded_text = self.text_encoder(embedded_text, mask) pooled = self.pool(encoded_text, mask)", "A tensor of shape ``(batch_size, num_labels)`` representing unnormalised log probabilities", "RegularizerApplicator from allennlp.nn import util from allennlp.training.metrics import CategoricalAccuracy, F1Measure", "overrides import overrides @Model.register(\"text_classifier\") class TextClassifier(Model): \"\"\" Implements a basic", "Final feedforward layer Optimized with CrossEntropyLoss. Evaluated with CategoricalAccuracy &", "``(batch_size, num_labels)`` representing unnormalised log probabilities of the label. label_probs", "loss : torch.FloatTensor, optional A scalar loss to be optimised.", "regularizer: Optional[RegularizerApplicator] = None, ) -> None: super(TextClassifier, self).__init__(vocab, regularizer)", "F.softmax(output_dict['logits'], dim=-1) output_dict['class_probs'] = class_probabilities return output_dict def get_metrics(self, reset:", "Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]: class_probabilities = F.softmax(output_dict['logits'], dim=-1) output_dict['class_probs']", "def forward(self, text: Dict[str, torch.LongTensor], label: torch.IntTensor = None, metadata:", "torch.nn.CrossEntropyLoss() self.pool = lambda text, mask: util.get_final_encoder_states(text, mask, bidirectional=True) initializer(self)", "torch.Tensor]: class_probabilities = F.softmax(output_dict['logits'], dim=-1) output_dict['class_probs'] = class_probabilities return output_dict", "self.text_encoder = text_encoder self.classifier_feedforward = classifier_feedforward self.prediction_layer = torch.nn.Linear(self.classifier_feedforward.get_output_dim() ,", "Vocabulary from allennlp.models.model import Model from allennlp.modules import FeedForward, TextFieldEmbedder,", "-> Dict[str, float]: metric_dict = {} sum_f1 = 0.0 for", "average_f1 = sum_f1 / total_len metric_dict['average_F1'] = average_f1 metric_dict['accuracy'] =", "shape ``(batch_size, num_labels)`` representing unnormalised log probabilities of the label.", "for i in range(self.num_classes): self.label_f1_metrics[vocab.get_token_from_index(index=i, namespace=\"labels\")] = F1Measure(positive_label=i) self.loss =", "per label for i in range(self.num_classes): metric = self.label_f1_metrics[self.vocab.get_token_from_index(index=i, namespace=\"labels\")]", "i in range(self.num_classes): self.label_f1_metrics[vocab.get_token_from_index(index=i, namespace=\"labels\")] = F1Measure(positive_label=i) self.loss = torch.nn.CrossEntropyLoss()", "metric_dict[name + '_F1'] = metric_val[2] sum_f1 += metric_val[2] names =", "classifier_feedforward: FeedForward, verbose_metrics: False, initializer: InitializerApplicator = InitializerApplicator(), regularizer: Optional[RegularizerApplicator]", "the premise and hypothesis with 'premise_tokens' and 'hypothesis_tokens' keys respectively.", "F.softmax(logits, dim=1) output_dict = {\"logits\": logits} if label is not", "From a ``LabelField`` metadata : ``List[Dict[str, Any]]``, optional, (default =", "name, metric in self.label_f1_metrics.items(): metric_val = metric.get_metric(reset) if self.verbose_metrics: metric_dict[name", "``List[Dict[str, Any]]``, optional, (default = None) Metadata containing the original", "consisting of: label_logits : torch.FloatTensor A tensor of shape ``(batch_size,", "allennlp.data import Vocabulary from allennlp.models.model import Model from allennlp.modules import", "from allennlp.nn import util from allennlp.training.metrics import CategoricalAccuracy, F1Measure from", "torch.LongTensor], label: torch.IntTensor = None, metadata: List[Dict[str, Any]] = None)", "log probabilities of the label. label_probs : torch.FloatTensor A tensor", "A scalar loss to be optimised. \"\"\" embedded_text = self.text_field_embedder(text)", "List, Any import torch import torch.nn.functional as F from allennlp.data", "the label. label_probs : torch.FloatTensor A tensor of shape ``(batch_size,", "= None) -> Dict[str, torch.Tensor]: \"\"\" Parameters ---------- text :", "self.text_encoder(embedded_text, mask) pooled = self.pool(encoded_text, mask) ff_hidden = self.classifier_feedforward(pooled) logits", "allennlp.nn import InitializerApplicator, RegularizerApplicator from allennlp.nn import util from allennlp.training.metrics", "of the label. label_probs : torch.FloatTensor A tensor of shape", "metric_dict = {} sum_f1 = 0.0 for name, metric in", "+= metric_val[2] names = list(self.label_f1_metrics.keys()) total_len = len(names) average_f1 =", ": torch.FloatTensor A tensor of shape ``(batch_size, num_labels)`` representing probabilities", "sum_f1 / total_len metric_dict['average_F1'] = average_f1 metric_dict['accuracy'] = self.label_accuracy.get_metric(reset) return", "None) Metadata containing the original tokenization of the premise and", "compute F1 per label for i in range(self.num_classes): metric =", "CrossEntropyLoss. Evaluated with CategoricalAccuracy & F1. \"\"\" def __init__(self, vocab:", "/ total_len metric_dict['average_F1'] = average_f1 metric_dict['accuracy'] = self.label_accuracy.get_metric(reset) return metric_dict", "be optimised. \"\"\" embedded_text = self.text_field_embedder(text) mask = util.get_text_field_mask(text) encoded_text", "BiLSTM 3) Append the first and last encoder states 4)", "util.get_final_encoder_states(text, mask, bidirectional=True) initializer(self) @overrides def forward(self, text: Dict[str, torch.LongTensor],", "------- An output dictionary consisting of: label_logits : torch.FloatTensor A", "Seq2SeqEncoder from allennlp.nn import InitializerApplicator, RegularizerApplicator from allennlp.nn import util", "'hypothesis_tokens' keys respectively. Returns ------- An output dictionary consisting of:", "super(TextClassifier, self).__init__(vocab, regularizer) self.text_field_embedder = text_field_embedder self.num_classes = self.vocab.get_vocab_size(\"labels\") self.text_encoder", "using `text_field_embedder` 2) Seq2SeqEncoder, e.g. BiLSTM 3) Append the first", "text, mask: util.get_final_encoder_states(text, mask, bidirectional=True) initializer(self) @overrides def forward(self, text:", "CategoricalAccuracy & F1. \"\"\" def __init__(self, vocab: Vocabulary, text_field_embedder: TextFieldEmbedder,", "F1. \"\"\" def __init__(self, vocab: Vocabulary, text_field_embedder: TextFieldEmbedder, text_encoder: Seq2SeqEncoder,", "as F from allennlp.data import Vocabulary from allennlp.models.model import Model", ": torch.IntTensor, optional (default = None) From a ``LabelField`` metadata", "with CategoricalAccuracy & F1. \"\"\" def __init__(self, vocab: Vocabulary, text_field_embedder:", "tokens using `text_field_embedder` 2) Seq2SeqEncoder, e.g. BiLSTM 3) Append the", "= None, metadata: List[Dict[str, Any]] = None) -> Dict[str, torch.Tensor]:", "from overrides import overrides @Model.register(\"text_classifier\") class TextClassifier(Model): \"\"\" Implements a", "verbose_metrics for i in range(self.num_classes): self.label_f1_metrics[vocab.get_token_from_index(index=i, namespace=\"labels\")] = F1Measure(positive_label=i) self.loss", "the label. loss : torch.FloatTensor, optional A scalar loss to", "metric(class_probs, label) self.label_accuracy(logits, label) return output_dict @overrides def decode(self, output_dict:", "feedforward layer Optimized with CrossEntropyLoss. Evaluated with CategoricalAccuracy & F1.", "dictionary consisting of: label_logits : torch.FloatTensor A tensor of shape", ": Dict[str, torch.LongTensor] From a ``TextField`` label : torch.IntTensor, optional", "self.num_classes) self.label_accuracy = CategoricalAccuracy() self.label_f1_metrics = {} self.verbose_metrics = verbose_metrics", "-> None: super(TextClassifier, self).__init__(vocab, regularizer) self.text_field_embedder = text_field_embedder self.num_classes =", "verbose_metrics: False, initializer: InitializerApplicator = InitializerApplicator(), regularizer: Optional[RegularizerApplicator] = None,", "unnormalised log probabilities of the label. label_probs : torch.FloatTensor A", "= class_probabilities return output_dict def get_metrics(self, reset: bool = False)" ]
[ "--rcfile=tests/pylintrc tests') namespace.add_task(pylint_tests) ##### # # build and distribute #", "set() for root, dirnames, files in os.walk(os.curdir): if '__pycache__' in", "disable=unused-argument dirs = set() for root, dirnames, files in os.walk(os.curdir):", "sdist') namespace.add_task(sdist) @invoke.task(pre=[clean_all]) def wheel(context): \"\"\"Build a wheel distribution\"\"\" context.run('python", "namespace_clean.add_task(build_clean, 'build') @invoke.task def dist_clean(context): \"\"\"Remove the dist directory\"\"\" #", "list(namespace_clean.tasks.values()) @invoke.task(pre=list(namespace_clean.tasks.values()), default=True) def clean_all(context): \"\"\"Run all clean tasks\"\"\" #", "= invoke.Collection() namespace_clean = invoke.Collection('clean') namespace.add_collection(namespace_clean, 'clean') ##### # #", "os.listdir(os.curdir): if name.endswith('.egg-info'): dirs.add(name) if name.endswith('.egg'): dirs.add(name) rmrf(dirs) namespace_clean.add_task(eggs_clean, 'eggs')", "distribution\"\"\" context.run('python setup.py bdist_wheel') namespace.add_task(wheel) # # these two tasks", "import shutil import invoke TASK_ROOT = pathlib.Path(__file__).resolve().parent TASK_ROOT_STR = str(TASK_ROOT)", "distribution\"\"\" context.run('python setup.py sdist') namespace.add_task(sdist) @invoke.task(pre=[clean_all]) def wheel(context): \"\"\"Build a", "doesn't remove bare files try: os.remove(item) except FileNotFoundError: pass #", "if file.endswith(\".pyc\"): dirs.add(os.path.join(root, file)) print(\"Removing __pycache__ directories and .pyc files\")", "be run with 'invoke'\"\"\" import os import pathlib import shutil", "task which runs all the tasks in the clean namespace", "# pylint: disable=unused-argument with context.cd(TASK_ROOT_STR): dirs = ['.pytest_cache', '.cache', '.coverage']", "clean namespace clean_tasks = list(namespace_clean.tasks.values()) @invoke.task(pre=list(namespace_clean.tasks.values()), default=True) def clean_all(context): \"\"\"Run", "shared function def rmrf(items, verbose=True): \"\"\"Silently remove a list of", "to pypi\"\"\" # context.run('twine upload dist/*') # namespace.add_task(pypi) # @invoke.task(pre=[sdist,", "disable=unused-argument rmrf(DISTDIR) namespace_clean.add_task(dist_clean, 'dist') @invoke.task def eggs_clean(context): \"\"\"Remove egg directories\"\"\"", "# context.run('twine upload dist/*') # namespace.add_task(pypi) # @invoke.task(pre=[sdist, wheel]) #", "# def pypi(context): # \"\"\"Build and upload a distribution to", "using pylint\"\"\" context.run('pylint --rcfile=cmd2_myplugin/pylintrc cmd2_myplugin') namespace.add_task(pylint) @invoke.task def pylint_tests(context): \"\"\"Check", "# pylint: disable=unused-argument rmrf(DISTDIR) namespace_clean.add_task(dist_clean, 'dist') @invoke.task def eggs_clean(context): \"\"\"Remove", "directories\"\"\" # pylint: disable=unused-argument with context.cd(TASK_ROOT_STR): dirs = ['.pytest_cache', '.cache',", "namespace = invoke.Collection() namespace_clean = invoke.Collection('clean') namespace.add_collection(namespace_clean, 'clean') ##### #", "= set() for root, dirnames, files in os.walk(os.curdir): if '__pycache__'", "except FileNotFoundError: pass # create namespaces namespace = invoke.Collection() namespace_clean", "directories and *.pyc files\"\"\" # pylint: disable=unused-argument dirs = set()", "items: if verbose: print(\"Removing {}\".format(item)) shutil.rmtree(item, ignore_errors=True) # rmtree doesn't", "disable=unused-argument with context.cd(TASK_ROOT_STR): dirs = ['.pytest_cache', '.cache', '.coverage'] rmrf(dirs) namespace_clean.add_task(pytest_clean,", "--cov-report=term --cov-report=html' if append_cov: command_str += ' --cov-append' if junit:", "def eggs_clean(context): \"\"\"Remove egg directories\"\"\" # pylint: disable=unused-argument dirs =", "# # @invoke.task(pre=[sdist, wheel]) # def pypi(context): # \"\"\"Build and", "pypi_test(context): # \"\"\"Build and upload a distribution to https://test.pypi.org\"\"\" #", "'.coverage'] rmrf(dirs) namespace_clean.add_task(pytest_clean, 'pytest') @invoke.task def pylint(context): \"\"\"Check code quality", "def bytecode_clean(context): \"\"\"Remove __pycache__ directories and *.pyc files\"\"\" # pylint:", "if junit: command_str += ' --junitxml=junit/test-results.xml' command_str += ' '", "\"\"\"Remove pytest cache and code coverage files and directories\"\"\" #", "rmrf(items, verbose=True): \"\"\"Silently remove a list of directories or files\"\"\"", "BUILDDIR = 'build' DISTDIR = 'dist' @invoke.task def build_clean(context): \"\"\"Remove", "namespace.add_task(pylint_tests) ##### # # build and distribute # ##### BUILDDIR", "invoke.Collection() namespace_clean = invoke.Collection('clean') namespace.add_collection(namespace_clean, 'clean') ##### # # pytest,", "= 'build' DISTDIR = 'dist' @invoke.task def build_clean(context): \"\"\"Remove the", "build and distribute # ##### BUILDDIR = 'build' DISTDIR =", "{}\".format(item)) shutil.rmtree(item, ignore_errors=True) # rmtree doesn't remove bare files try:", "rmtree doesn't remove bare files try: os.remove(item) except FileNotFoundError: pass", "# namespace.add_task(pypi) # @invoke.task(pre=[sdist, wheel]) # def pypi_test(context): # \"\"\"Build", "file in files: if file.endswith(\".pyc\"): dirs.add(os.path.join(root, file)) print(\"Removing __pycache__ directories", "\"\"\"Silently remove a list of directories or files\"\"\" if isinstance(items,", "coverage files and directories\"\"\" # pylint: disable=unused-argument with context.cd(TASK_ROOT_STR): dirs", "disable=unused-argument dirs = set() dirs.add('.eggs') for name in os.listdir(os.curdir): if", "\"\"\"Check code quality using pylint\"\"\" context.run('pylint --rcfile=cmd2_myplugin/pylintrc cmd2_myplugin') namespace.add_task(pylint) @invoke.task", "wheel distribution\"\"\" context.run('python setup.py bdist_wheel') namespace.add_task(wheel) # # these two", "you don't # accidentally run them and upload this template", "'.cache', '.coverage'] rmrf(dirs) namespace_clean.add_task(pytest_clean, 'pytest') @invoke.task def pylint(context): \"\"\"Check code", "of test suite using pylint\"\"\" context.run('pylint --rcfile=tests/pylintrc tests') namespace.add_task(pylint_tests) #####", "--cov-report=html' if append_cov: command_str += ' --cov-append' if junit: command_str", "str((TASK_ROOT / 'tests').relative_to(ROOT_PATH)) context.run(command_str, pty=pty) namespace.add_task(pytest) @invoke.task def pytest_clean(context): \"\"\"Remove", "'__pycache__' in dirnames: dirs.add(os.path.join(root, '__pycache__')) for file in files: if", "context.run('python setup.py sdist') namespace.add_task(sdist) @invoke.task(pre=[clean_all]) def wheel(context): \"\"\"Build a wheel", "pass # create namespaces namespace = invoke.Collection() namespace_clean = invoke.Collection('clean')", "template to pypi # # @invoke.task(pre=[sdist, wheel]) # def pypi(context):", "file.endswith(\".pyc\"): dirs.add(os.path.join(root, file)) print(\"Removing __pycache__ directories and .pyc files\") rmrf(dirs,", "distribute # ##### BUILDDIR = 'build' DISTDIR = 'dist' @invoke.task", "TASK_ROOT_STR = str(TASK_ROOT) # shared function def rmrf(items, verbose=True): \"\"\"Silently", "root, dirnames, files in os.walk(os.curdir): if '__pycache__' in dirnames: dirs.add(os.path.join(root,", "pty=pty) namespace.add_task(pytest) @invoke.task def pytest_clean(context): \"\"\"Remove pytest cache and code", "make a dummy clean task which runs all the tasks", "clean_all(context): \"\"\"Run all clean tasks\"\"\" # pylint: disable=unused-argument pass namespace_clean.add_task(clean_all,", "coding: utf-8 -*- \"\"\"Development related tasks to be run with", "\"\"\"Run all clean tasks\"\"\" # pylint: disable=unused-argument pass namespace_clean.add_task(clean_all, 'all')", "upload this template to pypi # # @invoke.task(pre=[sdist, wheel]) #", "code coverage using pytest\"\"\" ROOT_PATH = TASK_ROOT.parent.parent with context.cd(str(ROOT_PATH)): command_str", "the dist directory\"\"\" # pylint: disable=unused-argument rmrf(DISTDIR) namespace_clean.add_task(dist_clean, 'dist') @invoke.task", "test suite using pylint\"\"\" context.run('pylint --rcfile=tests/pylintrc tests') namespace.add_task(pylint_tests) ##### #", "# @invoke.task(pre=[sdist, wheel]) # def pypi(context): # \"\"\"Build and upload", "= 'pytest --cov=cmd2_myplugin --cov-report=term --cov-report=html' if append_cov: command_str += '", "def clean_all(context): \"\"\"Run all clean tasks\"\"\" # pylint: disable=unused-argument pass", "append_cov=False): \"\"\"Run tests and code coverage using pytest\"\"\" ROOT_PATH =", "os.remove(item) except FileNotFoundError: pass # create namespaces namespace = invoke.Collection()", "= TASK_ROOT.parent.parent with context.cd(str(ROOT_PATH)): command_str = 'pytest --cov=cmd2_myplugin --cov-report=term --cov-report=html'", "pylint: disable=unused-argument rmrf(DISTDIR) namespace_clean.add_task(dist_clean, 'dist') @invoke.task def eggs_clean(context): \"\"\"Remove egg", "= pathlib.Path(__file__).resolve().parent TASK_ROOT_STR = str(TASK_ROOT) # shared function def rmrf(items,", "suite using pylint\"\"\" context.run('pylint --rcfile=tests/pylintrc tests') namespace.add_task(pylint_tests) ##### # #", "upload dist/*') # namespace.add_task(pypi) # @invoke.task(pre=[sdist, wheel]) # def pypi_test(context):", "[items] for item in items: if verbose: print(\"Removing {}\".format(item)) shutil.rmtree(item,", "isinstance(items, str): items = [items] for item in items: if", "pylint: disable=unused-argument pass namespace_clean.add_task(clean_all, 'all') @invoke.task(pre=[clean_all]) def sdist(context): \"\"\"Create a", "namespace_clean.add_task(pytest_clean, 'pytest') @invoke.task def pylint(context): \"\"\"Check code quality using pylint\"\"\"", "coverage using pytest\"\"\" ROOT_PATH = TASK_ROOT.parent.parent with context.cd(str(ROOT_PATH)): command_str =", "files try: os.remove(item) except FileNotFoundError: pass # create namespaces namespace", "all clean tasks\"\"\" # pylint: disable=unused-argument pass namespace_clean.add_task(clean_all, 'all') @invoke.task(pre=[clean_all])", "namespace.add_task(wheel) # # these two tasks are commented out so", "clean_tasks = list(namespace_clean.tasks.values()) @invoke.task(pre=list(namespace_clean.tasks.values()), default=True) def clean_all(context): \"\"\"Run all clean", "and code coverage files and directories\"\"\" # pylint: disable=unused-argument with", "pty=True, append_cov=False): \"\"\"Run tests and code coverage using pytest\"\"\" ROOT_PATH", "pylint(context): \"\"\"Check code quality using pylint\"\"\" context.run('pylint --rcfile=cmd2_myplugin/pylintrc cmd2_myplugin') namespace.add_task(pylint)", "name.endswith('.egg'): dirs.add(name) rmrf(dirs) namespace_clean.add_task(eggs_clean, 'eggs') @invoke.task def bytecode_clean(context): \"\"\"Remove __pycache__", "def pypi_test(context): # \"\"\"Build and upload a distribution to https://test.pypi.org\"\"\"", "= str(TASK_ROOT) # shared function def rmrf(items, verbose=True): \"\"\"Silently remove", "try: os.remove(item) except FileNotFoundError: pass # create namespaces namespace =", "import os import pathlib import shutil import invoke TASK_ROOT =", "quality using pylint\"\"\" context.run('pylint --rcfile=cmd2_myplugin/pylintrc cmd2_myplugin') namespace.add_task(pylint) @invoke.task def pylint_tests(context):", "directory\"\"\" # pylint: disable=unused-argument rmrf(DISTDIR) namespace_clean.add_task(dist_clean, 'dist') @invoke.task def eggs_clean(context):", "dist/*') # namespace.add_task(pypi) # @invoke.task(pre=[sdist, wheel]) # def pypi_test(context): #", "# shared function def rmrf(items, verbose=True): \"\"\"Silently remove a list", "rmrf(BUILDDIR) namespace_clean.add_task(build_clean, 'build') @invoke.task def dist_clean(context): \"\"\"Remove the dist directory\"\"\"", "namespace_clean.add_task(dist_clean, 'dist') @invoke.task def eggs_clean(context): \"\"\"Remove egg directories\"\"\" # pylint:", "these two tasks are commented out so you don't #", "['.pytest_cache', '.cache', '.coverage'] rmrf(dirs) namespace_clean.add_task(pytest_clean, 'pytest') @invoke.task def pylint(context): \"\"\"Check", "\"\"\"Check code quality of test suite using pylint\"\"\" context.run('pylint --rcfile=tests/pylintrc", "files\"\"\" if isinstance(items, str): items = [items] for item in", "pypi # # @invoke.task(pre=[sdist, wheel]) # def pypi(context): # \"\"\"Build", "tests and code coverage using pytest\"\"\" ROOT_PATH = TASK_ROOT.parent.parent with", "shutil.rmtree(item, ignore_errors=True) # rmtree doesn't remove bare files try: os.remove(item)", "rmrf(dirs) namespace_clean.add_task(eggs_clean, 'eggs') @invoke.task def bytecode_clean(context): \"\"\"Remove __pycache__ directories and", "str): items = [items] for item in items: if verbose:", "quality of test suite using pylint\"\"\" context.run('pylint --rcfile=tests/pylintrc tests') namespace.add_task(pylint_tests)", "@invoke.task def pytest_clean(context): \"\"\"Remove pytest cache and code coverage files", "files in os.walk(os.curdir): if '__pycache__' in dirnames: dirs.add(os.path.join(root, '__pycache__')) for", "ignore_errors=True) # rmtree doesn't remove bare files try: os.remove(item) except", "'build' DISTDIR = 'dist' @invoke.task def build_clean(context): \"\"\"Remove the build", "TASK_ROOT = pathlib.Path(__file__).resolve().parent TASK_ROOT_STR = str(TASK_ROOT) # shared function def", "upload a distribution to https://test.pypi.org\"\"\" # context.run('twine upload --repository-url https://test.pypi.org/legacy/", "# @invoke.task(pre=[sdist, wheel]) # def pypi_test(context): # \"\"\"Build and upload", "pylint: disable=unused-argument rmrf(BUILDDIR) namespace_clean.add_task(build_clean, 'build') @invoke.task def dist_clean(context): \"\"\"Remove the", "files\") rmrf(dirs, verbose=False) namespace_clean.add_task(bytecode_clean, 'bytecode') # # make a dummy", "# ##### BUILDDIR = 'build' DISTDIR = 'dist' @invoke.task def", "if isinstance(items, str): items = [items] for item in items:", "bytecode_clean(context): \"\"\"Remove __pycache__ directories and *.pyc files\"\"\" # pylint: disable=unused-argument", "run them and upload this template to pypi # #", "@invoke.task def pylint(context): \"\"\"Check code quality using pylint\"\"\" context.run('pylint --rcfile=cmd2_myplugin/pylintrc", "dirs = set() dirs.add('.eggs') for name in os.listdir(os.curdir): if name.endswith('.egg-info'):", "import pathlib import shutil import invoke TASK_ROOT = pathlib.Path(__file__).resolve().parent TASK_ROOT_STR", "pytest, pylint, and codecov # ##### @invoke.task def pytest(context, junit=False,", "in os.walk(os.curdir): if '__pycache__' in dirnames: dirs.add(os.path.join(root, '__pycache__')) for file", "cache and code coverage files and directories\"\"\" # pylint: disable=unused-argument", "= invoke.Collection('clean') namespace.add_collection(namespace_clean, 'clean') ##### # # pytest, pylint, and", "verbose: print(\"Removing {}\".format(item)) shutil.rmtree(item, ignore_errors=True) # rmtree doesn't remove bare", "-*- coding: utf-8 -*- \"\"\"Development related tasks to be run", "' ' + str((TASK_ROOT / 'tests').relative_to(ROOT_PATH)) context.run(command_str, pty=pty) namespace.add_task(pytest) @invoke.task", "and distribute # ##### BUILDDIR = 'build' DISTDIR = 'dist'", "def pytest_clean(context): \"\"\"Remove pytest cache and code coverage files and", "source distribution\"\"\" context.run('python setup.py sdist') namespace.add_task(sdist) @invoke.task(pre=[clean_all]) def wheel(context): \"\"\"Build", "dirs = set() for root, dirnames, files in os.walk(os.curdir): if", "for file in files: if file.endswith(\".pyc\"): dirs.add(os.path.join(root, file)) print(\"Removing __pycache__", "DISTDIR = 'dist' @invoke.task def build_clean(context): \"\"\"Remove the build directory\"\"\"", "+= ' --junitxml=junit/test-results.xml' command_str += ' ' + str((TASK_ROOT /", "if name.endswith('.egg'): dirs.add(name) rmrf(dirs) namespace_clean.add_task(eggs_clean, 'eggs') @invoke.task def bytecode_clean(context): \"\"\"Remove", "name.endswith('.egg-info'): dirs.add(name) if name.endswith('.egg'): dirs.add(name) rmrf(dirs) namespace_clean.add_task(eggs_clean, 'eggs') @invoke.task def", "@invoke.task(pre=[clean_all]) def wheel(context): \"\"\"Build a wheel distribution\"\"\" context.run('python setup.py bdist_wheel')", "namespace_clean.add_task(clean_all, 'all') @invoke.task(pre=[clean_all]) def sdist(context): \"\"\"Create a source distribution\"\"\" context.run('python", "context.run('pylint --rcfile=cmd2_myplugin/pylintrc cmd2_myplugin') namespace.add_task(pylint) @invoke.task def pylint_tests(context): \"\"\"Check code quality", "for item in items: if verbose: print(\"Removing {}\".format(item)) shutil.rmtree(item, ignore_errors=True)", "# pylint: disable=unused-argument pass namespace_clean.add_task(clean_all, 'all') @invoke.task(pre=[clean_all]) def sdist(context): \"\"\"Create", "rmrf(dirs, verbose=False) namespace_clean.add_task(bytecode_clean, 'bytecode') # # make a dummy clean", "namespace_clean.add_task(bytecode_clean, 'bytecode') # # make a dummy clean task which", "build directory\"\"\" # pylint: disable=unused-argument rmrf(BUILDDIR) namespace_clean.add_task(build_clean, 'build') @invoke.task def", "# # these two tasks are commented out so you", "\"\"\"Build and upload a distribution to https://test.pypi.org\"\"\" # context.run('twine upload", "pylint: disable=unused-argument with context.cd(TASK_ROOT_STR): dirs = ['.pytest_cache', '.cache', '.coverage'] rmrf(dirs)", "out so you don't # accidentally run them and upload", "distribution to pypi\"\"\" # context.run('twine upload dist/*') # namespace.add_task(pypi) #", "code quality of test suite using pylint\"\"\" context.run('pylint --rcfile=tests/pylintrc tests')", "context.cd(str(ROOT_PATH)): command_str = 'pytest --cov=cmd2_myplugin --cov-report=term --cov-report=html' if append_cov: command_str", "rmrf(dirs) namespace_clean.add_task(pytest_clean, 'pytest') @invoke.task def pylint(context): \"\"\"Check code quality using", "@invoke.task def dist_clean(context): \"\"\"Remove the dist directory\"\"\" # pylint: disable=unused-argument", "\"\"\"Run tests and code coverage using pytest\"\"\" ROOT_PATH = TASK_ROOT.parent.parent", "dirnames: dirs.add(os.path.join(root, '__pycache__')) for file in files: if file.endswith(\".pyc\"): dirs.add(os.path.join(root,", "directory\"\"\" # pylint: disable=unused-argument rmrf(BUILDDIR) namespace_clean.add_task(build_clean, 'build') @invoke.task def dist_clean(context):", "# pytest, pylint, and codecov # ##### @invoke.task def pytest(context,", "append_cov: command_str += ' --cov-append' if junit: command_str += '", "pylint\"\"\" context.run('pylint --rcfile=cmd2_myplugin/pylintrc cmd2_myplugin') namespace.add_task(pylint) @invoke.task def pylint_tests(context): \"\"\"Check code", "tests') namespace.add_task(pylint_tests) ##### # # build and distribute # #####", "--rcfile=cmd2_myplugin/pylintrc cmd2_myplugin') namespace.add_task(pylint) @invoke.task def pylint_tests(context): \"\"\"Check code quality of", "wheel]) # def pypi(context): # \"\"\"Build and upload a distribution", "invoke.Collection('clean') namespace.add_collection(namespace_clean, 'clean') ##### # # pytest, pylint, and codecov", "with context.cd(TASK_ROOT_STR): dirs = ['.pytest_cache', '.cache', '.coverage'] rmrf(dirs) namespace_clean.add_task(pytest_clean, 'pytest')", "# # build and distribute # ##### BUILDDIR = 'build'", "pylint: disable=unused-argument dirs = set() for root, dirnames, files in", "' --junitxml=junit/test-results.xml' command_str += ' ' + str((TASK_ROOT / 'tests').relative_to(ROOT_PATH))", "def pypi(context): # \"\"\"Build and upload a distribution to pypi\"\"\"", "bdist_wheel') namespace.add_task(wheel) # # these two tasks are commented out", "set() dirs.add('.eggs') for name in os.listdir(os.curdir): if name.endswith('.egg-info'): dirs.add(name) if", "clean task which runs all the tasks in the clean", ".pyc files\") rmrf(dirs, verbose=False) namespace_clean.add_task(bytecode_clean, 'bytecode') # # make a", "and *.pyc files\"\"\" # pylint: disable=unused-argument dirs = set() for", "setup.py sdist') namespace.add_task(sdist) @invoke.task(pre=[clean_all]) def wheel(context): \"\"\"Build a wheel distribution\"\"\"", "def pytest(context, junit=False, pty=True, append_cov=False): \"\"\"Run tests and code coverage", "##### # # build and distribute # ##### BUILDDIR =", "pypi\"\"\" # context.run('twine upload dist/*') # namespace.add_task(pypi) # @invoke.task(pre=[sdist, wheel])", "namespace clean_tasks = list(namespace_clean.tasks.values()) @invoke.task(pre=list(namespace_clean.tasks.values()), default=True) def clean_all(context): \"\"\"Run all", "create namespaces namespace = invoke.Collection() namespace_clean = invoke.Collection('clean') namespace.add_collection(namespace_clean, 'clean')", "using pytest\"\"\" ROOT_PATH = TASK_ROOT.parent.parent with context.cd(str(ROOT_PATH)): command_str = 'pytest", "def wheel(context): \"\"\"Build a wheel distribution\"\"\" context.run('python setup.py bdist_wheel') namespace.add_task(wheel)", "dirs.add('.eggs') for name in os.listdir(os.curdir): if name.endswith('.egg-info'): dirs.add(name) if name.endswith('.egg'):", "*.pyc files\"\"\" # pylint: disable=unused-argument dirs = set() for root,", "pylint: disable=unused-argument dirs = set() dirs.add('.eggs') for name in os.listdir(os.curdir):", "pytest cache and code coverage files and directories\"\"\" # pylint:", "two tasks are commented out so you don't # accidentally", "# pylint: disable=unused-argument dirs = set() dirs.add('.eggs') for name in", "and upload this template to pypi # # @invoke.task(pre=[sdist, wheel])", "context.run('pylint --rcfile=tests/pylintrc tests') namespace.add_task(pylint_tests) ##### # # build and distribute", "\"\"\"Remove the dist directory\"\"\" # pylint: disable=unused-argument rmrf(DISTDIR) namespace_clean.add_task(dist_clean, 'dist')", "setup.py bdist_wheel') namespace.add_task(wheel) # # these two tasks are commented", "junit: command_str += ' --junitxml=junit/test-results.xml' command_str += ' ' +", "all the tasks in the clean namespace clean_tasks = list(namespace_clean.tasks.values())", "# these two tasks are commented out so you don't", "def rmrf(items, verbose=True): \"\"\"Silently remove a list of directories or", "# -*- coding: utf-8 -*- \"\"\"Development related tasks to be", "command_str += ' ' + str((TASK_ROOT / 'tests').relative_to(ROOT_PATH)) context.run(command_str, pty=pty)", "##### BUILDDIR = 'build' DISTDIR = 'dist' @invoke.task def build_clean(context):", "__pycache__ directories and *.pyc files\"\"\" # pylint: disable=unused-argument dirs =", "@invoke.task(pre=[clean_all]) def sdist(context): \"\"\"Create a source distribution\"\"\" context.run('python setup.py sdist')", "context.run('python setup.py bdist_wheel') namespace.add_task(wheel) # # these two tasks are", "in items: if verbose: print(\"Removing {}\".format(item)) shutil.rmtree(item, ignore_errors=True) # rmtree", "and .pyc files\") rmrf(dirs, verbose=False) namespace_clean.add_task(bytecode_clean, 'bytecode') # # make", "to pypi # # @invoke.task(pre=[sdist, wheel]) # def pypi(context): #", "accidentally run them and upload this template to pypi #", "FileNotFoundError: pass # create namespaces namespace = invoke.Collection() namespace_clean =", "remove bare files try: os.remove(item) except FileNotFoundError: pass # create", "@invoke.task def bytecode_clean(context): \"\"\"Remove __pycache__ directories and *.pyc files\"\"\" #", "dist directory\"\"\" # pylint: disable=unused-argument rmrf(DISTDIR) namespace_clean.add_task(dist_clean, 'dist') @invoke.task def", "bare files try: os.remove(item) except FileNotFoundError: pass # create namespaces", "= set() dirs.add('.eggs') for name in os.listdir(os.curdir): if name.endswith('.egg-info'): dirs.add(name)", "file)) print(\"Removing __pycache__ directories and .pyc files\") rmrf(dirs, verbose=False) namespace_clean.add_task(bytecode_clean,", "pylint, and codecov # ##### @invoke.task def pytest(context, junit=False, pty=True,", "def pylint_tests(context): \"\"\"Check code quality of test suite using pylint\"\"\"", "'bytecode') # # make a dummy clean task which runs", "so you don't # accidentally run them and upload this", "'invoke'\"\"\" import os import pathlib import shutil import invoke TASK_ROOT", "-*- \"\"\"Development related tasks to be run with 'invoke'\"\"\" import", "pass namespace_clean.add_task(clean_all, 'all') @invoke.task(pre=[clean_all]) def sdist(context): \"\"\"Create a source distribution\"\"\"", "a distribution to pypi\"\"\" # context.run('twine upload dist/*') # namespace.add_task(pypi)", "/ 'tests').relative_to(ROOT_PATH)) context.run(command_str, pty=pty) namespace.add_task(pytest) @invoke.task def pytest_clean(context): \"\"\"Remove pytest", "to https://test.pypi.org\"\"\" # context.run('twine upload --repository-url https://test.pypi.org/legacy/ dist/*') # namespace.add_task(pypi_test)", "tasks are commented out so you don't # accidentally run", "rmrf(DISTDIR) namespace_clean.add_task(dist_clean, 'dist') @invoke.task def eggs_clean(context): \"\"\"Remove egg directories\"\"\" #", "print(\"Removing __pycache__ directories and .pyc files\") rmrf(dirs, verbose=False) namespace_clean.add_task(bytecode_clean, 'bytecode')", "= ['.pytest_cache', '.cache', '.coverage'] rmrf(dirs) namespace_clean.add_task(pytest_clean, 'pytest') @invoke.task def pylint(context):", "a distribution to https://test.pypi.org\"\"\" # context.run('twine upload --repository-url https://test.pypi.org/legacy/ dist/*')", "@invoke.task(pre=[sdist, wheel]) # def pypi(context): # \"\"\"Build and upload a", "pathlib import shutil import invoke TASK_ROOT = pathlib.Path(__file__).resolve().parent TASK_ROOT_STR =", "cmd2_myplugin') namespace.add_task(pylint) @invoke.task def pylint_tests(context): \"\"\"Check code quality of test", "def sdist(context): \"\"\"Create a source distribution\"\"\" context.run('python setup.py sdist') namespace.add_task(sdist)", "--junitxml=junit/test-results.xml' command_str += ' ' + str((TASK_ROOT / 'tests').relative_to(ROOT_PATH)) context.run(command_str,", "os.walk(os.curdir): if '__pycache__' in dirnames: dirs.add(os.path.join(root, '__pycache__')) for file in", "# # pytest, pylint, and codecov # ##### @invoke.task def", "this template to pypi # # @invoke.task(pre=[sdist, wheel]) # def", "= list(namespace_clean.tasks.values()) @invoke.task(pre=list(namespace_clean.tasks.values()), default=True) def clean_all(context): \"\"\"Run all clean tasks\"\"\"", "don't # accidentally run them and upload this template to", "@invoke.task(pre=[sdist, wheel]) # def pypi_test(context): # \"\"\"Build and upload a", "files\"\"\" # pylint: disable=unused-argument dirs = set() for root, dirnames,", "disable=unused-argument rmrf(BUILDDIR) namespace_clean.add_task(build_clean, 'build') @invoke.task def dist_clean(context): \"\"\"Remove the dist", "the build directory\"\"\" # pylint: disable=unused-argument rmrf(BUILDDIR) namespace_clean.add_task(build_clean, 'build') @invoke.task", "in dirnames: dirs.add(os.path.join(root, '__pycache__')) for file in files: if file.endswith(\".pyc\"):", "clean tasks\"\"\" # pylint: disable=unused-argument pass namespace_clean.add_task(clean_all, 'all') @invoke.task(pre=[clean_all]) def", "os import pathlib import shutil import invoke TASK_ROOT = pathlib.Path(__file__).resolve().parent", "\"\"\"Remove egg directories\"\"\" # pylint: disable=unused-argument dirs = set() dirs.add('.eggs')", "+= ' --cov-append' if junit: command_str += ' --junitxml=junit/test-results.xml' command_str", "directories\"\"\" # pylint: disable=unused-argument dirs = set() dirs.add('.eggs') for name", "pypi(context): # \"\"\"Build and upload a distribution to pypi\"\"\" #", "namespace_clean.add_task(eggs_clean, 'eggs') @invoke.task def bytecode_clean(context): \"\"\"Remove __pycache__ directories and *.pyc", "invoke TASK_ROOT = pathlib.Path(__file__).resolve().parent TASK_ROOT_STR = str(TASK_ROOT) # shared function", "import invoke TASK_ROOT = pathlib.Path(__file__).resolve().parent TASK_ROOT_STR = str(TASK_ROOT) # shared", "'tests').relative_to(ROOT_PATH)) context.run(command_str, pty=pty) namespace.add_task(pytest) @invoke.task def pytest_clean(context): \"\"\"Remove pytest cache", "upload a distribution to pypi\"\"\" # context.run('twine upload dist/*') #", "default=True) def clean_all(context): \"\"\"Run all clean tasks\"\"\" # pylint: disable=unused-argument", "dirs.add(name) rmrf(dirs) namespace_clean.add_task(eggs_clean, 'eggs') @invoke.task def bytecode_clean(context): \"\"\"Remove __pycache__ directories", "# build and distribute # ##### BUILDDIR = 'build' DISTDIR", "def pylint(context): \"\"\"Check code quality using pylint\"\"\" context.run('pylint --rcfile=cmd2_myplugin/pylintrc cmd2_myplugin')", "for name in os.listdir(os.curdir): if name.endswith('.egg-info'): dirs.add(name) if name.endswith('.egg'): dirs.add(name)", "if verbose: print(\"Removing {}\".format(item)) shutil.rmtree(item, ignore_errors=True) # rmtree doesn't remove", "run with 'invoke'\"\"\" import os import pathlib import shutil import", "pytest(context, junit=False, pty=True, append_cov=False): \"\"\"Run tests and code coverage using", "# # make a dummy clean task which runs all", "tasks in the clean namespace clean_tasks = list(namespace_clean.tasks.values()) @invoke.task(pre=list(namespace_clean.tasks.values()), default=True)", "eggs_clean(context): \"\"\"Remove egg directories\"\"\" # pylint: disable=unused-argument dirs = set()", "'build') @invoke.task def dist_clean(context): \"\"\"Remove the dist directory\"\"\" # pylint:", "' + str((TASK_ROOT / 'tests').relative_to(ROOT_PATH)) context.run(command_str, pty=pty) namespace.add_task(pytest) @invoke.task def", "# def pypi_test(context): # \"\"\"Build and upload a distribution to", "sdist(context): \"\"\"Create a source distribution\"\"\" context.run('python setup.py sdist') namespace.add_task(sdist) @invoke.task(pre=[clean_all])", "name in os.listdir(os.curdir): if name.endswith('.egg-info'): dirs.add(name) if name.endswith('.egg'): dirs.add(name) rmrf(dirs)", "'all') @invoke.task(pre=[clean_all]) def sdist(context): \"\"\"Create a source distribution\"\"\" context.run('python setup.py", "list of directories or files\"\"\" if isinstance(items, str): items =", "'__pycache__')) for file in files: if file.endswith(\".pyc\"): dirs.add(os.path.join(root, file)) print(\"Removing", "directories and .pyc files\") rmrf(dirs, verbose=False) namespace_clean.add_task(bytecode_clean, 'bytecode') # #", "# rmtree doesn't remove bare files try: os.remove(item) except FileNotFoundError:", "command_str += ' --junitxml=junit/test-results.xml' command_str += ' ' + str((TASK_ROOT", "\"\"\"Create a source distribution\"\"\" context.run('python setup.py sdist') namespace.add_task(sdist) @invoke.task(pre=[clean_all]) def", "ROOT_PATH = TASK_ROOT.parent.parent with context.cd(str(ROOT_PATH)): command_str = 'pytest --cov=cmd2_myplugin --cov-report=term", "str(TASK_ROOT) # shared function def rmrf(items, verbose=True): \"\"\"Silently remove a", "\"\"\"Remove the build directory\"\"\" # pylint: disable=unused-argument rmrf(BUILDDIR) namespace_clean.add_task(build_clean, 'build')", "@invoke.task(pre=list(namespace_clean.tasks.values()), default=True) def clean_all(context): \"\"\"Run all clean tasks\"\"\" # pylint:", "files: if file.endswith(\".pyc\"): dirs.add(os.path.join(root, file)) print(\"Removing __pycache__ directories and .pyc", "pathlib.Path(__file__).resolve().parent TASK_ROOT_STR = str(TASK_ROOT) # shared function def rmrf(items, verbose=True):", "'clean') ##### # # pytest, pylint, and codecov # #####", "'pytest') @invoke.task def pylint(context): \"\"\"Check code quality using pylint\"\"\" context.run('pylint", "and code coverage using pytest\"\"\" ROOT_PATH = TASK_ROOT.parent.parent with context.cd(str(ROOT_PATH)):", "wheel(context): \"\"\"Build a wheel distribution\"\"\" context.run('python setup.py bdist_wheel') namespace.add_task(wheel) #", "\"\"\"Development related tasks to be run with 'invoke'\"\"\" import os", "TASK_ROOT.parent.parent with context.cd(str(ROOT_PATH)): command_str = 'pytest --cov=cmd2_myplugin --cov-report=term --cov-report=html' if", "\"\"\"Remove __pycache__ directories and *.pyc files\"\"\" # pylint: disable=unused-argument dirs", "them and upload this template to pypi # # @invoke.task(pre=[sdist,", "##### # # pytest, pylint, and codecov # ##### @invoke.task", "tasks to be run with 'invoke'\"\"\" import os import pathlib", "__pycache__ directories and .pyc files\") rmrf(dirs, verbose=False) namespace_clean.add_task(bytecode_clean, 'bytecode') #", "# pylint: disable=unused-argument rmrf(BUILDDIR) namespace_clean.add_task(build_clean, 'build') @invoke.task def dist_clean(context): \"\"\"Remove", "'eggs') @invoke.task def bytecode_clean(context): \"\"\"Remove __pycache__ directories and *.pyc files\"\"\"", "runs all the tasks in the clean namespace clean_tasks =", "shutil import invoke TASK_ROOT = pathlib.Path(__file__).resolve().parent TASK_ROOT_STR = str(TASK_ROOT) #", "+= ' ' + str((TASK_ROOT / 'tests').relative_to(ROOT_PATH)) context.run(command_str, pty=pty) namespace.add_task(pytest)", "utf-8 -*- \"\"\"Development related tasks to be run with 'invoke'\"\"\"", "egg directories\"\"\" # pylint: disable=unused-argument dirs = set() dirs.add('.eggs') for", "namespace.add_collection(namespace_clean, 'clean') ##### # # pytest, pylint, and codecov #", "junit=False, pty=True, append_cov=False): \"\"\"Run tests and code coverage using pytest\"\"\"", "\"\"\"Build a wheel distribution\"\"\" context.run('python setup.py bdist_wheel') namespace.add_task(wheel) # #", "of directories or files\"\"\" if isinstance(items, str): items = [items]", "dirs.add(os.path.join(root, '__pycache__')) for file in files: if file.endswith(\".pyc\"): dirs.add(os.path.join(root, file))", "# \"\"\"Build and upload a distribution to pypi\"\"\" # context.run('twine", "pytest_clean(context): \"\"\"Remove pytest cache and code coverage files and directories\"\"\"", "dirnames, files in os.walk(os.curdir): if '__pycache__' in dirnames: dirs.add(os.path.join(root, '__pycache__'))", "disable=unused-argument pass namespace_clean.add_task(clean_all, 'all') @invoke.task(pre=[clean_all]) def sdist(context): \"\"\"Create a source", "def build_clean(context): \"\"\"Remove the build directory\"\"\" # pylint: disable=unused-argument rmrf(BUILDDIR)", "--cov-append' if junit: command_str += ' --junitxml=junit/test-results.xml' command_str += '", "and codecov # ##### @invoke.task def pytest(context, junit=False, pty=True, append_cov=False):", "namespace.add_task(pylint) @invoke.task def pylint_tests(context): \"\"\"Check code quality of test suite", "namespaces namespace = invoke.Collection() namespace_clean = invoke.Collection('clean') namespace.add_collection(namespace_clean, 'clean') #####", "directories or files\"\"\" if isinstance(items, str): items = [items] for", "the tasks in the clean namespace clean_tasks = list(namespace_clean.tasks.values()) @invoke.task(pre=list(namespace_clean.tasks.values()),", "namespace.add_task(sdist) @invoke.task(pre=[clean_all]) def wheel(context): \"\"\"Build a wheel distribution\"\"\" context.run('python setup.py", "in files: if file.endswith(\".pyc\"): dirs.add(os.path.join(root, file)) print(\"Removing __pycache__ directories and", "with context.cd(str(ROOT_PATH)): command_str = 'pytest --cov=cmd2_myplugin --cov-report=term --cov-report=html' if append_cov:", "dirs.add(name) if name.endswith('.egg'): dirs.add(name) rmrf(dirs) namespace_clean.add_task(eggs_clean, 'eggs') @invoke.task def bytecode_clean(context):", "and upload a distribution to pypi\"\"\" # context.run('twine upload dist/*')", "namespace.add_task(pypi) # @invoke.task(pre=[sdist, wheel]) # def pypi_test(context): # \"\"\"Build and", "to be run with 'invoke'\"\"\" import os import pathlib import", "or files\"\"\" if isinstance(items, str): items = [items] for item", "# create namespaces namespace = invoke.Collection() namespace_clean = invoke.Collection('clean') namespace.add_collection(namespace_clean,", "@invoke.task def pylint_tests(context): \"\"\"Check code quality of test suite using", "and directories\"\"\" # pylint: disable=unused-argument with context.cd(TASK_ROOT_STR): dirs = ['.pytest_cache',", "remove a list of directories or files\"\"\" if isinstance(items, str):", "with 'invoke'\"\"\" import os import pathlib import shutil import invoke", "using pylint\"\"\" context.run('pylint --rcfile=tests/pylintrc tests') namespace.add_task(pylint_tests) ##### # # build", "pytest\"\"\" ROOT_PATH = TASK_ROOT.parent.parent with context.cd(str(ROOT_PATH)): command_str = 'pytest --cov=cmd2_myplugin", "a source distribution\"\"\" context.run('python setup.py sdist') namespace.add_task(sdist) @invoke.task(pre=[clean_all]) def wheel(context):", "namespace_clean = invoke.Collection('clean') namespace.add_collection(namespace_clean, 'clean') ##### # # pytest, pylint,", "##### @invoke.task def pytest(context, junit=False, pty=True, append_cov=False): \"\"\"Run tests and", "context.run(command_str, pty=pty) namespace.add_task(pytest) @invoke.task def pytest_clean(context): \"\"\"Remove pytest cache and", "@invoke.task def build_clean(context): \"\"\"Remove the build directory\"\"\" # pylint: disable=unused-argument", "and upload a distribution to https://test.pypi.org\"\"\" # context.run('twine upload --repository-url", "' --cov-append' if junit: command_str += ' --junitxml=junit/test-results.xml' command_str +=", "context.run('twine upload dist/*') # namespace.add_task(pypi) # @invoke.task(pre=[sdist, wheel]) # def", "are commented out so you don't # accidentally run them", "a wheel distribution\"\"\" context.run('python setup.py bdist_wheel') namespace.add_task(wheel) # # these", "def dist_clean(context): \"\"\"Remove the dist directory\"\"\" # pylint: disable=unused-argument rmrf(DISTDIR)", "# make a dummy clean task which runs all the", "--cov=cmd2_myplugin --cov-report=term --cov-report=html' if append_cov: command_str += ' --cov-append' if", "# \"\"\"Build and upload a distribution to https://test.pypi.org\"\"\" # context.run('twine", "commented out so you don't # accidentally run them and", "# pylint: disable=unused-argument dirs = set() for root, dirnames, files", "a list of directories or files\"\"\" if isinstance(items, str): items", "a dummy clean task which runs all the tasks in", "verbose=True): \"\"\"Silently remove a list of directories or files\"\"\" if", "'pytest --cov=cmd2_myplugin --cov-report=term --cov-report=html' if append_cov: command_str += ' --cov-append'", "context.cd(TASK_ROOT_STR): dirs = ['.pytest_cache', '.cache', '.coverage'] rmrf(dirs) namespace_clean.add_task(pytest_clean, 'pytest') @invoke.task", "if '__pycache__' in dirnames: dirs.add(os.path.join(root, '__pycache__')) for file in files:", "@invoke.task def pytest(context, junit=False, pty=True, append_cov=False): \"\"\"Run tests and code", "in the clean namespace clean_tasks = list(namespace_clean.tasks.values()) @invoke.task(pre=list(namespace_clean.tasks.values()), default=True) def", "item in items: if verbose: print(\"Removing {}\".format(item)) shutil.rmtree(item, ignore_errors=True) #", "dirs = ['.pytest_cache', '.cache', '.coverage'] rmrf(dirs) namespace_clean.add_task(pytest_clean, 'pytest') @invoke.task def", "distribution to https://test.pypi.org\"\"\" # context.run('twine upload --repository-url https://test.pypi.org/legacy/ dist/*') #", "for root, dirnames, files in os.walk(os.curdir): if '__pycache__' in dirnames:", "namespace.add_task(pytest) @invoke.task def pytest_clean(context): \"\"\"Remove pytest cache and code coverage", "items = [items] for item in items: if verbose: print(\"Removing", "in os.listdir(os.curdir): if name.endswith('.egg-info'): dirs.add(name) if name.endswith('.egg'): dirs.add(name) rmrf(dirs) namespace_clean.add_task(eggs_clean,", "which runs all the tasks in the clean namespace clean_tasks", "pylint_tests(context): \"\"\"Check code quality of test suite using pylint\"\"\" context.run('pylint", "# accidentally run them and upload this template to pypi", "the clean namespace clean_tasks = list(namespace_clean.tasks.values()) @invoke.task(pre=list(namespace_clean.tasks.values()), default=True) def clean_all(context):", "codecov # ##### @invoke.task def pytest(context, junit=False, pty=True, append_cov=False): \"\"\"Run", "files and directories\"\"\" # pylint: disable=unused-argument with context.cd(TASK_ROOT_STR): dirs =", "\"\"\"Build and upload a distribution to pypi\"\"\" # context.run('twine upload", "'dist') @invoke.task def eggs_clean(context): \"\"\"Remove egg directories\"\"\" # pylint: disable=unused-argument", "verbose=False) namespace_clean.add_task(bytecode_clean, 'bytecode') # # make a dummy clean task", "wheel]) # def pypi_test(context): # \"\"\"Build and upload a distribution", "build_clean(context): \"\"\"Remove the build directory\"\"\" # pylint: disable=unused-argument rmrf(BUILDDIR) namespace_clean.add_task(build_clean,", "pylint\"\"\" context.run('pylint --rcfile=tests/pylintrc tests') namespace.add_task(pylint_tests) ##### # # build and", "= [items] for item in items: if verbose: print(\"Removing {}\".format(item))", "tasks\"\"\" # pylint: disable=unused-argument pass namespace_clean.add_task(clean_all, 'all') @invoke.task(pre=[clean_all]) def sdist(context):", "# # -*- coding: utf-8 -*- \"\"\"Development related tasks to", "related tasks to be run with 'invoke'\"\"\" import os import", "function def rmrf(items, verbose=True): \"\"\"Silently remove a list of directories", "'dist' @invoke.task def build_clean(context): \"\"\"Remove the build directory\"\"\" # pylint:", "dirs.add(os.path.join(root, file)) print(\"Removing __pycache__ directories and .pyc files\") rmrf(dirs, verbose=False)", "dummy clean task which runs all the tasks in the", "@invoke.task def eggs_clean(context): \"\"\"Remove egg directories\"\"\" # pylint: disable=unused-argument dirs", "dist_clean(context): \"\"\"Remove the dist directory\"\"\" # pylint: disable=unused-argument rmrf(DISTDIR) namespace_clean.add_task(dist_clean,", "code coverage files and directories\"\"\" # pylint: disable=unused-argument with context.cd(TASK_ROOT_STR):", "# ##### @invoke.task def pytest(context, junit=False, pty=True, append_cov=False): \"\"\"Run tests", "if append_cov: command_str += ' --cov-append' if junit: command_str +=", "= 'dist' @invoke.task def build_clean(context): \"\"\"Remove the build directory\"\"\" #", "command_str += ' --cov-append' if junit: command_str += ' --junitxml=junit/test-results.xml'", "if name.endswith('.egg-info'): dirs.add(name) if name.endswith('.egg'): dirs.add(name) rmrf(dirs) namespace_clean.add_task(eggs_clean, 'eggs') @invoke.task", "print(\"Removing {}\".format(item)) shutil.rmtree(item, ignore_errors=True) # rmtree doesn't remove bare files", "+ str((TASK_ROOT / 'tests').relative_to(ROOT_PATH)) context.run(command_str, pty=pty) namespace.add_task(pytest) @invoke.task def pytest_clean(context):", "code quality using pylint\"\"\" context.run('pylint --rcfile=cmd2_myplugin/pylintrc cmd2_myplugin') namespace.add_task(pylint) @invoke.task def", "command_str = 'pytest --cov=cmd2_myplugin --cov-report=term --cov-report=html' if append_cov: command_str +=" ]
[ "run. # You can receive tunables in the command line,", "find the max rate. If this is the case, some", "or any other thing that might make you want to", "after each iteration. :parameters: finding_max_rate: boolean Indicates whether we are", "groups. cpu_util: CPU utilization percentage. tx_pps: TX in pps. rx_pps:", "running for the first time, trying to find the max", "in bps. tx_util: TX utilization percentage. latency: Latency groups. cpu_util:", "of run_results (like iteration for example) are not relevant. run_results:", "List of tunables passed as parameters. \"\"\" # Pre iteration", "case, the run_results will be None. run_results: dict A dictionary", "are running for the first time, trying to find the", "of tunables passed as parameters. :returns: bool: should stop the", "the DUT, for example define shapers, policers, increase buffers and", "Could use this to better prepare the DUT, for example", "run. The DUT might be overheated or any other thing", "the benchmark after querying the DUT post run. The DUT", "tunables passed as parameters. \"\"\" # Pre iteration function. This", "the DUT. # Could use this to better prepare the", "bps. rate_rx_bps: RX rate in bps. tx_util: TX utilization percentage.", "will run before TRex transmits to the DUT. # Could", "\"\"\" Function ran after each iteration. :parameters: finding_max_rate: boolean Indicates", "the command line, through the kwargs argument. pass def post_iteration(self,", "increase buffers and queues. # You can receive tunables in", "before TRex transmits to the DUT. # Could use this", "buffers and queues. # You can receive tunables in the", "this to decide if to continue the benchmark after querying", "are queued. drop_rate_percentage: Percentage of packets that were dropped. rate_tx_bps:", "relevant. run_results: dict A dictionary that contains the following keys:", "are of the previous iteration. kwargs: dict List of tunables", "of packets that are queued. drop_rate_percentage: Percentage of packets that", "core. rate_p: Running rate in percentage out of max. total_tx_L1:", "necessarily a number) Pay attention: The rate is of the", "for example) are not relevant. run_results: dict A dictionary that", "kwargs argument. should_stop = False return should_stop # dynamic load", ":returns: bool: should stop the benchmarking or not. \"\"\" #", "passed as parameters. \"\"\" # Pre iteration function. This function", "Description of iteration (not necessarily a number) kwargs: dict List", "cpu_util: CPU utilization percentage. tx_pps: TX in pps. rx_pps: RX", "iteration function. This function will run before TRex transmits to", "Post iteration function. This function will run after TRex transmits", "parameters. \"\"\" # Pre iteration function. This function will run", "whether we are running for the first time, trying to", "command line, through the kwargs argument. should_stop = False return", "the DUT post run. The DUT might be overheated or", "max rate. If this is the case, some values of", "to find the max rate. In this is the case,", "CPU utilization percentage. tx_pps: TX in pps. rx_pps: RX in", "# Pre iteration function. This function will run before TRex", "iteration for example) are not relevant. run_results: dict A dictionary", "make you want to stop the run. # You can", "the first time, trying to find the max rate. In", "kwargs argument. pass def post_iteration(self, finding_max_rate, run_results, **kwargs): \"\"\" Function", "dict A dictionary that contains the following keys: queue_full_percentage: Percentage", "this to better prepare the DUT, for example define shapers,", "were dropped. rate_tx_bps: TX rate in bps. rate_rx_bps: RX rate", "before each iteration. :parameters: finding_max_rate: boolean Indicates whether we are", "as parameters. :returns: bool: should stop the benchmarking or not.", "of max. total_tx_L1: Total TX L1. total_rx_L1: Total RX L1.", "Bandwidth per core. rate_p: Running rate in percentage out of", "necessarily a number) kwargs: dict List of tunables passed as", "dictionary that contains the following keys: queue_full_percentage: Percentage of packets", "RX L1. iteration: Description of iteration (not necessarily a number)", "each iteration. :parameters: finding_max_rate: boolean Indicates whether we are running", "not. \"\"\" # Post iteration function. This function will run", "after TRex transmits to the DUT. # Could use this", "the DUT. # Could use this to decide if to", "percentage. latency: Latency groups. cpu_util: CPU utilization percentage. tx_pps: TX", "we are running for the first time, trying to find", "import stl_path class MyNDRPlugin(): def __init__(self): pass def pre_iteration(self, finding_max_rate,", "ran after each iteration. :parameters: finding_max_rate: boolean Indicates whether we", "the case, some values of run_results (like iteration for example)", "Function ran before each iteration. :parameters: finding_max_rate: boolean Indicates whether", "rest are of the previous iteration. kwargs: dict List of", "= False return should_stop # dynamic load of python module", "DUT, for example define shapers, policers, increase buffers and queues.", "Indicates whether we are running for the first time, trying", "is the case, some values of run_results (like iteration for", "The DUT might be overheated or any other thing that", "Latency groups. cpu_util: CPU utilization percentage. tx_pps: TX in pps.", "the kwargs argument. pass def post_iteration(self, finding_max_rate, run_results, **kwargs): \"\"\"", "DUT. # Could use this to better prepare the DUT,", "the previous iteration. kwargs: dict List of tunables passed as", "Percentage of packets that are queued. drop_rate_percentage: Percentage of packets", "trying to find the max rate. In this is the", "tunables in the command line, through the kwargs argument. pass", "iteration function. This function will run after TRex transmits to", "the upcoming iteration. All the rest are of the previous", "run after TRex transmits to the DUT. # Could use", "rate. If this is the case, some values of run_results", "the case, the run_results will be None. run_results: dict A", "packets that are queued. drop_rate_percentage: Percentage of packets that were", "run_results: dict A dictionary that contains the following keys: queue_full_percentage:", "transmits to the DUT. # Could use this to better", "If this is the case, some values of run_results (like", "(like iteration for example) are not relevant. run_results: dict A", "Percentage of packets that were dropped. rate_tx_bps: TX rate in", "function will run after TRex transmits to the DUT. #", "utilization percentage. tx_pps: TX in pps. rx_pps: RX in pps.", "Pay attention: The rate is of the upcoming iteration. All", "continue the benchmark after querying the DUT post run. The", "rate in bps. rate_rx_bps: RX rate in bps. tx_util: TX", "# Could use this to better prepare the DUT, for", "\"\"\" # Post iteration function. This function will run after", "tunables in the command line, through the kwargs argument. should_stop", "that contains the following keys: queue_full_percentage: Percentage of packets that", "RX rate in bps. tx_util: TX utilization percentage. latency: Latency", "stop the benchmarking or not. \"\"\" # Post iteration function.", "benchmark after querying the DUT post run. The DUT might", "Pre iteration function. This function will run before TRex transmits", "in bps. rx_bps: RX in bps. bw_per_core: Bandwidth per core.", "\"\"\" # Pre iteration function. This function will run before", "tx_util: TX utilization percentage. latency: Latency groups. cpu_util: CPU utilization", "through the kwargs argument. pass def post_iteration(self, finding_max_rate, run_results, **kwargs):", "policers, increase buffers and queues. # You can receive tunables", "and queues. # You can receive tunables in the command", "tx_bps: TX in bps. rx_bps: RX in bps. bw_per_core: Bandwidth", "the command line, through the kwargs argument. should_stop = False", "decide if to continue the benchmark after querying the DUT", "any other thing that might make you want to stop", "You can receive tunables in the command line, through the", "run_results (like iteration for example) are not relevant. run_results: dict", "are not relevant. run_results: dict A dictionary that contains the", "L1. iteration: Description of iteration (not necessarily a number) kwargs:", "in pps. rx_pps: RX in pps. tx_bps: TX in bps.", "rate_tx_bps: TX rate in bps. rate_rx_bps: RX rate in bps.", "be overheated or any other thing that might make you", "should_stop = False return should_stop # dynamic load of python", "tx_pps: TX in pps. rx_pps: RX in pps. tx_bps: TX", "run_results, **kwargs): \"\"\" Function ran after each iteration. :parameters: finding_max_rate:", "is of the upcoming iteration. All the rest are of", "post_iteration(self, finding_max_rate, run_results, **kwargs): \"\"\" Function ran after each iteration.", "iteration (not necessarily a number) kwargs: dict List of tunables", "the max rate. In this is the case, the run_results", "as parameters. \"\"\" # Pre iteration function. This function will", "first time, trying to find the max rate. In this", "kwargs: dict List of tunables passed as parameters. :returns: bool:", "L1. iteration: Description of iteration (not necessarily a number) Pay", "to decide if to continue the benchmark after querying the", "kwargs: dict List of tunables passed as parameters. \"\"\" #", "not relevant. run_results: dict A dictionary that contains the following", "in percentage out of max. total_tx_L1: Total TX L1. total_rx_L1:", "run_results will be None. run_results: dict A dictionary that contains", "TRex transmits to the DUT. # Could use this to", "The rate is of the upcoming iteration. All the rest", "passed as parameters. :returns: bool: should stop the benchmarking or", "Function ran after each iteration. :parameters: finding_max_rate: boolean Indicates whether", "to stop the run. # You can receive tunables in", "bps. bw_per_core: Bandwidth per core. rate_p: Running rate in percentage", "DUT might be overheated or any other thing that might", "total_rx_L1: Total RX L1. iteration: Description of iteration (not necessarily", "percentage. tx_pps: TX in pps. rx_pps: RX in pps. tx_bps:", "This function will run before TRex transmits to the DUT.", "previous iteration. kwargs: dict List of tunables passed as parameters.", "in the command line, through the kwargs argument. pass def", "after querying the DUT post run. The DUT might be", "you want to stop the run. # You can receive", "pass def pre_iteration(self, finding_max_rate, run_results=None, **kwargs): \"\"\" Function ran before", "Total RX L1. iteration: Description of iteration (not necessarily a", "shapers, policers, increase buffers and queues. # You can receive", "None. run_results: dict A dictionary that contains the following keys:", "line, through the kwargs argument. should_stop = False return should_stop", "of the upcoming iteration. All the rest are of the", "querying the DUT post run. The DUT might be overheated", "__init__(self): pass def pre_iteration(self, finding_max_rate, run_results=None, **kwargs): \"\"\" Function ran", "# Post iteration function. This function will run after TRex", "dict List of tunables passed as parameters. :returns: bool: should", ":parameters: finding_max_rate: boolean Indicates whether we are running for the", "pass def post_iteration(self, finding_max_rate, run_results, **kwargs): \"\"\" Function ran after", "will run after TRex transmits to the DUT. # Could", "following keys: queue_full_percentage: Percentage of packets that are queued. drop_rate_percentage:", "of iteration (not necessarily a number) Pay attention: The rate", "case, some values of run_results (like iteration for example) are", "time, trying to find the max rate. If this is", "class MyNDRPlugin(): def __init__(self): pass def pre_iteration(self, finding_max_rate, run_results=None, **kwargs):", "bw_per_core: Bandwidth per core. rate_p: Running rate in percentage out", "(not necessarily a number) Pay attention: The rate is of", "utilization percentage. latency: Latency groups. cpu_util: CPU utilization percentage. tx_pps:", "tunables passed as parameters. :returns: bool: should stop the benchmarking", "for the first time, trying to find the max rate.", "number) Pay attention: The rate is of the upcoming iteration.", "\"\"\" Function ran before each iteration. :parameters: finding_max_rate: boolean Indicates", "latency: Latency groups. cpu_util: CPU utilization percentage. tx_pps: TX in", "to continue the benchmark after querying the DUT post run.", "stop the run. # You can receive tunables in the", "the max rate. If this is the case, some values", "(not necessarily a number) kwargs: dict List of tunables passed", "rate_p: Running rate in percentage out of max. total_tx_L1: Total", "keys: queue_full_percentage: Percentage of packets that are queued. drop_rate_percentage: Percentage", "pre_iteration(self, finding_max_rate, run_results=None, **kwargs): \"\"\" Function ran before each iteration.", "for example define shapers, policers, increase buffers and queues. #", "to better prepare the DUT, for example define shapers, policers,", "the kwargs argument. should_stop = False return should_stop # dynamic", "iteration: Description of iteration (not necessarily a number) Pay attention:", "to the DUT. # Could use this to better prepare", "iteration: Description of iteration (not necessarily a number) kwargs: dict", "Description of iteration (not necessarily a number) Pay attention: The", "This function will run after TRex transmits to the DUT.", "bool: should stop the benchmarking or not. \"\"\" # Post", "post run. The DUT might be overheated or any other", "in pps. tx_bps: TX in bps. rx_bps: RX in bps.", "rx_pps: RX in pps. tx_bps: TX in bps. rx_bps: RX", "prepare the DUT, for example define shapers, policers, increase buffers", "boolean Indicates whether we are running for the first time,", "iteration. All the rest are of the previous iteration. kwargs:", "command line, through the kwargs argument. pass def post_iteration(self, finding_max_rate,", "argument. should_stop = False return should_stop # dynamic load of", "is the case, the run_results will be None. run_results: dict", "RX in bps. bw_per_core: Bandwidth per core. rate_p: Running rate", "queue_full_percentage: Percentage of packets that are queued. drop_rate_percentage: Percentage of", "that are queued. drop_rate_percentage: Percentage of packets that were dropped.", "per core. rate_p: Running rate in percentage out of max.", "queues. # You can receive tunables in the command line,", "stl_path class MyNDRPlugin(): def __init__(self): pass def pre_iteration(self, finding_max_rate, run_results=None,", "**kwargs): \"\"\" Function ran after each iteration. :parameters: finding_max_rate: boolean", "this is the case, the run_results will be None. run_results:", "might be overheated or any other thing that might make", "finding_max_rate, run_results=None, **kwargs): \"\"\" Function ran before each iteration. :parameters:", "rate. In this is the case, the run_results will be", "overheated or any other thing that might make you want", "of iteration (not necessarily a number) kwargs: dict List of", "line, through the kwargs argument. pass def post_iteration(self, finding_max_rate, run_results,", "DUT. # Could use this to decide if to continue", "a number) Pay attention: The rate is of the upcoming", "in bps. rate_rx_bps: RX rate in bps. tx_util: TX utilization", "rate_rx_bps: RX rate in bps. tx_util: TX utilization percentage. latency:", "want to stop the run. # You can receive tunables", "iteration. kwargs: dict List of tunables passed as parameters. \"\"\"", "in the command line, through the kwargs argument. should_stop =", "the run_results will be None. run_results: dict A dictionary that", "return should_stop # dynamic load of python module def register():", "pps. tx_bps: TX in bps. rx_bps: RX in bps. bw_per_core:", "percentage out of max. total_tx_L1: Total TX L1. total_rx_L1: Total", "bps. tx_util: TX utilization percentage. latency: Latency groups. cpu_util: CPU", "time, trying to find the max rate. In this is", "pps. rx_pps: RX in pps. tx_bps: TX in bps. rx_bps:", "through the kwargs argument. should_stop = False return should_stop #", "the rest are of the previous iteration. kwargs: dict List", "# dynamic load of python module def register(): return MyNDRPlugin()", "TX L1. total_rx_L1: Total RX L1. iteration: Description of iteration", "max. total_tx_L1: Total TX L1. total_rx_L1: Total RX L1. iteration:", "iteration (not necessarily a number) Pay attention: The rate is", "first time, trying to find the max rate. If this", "to the DUT. # Could use this to decide if", "finding_max_rate, run_results, **kwargs): \"\"\" Function ran after each iteration. :parameters:", "List of tunables passed as parameters. :returns: bool: should stop", "be None. run_results: dict A dictionary that contains the following", "finding_max_rate: boolean Indicates whether we are running for the first", "number) kwargs: dict List of tunables passed as parameters. :returns:", "dict List of tunables passed as parameters. \"\"\" # Pre", "function will run before TRex transmits to the DUT. #", "if to continue the benchmark after querying the DUT post", "can receive tunables in the command line, through the kwargs", "rate is of the upcoming iteration. All the rest are", "function. This function will run before TRex transmits to the", "the benchmarking or not. \"\"\" # Post iteration function. This", "max rate. In this is the case, the run_results will", "the first time, trying to find the max rate. If", "some values of run_results (like iteration for example) are not", "to find the max rate. If this is the case,", "packets that were dropped. rate_tx_bps: TX rate in bps. rate_rx_bps:", "transmits to the DUT. # Could use this to decide", "In this is the case, the run_results will be None.", "rx_bps: RX in bps. bw_per_core: Bandwidth per core. rate_p: Running", "a number) kwargs: dict List of tunables passed as parameters.", "parameters. :returns: bool: should stop the benchmarking or not. \"\"\"", "will be None. run_results: dict A dictionary that contains the", "rate in percentage out of max. total_tx_L1: Total TX L1.", "use this to better prepare the DUT, for example define", "values of run_results (like iteration for example) are not relevant.", "TX rate in bps. rate_rx_bps: RX rate in bps. tx_util:", "or not. \"\"\" # Post iteration function. This function will", "of the previous iteration. kwargs: dict List of tunables passed", "TX in pps. rx_pps: RX in pps. tx_bps: TX in", "of tunables passed as parameters. \"\"\" # Pre iteration function.", "should_stop # dynamic load of python module def register(): return", "function. This function will run after TRex transmits to the", "should stop the benchmarking or not. \"\"\" # Post iteration", "example) are not relevant. run_results: dict A dictionary that contains", "attention: The rate is of the upcoming iteration. All the", "thing that might make you want to stop the run.", "out of max. total_tx_L1: Total TX L1. total_rx_L1: Total RX", "that might make you want to stop the run. #", "contains the following keys: queue_full_percentage: Percentage of packets that are", "of packets that were dropped. rate_tx_bps: TX rate in bps.", "RX in pps. tx_bps: TX in bps. rx_bps: RX in", "other thing that might make you want to stop the", "drop_rate_percentage: Percentage of packets that were dropped. rate_tx_bps: TX rate", "that were dropped. rate_tx_bps: TX rate in bps. rate_rx_bps: RX", "run_results=None, **kwargs): \"\"\" Function ran before each iteration. :parameters: finding_max_rate:", "dropped. rate_tx_bps: TX rate in bps. rate_rx_bps: RX rate in", "TX utilization percentage. latency: Latency groups. cpu_util: CPU utilization percentage.", "use this to decide if to continue the benchmark after", "Running rate in percentage out of max. total_tx_L1: Total TX", "L1. total_rx_L1: Total RX L1. iteration: Description of iteration (not", "receive tunables in the command line, through the kwargs argument.", "iteration. :parameters: finding_max_rate: boolean Indicates whether we are running for", "MyNDRPlugin(): def __init__(self): pass def pre_iteration(self, finding_max_rate, run_results=None, **kwargs): \"\"\"", "# Could use this to decide if to continue the", "DUT post run. The DUT might be overheated or any", "ran before each iteration. :parameters: finding_max_rate: boolean Indicates whether we", "All the rest are of the previous iteration. kwargs: dict", "rate in bps. tx_util: TX utilization percentage. latency: Latency groups.", "example define shapers, policers, increase buffers and queues. # You", "trying to find the max rate. If this is the", "run before TRex transmits to the DUT. # Could use", "the following keys: queue_full_percentage: Percentage of packets that are queued.", "total_tx_L1: Total TX L1. total_rx_L1: Total RX L1. iteration: Description", "better prepare the DUT, for example define shapers, policers, increase", "bps. rx_bps: RX in bps. bw_per_core: Bandwidth per core. rate_p:", "# You can receive tunables in the command line, through", "**kwargs): \"\"\" Function ran before each iteration. :parameters: finding_max_rate: boolean", "def post_iteration(self, finding_max_rate, run_results, **kwargs): \"\"\" Function ran after each", "A dictionary that contains the following keys: queue_full_percentage: Percentage of", "benchmarking or not. \"\"\" # Post iteration function. This function", "define shapers, policers, increase buffers and queues. # You can", "find the max rate. In this is the case, the", "argument. pass def post_iteration(self, finding_max_rate, run_results, **kwargs): \"\"\" Function ran", "the run. # You can receive tunables in the command", "in bps. bw_per_core: Bandwidth per core. rate_p: Running rate in", "upcoming iteration. All the rest are of the previous iteration.", "def __init__(self): pass def pre_iteration(self, finding_max_rate, run_results=None, **kwargs): \"\"\" Function", "this is the case, some values of run_results (like iteration", "False return should_stop # dynamic load of python module def", "might make you want to stop the run. # You", "def pre_iteration(self, finding_max_rate, run_results=None, **kwargs): \"\"\" Function ran before each", "TX in bps. rx_bps: RX in bps. bw_per_core: Bandwidth per", "Total TX L1. total_rx_L1: Total RX L1. iteration: Description of", "Could use this to decide if to continue the benchmark", "queued. drop_rate_percentage: Percentage of packets that were dropped. rate_tx_bps: TX" ]
[ "use in the frontend, if any.\"\"\" return self._icon @property def", "timedelta import logging import voluptuous as vol from homeassistant.components.sensor import", "for condition in config[CONF_MONITORED_CONDITIONS]] add_devices(sensors, True) class EpsonPrinterCartridge(Entity): \"\"\"Representation of", "the sensor.\"\"\" return self._name @property def icon(self): \"\"\"Icon to use", "Black', '%', 'mdi:water'], 'magenta': ['Inklevel Magenta', '%', 'mdi:water'], 'cyan': ['Inklevel", "Printer.\"\"\" from datetime import timedelta import logging import voluptuous as", "Cleaning', '%', 'mdi:water'], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_MONITORED_CONDITIONS):", "= [EpsonPrinterCartridge(api, condition) for condition in config[CONF_MONITORED_CONDITIONS]] add_devices(sensors, True) class", "api self._id = cartridgeidx self._name = MONITORED_CONDITIONS[self._id][0] self._unit = MONITORED_CONDITIONS[self._id][1]", "the name of the sensor.\"\"\" return self._name @property def icon(self):", "@property def icon(self): \"\"\"Icon to use in the frontend, if", "return self._name @property def icon(self): \"\"\"Icon to use in the", "Cyan', '%', 'mdi:water'], 'yellow': ['Inklevel Yellow', '%', 'mdi:water'], 'clean': ['Inklevel", "@property def available(self): \"\"\"Could the device be accessed during the", "logging.getLogger(__name__) MONITORED_CONDITIONS = { 'black': ['Inklevel Black', '%', 'mdi:water'], 'magenta':", "import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA", "condition in config[CONF_MONITORED_CONDITIONS]] add_devices(sensors, True) class EpsonPrinterCartridge(Entity): \"\"\"Representation of a", "\"\"\"Return the name of the sensor.\"\"\" return self._name @property def", "homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_HOST, CONF_MONITORED_CONDITIONS from homeassistant.exceptions", "[vol.In(MONITORED_CONDITIONS)]), }) SCAN_INTERVAL = timedelta(minutes=60) def setup_platform(hass, config, add_devices, discovery_info=None):", "if any.\"\"\" return self._icon @property def unit_of_measurement(self): \"\"\"Return the unit", "cartridgeidx): \"\"\"Initialize a cartridge sensor.\"\"\" self._api = api self._id =", "discovery_info=None): \"\"\"Set up the cartridge sensor.\"\"\" host = config.get(CONF_HOST) from", "['Inklevel Cyan', '%', 'mdi:water'], 'yellow': ['Inklevel Yellow', '%', 'mdi:water'], 'clean':", "'%', 'mdi:water'], 'cyan': ['Inklevel Cyan', '%', 'mdi:water'], 'yellow': ['Inklevel Yellow',", "frontend, if any.\"\"\" return self._icon @property def unit_of_measurement(self): \"\"\"Return the", "config[CONF_MONITORED_CONDITIONS]] add_devices(sensors, True) class EpsonPrinterCartridge(Entity): \"\"\"Representation of a cartridge sensor.\"\"\"", "sensors = [EpsonPrinterCartridge(api, condition) for condition in config[CONF_MONITORED_CONDITIONS]] add_devices(sensors, True)", "for Epson Workforce Printer.\"\"\" from datetime import timedelta import logging", "class EpsonPrinterCartridge(Entity): \"\"\"Representation of a cartridge sensor.\"\"\" def __init__(self, api,", "api = EpsonPrinterAPI(host) if not api.available: raise PlatformNotReady() sensors =", "\"\"\"Return the state of the device.\"\"\" return self._api.getSensorValue(self._id) @property def", "return self._api.getSensorValue(self._id) @property def available(self): \"\"\"Could the device be accessed", "@property def name(self): \"\"\"Return the name of the sensor.\"\"\" return", "__init__(self, api, cartridgeidx): \"\"\"Initialize a cartridge sensor.\"\"\" self._api = api", "import timedelta import logging import voluptuous as vol from homeassistant.components.sensor", "PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_MONITORED_CONDITIONS): vol.All(cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]), }) SCAN_INTERVAL", "def setup_platform(hass, config, add_devices, discovery_info=None): \"\"\"Set up the cartridge sensor.\"\"\"", "config.get(CONF_HOST) from epsonprinter_pkg.epsonprinterapi import EpsonPrinterAPI api = EpsonPrinterAPI(host) if not", "= timedelta(minutes=60) def setup_platform(hass, config, add_devices, discovery_info=None): \"\"\"Set up the", "self._api = api self._id = cartridgeidx self._name = MONITORED_CONDITIONS[self._id][0] self._unit", "self._icon = MONITORED_CONDITIONS[self._id][2] @property def name(self): \"\"\"Return the name of", "homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import", "'mdi:water'], 'magenta': ['Inklevel Magenta', '%', 'mdi:water'], 'cyan': ['Inklevel Cyan', '%',", "vol.Required(CONF_MONITORED_CONDITIONS): vol.All(cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]), }) SCAN_INTERVAL = timedelta(minutes=60) def setup_platform(hass, config,", "the device be accessed during the last update call.\"\"\" return", "self._api.available def update(self): \"\"\"Get the latest data from the Epson", "\"\"\"Support for Epson Workforce Printer.\"\"\" from datetime import timedelta import", "\"\"\"Representation of a cartridge sensor.\"\"\" def __init__(self, api, cartridgeidx): \"\"\"Initialize", "accessed during the last update call.\"\"\" return self._api.available def update(self):", "self._api.getSensorValue(self._id) @property def available(self): \"\"\"Could the device be accessed during", "= config.get(CONF_HOST) from epsonprinter_pkg.epsonprinterapi import EpsonPrinterAPI api = EpsonPrinterAPI(host) if", "return self._api.available def update(self): \"\"\"Get the latest data from the", "Entity REQUIREMENTS = ['epsonprinter==0.0.8'] _LOGGER = logging.getLogger(__name__) MONITORED_CONDITIONS = {", "import Entity REQUIREMENTS = ['epsonprinter==0.0.8'] _LOGGER = logging.getLogger(__name__) MONITORED_CONDITIONS =", "value is expressed in.\"\"\" return self._unit @property def state(self): \"\"\"Return", "the device.\"\"\" return self._api.getSensorValue(self._id) @property def available(self): \"\"\"Could the device", "EpsonPrinterAPI api = EpsonPrinterAPI(host) if not api.available: raise PlatformNotReady() sensors", "'mdi:water'], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_MONITORED_CONDITIONS): vol.All(cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]),", "= api self._id = cartridgeidx self._name = MONITORED_CONDITIONS[self._id][0] self._unit =", "of the sensor.\"\"\" return self._name @property def icon(self): \"\"\"Icon to", "a cartridge sensor.\"\"\" def __init__(self, api, cartridgeidx): \"\"\"Initialize a cartridge", "Yellow', '%', 'mdi:water'], 'clean': ['Inklevel Cleaning', '%', 'mdi:water'], } PLATFORM_SCHEMA", "Epson Workforce Printer.\"\"\" from datetime import timedelta import logging import", "from datetime import timedelta import logging import voluptuous as vol", "def __init__(self, api, cartridgeidx): \"\"\"Initialize a cartridge sensor.\"\"\" self._api =", "\"\"\"Initialize a cartridge sensor.\"\"\" self._api = api self._id = cartridgeidx", "the cartridge sensor.\"\"\" host = config.get(CONF_HOST) from epsonprinter_pkg.epsonprinterapi import EpsonPrinterAPI", "'mdi:water'], 'cyan': ['Inklevel Cyan', '%', 'mdi:water'], 'yellow': ['Inklevel Yellow', '%',", "import PLATFORM_SCHEMA from homeassistant.const import CONF_HOST, CONF_MONITORED_CONDITIONS from homeassistant.exceptions import", "name(self): \"\"\"Return the name of the sensor.\"\"\" return self._name @property", "import CONF_HOST, CONF_MONITORED_CONDITIONS from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as", "'yellow': ['Inklevel Yellow', '%', 'mdi:water'], 'clean': ['Inklevel Cleaning', '%', 'mdi:water'],", "'black': ['Inklevel Black', '%', 'mdi:water'], 'magenta': ['Inklevel Magenta', '%', 'mdi:water'],", "= MONITORED_CONDITIONS[self._id][0] self._unit = MONITORED_CONDITIONS[self._id][1] self._icon = MONITORED_CONDITIONS[self._id][2] @property def", "unit_of_measurement(self): \"\"\"Return the unit the value is expressed in.\"\"\" return", "homeassistant.helpers.entity import Entity REQUIREMENTS = ['epsonprinter==0.0.8'] _LOGGER = logging.getLogger(__name__) MONITORED_CONDITIONS", "PlatformNotReady() sensors = [EpsonPrinterCartridge(api, condition) for condition in config[CONF_MONITORED_CONDITIONS]] add_devices(sensors,", "PlatformNotReady import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity REQUIREMENTS", "MONITORED_CONDITIONS[self._id][2] @property def name(self): \"\"\"Return the name of the sensor.\"\"\"", "to use in the frontend, if any.\"\"\" return self._icon @property", "add_devices(sensors, True) class EpsonPrinterCartridge(Entity): \"\"\"Representation of a cartridge sensor.\"\"\" def", "return self._unit @property def state(self): \"\"\"Return the state of the", "name of the sensor.\"\"\" return self._name @property def icon(self): \"\"\"Icon", "the last update call.\"\"\" return self._api.available def update(self): \"\"\"Get the", "'clean': ['Inklevel Cleaning', '%', 'mdi:water'], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST):", "call.\"\"\" return self._api.available def update(self): \"\"\"Get the latest data from", "PLATFORM_SCHEMA from homeassistant.const import CONF_HOST, CONF_MONITORED_CONDITIONS from homeassistant.exceptions import PlatformNotReady", "sensor.\"\"\" host = config.get(CONF_HOST) from epsonprinter_pkg.epsonprinterapi import EpsonPrinterAPI api =", "in config[CONF_MONITORED_CONDITIONS]] add_devices(sensors, True) class EpsonPrinterCartridge(Entity): \"\"\"Representation of a cartridge", "cv from homeassistant.helpers.entity import Entity REQUIREMENTS = ['epsonprinter==0.0.8'] _LOGGER =", "Magenta', '%', 'mdi:water'], 'cyan': ['Inklevel Cyan', '%', 'mdi:water'], 'yellow': ['Inklevel", "device be accessed during the last update call.\"\"\" return self._api.available", "= ['epsonprinter==0.0.8'] _LOGGER = logging.getLogger(__name__) MONITORED_CONDITIONS = { 'black': ['Inklevel", "setup_platform(hass, config, add_devices, discovery_info=None): \"\"\"Set up the cartridge sensor.\"\"\" host", "as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_HOST,", "epsonprinter_pkg.epsonprinterapi import EpsonPrinterAPI api = EpsonPrinterAPI(host) if not api.available: raise", "= MONITORED_CONDITIONS[self._id][2] @property def name(self): \"\"\"Return the name of the", "be accessed during the last update call.\"\"\" return self._api.available def", "from homeassistant.const import CONF_HOST, CONF_MONITORED_CONDITIONS from homeassistant.exceptions import PlatformNotReady import", "import EpsonPrinterAPI api = EpsonPrinterAPI(host) if not api.available: raise PlatformNotReady()", "raise PlatformNotReady() sensors = [EpsonPrinterCartridge(api, condition) for condition in config[CONF_MONITORED_CONDITIONS]]", "a cartridge sensor.\"\"\" self._api = api self._id = cartridgeidx self._name", "homeassistant.const import CONF_HOST, CONF_MONITORED_CONDITIONS from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation", "= MONITORED_CONDITIONS[self._id][1] self._icon = MONITORED_CONDITIONS[self._id][2] @property def name(self): \"\"\"Return the", "@property def unit_of_measurement(self): \"\"\"Return the unit the value is expressed", "'%', 'mdi:water'], 'yellow': ['Inklevel Yellow', '%', 'mdi:water'], 'clean': ['Inklevel Cleaning',", "cartridge sensor.\"\"\" def __init__(self, api, cartridgeidx): \"\"\"Initialize a cartridge sensor.\"\"\"", "self._name = MONITORED_CONDITIONS[self._id][0] self._unit = MONITORED_CONDITIONS[self._id][1] self._icon = MONITORED_CONDITIONS[self._id][2] @property", "def state(self): \"\"\"Return the state of the device.\"\"\" return self._api.getSensorValue(self._id)", "from epsonprinter_pkg.epsonprinterapi import EpsonPrinterAPI api = EpsonPrinterAPI(host) if not api.available:", "sensor.\"\"\" self._api = api self._id = cartridgeidx self._name = MONITORED_CONDITIONS[self._id][0]", "MONITORED_CONDITIONS[self._id][0] self._unit = MONITORED_CONDITIONS[self._id][1] self._icon = MONITORED_CONDITIONS[self._id][2] @property def name(self):", "is expressed in.\"\"\" return self._unit @property def state(self): \"\"\"Return the", "timedelta(minutes=60) def setup_platform(hass, config, add_devices, discovery_info=None): \"\"\"Set up the cartridge", "def icon(self): \"\"\"Icon to use in the frontend, if any.\"\"\"", "api, cartridgeidx): \"\"\"Initialize a cartridge sensor.\"\"\" self._api = api self._id", "api.available: raise PlatformNotReady() sensors = [EpsonPrinterCartridge(api, condition) for condition in", "EpsonPrinterAPI(host) if not api.available: raise PlatformNotReady() sensors = [EpsonPrinterCartridge(api, condition)", "self._id = cartridgeidx self._name = MONITORED_CONDITIONS[self._id][0] self._unit = MONITORED_CONDITIONS[self._id][1] self._icon", "['Inklevel Black', '%', 'mdi:water'], 'magenta': ['Inklevel Magenta', '%', 'mdi:water'], 'cyan':", "unit the value is expressed in.\"\"\" return self._unit @property def", "'mdi:water'], 'yellow': ['Inklevel Yellow', '%', 'mdi:water'], 'clean': ['Inklevel Cleaning', '%',", "cartridge sensor.\"\"\" host = config.get(CONF_HOST) from epsonprinter_pkg.epsonprinterapi import EpsonPrinterAPI api", "\"\"\"Return the unit the value is expressed in.\"\"\" return self._unit", "CONF_HOST, CONF_MONITORED_CONDITIONS from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv", "from homeassistant.helpers.entity import Entity REQUIREMENTS = ['epsonprinter==0.0.8'] _LOGGER = logging.getLogger(__name__)", "update call.\"\"\" return self._api.available def update(self): \"\"\"Get the latest data", "def update(self): \"\"\"Get the latest data from the Epson printer.\"\"\"", "'magenta': ['Inklevel Magenta', '%', 'mdi:water'], 'cyan': ['Inklevel Cyan', '%', 'mdi:water'],", "in the frontend, if any.\"\"\" return self._icon @property def unit_of_measurement(self):", "available(self): \"\"\"Could the device be accessed during the last update", "MONITORED_CONDITIONS = { 'black': ['Inklevel Black', '%', 'mdi:water'], 'magenta': ['Inklevel", "SCAN_INTERVAL = timedelta(minutes=60) def setup_platform(hass, config, add_devices, discovery_info=None): \"\"\"Set up", "True) class EpsonPrinterCartridge(Entity): \"\"\"Representation of a cartridge sensor.\"\"\" def __init__(self,", "logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from", "datetime import timedelta import logging import voluptuous as vol from", "update(self): \"\"\"Get the latest data from the Epson printer.\"\"\" self._api.update()", "icon(self): \"\"\"Icon to use in the frontend, if any.\"\"\" return", "= cartridgeidx self._name = MONITORED_CONDITIONS[self._id][0] self._unit = MONITORED_CONDITIONS[self._id][1] self._icon =", "vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_HOST, CONF_MONITORED_CONDITIONS", "import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const", "from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_HOST, CONF_MONITORED_CONDITIONS from", "['Inklevel Yellow', '%', 'mdi:water'], 'clean': ['Inklevel Cleaning', '%', 'mdi:water'], }", "config, add_devices, discovery_info=None): \"\"\"Set up the cartridge sensor.\"\"\" host =", "device.\"\"\" return self._api.getSensorValue(self._id) @property def available(self): \"\"\"Could the device be", "from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity", "'cyan': ['Inklevel Cyan', '%', 'mdi:water'], 'yellow': ['Inklevel Yellow', '%', 'mdi:water'],", "'%', 'mdi:water'], 'clean': ['Inklevel Cleaning', '%', 'mdi:water'], } PLATFORM_SCHEMA =", "if not api.available: raise PlatformNotReady() sensors = [EpsonPrinterCartridge(api, condition) for", "sensor.\"\"\" return self._name @property def icon(self): \"\"\"Icon to use in", "@property def state(self): \"\"\"Return the state of the device.\"\"\" return", "= logging.getLogger(__name__) MONITORED_CONDITIONS = { 'black': ['Inklevel Black', '%', 'mdi:water'],", "cv.string, vol.Required(CONF_MONITORED_CONDITIONS): vol.All(cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]), }) SCAN_INTERVAL = timedelta(minutes=60) def setup_platform(hass,", "= EpsonPrinterAPI(host) if not api.available: raise PlatformNotReady() sensors = [EpsonPrinterCartridge(api,", "'mdi:water'], 'clean': ['Inklevel Cleaning', '%', 'mdi:water'], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({", "PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_MONITORED_CONDITIONS): vol.All(cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]), }) SCAN_INTERVAL = timedelta(minutes=60)", "vol.Required(CONF_HOST): cv.string, vol.Required(CONF_MONITORED_CONDITIONS): vol.All(cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]), }) SCAN_INTERVAL = timedelta(minutes=60) def", "homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity REQUIREMENTS = ['epsonprinter==0.0.8']", "Workforce Printer.\"\"\" from datetime import timedelta import logging import voluptuous", "the frontend, if any.\"\"\" return self._icon @property def unit_of_measurement(self): \"\"\"Return", "during the last update call.\"\"\" return self._api.available def update(self): \"\"\"Get", "not api.available: raise PlatformNotReady() sensors = [EpsonPrinterCartridge(api, condition) for condition", "last update call.\"\"\" return self._api.available def update(self): \"\"\"Get the latest", "self._icon @property def unit_of_measurement(self): \"\"\"Return the unit the value is", "of a cartridge sensor.\"\"\" def __init__(self, api, cartridgeidx): \"\"\"Initialize a", "condition) for condition in config[CONF_MONITORED_CONDITIONS]] add_devices(sensors, True) class EpsonPrinterCartridge(Entity): \"\"\"Representation", "return self._icon @property def unit_of_measurement(self): \"\"\"Return the unit the value", "state(self): \"\"\"Return the state of the device.\"\"\" return self._api.getSensorValue(self._id) @property", "in.\"\"\" return self._unit @property def state(self): \"\"\"Return the state of", "of the device.\"\"\" return self._api.getSensorValue(self._id) @property def available(self): \"\"\"Could the", "def available(self): \"\"\"Could the device be accessed during the last", "the unit the value is expressed in.\"\"\" return self._unit @property", "def name(self): \"\"\"Return the name of the sensor.\"\"\" return self._name", "[EpsonPrinterCartridge(api, condition) for condition in config[CONF_MONITORED_CONDITIONS]] add_devices(sensors, True) class EpsonPrinterCartridge(Entity):", "sensor.\"\"\" def __init__(self, api, cartridgeidx): \"\"\"Initialize a cartridge sensor.\"\"\" self._api", "= { 'black': ['Inklevel Black', '%', 'mdi:water'], 'magenta': ['Inklevel Magenta',", "EpsonPrinterCartridge(Entity): \"\"\"Representation of a cartridge sensor.\"\"\" def __init__(self, api, cartridgeidx):", "up the cartridge sensor.\"\"\" host = config.get(CONF_HOST) from epsonprinter_pkg.epsonprinterapi import", "add_devices, discovery_info=None): \"\"\"Set up the cartridge sensor.\"\"\" host = config.get(CONF_HOST)", "_LOGGER = logging.getLogger(__name__) MONITORED_CONDITIONS = { 'black': ['Inklevel Black', '%',", "}) SCAN_INTERVAL = timedelta(minutes=60) def setup_platform(hass, config, add_devices, discovery_info=None): \"\"\"Set", "'%', 'mdi:water'], 'magenta': ['Inklevel Magenta', '%', 'mdi:water'], 'cyan': ['Inklevel Cyan',", "import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity REQUIREMENTS =", "self._name @property def icon(self): \"\"\"Icon to use in the frontend,", "\"\"\"Icon to use in the frontend, if any.\"\"\" return self._icon", "state of the device.\"\"\" return self._api.getSensorValue(self._id) @property def available(self): \"\"\"Could", "['Inklevel Magenta', '%', 'mdi:water'], 'cyan': ['Inklevel Cyan', '%', 'mdi:water'], 'yellow':", "} PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_MONITORED_CONDITIONS): vol.All(cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]), })", "= PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_MONITORED_CONDITIONS): vol.All(cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]), }) SCAN_INTERVAL =", "self._unit = MONITORED_CONDITIONS[self._id][1] self._icon = MONITORED_CONDITIONS[self._id][2] @property def name(self): \"\"\"Return", "\"\"\"Could the device be accessed during the last update call.\"\"\"", "self._unit @property def state(self): \"\"\"Return the state of the device.\"\"\"", "as cv from homeassistant.helpers.entity import Entity REQUIREMENTS = ['epsonprinter==0.0.8'] _LOGGER", "the value is expressed in.\"\"\" return self._unit @property def state(self):", "vol.All(cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]), }) SCAN_INTERVAL = timedelta(minutes=60) def setup_platform(hass, config, add_devices,", "CONF_MONITORED_CONDITIONS from homeassistant.exceptions import PlatformNotReady import homeassistant.helpers.config_validation as cv from", "any.\"\"\" return self._icon @property def unit_of_measurement(self): \"\"\"Return the unit the", "'%', 'mdi:water'], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_MONITORED_CONDITIONS): vol.All(cv.ensure_list,", "\"\"\"Set up the cartridge sensor.\"\"\" host = config.get(CONF_HOST) from epsonprinter_pkg.epsonprinterapi", "REQUIREMENTS = ['epsonprinter==0.0.8'] _LOGGER = logging.getLogger(__name__) MONITORED_CONDITIONS = { 'black':", "cartridge sensor.\"\"\" self._api = api self._id = cartridgeidx self._name =", "def unit_of_measurement(self): \"\"\"Return the unit the value is expressed in.\"\"\"", "['epsonprinter==0.0.8'] _LOGGER = logging.getLogger(__name__) MONITORED_CONDITIONS = { 'black': ['Inklevel Black',", "the state of the device.\"\"\" return self._api.getSensorValue(self._id) @property def available(self):", "{ 'black': ['Inklevel Black', '%', 'mdi:water'], 'magenta': ['Inklevel Magenta', '%',", "cartridgeidx self._name = MONITORED_CONDITIONS[self._id][0] self._unit = MONITORED_CONDITIONS[self._id][1] self._icon = MONITORED_CONDITIONS[self._id][2]", "MONITORED_CONDITIONS[self._id][1] self._icon = MONITORED_CONDITIONS[self._id][2] @property def name(self): \"\"\"Return the name", "expressed in.\"\"\" return self._unit @property def state(self): \"\"\"Return the state", "voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import", "import PlatformNotReady import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity", "host = config.get(CONF_HOST) from epsonprinter_pkg.epsonprinterapi import EpsonPrinterAPI api = EpsonPrinterAPI(host)", "['Inklevel Cleaning', '%', 'mdi:water'], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string," ]
[ "be made dormant.\" ) await self.unclaim_channel(channel) else: # Cancel the", "be dormant after the cooldown expires. if claimant_id in self.scheduler:", "def move_to_available(self) -> None: \"\"\"Make a channel available.\"\"\" log.trace(\"Making a", "else: idle_seconds = constants.HelpChannels.deleted_idle_minutes * 60 time_elapsed = await _channel.get_idle_time(channel)", "the extant task to make the channel dormant will first", "if await _caches.claimants.get(ctx.channel.id) == ctx.author.id: log.trace(f\"{ctx.author} is the help channel", "become dormant in {timeout} sec.\") self.scheduler.schedule_later(timeout, channel.id, self.move_idle_channel(channel)) _stats.report_counts() @commands.Cog.listener()", "claim your own help channel in the Python Help: Available", "close command. # In other cases, the task is either", "channel to turn into an available channel. If no channel", "automatically closed or False if manually closed. \"\"\" claimant_id =", "await _message.is_empty(channel): idle_seconds = constants.HelpChannels.idle_minutes * 60 else: idle_seconds =", "could be possible that there is no claimant cached. In", "* When a channel becomes available, the dormant embed will", "becomes available. \"\"\" log.trace(\"Getting an available channel candidate.\") try: channel", "\"message\", attrgetter(\"channel.id\")) @lock.lock_arg(NAMESPACE, \"message\", attrgetter(\"author.id\")) @lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"message\", attrgetter(\"author.id\"), wait=True) async", "role if the claimant has no other channels left await", "_stats.report_complete_session(channel.id, is_auto) await self.move_to_dormant(channel) # Cancel the task that makes", "the longest amount of time * If there are no", "_message.is_empty(msg.channel): return log.info(f\"Claimant of #{msg.channel} ({msg.author}) deleted message, channel is", "#{channel} ({channel.id}) finally retrieved from the queue.\") self.queue_tasks.remove(task) return channel", "the command is invoked and the cog is ready (e.g.", "!= self.in_use_category: log.debug(f\"{ctx.author} invoked command 'close' outside an in-use help", "the category. Return None if no more channel names are", "help channel system of the guild. The system is based", "refill the Available category Help channels are named after the", "\"\"\" Create and return a new channel in the Dormant", "* If there are no more dormant channels, the bot", "\"\"\"Get the help category objects. Remove the cog if retrieval", "will first be cancelled. \"\"\" log.trace(f\"Handling in-use channel #{channel} ({channel.id}).\")", "\"\"\" # Don't use a discord.py check because the check", "await _caches.claimants.items()): # Remove the cooldown role if the claimant", "available, # we should move the superfluous ones over to", "will be sent Dormant Category * Contains channels which aren't", "return queue async def create_dormant(self) -> t.Optional[discord.TextChannel]: \"\"\" Create and", "= self.bot.get_channel(constants.HelpChannels.notify_channel) last_notification = await _message.notify(notify_channel, self.last_notification) if last_notification: self.last_notification", "category with channels.\") channels = list(_channel.get_category_channels(self.available_category)) missing = constants.HelpChannels.max_available -", "asyncio.QueueEmpty: log.info(\"No candidate channels in the queue; creating a new", "log.trace(f\"{ctx.author} is the help channel claimant, passing the check for", "use a discord.py check because the check needs to fail", "None: \"\"\"Move an available channel to the In Use category", "delay = constants.HelpChannels.deleted_idle_minutes * 60 self.scheduler.schedule_later(delay, msg.channel.id, self.move_idle_channel(msg.channel)) async def", "is_auto) await self.move_to_dormant(channel) # Cancel the task that makes the", "either already done or not-existent. if not is_auto: self.scheduler.cancel(channel.id) async", "_stats.report_counts() log.info(\"Cog is ready!\") async def move_idle_channel(self, channel: discord.TextChannel, has_task:", "a new channel available. \"\"\" log.info(f\"Channel #{message.channel} was claimed by", "*, is_auto: bool = True) -> None: \"\"\" Unclaim an", "the queue.\") notify_channel = self.bot.get_channel(constants.HelpChannels.notify_channel) last_notification = await _message.notify(notify_channel, self.last_notification)", "made dormant.\" ) await self.unclaim_channel(channel) else: # Cancel the existing", "being idle * Command can prematurely mark a channel as", "because the check needs to fail silently. if await self.close_check(ctx):", "which have been dormant for the longest amount of time", "_message.notify(notify_channel, self.last_notification) if last_notification: self.last_notification = last_notification self.bot.stats.incr(\"help.out_of_channel_alerts\") channel =", "# Prevent the command from being used until ready. #", "not the help channel claimant, checking roles.\") has_role = await", "to the In Use category and pin the `message`. Add", "the channel queue.\") channels = list(_channel.get_category_channels(self.dormant_category)) random.shuffle(channels) log.trace(\"Populating the channel", "from being used until ready. # The ready event wasn't", "sync its permission overwrites with the category. Return None if", "add some. if missing > 0: log.trace(f\"Moving {missing} missing channels", "#{channel} ({channel.id}) to the Available category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_available,", "system is based on a 3-category system: Available Category *", "Return None if no more channel names are available. \"\"\"", "make a new channel available. \"\"\" log.info(f\"Channel #{message.channel} was claimed", "def get_available_candidate(self) -> discord.TextChannel: \"\"\" Return a dormant channel to", "self.scheduler.cancel(msg.channel.id) delay = constants.HelpChannels.deleted_idle_minutes * 60 self.scheduler.schedule_later(delay, msg.channel.id, self.move_idle_channel(msg.channel)) async", "dormant channels, the bot will automatically create a new one", "the channel was automatically closed or False if manually closed.", "init_cog(self) -> None: \"\"\"Initialise the help channel system.\"\"\" log.trace(\"Waiting for", "for the dormant task is configured with `HelpChannels.deleted_idle_minutes`. \"\"\" await", "to move, helpers will be notified (see `notify()`) * When", "log.info(f\"Moving #{channel} ({channel.id}) to the Dormant category.\") await _channel.move_to_bottom( channel=channel,", "its permission overwrites with the category. Return None if no", "if not channel_utils.is_in_category(msg.channel, constants.Categories.help_in_use): return if not await _message.is_empty(msg.channel): return", "\"\"\" claimant_id = await _caches.claimants.get(channel.id) _unclaim_channel = self._unclaim_channel # It", "documentation.\"\"\" await _caches.claimants.delete(channel.id) # Ignore missing tasks because a channel", "self.last_notification) if last_notification: self.last_notification = last_notification self.bot.stats.incr(\"help.out_of_channel_alerts\") channel = await", "def close_command(self, ctx: commands.Context) -> None: \"\"\" Make the current", "added to the queue in a random order. \"\"\" log.trace(\"Creating", "datetime to ensure a correct POSIX timestamp. timestamp = datetime.now(timezone.utc).timestamp()", "a new channel in the Dormant category. The new channel", "move, helpers will be notified (see `notify()`) * When a", "channel becomes available, the dormant embed will be edited to", "channels to the Available category.\") for _ in range(missing): await", "log.trace(f\"Handling in-use channel #{channel} ({channel.id}).\") if not await _message.is_empty(channel): idle_seconds", "= \"help\" HELP_CHANNEL_TOPIC = \"\"\" This is a Python help", "is ready!\") async def move_idle_channel(self, channel: discord.TextChannel, has_task: bool =", "#{channel} ({channel.id}) into the channel queue.\") self.channel_queue.put_nowait(channel) _stats.report_counts() @lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"channel\")", "self.dormant_category.create_text_channel(name, topic=HELP_CHANNEL_TOPIC) async def close_check(self, ctx: commands.Context) -> bool: \"\"\"Return", "role removal task. Set `is_auto` to True if the channel", "still be dormant after the cooldown expires. if claimant_id in", "When a channel becomes available, the dormant embed will be", "help channel. You can claim your own help channel in", "discord.Message) -> None: \"\"\" Reschedule an in-use channel to become", "await self.unclaim_channel(channel) else: # Cancel the existing task, if any.", "return await self.dormant_category.create_text_channel(name, topic=HELP_CHANNEL_TOPIC) async def close_check(self, ctx: commands.Context) ->", "help channel\") return False if await _caches.claimants.get(ctx.channel.id) == ctx.author.id: log.trace(f\"{ctx.author}", "async def unclaim_channel(self, channel: discord.TextChannel, *, is_auto: bool = True)", "claimed. Cancel the scheduled cooldown role removal task. Set `is_auto`", "ready!\") async def move_idle_channel(self, channel: discord.TextChannel, has_task: bool = True)", "it may indefinitely hold the lock while waiting for a", "system.\"\"\" log.trace(\"Waiting for the guild to be available before initialisation.\")", "decorator = lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"claimant_id\", wait=True) _unclaim_channel = decorator(_unclaim_channel) return await", "bots. await self.init_task if channel_utils.is_in_category(message.channel, constants.Categories.help_available): if not _channel.is_excluded_channel(message.channel): await", "self.init_categories() await _cooldown.check_cooldowns(self.scheduler) self.channel_queue = self.create_channel_queue() self.name_queue = _name.create_name_queue( self.available_category,", "with `HelpChannels.deleted_idle_minutes`. \"\"\" await self.init_task if not channel_utils.is_in_category(msg.channel, constants.Categories.help_in_use): return", "can prematurely mark a channel as dormant * Channel claimant", "of time * If there are no more dormant channels,", "into an available channel. If no channel is available, wait", "a new channel.\") channel = await self.create_dormant() if not channel:", "log.debug(\"No more names available for new dormant channels.\") return None", "potentially long delays for the cog to become ready. self.close_command.enabled", "import attrgetter import discord import discord.abc from discord.ext import commands", "the cooldown role if the claimant has no other channels", "commands.Context) -> bool: \"\"\"Return True if the channel is in", "the time # the command is invoked and the cog", "This is a Python help channel. You can claim your", "channel named {name}.\") return await self.dormant_category.create_text_channel(name, topic=HELP_CHANNEL_TOPIC) async def close_check(self,", "ready. self.close_command.enabled = True await self.init_available() _stats.report_counts() log.info(\"Cog is ready!\")", "This may confuse users. So would potentially long delays for", "claimant has no other channels left await _cooldown.remove_cooldown_role(claimant) await _message.unpin(channel)", "len(channels) # If we've got less than `max_available` channel available,", "self.available_category = await channel_utils.try_get_channel( constants.Categories.help_available ) self.in_use_category = await channel_utils.try_get_channel(", "channel is empty now. Rescheduling task.\") # Cancel existing dormant", "\"\"\"Initialise the Available category with channels.\"\"\" log.trace(\"Initialising the Available category", "Move the channel to the In Use category and pin", "self.move_to_in_use(message.channel) await _cooldown.revoke_send_permissions(message.author, self.scheduler) await _message.pin(message) try: await _message.dm_on_open(message) except", "passing the check for dormant.\") self.bot.stats.incr(\"help.dormant_invoke.claimant\") return True log.trace(f\"{ctx.author} is", "* Command can prematurely mark a channel as dormant *", "The new time for the dormant task is configured with", "self.scheduler = scheduling.Scheduler(self.__class__.__name__) # Categories self.available_category: discord.CategoryChannel = None self.in_use_category:", "async def move_idle_channel(self, channel: discord.TextChannel, has_task: bool = True) ->", "if the channel is in use and the user is", "Add user with channel for dormant check. await _caches.claimants.set(message.channel.id, message.author.id)", "a queue of dormant channels to use for getting the", "or has a whitelisted role.\"\"\" if ctx.channel.category != self.in_use_category: log.debug(f\"{ctx.author}", "a dormant channel.\") task = asyncio.create_task(self.channel_queue.get()) self.queue_tasks.append(task) channel = await", "_message.is_empty(channel): idle_seconds = constants.HelpChannels.idle_minutes * 60 else: idle_seconds = constants.HelpChannels.deleted_idle_minutes", "list(_channel.get_category_channels(self.available_category)) missing = constants.HelpChannels.max_available - len(channels) # If we've got", "try: await _message.dm_on_open(message) except Exception as e: log.warning(\"Error occurred while", "the channel is empty. The new time for the dormant", "HelpChannels(commands.Cog): \"\"\" Manage the help channel system of the guild.", "the `channel` dormant if idle or schedule the move if", "it to be made dormant.\"\"\" log.info(f\"Moving #{channel} ({channel.id}) to the", "the claimant's question message and move the channel to the", "claimant to prevent them from asking another question. Lastly, make", "for the cog to become ready. self.close_command.enabled = True await", "the Available category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_available, ) _stats.report_counts() async", "the cooldown role from the channel claimant if they have", "dormant sooner if the channel is empty. The new time", "# If we've got less than `max_available` channel available, we", "in range(missing): await self.move_to_available() # If for some reason we", "await _caches.claimants.get(channel.id) _unclaim_channel = self._unclaim_channel # It could be possible", "configured with `HelpChannels.deleted_idle_minutes`. \"\"\" await self.init_task if not channel_utils.is_in_category(msg.channel, constants.Categories.help_in_use):", "_channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_in_use, ) timeout = constants.HelpChannels.idle_minutes * 60 log.trace(f\"Scheduling", "the cog to become ready. self.close_command.enabled = True await self.init_available()", "last_notification = await _message.notify(notify_channel, self.last_notification) if last_notification: self.last_notification = last_notification", "= await channel_utils.try_get_channel( constants.Categories.help_dormant ) except discord.HTTPException: log.exception(\"Failed to get", "keep track of cooldowns, user which claimed a channel will", "Use category and pin the `message`. Add a cooldown to", "queue.\") notify_channel = self.bot.get_channel(constants.HelpChannels.notify_channel) last_notification = await _message.notify(notify_channel, self.last_notification) if", "None if no more channel names are available. \"\"\" log.trace(\"Getting", "with a dormant one.\"\"\" if message.author.bot: return # Ignore messages", "idle longer than {idle_seconds} seconds \" f\"and will be made", "ready event wasn't used because channels could change categories between", "create a candidate channel; waiting to get one from the", "after {delay} seconds.\" ) self.scheduler.schedule_later(delay, channel.id, self.move_idle_channel(channel)) async def move_to_available(self)", "-> t.Optional[discord.TextChannel]: \"\"\" Create and return a new channel in", "because it may indefinitely hold the lock while waiting for", "to refill the Available category Help channels are named after", "t.Optional[discord.TextChannel]: \"\"\" Create and return a new channel in the", "not channel: log.info(\"Couldn't create a candidate channel; waiting to get", "than `max_available` channels available, # we should move the superfluous", "it with a dormant one.\"\"\" if message.author.bot: return # Ignore", "more than `max_available` channels available, # we should move the", "To keep track of cooldowns, user which claimed a channel", "f\"#{channel} ({channel.id}) is idle longer than {idle_seconds} seconds \" f\"and", "channel claimant, checking roles.\") has_role = await commands.has_any_role(*constants.HelpChannels.cmd_whitelist).predicate(ctx) if has_role:", "unclaim_channel(self, channel: discord.TextChannel, *, is_auto: bool = True) -> None:", "`channel` dormant if idle or schedule the move if still", "dormant channels.\") return None log.debug(f\"Creating a new dormant channel named", "new dormant channel named {name}.\") return await self.dormant_category.create_text_channel(name, topic=HELP_CHANNEL_TOPIC) async", "question. Lastly, make a new channel available. \"\"\" log.info(f\"Channel #{message.channel}", "- len(channels) # If we've got less than `max_available` channel", "rescheduling is required, the extant task to make the channel", "dormant.\"\"\" log.info(f\"Moving #{channel} ({channel.id}) to the In Use category.\") await", "channels which have been dormant for the longest amount of", "new channel will sync its permission overwrites with the category.", "task. Set `is_auto` to True if the channel was automatically", "if claimant_id is not None: decorator = lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"claimant_id\", wait=True)", "-> discord.TextChannel: \"\"\" Return a dormant channel to turn into", "discord.CategoryChannel = None # Queues self.channel_queue: asyncio.Queue[discord.TextChannel] = None self.name_queue:", "the cooldown expires. if claimant_id in self.scheduler: self.scheduler.cancel(claimant_id) claimant =", "= _name.create_name_queue( self.available_category, self.in_use_category, self.dormant_category, ) log.trace(\"Moving or rescheduling in-use", "dormant will first be cancelled. \"\"\" log.trace(f\"Handling in-use channel #{channel}", "True log.trace(f\"{ctx.author} is not the help channel claimant, checking roles.\")", "range(missing): await self.move_to_available() # If for some reason we have", "an in-use help channel\") return False if await _caches.claimants.get(ctx.channel.id) ==", "discord.abc from discord.ext import commands from bot import constants from", "channel=channel, category_id=constants.Categories.help_in_use, ) timeout = constants.HelpChannels.idle_minutes * 60 log.trace(f\"Scheduling #{channel}", "list(_channel.get_category_channels(self.dormant_category)) random.shuffle(channels) log.trace(\"Populating the channel queue with channels.\") queue =", "= await task log.trace(f\"Channel #{channel} ({channel.id}) finally retrieved from the", "if move_idle_channel wasn't called yet). # This may confuse users.", "if the claimant has no other channels left await _cooldown.remove_cooldown_role(claimant)", "become dormant sooner if the channel is empty. The new", "may indefinitely hold the lock while waiting for a channel.", "confuse users. So would potentially long delays for the cog", "indefinitely hold the lock while waiting for a channel. scheduling.create_task(self.move_to_available(),", "self.bot.wait_until_guild_available() log.trace(\"Initialising the cog.\") await self.init_categories() await _cooldown.check_cooldowns(self.scheduler) self.channel_queue =", "while sending DM:\", exc_info=e) # Add user with channel for", "the Dormant category. Remove the cooldown role from the channel", "attrgetter(\"author.id\")) @lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"message\", attrgetter(\"author.id\"), wait=True) async def claim_channel(self, message: discord.Message)", "on a 3-category system: Available Category * Contains channels which", "= self.bot.get_guild(constants.Guild.id).get_member(claimant_id) if claimant is None: log.info(f\"{claimant_id} left the guild", "\"\"\" log.info(f\"Channel #{message.channel} was claimed by `{message.author.id}`.\") await self.move_to_in_use(message.channel) await", "other channels left await _cooldown.remove_cooldown_role(claimant) await _message.unpin(channel) await _stats.report_complete_session(channel.id, is_auto)", "Dormant category. The new channel will sync its permission overwrites", "bot.exts.help_channels import _caches, _channel, _cooldown, _message, _name, _stats from bot.utils", "can claim your own help channel in the Python Help:", "channel queue with channels.\") queue = asyncio.Queue() for channel in", "log.info(f\"Moving #{channel} ({channel.id}) to the In Use category.\") await _channel.move_to_bottom(", "def create_dormant(self) -> t.Optional[discord.TextChannel]: \"\"\" Create and return a new", "False if await _caches.claimants.get(ctx.channel.id) == ctx.author.id: log.trace(f\"{ctx.author} is the help", "Dormant category.\") for channel in channels[:abs(missing)]: await self.unclaim_channel(channel) async def", "which claimed a channel will have a temporary role In", "60 self.scheduler.schedule_later(delay, msg.channel.id, self.move_idle_channel(msg.channel)) async def wait_for_dormant_channel(self) -> discord.TextChannel: \"\"\"Wait", "overwrites with the category. Return None if no more channel", "if manually closed. \"\"\" claimant_id = await _caches.claimants.get(channel.id) _unclaim_channel =", "channels, the bot will automatically create a new one *", "name=f\"help_claim_{message.id}\") def create_channel_queue(self) -> asyncio.Queue: \"\"\" Return a queue of", "for _ in range(missing): await self.move_to_available() # If for some", "channels = list(_channel.get_category_channels(self.dormant_category)) random.shuffle(channels) log.trace(\"Populating the channel queue with channels.\")", "log.trace(f\"Moving {missing} missing channels to the Available category.\") for _", "constants.HelpChannels.idle_minutes * 60 else: idle_seconds = constants.HelpChannels.deleted_idle_minutes * 60 time_elapsed", "= None self.dormant_category: discord.CategoryChannel = None # Queues self.channel_queue: asyncio.Queue[discord.TextChannel]", "# Not awaited because it may indefinitely hold the lock", "_channel.get_idle_time(channel) if time_elapsed is None or time_elapsed >= idle_seconds: log.info(", "not any(claimant.id == user_id for _, user_id in await _caches.claimants.items()):", "from bot import constants from bot.bot import Bot from bot.exts.help_channels", "incorrect to lock on None. Therefore, the lock is applied", "= self._unclaim_channel # It could be possible that there is", "= await self.create_dormant() if not channel: log.info(\"Couldn't create a candidate", "def cog_unload(self) -> None: \"\"\"Cancel the init task and scheduled", "we should add some. if missing > 0: log.trace(f\"Moving {missing}", "self.channel_queue = self.create_channel_queue() self.name_queue = _name.create_name_queue( self.available_category, self.in_use_category, self.dormant_category, )", "the dormant embed will be edited to show `AVAILABLE_MSG` *", "({channel.id}) to the Dormant category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_dormant, )", "= asyncio.Queue() for channel in channels: queue.put_nowait(channel) return queue async", "current in-use help channel dormant. May only be invoked by", "await self.claim_channel(message) else: await _message.check_for_answer(message) @commands.Cog.listener() async def on_message_delete(self, msg:", "by someone needing help * Channel moves to dormant category", "\"message\", attrgetter(\"author.id\")) @lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"message\", attrgetter(\"author.id\"), wait=True) async def claim_channel(self, message:", "whitelisted role.\"\"\" if ctx.channel.category != self.in_use_category: log.debug(f\"{ctx.author} invoked command 'close'", "self.get_available_candidate() log.info(f\"Making #{channel} ({channel.id}) available.\") await _message.send_available_message(channel) log.trace(f\"Moving #{channel} ({channel.id})", "channel will have a temporary role In Use Category *", "({channel.id}).\") if not await _message.is_empty(channel): idle_seconds = constants.HelpChannels.idle_minutes * 60", "_caches, _channel, _cooldown, _message, _name, _stats from bot.utils import channel", "def move_idle_channel(self, channel: discord.TextChannel, has_task: bool = True) -> None:", "for #{channel} ({channel.id}).\") embed = discord.Embed(description=_message.DORMANT_MSG) await channel.send(embed=embed) log.trace(f\"Pushing #{channel}", "self.bot.get_channel(constants.HelpChannels.notify_channel) last_notification = await _message.notify(notify_channel, self.last_notification) if last_notification: self.last_notification =", "roles.\") has_role = await commands.has_any_role(*constants.HelpChannels.cmd_whitelist).predicate(ctx) if has_role: self.bot.stats.incr(\"help.dormant_invoke.staff\") return has_role", "= logging.getLogger(__name__) NAMESPACE = \"help\" HELP_CHANNEL_TOPIC = \"\"\" This is", "#{channel} ({channel.id}).\") if not await _message.is_empty(channel): idle_seconds = constants.HelpChannels.idle_minutes *", "available in the queue and return it.\"\"\" log.trace(\"Waiting for a", "already done or not-existent. if not is_auto: self.scheduler.cancel(channel.id) async def", "\"\"\" Manage the help channel system of the guild. The", "channel.id, self.move_idle_channel(channel)) async def move_to_available(self) -> None: \"\"\"Make a channel", "dormant task is configured with `HelpChannels.deleted_idle_minutes`. \"\"\" await self.init_task if", "* 60 time_elapsed = await _channel.get_idle_time(channel) if time_elapsed is None", "def move_to_dormant(self, channel: discord.TextChannel) -> None: \"\"\"Make the `channel` dormant.\"\"\"", "_unclaim_channel = decorator(_unclaim_channel) return await _unclaim_channel(channel, claimant_id, is_auto) async def", "tasks because a channel may still be dormant after the", "be removed\") elif not any(claimant.id == user_id for _, user_id", "timestamp = datetime.now(timezone.utc).timestamp() await _caches.claim_times.set(message.channel.id, timestamp) await _caches.unanswered.set(message.channel.id, True) #", "an available channel. If no channel is available, wait indefinitely", "to the Dormant category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_dormant, ) log.trace(f\"Sending", "applied conditionally. if claimant_id is not None: decorator = lock.lock_arg(f\"{NAMESPACE}.unclaim\",", "candidate.\") try: channel = self.channel_queue.get_nowait() except asyncio.QueueEmpty: log.info(\"No candidate channels", "await _cooldown.remove_cooldown_role(claimant) await _message.unpin(channel) await _stats.report_complete_session(channel.id, is_auto) await self.move_to_dormant(channel) #", "channel system.\"\"\" log.trace(\"Waiting for the guild to be available before", "deleted message, channel is empty now. Rescheduling task.\") # Cancel", "# The ready event wasn't used because channels could change", "dormant task before scheduling new. self.scheduler.cancel(msg.channel.id) delay = constants.HelpChannels.deleted_idle_minutes *", "scheduled cooldown role removal task. Set `is_auto` to True if", "log.trace(\"Creating the channel queue.\") channels = list(_channel.get_category_channels(self.dormant_category)) random.shuffle(channels) log.trace(\"Populating the", "queue and return it.\"\"\" log.trace(\"Waiting for a dormant channel.\") task", "and scheduled tasks when the cog unloads.\"\"\" log.trace(\"Cog unload: cancelling", "({channel.id}) is still active; \" f\"scheduling it to be moved", "Therefore, the lock is applied conditionally. if claimant_id is not", "channel available, we should add some. if missing > 0:", "available. \"\"\" log.trace(\"Getting an available channel candidate.\") try: channel =", "None: \"\"\"Initialise the help channel system.\"\"\" log.trace(\"Waiting for the guild", "someone who needs help * Will always contain `constants.HelpChannels.max_available` channels;", "constants.Categories.help_dormant ) except discord.HTTPException: log.exception(\"Failed to get a category; cog", "a channel becomes dormant, an embed with `DORMANT_MSG` will be", "\"\"\" def __init__(self, bot: Bot): self.bot = bot self.scheduler =", "channel in the Python Help: Available category. \"\"\" class HelpChannels(commands.Cog):", "await commands.has_any_role(*constants.HelpChannels.cmd_whitelist).predicate(ctx) if has_role: self.bot.stats.incr(\"help.dormant_invoke.staff\") return has_role @commands.command(name=\"close\", aliases=[\"dormant\", \"solved\"],", "claimant is allowed to use the command * Allowed roles", "-> None: \"\"\" Make the `channel` dormant if idle or", "None self.last_notification: t.Optional[datetime] = None # Asyncio stuff self.queue_tasks: t.List[asyncio.Task]", "exc_info=e) # Add user with channel for dormant check. await", "None: \"\"\" Claim the channel in which the question `message`", ") except discord.HTTPException: log.exception(\"Failed to get a category; cog will", "bot.bot import Bot from bot.exts.help_channels import _caches, _channel, _cooldown, _message,", "Unpin the claimant's question message and move the channel to", "async def close_check(self, ctx: commands.Context) -> bool: \"\"\"Return True if", "import constants from bot.bot import Bot from bot.exts.help_channels import _caches,", "the Dormant category.\") for channel in channels[:abs(missing)]: await self.unclaim_channel(channel) async", "are occupied by someone needing help * Channel moves to", "the claimant to prevent them from asking another question. Lastly,", "discord.TextChannel, *, is_auto: bool = True) -> None: \"\"\" Unclaim", "notified (see `notify()`) * When a channel becomes available, the", "self.init_task if channel_utils.is_in_category(message.channel, constants.Categories.help_available): if not _channel.is_excluded_channel(message.channel): await self.claim_channel(message) else:", "f\"#{channel} ({channel.id}) is still active; \" f\"scheduling it to be", "\"solved\"], enabled=False) async def close_command(self, ctx: commands.Context) -> None: \"\"\"", "in #{ctx.channel}.\") await self.unclaim_channel(ctx.channel, is_auto=False) async def get_available_candidate(self) -> discord.TextChannel:", "channels are added to the queue in a random order.", "time_elapsed >= idle_seconds: log.info( f\"#{channel} ({channel.id}) is idle longer than", "by the close command. # In other cases, the task", "* Channels are used to refill the Available category Help", "seconds.\" ) self.scheduler.schedule_later(delay, channel.id, self.move_idle_channel(channel)) async def move_to_available(self) -> None:", "* Channel claimant is allowed to use the command *", "ctx: commands.Context) -> bool: \"\"\"Return True if the channel is", "datetime import datetime, timezone from operator import attrgetter import discord", "\"\"\" Make the current in-use help channel dormant. May only", "sent Dormant Category * Contains channels which aren't in use", "log.trace(f\"Channel #{channel} ({channel.id}) finally retrieved from the queue.\") self.queue_tasks.remove(task) return", "\"\"\"Cancel the init task and scheduled tasks when the cog", "no channel is available, wait indefinitely until one becomes available.", "missing > 0: log.trace(f\"Moving {missing} missing channels to the Available", "channels.\") channels = list(_channel.get_category_channels(self.available_category)) missing = constants.HelpChannels.max_available - len(channels) #", "self.available_category, self.in_use_category, self.dormant_category, ) log.trace(\"Moving or rescheduling in-use channels.\") for", "self.bot.stats.incr(\"help.dormant_invoke.staff\") return has_role @commands.command(name=\"close\", aliases=[\"dormant\", \"solved\"], enabled=False) async def close_command(self,", "it dormant. Unpin the claimant's question message and move the", "is invoked and the cog is ready (e.g. if move_idle_channel", "channel.send(embed=embed) log.trace(f\"Pushing #{channel} ({channel.id}) into the channel queue.\") self.channel_queue.put_nowait(channel) _stats.report_counts()", "channel in channels: queue.put_nowait(channel) return queue async def create_dormant(self) ->", "\"claimant_id\", wait=True) _unclaim_channel = decorator(_unclaim_channel) return await _unclaim_channel(channel, claimant_id, is_auto)", "a new one * If there are no dormant channels", "async def get_available_candidate(self) -> discord.TextChannel: \"\"\" Return a dormant channel", "are named after the chemical elements in `bot/resources/elements.json`. \"\"\" def", "rescheduling in-use channels.\") for channel in _channel.get_category_channels(self.in_use_category): await self.move_idle_channel(channel, has_task=False)", "waiting for a channel. scheduling.create_task(self.move_to_available(), name=f\"help_claim_{message.id}\") def create_channel_queue(self) -> asyncio.Queue:", "unload: cancelling the init_cog task\") self.init_task.cancel() log.trace(\"Cog unload: cancelling the", "the task that makes the channel dormant only if called", "f\"and will be made dormant.\" ) await self.unclaim_channel(channel) else: #", "the cog is ready (e.g. if move_idle_channel wasn't called yet).", "0: log.trace(f\"Moving {missing} missing channels to the Available category.\") for", "discord.Message) -> None: \"\"\" Claim the channel in which the", "a channel. scheduling.create_task(self.move_to_available(), name=f\"help_claim_{message.id}\") def create_channel_queue(self) -> asyncio.Queue: \"\"\" Return", ") self.scheduler.schedule_later(delay, channel.id, self.move_idle_channel(channel)) async def move_to_available(self) -> None: \"\"\"Make", "= datetime.now(timezone.utc).timestamp() await _caches.claim_times.set(message.channel.id, timestamp) await _caches.unanswered.set(message.channel.id, True) # Not", "schedule it to be made dormant.\"\"\" log.info(f\"Moving #{channel} ({channel.id}) to", "constants.HelpChannels.deleted_idle_minutes * 60 self.scheduler.schedule_later(delay, msg.channel.id, self.move_idle_channel(msg.channel)) async def wait_for_dormant_channel(self) ->", "commands from bot import constants from bot.bot import Bot from", "operator import attrgetter import discord import discord.abc from discord.ext import", "someone needing help * Channel moves to dormant category after", "* 60 self.scheduler.schedule_later(delay, msg.channel.id, self.move_idle_channel(msg.channel)) async def wait_for_dormant_channel(self) -> discord.TextChannel:", "available.\"\"\" log.trace(\"Making a channel available.\") channel = await self.get_available_candidate() log.info(f\"Making", "for full documentation.\"\"\" await _caches.claimants.delete(channel.id) # Ignore missing tasks because", "timestamp. timestamp = datetime.now(timezone.utc).timestamp() await _caches.claim_times.set(message.channel.id, timestamp) await _caches.unanswered.set(message.channel.id, True)", "who needs help * Will always contain `constants.HelpChannels.max_available` channels; refilled", "log.info( f\"#{channel} ({channel.id}) is still active; \" f\"scheduling it to", "is None or time_elapsed >= idle_seconds: log.info( f\"#{channel} ({channel.id}) is", "await _message.send_available_message(channel) log.trace(f\"Moving #{channel} ({channel.id}) to the Available category.\") await", "channel: discord.TextChannel, claimant_id: int, is_auto: bool) -> None: \"\"\"Actual implementation", "ctx: commands.Context) -> None: \"\"\" Make the current in-use help", "after the cooldown expires. if claimant_id in self.scheduler: self.scheduler.cancel(claimant_id) claimant", "help category objects. Remove the cog if retrieval fails.\"\"\" log.trace(\"Getting", "\"\"\"Wait for a dormant channel to become available in the", "the help channel claimant, checking roles.\") has_role = await commands.has_any_role(*constants.HelpChannels.cmd_whitelist).predicate(ctx)", "dormant * Channel claimant is allowed to use the command", "self.name_queue: t.Deque[str] = None self.last_notification: t.Optional[datetime] = None # Asyncio", "try: self.available_category = await channel_utils.try_get_channel( constants.Categories.help_available ) self.in_use_category = await", "In Use Category * Contains all channels which are occupied", "be possible that there is no claimant cached. In such", "_channel.is_excluded_channel(message.channel): await self.claim_channel(message) else: await _message.check_for_answer(message) @commands.Cog.listener() async def on_message_delete(self,", "during their help session; the cooldown role won't be removed\")", "a name for a new dormant channel.\") try: name =", "channel queue.\") self.channel_queue.put_nowait(channel) _stats.report_counts() @lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"channel\") async def unclaim_channel(self, channel:", "`has_task` is True and rescheduling is required, the extant task", "idle or schedule the move if still active. If `has_task`", "Claim the channel in which the question `message` was sent.", "become ready. self.close_command.enabled = True await self.init_available() _stats.report_counts() log.info(\"Cog is", "the channels which have been dormant for the longest amount", "channel becomes dormant, an embed with `DORMANT_MSG` will be sent", "If we've got less than `max_available` channel available, we should", "claim_channel(self, message: discord.Message) -> None: \"\"\" Claim the channel in", "`is_auto` to True if the channel was automatically closed or", "* Contains all channels which are occupied by someone needing", "if any. if has_task: self.scheduler.cancel(channel.id) delay = idle_seconds - time_elapsed", "\"help\" HELP_CHANNEL_TOPIC = \"\"\" This is a Python help channel.", "the current in-use help channel dormant. May only be invoked", "all channels which are occupied by someone needing help *", "#{message.channel} was claimed by `{message.author.id}`.\") await self.move_to_in_use(message.channel) await _cooldown.revoke_send_permissions(message.author, self.scheduler)", "__init__(self, bot: Bot): self.bot = bot self.scheduler = scheduling.Scheduler(self.__class__.__name__) #", "occupied by someone who needs help * Will always contain", "channel. You can claim your own help channel in the", "topic=HELP_CHANNEL_TOPIC) async def close_check(self, ctx: commands.Context) -> bool: \"\"\"Return True", "bool = True) -> None: \"\"\" Make the `channel` dormant", "self.scheduler.cancel(claimant_id) claimant = self.bot.get_guild(constants.Guild.id).get_member(claimant_id) if claimant is None: log.info(f\"{claimant_id} left", "message and move the channel to the Dormant category. Remove", "the help channel claimant, passing the check for dormant.\") self.bot.stats.incr(\"help.dormant_invoke.claimant\")", "for the command are configurable with `constants.HelpChannels.cmd_whitelist` * When a", "cooldown expires. if claimant_id in self.scheduler: self.scheduler.cancel(claimant_id) claimant = self.bot.get_guild(constants.Guild.id).get_member(claimant_id)", "{abs(missing)} superfluous available channels over to the Dormant category.\") for", "self.scheduler.schedule_later(timeout, channel.id, self.move_idle_channel(channel)) _stats.report_counts() @commands.Cog.listener() async def on_message(self, message: discord.Message)", "create_channel_queue(self) -> asyncio.Queue: \"\"\" Return a queue of dormant channels", "the cog.\") await self.init_categories() await _cooldown.check_cooldowns(self.scheduler) self.channel_queue = self.create_channel_queue() self.name_queue", "try: channel = self.channel_queue.get_nowait() except asyncio.QueueEmpty: log.info(\"No candidate channels in", "get one from the queue.\") notify_channel = self.bot.get_channel(constants.HelpChannels.notify_channel) last_notification =", "def init_available(self) -> None: \"\"\"Initialise the Available category with channels.\"\"\"", "attrgetter import discord import discord.abc from discord.ext import commands from", "to become dormant sooner if the channel is empty. The", "new. self.scheduler.cancel(msg.channel.id) delay = constants.HelpChannels.deleted_idle_minutes * 60 self.scheduler.schedule_later(delay, msg.channel.id, self.move_idle_channel(msg.channel))", "if they have no other channels claimed. Cancel the scheduled", "make the channel dormant will first be cancelled. \"\"\" log.trace(f\"Handling", "if called by the close command. # In other cases,", "if no more channel names are available. \"\"\" log.trace(\"Getting a", "while waiting for a channel. scheduling.create_task(self.move_to_available(), name=f\"help_claim_{message.id}\") def create_channel_queue(self) ->", "await self.get_available_candidate() log.info(f\"Making #{channel} ({channel.id}) available.\") await _message.send_available_message(channel) log.trace(f\"Moving #{channel}", "\"channel\") async def unclaim_channel(self, channel: discord.TextChannel, *, is_auto: bool =", "None: \"\"\" Make the current in-use help channel dormant. May", "candidate channel; waiting to get one from the queue.\") notify_channel", "# If for some reason we have more than `max_available`", "if not _channel.is_excluded_channel(message.channel): await self.claim_channel(message) else: await _message.check_for_answer(message) @commands.Cog.listener() async", "t.Deque[str] = None self.last_notification: t.Optional[datetime] = None # Asyncio stuff", "or time_elapsed >= idle_seconds: log.info( f\"#{channel} ({channel.id}) is idle longer", "use the command * Allowed roles for the command are", "Make the current in-use help channel dormant. May only be", "Category * Contains channels which aren't in use * Channels", "no claimant cached. In such case, it'd be useless and", "ready (e.g. if move_idle_channel wasn't called yet). # This may", "by someone who needs help * Will always contain `constants.HelpChannels.max_available`", "we've got less than `max_available` channel available, we should add", "useless and # possibly incorrect to lock on None. Therefore,", "Add a cooldown to the claimant to prevent them from", "channel for dormant check. await _caches.claimants.set(message.channel.id, message.author.id) self.bot.stats.incr(\"help.claimed\") # Must", "configurable with `constants.HelpChannels.cmd_whitelist` * When a channel becomes dormant, an", "a channel may still be dormant after the cooldown expires.", "dormant. May only be invoked by the channel's claimant or", "will be made dormant.\" ) await self.unclaim_channel(channel) else: # Cancel", "task log.trace(f\"Channel #{channel} ({channel.id}) finally retrieved from the queue.\") self.queue_tasks.remove(task)", "and move the channel to the Dormant category. Remove the", "Dormant category. Remove the cooldown role from the channel claimant", "correct POSIX timestamp. timestamp = datetime.now(timezone.utc).timestamp() await _caches.claim_times.set(message.channel.id, timestamp) await", "have no other channels claimed. Cancel the scheduled cooldown role", "t.List[asyncio.Task] = [] self.init_task = self.bot.loop.create_task(self.init_cog()) def cog_unload(self) -> None:", "task is either already done or not-existent. if not is_auto:", "in use and the user is the claimant or has", "extant task to make the channel dormant will first be", "channel's claimant or by staff. \"\"\" # Don't use a", "@commands.command(name=\"close\", aliases=[\"dormant\", \"solved\"], enabled=False) async def close_command(self, ctx: commands.Context) ->", "cog to become ready. self.close_command.enabled = True await self.init_available() _stats.report_counts()", "new channel in the Dormant category. The new channel will", "available channel to the In Use category and replace it", "await _message.is_empty(msg.channel): return log.info(f\"Claimant of #{msg.channel} ({msg.author}) deleted message, channel", "self.bot.stats.incr(\"help.out_of_channel_alerts\") channel = await self.wait_for_dormant_channel() return channel async def init_available(self)", "\"\"\"Make a channel in-use and schedule it to be made", "named {name}.\") return await self.dormant_category.create_text_channel(name, topic=HELP_CHANNEL_TOPIC) async def close_check(self, ctx:", "to dormant. elif missing < 0: log.trace(f\"Moving {abs(missing)} superfluous available", "is None: log.info(f\"{claimant_id} left the guild during their help session;", "in `bot/resources/elements.json`. \"\"\" def __init__(self, bot: Bot): self.bot = bot", "* 60 else: idle_seconds = constants.HelpChannels.deleted_idle_minutes * 60 time_elapsed =", "roles for the command are configurable with `constants.HelpChannels.cmd_whitelist` * When", "await self.move_idle_channel(channel, has_task=False) # Prevent the command from being used", "and # possibly incorrect to lock on None. Therefore, the", "channel as dormant * Channel claimant is allowed to use", "channel=channel, category_id=constants.Categories.help_dormant, ) log.trace(f\"Sending dormant message for #{channel} ({channel.id}).\") embed", "use and the user is the claimant or has a", "discord import discord.abc from discord.ext import commands from bot import", "the queue in a random order. \"\"\" log.trace(\"Creating the channel", "candidate channels in the queue; creating a new channel.\") channel", "channel.\") task = asyncio.create_task(self.channel_queue.get()) self.queue_tasks.append(task) channel = await task log.trace(f\"Channel", "the close command. # In other cases, the task is", "to the Available category.\") for _ in range(missing): await self.move_to_available()", "Don't use a discord.py check because the check needs to", "channel_utils.try_get_channel( constants.Categories.help_dormant ) except discord.HTTPException: log.exception(\"Failed to get a category;", "dormant channels * Prioritise using the channels which have been", "#{channel} ({channel.id}) to the In Use category.\") await _channel.move_to_bottom( channel=channel,", "task = asyncio.create_task(self.channel_queue.get()) self.queue_tasks.append(task) channel = await task log.trace(f\"Channel #{channel}", "dormant channel.\") try: name = self.name_queue.popleft() except IndexError: log.debug(\"No more", "for dormant.\") self.bot.stats.incr(\"help.dormant_invoke.claimant\") return True log.trace(f\"{ctx.author} is not the help", "closed or False if manually closed. \"\"\" claimant_id = await", "before scheduling new. self.scheduler.cancel(msg.channel.id) delay = constants.HelpChannels.deleted_idle_minutes * 60 self.scheduler.schedule_later(delay,", "the guild. The system is based on a 3-category system:", "-> None: \"\"\" Reschedule an in-use channel to become dormant", "replace it with a dormant one.\"\"\" if message.author.bot: return #", "a cooldown to the claimant to prevent them from asking", "to use the command * Allowed roles for the command", "waiting to get one from the queue.\") notify_channel = self.bot.get_channel(constants.HelpChannels.notify_channel)", "objects. Remove the cog if retrieval fails.\"\"\" log.trace(\"Getting the CategoryChannel", "or schedule the move if still active. If `has_task` is", "0: log.trace(f\"Moving {abs(missing)} superfluous available channels over to the Dormant", "discord.TextChannel, claimant_id: int, is_auto: bool) -> None: \"\"\"Actual implementation of", "available channel. If no channel is available, wait indefinitely until", "await self.init_task if channel_utils.is_in_category(message.channel, constants.Categories.help_available): if not _channel.is_excluded_channel(message.channel): await self.claim_channel(message)", "log.trace(\"Initialising the cog.\") await self.init_categories() await _cooldown.check_cooldowns(self.scheduler) self.channel_queue = self.create_channel_queue()", "the existing task, if any. if has_task: self.scheduler.cancel(channel.id) delay =", "when the cog unloads.\"\"\" log.trace(\"Cog unload: cancelling the init_cog task\")", "an interval `constants.HelpChannels.claim_minutes` * To keep track of cooldowns, user", "the channel dormant only if called by the close command.", "until ready. # The ready event wasn't used because channels", "to the Dormant category. Remove the cooldown role from the", "has_task: bool = True) -> None: \"\"\" Make the `channel`", "# possibly incorrect to lock on None. Therefore, the lock", "ready to be occupied by someone who needs help *", "channels which are ready to be occupied by someone who", "`notify()`) * When a channel becomes available, the dormant embed", "of dormant channels to use for getting the next available", "may still be dormant after the cooldown expires. if claimant_id", "timezone-aware datetime to ensure a correct POSIX timestamp. timestamp =", "self.unclaim_channel(channel) else: # Cancel the existing task, if any. if", "* User can only claim a channel at an interval", "msg.channel.id, self.move_idle_channel(msg.channel)) async def wait_for_dormant_channel(self) -> discord.TextChannel: \"\"\"Wait for a", "name for a new dormant channel.\") try: name = self.name_queue.popleft()", "@lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"message\", attrgetter(\"author.id\"), wait=True) async def claim_channel(self, message: discord.Message) ->", "init_cog task\") self.init_task.cancel() log.trace(\"Cog unload: cancelling the channel queue tasks\")", "Use category and replace it with a dormant one.\"\"\" if", "log.trace(\"Getting an available channel candidate.\") try: channel = self.channel_queue.get_nowait() except", "if not is_auto: self.scheduler.cancel(channel.id) async def move_to_in_use(self, channel: discord.TextChannel) ->", "None: \"\"\" Unclaim an in-use help `channel` to make it", "the `message`. Add a cooldown to the claimant to prevent", "#{channel} ({channel.id}) to the Dormant category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_dormant,", "if last_notification: self.last_notification = last_notification self.bot.stats.incr(\"help.out_of_channel_alerts\") channel = await self.wait_for_dormant_channel()", "task and scheduled tasks when the cog unloads.\"\"\" log.trace(\"Cog unload:", "can only claim a channel at an interval `constants.HelpChannels.claim_minutes` *", "chemical elements in `bot/resources/elements.json`. \"\"\" def __init__(self, bot: Bot): self.bot", "In such case, it'd be useless and # possibly incorrect", "the check for dormant.\") self.bot.stats.incr(\"help.dormant_invoke.claimant\") return True log.trace(f\"{ctx.author} is not", "check needs to fail silently. if await self.close_check(ctx): log.info(f\"Close command", "the Available category.\") for _ in range(missing): await self.move_to_available() #", "await self.init_task if not channel_utils.is_in_category(msg.channel, constants.Categories.help_in_use): return if not await", "outside an in-use help channel\") return False if await _caches.claimants.get(ctx.channel.id)", "t from datetime import datetime, timezone from operator import attrgetter", "* Allowed roles for the command are configurable with `constants.HelpChannels.cmd_whitelist`", "wasn't used because channels could change categories between the time", "return True log.trace(f\"{ctx.author} is not the help channel claimant, checking", "60 log.trace(f\"Scheduling #{channel} ({channel.id}) to become dormant in {timeout} sec.\")", "self.channel_queue: asyncio.Queue[discord.TextChannel] = None self.name_queue: t.Deque[str] = None self.last_notification: t.Optional[datetime]", "command from being used until ready. # The ready event", "available. \"\"\" log.info(f\"Channel #{message.channel} was claimed by `{message.author.id}`.\") await self.move_to_in_use(message.channel)", "POSIX timestamp. timestamp = datetime.now(timezone.utc).timestamp() await _caches.claim_times.set(message.channel.id, timestamp) await _caches.unanswered.set(message.channel.id,", "When a channel becomes dormant, an embed with `DORMANT_MSG` will", "embed with `DORMANT_MSG` will be sent Dormant Category * Contains", "import logging import random import typing as t from datetime", "the command are configurable with `constants.HelpChannels.cmd_whitelist` * When a channel", "not _channel.is_excluded_channel(message.channel): await self.claim_channel(message) else: await _message.check_for_answer(message) @commands.Cog.listener() async def", "channel: log.info(\"Couldn't create a candidate channel; waiting to get one", "missing < 0: log.trace(f\"Moving {abs(missing)} superfluous available channels over to", "* Will always contain `constants.HelpChannels.max_available` channels; refilled automatically from the", "hold the lock while waiting for a channel. scheduling.create_task(self.move_to_available(), name=f\"help_claim_{message.id}\")", "sent by bots. await self.init_task if channel_utils.is_in_category(message.channel, constants.Categories.help_available): if not", "no more dormant channels, the bot will automatically create a", "= self.bot.loop.create_task(self.init_cog()) def cog_unload(self) -> None: \"\"\"Cancel the init task", "over to dormant. elif missing < 0: log.trace(f\"Moving {abs(missing)} superfluous", "Categories self.available_category: discord.CategoryChannel = None self.in_use_category: discord.CategoryChannel = None self.dormant_category:", "guild during their help session; the cooldown role won't be", "HELP_CHANNEL_TOPIC = \"\"\" This is a Python help channel. You", "idle_seconds - time_elapsed log.info( f\"#{channel} ({channel.id}) is still active; \"", "task in self.queue_tasks: task.cancel() self.scheduler.cancel_all() @lock.lock_arg(NAMESPACE, \"message\", attrgetter(\"channel.id\")) @lock.lock_arg(NAMESPACE, \"message\",", "an in-use help `channel` to make it dormant. Unpin the", "Asyncio stuff self.queue_tasks: t.List[asyncio.Task] = [] self.init_task = self.bot.loop.create_task(self.init_cog()) def", "a whitelisted role.\"\"\" if ctx.channel.category != self.in_use_category: log.debug(f\"{ctx.author} invoked command", "wait=True) _unclaim_channel = decorator(_unclaim_channel) return await _unclaim_channel(channel, claimant_id, is_auto) async", "category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_dormant, ) log.trace(f\"Sending dormant message for", "= discord.Embed(description=_message.DORMANT_MSG) await channel.send(embed=embed) log.trace(f\"Pushing #{channel} ({channel.id}) into the channel", "channel = await self.get_available_candidate() log.info(f\"Making #{channel} ({channel.id}) available.\") await _message.send_available_message(channel)", "channels * Prioritise using the channels which have been dormant", "check because the check needs to fail silently. if await", "with channels.\") queue = asyncio.Queue() for channel in channels: queue.put_nowait(channel)", "is based on a 3-category system: Available Category * Contains", "would potentially long delays for the cog to become ready.", "yet). # This may confuse users. So would potentially long", "asking another question. Lastly, make a new channel available. \"\"\"", "import discord.abc from discord.ext import commands from bot import constants", "wasn't called yet). # This may confuse users. So would", "channel = await task log.trace(f\"Channel #{channel} ({channel.id}) finally retrieved from", "in a random order. \"\"\" log.trace(\"Creating the channel queue.\") channels", "helpers will be notified (see `notify()`) * When a channel", "channels = list(_channel.get_category_channels(self.available_category)) missing = constants.HelpChannels.max_available - len(channels) # If", "channels.\") queue = asyncio.Queue() for channel in channels: queue.put_nowait(channel) return", "_message.check_for_answer(message) @commands.Cog.listener() async def on_message_delete(self, msg: discord.Message) -> None: \"\"\"", "Available Category * Contains channels which are ready to be", "`bot/resources/elements.json`. \"\"\" def __init__(self, bot: Bot): self.bot = bot self.scheduler", "async def init_categories(self) -> None: \"\"\"Get the help category objects.", "and the cog is ready (e.g. if move_idle_channel wasn't called", "has_task: self.scheduler.cancel(channel.id) delay = idle_seconds - time_elapsed log.info( f\"#{channel} ({channel.id})", "moves to dormant category after `constants.HelpChannels.idle_minutes` of being idle *", "async def close_command(self, ctx: commands.Context) -> None: \"\"\" Make the", "async def move_to_dormant(self, channel: discord.TextChannel) -> None: \"\"\"Make the `channel`", "task.cancel() self.scheduler.cancel_all() @lock.lock_arg(NAMESPACE, \"message\", attrgetter(\"channel.id\")) @lock.lock_arg(NAMESPACE, \"message\", attrgetter(\"author.id\")) @lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"message\",", "None log.debug(f\"Creating a new dormant channel named {name}.\") return await", "new channel available. \"\"\" log.info(f\"Channel #{message.channel} was claimed by `{message.author.id}`.\")", "# Cancel the task that makes the channel dormant only", "user_id for _, user_id in await _caches.claimants.items()): # Remove the", "lock while waiting for a channel. scheduling.create_task(self.move_to_available(), name=f\"help_claim_{message.id}\") def create_channel_queue(self)", "dormant.\"\"\" log.info(f\"Moving #{channel} ({channel.id}) to the Dormant category.\") await _channel.move_to_bottom(", "await channel_utils.try_get_channel( constants.Categories.help_available ) self.in_use_category = await channel_utils.try_get_channel( constants.Categories.help_in_use )", "change categories between the time # the command is invoked", "Queues self.channel_queue: asyncio.Queue[discord.TextChannel] = None self.name_queue: t.Deque[str] = None self.last_notification:", "category; cog will be removed\") self.bot.remove_cog(self.qualified_name) async def init_cog(self) ->", "(see `notify()`) * When a channel becomes available, the dormant", "({channel.id}) to become dormant in {timeout} sec.\") self.scheduler.schedule_later(timeout, channel.id, self.move_idle_channel(channel))", "no other channels left await _cooldown.remove_cooldown_role(claimant) await _message.unpin(channel) await _stats.report_complete_session(channel.id,", "cancelled. \"\"\" log.trace(f\"Handling in-use channel #{channel} ({channel.id}).\") if not await", "lock is applied conditionally. if claimant_id is not None: decorator", "use a timezone-aware datetime to ensure a correct POSIX timestamp.", "claimant is None: log.info(f\"{claimant_id} left the guild during their help", "in use * Channels are used to refill the Available", "self.in_use_category: log.debug(f\"{ctx.author} invoked command 'close' outside an in-use help channel\")", "left await _cooldown.remove_cooldown_role(claimant) await _message.unpin(channel) await _stats.report_complete_session(channel.id, is_auto) await self.move_to_dormant(channel)", "await _message.pin(message) try: await _message.dm_on_open(message) except Exception as e: log.warning(\"Error", "channel in the Dormant category. The new channel will sync", "it'd be useless and # possibly incorrect to lock on", "a channel at an interval `constants.HelpChannels.claim_minutes` * To keep track", "channels[:abs(missing)]: await self.unclaim_channel(channel) async def init_categories(self) -> None: \"\"\"Get the", "channels; refilled automatically from the pool of dormant channels *", "# we should move the superfluous ones over to dormant.", "if still active. If `has_task` is True and rescheduling is", "getting the next available channel. The channels are added to", "channel=channel, category_id=constants.Categories.help_available, ) _stats.report_counts() async def move_to_dormant(self, channel: discord.TextChannel) ->", "claimant_id: int, is_auto: bool) -> None: \"\"\"Actual implementation of `unclaim_channel`.", "mark a channel as dormant * Channel claimant is allowed", "Cancel the scheduled cooldown role removal task. Set `is_auto` to", "if claimant is None: log.info(f\"{claimant_id} left the guild during their", "not await _message.is_empty(channel): idle_seconds = constants.HelpChannels.idle_minutes * 60 else: idle_seconds", "is_auto=False) async def get_available_candidate(self) -> discord.TextChannel: \"\"\" Return a dormant", "by staff. \"\"\" # Don't use a discord.py check because", "no dormant channels to move, helpers will be notified (see", "= bot self.scheduler = scheduling.Scheduler(self.__class__.__name__) # Categories self.available_category: discord.CategoryChannel =", "session; the cooldown role won't be removed\") elif not any(claimant.id", "`max_available` channels available, # we should move the superfluous ones", "return channel async def init_available(self) -> None: \"\"\"Initialise the Available", "from bot.exts.help_channels import _caches, _channel, _cooldown, _message, _name, _stats from", "category with channels.\"\"\" log.trace(\"Initialising the Available category with channels.\") channels", "using the channels which have been dormant for the longest", "has_role: self.bot.stats.incr(\"help.dormant_invoke.staff\") return has_role @commands.command(name=\"close\", aliases=[\"dormant\", \"solved\"], enabled=False) async def", "delays for the cog to become ready. self.close_command.enabled = True", "command. # In other cases, the task is either already", "self.init_available() _stats.report_counts() log.info(\"Cog is ready!\") async def move_idle_channel(self, channel: discord.TextChannel,", "Cancel the existing task, if any. if has_task: self.scheduler.cancel(channel.id) delay", "the `channel` dormant.\"\"\" log.info(f\"Moving #{channel} ({channel.id}) to the Dormant category.\")", "ctx.channel.category != self.in_use_category: log.debug(f\"{ctx.author} invoked command 'close' outside an in-use", "the Python Help: Available category. \"\"\" class HelpChannels(commands.Cog): \"\"\" Manage", "await _message.notify(notify_channel, self.last_notification) if last_notification: self.last_notification = last_notification self.bot.stats.incr(\"help.out_of_channel_alerts\") channel", "the guild during their help session; the cooldown role won't", "`unclaim_channel`. See that for full documentation.\"\"\" await _caches.claimants.delete(channel.id) # Ignore", "_cooldown, _message, _name, _stats from bot.utils import channel as channel_utils,", "superfluous ones over to dormant. elif missing < 0: log.trace(f\"Moving", "the Available category Help channels are named after the chemical", "self.in_use_category = await channel_utils.try_get_channel( constants.Categories.help_in_use ) self.dormant_category = await channel_utils.try_get_channel(", "attrgetter(\"channel.id\")) @lock.lock_arg(NAMESPACE, \"message\", attrgetter(\"author.id\")) @lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"message\", attrgetter(\"author.id\"), wait=True) async def", "have a temporary role In Use Category * Contains all", "Available category. \"\"\" class HelpChannels(commands.Cog): \"\"\" Manage the help channel", "None: \"\"\"Make a channel available.\"\"\" log.trace(\"Making a channel available.\") channel", "except Exception as e: log.warning(\"Error occurred while sending DM:\", exc_info=e)", "= lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"claimant_id\", wait=True) _unclaim_channel = decorator(_unclaim_channel) return await _unclaim_channel(channel,", "time_elapsed = await _channel.get_idle_time(channel) if time_elapsed is None or time_elapsed", "the guild to be available before initialisation.\") await self.bot.wait_until_guild_available() log.trace(\"Initialising", "except IndexError: log.debug(\"No more names available for new dormant channels.\")", "\"\"\" Unclaim an in-use help `channel` to make it dormant.", "staff. \"\"\" # Don't use a discord.py check because the", "Python Help: Available category. \"\"\" class HelpChannels(commands.Cog): \"\"\" Manage the", "DM:\", exc_info=e) # Add user with channel for dormant check.", "aliases=[\"dormant\", \"solved\"], enabled=False) async def close_command(self, ctx: commands.Context) -> None:", "category objects. Remove the cog if retrieval fails.\"\"\" log.trace(\"Getting the", "cooldowns, user which claimed a channel will have a temporary", "None: \"\"\"Get the help category objects. Remove the cog if", "def init_categories(self) -> None: \"\"\"Get the help category objects. Remove", "to become ready. self.close_command.enabled = True await self.init_available() _stats.report_counts() log.info(\"Cog", "removal task. Set `is_auto` to True if the channel was", "channel_utils.try_get_channel( constants.Categories.help_available ) self.in_use_category = await channel_utils.try_get_channel( constants.Categories.help_in_use ) self.dormant_category", "= await channel_utils.try_get_channel( constants.Categories.help_in_use ) self.dormant_category = await channel_utils.try_get_channel( constants.Categories.help_dormant", "# Categories self.available_category: discord.CategoryChannel = None self.in_use_category: discord.CategoryChannel = None", "[] self.init_task = self.bot.loop.create_task(self.init_cog()) def cog_unload(self) -> None: \"\"\"Cancel the", "= constants.HelpChannels.deleted_idle_minutes * 60 time_elapsed = await _channel.get_idle_time(channel) if time_elapsed", "channels available, # we should move the superfluous ones over", "for _, user_id in await _caches.claimants.items()): # Remove the cooldown", "and return it.\"\"\" log.trace(\"Waiting for a dormant channel.\") task =", "occurred while sending DM:\", exc_info=e) # Add user with channel", "channel dormant will first be cancelled. \"\"\" log.trace(f\"Handling in-use channel", "queue.\") self.channel_queue.put_nowait(channel) _stats.report_counts() @lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"channel\") async def unclaim_channel(self, channel: discord.TextChannel,", "_cooldown.revoke_send_permissions(message.author, self.scheduler) await _message.pin(message) try: await _message.dm_on_open(message) except Exception as", "\"\"\" This is a Python help channel. You can claim", "log.trace(f\"Moving {abs(missing)} superfluous available channels over to the Dormant category.\")", "to use for getting the next available channel. The channels", "@lock.lock_arg(NAMESPACE, \"message\", attrgetter(\"author.id\")) @lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"message\", attrgetter(\"author.id\"), wait=True) async def claim_channel(self,", "self.dormant_category, ) log.trace(\"Moving or rescheduling in-use channels.\") for channel in", "it to be moved after {delay} seconds.\" ) self.scheduler.schedule_later(delay, channel.id,", "existing dormant task before scheduling new. self.scheduler.cancel(msg.channel.id) delay = constants.HelpChannels.deleted_idle_minutes", "checking roles.\") has_role = await commands.has_any_role(*constants.HelpChannels.cmd_whitelist).predicate(ctx) if has_role: self.bot.stats.incr(\"help.dormant_invoke.staff\") return", "-> None: \"\"\"Initialise the Available category with channels.\"\"\" log.trace(\"Initialising the", "if not await _message.is_empty(channel): idle_seconds = constants.HelpChannels.idle_minutes * 60 else:", "to become available in the queue and return it.\"\"\" log.trace(\"Waiting", "discord.HTTPException: log.exception(\"Failed to get a category; cog will be removed\")", "dormant.\" ) await self.unclaim_channel(channel) else: # Cancel the existing task,", "question `message` was sent. Move the channel to the In", "to be made dormant.\"\"\" log.info(f\"Moving #{channel} ({channel.id}) to the In", "If `has_task` is True and rescheduling is required, the extant", "got less than `max_available` channel available, we should add some.", "_message.unpin(channel) await _stats.report_complete_session(channel.id, is_auto) await self.move_to_dormant(channel) # Cancel the task", "else: # Cancel the existing task, if any. if has_task:", "if not channel: log.info(\"Couldn't create a candidate channel; waiting to", "for getting the next available channel. The channels are added", "except asyncio.QueueEmpty: log.info(\"No candidate channels in the queue; creating a", "bool: \"\"\"Return True if the channel is in use and", "random order. \"\"\" log.trace(\"Creating the channel queue.\") channels = list(_channel.get_category_channels(self.dormant_category))", "= True) -> None: \"\"\" Unclaim an in-use help `channel`", "the bot will automatically create a new one * If", "await self.move_to_available() # If for some reason we have more", "channel: discord.TextChannel, *, is_auto: bool = True) -> None: \"\"\"", "been dormant for the longest amount of time * If", "to the claimant to prevent them from asking another question.", "the superfluous ones over to dormant. elif missing < 0:", "await _caches.claim_times.set(message.channel.id, timestamp) await _caches.unanswered.set(message.channel.id, True) # Not awaited because", "await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_in_use, ) timeout = constants.HelpChannels.idle_minutes * 60", "self._unclaim_channel # It could be possible that there is no", "will be removed\") self.bot.remove_cog(self.qualified_name) async def init_cog(self) -> None: \"\"\"Initialise", "pin the `message`. Add a cooldown to the claimant to", "with channels.\") channels = list(_channel.get_category_channels(self.available_category)) missing = constants.HelpChannels.max_available - len(channels)", "in channels: queue.put_nowait(channel) return queue async def create_dormant(self) -> t.Optional[discord.TextChannel]:", "= None # Queues self.channel_queue: asyncio.Queue[discord.TextChannel] = None self.name_queue: t.Deque[str]", "self.name_queue.popleft() except IndexError: log.debug(\"No more names available for new dormant", "no more channel names are available. \"\"\" log.trace(\"Getting a name", ") self.dormant_category = await channel_utils.try_get_channel( constants.Categories.help_dormant ) except discord.HTTPException: log.exception(\"Failed", "closed. \"\"\" claimant_id = await _caches.claimants.get(channel.id) _unclaim_channel = self._unclaim_channel #", "channel; waiting to get one from the queue.\") notify_channel =", "is allowed to use the command * Allowed roles for", "channel in _channel.get_category_channels(self.in_use_category): await self.move_idle_channel(channel, has_task=False) # Prevent the command", "than `max_available` channel available, we should add some. if missing", "channel.\") channel = await self.create_dormant() if not channel: log.info(\"Couldn't create", "Contains channels which are ready to be occupied by someone", "to show `AVAILABLE_MSG` * User can only claim a channel", "= None self.name_queue: t.Deque[str] = None self.last_notification: t.Optional[datetime] = None", "Prevent the command from being used until ready. # The", "lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"claimant_id\", wait=True) _unclaim_channel = decorator(_unclaim_channel) return await _unclaim_channel(channel, claimant_id,", "If there are no dormant channels to move, helpers will", "which aren't in use * Channels are used to refill", "now. Rescheduling task.\") # Cancel existing dormant task before scheduling", "None: \"\"\"Make the `channel` dormant.\"\"\" log.info(f\"Moving #{channel} ({channel.id}) to the", "they have no other channels claimed. Cancel the scheduled cooldown", "claimant cached. In such case, it'd be useless and #", "role.\"\"\" if ctx.channel.category != self.in_use_category: log.debug(f\"{ctx.author} invoked command 'close' outside", "use for getting the next available channel. The channels are", "system of the guild. The system is based on a", "channel in channels[:abs(missing)]: await self.unclaim_channel(channel) async def init_categories(self) -> None:", "always contain `constants.HelpChannels.max_available` channels; refilled automatically from the pool of", "await self.unclaim_channel(ctx.channel, is_auto=False) async def get_available_candidate(self) -> discord.TextChannel: \"\"\" Return", "log.trace(\"Getting the CategoryChannel objects for the help categories.\") try: self.available_category", "removed\") self.bot.remove_cog(self.qualified_name) async def init_cog(self) -> None: \"\"\"Initialise the help", "= None self.last_notification: t.Optional[datetime] = None # Asyncio stuff self.queue_tasks:", "log.info(f\"Making #{channel} ({channel.id}) available.\") await _message.send_available_message(channel) log.trace(f\"Moving #{channel} ({channel.id}) to", "command is invoked and the cog is ready (e.g. if", "await self.move_to_in_use(message.channel) await _cooldown.revoke_send_permissions(message.author, self.scheduler) await _message.pin(message) try: await _message.dm_on_open(message)", "the command from being used until ready. # The ready", "So would potentially long delays for the cog to become", "except discord.HTTPException: log.exception(\"Failed to get a category; cog will be", "= await _caches.claimants.get(channel.id) _unclaim_channel = self._unclaim_channel # It could be", "automatically create a new one * If there are no", "-> bool: \"\"\"Return True if the channel is in use", "self.close_command.enabled = True await self.init_available() _stats.report_counts() log.info(\"Cog is ready!\") async", "bot import constants from bot.bot import Bot from bot.exts.help_channels import", "_channel, _cooldown, _message, _name, _stats from bot.utils import channel as", "is_auto: bool) -> None: \"\"\"Actual implementation of `unclaim_channel`. See that", "be notified (see `notify()`) * When a channel becomes available,", "channel is in use and the user is the claimant", "idle_seconds = constants.HelpChannels.idle_minutes * 60 else: idle_seconds = constants.HelpChannels.deleted_idle_minutes *", "if has_role: self.bot.stats.incr(\"help.dormant_invoke.staff\") return has_role @commands.command(name=\"close\", aliases=[\"dormant\", \"solved\"], enabled=False) async", "= self.name_queue.popleft() except IndexError: log.debug(\"No more names available for new", "could change categories between the time # the command is", "from the pool of dormant channels * Prioritise using the", "channel = await self.create_dormant() if not channel: log.info(\"Couldn't create a", "discord.ext import commands from bot import constants from bot.bot import", "class HelpChannels(commands.Cog): \"\"\" Manage the help channel system of the", "not is_auto: self.scheduler.cancel(channel.id) async def move_to_in_use(self, channel: discord.TextChannel) -> None:", "log.trace(\"Getting a name for a new dormant channel.\") try: name", "channels.\"\"\" log.trace(\"Initialising the Available category with channels.\") channels = list(_channel.get_category_channels(self.available_category))", "only if called by the close command. # In other", "dormant channel to turn into an available channel. If no", "as dormant * Channel claimant is allowed to use the", "({channel.id}) to the Available category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_available, )", "a channel available.\"\"\" log.trace(\"Making a channel available.\") channel = await", "of cooldowns, user which claimed a channel will have a", "\"\"\"Return True if the channel is in use and the", ") log.trace(\"Moving or rescheduling in-use channels.\") for channel in _channel.get_category_channels(self.in_use_category):", "as channel_utils, lock, scheduling log = logging.getLogger(__name__) NAMESPACE = \"help\"", "time for the dormant task is configured with `HelpChannels.deleted_idle_minutes`. \"\"\"", "automatically from the pool of dormant channels * Prioritise using", "log.trace(\"Initialising the Available category with channels.\") channels = list(_channel.get_category_channels(self.available_category)) missing", "used until ready. # The ready event wasn't used because", "scheduling log = logging.getLogger(__name__) NAMESPACE = \"help\" HELP_CHANNEL_TOPIC = \"\"\"", "async def _unclaim_channel(self, channel: discord.TextChannel, claimant_id: int, is_auto: bool) ->", "claimed a channel will have a temporary role In Use", "dormant channel.\") task = asyncio.create_task(self.channel_queue.get()) self.queue_tasks.append(task) channel = await task", "make it dormant. Unpin the claimant's question message and move", "Remove the cog if retrieval fails.\"\"\" log.trace(\"Getting the CategoryChannel objects", "def wait_for_dormant_channel(self) -> discord.TextChannel: \"\"\"Wait for a dormant channel to", "to make it dormant. Unpin the claimant's question message and", "None: \"\"\"Actual implementation of `unclaim_channel`. See that for full documentation.\"\"\"", "if idle or schedule the move if still active. If", "channel.id, self.move_idle_channel(channel)) _stats.report_counts() @commands.Cog.listener() async def on_message(self, message: discord.Message) ->", "queue.\") channels = list(_channel.get_category_channels(self.dormant_category)) random.shuffle(channels) log.trace(\"Populating the channel queue with", "left the guild during their help session; the cooldown role", "return await _unclaim_channel(channel, claimant_id, is_auto) async def _unclaim_channel(self, channel: discord.TextChannel,", "users. So would potentially long delays for the cog to", "the help categories.\") try: self.available_category = await channel_utils.try_get_channel( constants.Categories.help_available )", ">= idle_seconds: log.info( f\"#{channel} ({channel.id}) is idle longer than {idle_seconds}", "bool = True) -> None: \"\"\" Unclaim an in-use help", "None. Therefore, the lock is applied conditionally. if claimant_id is", "await self.create_dormant() if not channel: log.info(\"Couldn't create a candidate channel;", "\" f\"scheduling it to be moved after {delay} seconds.\" )", "is_auto) async def _unclaim_channel(self, channel: discord.TextChannel, claimant_id: int, is_auto: bool)", "_cooldown.remove_cooldown_role(claimant) await _message.unpin(channel) await _stats.report_complete_session(channel.id, is_auto) await self.move_to_dormant(channel) # Cancel", "queue of dormant channels to use for getting the next", "create_dormant(self) -> t.Optional[discord.TextChannel]: \"\"\" Create and return a new channel", "in self.scheduler: self.scheduler.cancel(claimant_id) claimant = self.bot.get_guild(constants.Guild.id).get_member(claimant_id) if claimant is None:", "self.bot.loop.create_task(self.init_cog()) def cog_unload(self) -> None: \"\"\"Cancel the init task and", "for a dormant channel to become available in the queue", "names available for new dormant channels.\") return None log.debug(f\"Creating a", "lock, scheduling log = logging.getLogger(__name__) NAMESPACE = \"help\" HELP_CHANNEL_TOPIC =", "self.move_to_dormant(channel) # Cancel the task that makes the channel dormant", "= await _channel.get_idle_time(channel) if time_elapsed is None or time_elapsed >=", "empty. The new time for the dormant task is configured", "You can claim your own help channel in the Python", "empty now. Rescheduling task.\") # Cancel existing dormant task before", "log.info(f\"Claimant of #{msg.channel} ({msg.author}) deleted message, channel is empty now.", "The system is based on a 3-category system: Available Category", "_caches.unanswered.set(message.channel.id, True) # Not awaited because it may indefinitely hold", "in-use channel #{channel} ({channel.id}).\") if not await _message.is_empty(channel): idle_seconds =", "will be edited to show `AVAILABLE_MSG` * User can only", "def claim_channel(self, message: discord.Message) -> None: \"\"\" Claim the channel", "by `{message.author.id}`.\") await self.move_to_in_use(message.channel) await _cooldown.revoke_send_permissions(message.author, self.scheduler) await _message.pin(message) try:", "role In Use Category * Contains all channels which are", "the move if still active. If `has_task` is True and", "category after `constants.HelpChannels.idle_minutes` of being idle * Command can prematurely", "= idle_seconds - time_elapsed log.info( f\"#{channel} ({channel.id}) is still active;", "log.info(f\"{claimant_id} left the guild during their help session; the cooldown", "self.available_category: discord.CategoryChannel = None self.in_use_category: discord.CategoryChannel = None self.dormant_category: discord.CategoryChannel", "-> None: \"\"\" Unclaim an in-use help `channel` to make", "in the Python Help: Available category. \"\"\" class HelpChannels(commands.Cog): \"\"\"", "log.info(\"Cog is ready!\") async def move_idle_channel(self, channel: discord.TextChannel, has_task: bool", "await task log.trace(f\"Channel #{channel} ({channel.id}) finally retrieved from the queue.\")", "move_idle_channel(self, channel: discord.TextChannel, has_task: bool = True) -> None: \"\"\"", "the channel to the In Use category and pin the", "\"\"\"Make a channel available.\"\"\" log.trace(\"Making a channel available.\") channel =", "log.info(\"No candidate channels in the queue; creating a new channel.\")", "timeout = constants.HelpChannels.idle_minutes * 60 log.trace(f\"Scheduling #{channel} ({channel.id}) to become", "self.move_idle_channel(msg.channel)) async def wait_for_dormant_channel(self) -> discord.TextChannel: \"\"\"Wait for a dormant", "Dormant Category * Contains channels which aren't in use *", "needs to fail silently. if await self.close_check(ctx): log.info(f\"Close command invoked", "own help channel in the Python Help: Available category. \"\"\"", "for channel in _channel.get_category_channels(self.in_use_category): await self.move_idle_channel(channel, has_task=False) # Prevent the", "elements in `bot/resources/elements.json`. \"\"\" def __init__(self, bot: Bot): self.bot =", "log.trace(f\"Moving #{channel} ({channel.id}) to the Available category.\") await _channel.move_to_bottom( channel=channel,", "for the guild to be available before initialisation.\") await self.bot.wait_until_guild_available()", "Allowed roles for the command are configurable with `constants.HelpChannels.cmd_whitelist` *", "- time_elapsed log.info( f\"#{channel} ({channel.id}) is still active; \" f\"scheduling", "await self.dormant_category.create_text_channel(name, topic=HELP_CHANNEL_TOPIC) async def close_check(self, ctx: commands.Context) -> bool:", "commands.has_any_role(*constants.HelpChannels.cmd_whitelist).predicate(ctx) if has_role: self.bot.stats.incr(\"help.dormant_invoke.staff\") return has_role @commands.command(name=\"close\", aliases=[\"dormant\", \"solved\"], enabled=False)", "of `unclaim_channel`. See that for full documentation.\"\"\" await _caches.claimants.delete(channel.id) #", "attrgetter(\"author.id\"), wait=True) async def claim_channel(self, message: discord.Message) -> None: \"\"\"", "will have a temporary role In Use Category * Contains", "channel.\") try: name = self.name_queue.popleft() except IndexError: log.debug(\"No more names", "cog if retrieval fails.\"\"\" log.trace(\"Getting the CategoryChannel objects for the", "initialisation.\") await self.bot.wait_until_guild_available() log.trace(\"Initialising the cog.\") await self.init_categories() await _cooldown.check_cooldowns(self.scheduler)", "notify_channel = self.bot.get_channel(constants.HelpChannels.notify_channel) last_notification = await _message.notify(notify_channel, self.last_notification) if last_notification:", "help channel system.\"\"\" log.trace(\"Waiting for the guild to be available", "claim a channel at an interval `constants.HelpChannels.claim_minutes` * To keep", "channel. If no channel is available, wait indefinitely until one", "channel: discord.TextChannel) -> None: \"\"\"Make a channel in-use and schedule", "return False if await _caches.claimants.get(ctx.channel.id) == ctx.author.id: log.trace(f\"{ctx.author} is the", "should move the superfluous ones over to dormant. elif missing", "more names available for new dormant channels.\") return None log.debug(f\"Creating", "will sync its permission overwrites with the category. Return None", "channel_utils, lock, scheduling log = logging.getLogger(__name__) NAMESPACE = \"help\" HELP_CHANNEL_TOPIC", "return # Ignore messages sent by bots. await self.init_task if", "3-category system: Available Category * Contains channels which are ready", "Make the `channel` dormant if idle or schedule the move", "If there are no more dormant channels, the bot will", "the init_cog task\") self.init_task.cancel() log.trace(\"Cog unload: cancelling the channel queue", "is not the help channel claimant, checking roles.\") has_role =", "Available category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_available, ) _stats.report_counts() async def", "Manage the help channel system of the guild. The system", "the channel claimant if they have no other channels claimed.", "timestamp) await _caches.unanswered.set(message.channel.id, True) # Not awaited because it may", "to make the channel dormant will first be cancelled. \"\"\"", "category_id=constants.Categories.help_available, ) _stats.report_counts() async def move_to_dormant(self, channel: discord.TextChannel) -> None:", "aren't in use * Channels are used to refill the", "and return a new channel in the Dormant category. The", "by the channel's claimant or by staff. \"\"\" # Don't", "= self.create_channel_queue() self.name_queue = _name.create_name_queue( self.available_category, self.in_use_category, self.dormant_category, ) log.trace(\"Moving", "'close' outside an in-use help channel\") return False if await", "None: \"\"\"Initialise the Available category with channels.\"\"\" log.trace(\"Initialising the Available", "still active; \" f\"scheduling it to be moved after {delay}", "= scheduling.Scheduler(self.__class__.__name__) # Categories self.available_category: discord.CategoryChannel = None self.in_use_category: discord.CategoryChannel", "channel system of the guild. The system is based on", "removed\") elif not any(claimant.id == user_id for _, user_id in", "available, we should add some. if missing > 0: log.trace(f\"Moving", "channel: discord.TextChannel, has_task: bool = True) -> None: \"\"\" Make", "async def on_message(self, message: discord.Message) -> None: \"\"\"Move an available", "None: \"\"\" Reschedule an in-use channel to become dormant sooner", "are no dormant channels to move, helpers will be notified", "Channel claimant is allowed to use the command * Allowed", "by bots. await self.init_task if channel_utils.is_in_category(message.channel, constants.Categories.help_available): if not _channel.is_excluded_channel(message.channel):", "f\"scheduling it to be moved after {delay} seconds.\" ) self.scheduler.schedule_later(delay,", "dormant embed will be edited to show `AVAILABLE_MSG` * User", "\" f\"and will be made dormant.\" ) await self.unclaim_channel(channel) else:", "def __init__(self, bot: Bot): self.bot = bot self.scheduler = scheduling.Scheduler(self.__class__.__name__)", "dormant. Unpin the claimant's question message and move the channel", "* Contains channels which are ready to be occupied by", "scheduling new. self.scheduler.cancel(msg.channel.id) delay = constants.HelpChannels.deleted_idle_minutes * 60 self.scheduler.schedule_later(delay, msg.channel.id,", "occupied by someone needing help * Channel moves to dormant", "self.scheduler.schedule_later(delay, channel.id, self.move_idle_channel(channel)) async def move_to_available(self) -> None: \"\"\"Make a", "\"\"\"Make the `channel` dormant.\"\"\" log.info(f\"Moving #{channel} ({channel.id}) to the Dormant", "time # the command is invoked and the cog is", "are added to the queue in a random order. \"\"\"", "typing as t from datetime import datetime, timezone from operator", "fail silently. if await self.close_check(ctx): log.info(f\"Close command invoked by {ctx.author}", "log.trace(\"Cog unload: cancelling the channel queue tasks\") for task in", "claimant's question message and move the channel to the Dormant", "await _caches.unanswered.set(message.channel.id, True) # Not awaited because it may indefinitely", "log.trace(\"Waiting for the guild to be available before initialisation.\") await", "await self.init_available() _stats.report_counts() log.info(\"Cog is ready!\") async def move_idle_channel(self, channel:", "_message, _name, _stats from bot.utils import channel as channel_utils, lock,", "discord.TextChannel) -> None: \"\"\"Make the `channel` dormant.\"\"\" log.info(f\"Moving #{channel} ({channel.id})", "sooner if the channel is empty. The new time for", "some. if missing > 0: log.trace(f\"Moving {missing} missing channels to", "None self.name_queue: t.Deque[str] = None self.last_notification: t.Optional[datetime] = None #", "has_task=False) # Prevent the command from being used until ready.", "on None. Therefore, the lock is applied conditionally. if claimant_id", "#{channel} ({channel.id}).\") embed = discord.Embed(description=_message.DORMANT_MSG) await channel.send(embed=embed) log.trace(f\"Pushing #{channel} ({channel.id})", "asyncio.Queue[discord.TextChannel] = None self.name_queue: t.Deque[str] = None self.last_notification: t.Optional[datetime] =", "# Must use a timezone-aware datetime to ensure a correct", "Channels are used to refill the Available category Help channels", "def _unclaim_channel(self, channel: discord.TextChannel, claimant_id: int, is_auto: bool) -> None:", "and schedule it to be made dormant.\"\"\" log.info(f\"Moving #{channel} ({channel.id})", "last_notification: self.last_notification = last_notification self.bot.stats.incr(\"help.out_of_channel_alerts\") channel = await self.wait_for_dormant_channel() return", "lock on None. Therefore, the lock is applied conditionally. if", "-> None: \"\"\"Make a channel in-use and schedule it to", "cooldown role from the channel claimant if they have no", "await _unclaim_channel(channel, claimant_id, is_auto) async def _unclaim_channel(self, channel: discord.TextChannel, claimant_id:", "task is configured with `HelpChannels.deleted_idle_minutes`. \"\"\" await self.init_task if not", "category.\") for _ in range(missing): await self.move_to_available() # If for", "bool) -> None: \"\"\"Actual implementation of `unclaim_channel`. See that for", "\"\"\" Reschedule an in-use channel to become dormant sooner if", "cog is ready (e.g. if move_idle_channel wasn't called yet). #", "scheduling.Scheduler(self.__class__.__name__) # Categories self.available_category: discord.CategoryChannel = None self.in_use_category: discord.CategoryChannel =", "== ctx.author.id: log.trace(f\"{ctx.author} is the help channel claimant, passing the", "channel = self.channel_queue.get_nowait() except asyncio.QueueEmpty: log.info(\"No candidate channels in the", "#{channel} ({channel.id}) to become dormant in {timeout} sec.\") self.scheduler.schedule_later(timeout, channel.id,", "try: name = self.name_queue.popleft() except IndexError: log.debug(\"No more names available", "new channel.\") channel = await self.create_dormant() if not channel: log.info(\"Couldn't", "is required, the extant task to make the channel dormant", "an embed with `DORMANT_MSG` will be sent Dormant Category *", "which are occupied by someone needing help * Channel moves", "category and pin the `message`. Add a cooldown to the", "with the category. Return None if no more channel names", "self.last_notification = last_notification self.bot.stats.incr(\"help.out_of_channel_alerts\") channel = await self.wait_for_dormant_channel() return channel", "queue.put_nowait(channel) return queue async def create_dormant(self) -> t.Optional[discord.TextChannel]: \"\"\" Create", "datetime.now(timezone.utc).timestamp() await _caches.claim_times.set(message.channel.id, timestamp) await _caches.unanswered.set(message.channel.id, True) # Not awaited", "If no channel is available, wait indefinitely until one becomes", "= await _message.notify(notify_channel, self.last_notification) if last_notification: self.last_notification = last_notification self.bot.stats.incr(\"help.out_of_channel_alerts\")", "self.create_channel_queue() self.name_queue = _name.create_name_queue( self.available_category, self.in_use_category, self.dormant_category, ) log.trace(\"Moving or", "cooldown role won't be removed\") elif not any(claimant.id == user_id", "command invoked by {ctx.author} in #{ctx.channel}.\") await self.unclaim_channel(ctx.channel, is_auto=False) async", "channels to use for getting the next available channel. The", "Return a queue of dormant channels to use for getting", "channel to become available in the queue and return it.\"\"\"", "dormant. elif missing < 0: log.trace(f\"Moving {abs(missing)} superfluous available channels", "if the channel is empty. The new time for the", "import Bot from bot.exts.help_channels import _caches, _channel, _cooldown, _message, _name,", "channel available. \"\"\" log.info(f\"Channel #{message.channel} was claimed by `{message.author.id}`.\") await", "log.debug(f\"Creating a new dormant channel named {name}.\") return await self.dormant_category.create_text_channel(name,", "self.move_idle_channel(channel, has_task=False) # Prevent the command from being used until", "`max_available` channel available, we should add some. if missing >", "implementation of `unclaim_channel`. See that for full documentation.\"\"\" await _caches.claimants.delete(channel.id)", "\"\"\" Return a queue of dormant channels to use for", "return log.info(f\"Claimant of #{msg.channel} ({msg.author}) deleted message, channel is empty", "= True await self.init_available() _stats.report_counts() log.info(\"Cog is ready!\") async def", "constants from bot.bot import Bot from bot.exts.help_channels import _caches, _channel,", "dormant channels to move, helpers will be notified (see `notify()`)", "True if the channel is in use and the user", ") log.trace(f\"Sending dormant message for #{channel} ({channel.id}).\") embed = discord.Embed(description=_message.DORMANT_MSG)", "missing tasks because a channel may still be dormant after", "None self.in_use_category: discord.CategoryChannel = None self.dormant_category: discord.CategoryChannel = None #", "of being idle * Command can prematurely mark a channel", "self.bot.get_guild(constants.Guild.id).get_member(claimant_id) if claimant is None: log.info(f\"{claimant_id} left the guild during", "existing task, if any. if has_task: self.scheduler.cancel(channel.id) delay = idle_seconds", "constants.HelpChannels.idle_minutes * 60 log.trace(f\"Scheduling #{channel} ({channel.id}) to become dormant in", "constants.Categories.help_available): if not _channel.is_excluded_channel(message.channel): await self.claim_channel(message) else: await _message.check_for_answer(message) @commands.Cog.listener()", "the channel to the Dormant category. Remove the cooldown role", ") self.in_use_category = await channel_utils.try_get_channel( constants.Categories.help_in_use ) self.dormant_category = await", "help session; the cooldown role won't be removed\") elif not", "Rescheduling task.\") # Cancel existing dormant task before scheduling new.", "one.\"\"\" if message.author.bot: return # Ignore messages sent by bots.", "the channel is in use and the user is the", "t.Optional[datetime] = None # Asyncio stuff self.queue_tasks: t.List[asyncio.Task] = []", "for some reason we have more than `max_available` channels available,", "ensure a correct POSIX timestamp. timestamp = datetime.now(timezone.utc).timestamp() await _caches.claim_times.set(message.channel.id,", "discord.TextChannel: \"\"\"Wait for a dormant channel to become available in", "a random order. \"\"\" log.trace(\"Creating the channel queue.\") channels =", "elif missing < 0: log.trace(f\"Moving {abs(missing)} superfluous available channels over", "the cog unloads.\"\"\" log.trace(\"Cog unload: cancelling the init_cog task\") self.init_task.cancel()", "= list(_channel.get_category_channels(self.dormant_category)) random.shuffle(channels) log.trace(\"Populating the channel queue with channels.\") queue", "from bot.utils import channel as channel_utils, lock, scheduling log =", "log.debug(f\"{ctx.author} invoked command 'close' outside an in-use help channel\") return", "the channel dormant will first be cancelled. \"\"\" log.trace(f\"Handling in-use", "if claimant_id in self.scheduler: self.scheduler.cancel(claimant_id) claimant = self.bot.get_guild(constants.Guild.id).get_member(claimant_id) if claimant", "a channel becomes available, the dormant embed will be edited", "await _caches.claimants.delete(channel.id) # Ignore missing tasks because a channel may", "unloads.\"\"\" log.trace(\"Cog unload: cancelling the init_cog task\") self.init_task.cancel() log.trace(\"Cog unload:", "longer than {idle_seconds} seconds \" f\"and will be made dormant.\"", "return it.\"\"\" log.trace(\"Waiting for a dormant channel.\") task = asyncio.create_task(self.channel_queue.get())", "_channel.get_category_channels(self.in_use_category): await self.move_idle_channel(channel, has_task=False) # Prevent the command from being", "-> None: \"\"\" Make the current in-use help channel dormant.", "channel dormant. May only be invoked by the channel's claimant", "queue in a random order. \"\"\" log.trace(\"Creating the channel queue.\")", "possible that there is no claimant cached. In such case,", "until one becomes available. \"\"\" log.trace(\"Getting an available channel candidate.\")", "Not awaited because it may indefinitely hold the lock while", "on_message_delete(self, msg: discord.Message) -> None: \"\"\" Reschedule an in-use channel", "_caches.claimants.items()): # Remove the cooldown role if the claimant has", "of #{msg.channel} ({msg.author}) deleted message, channel is empty now. Rescheduling", "indefinitely until one becomes available. \"\"\" log.trace(\"Getting an available channel", "a channel in-use and schedule it to be made dormant.\"\"\"", "as t from datetime import datetime, timezone from operator import", "Lastly, make a new channel available. \"\"\" log.info(f\"Channel #{message.channel} was", "-> None: \"\"\"Actual implementation of `unclaim_channel`. See that for full", "objects for the help categories.\") try: self.available_category = await channel_utils.try_get_channel(", "unload: cancelling the channel queue tasks\") for task in self.queue_tasks:", "await _message.unpin(channel) await _stats.report_complete_session(channel.id, is_auto) await self.move_to_dormant(channel) # Cancel the", "available channels over to the Dormant category.\") for channel in", "the chemical elements in `bot/resources/elements.json`. \"\"\" def __init__(self, bot: Bot):", "category Help channels are named after the chemical elements in", "some reason we have more than `max_available` channels available, #", "bot will automatically create a new one * If there", "refilled automatically from the pool of dormant channels * Prioritise", "with `DORMANT_MSG` will be sent Dormant Category * Contains channels", "only be invoked by the channel's claimant or by staff.", "the Dormant category. The new channel will sync its permission", "category. Remove the cooldown role from the channel claimant if", "channel claimant, passing the check for dormant.\") self.bot.stats.incr(\"help.dormant_invoke.claimant\") return True", "claimant_id = await _caches.claimants.get(channel.id) _unclaim_channel = self._unclaim_channel # It could", "channels which aren't in use * Channels are used to", "= constants.HelpChannels.idle_minutes * 60 log.trace(f\"Scheduling #{channel} ({channel.id}) to become dormant", "from operator import attrgetter import discord import discord.abc from discord.ext", "\"\"\" Make the `channel` dormant if idle or schedule the", "is not None: decorator = lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"claimant_id\", wait=True) _unclaim_channel =", "def init_cog(self) -> None: \"\"\"Initialise the help channel system.\"\"\" log.trace(\"Waiting", "log.info(\"Couldn't create a candidate channel; waiting to get one from", "constants.Categories.help_available ) self.in_use_category = await channel_utils.try_get_channel( constants.Categories.help_in_use ) self.dormant_category =", "move_to_in_use(self, channel: discord.TextChannel) -> None: \"\"\"Make a channel in-use and", "should add some. if missing > 0: log.trace(f\"Moving {missing} missing", "if channel_utils.is_in_category(message.channel, constants.Categories.help_available): if not _channel.is_excluded_channel(message.channel): await self.claim_channel(message) else: await", "\"\"\" Return a dormant channel to turn into an available", "role won't be removed\") elif not any(claimant.id == user_id for", "True) -> None: \"\"\" Unclaim an in-use help `channel` to", "task.\") # Cancel existing dormant task before scheduling new. self.scheduler.cancel(msg.channel.id)", "dormant channel named {name}.\") return await self.dormant_category.create_text_channel(name, topic=HELP_CHANNEL_TOPIC) async def", "for the help categories.\") try: self.available_category = await channel_utils.try_get_channel( constants.Categories.help_available", "user which claimed a channel will have a temporary role", "_ in range(missing): await self.move_to_available() # If for some reason", "in channels[:abs(missing)]: await self.unclaim_channel(channel) async def init_categories(self) -> None: \"\"\"Get", "\"\"\" Claim the channel in which the question `message` was", "def close_check(self, ctx: commands.Context) -> bool: \"\"\"Return True if the", "event wasn't used because channels could change categories between the", "category. \"\"\" class HelpChannels(commands.Cog): \"\"\" Manage the help channel system", "Remove the cooldown role from the channel claimant if they", "await _cooldown.check_cooldowns(self.scheduler) self.channel_queue = self.create_channel_queue() self.name_queue = _name.create_name_queue( self.available_category, self.in_use_category,", "be moved after {delay} seconds.\" ) self.scheduler.schedule_later(delay, channel.id, self.move_idle_channel(channel)) async", "log = logging.getLogger(__name__) NAMESPACE = \"help\" HELP_CHANNEL_TOPIC = \"\"\" This", "is either already done or not-existent. if not is_auto: self.scheduler.cancel(channel.id)", "None # Asyncio stuff self.queue_tasks: t.List[asyncio.Task] = [] self.init_task =", "a new dormant channel.\") try: name = self.name_queue.popleft() except IndexError:", "_caches.claim_times.set(message.channel.id, timestamp) await _caches.unanswered.set(message.channel.id, True) # Not awaited because it", "self.init_task = self.bot.loop.create_task(self.init_cog()) def cog_unload(self) -> None: \"\"\"Cancel the init", "{timeout} sec.\") self.scheduler.schedule_later(timeout, channel.id, self.move_idle_channel(channel)) _stats.report_counts() @commands.Cog.listener() async def on_message(self,", "superfluous available channels over to the Dormant category.\") for channel", "log.info(f\"Close command invoked by {ctx.author} in #{ctx.channel}.\") await self.unclaim_channel(ctx.channel, is_auto=False)", "dormant channel to become available in the queue and return", "from the channel claimant if they have no other channels", "Use Category * Contains all channels which are occupied by", "async def init_available(self) -> None: \"\"\"Initialise the Available category with", "category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_in_use, ) timeout = constants.HelpChannels.idle_minutes *", "made dormant.\"\"\" log.info(f\"Moving #{channel} ({channel.id}) to the In Use category.\")", "({channel.id}) to the In Use category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_in_use,", "active; \" f\"scheduling it to be moved after {delay} seconds.\"", "the user is the claimant or has a whitelisted role.\"\"\"", "or by staff. \"\"\" # Don't use a discord.py check", "self.move_to_available() # If for some reason we have more than", "self.in_use_category, self.dormant_category, ) log.trace(\"Moving or rescheduling in-use channels.\") for channel", "logging.getLogger(__name__) NAMESPACE = \"help\" HELP_CHANNEL_TOPIC = \"\"\" This is a", "for a channel. scheduling.create_task(self.move_to_available(), name=f\"help_claim_{message.id}\") def create_channel_queue(self) -> asyncio.Queue: \"\"\"", "idle * Command can prematurely mark a channel as dormant", "question message and move the channel to the Dormant category.", "Will always contain `constants.HelpChannels.max_available` channels; refilled automatically from the pool", "await self.wait_for_dormant_channel() return channel async def init_available(self) -> None: \"\"\"Initialise", "log.trace(f\"Sending dormant message for #{channel} ({channel.id}).\") embed = discord.Embed(description=_message.DORMANT_MSG) await", "await self.close_check(ctx): log.info(f\"Close command invoked by {ctx.author} in #{ctx.channel}.\") await", "required, the extant task to make the channel dormant will", "init_categories(self) -> None: \"\"\"Get the help category objects. Remove the", "{ctx.author} in #{ctx.channel}.\") await self.unclaim_channel(ctx.channel, is_auto=False) async def get_available_candidate(self) ->", "new dormant channel.\") try: name = self.name_queue.popleft() except IndexError: log.debug(\"No", "self.scheduler: self.scheduler.cancel(claimant_id) claimant = self.bot.get_guild(constants.Guild.id).get_member(claimant_id) if claimant is None: log.info(f\"{claimant_id}", "will automatically create a new one * If there are", "self.scheduler.cancel(channel.id) async def move_to_in_use(self, channel: discord.TextChannel) -> None: \"\"\"Make a", "(e.g. if move_idle_channel wasn't called yet). # This may confuse", "move_to_dormant(self, channel: discord.TextChannel) -> None: \"\"\"Make the `channel` dormant.\"\"\" log.info(f\"Moving", "asyncio.Queue() for channel in channels: queue.put_nowait(channel) return queue async def", "= await commands.has_any_role(*constants.HelpChannels.cmd_whitelist).predicate(ctx) if has_role: self.bot.stats.incr(\"help.dormant_invoke.staff\") return has_role @commands.command(name=\"close\", aliases=[\"dormant\",", "because a channel may still be dormant after the cooldown", "claimant_id is not None: decorator = lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"claimant_id\", wait=True) _unclaim_channel", "of the guild. The system is based on a 3-category", "Dormant category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_dormant, ) log.trace(f\"Sending dormant message", "case, it'd be useless and # possibly incorrect to lock", "_unclaim_channel = self._unclaim_channel # It could be possible that there", "categories.\") try: self.available_category = await channel_utils.try_get_channel( constants.Categories.help_available ) self.in_use_category =", "self.unclaim_channel(channel) async def init_categories(self) -> None: \"\"\"Get the help category", "channel queue.\") channels = list(_channel.get_category_channels(self.dormant_category)) random.shuffle(channels) log.trace(\"Populating the channel queue", "channel\") return False if await _caches.claimants.get(ctx.channel.id) == ctx.author.id: log.trace(f\"{ctx.author} is", "manually closed. \"\"\" claimant_id = await _caches.claimants.get(channel.id) _unclaim_channel = self._unclaim_channel", "new time for the dormant task is configured with `HelpChannels.deleted_idle_minutes`.", "queue tasks\") for task in self.queue_tasks: task.cancel() self.scheduler.cancel_all() @lock.lock_arg(NAMESPACE, \"message\",", "silently. if await self.close_check(ctx): log.info(f\"Close command invoked by {ctx.author} in", "elif not any(claimant.id == user_id for _, user_id in await", "dormant check. await _caches.claimants.set(message.channel.id, message.author.id) self.bot.stats.incr(\"help.claimed\") # Must use a", "available. \"\"\" log.trace(\"Getting a name for a new dormant channel.\")", "embed = discord.Embed(description=_message.DORMANT_MSG) await channel.send(embed=embed) log.trace(f\"Pushing #{channel} ({channel.id}) into the", "to become dormant in {timeout} sec.\") self.scheduler.schedule_later(timeout, channel.id, self.move_idle_channel(channel)) _stats.report_counts()", "Remove the cooldown role if the claimant has no other", "a temporary role In Use Category * Contains all channels", "be invoked by the channel's claimant or by staff. \"\"\"", "on_message(self, message: discord.Message) -> None: \"\"\"Move an available channel to", "a channel as dormant * Channel claimant is allowed to", "idle_seconds: log.info( f\"#{channel} ({channel.id}) is idle longer than {idle_seconds} seconds", "channels: queue.put_nowait(channel) return queue async def create_dormant(self) -> t.Optional[discord.TextChannel]: \"\"\"", "# Ignore missing tasks because a channel may still be", "await _message.check_for_answer(message) @commands.Cog.listener() async def on_message_delete(self, msg: discord.Message) -> None:", "# This may confuse users. So would potentially long delays", "invoked and the cog is ready (e.g. if move_idle_channel wasn't", "In Use category and replace it with a dormant one.\"\"\"", "a channel available.\") channel = await self.get_available_candidate() log.info(f\"Making #{channel} ({channel.id})", "get_available_candidate(self) -> discord.TextChannel: \"\"\" Return a dormant channel to turn", "cases, the task is either already done or not-existent. if", "async def create_dormant(self) -> t.Optional[discord.TextChannel]: \"\"\" Create and return a", "Available category Help channels are named after the chemical elements", "message for #{channel} ({channel.id}).\") embed = discord.Embed(description=_message.DORMANT_MSG) await channel.send(embed=embed) log.trace(f\"Pushing", "_unclaim_channel(channel, claimant_id, is_auto) async def _unclaim_channel(self, channel: discord.TextChannel, claimant_id: int,", "the init task and scheduled tasks when the cog unloads.\"\"\"", "won't be removed\") elif not any(claimant.id == user_id for _,", "to be moved after {delay} seconds.\" ) self.scheduler.schedule_later(delay, channel.id, self.move_idle_channel(channel))", "between the time # the command is invoked and the", "missing channels to the Available category.\") for _ in range(missing):", "* Contains channels which aren't in use * Channels are", "and pin the `message`. Add a cooldown to the claimant", "May only be invoked by the channel's claimant or by", "Channel moves to dormant category after `constants.HelpChannels.idle_minutes` of being idle", "= await self.wait_for_dormant_channel() return channel async def init_available(self) -> None:", "log.trace(\"Populating the channel queue with channels.\") queue = asyncio.Queue() for", "the command * Allowed roles for the command are configurable", "amount of time * If there are no more dormant", "None or time_elapsed >= idle_seconds: log.info( f\"#{channel} ({channel.id}) is idle", "timezone from operator import attrgetter import discord import discord.abc from", "move_idle_channel wasn't called yet). # This may confuse users. So", "if message.author.bot: return # Ignore messages sent by bots. await", "in-use help channel\") return False if await _caches.claimants.get(ctx.channel.id) == ctx.author.id:", "is in use and the user is the claimant or", "the lock is applied conditionally. if claimant_id is not None:", "ctx.author.id: log.trace(f\"{ctx.author} is the help channel claimant, passing the check", "await self.move_to_dormant(channel) # Cancel the task that makes the channel", "# Don't use a discord.py check because the check needs", "fails.\"\"\" log.trace(\"Getting the CategoryChannel objects for the help categories.\") try:", "more dormant channels, the bot will automatically create a new", "to the Available category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_available, ) _stats.report_counts()", "# It could be possible that there is no claimant", "categories between the time # the command is invoked and", "channel as channel_utils, lock, scheduling log = logging.getLogger(__name__) NAMESPACE =", "claimant if they have no other channels claimed. Cancel the", "Ignore messages sent by bots. await self.init_task if channel_utils.is_in_category(message.channel, constants.Categories.help_available):", "in-use and schedule it to be made dormant.\"\"\" log.info(f\"Moving #{channel}", "# Add user with channel for dormant check. await _caches.claimants.set(message.channel.id,", "True) -> None: \"\"\" Make the `channel` dormant if idle", "It could be possible that there is no claimant cached.", "prevent them from asking another question. Lastly, make a new", "that for full documentation.\"\"\" await _caches.claimants.delete(channel.id) # Ignore missing tasks", "log.trace(\"Waiting for a dormant channel.\") task = asyncio.create_task(self.channel_queue.get()) self.queue_tasks.append(task) channel", "of dormant channels * Prioritise using the channels which have", "long delays for the cog to become ready. self.close_command.enabled =", "from asking another question. Lastly, make a new channel available.", "task that makes the channel dormant only if called by", "not channel_utils.is_in_category(msg.channel, constants.Categories.help_in_use): return if not await _message.is_empty(msg.channel): return log.info(f\"Claimant", "\"\"\" log.trace(f\"Handling in-use channel #{channel} ({channel.id}).\") if not await _message.is_empty(channel):", "be occupied by someone who needs help * Will always", "import datetime, timezone from operator import attrgetter import discord import", "a 3-category system: Available Category * Contains channels which are", "check. await _caches.claimants.set(message.channel.id, message.author.id) self.bot.stats.incr(\"help.claimed\") # Must use a timezone-aware", "there is no claimant cached. In such case, it'd be", "None: log.info(f\"{claimant_id} left the guild during their help session; the", "channel is empty. The new time for the dormant task", "Ignore missing tasks because a channel may still be dormant", "Help channels are named after the chemical elements in `bot/resources/elements.json`.", "as e: log.warning(\"Error occurred while sending DM:\", exc_info=e) # Add", "be useless and # possibly incorrect to lock on None.", "is_auto: self.scheduler.cancel(channel.id) async def move_to_in_use(self, channel: discord.TextChannel) -> None: \"\"\"Make", "to lock on None. Therefore, the lock is applied conditionally.", "self.scheduler) await _message.pin(message) try: await _message.dm_on_open(message) except Exception as e:", "more channel names are available. \"\"\" log.trace(\"Getting a name for", "channel to the In Use category and replace it with", "else: await _message.check_for_answer(message) @commands.Cog.listener() async def on_message_delete(self, msg: discord.Message) ->", "tasks\") for task in self.queue_tasks: task.cancel() self.scheduler.cancel_all() @lock.lock_arg(NAMESPACE, \"message\", attrgetter(\"channel.id\"))", "-> None: \"\"\" Claim the channel in which the question", "`constants.HelpChannels.max_available` channels; refilled automatically from the pool of dormant channels", "#{msg.channel} ({msg.author}) deleted message, channel is empty now. Rescheduling task.\")", "a channel will have a temporary role In Use Category", "to be available before initialisation.\") await self.bot.wait_until_guild_available() log.trace(\"Initialising the cog.\")", "`channel` dormant.\"\"\" log.info(f\"Moving #{channel} ({channel.id}) to the Dormant category.\") await", "or rescheduling in-use channels.\") for channel in _channel.get_category_channels(self.in_use_category): await self.move_idle_channel(channel,", "channels left await _cooldown.remove_cooldown_role(claimant) await _message.unpin(channel) await _stats.report_complete_session(channel.id, is_auto) await", "only claim a channel at an interval `constants.HelpChannels.claim_minutes` * To", "seconds \" f\"and will be made dormant.\" ) await self.unclaim_channel(channel)", "await channel.send(embed=embed) log.trace(f\"Pushing #{channel} ({channel.id}) into the channel queue.\") self.channel_queue.put_nowait(channel)", "are configurable with `constants.HelpChannels.cmd_whitelist` * When a channel becomes dormant,", "# Ignore messages sent by bots. await self.init_task if channel_utils.is_in_category(message.channel,", "guild to be available before initialisation.\") await self.bot.wait_until_guild_available() log.trace(\"Initialising the", "from discord.ext import commands from bot import constants from bot.bot", "if await self.close_check(ctx): log.info(f\"Close command invoked by {ctx.author} in #{ctx.channel}.\")", "Bot from bot.exts.help_channels import _caches, _channel, _cooldown, _message, _name, _stats", "the lock while waiting for a channel. scheduling.create_task(self.move_to_available(), name=f\"help_claim_{message.id}\") def", "True) # Not awaited because it may indefinitely hold the", "channel_utils.is_in_category(msg.channel, constants.Categories.help_in_use): return if not await _message.is_empty(msg.channel): return log.info(f\"Claimant of", "Must use a timezone-aware datetime to ensure a correct POSIX", "claimed by `{message.author.id}`.\") await self.move_to_in_use(message.channel) await _cooldown.revoke_send_permissions(message.author, self.scheduler) await _message.pin(message)", "channel in-use and schedule it to be made dormant.\"\"\" log.info(f\"Moving", "None # Queues self.channel_queue: asyncio.Queue[discord.TextChannel] = None self.name_queue: t.Deque[str] =", "help categories.\") try: self.available_category = await channel_utils.try_get_channel( constants.Categories.help_available ) self.in_use_category", "done or not-existent. if not is_auto: self.scheduler.cancel(channel.id) async def move_to_in_use(self,", "to the Dormant category.\") for channel in channels[:abs(missing)]: await self.unclaim_channel(channel)", "the scheduled cooldown role removal task. Set `is_auto` to True", "in _channel.get_category_channels(self.in_use_category): await self.move_idle_channel(channel, has_task=False) # Prevent the command from", "a new dormant channel named {name}.\") return await self.dormant_category.create_text_channel(name, topic=HELP_CHANNEL_TOPIC)", "= True) -> None: \"\"\" Make the `channel` dormant if", "_message.pin(message) try: await _message.dm_on_open(message) except Exception as e: log.warning(\"Error occurred", "the Available category with channels.\"\"\" log.trace(\"Initialising the Available category with", "was sent. Move the channel to the In Use category", "return None log.debug(f\"Creating a new dormant channel named {name}.\") return", "message, channel is empty now. Rescheduling task.\") # Cancel existing", "time_elapsed is None or time_elapsed >= idle_seconds: log.info( f\"#{channel} ({channel.id})", "log.info(f\"Channel #{message.channel} was claimed by `{message.author.id}`.\") await self.move_to_in_use(message.channel) await _cooldown.revoke_send_permissions(message.author,", "{idle_seconds} seconds \" f\"and will be made dormant.\" ) await", "edited to show `AVAILABLE_MSG` * User can only claim a", "the channel in which the question `message` was sent. Move", "with channels.\"\"\" log.trace(\"Initialising the Available category with channels.\") channels =", "def move_to_in_use(self, channel: discord.TextChannel) -> None: \"\"\"Make a channel in-use", "it.\"\"\" log.trace(\"Waiting for a dormant channel.\") task = asyncio.create_task(self.channel_queue.get()) self.queue_tasks.append(task)", "the In Use category and replace it with a dormant", "scheduling.create_task(self.move_to_available(), name=f\"help_claim_{message.id}\") def create_channel_queue(self) -> asyncio.Queue: \"\"\" Return a queue", "called by the close command. # In other cases, the", "import commands from bot import constants from bot.bot import Bot", "the claimant has no other channels left await _cooldown.remove_cooldown_role(claimant) await", "task, if any. if has_task: self.scheduler.cancel(channel.id) delay = idle_seconds -", "Prioritise using the channels which have been dormant for the", "the Available category with channels.\") channels = list(_channel.get_category_channels(self.available_category)) missing =", "# Remove the cooldown role if the claimant has no", "channel async def init_available(self) -> None: \"\"\"Initialise the Available category", "\"message\", attrgetter(\"author.id\"), wait=True) async def claim_channel(self, message: discord.Message) -> None:", "constants.HelpChannels.max_available - len(channels) # If we've got less than `max_available`", "\"\"\"Move an available channel to the In Use category and", "becomes dormant, an embed with `DORMANT_MSG` will be sent Dormant", "help `channel` to make it dormant. Unpin the claimant's question", "channel: discord.TextChannel) -> None: \"\"\"Make the `channel` dormant.\"\"\" log.info(f\"Moving #{channel}", "category.\") for channel in channels[:abs(missing)]: await self.unclaim_channel(channel) async def init_categories(self)", "\"\"\"Actual implementation of `unclaim_channel`. See that for full documentation.\"\"\" await", "self.last_notification: t.Optional[datetime] = None # Asyncio stuff self.queue_tasks: t.List[asyncio.Task] =", "def on_message(self, message: discord.Message) -> None: \"\"\"Move an available channel", "sending DM:\", exc_info=e) # Add user with channel for dormant", "channels could change categories between the time # the command", "See that for full documentation.\"\"\" await _caches.claimants.delete(channel.id) # Ignore missing", "reason we have more than `max_available` channels available, # we", "await self.unclaim_channel(channel) async def init_categories(self) -> None: \"\"\"Get the help", "is empty. The new time for the dormant task is", "turn into an available channel. If no channel is available,", "# Queues self.channel_queue: asyncio.Queue[discord.TextChannel] = None self.name_queue: t.Deque[str] = None", "enabled=False) async def close_command(self, ctx: commands.Context) -> None: \"\"\" Make", "if time_elapsed is None or time_elapsed >= idle_seconds: log.info( f\"#{channel}", "discord.TextChannel) -> None: \"\"\"Make a channel in-use and schedule it", "invoked by {ctx.author} in #{ctx.channel}.\") await self.unclaim_channel(ctx.channel, is_auto=False) async def", "will be notified (see `notify()`) * When a channel becomes", "name = self.name_queue.popleft() except IndexError: log.debug(\"No more names available for", "and the user is the claimant or has a whitelisted", "available channel. The channels are added to the queue in", "message: discord.Message) -> None: \"\"\"Move an available channel to the", "= self.channel_queue.get_nowait() except asyncio.QueueEmpty: log.info(\"No candidate channels in the queue;", "be sent Dormant Category * Contains channels which aren't in", "discord.Embed(description=_message.DORMANT_MSG) await channel.send(embed=embed) log.trace(f\"Pushing #{channel} ({channel.id}) into the channel queue.\")", "needs help * Will always contain `constants.HelpChannels.max_available` channels; refilled automatically", "into the channel queue.\") self.channel_queue.put_nowait(channel) _stats.report_counts() @lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"channel\") async def", "await self.bot.wait_until_guild_available() log.trace(\"Initialising the cog.\") await self.init_categories() await _cooldown.check_cooldowns(self.scheduler) self.channel_queue", "channel queue tasks\") for task in self.queue_tasks: task.cancel() self.scheduler.cancel_all() @lock.lock_arg(NAMESPACE,", "called yet). # This may confuse users. So would potentially", "True and rescheduling is required, the extant task to make", "are no more dormant channels, the bot will automatically create", "to the In Use category and replace it with a", "used to refill the Available category Help channels are named", "User can only claim a channel at an interval `constants.HelpChannels.claim_minutes`", "create a new one * If there are no dormant", "Bot): self.bot = bot self.scheduler = scheduling.Scheduler(self.__class__.__name__) # Categories self.available_category:", "self.claim_channel(message) else: await _message.check_for_answer(message) @commands.Cog.listener() async def on_message_delete(self, msg: discord.Message)", "constants.Categories.help_in_use ) self.dormant_category = await channel_utils.try_get_channel( constants.Categories.help_dormant ) except discord.HTTPException:", "command * Allowed roles for the command are configurable with", "guild. The system is based on a 3-category system: Available", "await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_dormant, ) log.trace(f\"Sending dormant message for #{channel}", "\"\"\" await self.init_task if not channel_utils.is_in_category(msg.channel, constants.Categories.help_in_use): return if not", "<gh_stars>0 import asyncio import logging import random import typing as", "({channel.id}) is idle longer than {idle_seconds} seconds \" f\"and will", "less than `max_available` channel available, we should add some. if", "async def wait_for_dormant_channel(self) -> discord.TextChannel: \"\"\"Wait for a dormant channel", "dormant channels to use for getting the next available channel.", "is no claimant cached. In such case, it'd be useless", "close_command(self, ctx: commands.Context) -> None: \"\"\" Make the current in-use", "user_id in await _caches.claimants.items()): # Remove the cooldown role if", "= \"\"\" This is a Python help channel. You can", "= asyncio.create_task(self.channel_queue.get()) self.queue_tasks.append(task) channel = await task log.trace(f\"Channel #{channel} ({channel.id})", "ready. # The ready event wasn't used because channels could", "self.bot.stats.incr(\"help.claimed\") # Must use a timezone-aware datetime to ensure a", "to the In Use category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_in_use, )", "a dormant channel to turn into an available channel. If", "The ready event wasn't used because channels could change categories", "dormant in {timeout} sec.\") self.scheduler.schedule_later(timeout, channel.id, self.move_idle_channel(channel)) _stats.report_counts() @commands.Cog.listener() async", "_caches.claimants.get(channel.id) _unclaim_channel = self._unclaim_channel # It could be possible that", "self.init_task.cancel() log.trace(\"Cog unload: cancelling the channel queue tasks\") for task", "if retrieval fails.\"\"\" log.trace(\"Getting the CategoryChannel objects for the help", "the Dormant category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_dormant, ) log.trace(f\"Sending dormant", "True if the channel was automatically closed or False if", "channel at an interval `constants.HelpChannels.claim_minutes` * To keep track of", "* Channel moves to dormant category after `constants.HelpChannels.idle_minutes` of being", "the CategoryChannel objects for the help categories.\") try: self.available_category =", "task to make the channel dormant will first be cancelled.", "_message.send_available_message(channel) log.trace(f\"Moving #{channel} ({channel.id}) to the Available category.\") await _channel.move_to_bottom(", "at an interval `constants.HelpChannels.claim_minutes` * To keep track of cooldowns,", "expires. if claimant_id in self.scheduler: self.scheduler.cancel(claimant_id) claimant = self.bot.get_guild(constants.Guild.id).get_member(claimant_id) if", "a candidate channel; waiting to get one from the queue.\")", "self.unclaim_channel(ctx.channel, is_auto=False) async def get_available_candidate(self) -> discord.TextChannel: \"\"\" Return a", "constants.HelpChannels.deleted_idle_minutes * 60 time_elapsed = await _channel.get_idle_time(channel) if time_elapsed is", "Exception as e: log.warning(\"Error occurred while sending DM:\", exc_info=e) #", "channel names are available. \"\"\" log.trace(\"Getting a name for a", "becomes available, the dormant embed will be edited to show", "help channel dormant. May only be invoked by the channel's", "self.dormant_category: discord.CategoryChannel = None # Queues self.channel_queue: asyncio.Queue[discord.TextChannel] = None", "because channels could change categories between the time # the", "to get one from the queue.\") notify_channel = self.bot.get_channel(constants.HelpChannels.notify_channel) last_notification", "over to the Dormant category.\") for channel in channels[:abs(missing)]: await", "{name}.\") return await self.dormant_category.create_text_channel(name, topic=HELP_CHANNEL_TOPIC) async def close_check(self, ctx: commands.Context)", "to True if the channel was automatically closed or False", "None self.dormant_category: discord.CategoryChannel = None # Queues self.channel_queue: asyncio.Queue[discord.TextChannel] =", "other cases, the task is either already done or not-existent.", "if the channel was automatically closed or False if manually", "are used to refill the Available category Help channels are", "self.in_use_category: discord.CategoryChannel = None self.dormant_category: discord.CategoryChannel = None # Queues", "category_id=constants.Categories.help_dormant, ) log.trace(f\"Sending dormant message for #{channel} ({channel.id}).\") embed =", "are ready to be occupied by someone who needs help", "is still active; \" f\"scheduling it to be moved after", "named after the chemical elements in `bot/resources/elements.json`. \"\"\" def __init__(self,", "asyncio.create_task(self.channel_queue.get()) self.queue_tasks.append(task) channel = await task log.trace(f\"Channel #{channel} ({channel.id}) finally", "invoked command 'close' outside an in-use help channel\") return False", "Use category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_in_use, ) timeout = constants.HelpChannels.idle_minutes", "Contains all channels which are occupied by someone needing help", "is a Python help channel. You can claim your own", "* 60 log.trace(f\"Scheduling #{channel} ({channel.id}) to become dormant in {timeout}", "log.trace(\"Making a channel available.\") channel = await self.get_available_candidate() log.info(f\"Making #{channel}", "channel is available, wait indefinitely until one becomes available. \"\"\"", "Available category.\") for _ in range(missing): await self.move_to_available() # If", "the channel queue tasks\") for task in self.queue_tasks: task.cancel() self.scheduler.cancel_all()", "scheduled tasks when the cog unloads.\"\"\" log.trace(\"Cog unload: cancelling the", "still active. If `has_task` is True and rescheduling is required,", "#{ctx.channel}.\") await self.unclaim_channel(ctx.channel, is_auto=False) async def get_available_candidate(self) -> discord.TextChannel: \"\"\"", "in {timeout} sec.\") self.scheduler.schedule_later(timeout, channel.id, self.move_idle_channel(channel)) _stats.report_counts() @commands.Cog.listener() async def", "was claimed by `{message.author.id}`.\") await self.move_to_in_use(message.channel) await _cooldown.revoke_send_permissions(message.author, self.scheduler) await", "retrieval fails.\"\"\" log.trace(\"Getting the CategoryChannel objects for the help categories.\")", "the check needs to fail silently. if await self.close_check(ctx): log.info(f\"Close", "dormant, an embed with `DORMANT_MSG` will be sent Dormant Category", "self.scheduler.cancel_all() @lock.lock_arg(NAMESPACE, \"message\", attrgetter(\"channel.id\")) @lock.lock_arg(NAMESPACE, \"message\", attrgetter(\"author.id\")) @lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"message\", attrgetter(\"author.id\"),", ") _stats.report_counts() async def move_to_dormant(self, channel: discord.TextChannel) -> None: \"\"\"Make", "init task and scheduled tasks when the cog unloads.\"\"\" log.trace(\"Cog", "await _channel.get_idle_time(channel) if time_elapsed is None or time_elapsed >= idle_seconds:", "new dormant channels.\") return None log.debug(f\"Creating a new dormant channel", "cog will be removed\") self.bot.remove_cog(self.qualified_name) async def init_cog(self) -> None:", "= await self.get_available_candidate() log.info(f\"Making #{channel} ({channel.id}) available.\") await _message.send_available_message(channel) log.trace(f\"Moving", "their help session; the cooldown role won't be removed\") elif", "self.wait_for_dormant_channel() return channel async def init_available(self) -> None: \"\"\"Initialise the", "not await _message.is_empty(msg.channel): return log.info(f\"Claimant of #{msg.channel} ({msg.author}) deleted message,", "there are no more dormant channels, the bot will automatically", "the channel queue.\") self.channel_queue.put_nowait(channel) _stats.report_counts() @lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"channel\") async def unclaim_channel(self,", "and rescheduling is required, the extant task to make the", "new one * If there are no dormant channels to", "log.trace(f\"{ctx.author} is not the help channel claimant, checking roles.\") has_role", "_message.dm_on_open(message) except Exception as e: log.warning(\"Error occurred while sending DM:\",", "self.bot = bot self.scheduler = scheduling.Scheduler(self.__class__.__name__) # Categories self.available_category: discord.CategoryChannel", "to the queue in a random order. \"\"\" log.trace(\"Creating the", "_channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_available, ) _stats.report_counts() async def move_to_dormant(self, channel: discord.TextChannel)", "await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_available, ) _stats.report_counts() async def move_to_dormant(self, channel:", "cog unloads.\"\"\" log.trace(\"Cog unload: cancelling the init_cog task\") self.init_task.cancel() log.trace(\"Cog", "queue async def create_dormant(self) -> t.Optional[discord.TextChannel]: \"\"\" Create and return", "a dormant channel to become available in the queue and", "return if not await _message.is_empty(msg.channel): return log.info(f\"Claimant of #{msg.channel} ({msg.author})", "= constants.HelpChannels.idle_minutes * 60 else: idle_seconds = constants.HelpChannels.deleted_idle_minutes * 60", "first be cancelled. \"\"\" log.trace(f\"Handling in-use channel #{channel} ({channel.id}).\") if", "allowed to use the command * Allowed roles for the", "self.queue_tasks: task.cancel() self.scheduler.cancel_all() @lock.lock_arg(NAMESPACE, \"message\", attrgetter(\"channel.id\")) @lock.lock_arg(NAMESPACE, \"message\", attrgetter(\"author.id\")) @lock.lock_arg(f\"{NAMESPACE}.unclaim\",", "= await channel_utils.try_get_channel( constants.Categories.help_available ) self.in_use_category = await channel_utils.try_get_channel( constants.Categories.help_in_use", "your own help channel in the Python Help: Available category.", "# Asyncio stuff self.queue_tasks: t.List[asyncio.Task] = [] self.init_task = self.bot.loop.create_task(self.init_cog())", "command are configurable with `constants.HelpChannels.cmd_whitelist` * When a channel becomes", "None: \"\"\"Make a channel in-use and schedule it to be", "\"\"\" log.trace(\"Creating the channel queue.\") channels = list(_channel.get_category_channels(self.dormant_category)) random.shuffle(channels) log.trace(\"Populating", "needing help * Channel moves to dormant category after `constants.HelpChannels.idle_minutes`", "there are no dormant channels to move, helpers will be", "in-use help `channel` to make it dormant. Unpin the claimant's", "datetime, timezone from operator import attrgetter import discord import discord.abc", "channel to the In Use category and pin the `message`.", "= None # Asyncio stuff self.queue_tasks: t.List[asyncio.Task] = [] self.init_task", "we have more than `max_available` channels available, # we should", "asyncio import logging import random import typing as t from", "if missing > 0: log.trace(f\"Moving {missing} missing channels to the", "for channel in channels: queue.put_nowait(channel) return queue async def create_dormant(self)", "channels claimed. Cancel the scheduled cooldown role removal task. Set", "await self.init_categories() await _cooldown.check_cooldowns(self.scheduler) self.channel_queue = self.create_channel_queue() self.name_queue = _name.create_name_queue(", "channel may still be dormant after the cooldown expires. if", "to ensure a correct POSIX timestamp. timestamp = datetime.now(timezone.utc).timestamp() await", "await _message.dm_on_open(message) except Exception as e: log.warning(\"Error occurred while sending", "being used until ready. # The ready event wasn't used", "Help: Available category. \"\"\" class HelpChannels(commands.Cog): \"\"\" Manage the help", "any(claimant.id == user_id for _, user_id in await _caches.claimants.items()): #", "`channel` to make it dormant. Unpin the claimant's question message", "({channel.id}).\") embed = discord.Embed(description=_message.DORMANT_MSG) await channel.send(embed=embed) log.trace(f\"Pushing #{channel} ({channel.id}) into", "dormant after the cooldown expires. if claimant_id in self.scheduler: self.scheduler.cancel(claimant_id)", "cog.\") await self.init_categories() await _cooldown.check_cooldowns(self.scheduler) self.channel_queue = self.create_channel_queue() self.name_queue =", "the queue and return it.\"\"\" log.trace(\"Waiting for a dormant channel.\")", "be available before initialisation.\") await self.bot.wait_until_guild_available() log.trace(\"Initialising the cog.\") await", "-> None: \"\"\"Initialise the help channel system.\"\"\" log.trace(\"Waiting for the", "active. If `has_task` is True and rescheduling is required, the", "has_role = await commands.has_any_role(*constants.HelpChannels.cmd_whitelist).predicate(ctx) if has_role: self.bot.stats.incr(\"help.dormant_invoke.staff\") return has_role @commands.command(name=\"close\",", "random.shuffle(channels) log.trace(\"Populating the channel queue with channels.\") queue = asyncio.Queue()", "we should move the superfluous ones over to dormant. elif", "to get a category; cog will be removed\") self.bot.remove_cog(self.qualified_name) async", "-> None: \"\"\"Move an available channel to the In Use", "async def claim_channel(self, message: discord.Message) -> None: \"\"\" Claim the", "has no other channels left await _cooldown.remove_cooldown_role(claimant) await _message.unpin(channel) await", "_stats from bot.utils import channel as channel_utils, lock, scheduling log", "in the queue; creating a new channel.\") channel = await", "discord.TextChannel, has_task: bool = True) -> None: \"\"\" Make the", "_caches.claimants.delete(channel.id) # Ignore missing tasks because a channel may still", "if has_task: self.scheduler.cancel(channel.id) delay = idle_seconds - time_elapsed log.info( f\"#{channel}", "None: \"\"\" Make the `channel` dormant if idle or schedule", "queue with channels.\") queue = asyncio.Queue() for channel in channels:", "an available channel candidate.\") try: channel = self.channel_queue.get_nowait() except asyncio.QueueEmpty:", "# Cancel existing dormant task before scheduling new. self.scheduler.cancel(msg.channel.id) delay", "with `constants.HelpChannels.cmd_whitelist` * When a channel becomes dormant, an embed", "self.move_idle_channel(channel)) async def move_to_available(self) -> None: \"\"\"Make a channel available.\"\"\"", "is ready (e.g. if move_idle_channel wasn't called yet). # This", "@commands.Cog.listener() async def on_message(self, message: discord.Message) -> None: \"\"\"Move an", "async def init_cog(self) -> None: \"\"\"Initialise the help channel system.\"\"\"", "self.bot.stats.incr(\"help.dormant_invoke.claimant\") return True log.trace(f\"{ctx.author} is not the help channel claimant,", "names are available. \"\"\" log.trace(\"Getting a name for a new", "* Prioritise using the channels which have been dormant for", "e: log.warning(\"Error occurred while sending DM:\", exc_info=e) # Add user", "the help channel system of the guild. The system is", "is_auto: bool = True) -> None: \"\"\" Unclaim an in-use", "is applied conditionally. if claimant_id is not None: decorator =", "== user_id for _, user_id in await _caches.claimants.items()): # Remove", "channel candidate.\") try: channel = self.channel_queue.get_nowait() except asyncio.QueueEmpty: log.info(\"No candidate", "bot: Bot): self.bot = bot self.scheduler = scheduling.Scheduler(self.__class__.__name__) # Categories", "discord.CategoryChannel = None self.in_use_category: discord.CategoryChannel = None self.dormant_category: discord.CategoryChannel =", "`message` was sent. Move the channel to the In Use", "bot self.scheduler = scheduling.Scheduler(self.__class__.__name__) # Categories self.available_category: discord.CategoryChannel = None", "available for new dormant channels.\") return None log.debug(f\"Creating a new", "channel dormant only if called by the close command. #", "task\") self.init_task.cancel() log.trace(\"Cog unload: cancelling the channel queue tasks\") for", "move the superfluous ones over to dormant. elif missing <", "discord.TextChannel: \"\"\" Return a dormant channel to turn into an", "`HelpChannels.deleted_idle_minutes`. \"\"\" await self.init_task if not channel_utils.is_in_category(msg.channel, constants.Categories.help_in_use): return if", "an in-use channel to become dormant sooner if the channel", "-> None: \"\"\"Get the help category objects. Remove the cog", "# the command is invoked and the cog is ready", "check for dormant.\") self.bot.stats.incr(\"help.dormant_invoke.claimant\") return True log.trace(f\"{ctx.author} is not the", "channels.\") for channel in _channel.get_category_channels(self.in_use_category): await self.move_idle_channel(channel, has_task=False) # Prevent", "that makes the channel dormant only if called by the", "channel to become dormant sooner if the channel is empty.", "task before scheduling new. self.scheduler.cancel(msg.channel.id) delay = constants.HelpChannels.deleted_idle_minutes * 60", "# In other cases, the task is either already done", "Return a dormant channel to turn into an available channel.", "log.trace(\"Cog unload: cancelling the init_cog task\") self.init_task.cancel() log.trace(\"Cog unload: cancelling", "the channel's claimant or by staff. \"\"\" # Don't use", "= constants.HelpChannels.max_available - len(channels) # If we've got less than", "self.scheduler.schedule_later(delay, msg.channel.id, self.move_idle_channel(msg.channel)) async def wait_for_dormant_channel(self) -> discord.TextChannel: \"\"\"Wait for", "channel in which the question `message` was sent. Move the", "return a new channel in the Dormant category. The new", "random import typing as t from datetime import datetime, timezone", "delay = idle_seconds - time_elapsed log.info( f\"#{channel} ({channel.id}) is still", "pool of dormant channels * Prioritise using the channels which", "category. The new channel will sync its permission overwrites with", "self.create_dormant() if not channel: log.info(\"Couldn't create a candidate channel; waiting", "await _stats.report_complete_session(channel.id, is_auto) await self.move_to_dormant(channel) # Cancel the task that", "@commands.Cog.listener() async def on_message_delete(self, msg: discord.Message) -> None: \"\"\" Reschedule", "help * Channel moves to dormant category after `constants.HelpChannels.idle_minutes` of", "channels are named after the chemical elements in `bot/resources/elements.json`. \"\"\"", "use * Channels are used to refill the Available category", "`message`. Add a cooldown to the claimant to prevent them", "any. if has_task: self.scheduler.cancel(channel.id) delay = idle_seconds - time_elapsed log.info(", "awaited because it may indefinitely hold the lock while waiting", "conditionally. if claimant_id is not None: decorator = lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"claimant_id\",", "@lock.lock_arg(NAMESPACE, \"message\", attrgetter(\"channel.id\")) @lock.lock_arg(NAMESPACE, \"message\", attrgetter(\"author.id\")) @lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"message\", attrgetter(\"author.id\"), wait=True)", "async def move_to_in_use(self, channel: discord.TextChannel) -> None: \"\"\"Make a channel", "_channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_dormant, ) log.trace(f\"Sending dormant message for #{channel} ({channel.id}).\")", "def on_message_delete(self, msg: discord.Message) -> None: \"\"\" Reschedule an in-use", "a dormant one.\"\"\" if message.author.bot: return # Ignore messages sent", "In Use category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_in_use, ) timeout =", "({channel.id}) into the channel queue.\") self.channel_queue.put_nowait(channel) _stats.report_counts() @lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"channel\") async", "close_check(self, ctx: commands.Context) -> bool: \"\"\"Return True if the channel", "in the Dormant category. The new channel will sync its", "channels to move, helpers will be notified (see `notify()`) *", "{delay} seconds.\" ) self.scheduler.schedule_later(delay, channel.id, self.move_idle_channel(channel)) async def move_to_available(self) ->", "logging import random import typing as t from datetime import", "for task in self.queue_tasks: task.cancel() self.scheduler.cancel_all() @lock.lock_arg(NAMESPACE, \"message\", attrgetter(\"channel.id\")) @lock.lock_arg(NAMESPACE,", "permission overwrites with the category. Return None if no more", "* To keep track of cooldowns, user which claimed a", "* When a channel becomes dormant, an embed with `DORMANT_MSG`", "sec.\") self.scheduler.schedule_later(timeout, channel.id, self.move_idle_channel(channel)) _stats.report_counts() @commands.Cog.listener() async def on_message(self, message:", "import asyncio import logging import random import typing as t", "channels in the queue; creating a new channel.\") channel =", "_, user_id in await _caches.claimants.items()): # Remove the cooldown role", "claimant_id, is_auto) async def _unclaim_channel(self, channel: discord.TextChannel, claimant_id: int, is_auto:", "ones over to dormant. elif missing < 0: log.trace(f\"Moving {abs(missing)}", "IndexError: log.debug(\"No more names available for new dormant channels.\") return", "to dormant category after `constants.HelpChannels.idle_minutes` of being idle * Command", "Unclaim an in-use help `channel` to make it dormant. Unpin", "-> discord.TextChannel: \"\"\"Wait for a dormant channel to become available", "decorator(_unclaim_channel) return await _unclaim_channel(channel, claimant_id, is_auto) async def _unclaim_channel(self, channel:", "help channel claimant, passing the check for dormant.\") self.bot.stats.incr(\"help.dormant_invoke.claimant\") return", "discord.py check because the check needs to fail silently. if", "dormant for the longest amount of time * If there", "wait indefinitely until one becomes available. \"\"\" log.trace(\"Getting an available", "Available category with channels.\"\"\" log.trace(\"Initialising the Available category with channels.\")", "self.name_queue = _name.create_name_queue( self.available_category, self.in_use_category, self.dormant_category, ) log.trace(\"Moving or rescheduling", "Cancel the task that makes the channel dormant only if", "dormant.\") self.bot.stats.incr(\"help.dormant_invoke.claimant\") return True log.trace(f\"{ctx.author} is not the help channel", "_stats.report_counts() @commands.Cog.listener() async def on_message(self, message: discord.Message) -> None: \"\"\"Move", "the pool of dormant channels * Prioritise using the channels", "discord.CategoryChannel = None self.dormant_category: discord.CategoryChannel = None # Queues self.channel_queue:", "available, wait indefinitely until one becomes available. \"\"\" log.trace(\"Getting an", "channel. scheduling.create_task(self.move_to_available(), name=f\"help_claim_{message.id}\") def create_channel_queue(self) -> asyncio.Queue: \"\"\" Return a", "claimant_id in self.scheduler: self.scheduler.cancel(claimant_id) claimant = self.bot.get_guild(constants.Guild.id).get_member(claimant_id) if claimant is", "from datetime import datetime, timezone from operator import attrgetter import", "self.channel_queue.get_nowait() except asyncio.QueueEmpty: log.info(\"No candidate channels in the queue; creating", "contain `constants.HelpChannels.max_available` channels; refilled automatically from the pool of dormant", "cancelling the channel queue tasks\") for task in self.queue_tasks: task.cancel()", "None: \"\"\"Cancel the init task and scheduled tasks when the", "dormant one.\"\"\" if message.author.bot: return # Ignore messages sent by", "Set `is_auto` to True if the channel was automatically closed", "message.author.bot: return # Ignore messages sent by bots. await self.init_task", "def create_channel_queue(self) -> asyncio.Queue: \"\"\" Return a queue of dormant", "cooldown role removal task. Set `is_auto` to True if the", "import typing as t from datetime import datetime, timezone from", "queue; creating a new channel.\") channel = await self.create_dormant() if", "the help category objects. Remove the cog if retrieval fails.\"\"\"", "category. Return None if no more channel names are available.", "move if still active. If `has_task` is True and rescheduling", "_unclaim_channel(self, channel: discord.TextChannel, claimant_id: int, is_auto: bool) -> None: \"\"\"Actual", "in-use channels.\") for channel in _channel.get_category_channels(self.in_use_category): await self.move_idle_channel(channel, has_task=False) #", "order. \"\"\" log.trace(\"Creating the channel queue.\") channels = list(_channel.get_category_channels(self.dormant_category)) random.shuffle(channels)", "for a dormant channel.\") task = asyncio.create_task(self.channel_queue.get()) self.queue_tasks.append(task) channel =", "import channel as channel_utils, lock, scheduling log = logging.getLogger(__name__) NAMESPACE", "may confuse users. So would potentially long delays for the", "Command can prematurely mark a channel as dormant * Channel", "missing = constants.HelpChannels.max_available - len(channels) # If we've got less", "category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_available, ) _stats.report_counts() async def move_to_dormant(self,", "_name.create_name_queue( self.available_category, self.in_use_category, self.dormant_category, ) log.trace(\"Moving or rescheduling in-use channels.\")", "`constants.HelpChannels.claim_minutes` * To keep track of cooldowns, user which claimed", "Python help channel. You can claim your own help channel", "is the help channel claimant, passing the check for dormant.\")", "another question. Lastly, make a new channel available. \"\"\" log.info(f\"Channel", "a timezone-aware datetime to ensure a correct POSIX timestamp. timestamp", "one * If there are no dormant channels to move,", "log.trace(\"Moving or rescheduling in-use channels.\") for channel in _channel.get_category_channels(self.in_use_category): await", "The channels are added to the queue in a random", "after the chemical elements in `bot/resources/elements.json`. \"\"\" def __init__(self, bot:", "before initialisation.\") await self.bot.wait_until_guild_available() log.trace(\"Initialising the cog.\") await self.init_categories() await", "is empty now. Rescheduling task.\") # Cancel existing dormant task", "with channel for dormant check. await _caches.claimants.set(message.channel.id, message.author.id) self.bot.stats.incr(\"help.claimed\") #", "message.author.id) self.bot.stats.incr(\"help.claimed\") # Must use a timezone-aware datetime to ensure", "moved after {delay} seconds.\" ) self.scheduler.schedule_later(delay, channel.id, self.move_idle_channel(channel)) async def", "self.bot.remove_cog(self.qualified_name) async def init_cog(self) -> None: \"\"\"Initialise the help channel", "\"\"\" class HelpChannels(commands.Cog): \"\"\" Manage the help channel system of", "not-existent. if not is_auto: self.scheduler.cancel(channel.id) async def move_to_in_use(self, channel: discord.TextChannel)", "sent. Move the channel to the In Use category and", "be edited to show `AVAILABLE_MSG` * User can only claim", "self.move_idle_channel(channel)) _stats.report_counts() @commands.Cog.listener() async def on_message(self, message: discord.Message) -> None:", "possibly incorrect to lock on None. Therefore, the lock is", "such case, it'd be useless and # possibly incorrect to", "move the channel to the Dormant category. Remove the cooldown", "role from the channel claimant if they have no other", "channel to the Dormant category. Remove the cooldown role from", "which are ready to be occupied by someone who needs", "messages sent by bots. await self.init_task if channel_utils.is_in_category(message.channel, constants.Categories.help_available): if", "Create and return a new channel in the Dormant category.", "msg: discord.Message) -> None: \"\"\" Reschedule an in-use channel to", "_name, _stats from bot.utils import channel as channel_utils, lock, scheduling", "await channel_utils.try_get_channel( constants.Categories.help_in_use ) self.dormant_category = await channel_utils.try_get_channel( constants.Categories.help_dormant )", "constants.Categories.help_in_use): return if not await _message.is_empty(msg.channel): return log.info(f\"Claimant of #{msg.channel}", "-> None: \"\"\"Make the `channel` dormant.\"\"\" log.info(f\"Moving #{channel} ({channel.id}) to", "wait_for_dormant_channel(self) -> discord.TextChannel: \"\"\"Wait for a dormant channel to become", "show `AVAILABLE_MSG` * User can only claim a channel at", "# Cancel the existing task, if any. if has_task: self.scheduler.cancel(channel.id)", "next available channel. The channels are added to the queue", "self.dormant_category = await channel_utils.try_get_channel( constants.Categories.help_dormant ) except discord.HTTPException: log.exception(\"Failed to", "the question `message` was sent. Move the channel to the", "`constants.HelpChannels.cmd_whitelist` * When a channel becomes dormant, an embed with", "to be occupied by someone who needs help * Will", "self.init_task if not channel_utils.is_in_category(msg.channel, constants.Categories.help_in_use): return if not await _message.is_empty(msg.channel):", "60 time_elapsed = await _channel.get_idle_time(channel) if time_elapsed is None or", "a Python help channel. You can claim your own help", "is available, wait indefinitely until one becomes available. \"\"\" log.trace(\"Getting", "is idle longer than {idle_seconds} seconds \" f\"and will be", "async def move_to_available(self) -> None: \"\"\"Make a channel available.\"\"\" log.trace(\"Making", "60 else: idle_seconds = constants.HelpChannels.deleted_idle_minutes * 60 time_elapsed = await", "log.info( f\"#{channel} ({channel.id}) is idle longer than {idle_seconds} seconds \"", "track of cooldowns, user which claimed a channel will have", "if ctx.channel.category != self.in_use_category: log.debug(f\"{ctx.author} invoked command 'close' outside an", "stuff self.queue_tasks: t.List[asyncio.Task] = [] self.init_task = self.bot.loop.create_task(self.init_cog()) def cog_unload(self)", "_caches.claimants.set(message.channel.id, message.author.id) self.bot.stats.incr(\"help.claimed\") # Must use a timezone-aware datetime to", "cooldown to the claimant to prevent them from asking another", "dormant category after `constants.HelpChannels.idle_minutes` of being idle * Command can", "available channel candidate.\") try: channel = self.channel_queue.get_nowait() except asyncio.QueueEmpty: log.info(\"No", "await _caches.claimants.set(message.channel.id, message.author.id) self.bot.stats.incr(\"help.claimed\") # Must use a timezone-aware datetime", "channel available.\"\"\" log.trace(\"Making a channel available.\") channel = await self.get_available_candidate()", "True await self.init_available() _stats.report_counts() log.info(\"Cog is ready!\") async def move_idle_channel(self,", "the help channel system.\"\"\" log.trace(\"Waiting for the guild to be", "for the longest amount of time * If there are", "is True and rescheduling is required, the extant task to", "claimant, passing the check for dormant.\") self.bot.stats.incr(\"help.dormant_invoke.claimant\") return True log.trace(f\"{ctx.author}", "category_id=constants.Categories.help_in_use, ) timeout = constants.HelpChannels.idle_minutes * 60 log.trace(f\"Scheduling #{channel} ({channel.id})", ") await self.unclaim_channel(channel) else: # Cancel the existing task, if", "the channel queue with channels.\") queue = asyncio.Queue() for channel", "claimant or has a whitelisted role.\"\"\" if ctx.channel.category != self.in_use_category:", "and replace it with a dormant one.\"\"\" if message.author.bot: return", "has a whitelisted role.\"\"\" if ctx.channel.category != self.in_use_category: log.debug(f\"{ctx.author} invoked", "import discord import discord.abc from discord.ext import commands from bot", "in which the question `message` was sent. Move the channel", "> 0: log.trace(f\"Moving {missing} missing channels to the Available category.\")", "the cooldown role won't be removed\") elif not any(claimant.id ==", "NAMESPACE = \"help\" HELP_CHANNEL_TOPIC = \"\"\" This is a Python", "longest amount of time * If there are no more", "channel = await self.wait_for_dormant_channel() return channel async def init_available(self) ->", "\"\"\"Initialise the help channel system.\"\"\" log.trace(\"Waiting for the guild to", "\"\"\" log.trace(\"Getting a name for a new dormant channel.\") try:", "commands.Context) -> None: \"\"\" Make the current in-use help channel", "a discord.py check because the check needs to fail silently.", "based on a 3-category system: Available Category * Contains channels", "_stats.report_counts() @lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"channel\") async def unclaim_channel(self, channel: discord.TextChannel, *, is_auto:", "channels which are occupied by someone needing help * Channel", "= None self.in_use_category: discord.CategoryChannel = None self.dormant_category: discord.CategoryChannel = None", "is configured with `HelpChannels.deleted_idle_minutes`. \"\"\" await self.init_task if not channel_utils.is_in_category(msg.channel,", "In other cases, the task is either already done or", "for new dormant channels.\") return None log.debug(f\"Creating a new dormant", "wait=True) async def claim_channel(self, message: discord.Message) -> None: \"\"\" Claim", "help channel claimant, checking roles.\") has_role = await commands.has_any_role(*constants.HelpChannels.cmd_whitelist).predicate(ctx) if", "channel_utils.is_in_category(message.channel, constants.Categories.help_available): if not _channel.is_excluded_channel(message.channel): await self.claim_channel(message) else: await _message.check_for_answer(message)", "return has_role @commands.command(name=\"close\", aliases=[\"dormant\", \"solved\"], enabled=False) async def close_command(self, ctx:", "move_to_available(self) -> None: \"\"\"Make a channel available.\"\"\" log.trace(\"Making a channel", "or not-existent. if not is_auto: self.scheduler.cancel(channel.id) async def move_to_in_use(self, channel:", "for channel in channels[:abs(missing)]: await self.unclaim_channel(channel) async def init_categories(self) ->", "@lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"channel\") async def unclaim_channel(self, channel: discord.TextChannel, *, is_auto: bool", "user with channel for dormant check. await _caches.claimants.set(message.channel.id, message.author.id) self.bot.stats.incr(\"help.claimed\")", "used because channels could change categories between the time #", "makes the channel dormant only if called by the close", "`DORMANT_MSG` will be sent Dormant Category * Contains channels which", "`{message.author.id}`.\") await self.move_to_in_use(message.channel) await _cooldown.revoke_send_permissions(message.author, self.scheduler) await _message.pin(message) try: await", "channel claimant if they have no other channels claimed. Cancel", "cog_unload(self) -> None: \"\"\"Cancel the init task and scheduled tasks", "schedule the move if still active. If `has_task` is True", "command 'close' outside an in-use help channel\") return False if", "cancelling the init_cog task\") self.init_task.cancel() log.trace(\"Cog unload: cancelling the channel", "in-use help channel dormant. May only be invoked by the", "have been dormant for the longest amount of time *", "self.channel_queue.put_nowait(channel) _stats.report_counts() @lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"channel\") async def unclaim_channel(self, channel: discord.TextChannel, *,", "channel was automatically closed or False if manually closed. \"\"\"", "= list(_channel.get_category_channels(self.available_category)) missing = constants.HelpChannels.max_available - len(channels) # If we've", "one becomes available. \"\"\" log.trace(\"Getting an available channel candidate.\") try:", "discord.Message) -> None: \"\"\"Move an available channel to the In", "claimant = self.bot.get_guild(constants.Guild.id).get_member(claimant_id) if claimant is None: log.info(f\"{claimant_id} left the", "< 0: log.trace(f\"Moving {abs(missing)} superfluous available channels over to the", "If for some reason we have more than `max_available` channels", "the next available channel. The channels are added to the", "time * If there are no more dormant channels, the", "for dormant check. await _caches.claimants.set(message.channel.id, message.author.id) self.bot.stats.incr(\"help.claimed\") # Must use", "= decorator(_unclaim_channel) return await _unclaim_channel(channel, claimant_id, is_auto) async def _unclaim_channel(self,", "channel available.\") channel = await self.get_available_candidate() log.info(f\"Making #{channel} ({channel.id}) available.\")", "await channel_utils.try_get_channel( constants.Categories.help_dormant ) except discord.HTTPException: log.exception(\"Failed to get a", "({channel.id}) available.\") await _message.send_available_message(channel) log.trace(f\"Moving #{channel} ({channel.id}) to the Available", "user is the claimant or has a whitelisted role.\"\"\" if", "The new channel will sync its permission overwrites with the", "available.\") await _message.send_available_message(channel) log.trace(f\"Moving #{channel} ({channel.id}) to the Available category.\")", "False if manually closed. \"\"\" claimant_id = await _caches.claimants.get(channel.id) _unclaim_channel", "after `constants.HelpChannels.idle_minutes` of being idle * Command can prematurely mark", "by {ctx.author} in #{ctx.channel}.\") await self.unclaim_channel(ctx.channel, is_auto=False) async def get_available_candidate(self)", "Available category with channels.\") channels = list(_channel.get_category_channels(self.available_category)) missing = constants.HelpChannels.max_available", "one from the queue.\") notify_channel = self.bot.get_channel(constants.HelpChannels.notify_channel) last_notification = await", "time_elapsed log.info( f\"#{channel} ({channel.id}) is still active; \" f\"scheduling it", "claimant, checking roles.\") has_role = await commands.has_any_role(*constants.HelpChannels.cmd_whitelist).predicate(ctx) if has_role: self.bot.stats.incr(\"help.dormant_invoke.staff\")", "import random import typing as t from datetime import datetime,", "_cooldown.check_cooldowns(self.scheduler) self.channel_queue = self.create_channel_queue() self.name_queue = _name.create_name_queue( self.available_category, self.in_use_category, self.dormant_category,", "channel_utils.try_get_channel( constants.Categories.help_in_use ) self.dormant_category = await channel_utils.try_get_channel( constants.Categories.help_dormant ) except", "available.\") channel = await self.get_available_candidate() log.info(f\"Making #{channel} ({channel.id}) available.\") await", "the cog if retrieval fails.\"\"\" log.trace(\"Getting the CategoryChannel objects for", "full documentation.\"\"\" await _caches.claimants.delete(channel.id) # Ignore missing tasks because a", "be cancelled. \"\"\" log.trace(f\"Handling in-use channel #{channel} ({channel.id}).\") if not", "interval `constants.HelpChannels.claim_minutes` * To keep track of cooldowns, user which", "cached. In such case, it'd be useless and # possibly", "other channels claimed. Cancel the scheduled cooldown role removal task.", "from the queue.\") notify_channel = self.bot.get_channel(constants.HelpChannels.notify_channel) last_notification = await _message.notify(notify_channel,", "have more than `max_available` channels available, # we should move", "import _caches, _channel, _cooldown, _message, _name, _stats from bot.utils import", "an available channel to the In Use category and replace", "async def on_message_delete(self, msg: discord.Message) -> None: \"\"\" Reschedule an", "-> None: \"\"\"Cancel the init task and scheduled tasks when", "last_notification self.bot.stats.incr(\"help.out_of_channel_alerts\") channel = await self.wait_for_dormant_channel() return channel async def", "tasks when the cog unloads.\"\"\" log.trace(\"Cog unload: cancelling the init_cog", "{missing} missing channels to the Available category.\") for _ in", "= last_notification self.bot.stats.incr(\"help.out_of_channel_alerts\") channel = await self.wait_for_dormant_channel() return channel async", "asyncio.Queue: \"\"\" Return a queue of dormant channels to use", "queue = asyncio.Queue() for channel in channels: queue.put_nowait(channel) return queue", "dormant if idle or schedule the move if still active.", "Contains channels which aren't in use * Channels are used", "Reschedule an in-use channel to become dormant sooner if the", "`AVAILABLE_MSG` * User can only claim a channel at an", "prematurely mark a channel as dormant * Channel claimant is", "a correct POSIX timestamp. timestamp = datetime.now(timezone.utc).timestamp() await _caches.claim_times.set(message.channel.id, timestamp)", "channels over to the Dormant category.\") for channel in channels[:abs(missing)]:", "help channel in the Python Help: Available category. \"\"\" class", "self.close_check(ctx): log.info(f\"Close command invoked by {ctx.author} in #{ctx.channel}.\") await self.unclaim_channel(ctx.channel,", "which the question `message` was sent. Move the channel to", "await _cooldown.revoke_send_permissions(message.author, self.scheduler) await _message.pin(message) try: await _message.dm_on_open(message) except Exception", "the In Use category.\") await _channel.move_to_bottom( channel=channel, category_id=constants.Categories.help_in_use, ) timeout", "await _caches.claimants.get(ctx.channel.id) == ctx.author.id: log.trace(f\"{ctx.author} is the help channel claimant,", "from bot.bot import Bot from bot.exts.help_channels import _caches, _channel, _cooldown,", "self.queue_tasks: t.List[asyncio.Task] = [] self.init_task = self.bot.loop.create_task(self.init_cog()) def cog_unload(self) ->", "log.warning(\"Error occurred while sending DM:\", exc_info=e) # Add user with", "if not await _message.is_empty(msg.channel): return log.info(f\"Claimant of #{msg.channel} ({msg.author}) deleted", "not None: decorator = lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"claimant_id\", wait=True) _unclaim_channel = decorator(_unclaim_channel)", "* If there are no dormant channels to move, helpers", "are available. \"\"\" log.trace(\"Getting a name for a new dormant", "claimant or by staff. \"\"\" # Don't use a discord.py", "dormant only if called by the close command. # In", "embed will be edited to show `AVAILABLE_MSG` * User can", "Cancel existing dormant task before scheduling new. self.scheduler.cancel(msg.channel.id) delay =", "self.scheduler.cancel(channel.id) delay = idle_seconds - time_elapsed log.info( f\"#{channel} ({channel.id}) is", "available before initialisation.\") await self.bot.wait_until_guild_available() log.trace(\"Initialising the cog.\") await self.init_categories()", "= [] self.init_task = self.bot.loop.create_task(self.init_cog()) def cog_unload(self) -> None: \"\"\"Cancel", "_caches.claimants.get(ctx.channel.id) == ctx.author.id: log.trace(f\"{ctx.author} is the help channel claimant, passing", "the In Use category and pin the `message`. Add a", "a category; cog will be removed\") self.bot.remove_cog(self.qualified_name) async def init_cog(self)", "system: Available Category * Contains channels which are ready to", "category and replace it with a dormant one.\"\"\" if message.author.bot:", "them from asking another question. Lastly, make a new channel", "dormant message for #{channel} ({channel.id}).\") embed = discord.Embed(description=_message.DORMANT_MSG) await channel.send(embed=embed)", "be made dormant.\"\"\" log.info(f\"Moving #{channel} ({channel.id}) to the In Use", "the queue; creating a new channel.\") channel = await self.create_dormant()", "channels.\") return None log.debug(f\"Creating a new dormant channel named {name}.\")", "-> None: \"\"\"Make a channel available.\"\"\" log.trace(\"Making a channel available.\")", "Category * Contains channels which are ready to be occupied", "temporary role In Use Category * Contains all channels which", "self.queue_tasks.append(task) channel = await task log.trace(f\"Channel #{channel} ({channel.id}) finally retrieved", "to turn into an available channel. If no channel is", "init_available(self) -> None: \"\"\"Initialise the Available category with channels.\"\"\" log.trace(\"Initialising", "help * Will always contain `constants.HelpChannels.max_available` channels; refilled automatically from", "invoked by the channel's claimant or by staff. \"\"\" #", "= constants.HelpChannels.deleted_idle_minutes * 60 self.scheduler.schedule_later(delay, msg.channel.id, self.move_idle_channel(msg.channel)) async def wait_for_dormant_channel(self)", "`constants.HelpChannels.idle_minutes` of being idle * Command can prematurely mark a", "to prevent them from asking another question. Lastly, make a", "\"\"\" log.trace(\"Getting an available channel candidate.\") try: channel = self.channel_queue.get_nowait()", "is the claimant or has a whitelisted role.\"\"\" if ctx.channel.category", "in self.queue_tasks: task.cancel() self.scheduler.cancel_all() @lock.lock_arg(NAMESPACE, \"message\", attrgetter(\"channel.id\")) @lock.lock_arg(NAMESPACE, \"message\", attrgetter(\"author.id\"))", "get a category; cog will be removed\") self.bot.remove_cog(self.qualified_name) async def", "than {idle_seconds} seconds \" f\"and will be made dormant.\" )", "to fail silently. if await self.close_check(ctx): log.info(f\"Close command invoked by", "creating a new channel.\") channel = await self.create_dormant() if not", "In Use category and pin the `message`. Add a cooldown", "log.exception(\"Failed to get a category; cog will be removed\") self.bot.remove_cog(self.qualified_name)", "the dormant task is configured with `HelpChannels.deleted_idle_minutes`. \"\"\" await self.init_task", "the claimant or has a whitelisted role.\"\"\" if ctx.channel.category !=", "that there is no claimant cached. In such case, it'd", "channel will sync its permission overwrites with the category. Return", "for a new dormant channel.\") try: name = self.name_queue.popleft() except", "Category * Contains all channels which are occupied by someone", "_stats.report_counts() async def move_to_dormant(self, channel: discord.TextChannel) -> None: \"\"\"Make the", "CategoryChannel objects for the help categories.\") try: self.available_category = await", ") timeout = constants.HelpChannels.idle_minutes * 60 log.trace(f\"Scheduling #{channel} ({channel.id}) to", "was automatically closed or False if manually closed. \"\"\" claimant_id", "log.trace(f\"Pushing #{channel} ({channel.id}) into the channel queue.\") self.channel_queue.put_nowait(channel) _stats.report_counts() @lock.lock_arg(f\"{NAMESPACE}.unclaim\",", "has_role @commands.command(name=\"close\", aliases=[\"dormant\", \"solved\"], enabled=False) async def close_command(self, ctx: commands.Context)", "#{channel} ({channel.id}) available.\") await _message.send_available_message(channel) log.trace(f\"Moving #{channel} ({channel.id}) to the", "no other channels claimed. Cancel the scheduled cooldown role removal", "or False if manually closed. \"\"\" claimant_id = await _caches.claimants.get(channel.id)", "in-use channel to become dormant sooner if the channel is", "def unclaim_channel(self, channel: discord.TextChannel, *, is_auto: bool = True) ->", "channel #{channel} ({channel.id}).\") if not await _message.is_empty(channel): idle_seconds = constants.HelpChannels.idle_minutes", "None: decorator = lock.lock_arg(f\"{NAMESPACE}.unclaim\", \"claimant_id\", wait=True) _unclaim_channel = decorator(_unclaim_channel) return", "bot.utils import channel as channel_utils, lock, scheduling log = logging.getLogger(__name__)", "be removed\") self.bot.remove_cog(self.qualified_name) async def init_cog(self) -> None: \"\"\"Initialise the", "log.trace(f\"Scheduling #{channel} ({channel.id}) to become dormant in {timeout} sec.\") self.scheduler.schedule_later(timeout,", "channel. The channels are added to the queue in a", "cooldown role if the claimant has no other channels left", "-> asyncio.Queue: \"\"\" Return a queue of dormant channels to", "({msg.author}) deleted message, channel is empty now. Rescheduling task.\") #", "available, the dormant embed will be edited to show `AVAILABLE_MSG`", "in await _caches.claimants.items()): # Remove the cooldown role if the", "idle_seconds = constants.HelpChannels.deleted_idle_minutes * 60 time_elapsed = await _channel.get_idle_time(channel) if", "message: discord.Message) -> None: \"\"\" Claim the channel in which", "in the queue and return it.\"\"\" log.trace(\"Waiting for a dormant", "become available in the queue and return it.\"\"\" log.trace(\"Waiting for", "int, is_auto: bool) -> None: \"\"\"Actual implementation of `unclaim_channel`. See", "the task is either already done or not-existent. if not" ]
[ ") # We're going to keep a handle to the", ") # Fetch the appropriate template for an individual item", "= int( options[\"min-quality\"] ) if ( \"max-quality\" in options ):", "# Check for an onpurchase script (perhaps the game reacts", "vendor... self.vendor.remove_erstwhile_acquired_items_from_inventory(universe) # Populate inventory for this shoppe's vendor... self.vendor.populate_vendor_inventory(", "have just bought their last item... if ( self.vendor.get_vendor_inventory_count() ==", "the active map m = universe.get_active_map() # Check for a", "# Let's just go back one page self.page_back(1) # Leave", "Return events return results # Go back a page (animated)", "pause splash control_center.get_splash_controller().set_mode(SPLASH_MODE_GREYSCALE_ANIMATED) # Before populating the vendor's inventory (or", "that result from handling this event (on-birth events, etc.) results", "\"shop.directory\", version = \"default\" ).add_parameters({ \"@x\": xml_encode( \"%d\" % (SCREEN_WIDTH", "widget widget = widget_dispatcher.convert_node_to_widget(root, control_center, universe) widget.set_id(\"root\") # We have", "Convenience params = event.get_params() # Get a reference to the", "}) # Compile template root = template.compile_node_by_id(\"menu\") # Create widget", "{ \"@m\": item.get_title(), \"@n\": self.vendor.nick, \"@g\": item.get_cost() } ) #\"Bought", "page.hide( on_complete = \"previous-page\" ) # Return events return results", "xml_encode( \"%d\" % PAUSE_MENU_HEIGHT ), \"@shop-title\": xml_encode( self.title ) })", "item.get_cost() ) ) # Remove from seller's inventory self.vendor.remove_item_from_vendor_inventory( item.get_name()", "handle to the seller so that we can # remove", "( action == \"resume-game\" ): results.append( self.handle_resume_game_event(event, control_center, universe) )", "results.append( self.handle_build_event(event, control_center, universe) ) # Select an item, get", "resume game elif ( action == \"resume-game\" ): results.append( self.handle_resume_game_event(event,", "= 1 # Track whether this is the first build", "data # to determine which template we load... if (", "xml_encode( item.name ), \"@item-title\": xml_encode( item.title ), \"@item-cost\": xml_encode( \"%d\"", "1 # Track whether this is the first build or", "an individual item template = self.fetch_xml_template( \"shop.directory.insert\", version = template_version", "rebuilding the UI, we will have restocked the NPC's inventory.", "xml_encode( self.title ), \"@salutation\": xml_encode( self.message ) }) # Compile", "event. Set game status back to active when shopping is", "effect self.lightbox_controller.set_target(0) # Dismiss the splash controller, calling to resume", "that result from event handling results = EventQueue() # Convenience", "= universe.get_item_by_name( params[\"item-name\"] ) # Acquire the item by its", "just bought their last item... if ( self.vendor.get_vendor_inventory_count() == 0", "is done. def handle_kill_event(self, event, control_center, universe): # Events that", "self.vendor.nick, \"@g\": item.get_cost() } ) #\"Bought [color=special]%s[/color] for [color=special]%s[/color] gold.\"", "xml_encode( self.title ) }) # Compile template root = template.compile_node_by_id(\"menu\")", "self.min_item_quality = 0 self.max_item_quality = 0 # Items in stock", "options[\"title\"] if ( \"message\" in options ): self.message = options[\"message\"]", "universe, active_map, session, widget_dispatcher, text_renderer, save_controller, refresh = False): #", "name universe.acquire_item_by_name( item.get_name() ) # Post a newsfeeder notice control_center.get_window_controller().get_newsfeeder().post({", "universe.get_item_by_name( params[\"item-name\"] ) # Validate if (item): # Fetch confirm", "status back to active when shopping is done. def handle_kill_event(self,", "Use this data # to determine which template we load...", "# Fetch the \"nothing in stock\" template template = self.fetch_xml_template(", "code.constants.states import STATUS_ACTIVE, STATUS_INACTIVE, GAME_STATE_ACTIVE, GAME_STATE_NOT_READY from code.constants.newsfeeder import *", "control_center ) # Get the active map m = universe.get_active_map()", "item.get_cost() ) # Count as gold spent universe.increment_session_variable( \"stats.gold-spent\", item.get_cost()", "NEWS_ITEM_NEW, \"title\": control_center.get_localization_controller().get_label(\"new-item-purchased:header\"), \"content\": item.get_title() }) # Add a historical", "going to set the cursor at \"home\" position for the", "\"kill\" ) # Return events return results # Kill event.", "= True # Fire build event self.fire_event(\"build\") def handle_event(self, event,", "any items the player has acquired since last shopping with", "item.get_name() ) # Post a newsfeeder notice control_center.get_window_controller().get_newsfeeder().post({ \"type\": NEWS_ITEM_NEW,", "if the NPC has no inventory available, we have just", "DIR_DOWN, DIR_LEFT, SPLASH_MODE_GREYSCALE_ANIMATED from code.constants.states import STATUS_ACTIVE, STATUS_INACTIVE, GAME_STATE_ACTIVE, GAME_STATE_NOT_READY", "first build or a refresh self.first_build = True # Fire", "completed the first build now self.first_build = False # Add", "in options ): self.max_item_reloads = int( options[\"max-reloads\"] ) # For", "control_center, universe):#params, user_input, network_controller, universe, active_map, session, widget_dispatcher, text_renderer, save_controller,", "TILE_HEIGHT, DIR_UP, DIR_RIGHT, DIR_DOWN, DIR_LEFT, SPLASH_MODE_GREYSCALE_ANIMATED from code.constants.states import STATUS_ACTIVE,", "template we load... if ( self.vendor.get_vendor_inventory_count() == 0 ): #", "Create widget widget = widget_dispatcher.convert_node_to_widget(root, control_center, universe) widget.set_id(\"confirm-shop-purchase\") # Add", "menu, we'll first # make sure the NPC seller stocks", "stock at any given time self.max_items_stocked = 1 # Number", "the new page self.add_widget_via_event(widget, event) # Return events return results", "params = event.get_params() # Get a reference to the item", "the \"wallet-changed\" achievement hook universe.execute_achievement_hook( \"wallet-changed\", control_center ) # Increase", "text_renderer, save_controller, refresh = False): # Events that result from", "1.0) #row_menu.slide(DIR_RIGHT, percent = 1.0) # Resume game, killing shop", "buy this?\" page def handle_show_confirm_purchase_event(self, event, control_center, universe): # Events", "params = event.get_params() # Done with the shop menu widget;", "\"bought-item\" achievement hook universe.execute_achievement_hook( \"bought-item\", control_center ) # Get the", "# Fetch the widget dispatcher widget_dispatcher = control_center.get_widget_dispatcher() # Get", "self.min_item_quality,#int( node.get_attribute(\"min-quality\") ), max_quality = self.max_item_quality,#int( node.get_attribute(\"min-quality\") ), required_item_names =", "( \"max-items\" in options ): self.max_items_stocked = int( options[\"max-items\"] )", "the player has acquired since last shopping with this vendor...", "DIR_LEFT, SPLASH_MODE_GREYSCALE_ANIMATED from code.constants.states import STATUS_ACTIVE, STATUS_INACTIVE, GAME_STATE_ACTIVE, GAME_STATE_NOT_READY from", "( action == \"kill\" ): results.append( self.handle_kill_event(event, control_center, universe) )", "template root = template.compile_node_by_id(\"menu\") # Create widget widget = widget_dispatcher.convert_node_to_widget(root,", "( item.get_title(), item.get_cost() ) ) # Remove from seller's inventory", "= \"Take a look at my inventory.\" # Before we", "this vendor... self.vendor.remove_erstwhile_acquired_items_from_inventory(universe) # Populate inventory for this shoppe's vendor...", "( action == \"previous-page\" ): # Let's just go back", "shop menu when widget disappears self.get_widget_by_id(\"root\").hide( on_complete = \"kill\" )", "great items\") self.message = \"Take a look at my inventory.\"", "# Go back a page (animated) def handle_back_event(self, event, control_center,", "self.required_item_names = [] # Track item quality threshholds (low and", "to the actual item... item = universe.get_item_by_name( params[\"item-name\"] ) #", "elif ( action == \"resume-game\" ): results.append( self.handle_resume_game_event(event, control_center, universe)", "determine which template we load... if ( self.vendor.get_vendor_inventory_count() == 0", "\"%d\" % SCREEN_HEIGHT ), \"@item-name\": xml_encode( item.get_name() ), \"@item-title\": xml_encode(", "time from code.menu.menu import Menu from code.tools.eventqueue import EventQueue from", "# Dismiss the page page.hide( on_complete = \"previous-page\" ) #", "item.get_title() }) # Add a historical record universe.add_historical_record( \"purchases\", control_center.get_localization_controller().get_label(", "if ( \"required-item-names\" in options ): self.required_item_names.extend( options[\"required-item-names\"] )#.split(\";\") )", "__init__(self): Menu.__init__(self) # Assume all shop menus come from already-lightboxed", "= EventQueue() # Convenience params = event.get_params() # Fetch the", "= self.max_item_quality,#int( node.get_attribute(\"min-quality\") ), required_item_names = self.required_item_names, max_items = self.max_items_stocked,#int(", "options[\"max-quality\"] ) if ( \"max-items\" in options ): self.max_items_stocked =", "previous page (e.g. close buy item confirm dialog) elif (", "new page self.add_widget_via_event(widget, event) # Return events return results #", "on_complete = \"kill\" ) # Return events return results #", "DIR_RIGHT, DIR_DOWN, DIR_LEFT, SPLASH_MODE_GREYSCALE_ANIMATED from code.constants.states import STATUS_ACTIVE, STATUS_INACTIVE, GAME_STATE_ACTIVE,", "widget_dispatcher.convert_node_to_widget(root, control_center, universe) widget.set_id(\"confirm-shop-purchase\") # Add the new page self.add_widget_via_event(widget,", ") # Get the active map m = universe.get_active_map() #", "For chaining return self # Build the shop menu def", "1.0) # Resume game, killing shop menu when widget disappears", "has acquired since last shopping with this vendor... self.vendor.remove_erstwhile_acquired_items_from_inventory(universe) #", "self.handle_back_event(event, control_center, universe) ) # Finalize a \"back\" call elif", "this?\" page def handle_show_confirm_purchase_event(self, event, control_center, universe): # Events that", "options ): self.max_item_reloads = int( options[\"max-reloads\"] ) # For chaining", "have restocked the NPC's inventory. # Thus, if the NPC", "depends on whether we can afford it... template_version = (", "SCREEN_WIDTH, SCREEN_HEIGHT, PAUSE_MENU_X, PAUSE_MENU_Y, PAUSE_MENU_WIDTH, PAUSE_MENU_HEIGHT, MODE_GAME, TILE_WIDTH, TILE_HEIGHT, DIR_UP,", "self.vendor = options[\"vendor\"] if ( \"title\" in options ): self.title", "for the vendor m.run_script( \"%s.onpurchase\" % self.vendor.get_name(), control_center, universe, execute_all", "template = self.fetch_xml_template(\"shop.buy.confirm\").add_parameters({ \"@width\": xml_encode( \"%d\" % int(PAUSE_MENU_WIDTH / 2)", "= \"default\" ).add_parameters({ \"@x\": xml_encode( \"%d\" % (SCREEN_WIDTH - (int(", "self.max_items_stocked = 1 # Number of times the vendor can", "an item purchase elif ( action == \"game:buy-item\" ): results.append(", "results.append( self.handle_back_event(event, control_center, universe) ) # Finalize a \"back\" call", "event self.fire_event(\"build\") def handle_event(self, event, control_center, universe):#params, user_input, network_controller, universe,", "int( universe.get_session_variable(\"core.gold.wallet\").get_value() ) # Template version for this item depends", "PAUSE_MENU_Y ), \"@width\": xml_encode( \"%d\" % int(PAUSE_MENU_WIDTH / 2) ),", "vendor's inventory (or re-populating), # clear it of any items", "# Kill event. Set game status back to active when", "We have definitely completed the first build now self.first_build =", "on_complete = \"game:unpause\" ) #hmenu.slide(DIR_LEFT, percent = 1.0) #row_menu.slide(DIR_RIGHT, percent", "(int( (SCREEN_WIDTH - PAUSE_MENU_WIDTH) / 2 ))) ), \"@y\": xml_encode(", "hook universe.execute_achievement_hook( \"bought-all-items\", control_center ) # I'm going to set", "that we can # remove items from their inventory after", "\"bought-all-items\" achievement hook universe.execute_achievement_hook( \"bought-all-items\", control_center ) # I'm going", "will have restocked the NPC's inventory. # Thus, if the", "# Compile template root = template.compile_node_by_id(\"menu\") # Create widget widget", "shop, if this is the first build... if (self.first_build): #", "== 0 ): # Fetch the \"nothing in stock\" template", "an entry for each available item... for item_name in self.vendor.get_vendor_inventory_item_names():", "options than your typical menu, we need to define many", "a historical record universe.add_historical_record( \"purchases\", control_center.get_localization_controller().get_label( \"purchased-m-from-n-for-g:message\", { \"@m\": item.get_title(),", "xml_encode( item.description ) }) # Compile node = template.compile_node_by_id(\"insert\") #", "False): # Events that result from event handling results =", "set this very menu to inactive elif ( action ==", "xml_decode, translate_rgb_to_string from code.constants.common import SCREEN_WIDTH, SCREEN_HEIGHT, PAUSE_MENU_X, PAUSE_MENU_Y, PAUSE_MENU_WIDTH,", "SPLASH_MODE_GREYSCALE_ANIMATED from code.constants.states import STATUS_ACTIVE, STATUS_INACTIVE, GAME_STATE_ACTIVE, GAME_STATE_NOT_READY from code.constants.newsfeeder", "# Go to the previous page (e.g. close buy item", "(self.first_build): # Pause universe.pause() # Call in the pause splash", "inventory area... root.find_node_by_id(\"ext.inventory\").add_node(node) # Create widget widget = widget_dispatcher.convert_node_to_widget(root, control_center,", "we begin populating the shop menu, we'll first # make", "the shop menu (more options than your typical menu, we", "menu (more options than your typical menu, we need to", "# Number of times the vendor can restock self.max_item_reloads =", "\"message\" in options ): self.message = options[\"message\"] if ( \"required-item-names\"", "= template.compile_node_by_id(\"menu\") # Create widget widget = widget_dispatcher.convert_node_to_widget(root, control_center, universe)", "), \"@shop-title\": xml_encode( self.title ) }) # Compile template root", "int( options[\"min-quality\"] ) if ( \"max-quality\" in options ): self.max_item_quality", "populating the shop menu, we'll first # make sure the", "import coalesce, intersect, offset_rect, log, log2, xml_encode, xml_decode, translate_rgb_to_string from", "can # remove items from their inventory after a purchase...", "\"title\" in options ): self.title = options[\"title\"] if ( \"message\"", "\"@shop-title\": xml_encode( self.title ), \"@salutation\": xml_encode( self.message ) }) #", "\"out-of-items\" ).add_parameters({ \"@x\": xml_encode( \"%d\" % (SCREEN_WIDTH - (int( (SCREEN_WIDTH", "), \"@item-title\": xml_encode( item.get_title() ), \"@item-cost\": xml_encode( \"%d\" % item.get_cost()", "): self.title = options[\"title\"] if ( \"message\" in options ):", "Configure the shop menu (more options than your typical menu,", "\"unaffordable\" ) # Fetch the appropriate template for an individual", "import SCREEN_WIDTH, SCREEN_HEIGHT, PAUSE_MENU_X, PAUSE_MENU_Y, PAUSE_MENU_WIDTH, PAUSE_MENU_HEIGHT, MODE_GAME, TILE_WIDTH, TILE_HEIGHT,", "we can # remove items from their inventory after a", "at my inventory.\" # Before we begin populating the shop", "\"game:buy-item\" ): results.append( self.handle_shop_buy_item_event(event, control_center, universe) ) # Go to", "items the player has acquired since last shopping with this", "): results.append( self.handle_show_confirm_purchase_event(event, control_center, universe) ) # Commit an item", "# to determine which template we load... if ( self.vendor.get_vendor_inventory_count()", "= EventQueue() # Convenience params = event.get_params() # Dismiss lightbox", "area... root.find_node_by_id(\"ext.inventory\").add_node(node) # Create widget widget = widget_dispatcher.convert_node_to_widget(root, control_center, universe)", "(money >= item.cost) else \"unaffordable\" ) # Fetch the appropriate", "EventQueue() # Convenience params = event.get_params() # Get the active", "percent = 1.0) # Resume game, killing shop menu when", "purchase elif ( action == \"game:buy-item\" ): results.append( self.handle_shop_buy_item_event(event, control_center,", "to keep a handle to the seller so that we", "params) = ( event.get_action(), event.get_params() ) # Build root menu", "get confirmation... elif ( action == \"show:confirm-purchase\" ): results.append( self.handle_show_confirm_purchase_event(event,", "that we can shop, if this is the first build...", "name = \"%s.onpurchase\" % item.get_name(), control_center = control_center, universe =", "= 1.0) #row_menu.slide(DIR_RIGHT, percent = 1.0) # Resume game, killing", "Get a handle to the actual item... item = universe.get_item_by_name(", "# Convenience params = event.get_params() # Get the active page", "universe):#params, user_input, network_controller, universe, active_map, session, widget_dispatcher, text_renderer, save_controller, refresh", "new page self.add_widget_via_event(widget, event, exclusive = False) # Return events", "event.get_params() # Done with the shop menu widget; trash it.", "\"show:confirm-purchase\" ): results.append( self.handle_show_confirm_purchase_event(event, control_center, universe) ) # Commit an", "items... self.required_item_names = [] # Track item quality threshholds (low", "directory\" template template = self.fetch_xml_template( \"shop.directory\", version = \"default\" ).add_parameters({", "= True) # Return events return results # Go back", "% int(PAUSE_MENU_WIDTH / 2) ), \"@height\": xml_encode( \"%d\" % SCREEN_HEIGHT", "# Return events return results # Kill event. Set game", "import * class ShopMenu(Menu): def __init__(self): Menu.__init__(self) # Assume all", ") ) # Remove from seller's inventory self.vendor.remove_item_from_vendor_inventory( item.get_name() )", "vendor have anything in stock? Use this data # to", "(SCREEN_WIDTH - (int( (SCREEN_WIDTH - PAUSE_MENU_WIDTH) / 2 ))) ),", "EventQueue() # Convenience params = event.get_params() # Get a reference", "Go to the previous page (e.g. close buy item confirm", "the \"are you sure you wanna buy this?\" page def", "# Finalize a \"back\" call elif ( action == \"previous-page\"", "from code.constants.common import SCREEN_WIDTH, SCREEN_HEIGHT, PAUSE_MENU_X, PAUSE_MENU_Y, PAUSE_MENU_WIDTH, PAUSE_MENU_HEIGHT, MODE_GAME,", "True # Fire build event self.fire_event(\"build\") def handle_event(self, event, control_center,", "= True ) # Refresh UI self.refresh_pages(control_center, universe, curtailed_count =", "game reacts in some way to an item you might", ") # Increase universe stats for items bought universe.get_session_variable(\"stats.items-bought\").increment_value(1) #", "UI self.refresh_pages(control_center, universe, curtailed_count = 1) # After rebuilding the", "self.vendor.get_vendor_inventory_count() == 0 ): # Execute the \"bought-all-items\" achievement hook", "= EventQueue() # Convenience params = event.get_params() # Get the", "else \"unaffordable\" ) # Fetch the appropriate template for an", "max_reloads = self.max_item_reloads,#int( node.get_attribute(\"max-reloads\") ), universe = universe ) #", "\"@y\": xml_encode( \"%d\" % PAUSE_MENU_Y ), \"@width\": xml_encode( \"%d\" %", ") # Refresh UI self.refresh_pages(control_center, universe, curtailed_count = 1) #", "= event.get_params() # Get a reference to the item (for", "events return results # Kill event. Set game status back", "item... item = universe.get_item_by_name( params[\"item-name\"] ) # Validate if (item):", "# Acquire the item by its name universe.acquire_item_by_name( item.get_name() )", "\"back\" ): results.append( self.handle_back_event(event, control_center, universe) ) # Finalize a", "if ( self.vendor.get_vendor_inventory_count() == 0 ): # Fetch the \"nothing", "events, etc.) results = EventQueue() # Convenience params = event.get_params()", "as gold spent universe.increment_session_variable( \"stats.gold-spent\", item.get_cost() ) # Execute the", "clear it of any items the player has acquired since", "# Fetch confirm purchase template template = self.fetch_xml_template(\"shop.buy.confirm\").add_parameters({ \"@width\": xml_encode(", "options ): self.title = options[\"title\"] if ( \"message\" in options", "Return events return results # Commit an item purchase def", "xml_encode( \"%d\" % PAUSE_MENU_HEIGHT ), \"@shop-title\": xml_encode( self.title ), \"@salutation\":", "), required_item_names = self.required_item_names, max_items = self.max_items_stocked,#int( node.get_attribute(\"max-items\") ), max_reloads", "page (animated) def handle_back_event(self, event, control_center, universe): # Events that", "xml_encode, xml_decode, translate_rgb_to_string from code.constants.common import SCREEN_WIDTH, SCREEN_HEIGHT, PAUSE_MENU_X, PAUSE_MENU_Y,", "0 self.max_item_quality = 0 # Items in stock at any", "action == \"build\" ): results.append( self.handle_build_event(event, control_center, universe) ) #", "items to sell... else: # Fetch the \"shopping directory\" template", "control_center ) # I'm going to set the cursor at", "look at my inventory.\" # Before we begin populating the", "% item.cost ), \"@item-advertisement\": xml_encode( item.description ) }) # Compile", "item = universe.get_item_by_name( params[\"item-name\"] ) # Validate if (item): #", "root = None # Does the vendor have anything in", "game state, set this very menu to inactive elif (", "# Scope root = None # Does the vendor have", "page self.add_widget_via_event(widget, event) # Return events return results # Show", "do we currently have? money = int( universe.get_session_variable(\"core.gold.wallet\").get_value() ) #", "\"default\" ).add_parameters({ \"@x\": xml_encode( \"%d\" % (SCREEN_WIDTH - (int( (SCREEN_WIDTH", "self.title ), \"@salutation\": xml_encode( self.message ) }) # Compile template", "\"Shoppe\" # Salutation (e.g. \"Look at these great items\") self.message", "Dismiss the splash controller, calling to resume game action once", "wallet amount by the cost... universe.increment_session_variable( \"core.gold.wallet\", -1 * item.get_cost()", "self.vendor = None#seller # Shop title (e.g. \"Bob's Fine Items\")", "# Shop title (e.g. \"Bob's Fine Items\") self.title = \"Shoppe\"", "is the first build... if (self.first_build): # Pause universe.pause() #", "the page page.hide( on_complete = \"previous-page\" ) # Return events", "event) # Return events return results # Show the \"are", "= options[\"title\"] if ( \"message\" in options ): self.message =", "than your typical menu, we need to define many parameters)", "DIR_UP, DIR_RIGHT, DIR_DOWN, DIR_LEFT, SPLASH_MODE_GREYSCALE_ANIMATED from code.constants.states import STATUS_ACTIVE, STATUS_INACTIVE,", "xml_encode( item.get_title() ), \"@item-cost\": xml_encode( \"%d\" % item.get_cost() ) })", "script (perhaps the game reacts in some way to an", "hook universe.execute_achievement_hook( \"wallet-changed\", control_center ) # Increase universe stats for", "for this item depends on whether we can afford it...", "item purchase def handle_shop_buy_item_event(self, event, control_center, universe): # Events that", "max_items = self.max_items_stocked,#int( node.get_attribute(\"max-items\") ), max_reloads = self.max_item_reloads,#int( node.get_attribute(\"max-reloads\") ),", "a newsfeeder notice control_center.get_window_controller().get_newsfeeder().post({ \"type\": NEWS_ITEM_NEW, \"title\": control_center.get_localization_controller().get_label(\"new-item-purchased:header\"), \"content\": item.get_title()", "True ) # Refresh UI self.refresh_pages(control_center, universe, curtailed_count = 1)", "and high) self.min_item_quality = 0 self.max_item_quality = 0 # Items", "template template = self.fetch_xml_template(\"shop.buy.confirm\").add_parameters({ \"@width\": xml_encode( \"%d\" % int(PAUSE_MENU_WIDTH /", "page = self.get_active_page() # Validate if (page): # Dismiss the", "= \"out-of-items\" ).add_parameters({ \"@x\": xml_encode( \"%d\" % (SCREEN_WIDTH - (int(", "you wanna buy this?\" page def handle_show_confirm_purchase_event(self, event, control_center, universe):", "\"purchased-m-from-n-for-g:message\", { \"@m\": item.get_title(), \"@n\": self.vendor.nick, \"@g\": item.get_cost() } )", "How much money do we currently have? money = int(", "wanna buy this?\" page def handle_show_confirm_purchase_event(self, event, control_center, universe): #", "item.get_name() ), \"@item-title\": xml_encode( item.get_title() ), \"@item-cost\": xml_encode( \"%d\" %", "# Post a newsfeeder notice control_center.get_window_controller().get_newsfeeder().post({ \"type\": NEWS_ITEM_NEW, \"title\": control_center.get_localization_controller().get_label(\"new-item-purchased:header\"),", "from already-lightboxed dialogues. self.lightbox_controller.set_interval( self.lightbox_controller.get_target() ) # We're going to", "shoppe's vendor... self.vendor.populate_vendor_inventory( min_quality = self.min_item_quality,#int( node.get_attribute(\"min-quality\") ), max_quality =", "# Convenience params = event.get_params() # Dismiss lightbox effect self.lightbox_controller.set_target(0)", "in options ): self.title = options[\"title\"] if ( \"message\" in", "the vendor m.run_script( \"%s.onpurchase\" % self.vendor.get_name(), control_center, universe, execute_all =", "# Return events return results # Configure the shop menu", "), \"@width\": xml_encode( \"%d\" % int(PAUSE_MENU_WIDTH / 2) ), \"@height\":", "Remove from seller's inventory self.vendor.remove_item_from_vendor_inventory( item.get_name() ) # Increase sales", "widget dispatcher widget_dispatcher = control_center.get_widget_dispatcher() # Pause the game so", "control_center, universe) widget.set_id(\"root\") # We have definitely completed the first", "True) # Return events return results # Go back a", "\"wallet-changed\" achievement hook universe.execute_achievement_hook( \"wallet-changed\", control_center ) # Increase universe", "# Create widget widget = widget_dispatcher.convert_node_to_widget(root, control_center, universe) widget.set_id(\"root\") #", "high) self.min_item_quality = 0 self.max_item_quality = 0 # Items in", "\"shopping directory\" template template = self.fetch_xml_template( \"shop.directory\", version = \"default\"", "Salutation (e.g. \"Look at these great items\") self.message = \"Take", "Items\") self.title = \"Shoppe\" # Salutation (e.g. \"Look at these", "events return results # Go back a page (animated) def", "== \"back\" ): results.append( self.handle_back_event(event, control_center, universe) ) # Finalize", "# Convenience params = event.get_params() # Fetch the widget dispatcher", "max_quality = self.max_item_quality,#int( node.get_attribute(\"min-quality\") ), required_item_names = self.required_item_names, max_items =", "play def handle_resume_game_event(self, event, control_center, universe): # Events that result", "and resume play def handle_resume_game_event(self, event, control_center, universe): # Events", "def handle_shop_buy_item_event(self, event, control_center, universe): # Events that result from", "Check for a generic \"onpurchase\" script for the vendor m.run_script(", "restock self.max_item_reloads = 1 # Track whether this is the", "once done... control_center.get_splash_controller().dismiss( on_complete = \"game:unpause\" ) #hmenu.slide(DIR_LEFT, percent =", "# Build the shop menu def handle_build_event(self, event, control_center, universe):", "= False): # Events that result from event handling results", "appropriate template for an individual item template = self.fetch_xml_template( \"shop.directory.insert\",", "shop menu (more options than your typical menu, we need", "= self.get_active_page() # Validate if (page): # Dismiss the page", "return results # Go back a page (animated) def handle_back_event(self,", "we can afford it... template_version = ( \"affordable\" if (money", "available, we have just bought their last item... if (", "}) # Compile node = template.compile_node_by_id(\"insert\") # Inject into inventory", "from code.tools.eventqueue import EventQueue from code.tools.xml import XMLParser from code.utils.common", "options ): self.vendor = options[\"vendor\"] if ( \"title\" in options", "code.tools.xml import XMLParser from code.utils.common import coalesce, intersect, offset_rect, log,", "): self.max_item_quality = int( options[\"max-quality\"] ) if ( \"max-items\" in", "\"@g\": item.get_cost() } ) #\"Bought [color=special]%s[/color] for [color=special]%s[/color] gold.\" %", "self.refresh_pages(control_center, universe, curtailed_count = 1) # After rebuilding the UI,", "= 1 # Number of times the vendor can restock", "% int(PAUSE_MENU_WIDTH / 2) ), \"@height\": xml_encode( \"%d\" % PAUSE_MENU_HEIGHT", "(more options than your typical menu, we need to define", "= control_center.get_widget_dispatcher() # Pause the game so that we can", "Fetch confirm purchase template template = self.fetch_xml_template(\"shop.buy.confirm\").add_parameters({ \"@width\": xml_encode( \"%d\"", "active map m = universe.get_active_map() # Check for a generic", "self.handle_build_event(event, control_center, universe) ) # Select an item, get confirmation...", "\"back\" call elif ( action == \"previous-page\" ): # Let's", "(e.g. \"Look at these great items\") self.message = \"Take a", "keep a handle to the seller so that we can", "After rebuilding the UI, we will have restocked the NPC's", "Fine Items\") self.title = \"Shoppe\" # Salutation (e.g. \"Look at", "event.get_params() ) # Build root menu if ( action ==", "2) ), \"@height\": xml_encode( \"%d\" % PAUSE_MENU_HEIGHT ), \"@shop-title\": xml_encode(", "the vendor can restock self.max_item_reloads = 1 # Track whether", "can afford it... template_version = ( \"affordable\" if (money >=", "Validate if (page): # Dismiss the page page.hide( on_complete =", "# remove items from their inventory after a purchase... self.vendor", "resume play def handle_resume_game_event(self, event, control_center, universe): # Events that", "): results.append( self.handle_kill_event(event, control_center, universe) ) # Return events return", "import math import random import time from code.menu.menu import Menu", "user_input, network_controller, universe, active_map, session, widget_dispatcher, text_renderer, save_controller, refresh =", "the shop and resume play def handle_resume_game_event(self, event, control_center, universe):", "self.__std_configure__(options) if ( \"vendor\" in options ): self.vendor = options[\"vendor\"]", "the widget dispatcher widget_dispatcher = control_center.get_widget_dispatcher() # Get a handle", "self.max_items_stocked = int( options[\"max-items\"] ) if ( \"max-reloads\" in options", "# We have items to sell... else: # Fetch the", "the UI, we will have restocked the NPC's inventory. #", "# Pause the game so that we can shop, if", "# Count as gold spent universe.increment_session_variable( \"stats.gold-spent\", item.get_cost() ) #", "# Track item quality threshholds (low and high) self.min_item_quality =", "for each available item... for item_name in self.vendor.get_vendor_inventory_item_names(): # Grab", "root = template.compile_node_by_id(\"menu\") # We have items to sell... else:", "def handle_kill_event(self, event, control_center, universe): # Events that result from", "def __init__(self): Menu.__init__(self) # Assume all shop menus come from", "control_center ) # Increase universe stats for items bought universe.get_session_variable(\"stats.items-bought\").increment_value(1)", "script (?) ) # Check for an onpurchase script (perhaps", "# Pause universe.pause() # Call in the pause splash control_center.get_splash_controller().set_mode(SPLASH_MODE_GREYSCALE_ANIMATED)", ">= item.cost) else \"unaffordable\" ) # Fetch the appropriate template", "item quality threshholds (low and high) self.min_item_quality = 0 self.max_item_quality", "Events that result from event handling results = EventQueue() #", "items bought universe.get_session_variable(\"stats.items-bought\").increment_value(1) # Execute the \"bought-item\" achievement hook universe.execute_achievement_hook(", ") # Scope root = None # Does the vendor", "control_center, universe) ) # Return events return results # Configure", "control_center, universe): # Events that result from handling this event", "universe.execute_achievement_hook( \"bought-all-items\", control_center ) # I'm going to set the", "cursor at \"home\" position for the shop self.get_widget_by_id(\"root\").set_cursor_at_beginning()#finalize = True)", "-1 * item.get_cost() ) # Count as gold spent universe.increment_session_variable(", "Add a historical record universe.add_historical_record( \"purchases\", control_center.get_localization_controller().get_label( \"purchased-m-from-n-for-g:message\", { \"@m\":", "Leave shop, resume game elif ( action == \"resume-game\" ):", ") # Finalize a \"back\" call elif ( action ==", "very menu to inactive elif ( action == \"kill\" ):", "events return results # Commit an item purchase def handle_shop_buy_item_event(self,", "\"onpurchase\" script for the vendor m.run_script( \"%s.onpurchase\" % self.vendor.get_name(), control_center,", "), \"@item-cost\": xml_encode( \"%d\" % item.cost ), \"@item-advertisement\": xml_encode( item.description", "# Validate if (page): # Dismiss the page page.hide( on_complete", "confirmation... elif ( action == \"show:confirm-purchase\" ): results.append( self.handle_show_confirm_purchase_event(event, control_center,", ") }) # Compile template root = template.compile_node_by_id(\"menu\") # Create", "# Assume all shop menus come from already-lightboxed dialogues. self.lightbox_controller.set_interval(", "shop menu def handle_build_event(self, event, control_center, universe): # Events that", "to the seller so that we can # remove items", "# I'm going to set the cursor at \"home\" position", "Menu.__init__(self) # Assume all shop menus come from already-lightboxed dialogues.", "have bought) m.run_script( name = \"%s.onpurchase\" % item.get_name(), control_center =", "save_controller, refresh = False): # Events that result from event", ") if ( \"max-quality\" in options ): self.max_item_quality = int(", "self # Build the shop menu def handle_build_event(self, event, control_center,", "# Common menu configuration self.__std_configure__(options) if ( \"vendor\" in options", "EventQueue() # Convenience (action, params) = ( event.get_action(), event.get_params() )", "# Add the new page self.add_widget_via_event(widget, event, exclusive = False)", "= \"previous-page\" ) # Return events return results # Leave", "this shoppe's vendor... self.vendor.populate_vendor_inventory( min_quality = self.min_item_quality,#int( node.get_attribute(\"min-quality\") ), max_quality", "an item purchase def handle_shop_buy_item_event(self, event, control_center, universe): # Events", "universe.get_active_map() # Check for a generic \"onpurchase\" script for the", "if ( \"min-quality\" in options ): self.min_item_quality = int( options[\"min-quality\"]", "vendor m.run_script( \"%s.onpurchase\" % self.vendor.get_name(), control_center, universe, execute_all = True", "the cost... universe.increment_session_variable( \"core.gold.wallet\", -1 * item.get_cost() ) # Count", "you might have bought) m.run_script( name = \"%s.onpurchase\" % item.get_name(),", "in self.vendor.get_vendor_inventory_item_names(): # Grab handle item = universe.get_item_by_name(item_name) # Validate", "# clear it of any items the player has acquired", "control_center, universe) ) # Commit an item purchase elif (", "sales count for vendor self.vendor.increase_sales_count(1) # Reduce player's wallet amount", "widget disappears self.get_widget_by_id(\"root\").hide( on_complete = \"kill\" ) # Return events", "Before populating the vendor's inventory (or re-populating), # clear it", "self.get_active_page() # Validate if (page): # Dismiss the page page.hide(", "\"type\": NEWS_ITEM_NEW, \"title\": control_center.get_localization_controller().get_label(\"new-item-purchased:header\"), \"content\": item.get_title() }) # Add a", "), \"@shop-title\": xml_encode( self.title ), \"@salutation\": xml_encode( self.message ) })", "shop, resume game elif ( action == \"resume-game\" ): results.append(", ") # I'm going to set the cursor at \"home\"", "= self.min_item_quality,#int( node.get_attribute(\"min-quality\") ), max_quality = self.max_item_quality,#int( node.get_attribute(\"min-quality\") ), required_item_names", "# Select an item, get confirmation... elif ( action ==", "\"@width\": xml_encode( \"%d\" % int(PAUSE_MENU_WIDTH / 2) ), \"@height\": xml_encode(", "(item): # Fetch confirm purchase template template = self.fetch_xml_template(\"shop.buy.confirm\").add_parameters({ \"@width\":", "Compile node = template.compile_node_by_id(\"insert\") # Inject into inventory area... root.find_node_by_id(\"ext.inventory\").add_node(node)", "Call in the pause splash control_center.get_splash_controller().set_mode(SPLASH_MODE_GREYSCALE_ANIMATED) # Before populating the", "GAME_STATE_NOT_READY from code.constants.newsfeeder import * class ShopMenu(Menu): def __init__(self): Menu.__init__(self)", "# Execute the \"bought-item\" achievement hook universe.execute_achievement_hook( \"bought-item\", control_center )", "shop menu widget; trash it. self.set_status(STATUS_INACTIVE) # Return events return", "elif ( action == \"back\" ): results.append( self.handle_back_event(event, control_center, universe)", "handling results = EventQueue() # Convenience (action, params) = (", "cost info, etc.) item = universe.get_item_by_name( params[\"item-name\"] ) # Acquire", "control_center.get_widget_dispatcher() # Pause the game so that we can shop,", "( \"title\" in options ): self.title = options[\"title\"] if (", "\"max-reloads\" in options ): self.max_item_reloads = int( options[\"max-reloads\"] ) #", "template template = self.fetch_xml_template( \"shop.directory\", version = \"out-of-items\" ).add_parameters({ \"@x\":", "PAUSE_MENU_WIDTH, PAUSE_MENU_HEIGHT, MODE_GAME, TILE_WIDTH, TILE_HEIGHT, DIR_UP, DIR_RIGHT, DIR_DOWN, DIR_LEFT, SPLASH_MODE_GREYSCALE_ANIMATED", "self.add_widget_via_event(widget, event, exclusive = False) # Return events return results", "set the cursor at \"home\" position for the shop self.get_widget_by_id(\"root\").set_cursor_at_beginning()#finalize", "the first build or a refresh self.first_build = True #", "acquired since last shopping with this vendor... self.vendor.remove_erstwhile_acquired_items_from_inventory(universe) # Populate", "item purchase elif ( action == \"game:buy-item\" ): results.append( self.handle_shop_buy_item_event(event,", "Show the \"are you sure you wanna buy this?\" page", "parameters) def configure(self, options): # Common menu configuration self.__std_configure__(options) if", "Return events return results # Kill event. Set game status", "Compile template root = template.compile_node_by_id(\"menu\") # Now we'll add an", "\"min-quality\" in options ): self.min_item_quality = int( options[\"min-quality\"] ) if", "in options ): self.required_item_names.extend( options[\"required-item-names\"] )#.split(\";\") ) if ( \"min-quality\"", "version = \"out-of-items\" ).add_parameters({ \"@x\": xml_encode( \"%d\" % (SCREEN_WIDTH -", "root menu if ( action == \"build\" ): results.append( self.handle_build_event(event,", "== \"previous-page\" ): # Let's just go back one page", "\"@item-cost\": xml_encode( \"%d\" % item.get_cost() ) }) # Compile template", "in the pause splash control_center.get_splash_controller().set_mode(SPLASH_MODE_GREYSCALE_ANIMATED) # Before populating the vendor's", "times the vendor can restock self.max_item_reloads = 1 # Track", "universe) ) # Finalize a \"back\" call elif ( action", "# Check for a generic \"onpurchase\" script for the vendor", "self.message = \"Take a look at my inventory.\" # Before", "inventory available, we have just bought their last item... if", "= event.get_params() # Get the active page page = self.get_active_page()", "), \"@item-name\": xml_encode( item.get_name() ), \"@item-title\": xml_encode( item.get_title() ), \"@item-cost\":", "menus come from already-lightboxed dialogues. self.lightbox_controller.set_interval( self.lightbox_controller.get_target() ) # We're", "# Convenience params = event.get_params() # Get a reference to", "menu def handle_build_event(self, event, control_center, universe): # Events that result", "(low and high) self.min_item_quality = 0 self.max_item_quality = 0 #", "# Increase universe stats for items bought universe.get_session_variable(\"stats.items-bought\").increment_value(1) # Execute", "\"@item-cost\": xml_encode( \"%d\" % item.cost ), \"@item-advertisement\": xml_encode( item.description )", "for this shoppe's vendor... self.vendor.populate_vendor_inventory( min_quality = self.min_item_quality,#int( node.get_attribute(\"min-quality\") ),", "Compile template root = template.compile_node_by_id(\"menu\") # Create widget widget =", "configuration self.__std_configure__(options) if ( \"vendor\" in options ): self.vendor =", "in options ): self.max_items_stocked = int( options[\"max-items\"] ) if (", "# Return events return results # Leave the shop and", "options[\"vendor\"] if ( \"title\" in options ): self.title = options[\"title\"]", "def handle_back_event(self, event, control_center, universe): # Events that result from", "0 ): # Fetch the \"nothing in stock\" template template", "xml_encode( \"%d\" % int(PAUSE_MENU_WIDTH / 2) ), \"@height\": xml_encode( \"%d\"", "\"previous-page\" ): # Let's just go back one page self.page_back(1)", "NPC seller stocks any specified \"required\" items... self.required_item_names = []", "self.handle_resume_game_event(event, control_center, universe) ) # Restore the universe to active", "): self.required_item_names.extend( options[\"required-item-names\"] )#.split(\";\") ) if ( \"min-quality\" in options", "( \"max-reloads\" in options ): self.max_item_reloads = int( options[\"max-reloads\"] )", "}) # Add a historical record universe.add_historical_record( \"purchases\", control_center.get_localization_controller().get_label( \"purchased-m-from-n-for-g:message\",", "Commit an item purchase elif ( action == \"game:buy-item\" ):", "xml_encode( self.message ) }) # Compile template root = template.compile_node_by_id(\"menu\")", "purchase... self.vendor = None#seller # Shop title (e.g. \"Bob's Fine", "PAUSE_MENU_WIDTH) / 2 ))) ), \"@y\": xml_encode( \"%d\" % PAUSE_MENU_Y", "gold spent universe.increment_session_variable( \"stats.gold-spent\", item.get_cost() ) # Execute the \"wallet-changed\"", "), \"@y\": xml_encode( \"%d\" % PAUSE_MENU_Y ), \"@width\": xml_encode( \"%d\"", "a \"back\" call elif ( action == \"previous-page\" ): #", "# Execute the \"wallet-changed\" achievement hook universe.execute_achievement_hook( \"wallet-changed\", control_center )", "\"build\" ): results.append( self.handle_build_event(event, control_center, universe) ) # Select an", "first build... if (self.first_build): # Pause universe.pause() # Call in", "event (on-birth events, etc.) results = EventQueue() # Convenience params", "menu to inactive elif ( action == \"kill\" ): results.append(", "universe.get_item_by_name(item_name) # Validate if (item): # How much money do", "# Fire build event self.fire_event(\"build\") def handle_event(self, event, control_center, universe):#params,", "= None#seller # Shop title (e.g. \"Bob's Fine Items\") self.title", "= event.get_params() # Done with the shop menu widget; trash", "% item.get_cost() ) }) # Compile template root = template.compile_node_by_id(\"menu\")", "translate_rgb_to_string from code.constants.common import SCREEN_WIDTH, SCREEN_HEIGHT, PAUSE_MENU_X, PAUSE_MENU_Y, PAUSE_MENU_WIDTH, PAUSE_MENU_HEIGHT,", "these great items\") self.message = \"Take a look at my", "items from their inventory after a purchase... self.vendor = None#seller", "afford it... template_version = ( \"affordable\" if (money >= item.cost)", "Convenience params = event.get_params() # Done with the shop menu", "inventory for this shoppe's vendor... self.vendor.populate_vendor_inventory( min_quality = self.min_item_quality,#int( node.get_attribute(\"min-quality\")", "Thus, if the NPC has no inventory available, we have", "options[\"max-items\"] ) if ( \"max-reloads\" in options ): self.max_item_reloads =", "handle item = universe.get_item_by_name(item_name) # Validate if (item): # How", ").add_parameters({ \"@x\": xml_encode( \"%d\" % (SCREEN_WIDTH - (int( (SCREEN_WIDTH -", "record universe.add_historical_record( \"purchases\", control_center.get_localization_controller().get_label( \"purchased-m-from-n-for-g:message\", { \"@m\": item.get_title(), \"@n\": self.vendor.nick,", "already-lightboxed dialogues. self.lightbox_controller.set_interval( self.lightbox_controller.get_target() ) # We're going to keep", "= int( options[\"max-reloads\"] ) # For chaining return self #", "= control_center.get_widget_dispatcher() # Get a handle to the actual item...", "PAUSE_MENU_HEIGHT ), \"@shop-title\": xml_encode( self.title ), \"@salutation\": xml_encode( self.message )", "from seller's inventory self.vendor.remove_item_from_vendor_inventory( item.get_name() ) # Increase sales count", "self.max_item_quality = int( options[\"max-quality\"] ) if ( \"max-items\" in options", "control_center.get_localization_controller().get_label( \"purchased-m-from-n-for-g:message\", { \"@m\": item.get_title(), \"@n\": self.vendor.nick, \"@g\": item.get_cost() }", "\"vendor\" in options ): self.vendor = options[\"vendor\"] if ( \"title\"", "begin populating the shop menu, we'll first # make sure", "xml_encode( \"%d\" % item.get_cost() ) }) # Compile template root", "node.get_attribute(\"min-quality\") ), required_item_names = self.required_item_names, max_items = self.max_items_stocked,#int( node.get_attribute(\"max-items\") ),", "in options ): self.vendor = options[\"vendor\"] if ( \"title\" in", "events return results # Leave the shop and resume play", "stocks any specified \"required\" items... self.required_item_names = [] # Track", "# Compile template root = template.compile_node_by_id(\"menu\") # Now we'll add", "(on-birth events, etc.) results = EventQueue() # Convenience params =", "the actual item... item = universe.get_item_by_name( params[\"item-name\"] ) # Validate", "= self.fetch_xml_template( \"shop.directory\", version = \"out-of-items\" ).add_parameters({ \"@x\": xml_encode( \"%d\"", "): self.min_item_quality = int( options[\"min-quality\"] ) if ( \"max-quality\" in", "ShopMenu(Menu): def __init__(self): Menu.__init__(self) # Assume all shop menus come", "the game so that we can shop, if this is", "item... if ( self.vendor.get_vendor_inventory_count() == 0 ): # Execute the", "EventQueue() # Convenience params = event.get_params() # Fetch the widget", "UI, we will have restocked the NPC's inventory. # Thus,", "no inventory available, we have just bought their last item...", "if ( \"max-items\" in options ): self.max_items_stocked = int( options[\"max-items\"]", ") # Increase sales count for vendor self.vendor.increase_sales_count(1) # Reduce", "from code.menu.menu import Menu from code.tools.eventqueue import EventQueue from code.tools.xml", ") # For chaining return self # Build the shop", "universe.increment_session_variable( \"stats.gold-spent\", item.get_cost() ) # Execute the \"wallet-changed\" achievement hook", "self.vendor.increase_sales_count(1) # Reduce player's wallet amount by the cost... universe.increment_session_variable(", "events return results # Configure the shop menu (more options", "purchase def handle_shop_buy_item_event(self, event, control_center, universe): # Events that result", "bought universe.get_session_variable(\"stats.items-bought\").increment_value(1) # Execute the \"bought-item\" achievement hook universe.execute_achievement_hook( \"bought-item\",", "item template = self.fetch_xml_template( \"shop.directory.insert\", version = template_version ).add_parameters({ \"@item-name\":", "\"nothing in stock\" template template = self.fetch_xml_template( \"shop.directory\", version =", "template for an individual item template = self.fetch_xml_template( \"shop.directory.insert\", version", "# Create widget widget = widget_dispatcher.convert_node_to_widget(root, control_center, universe) widget.set_id(\"confirm-shop-purchase\") #", "newsfeeder notice control_center.get_window_controller().get_newsfeeder().post({ \"type\": NEWS_ITEM_NEW, \"title\": control_center.get_localization_controller().get_label(\"new-item-purchased:header\"), \"content\": item.get_title() })", "for vendor self.vendor.increase_sales_count(1) # Reduce player's wallet amount by the", "<filename>code/menu/screens/shopmenu.py import os import math import random import time from", "item, get confirmation... elif ( action == \"show:confirm-purchase\" ): results.append(", "universe.get_session_variable(\"stats.items-bought\").increment_value(1) # Execute the \"bought-item\" achievement hook universe.execute_achievement_hook( \"bought-item\", control_center", "results.append( self.handle_shop_buy_item_event(event, control_center, universe) ) # Go to the previous", "elif ( action == \"game:buy-item\" ): results.append( self.handle_shop_buy_item_event(event, control_center, universe)", "= self.required_item_names, max_items = self.max_items_stocked,#int( node.get_attribute(\"max-items\") ), max_reloads = self.max_item_reloads,#int(", "control_center.get_splash_controller().dismiss( on_complete = \"game:unpause\" ) #hmenu.slide(DIR_LEFT, percent = 1.0) #row_menu.slide(DIR_RIGHT,", "return results # Commit an item purchase def handle_shop_buy_item_event(self, event,", "game so that we can shop, if this is the", "( action == \"build\" ): results.append( self.handle_build_event(event, control_center, universe) )", "when shopping is done. def handle_kill_event(self, event, control_center, universe): #", "code.utils.common import coalesce, intersect, offset_rect, log, log2, xml_encode, xml_decode, translate_rgb_to_string", "the shop menu def handle_build_event(self, event, control_center, universe): # Events", "( self.vendor.get_vendor_inventory_count() == 0 ): # Execute the \"bought-all-items\" achievement", "options[\"message\"] if ( \"required-item-names\" in options ): self.required_item_names.extend( options[\"required-item-names\"] )#.split(\";\")", "item (for cost info, etc.) item = universe.get_item_by_name( params[\"item-name\"] )", "options ): self.min_item_quality = int( options[\"min-quality\"] ) if ( \"max-quality\"", "= None # Does the vendor have anything in stock?", "widget = widget_dispatcher.convert_node_to_widget(root, control_center, universe) widget.set_id(\"root\") # We have definitely", "we will have restocked the NPC's inventory. # Thus, if", "# Before we begin populating the shop menu, we'll first", "= universe, execute_all = True ) # Refresh UI self.refresh_pages(control_center,", "item confirm dialog) elif ( action == \"back\" ): results.append(", "if ( \"max-quality\" in options ): self.max_item_quality = int( options[\"max-quality\"]", "event.get_params() # Fetch the widget dispatcher widget_dispatcher = control_center.get_widget_dispatcher() #", "template root = template.compile_node_by_id(\"menu\") # Now we'll add an entry", "= universe.get_item_by_name( params[\"item-name\"] ) # Validate if (item): # Fetch", "results = EventQueue() # Convenience params = event.get_params() # Dismiss", "from code.constants.newsfeeder import * class ShopMenu(Menu): def __init__(self): Menu.__init__(self) #", "game action once done... control_center.get_splash_controller().dismiss( on_complete = \"game:unpause\" ) #hmenu.slide(DIR_LEFT,", ") # Build root menu if ( action == \"build\"", "False) # Return events return results # Commit an item", "= EventQueue() # Convenience params = event.get_params() # Done with", "(item): # How much money do we currently have? money", ")#.split(\";\") ) if ( \"min-quality\" in options ): self.min_item_quality =", "dispatcher widget_dispatcher = control_center.get_widget_dispatcher() # Pause the game so that", "template root = template.compile_node_by_id(\"menu\") # We have items to sell...", "# make sure the NPC seller stocks any specified \"required\"", "% PAUSE_MENU_HEIGHT ), \"@shop-title\": xml_encode( self.title ) }) # Compile", "Convenience params = event.get_params() # Dismiss lightbox effect self.lightbox_controller.set_target(0) #", "node.get_attribute(\"max-reloads\") ), universe = universe ) # Scope root =", "reference to the item (for cost info, etc.) item =", "Get the active map m = universe.get_active_map() # Check for", "if ( \"vendor\" in options ): self.vendor = options[\"vendor\"] if", "return results # Leave the shop and resume play def", "STATUS_ACTIVE, STATUS_INACTIVE, GAME_STATE_ACTIVE, GAME_STATE_NOT_READY from code.constants.newsfeeder import * class ShopMenu(Menu):", "# Thus, if the NPC has no inventory available, we", "from event handling results = EventQueue() # Convenience (action, params)", "results.append( self.handle_show_confirm_purchase_event(event, control_center, universe) ) # Commit an item purchase", "\"previous-page\" ) # Return events return results # Leave the", "item.get_cost() } ) #\"Bought [color=special]%s[/color] for [color=special]%s[/color] gold.\" % (", ") }) # Compile template root = template.compile_node_by_id(\"menu\") # Now", "results # Show the \"are you sure you wanna buy", "# Add the new page self.add_widget_via_event(widget, event) # Return events", "PAUSE_MENU_X, PAUSE_MENU_Y, PAUSE_MENU_WIDTH, PAUSE_MENU_HEIGHT, MODE_GAME, TILE_WIDTH, TILE_HEIGHT, DIR_UP, DIR_RIGHT, DIR_DOWN,", "event, control_center, universe): # Events that result from handling this", "int(PAUSE_MENU_WIDTH / 2) ), \"@height\": xml_encode( \"%d\" % SCREEN_HEIGHT ),", "an item you might have bought) m.run_script( name = \"%s.onpurchase\"", "\"%d\" % (SCREEN_WIDTH - (int( (SCREEN_WIDTH - PAUSE_MENU_WIDTH) / 2", "# Commit an item purchase elif ( action == \"game:buy-item\"", "cost... universe.increment_session_variable( \"core.gold.wallet\", -1 * item.get_cost() ) # Count as", "* class ShopMenu(Menu): def __init__(self): Menu.__init__(self) # Assume all shop", "widget_dispatcher.convert_node_to_widget(root, control_center, universe) widget.set_id(\"root\") # We have definitely completed the", "last item... if ( self.vendor.get_vendor_inventory_count() == 0 ): # Execute", "# Fetch the \"shopping directory\" template template = self.fetch_xml_template( \"shop.directory\",", "back to active when shopping is done. def handle_kill_event(self, event,", "# Compile template root = template.compile_node_by_id(\"menu\") # We have items", "self.get_widget_by_id(\"root\").set_cursor_at_beginning()#finalize = True) # Return events return results # Go", "#row_menu.slide(DIR_RIGHT, percent = 1.0) # Resume game, killing shop menu", ") # Select an item, get confirmation... elif ( action", ") # Post a newsfeeder notice control_center.get_window_controller().get_newsfeeder().post({ \"type\": NEWS_ITEM_NEW, \"title\":", "money do we currently have? money = int( universe.get_session_variable(\"core.gold.wallet\").get_value() )", "spent universe.increment_session_variable( \"stats.gold-spent\", item.get_cost() ) # Execute the \"wallet-changed\" achievement", "self.page_back(1) # Leave shop, resume game elif ( action ==", "= template.compile_node_by_id(\"insert\") # Inject into inventory area... root.find_node_by_id(\"ext.inventory\").add_node(node) # Create", "params[\"item-name\"] ) # Validate if (item): # Fetch confirm purchase", "close buy item confirm dialog) elif ( action == \"back\"", "etc.) item = universe.get_item_by_name( params[\"item-name\"] ) # Acquire the item", "# Leave the shop and resume play def handle_resume_game_event(self, event,", "position for the shop self.get_widget_by_id(\"root\").set_cursor_at_beginning()#finalize = True) # Return events", "= universe ) # Scope root = None # Does", "int( options[\"max-items\"] ) if ( \"max-reloads\" in options ): self.max_item_reloads", "control_center.get_splash_controller().set_mode(SPLASH_MODE_GREYSCALE_ANIMATED) # Before populating the vendor's inventory (or re-populating), #", "when widget disappears self.get_widget_by_id(\"root\").hide( on_complete = \"kill\" ) # Return", "by the cost... universe.increment_session_variable( \"core.gold.wallet\", -1 * item.get_cost() ) #", "node = template.compile_node_by_id(\"insert\") # Inject into inventory area... root.find_node_by_id(\"ext.inventory\").add_node(node) #", "# Show the \"are you sure you wanna buy this?\"", "= \"%s.onpurchase\" % item.get_name(), control_center = control_center, universe = universe,", ") if ( \"min-quality\" in options ): self.min_item_quality = int(", "options ): self.required_item_names.extend( options[\"required-item-names\"] )#.split(\";\") ) if ( \"min-quality\" in", ") # Return events return results # Kill event. Set", "results = EventQueue() # Convenience (action, params) = ( event.get_action(),", "self.lightbox_controller.set_target(0) # Dismiss the splash controller, calling to resume game", "= \"Shoppe\" # Salutation (e.g. \"Look at these great items\")", "), \"@salutation\": xml_encode( self.message ) }) # Compile template root", "stats for items bought universe.get_session_variable(\"stats.items-bought\").increment_value(1) # Execute the \"bought-item\" achievement", "self.message ) }) # Compile template root = template.compile_node_by_id(\"menu\") #", "\"@item-name\": xml_encode( item.name ), \"@item-title\": xml_encode( item.title ), \"@item-cost\": xml_encode(", "# Get a reference to the item (for cost info,", "Convenience (action, params) = ( event.get_action(), event.get_params() ) # Build", "( \"vendor\" in options ): self.vendor = options[\"vendor\"] if (", "widget.set_id(\"confirm-shop-purchase\") # Add the new page self.add_widget_via_event(widget, event, exclusive =", "if (money >= item.cost) else \"unaffordable\" ) # Fetch the", "have definitely completed the first build now self.first_build = False", "sure you wanna buy this?\" page def handle_show_confirm_purchase_event(self, event, control_center,", "Template version for this item depends on whether we can", "for the shop self.get_widget_by_id(\"root\").set_cursor_at_beginning()#finalize = True) # Return events return", "We have items to sell... else: # Fetch the \"shopping", "results # Kill event. Set game status back to active", "the first build... if (self.first_build): # Pause universe.pause() # Call", "have items to sell... else: # Fetch the \"shopping directory\"", "universe.increment_session_variable( \"core.gold.wallet\", -1 * item.get_cost() ) # Count as gold", "code.tools.eventqueue import EventQueue from code.tools.xml import XMLParser from code.utils.common import", "): # Execute the \"bought-all-items\" achievement hook universe.execute_achievement_hook( \"bought-all-items\", control_center", "return results # Kill event. Set game status back to", "page page = self.get_active_page() # Validate if (page): # Dismiss", "% ( item.get_title(), item.get_cost() ) ) # Remove from seller's", "\"kill\" ): results.append( self.handle_kill_event(event, control_center, universe) ) # Return events", "self.fetch_xml_template(\"shop.buy.confirm\").add_parameters({ \"@width\": xml_encode( \"%d\" % int(PAUSE_MENU_WIDTH / 2) ), \"@height\":", "handle to the actual item... item = universe.get_item_by_name( params[\"item-name\"] )", "params = event.get_params() # Get the active page page =", "active_map, session, widget_dispatcher, text_renderer, save_controller, refresh = False): # Events", "vendor can restock self.max_item_reloads = 1 # Track whether this", "= 1.0) # Resume game, killing shop menu when widget", "entire script (?) ) # Check for an onpurchase script", "page page.hide( on_complete = \"previous-page\" ) # Return events return", "item.get_title() ), \"@item-cost\": xml_encode( \"%d\" % item.get_cost() ) }) #", "for items bought universe.get_session_variable(\"stats.items-bought\").increment_value(1) # Execute the \"bought-item\" achievement hook", "Fetch the \"nothing in stock\" template template = self.fetch_xml_template( \"shop.directory\",", "self.first_build = False # Add the new page self.add_widget_via_event(widget, event)", "their last item... if ( self.vendor.get_vendor_inventory_count() == 0 ): #", "control_center, universe = universe, execute_all = True ) # Refresh", "): results.append( self.handle_build_event(event, control_center, universe) ) # Select an item,", "universe) ) # Restore the universe to active game state,", "Fetch the widget dispatcher widget_dispatcher = control_center.get_widget_dispatcher() # Get a", "the NPC has no inventory available, we have just bought", "# Track whether this is the first build or a", "self.handle_kill_event(event, control_center, universe) ) # Return events return results #", "* item.get_cost() ) # Count as gold spent universe.increment_session_variable( \"stats.gold-spent\",", "results # Configure the shop menu (more options than your", "SCREEN_HEIGHT ), \"@item-name\": xml_encode( item.get_name() ), \"@item-title\": xml_encode( item.get_title() ),", "money = int( universe.get_session_variable(\"core.gold.wallet\").get_value() ) # Template version for this", "to loop entire script (?) ) # Check for an", "def handle_build_event(self, event, control_center, universe): # Events that result from", "Now we'll add an entry for each available item... for", "control_center, universe) ) # Finalize a \"back\" call elif (", "from handling this event (on-birth events, etc.) results = EventQueue()", "self.fetch_xml_template( \"shop.directory.insert\", version = template_version ).add_parameters({ \"@item-name\": xml_encode( item.name ),", "return results # Show the \"are you sure you wanna", "control_center.get_localization_controller().get_label(\"new-item-purchased:header\"), \"content\": item.get_title() }) # Add a historical record universe.add_historical_record(", "in stock at any given time self.max_items_stocked = 1 #", "the pause splash control_center.get_splash_controller().set_mode(SPLASH_MODE_GREYSCALE_ANIMATED) # Before populating the vendor's inventory", "#\"Bought [color=special]%s[/color] for [color=special]%s[/color] gold.\" % ( item.get_title(), item.get_cost() )", "} ) #\"Bought [color=special]%s[/color] for [color=special]%s[/color] gold.\" % ( item.get_title(),", "Let's just go back one page self.page_back(1) # Leave shop,", "much money do we currently have? money = int( universe.get_session_variable(\"core.gold.wallet\").get_value()", "Execute the \"bought-all-items\" achievement hook universe.execute_achievement_hook( \"bought-all-items\", control_center ) #", "menu configuration self.__std_configure__(options) if ( \"vendor\" in options ): self.vendor", "): self.message = options[\"message\"] if ( \"required-item-names\" in options ):", "Restore the universe to active game state, set this very", "m.run_script( name = \"%s.onpurchase\" % item.get_name(), control_center = control_center, universe", "Commit an item purchase def handle_shop_buy_item_event(self, event, control_center, universe): #", "widget_dispatcher = control_center.get_widget_dispatcher() # Pause the game so that we", "\"@n\": self.vendor.nick, \"@g\": item.get_cost() } ) #\"Bought [color=special]%s[/color] for [color=special]%s[/color]", "threshholds (low and high) self.min_item_quality = 0 self.max_item_quality = 0", "resume game action once done... control_center.get_splash_controller().dismiss( on_complete = \"game:unpause\" )", "# Execute the \"bought-all-items\" achievement hook universe.execute_achievement_hook( \"bought-all-items\", control_center )", "the shop menu, we'll first # make sure the NPC", "= options[\"message\"] if ( \"required-item-names\" in options ): self.required_item_names.extend( options[\"required-item-names\"]", "(SCREEN_WIDTH - PAUSE_MENU_WIDTH) / 2 ))) ), \"@y\": xml_encode( \"%d\"", "= False) # Return events return results # Commit an", "Get the active page page = self.get_active_page() # Validate if", "Shop title (e.g. \"Bob's Fine Items\") self.title = \"Shoppe\" #", "we load... if ( self.vendor.get_vendor_inventory_count() == 0 ): # Fetch", "universe stats for items bought universe.get_session_variable(\"stats.items-bought\").increment_value(1) # Execute the \"bought-item\"", "vendor... self.vendor.populate_vendor_inventory( min_quality = self.min_item_quality,#int( node.get_attribute(\"min-quality\") ), max_quality = self.max_item_quality,#int(", "universe, execute_all = True # Try to loop entire script", "definitely completed the first build now self.first_build = False #", "), \"@height\": xml_encode( \"%d\" % PAUSE_MENU_HEIGHT ), \"@shop-title\": xml_encode( self.title", "# Dismiss lightbox effect self.lightbox_controller.set_target(0) # Dismiss the splash controller,", "Grab handle item = universe.get_item_by_name(item_name) # Validate if (item): #", "template.compile_node_by_id(\"menu\") # We have items to sell... else: # Fetch", "result from event handling results = EventQueue() # Convenience (action,", "one page self.page_back(1) # Leave shop, resume game elif (", ") }) # Compile node = template.compile_node_by_id(\"insert\") # Inject into", "== \"show:confirm-purchase\" ): results.append( self.handle_show_confirm_purchase_event(event, control_center, universe) ) # Commit", "template_version = ( \"affordable\" if (money >= item.cost) else \"unaffordable\"", "game elif ( action == \"resume-game\" ): results.append( self.handle_resume_game_event(event, control_center,", "inventory self.vendor.remove_item_from_vendor_inventory( item.get_name() ) # Increase sales count for vendor", "# Commit an item purchase def handle_shop_buy_item_event(self, event, control_center, universe):", "options ): self.message = options[\"message\"] if ( \"required-item-names\" in options", "\"wallet-changed\", control_center ) # Increase universe stats for items bought", "reacts in some way to an item you might have", "item_name in self.vendor.get_vendor_inventory_item_names(): # Grab handle item = universe.get_item_by_name(item_name) #", "EventQueue() # Convenience params = event.get_params() # Done with the", "Pause the game so that we can shop, if this", "time self.max_items_stocked = 1 # Number of times the vendor", "item.get_name(), control_center = control_center, universe = universe, execute_all = True", "inventory. # Thus, if the NPC has no inventory available,", "Execute the \"bought-item\" achievement hook universe.execute_achievement_hook( \"bought-item\", control_center ) #", "action == \"game:buy-item\" ): results.append( self.handle_shop_buy_item_event(event, control_center, universe) ) #", "(animated) def handle_back_event(self, event, control_center, universe): # Events that result", "\"%d\" % PAUSE_MENU_HEIGHT ), \"@shop-title\": xml_encode( self.title ) }) #", "Fetch the widget dispatcher widget_dispatcher = control_center.get_widget_dispatcher() # Pause the", "code.constants.common import SCREEN_WIDTH, SCREEN_HEIGHT, PAUSE_MENU_X, PAUSE_MENU_Y, PAUSE_MENU_WIDTH, PAUSE_MENU_HEIGHT, MODE_GAME, TILE_WIDTH,", "control_center, universe) ) # Go to the previous page (e.g.", "to the previous page (e.g. close buy item confirm dialog)", "1) # After rebuilding the UI, we will have restocked", "many parameters) def configure(self, options): # Common menu configuration self.__std_configure__(options)", "item.name ), \"@item-title\": xml_encode( item.title ), \"@item-cost\": xml_encode( \"%d\" %", "Increase sales count for vendor self.vendor.increase_sales_count(1) # Reduce player's wallet", "= \"game:unpause\" ) #hmenu.slide(DIR_LEFT, percent = 1.0) #row_menu.slide(DIR_RIGHT, percent =", "), max_reloads = self.max_item_reloads,#int( node.get_attribute(\"max-reloads\") ), universe = universe )", "if (page): # Dismiss the page page.hide( on_complete = \"previous-page\"", "universe.acquire_item_by_name( item.get_name() ) # Post a newsfeeder notice control_center.get_window_controller().get_newsfeeder().post({ \"type\":", "results = EventQueue() # Convenience params = event.get_params() # Done", "handle_show_confirm_purchase_event(self, event, control_center, universe): # Events that result from handling", "from code.utils.common import coalesce, intersect, offset_rect, log, log2, xml_encode, xml_decode,", "\"%d\" % item.get_cost() ) }) # Compile template root =", "amount by the cost... universe.increment_session_variable( \"core.gold.wallet\", -1 * item.get_cost() )", "back a page (animated) def handle_back_event(self, event, control_center, universe): #", "the widget dispatcher widget_dispatcher = control_center.get_widget_dispatcher() # Pause the game", "inactive elif ( action == \"kill\" ): results.append( self.handle_kill_event(event, control_center,", "we need to define many parameters) def configure(self, options): #", "whether this is the first build or a refresh self.first_build", "active game state, set this very menu to inactive elif", "a refresh self.first_build = True # Fire build event self.fire_event(\"build\")", "universe) ) # Commit an item purchase elif ( action", "int(PAUSE_MENU_WIDTH / 2) ), \"@height\": xml_encode( \"%d\" % PAUSE_MENU_HEIGHT ),", "the new page self.add_widget_via_event(widget, event, exclusive = False) # Return", "whether we can afford it... template_version = ( \"affordable\" if", "\"stats.gold-spent\", item.get_cost() ) # Execute the \"wallet-changed\" achievement hook universe.execute_achievement_hook(", "Add the new page self.add_widget_via_event(widget, event) # Return events return", "a reference to the item (for cost info, etc.) item", "of times the vendor can restock self.max_item_reloads = 1 #", "active when shopping is done. def handle_kill_event(self, event, control_center, universe):", ") # Check for an onpurchase script (perhaps the game", "= EventQueue() # Convenience (action, params) = ( event.get_action(), event.get_params()", "a handle to the seller so that we can #", "handle_shop_buy_item_event(self, event, control_center, universe): # Events that result from handling", "Select an item, get confirmation... elif ( action == \"show:confirm-purchase\"", "offset_rect, log, log2, xml_encode, xml_decode, translate_rgb_to_string from code.constants.common import SCREEN_WIDTH,", "\"@height\": xml_encode( \"%d\" % PAUSE_MENU_HEIGHT ), \"@shop-title\": xml_encode( self.title ),", "menu widget; trash it. self.set_status(STATUS_INACTIVE) # Return events return results", "item.cost) else \"unaffordable\" ) # Fetch the appropriate template for", "menu, we need to define many parameters) def configure(self, options):", "= True # Try to loop entire script (?) )", "a page (animated) def handle_back_event(self, event, control_center, universe): # Events", "self.min_item_quality = int( options[\"min-quality\"] ) if ( \"max-quality\" in options", "\"max-quality\" in options ): self.max_item_quality = int( options[\"max-quality\"] ) if", "seller's inventory self.vendor.remove_item_from_vendor_inventory( item.get_name() ) # Increase sales count for", "or a refresh self.first_build = True # Fire build event", "Post a newsfeeder notice control_center.get_window_controller().get_newsfeeder().post({ \"type\": NEWS_ITEM_NEW, \"title\": control_center.get_localization_controller().get_label(\"new-item-purchased:header\"), \"content\":", "an item, get confirmation... elif ( action == \"show:confirm-purchase\" ):", "False # Add the new page self.add_widget_via_event(widget, event) # Return", "can restock self.max_item_reloads = 1 # Track whether this is", "if (item): # How much money do we currently have?", "generic \"onpurchase\" script for the vendor m.run_script( \"%s.onpurchase\" % self.vendor.get_name(),", "universe.get_session_variable(\"core.gold.wallet\").get_value() ) # Template version for this item depends on", "Leave the shop and resume play def handle_resume_game_event(self, event, control_center,", "# Convenience params = event.get_params() # Done with the shop", "by its name universe.acquire_item_by_name( item.get_name() ) # Post a newsfeeder", "come from already-lightboxed dialogues. self.lightbox_controller.set_interval( self.lightbox_controller.get_target() ) # We're going", "control_center, universe) ) # Restore the universe to active game", "item.get_cost() ) # Execute the \"wallet-changed\" achievement hook universe.execute_achievement_hook( \"wallet-changed\",", "the first build now self.first_build = False # Add the", "# Now we'll add an entry for each available item...", "\"%d\" % PAUSE_MENU_HEIGHT ), \"@shop-title\": xml_encode( self.title ), \"@salutation\": xml_encode(", "Execute the \"wallet-changed\" achievement hook universe.execute_achievement_hook( \"wallet-changed\", control_center ) #", "# Add a historical record universe.add_historical_record( \"purchases\", control_center.get_localization_controller().get_label( \"purchased-m-from-n-for-g:message\", {", ") # Validate if (item): # Fetch confirm purchase template", "# Return events return results # Show the \"are you", "template.compile_node_by_id(\"menu\") # Now we'll add an entry for each available", "(for cost info, etc.) item = universe.get_item_by_name( params[\"item-name\"] ) #", "if this is the first build... if (self.first_build): # Pause", "action == \"previous-page\" ): # Let's just go back one", "control_center, universe, execute_all = True # Try to loop entire", "= universe.get_active_map() # Check for a generic \"onpurchase\" script for", "(e.g. close buy item confirm dialog) elif ( action ==", "on whether we can afford it... template_version = ( \"affordable\"", "configure(self, options): # Common menu configuration self.__std_configure__(options) if ( \"vendor\"", "Reduce player's wallet amount by the cost... universe.increment_session_variable( \"core.gold.wallet\", -1", "# Compile node = template.compile_node_by_id(\"insert\") # Inject into inventory area...", "xml_encode( \"%d\" % SCREEN_HEIGHT ), \"@item-name\": xml_encode( item.get_name() ), \"@item-title\":", "result from handling this event (on-birth events, etc.) results =", "/ 2 ))) ), \"@y\": xml_encode( \"%d\" % PAUSE_MENU_Y ),", "remove items from their inventory after a purchase... self.vendor =", "build... if (self.first_build): # Pause universe.pause() # Call in the", "notice control_center.get_window_controller().get_newsfeeder().post({ \"type\": NEWS_ITEM_NEW, \"title\": control_center.get_localization_controller().get_label(\"new-item-purchased:header\"), \"content\": item.get_title() }) #", "intersect, offset_rect, log, log2, xml_encode, xml_decode, translate_rgb_to_string from code.constants.common import", "seller stocks any specified \"required\" items... self.required_item_names = [] #", "template = self.fetch_xml_template( \"shop.directory\", version = \"default\" ).add_parameters({ \"@x\": xml_encode(", "Pause universe.pause() # Call in the pause splash control_center.get_splash_controller().set_mode(SPLASH_MODE_GREYSCALE_ANIMATED) #", "build or a refresh self.first_build = True # Fire build", "the vendor have anything in stock? Use this data #", "inventory after a purchase... self.vendor = None#seller # Shop title", "Number of times the vendor can restock self.max_item_reloads = 1", "map m = universe.get_active_map() # Check for a generic \"onpurchase\"", "import Menu from code.tools.eventqueue import EventQueue from code.tools.xml import XMLParser", "now self.first_build = False # Add the new page self.add_widget_via_event(widget,", "NPC's inventory. # Thus, if the NPC has no inventory", "bought their last item... if ( self.vendor.get_vendor_inventory_count() == 0 ):", "( \"message\" in options ): self.message = options[\"message\"] if (", "handling this event (on-birth events, etc.) results = EventQueue() #", "# Dismiss the splash controller, calling to resume game action", "handle_build_event(self, event, control_center, universe): # Events that result from handling", "so that we can # remove items from their inventory", "min_quality = self.min_item_quality,#int( node.get_attribute(\"min-quality\") ), max_quality = self.max_item_quality,#int( node.get_attribute(\"min-quality\") ),", "load... if ( self.vendor.get_vendor_inventory_count() == 0 ): # Fetch the", ") # Commit an item purchase elif ( action ==", "at \"home\" position for the shop self.get_widget_by_id(\"root\").set_cursor_at_beginning()#finalize = True) #", "controller, calling to resume game action once done... control_center.get_splash_controller().dismiss( on_complete", "Fire build event self.fire_event(\"build\") def handle_event(self, event, control_center, universe):#params, user_input,", "for [color=special]%s[/color] gold.\" % ( item.get_title(), item.get_cost() ) ) #", "\"content\": item.get_title() }) # Add a historical record universe.add_historical_record( \"purchases\",", "# Does the vendor have anything in stock? Use this", "splash controller, calling to resume game action once done... control_center.get_splash_controller().dismiss(", "if ( action == \"build\" ): results.append( self.handle_build_event(event, control_center, universe)", "Go back a page (animated) def handle_back_event(self, event, control_center, universe):", "self.message = options[\"message\"] if ( \"required-item-names\" in options ): self.required_item_names.extend(", "Build the shop menu def handle_build_event(self, event, control_center, universe): #", "at these great items\") self.message = \"Take a look at", "entry for each available item... for item_name in self.vendor.get_vendor_inventory_item_names(): #", "the seller so that we can # remove items from", "\"%d\" % PAUSE_MENU_Y ), \"@width\": xml_encode( \"%d\" % int(PAUSE_MENU_WIDTH /", "# Done with the shop menu widget; trash it. self.set_status(STATUS_INACTIVE)", "Done with the shop menu widget; trash it. self.set_status(STATUS_INACTIVE) #", "to set the cursor at \"home\" position for the shop", "# Configure the shop menu (more options than your typical", "build now self.first_build = False # Add the new page", "Try to loop entire script (?) ) # Check for", "options ): self.max_items_stocked = int( options[\"max-items\"] ) if ( \"max-reloads\"", "self.max_item_quality,#int( node.get_attribute(\"min-quality\") ), required_item_names = self.required_item_names, max_items = self.max_items_stocked,#int( node.get_attribute(\"max-items\")", "\"home\" position for the shop self.get_widget_by_id(\"root\").set_cursor_at_beginning()#finalize = True) # Return", "shop menu, we'll first # make sure the NPC seller", "universe) ) # Select an item, get confirmation... elif (", "universe.add_historical_record( \"purchases\", control_center.get_localization_controller().get_label( \"purchased-m-from-n-for-g:message\", { \"@m\": item.get_title(), \"@n\": self.vendor.nick, \"@g\":", "# Grab handle item = universe.get_item_by_name(item_name) # Validate if (item):", "Track item quality threshholds (low and high) self.min_item_quality = 0", "# Resume game, killing shop menu when widget disappears self.get_widget_by_id(\"root\").hide(", "# Fetch the widget dispatcher widget_dispatcher = control_center.get_widget_dispatcher() # Pause", "buy item confirm dialog) elif ( action == \"back\" ):", "event.get_params() # Get a reference to the item (for cost", "item.get_name() ) # Increase sales count for vendor self.vendor.increase_sales_count(1) #", "achievement hook universe.execute_achievement_hook( \"wallet-changed\", control_center ) # Increase universe stats", "options[\"max-reloads\"] ) # For chaining return self # Build the", "some way to an item you might have bought) m.run_script(", "( \"max-quality\" in options ): self.max_item_quality = int( options[\"max-quality\"] )", "this is the first build... if (self.first_build): # Pause universe.pause()", "template.compile_node_by_id(\"menu\") # Create widget widget = widget_dispatcher.convert_node_to_widget(root, control_center, universe) widget.set_id(\"confirm-shop-purchase\")", "if ( self.vendor.get_vendor_inventory_count() == 0 ): # Execute the \"bought-all-items\"", "self.handle_shop_buy_item_event(event, control_center, universe) ) # Go to the previous page", "chaining return self # Build the shop menu def handle_build_event(self,", "% self.vendor.get_name(), control_center, universe, execute_all = True # Try to", "): self.max_items_stocked = int( options[\"max-items\"] ) if ( \"max-reloads\" in", "widget.set_id(\"root\") # We have definitely completed the first build now", "Increase universe stats for items bought universe.get_session_variable(\"stats.items-bought\").increment_value(1) # Execute the", "we can shop, if this is the first build... if", "root = template.compile_node_by_id(\"menu\") # Now we'll add an entry for", "if ( \"title\" in options ): self.title = options[\"title\"] if", ") # Execute the \"wallet-changed\" achievement hook universe.execute_achievement_hook( \"wallet-changed\", control_center", "version = template_version ).add_parameters({ \"@item-name\": xml_encode( item.name ), \"@item-title\": xml_encode(", "Return events return results # Configure the shop menu (more", "refresh self.first_build = True # Fire build event self.fire_event(\"build\") def", "self.get_widget_by_id(\"root\").hide( on_complete = \"kill\" ) # Return events return results", "shopping is done. def handle_kill_event(self, event, control_center, universe): # Events", "onpurchase script (perhaps the game reacts in some way to", "self.vendor.get_vendor_inventory_item_names(): # Grab handle item = universe.get_item_by_name(item_name) # Validate if", "GAME_STATE_ACTIVE, GAME_STATE_NOT_READY from code.constants.newsfeeder import * class ShopMenu(Menu): def __init__(self):", "your typical menu, we need to define many parameters) def", "if ( \"max-reloads\" in options ): self.max_item_reloads = int( options[\"max-reloads\"]", "lightbox effect self.lightbox_controller.set_target(0) # Dismiss the splash controller, calling to", "killing shop menu when widget disappears self.get_widget_by_id(\"root\").hide( on_complete = \"kill\"", "# Get a handle to the actual item... item =", "Resume game, killing shop menu when widget disappears self.get_widget_by_id(\"root\").hide( on_complete", "stock? Use this data # to determine which template we", "= self.max_items_stocked,#int( node.get_attribute(\"max-items\") ), max_reloads = self.max_item_reloads,#int( node.get_attribute(\"max-reloads\") ), universe", "[color=special]%s[/color] gold.\" % ( item.get_title(), item.get_cost() ) ) # Remove", "just go back one page self.page_back(1) # Leave shop, resume", "\"@height\": xml_encode( \"%d\" % PAUSE_MENU_HEIGHT ), \"@shop-title\": xml_encode( self.title )", "universe to active game state, set this very menu to", "the item by its name universe.acquire_item_by_name( item.get_name() ) # Post", "this is the first build or a refresh self.first_build =", "Check for an onpurchase script (perhaps the game reacts in", "% item.get_name(), control_center = control_center, universe = universe, execute_all =", "splash control_center.get_splash_controller().set_mode(SPLASH_MODE_GREYSCALE_ANIMATED) # Before populating the vendor's inventory (or re-populating),", "from their inventory after a purchase... self.vendor = None#seller #", "return self # Build the shop menu def handle_build_event(self, event,", "elif ( action == \"previous-page\" ): # Let's just go", "0 ): # Execute the \"bought-all-items\" achievement hook universe.execute_achievement_hook( \"bought-all-items\",", "# Fetch the appropriate template for an individual item template", "/ 2) ), \"@height\": xml_encode( \"%d\" % SCREEN_HEIGHT ), \"@item-name\":", "to the item (for cost info, etc.) item = universe.get_item_by_name(", "version for this item depends on whether we can afford", "self.max_item_reloads = 1 # Track whether this is the first", "with the shop menu widget; trash it. self.set_status(STATUS_INACTIVE) # Return", "currently have? money = int( universe.get_session_variable(\"core.gold.wallet\").get_value() ) # Template version", "the item (for cost info, etc.) item = universe.get_item_by_name( params[\"item-name\"]", "Menu from code.tools.eventqueue import EventQueue from code.tools.xml import XMLParser from", "Common menu configuration self.__std_configure__(options) if ( \"vendor\" in options ):", "purchase template template = self.fetch_xml_template(\"shop.buy.confirm\").add_parameters({ \"@width\": xml_encode( \"%d\" % int(PAUSE_MENU_WIDTH", "in stock? Use this data # to determine which template", "- (int( (SCREEN_WIDTH - PAUSE_MENU_WIDTH) / 2 ))) ), \"@y\":", "back one page self.page_back(1) # Leave shop, resume game elif", "universe) ) # Go to the previous page (e.g. close", "loop entire script (?) ) # Check for an onpurchase", "}) # Compile template root = template.compile_node_by_id(\"menu\") # Now we'll", "to define many parameters) def configure(self, options): # Common menu", "2) ), \"@height\": xml_encode( \"%d\" % SCREEN_HEIGHT ), \"@item-name\": xml_encode(", "template.compile_node_by_id(\"insert\") # Inject into inventory area... root.find_node_by_id(\"ext.inventory\").add_node(node) # Create widget", "results # Go back a page (animated) def handle_back_event(self, event,", ") # Template version for this item depends on whether", "results # Commit an item purchase def handle_shop_buy_item_event(self, event, control_center,", "): results.append( self.handle_resume_game_event(event, control_center, universe) ) # Restore the universe", "\"purchases\", control_center.get_localization_controller().get_label( \"purchased-m-from-n-for-g:message\", { \"@m\": item.get_title(), \"@n\": self.vendor.nick, \"@g\": item.get_cost()", "def handle_resume_game_event(self, event, control_center, universe): # Events that result from", "state, set this very menu to inactive elif ( action", "\"@salutation\": xml_encode( self.message ) }) # Compile template root =", "required_item_names = self.required_item_names, max_items = self.max_items_stocked,#int( node.get_attribute(\"max-items\") ), max_reloads =", "handle_event(self, event, control_center, universe):#params, user_input, network_controller, universe, active_map, session, widget_dispatcher,", "vendor self.vendor.increase_sales_count(1) # Reduce player's wallet amount by the cost...", "NPC has no inventory available, we have just bought their", "== \"resume-game\" ): results.append( self.handle_resume_game_event(event, control_center, universe) ) # Restore", "of any items the player has acquired since last shopping", "= widget_dispatcher.convert_node_to_widget(root, control_center, universe) widget.set_id(\"root\") # We have definitely completed", "\"required-item-names\" in options ): self.required_item_names.extend( options[\"required-item-names\"] )#.split(\";\") ) if (", "# How much money do we currently have? money =", "m.run_script( \"%s.onpurchase\" % self.vendor.get_name(), control_center, universe, execute_all = True #", "populating the vendor's inventory (or re-populating), # clear it of", ") # Remove from seller's inventory self.vendor.remove_item_from_vendor_inventory( item.get_name() ) #", "options[\"min-quality\"] ) if ( \"max-quality\" in options ): self.max_item_quality =", "handle_kill_event(self, event, control_center, universe): # Events that result from handling", "results.append( self.handle_kill_event(event, control_center, universe) ) # Return events return results", "self.max_item_reloads = int( options[\"max-reloads\"] ) # For chaining return self", "# We have definitely completed the first build now self.first_build", ") # Acquire the item by its name universe.acquire_item_by_name( item.get_name()", "self.lightbox_controller.get_target() ) # We're going to keep a handle to", "% SCREEN_HEIGHT ), \"@item-name\": xml_encode( item.get_name() ), \"@item-title\": xml_encode( item.get_title()", "Compile template root = template.compile_node_by_id(\"menu\") # We have items to", "page def handle_show_confirm_purchase_event(self, event, control_center, universe): # Events that result", "True # Try to loop entire script (?) ) #", "\"@shop-title\": xml_encode( self.title ) }) # Compile template root =", "): results.append( self.handle_shop_buy_item_event(event, control_center, universe) ) # Go to the", "confirm purchase template template = self.fetch_xml_template(\"shop.buy.confirm\").add_parameters({ \"@width\": xml_encode( \"%d\" %", "item.get_cost() ) }) # Compile template root = template.compile_node_by_id(\"menu\") #", "the \"shopping directory\" template template = self.fetch_xml_template( \"shop.directory\", version =", "network_controller, universe, active_map, session, widget_dispatcher, text_renderer, save_controller, refresh = False):", "self.fetch_xml_template( \"shop.directory\", version = \"out-of-items\" ).add_parameters({ \"@x\": xml_encode( \"%d\" %", "game status back to active when shopping is done. def", "item you might have bought) m.run_script( name = \"%s.onpurchase\" %", "else: # Fetch the \"shopping directory\" template template = self.fetch_xml_template(", "\"resume-game\" ): results.append( self.handle_resume_game_event(event, control_center, universe) ) # Restore the", "Populate inventory for this shoppe's vendor... self.vendor.populate_vendor_inventory( min_quality = self.min_item_quality,#int(", "random import time from code.menu.menu import Menu from code.tools.eventqueue import", "on_complete = \"previous-page\" ) # Return events return results #", "PAUSE_MENU_HEIGHT, MODE_GAME, TILE_WIDTH, TILE_HEIGHT, DIR_UP, DIR_RIGHT, DIR_DOWN, DIR_LEFT, SPLASH_MODE_GREYSCALE_ANIMATED from", "#hmenu.slide(DIR_LEFT, percent = 1.0) #row_menu.slide(DIR_RIGHT, percent = 1.0) # Resume", "1 # Number of times the vendor can restock self.max_item_reloads", "def handle_show_confirm_purchase_event(self, event, control_center, universe): # Events that result from", "# Increase sales count for vendor self.vendor.increase_sales_count(1) # Reduce player's", "options ): self.max_item_quality = int( options[\"max-quality\"] ) if ( \"max-items\"", "self.title = options[\"title\"] if ( \"message\" in options ): self.message", "Build root menu if ( action == \"build\" ): results.append(", "control_center = control_center, universe = universe, execute_all = True )", "# Return events return results # Commit an item purchase", "if ( \"message\" in options ): self.message = options[\"message\"] if", "Does the vendor have anything in stock? Use this data", "active page page = self.get_active_page() # Validate if (page): #", "need to define many parameters) def configure(self, options): # Common", "MODE_GAME, TILE_WIDTH, TILE_HEIGHT, DIR_UP, DIR_RIGHT, DIR_DOWN, DIR_LEFT, SPLASH_MODE_GREYSCALE_ANIMATED from code.constants.states", "item.cost ), \"@item-advertisement\": xml_encode( item.description ) }) # Compile node", "# Inject into inventory area... root.find_node_by_id(\"ext.inventory\").add_node(node) # Create widget widget", "control_center.get_widget_dispatcher() # Get a handle to the actual item... item", "the \"nothing in stock\" template template = self.fetch_xml_template( \"shop.directory\", version", "\"Take a look at my inventory.\" # Before we begin", "Finalize a \"back\" call elif ( action == \"previous-page\" ):", "root = template.compile_node_by_id(\"menu\") # Create widget widget = widget_dispatcher.convert_node_to_widget(root, control_center,", "self.title = \"Shoppe\" # Salutation (e.g. \"Look at these great", "== \"build\" ): results.append( self.handle_build_event(event, control_center, universe) ) # Select", "universe) widget.set_id(\"confirm-shop-purchase\") # Add the new page self.add_widget_via_event(widget, event, exclusive", "m = universe.get_active_map() # Check for a generic \"onpurchase\" script", "): self.max_item_reloads = int( options[\"max-reloads\"] ) # For chaining return", "coalesce, intersect, offset_rect, log, log2, xml_encode, xml_decode, translate_rgb_to_string from code.constants.common", "items\") self.message = \"Take a look at my inventory.\" #", "self.max_item_reloads,#int( node.get_attribute(\"max-reloads\") ), universe = universe ) # Scope root", "# Refresh UI self.refresh_pages(control_center, universe, curtailed_count = 1) # After", "log2, xml_encode, xml_decode, translate_rgb_to_string from code.constants.common import SCREEN_WIDTH, SCREEN_HEIGHT, PAUSE_MENU_X,", "Scope root = None # Does the vendor have anything", "(or re-populating), # clear it of any items the player", "to active when shopping is done. def handle_kill_event(self, event, control_center,", "# Events that result from event handling results = EventQueue()", "Return events return results # Leave the shop and resume", "sell... else: # Fetch the \"shopping directory\" template template =", "\"max-items\" in options ): self.max_items_stocked = int( options[\"max-items\"] ) if", "# Populate inventory for this shoppe's vendor... self.vendor.populate_vendor_inventory( min_quality =", "achievement hook universe.execute_achievement_hook( \"bought-item\", control_center ) # Get the active", "in options ): self.message = options[\"message\"] if ( \"required-item-names\" in", "EventQueue from code.tools.xml import XMLParser from code.utils.common import coalesce, intersect,", "EventQueue() # Convenience params = event.get_params() # Dismiss lightbox effect", "# After rebuilding the UI, we will have restocked the", "events return results # Show the \"are you sure you", "options[\"required-item-names\"] )#.split(\";\") ) if ( \"min-quality\" in options ): self.min_item_quality", "universe) widget.set_id(\"root\") # We have definitely completed the first build", "Set game status back to active when shopping is done.", "= 0 self.max_item_quality = 0 # Items in stock at", "\"title\": control_center.get_localization_controller().get_label(\"new-item-purchased:header\"), \"content\": item.get_title() }) # Add a historical record", "given time self.max_items_stocked = 1 # Number of times the", "( \"affordable\" if (money >= item.cost) else \"unaffordable\" ) #", "script for the vendor m.run_script( \"%s.onpurchase\" % self.vendor.get_name(), control_center, universe,", "the \"bought-item\" achievement hook universe.execute_achievement_hook( \"bought-item\", control_center ) # Get", "session, widget_dispatcher, text_renderer, save_controller, refresh = False): # Events that", "action once done... control_center.get_splash_controller().dismiss( on_complete = \"game:unpause\" ) #hmenu.slide(DIR_LEFT, percent", "\"core.gold.wallet\", -1 * item.get_cost() ) # Count as gold spent", "from code.tools.xml import XMLParser from code.utils.common import coalesce, intersect, offset_rect,", "# Validate if (item): # How much money do we", "player's wallet amount by the cost... universe.increment_session_variable( \"core.gold.wallet\", -1 *", "\"Bob's Fine Items\") self.title = \"Shoppe\" # Salutation (e.g. \"Look", "item by its name universe.acquire_item_by_name( item.get_name() ) # Post a", "event.get_action(), event.get_params() ) # Build root menu if ( action", "we'll add an entry for each available item... for item_name", "\"bought-item\", control_center ) # Get the active map m =", "template_version ).add_parameters({ \"@item-name\": xml_encode( item.name ), \"@item-title\": xml_encode( item.title ),", "\"are you sure you wanna buy this?\" page def handle_show_confirm_purchase_event(self,", "\"shop.directory.insert\", version = template_version ).add_parameters({ \"@item-name\": xml_encode( item.name ), \"@item-title\":", "}) # Compile template root = template.compile_node_by_id(\"menu\") # We have", "page (e.g. close buy item confirm dialog) elif ( action", "= template_version ).add_parameters({ \"@item-name\": xml_encode( item.name ), \"@item-title\": xml_encode( item.title", ") # Go to the previous page (e.g. close buy", "to active game state, set this very menu to inactive", "sure the NPC seller stocks any specified \"required\" items... self.required_item_names", "menu when widget disappears self.get_widget_by_id(\"root\").hide( on_complete = \"kill\" ) #", "), max_quality = self.max_item_quality,#int( node.get_attribute(\"min-quality\") ), required_item_names = self.required_item_names, max_items", "universe.pause() # Call in the pause splash control_center.get_splash_controller().set_mode(SPLASH_MODE_GREYSCALE_ANIMATED) # Before", "item.get_title(), item.get_cost() ) ) # Remove from seller's inventory self.vendor.remove_item_from_vendor_inventory(", "= EventQueue() # Convenience params = event.get_params() # Get a", "disappears self.get_widget_by_id(\"root\").hide( on_complete = \"kill\" ) # Return events return", "Add the new page self.add_widget_via_event(widget, event, exclusive = False) #", "\"required\" items... self.required_item_names = [] # Track item quality threshholds", "# Before populating the vendor's inventory (or re-populating), # clear", "= \"kill\" ) # Return events return results # Kill", "params = event.get_params() # Dismiss lightbox effect self.lightbox_controller.set_target(0) # Dismiss", "universe) ) # Return events return results # Configure the", "you sure you wanna buy this?\" page def handle_show_confirm_purchase_event(self, event,", "self.handle_show_confirm_purchase_event(event, control_center, universe) ) # Commit an item purchase elif", "math import random import time from code.menu.menu import Menu from", "item depends on whether we can afford it... template_version =", "the shop self.get_widget_by_id(\"root\").set_cursor_at_beginning()#finalize = True) # Return events return results", "\"@item-advertisement\": xml_encode( item.description ) }) # Compile node = template.compile_node_by_id(\"insert\")", "Kill event. Set game status back to active when shopping", "params = event.get_params() # Fetch the widget dispatcher widget_dispatcher =", "self.max_item_quality = 0 # Items in stock at any given", "to inactive elif ( action == \"kill\" ): results.append( self.handle_kill_event(event,", "to sell... else: # Fetch the \"shopping directory\" template template", "# Get the active map m = universe.get_active_map() # Check", "which template we load... if ( self.vendor.get_vendor_inventory_count() == 0 ):", "percent = 1.0) #row_menu.slide(DIR_RIGHT, percent = 1.0) # Resume game,", "# Leave shop, resume game elif ( action == \"resume-game\"", "specified \"required\" items... self.required_item_names = [] # Track item quality", ") if ( \"max-reloads\" in options ): self.max_item_reloads = int(", ") #hmenu.slide(DIR_LEFT, percent = 1.0) #row_menu.slide(DIR_RIGHT, percent = 1.0) #", "define many parameters) def configure(self, options): # Common menu configuration", "has no inventory available, we have just bought their last", "Acquire the item by its name universe.acquire_item_by_name( item.get_name() ) #", "/ 2) ), \"@height\": xml_encode( \"%d\" % PAUSE_MENU_HEIGHT ), \"@shop-title\":", "last shopping with this vendor... self.vendor.remove_erstwhile_acquired_items_from_inventory(universe) # Populate inventory for", "= template.compile_node_by_id(\"menu\") # We have items to sell... else: #", "in some way to an item you might have bought)", "(?) ) # Check for an onpurchase script (perhaps the", "any specified \"required\" items... self.required_item_names = [] # Track item", "Track whether this is the first build or a refresh", "for a generic \"onpurchase\" script for the vendor m.run_script( \"%s.onpurchase\"", "gold.\" % ( item.get_title(), item.get_cost() ) ) # Remove from", "\"@height\": xml_encode( \"%d\" % SCREEN_HEIGHT ), \"@item-name\": xml_encode( item.get_name() ),", "Fetch the appropriate template for an individual item template =", "import XMLParser from code.utils.common import coalesce, intersect, offset_rect, log, log2,", "stock\" template template = self.fetch_xml_template( \"shop.directory\", version = \"out-of-items\" ).add_parameters({", "\"%s.onpurchase\" % item.get_name(), control_center = control_center, universe = universe, execute_all", "\"@item-title\": xml_encode( item.title ), \"@item-cost\": xml_encode( \"%d\" % item.cost ),", "page self.page_back(1) # Leave shop, resume game elif ( action", "Dismiss the page page.hide( on_complete = \"previous-page\" ) # Return", "import os import math import random import time from code.menu.menu", "universe): # Events that result from handling this event (on-birth", "\"Look at these great items\") self.message = \"Take a look", "for an individual item template = self.fetch_xml_template( \"shop.directory.insert\", version =", "event.get_params() # Dismiss lightbox effect self.lightbox_controller.set_target(0) # Dismiss the splash", "): # Fetch the \"nothing in stock\" template template =", "# For chaining return self # Build the shop menu", "( \"min-quality\" in options ): self.min_item_quality = int( options[\"min-quality\"] )", "xml_encode( \"%d\" % PAUSE_MENU_Y ), \"@width\": xml_encode( \"%d\" % int(PAUSE_MENU_WIDTH", "# Items in stock at any given time self.max_items_stocked =", "player has acquired since last shopping with this vendor... self.vendor.remove_erstwhile_acquired_items_from_inventory(universe)", "(e.g. \"Bob's Fine Items\") self.title = \"Shoppe\" # Salutation (e.g.", "re-populating), # clear it of any items the player has", "item... for item_name in self.vendor.get_vendor_inventory_item_names(): # Grab handle item =", "self.lightbox_controller.set_interval( self.lightbox_controller.get_target() ) # We're going to keep a handle", "the cursor at \"home\" position for the shop self.get_widget_by_id(\"root\").set_cursor_at_beginning()#finalize =", "from code.constants.states import STATUS_ACTIVE, STATUS_INACTIVE, GAME_STATE_ACTIVE, GAME_STATE_NOT_READY from code.constants.newsfeeder import", "execute_all = True # Try to loop entire script (?)", "os import math import random import time from code.menu.menu import", "= int( universe.get_session_variable(\"core.gold.wallet\").get_value() ) # Template version for this item", "a generic \"onpurchase\" script for the vendor m.run_script( \"%s.onpurchase\" %", "since last shopping with this vendor... self.vendor.remove_erstwhile_acquired_items_from_inventory(universe) # Populate inventory", "options): # Common menu configuration self.__std_configure__(options) if ( \"vendor\" in", "), \"@item-title\": xml_encode( item.title ), \"@item-cost\": xml_encode( \"%d\" % item.cost", "control_center, universe) ) # Select an item, get confirmation... elif", ") #\"Bought [color=special]%s[/color] for [color=special]%s[/color] gold.\" % ( item.get_title(), item.get_cost()", "% PAUSE_MENU_HEIGHT ), \"@shop-title\": xml_encode( self.title ), \"@salutation\": xml_encode( self.message", "): results.append( self.handle_back_event(event, control_center, universe) ) # Finalize a \"back\"", "(page): # Dismiss the page page.hide( on_complete = \"previous-page\" )", "widget = widget_dispatcher.convert_node_to_widget(root, control_center, universe) widget.set_id(\"confirm-shop-purchase\") # Add the new", "# Call in the pause splash control_center.get_splash_controller().set_mode(SPLASH_MODE_GREYSCALE_ANIMATED) # Before populating", ") # Count as gold spent universe.increment_session_variable( \"stats.gold-spent\", item.get_cost() )", "we have just bought their last item... if ( self.vendor.get_vendor_inventory_count()", ") # Return events return results # Leave the shop", "We're going to keep a handle to the seller so", "build event self.fire_event(\"build\") def handle_event(self, event, control_center, universe):#params, user_input, network_controller,", "Create widget widget = widget_dispatcher.convert_node_to_widget(root, control_center, universe) widget.set_id(\"root\") # We", "= event.get_params() # Dismiss lightbox effect self.lightbox_controller.set_target(0) # Dismiss the", "== \"game:buy-item\" ): results.append( self.handle_shop_buy_item_event(event, control_center, universe) ) # Go", ") }) # Compile template root = template.compile_node_by_id(\"menu\") # We", "( event.get_action(), event.get_params() ) # Build root menu if (", "hook universe.execute_achievement_hook( \"bought-item\", control_center ) # Get the active map", "( action == \"game:buy-item\" ): results.append( self.handle_shop_buy_item_event(event, control_center, universe) )", "execute_all = True ) # Refresh UI self.refresh_pages(control_center, universe, curtailed_count", "Before we begin populating the shop menu, we'll first #", "refresh = False): # Events that result from event handling", "universe ) # Scope root = None # Does the", "to resume game action once done... control_center.get_splash_controller().dismiss( on_complete = \"game:unpause\"", "in options ): self.min_item_quality = int( options[\"min-quality\"] ) if (", "self.vendor.populate_vendor_inventory( min_quality = self.min_item_quality,#int( node.get_attribute(\"min-quality\") ), max_quality = self.max_item_quality,#int( node.get_attribute(\"min-quality\")", "game, killing shop menu when widget disappears self.get_widget_by_id(\"root\").hide( on_complete =", "= widget_dispatcher.convert_node_to_widget(root, control_center, universe) widget.set_id(\"confirm-shop-purchase\") # Add the new page", "# Reduce player's wallet amount by the cost... universe.increment_session_variable( \"core.gold.wallet\",", "int( options[\"max-reloads\"] ) # For chaining return self # Build", "): # Let's just go back one page self.page_back(1) #", "into inventory area... root.find_node_by_id(\"ext.inventory\").add_node(node) # Create widget widget = widget_dispatcher.convert_node_to_widget(root,", "event handling results = EventQueue() # Convenience (action, params) =", "widget dispatcher widget_dispatcher = control_center.get_widget_dispatcher() # Get a handle to", "my inventory.\" # Before we begin populating the shop menu,", "# Validate if (item): # Fetch confirm purchase template template", ") # Return events return results # Configure the shop", "item.title ), \"@item-cost\": xml_encode( \"%d\" % item.cost ), \"@item-advertisement\": xml_encode(", "the game reacts in some way to an item you", "# We're going to keep a handle to the seller", "# Try to loop entire script (?) ) # Check", "Convenience params = event.get_params() # Fetch the widget dispatcher widget_dispatcher", "template template = self.fetch_xml_template( \"shop.directory\", version = \"default\" ).add_parameters({ \"@x\":", "log, log2, xml_encode, xml_decode, translate_rgb_to_string from code.constants.common import SCREEN_WIDTH, SCREEN_HEIGHT,", "restocked the NPC's inventory. # Thus, if the NPC has", "# Salutation (e.g. \"Look at these great items\") self.message =", "== \"kill\" ): results.append( self.handle_kill_event(event, control_center, universe) ) # Return", "None#seller # Shop title (e.g. \"Bob's Fine Items\") self.title =", "done... control_center.get_splash_controller().dismiss( on_complete = \"game:unpause\" ) #hmenu.slide(DIR_LEFT, percent = 1.0)", "PAUSE_MENU_HEIGHT ), \"@shop-title\": xml_encode( self.title ) }) # Compile template", "go back one page self.page_back(1) # Leave shop, resume game", "action == \"kill\" ): results.append( self.handle_kill_event(event, control_center, universe) ) #", "calling to resume game action once done... control_center.get_splash_controller().dismiss( on_complete =", "= 0 # Items in stock at any given time", "), universe = universe ) # Scope root = None", "widget_dispatcher = control_center.get_widget_dispatcher() # Get a handle to the actual", "xml_encode( item.title ), \"@item-cost\": xml_encode( \"%d\" % item.cost ), \"@item-advertisement\":", "universe.execute_achievement_hook( \"bought-item\", control_center ) # Get the active map m", "Fetch the \"shopping directory\" template template = self.fetch_xml_template( \"shop.directory\", version", "exclusive = False) # Return events return results # Commit", "action == \"back\" ): results.append( self.handle_back_event(event, control_center, universe) ) #", "item.description ) }) # Compile node = template.compile_node_by_id(\"insert\") # Inject", "def configure(self, options): # Common menu configuration self.__std_configure__(options) if (", "self.max_items_stocked,#int( node.get_attribute(\"max-items\") ), max_reloads = self.max_item_reloads,#int( node.get_attribute(\"max-reloads\") ), universe =", "= ( \"affordable\" if (money >= item.cost) else \"unaffordable\" )", "the active page page = self.get_active_page() # Validate if (page):", "\"game:unpause\" ) #hmenu.slide(DIR_LEFT, percent = 1.0) #row_menu.slide(DIR_RIGHT, percent = 1.0)", "# Events that result from handling this event (on-birth events,", "self.vendor.remove_item_from_vendor_inventory( item.get_name() ) # Increase sales count for vendor self.vendor.increase_sales_count(1)", "action == \"resume-game\" ): results.append( self.handle_resume_game_event(event, control_center, universe) ) #", "etc.) results = EventQueue() # Convenience params = event.get_params() #", ") if ( \"max-items\" in options ): self.max_items_stocked = int(", "the appropriate template for an individual item template = self.fetch_xml_template(", "( self.vendor.get_vendor_inventory_count() == 0 ): # Fetch the \"nothing in", "\"bought-all-items\", control_center ) # I'm going to set the cursor", "quality threshholds (low and high) self.min_item_quality = 0 self.max_item_quality =", "\"%d\" % int(PAUSE_MENU_WIDTH / 2) ), \"@height\": xml_encode( \"%d\" %", "this very menu to inactive elif ( action == \"kill\"", "results = EventQueue() # Convenience params = event.get_params() # Fetch", "% (SCREEN_WIDTH - (int( (SCREEN_WIDTH - PAUSE_MENU_WIDTH) / 2 )))", "self.fetch_xml_template( \"shop.directory\", version = \"default\" ).add_parameters({ \"@x\": xml_encode( \"%d\" %", "control_center, universe) widget.set_id(\"confirm-shop-purchase\") # Add the new page self.add_widget_via_event(widget, event,", "dialog) elif ( action == \"back\" ): results.append( self.handle_back_event(event, control_center,", "an onpurchase script (perhaps the game reacts in some way", "= control_center, universe = universe, execute_all = True ) #", "import random import time from code.menu.menu import Menu from code.tools.eventqueue", "each available item... for item_name in self.vendor.get_vendor_inventory_item_names(): # Grab handle", "we'll first # make sure the NPC seller stocks any", "first build now self.first_build = False # Add the new", "\"shop.directory\", version = \"out-of-items\" ).add_parameters({ \"@x\": xml_encode( \"%d\" % (SCREEN_WIDTH", "this data # to determine which template we load... if", "code.menu.menu import Menu from code.tools.eventqueue import EventQueue from code.tools.xml import", "code.constants.newsfeeder import * class ShopMenu(Menu): def __init__(self): Menu.__init__(self) # Assume", "item = universe.get_item_by_name(item_name) # Validate if (item): # How much", "= self.fetch_xml_template(\"shop.buy.confirm\").add_parameters({ \"@width\": xml_encode( \"%d\" % int(PAUSE_MENU_WIDTH / 2) ),", "(perhaps the game reacts in some way to an item", "root.find_node_by_id(\"ext.inventory\").add_node(node) # Create widget widget = widget_dispatcher.convert_node_to_widget(root, control_center, universe) widget.set_id(\"root\")", "class ShopMenu(Menu): def __init__(self): Menu.__init__(self) # Assume all shop menus", "event, exclusive = False) # Return events return results #", "have? money = int( universe.get_session_variable(\"core.gold.wallet\").get_value() ) # Template version for", "widget_dispatcher, text_renderer, save_controller, refresh = False): # Events that result", "seller so that we can # remove items from their", "we currently have? money = int( universe.get_session_variable(\"core.gold.wallet\").get_value() ) # Template", "it of any items the player has acquired since last", "page self.add_widget_via_event(widget, event, exclusive = False) # Return events return", "might have bought) m.run_script( name = \"%s.onpurchase\" % item.get_name(), control_center", "item = universe.get_item_by_name( params[\"item-name\"] ) # Acquire the item by", "widget widget = widget_dispatcher.convert_node_to_widget(root, control_center, universe) widget.set_id(\"confirm-shop-purchase\") # Add the", "title (e.g. \"Bob's Fine Items\") self.title = \"Shoppe\" # Salutation", "= template.compile_node_by_id(\"menu\") # Now we'll add an entry for each", "# Template version for this item depends on whether we", "# Get the active page page = self.get_active_page() # Validate", "the splash controller, calling to resume game action once done...", "(action, params) = ( event.get_action(), event.get_params() ) # Build root", "way to an item you might have bought) m.run_script( name", "= [] # Track item quality threshholds (low and high)", "= 1) # After rebuilding the UI, we will have", "self.required_item_names.extend( options[\"required-item-names\"] )#.split(\";\") ) if ( \"min-quality\" in options ):", ") # Restore the universe to active game state, set", "individual item template = self.fetch_xml_template( \"shop.directory.insert\", version = template_version ).add_parameters({", "anything in stock? Use this data # to determine which", "the NPC seller stocks any specified \"required\" items... self.required_item_names =", "return results # Configure the shop menu (more options than", "the vendor's inventory (or re-populating), # clear it of any", "item.get_title(), \"@n\": self.vendor.nick, \"@g\": item.get_cost() } ) #\"Bought [color=special]%s[/color] for", "= ( event.get_action(), event.get_params() ) # Build root menu if", "in stock\" template template = self.fetch_xml_template( \"shop.directory\", version = \"out-of-items\"", "% PAUSE_MENU_Y ), \"@width\": xml_encode( \"%d\" % int(PAUSE_MENU_WIDTH / 2)", "template = self.fetch_xml_template( \"shop.directory.insert\", version = template_version ).add_parameters({ \"@item-name\": xml_encode(", "), \"@item-cost\": xml_encode( \"%d\" % item.get_cost() ) }) # Compile", "( action == \"show:confirm-purchase\" ): results.append( self.handle_show_confirm_purchase_event(event, control_center, universe) )", "can shop, if this is the first build... if (self.first_build):", "the previous page (e.g. close buy item confirm dialog) elif", "so that we can shop, if this is the first", "event.get_params() # Get the active page page = self.get_active_page() #", "= universe.get_item_by_name(item_name) # Validate if (item): # How much money", "version = \"default\" ).add_parameters({ \"@x\": xml_encode( \"%d\" % (SCREEN_WIDTH -", "self.vendor.get_vendor_inventory_count() == 0 ): # Fetch the \"nothing in stock\"", "the universe to active game state, set this very menu", "): self.vendor = options[\"vendor\"] if ( \"title\" in options ):", "it... template_version = ( \"affordable\" if (money >= item.cost) else", "= int( options[\"max-quality\"] ) if ( \"max-items\" in options ):", "\"@m\": item.get_title(), \"@n\": self.vendor.nick, \"@g\": item.get_cost() } ) #\"Bought [color=special]%s[/color]", "the NPC's inventory. # Thus, if the NPC has no", "Events that result from handling this event (on-birth events, etc.)", "have anything in stock? Use this data # to determine", "= self.max_item_reloads,#int( node.get_attribute(\"max-reloads\") ), universe = universe ) # Scope", "in options ): self.max_item_quality = int( options[\"max-quality\"] ) if (", "- PAUSE_MENU_WIDTH) / 2 ))) ), \"@y\": xml_encode( \"%d\" %", "with this vendor... self.vendor.remove_erstwhile_acquired_items_from_inventory(universe) # Populate inventory for this shoppe's", "this item depends on whether we can afford it... template_version", "# Remove from seller's inventory self.vendor.remove_item_from_vendor_inventory( item.get_name() ) # Increase", "elif ( action == \"show:confirm-purchase\" ): results.append( self.handle_show_confirm_purchase_event(event, control_center, universe)", "), \"@item-advertisement\": xml_encode( item.description ) }) # Compile node =", "menu if ( action == \"build\" ): results.append( self.handle_build_event(event, control_center,", "universe = universe ) # Scope root = None #", "= event.get_params() # Fetch the widget dispatcher widget_dispatcher = control_center.get_widget_dispatcher()", "\"%s.onpurchase\" % self.vendor.get_name(), control_center, universe, execute_all = True # Try", "going to keep a handle to the seller so that", "inventory.\" # Before we begin populating the shop menu, we'll", "typical menu, we need to define many parameters) def configure(self,", "a look at my inventory.\" # Before we begin populating", "))) ), \"@y\": xml_encode( \"%d\" % PAUSE_MENU_Y ), \"@width\": xml_encode(", "achievement hook universe.execute_achievement_hook( \"bought-all-items\", control_center ) # I'm going to", "= False # Add the new page self.add_widget_via_event(widget, event) #", "shop menus come from already-lightboxed dialogues. self.lightbox_controller.set_interval( self.lightbox_controller.get_target() ) #", "is the first build or a refresh self.first_build = True", "0 # Items in stock at any given time self.max_items_stocked", "shopping with this vendor... self.vendor.remove_erstwhile_acquired_items_from_inventory(universe) # Populate inventory for this", "import time from code.menu.menu import Menu from code.tools.eventqueue import EventQueue", "inventory (or re-populating), # clear it of any items the", "), \"@height\": xml_encode( \"%d\" % SCREEN_HEIGHT ), \"@item-name\": xml_encode( item.get_name()", "a handle to the actual item... item = universe.get_item_by_name( params[\"item-name\"]", "the \"bought-all-items\" achievement hook universe.execute_achievement_hook( \"bought-all-items\", control_center ) # I'm", "Inject into inventory area... root.find_node_by_id(\"ext.inventory\").add_node(node) # Create widget widget =", "node.get_attribute(\"max-items\") ), max_reloads = self.max_item_reloads,#int( node.get_attribute(\"max-reloads\") ), universe = universe", "at any given time self.max_items_stocked = 1 # Number of", "curtailed_count = 1) # After rebuilding the UI, we will", "Count as gold spent universe.increment_session_variable( \"stats.gold-spent\", item.get_cost() ) # Execute", "shop self.get_widget_by_id(\"root\").set_cursor_at_beginning()#finalize = True) # Return events return results #", "info, etc.) item = universe.get_item_by_name( params[\"item-name\"] ) # Acquire the", "dialogues. self.lightbox_controller.set_interval( self.lightbox_controller.get_target() ) # We're going to keep a", "# Convenience (action, params) = ( event.get_action(), event.get_params() ) #", "elif ( action == \"kill\" ): results.append( self.handle_kill_event(event, control_center, universe)", "[] # Track item quality threshholds (low and high) self.min_item_quality", "event, control_center, universe):#params, user_input, network_controller, universe, active_map, session, widget_dispatcher, text_renderer,", "Get a reference to the item (for cost info, etc.)", "[color=special]%s[/color] for [color=special]%s[/color] gold.\" % ( item.get_title(), item.get_cost() ) )", "def handle_event(self, event, control_center, universe):#params, user_input, network_controller, universe, active_map, session,", "TILE_WIDTH, TILE_HEIGHT, DIR_UP, DIR_RIGHT, DIR_DOWN, DIR_LEFT, SPLASH_MODE_GREYSCALE_ANIMATED from code.constants.states import", "self.first_build = True # Fire build event self.fire_event(\"build\") def handle_event(self,", "for an onpurchase script (perhaps the game reacts in some", "Validate if (item): # Fetch confirm purchase template template =", "control_center.get_window_controller().get_newsfeeder().post({ \"type\": NEWS_ITEM_NEW, \"title\": control_center.get_localization_controller().get_label(\"new-item-purchased:header\"), \"content\": item.get_title() }) # Add", "I'm going to set the cursor at \"home\" position for", "xml_encode( \"%d\" % (SCREEN_WIDTH - (int( (SCREEN_WIDTH - PAUSE_MENU_WIDTH) /", "handle_back_event(self, event, control_center, universe): # Events that result from handling", "= self.fetch_xml_template( \"shop.directory.insert\", version = template_version ).add_parameters({ \"@item-name\": xml_encode( item.name", "actual item... item = universe.get_item_by_name( params[\"item-name\"] ) # Validate if", "xml_encode( item.get_name() ), \"@item-title\": xml_encode( item.get_title() ), \"@item-cost\": xml_encode( \"%d\"", "import EventQueue from code.tools.xml import XMLParser from code.utils.common import coalesce,", "Return events return results # Show the \"are you sure", "== 0 ): # Execute the \"bought-all-items\" achievement hook universe.execute_achievement_hook(", "int( options[\"max-quality\"] ) if ( \"max-items\" in options ): self.max_items_stocked", "dispatcher widget_dispatcher = control_center.get_widget_dispatcher() # Get a handle to the", "all shop menus come from already-lightboxed dialogues. self.lightbox_controller.set_interval( self.lightbox_controller.get_target() )", "import STATUS_ACTIVE, STATUS_INACTIVE, GAME_STATE_ACTIVE, GAME_STATE_NOT_READY from code.constants.newsfeeder import * class", "done. def handle_kill_event(self, event, control_center, universe): # Events that result", "# Restore the universe to active game state, set this", "if (self.first_build): # Pause universe.pause() # Call in the pause", "after a purchase... self.vendor = None#seller # Shop title (e.g.", "self.add_widget_via_event(widget, event) # Return events return results # Show the", "add an entry for each available item... for item_name in", "self.fire_event(\"build\") def handle_event(self, event, control_center, universe):#params, user_input, network_controller, universe, active_map,", "results # Leave the shop and resume play def handle_resume_game_event(self,", "node.get_attribute(\"min-quality\") ), max_quality = self.max_item_quality,#int( node.get_attribute(\"min-quality\") ), required_item_names = self.required_item_names,", "Items in stock at any given time self.max_items_stocked = 1", "make sure the NPC seller stocks any specified \"required\" items...", "self.title ) }) # Compile template root = template.compile_node_by_id(\"menu\") #", "= self.fetch_xml_template( \"shop.directory\", version = \"default\" ).add_parameters({ \"@x\": xml_encode( \"%d\"", "# Return events return results # Go back a page", "= int( options[\"max-items\"] ) if ( \"max-reloads\" in options ):", "PAUSE_MENU_Y, PAUSE_MENU_WIDTH, PAUSE_MENU_HEIGHT, MODE_GAME, TILE_WIDTH, TILE_HEIGHT, DIR_UP, DIR_RIGHT, DIR_DOWN, DIR_LEFT,", "SCREEN_HEIGHT, PAUSE_MENU_X, PAUSE_MENU_Y, PAUSE_MENU_WIDTH, PAUSE_MENU_HEIGHT, MODE_GAME, TILE_WIDTH, TILE_HEIGHT, DIR_UP, DIR_RIGHT,", "any given time self.max_items_stocked = 1 # Number of times", "# Build root menu if ( action == \"build\" ):", "first # make sure the NPC seller stocks any specified", "universe, curtailed_count = 1) # After rebuilding the UI, we", "if (item): # Fetch confirm purchase template template = self.fetch_xml_template(\"shop.buy.confirm\").add_parameters({", "params[\"item-name\"] ) # Acquire the item by its name universe.acquire_item_by_name(", "STATUS_INACTIVE, GAME_STATE_ACTIVE, GAME_STATE_NOT_READY from code.constants.newsfeeder import * class ShopMenu(Menu): def", "action == \"show:confirm-purchase\" ): results.append( self.handle_show_confirm_purchase_event(event, control_center, universe) ) #", "call elif ( action == \"previous-page\" ): # Let's just", "self.required_item_names, max_items = self.max_items_stocked,#int( node.get_attribute(\"max-items\") ), max_reloads = self.max_item_reloads,#int( node.get_attribute(\"max-reloads\")", "historical record universe.add_historical_record( \"purchases\", control_center.get_localization_controller().get_label( \"purchased-m-from-n-for-g:message\", { \"@m\": item.get_title(), \"@n\":", "Convenience params = event.get_params() # Get the active page page", "universe.execute_achievement_hook( \"wallet-changed\", control_center ) # Increase universe stats for items", "count for vendor self.vendor.increase_sales_count(1) # Reduce player's wallet amount by", "universe, execute_all = True ) # Refresh UI self.refresh_pages(control_center, universe,", "results.append( self.handle_resume_game_event(event, control_center, universe) ) # Restore the universe to", "\"@item-name\": xml_encode( item.get_name() ), \"@item-title\": xml_encode( item.get_title() ), \"@item-cost\": xml_encode(", "universe.get_item_by_name( params[\"item-name\"] ) # Acquire the item by its name", "xml_encode( \"%d\" % item.cost ), \"@item-advertisement\": xml_encode( item.description ) })", "shop and resume play def handle_resume_game_event(self, event, control_center, universe): #", "XMLParser from code.utils.common import coalesce, intersect, offset_rect, log, log2, xml_encode,", "a purchase... self.vendor = None#seller # Shop title (e.g. \"Bob's", "= options[\"vendor\"] if ( \"title\" in options ): self.title =", "\"@item-title\": xml_encode( item.get_title() ), \"@item-cost\": xml_encode( \"%d\" % item.get_cost() )", "for item_name in self.vendor.get_vendor_inventory_item_names(): # Grab handle item = universe.get_item_by_name(item_name)", "confirm dialog) elif ( action == \"back\" ): results.append( self.handle_back_event(event,", "self.vendor.remove_erstwhile_acquired_items_from_inventory(universe) # Populate inventory for this shoppe's vendor... self.vendor.populate_vendor_inventory( min_quality", "universe = universe, execute_all = True ) # Refresh UI", "their inventory after a purchase... self.vendor = None#seller # Shop", ").add_parameters({ \"@item-name\": xml_encode( item.name ), \"@item-title\": xml_encode( item.title ), \"@item-cost\":", "\"%d\" % item.cost ), \"@item-advertisement\": xml_encode( item.description ) }) #", "self.vendor.get_name(), control_center, universe, execute_all = True # Try to loop", "handle_resume_game_event(self, event, control_center, universe): # Events that result from handling", "bought) m.run_script( name = \"%s.onpurchase\" % item.get_name(), control_center = control_center,", "its name universe.acquire_item_by_name( item.get_name() ) # Post a newsfeeder notice", "( action == \"back\" ): results.append( self.handle_back_event(event, control_center, universe) )", "Validate if (item): # How much money do we currently", "\"affordable\" if (money >= item.cost) else \"unaffordable\" ) # Fetch", "( \"required-item-names\" in options ): self.required_item_names.extend( options[\"required-item-names\"] )#.split(\";\") ) if", "to an item you might have bought) m.run_script( name =", "Assume all shop menus come from already-lightboxed dialogues. self.lightbox_controller.set_interval( self.lightbox_controller.get_target()", "None # Does the vendor have anything in stock? Use", "to determine which template we load... if ( self.vendor.get_vendor_inventory_count() ==", "this event (on-birth events, etc.) results = EventQueue() # Convenience", "template = self.fetch_xml_template( \"shop.directory\", version = \"out-of-items\" ).add_parameters({ \"@x\": xml_encode(", "the shop menu widget; trash it. self.set_status(STATUS_INACTIVE) # Return events", "Dismiss lightbox effect self.lightbox_controller.set_target(0) # Dismiss the splash controller, calling", "2 ))) ), \"@y\": xml_encode( \"%d\" % PAUSE_MENU_Y ), \"@width\":", "Refresh UI self.refresh_pages(control_center, universe, curtailed_count = 1) # After rebuilding", "available item... for item_name in self.vendor.get_vendor_inventory_item_names(): # Grab handle item", "\"@x\": xml_encode( \"%d\" % (SCREEN_WIDTH - (int( (SCREEN_WIDTH - PAUSE_MENU_WIDTH)", "results = EventQueue() # Convenience params = event.get_params() # Get" ]
[ "logging.debug(\"Searching for installed '%s'...\" % filename) which = procutils.which(filename, os.X_OK)", "count else 3 try: proc = subprocess.Popen([script, '-n', str(count)], close_fds=True,", "extra-info descriptors, and networkstatus document. .. warning: This function can", "this directory as the current working directory for the bridge", "\"\"\" from __future__ import print_function import logging import sys import", "return None logging.debug(\"Found installed script at '%s'\" % executable) return", "keys for each mocked OR, which are embedded in the", "a script which creates fake bridge descriptors for testing purposes.", "whatever directory we are currently in. \"\"\" import subprocess import", "import os from twisted.python import procutils def find(filename): \"\"\"Find the", "sources are minimal, because it creates the keys for each", "well as daemonisation. ** Module Overview: ** \"\"\" from __future__", "be created in it. If None, use the whatever directory", "generateDescriptors(count=None, rundir=None): \"\"\"Run a script which creates fake bridge descriptors", "descriptors.\" % str(count)) del subprocess return statuscode def doDumpBridges(config): \"\"\"Dump", "run in. The directory MUST already exist, and the descriptor", "descriptors, used to calculate the OR fingerprints, and sign the", "\"\"\"Dump bridges by assignment to a file. This function handles", "break if not executable: return None logging.debug(\"Found installed script at", "will be created in it. If None, use the whatever", "file is part of BridgeDB, a Tor bridge distribution system.", "def find(filename): \"\"\"Find the executable ``filename``. :param string filename: The", "servers, as well as daemonisation. ** Module Overview: ** \"\"\"", "% str(count)) del subprocess return statuscode def doDumpBridges(config): \"\"\"Dump bridges", "which creates fake bridge descriptors for testing purposes. This will", "which: if os.stat(that).st_uid == os.geteuid(): executable = that break if", "current configuration. \"\"\" import bridgedb.Bucket as bucket bucketManager = bucket.BucketManager(config)", "0xA3ADB67A2CDB8B35 <<EMAIL>> # please also see AUTHORS file # :copyright:", "to a file. This function handles the commandline '--dump-bridges' option.", "which = procutils.which(filename, os.X_OK) if len(which) > 0: for that", "%d)\" % proc.returncode) statuscode = proc.returncode else: print(\"Sucessfully generated %s", "return statuscode def doDumpBridges(config): \"\"\"Dump bridges by assignment to a", "if proc.returncode: print(\"There was an error generating bridge descriptors.\", \"(Returncode:", "are currently in. \"\"\" import subprocess import os.path proc =", "Overview: ** \"\"\" from __future__ import print_function import logging import", "# :authors: <NAME> 0xA3ADB67A2CDB8B35 <<EMAIL>> # please also see AUTHORS", "assignment to a file. This function handles the commandline '--dump-bridges'", "the executable ``filename``. :param string filename: The executable to search", "at '%s'\" % executable) return executable def generateDescriptors(count=None, rundir=None): \"\"\"Run", "# (c) 2007-2015, all entities within the AUTHORS file #", "search for. Must be in the effective user ID's $PATH.", "# # :authors: <NAME> 0xA3ADB67A2CDB8B35 <<EMAIL>> # please also see", "subprocess.Popen([script, '-n', str(count)], close_fds=True, cwd=rundir) finally: if proc is not", ".. _Leekspin: https://gitweb.torproject.org/user/isis/leekspin.git :param integer count: Number of mocked bridges", "also see AUTHORS file # :copyright: (c) 2007-2015, The Tor", "creates fake bridge descriptors for testing purposes. This will run", "os.geteuid(): executable = that break if not executable: return None", "None: proc.wait() if proc.returncode: print(\"There was an error generating bridge", "Tor bridge distribution system. # # :authors: <NAME> 0xA3ADB67A2CDB8B35 <<EMAIL>>", "it creates the keys for each mocked OR, which are", "other things. .. _Leekspin: https://gitweb.torproject.org/user/isis/leekspin.git :param integer count: Number of", "logging.debug(\"Found installed script at '%s'\" % executable) return executable def", "executable = None logging.debug(\"Searching for installed '%s'...\" % filename) which", "creates the keys for each mocked OR, which are embedded", "for installed '%s'...\" % filename) which = procutils.which(filename, os.X_OK) if", "descriptor files will be created in it. If None, use", "This function handles the commandline '--dump-bridges' option. :type config: :class:`bridgedb.Main.Conf`", "rundir: If given, use this directory as the current working", "bridge descriptors.\", \"(Returncode: %d)\" % proc.returncode) statuscode = proc.returncode else:", ":param string filename: The executable to search for. Must be", "if count else 3 try: proc = subprocess.Popen([script, '-n', str(count)],", "very long time to run, especially in headless environments where", "os from twisted.python import procutils def find(filename): \"\"\"Find the executable", "executable to search for. Must be in the effective user", "else: print(\"Sucessfully generated %s descriptors.\" % str(count)) del subprocess return", "file. This function handles the commandline '--dump-bridges' option. :type config:", "AUTHORS file # :copyright: (c) 2007-2015, The Tor Project, Inc.", "be in the effective user ID's $PATH. :rtype: string :returns:", "``filename``. :param string filename: The executable to search for. Must", "rundir=None): \"\"\"Run a script which creates fake bridge descriptors for", "= rundir if os.path.isdir(rundir) else None count = count if", "not executable: return None logging.debug(\"Found installed script at '%s'\" %", "the commandline '--dump-bridges' option. :type config: :class:`bridgedb.Main.Conf` :param config: The", "if os.path.isdir(rundir) else None count = count if count else", "3 try: proc = subprocess.Popen([script, '-n', str(count)], close_fds=True, cwd=rundir) finally:", "server descriptors, bridge extra-info descriptors, and networkstatus document. .. warning:", "the OR fingerprints, and sign the descriptors, among other things.", "count if count else 3 try: proc = subprocess.Popen([script, '-n',", "The Tor Project, Inc. # (c) 2007-2015, all entities within", "return executable def generateDescriptors(count=None, rundir=None): \"\"\"Run a script which creates", "Module Overview: ** \"\"\" from __future__ import print_function import logging", "os.X_OK) if len(which) > 0: for that in which: if", "None, use the whatever directory we are currently in. \"\"\"", "\"(Returncode: %d)\" % proc.returncode) statuscode = proc.returncode else: print(\"Sucessfully generated", "import print_function import logging import sys import os from twisted.python", "None. \"\"\" executable = None logging.debug(\"Searching for installed '%s'...\" %", "we are currently in. \"\"\" import subprocess import os.path proc", "executable def generateDescriptors(count=None, rundir=None): \"\"\"Run a script which creates fake", "not None: proc.wait() if proc.returncode: print(\"There was an error generating", "-*- coding: utf-8 ; test-case-name: bridgedb.test.test_runner -*- # # This", "\"\"\" import bridgedb.Bucket as bucket bucketManager = bucket.BucketManager(config) bucketManager.assignBridgesToBuckets() bucketManager.dumpBridges()", "running components and servers, as well as daemonisation. ** Module", "server descriptors, used to calculate the OR fingerprints, and sign", "= None statuscode = 0 script = 'leekspin' rundir =", "Project, Inc. # (c) 2007-2015, all entities within the AUTHORS", "headless environments where entropy sources are minimal, because it creates", ":class:`bridgedb.Main.Conf` :param config: The current configuration. \"\"\" import bridgedb.Bucket as", "proc.returncode: print(\"There was an error generating bridge descriptors.\", \"(Returncode: %d)\"", "environments where entropy sources are minimal, because it creates the", ":type config: :class:`bridgedb.Main.Conf` :param config: The current configuration. \"\"\" import", "commandline '--dump-bridges' option. :type config: :class:`bridgedb.Main.Conf` :param config: The current", "of BridgeDB, a Tor bridge distribution system. # # :authors:", "sys import os from twisted.python import procutils def find(filename): \"\"\"Find", "None statuscode = 0 script = 'leekspin' rundir = rundir", "Tor Project, Inc. # (c) 2007-2015, all entities within the", "is part of BridgeDB, a Tor bridge distribution system. #", "it. If None, use the whatever directory we are currently", "print_function import logging import sys import os from twisted.python import", "(c) 2012-2015, Isis Lovecruft # :license: 3-clause BSD, see included", "descriptors, and networkstatus document. .. warning: This function can take", "script at '%s'\" % executable) return executable def generateDescriptors(count=None, rundir=None):", "None logging.debug(\"Searching for installed '%s'...\" % filename) which = procutils.which(filename,", "2007-2015, all entities within the AUTHORS file # (c) 2012-2015,", "** \"\"\" from __future__ import print_function import logging import sys", "# please also see AUTHORS file # :copyright: (c) 2007-2015,", "if os.stat(that).st_uid == os.geteuid(): executable = that break if not", "or None :param rundir: If given, use this directory as", "returns None. \"\"\" executable = None logging.debug(\"Searching for installed '%s'...\"", "generated %s descriptors.\" % str(count)) del subprocess return statuscode def", "-*- # # This file is part of BridgeDB, a", "os.stat(that).st_uid == os.geteuid(): executable = that break if not executable:", "descriptors.\", \"(Returncode: %d)\" % proc.returncode) statuscode = proc.returncode else: print(\"Sucessfully", "the bridge descriptor generator script to run in. The directory", "= that break if not executable: return None logging.debug(\"Found installed", "'-n', str(count)], close_fds=True, cwd=rundir) finally: if proc is not None:", "which are embedded in the server descriptors, used to calculate", "are embedded in the server descriptors, used to calculate the", "statuscode = proc.returncode else: print(\"Sucessfully generated %s descriptors.\" % str(count))", "; test-case-name: bridgedb.test.test_runner -*- # # This file is part", "<NAME> 0xA3ADB67A2CDB8B35 <<EMAIL>> # please also see AUTHORS file #", "rundir if os.path.isdir(rundir) else None count = count if count", "distribution system. # # :authors: <NAME> 0xA3ADB67A2CDB8B35 <<EMAIL>> # please", "executable: return None logging.debug(\"Found installed script at '%s'\" % executable)", "= subprocess.Popen([script, '-n', str(count)], close_fds=True, cwd=rundir) finally: if proc is", "error generating bridge descriptors.\", \"(Returncode: %d)\" % proc.returncode) statuscode =", "networkstatus document. .. warning: This function can take a very", "count: Number of mocked bridges to generate descriptor for. (default:", "an error generating bridge descriptors.\", \"(Returncode: %d)\" % proc.returncode) statuscode", "descriptor generator script to run in. The directory MUST already", "import sys import os from twisted.python import procutils def find(filename):", "'%s'\" % executable) return executable def generateDescriptors(count=None, rundir=None): \"\"\"Run a", "%s descriptors.\" % str(count)) del subprocess return statuscode def doDumpBridges(config):", ":copyright: (c) 2007-2015, The Tor Project, Inc. # (c) 2007-2015,", "file # :copyright: (c) 2007-2015, The Tor Project, Inc. #", "to search for. Must be in the effective user ID's", "doDumpBridges(config): \"\"\"Dump bridges by assignment to a file. This function", "minimal, because it creates the keys for each mocked OR,", "bridge extra-info descriptors, and networkstatus document. .. warning: This function", "generate descriptor for. (default: 3) :type rundir: string or None", "descriptors, among other things. .. _Leekspin: https://gitweb.torproject.org/user/isis/leekspin.git :param integer count:", "will run Leekspin_ to create bridge server descriptors, bridge extra-info", "script = 'leekspin' rundir = rundir if os.path.isdir(rundir) else None", "as daemonisation. ** Module Overview: ** \"\"\" from __future__ import", "cwd=rundir) finally: if proc is not None: proc.wait() if proc.returncode:", "in the effective user ID's $PATH. :rtype: string :returns: The", "descriptor for. (default: 3) :type rundir: string or None :param", "BSD, see included LICENSE for information \"\"\"Classes for running components", "files will be created in it. If None, use the", "within the AUTHORS file # (c) 2012-2015, Isis Lovecruft #", "and servers, as well as daemonisation. ** Module Overview: **", "subprocess return statuscode def doDumpBridges(config): \"\"\"Dump bridges by assignment to", "for running components and servers, as well as daemonisation. **", "== os.geteuid(): executable = that break if not executable: return", "for the bridge descriptor generator script to run in. The", "\"\"\"Find the executable ``filename``. :param string filename: The executable to", "% executable) return executable def generateDescriptors(count=None, rundir=None): \"\"\"Run a script", "The current configuration. \"\"\" import bridgedb.Bucket as bucket bucketManager =", "% proc.returncode) statuscode = proc.returncode else: print(\"Sucessfully generated %s descriptors.\"", "see AUTHORS file # :copyright: (c) 2007-2015, The Tor Project,", "and the descriptor files will be created in it. If", "\"\"\" executable = None logging.debug(\"Searching for installed '%s'...\" % filename)", "= 0 script = 'leekspin' rundir = rundir if os.path.isdir(rundir)", "where entropy sources are minimal, because it creates the keys", "# This file is part of BridgeDB, a Tor bridge", "Must be in the effective user ID's $PATH. :rtype: string", "https://gitweb.torproject.org/user/isis/leekspin.git :param integer count: Number of mocked bridges to generate", "os.path proc = None statuscode = 0 script = 'leekspin'", "If None, use the whatever directory we are currently in.", "% filename) which = procutils.which(filename, os.X_OK) if len(which) > 0:", "(default: 3) :type rundir: string or None :param rundir: If", "see included LICENSE for information \"\"\"Classes for running components and", "that break if not executable: return None logging.debug(\"Found installed script", "executable ``filename``. :param string filename: The executable to search for.", "mocked OR, which are embedded in the server descriptors, used", "the whatever directory we are currently in. \"\"\" import subprocess", "_Leekspin: https://gitweb.torproject.org/user/isis/leekspin.git :param integer count: Number of mocked bridges to", "in which: if os.stat(that).st_uid == os.geteuid(): executable = that break", "a file. This function handles the commandline '--dump-bridges' option. :type", "# :license: 3-clause BSD, see included LICENSE for information \"\"\"Classes", "a Tor bridge distribution system. # # :authors: <NAME> 0xA3ADB67A2CDB8B35", "'leekspin' rundir = rundir if os.path.isdir(rundir) else None count =", "in headless environments where entropy sources are minimal, because it", "mocked bridges to generate descriptor for. (default: 3) :type rundir:", "OR fingerprints, and sign the descriptors, among other things. ..", "configuration. \"\"\" import bridgedb.Bucket as bucket bucketManager = bucket.BucketManager(config) bucketManager.assignBridgesToBuckets()", "Leekspin_ to create bridge server descriptors, bridge extra-info descriptors, and", "option. :type config: :class:`bridgedb.Main.Conf` :param config: The current configuration. \"\"\"", "to run in. The directory MUST already exist, and the", "please also see AUTHORS file # :copyright: (c) 2007-2015, The", "working directory for the bridge descriptor generator script to run", ".. warning: This function can take a very long time", "# -*- coding: utf-8 ; test-case-name: bridgedb.test.test_runner -*- # #", "for that in which: if os.stat(that).st_uid == os.geteuid(): executable =", "Inc. # (c) 2007-2015, all entities within the AUTHORS file", "integer count: Number of mocked bridges to generate descriptor for.", "location of the executable, if found. Otherwise, returns None. \"\"\"", "proc is not None: proc.wait() if proc.returncode: print(\"There was an", "embedded in the server descriptors, used to calculate the OR", "directory we are currently in. \"\"\" import subprocess import os.path", "str(count)) del subprocess return statuscode def doDumpBridges(config): \"\"\"Dump bridges by", "long time to run, especially in headless environments where entropy", "None :param rundir: If given, use this directory as the", "from __future__ import print_function import logging import sys import os", "for information \"\"\"Classes for running components and servers, as well", "that in which: if os.stat(that).st_uid == os.geteuid(): executable = that", "fake bridge descriptors for testing purposes. This will run Leekspin_", "find(filename): \"\"\"Find the executable ``filename``. :param string filename: The executable", "included LICENSE for information \"\"\"Classes for running components and servers,", "filename) which = procutils.which(filename, os.X_OK) if len(which) > 0: for", "rundir = rundir if os.path.isdir(rundir) else None count = count", "subprocess import os.path proc = None statuscode = 0 script", "use this directory as the current working directory for the", "use the whatever directory we are currently in. \"\"\" import", "3-clause BSD, see included LICENSE for information \"\"\"Classes for running", "warning: This function can take a very long time to", "import os.path proc = None statuscode = 0 script =", "import procutils def find(filename): \"\"\"Find the executable ``filename``. :param string", "bridges to generate descriptor for. (default: 3) :type rundir: string", "bridge distribution system. # # :authors: <NAME> 0xA3ADB67A2CDB8B35 <<EMAIL>> #", "logging import sys import os from twisted.python import procutils def", "for. (default: 3) :type rundir: string or None :param rundir:", "utf-8 ; test-case-name: bridgedb.test.test_runner -*- # # This file is", "2012-2015, Isis Lovecruft # :license: 3-clause BSD, see included LICENSE", "if not executable: return None logging.debug(\"Found installed script at '%s'\"", "descriptors, bridge extra-info descriptors, and networkstatus document. .. warning: This", "count = count if count else 3 try: proc =", "The executable to search for. Must be in the effective", "2007-2015, The Tor Project, Inc. # (c) 2007-2015, all entities", "to run, especially in headless environments where entropy sources are", "executable = that break if not executable: return None logging.debug(\"Found", "and networkstatus document. .. warning: This function can take a", "coding: utf-8 ; test-case-name: bridgedb.test.test_runner -*- # # This file", "for. Must be in the effective user ID's $PATH. :rtype:", "in it. If None, use the whatever directory we are", "del subprocess return statuscode def doDumpBridges(config): \"\"\"Dump bridges by assignment", "string filename: The executable to search for. Must be in", "string or None :param rundir: If given, use this directory", "test-case-name: bridgedb.test.test_runner -*- # # This file is part of", "Isis Lovecruft # :license: 3-clause BSD, see included LICENSE for", "This will run Leekspin_ to create bridge server descriptors, bridge", "part of BridgeDB, a Tor bridge distribution system. # #", "The directory MUST already exist, and the descriptor files will", "testing purposes. This will run Leekspin_ to create bridge server", "in. \"\"\" import subprocess import os.path proc = None statuscode", "0: for that in which: if os.stat(that).st_uid == os.geteuid(): executable", "script to run in. The directory MUST already exist, and", "= None logging.debug(\"Searching for installed '%s'...\" % filename) which =", "script which creates fake bridge descriptors for testing purposes. This", "If given, use this directory as the current working directory", "executable, if found. Otherwise, returns None. \"\"\" executable = None", "\"\"\" import subprocess import os.path proc = None statuscode =", "(c) 2007-2015, all entities within the AUTHORS file # (c)", "descriptors for testing purposes. This will run Leekspin_ to create", "from twisted.python import procutils def find(filename): \"\"\"Find the executable ``filename``.", "because it creates the keys for each mocked OR, which", "the keys for each mocked OR, which are embedded in", "= 'leekspin' rundir = rundir if os.path.isdir(rundir) else None count", "bridgedb.test.test_runner -*- # # This file is part of BridgeDB,", "purposes. This will run Leekspin_ to create bridge server descriptors,", "the AUTHORS file # (c) 2012-2015, Isis Lovecruft # :license:", "fingerprints, and sign the descriptors, among other things. .. _Leekspin:", "for testing purposes. This will run Leekspin_ to create bridge", "\"\"\"Run a script which creates fake bridge descriptors for testing", "bridge descriptors for testing purposes. This will run Leekspin_ to", "function can take a very long time to run, especially", "bridge server descriptors, bridge extra-info descriptors, and networkstatus document. ..", "close_fds=True, cwd=rundir) finally: if proc is not None: proc.wait() if", "None logging.debug(\"Found installed script at '%s'\" % executable) return executable", "file # (c) 2012-2015, Isis Lovecruft # :license: 3-clause BSD,", "procutils.which(filename, os.X_OK) if len(which) > 0: for that in which:", "def generateDescriptors(count=None, rundir=None): \"\"\"Run a script which creates fake bridge", "LICENSE for information \"\"\"Classes for running components and servers, as", "statuscode def doDumpBridges(config): \"\"\"Dump bridges by assignment to a file.", "current working directory for the bridge descriptor generator script to", "filename: The executable to search for. Must be in the", "time to run, especially in headless environments where entropy sources", "if proc is not None: proc.wait() if proc.returncode: print(\"There was", "proc.returncode) statuscode = proc.returncode else: print(\"Sucessfully generated %s descriptors.\" %", "function handles the commandline '--dump-bridges' option. :type config: :class:`bridgedb.Main.Conf` :param", ":param rundir: If given, use this directory as the current", "MUST already exist, and the descriptor files will be created", "among other things. .. _Leekspin: https://gitweb.torproject.org/user/isis/leekspin.git :param integer count: Number", "to calculate the OR fingerprints, and sign the descriptors, among", "try: proc = subprocess.Popen([script, '-n', str(count)], close_fds=True, cwd=rundir) finally: if", "all entities within the AUTHORS file # (c) 2012-2015, Isis", "executable) return executable def generateDescriptors(count=None, rundir=None): \"\"\"Run a script which", "the server descriptors, used to calculate the OR fingerprints, and", "to create bridge server descriptors, bridge extra-info descriptors, and networkstatus", "statuscode = 0 script = 'leekspin' rundir = rundir if", "proc = subprocess.Popen([script, '-n', str(count)], close_fds=True, cwd=rundir) finally: if proc", "of mocked bridges to generate descriptor for. (default: 3) :type", "handles the commandline '--dump-bridges' option. :type config: :class:`bridgedb.Main.Conf` :param config:", "user ID's $PATH. :rtype: string :returns: The location of the", "found. Otherwise, returns None. \"\"\" executable = None logging.debug(\"Searching for", "if found. Otherwise, returns None. \"\"\" executable = None logging.debug(\"Searching", "the current working directory for the bridge descriptor generator script", "exist, and the descriptor files will be created in it.", "generating bridge descriptors.\", \"(Returncode: %d)\" % proc.returncode) statuscode = proc.returncode", "config: :class:`bridgedb.Main.Conf` :param config: The current configuration. \"\"\" import bridgedb.Bucket", "can take a very long time to run, especially in", "The location of the executable, if found. Otherwise, returns None.", "string :returns: The location of the executable, if found. Otherwise,", "the descriptor files will be created in it. If None,", "None count = count if count else 3 try: proc", "print(\"There was an error generating bridge descriptors.\", \"(Returncode: %d)\" %", "document. .. warning: This function can take a very long", "This function can take a very long time to run,", "create bridge server descriptors, bridge extra-info descriptors, and networkstatus document.", "proc = None statuscode = 0 script = 'leekspin' rundir", "print(\"Sucessfully generated %s descriptors.\" % str(count)) del subprocess return statuscode", ":license: 3-clause BSD, see included LICENSE for information \"\"\"Classes for", "__future__ import print_function import logging import sys import os from", "daemonisation. ** Module Overview: ** \"\"\" from __future__ import print_function", "Lovecruft # :license: 3-clause BSD, see included LICENSE for information", "information \"\"\"Classes for running components and servers, as well as", "the executable, if found. Otherwise, returns None. \"\"\" executable =", "entropy sources are minimal, because it creates the keys for", "os.path.isdir(rundir) else None count = count if count else 3", "proc.returncode else: print(\"Sucessfully generated %s descriptors.\" % str(count)) del subprocess", "created in it. If None, use the whatever directory we", "(c) 2007-2015, The Tor Project, Inc. # (c) 2007-2015, all", ":param integer count: Number of mocked bridges to generate descriptor", "entities within the AUTHORS file # (c) 2012-2015, Isis Lovecruft", "the descriptors, among other things. .. _Leekspin: https://gitweb.torproject.org/user/isis/leekspin.git :param integer", "= procutils.which(filename, os.X_OK) if len(which) > 0: for that in", "twisted.python import procutils def find(filename): \"\"\"Find the executable ``filename``. :param", "as the current working directory for the bridge descriptor generator", "to generate descriptor for. (default: 3) :type rundir: string or", "was an error generating bridge descriptors.\", \"(Returncode: %d)\" % proc.returncode)", "$PATH. :rtype: string :returns: The location of the executable, if", "config: The current configuration. \"\"\" import bridgedb.Bucket as bucket bucketManager", "\"\"\"Classes for running components and servers, as well as daemonisation.", "system. # # :authors: <NAME> 0xA3ADB67A2CDB8B35 <<EMAIL>> # please also", "components and servers, as well as daemonisation. ** Module Overview:", "<<EMAIL>> # please also see AUTHORS file # :copyright: (c)", "# # This file is part of BridgeDB, a Tor", "generator script to run in. The directory MUST already exist,", "** Module Overview: ** \"\"\" from __future__ import print_function import", "0 script = 'leekspin' rundir = rundir if os.path.isdir(rundir) else", "currently in. \"\"\" import subprocess import os.path proc = None", "bridge descriptor generator script to run in. The directory MUST", "by assignment to a file. This function handles the commandline", ":rtype: string :returns: The location of the executable, if found.", "especially in headless environments where entropy sources are minimal, because", "sign the descriptors, among other things. .. _Leekspin: https://gitweb.torproject.org/user/isis/leekspin.git :param", "run, especially in headless environments where entropy sources are minimal,", "# :copyright: (c) 2007-2015, The Tor Project, Inc. # (c)", "installed '%s'...\" % filename) which = procutils.which(filename, os.X_OK) if len(which)", "BridgeDB, a Tor bridge distribution system. # # :authors: <NAME>", ":authors: <NAME> 0xA3ADB67A2CDB8B35 <<EMAIL>> # please also see AUTHORS file", ":returns: The location of the executable, if found. Otherwise, returns", "finally: if proc is not None: proc.wait() if proc.returncode: print(\"There", "This file is part of BridgeDB, a Tor bridge distribution", "each mocked OR, which are embedded in the server descriptors,", "3) :type rundir: string or None :param rundir: If given,", "installed script at '%s'\" % executable) return executable def generateDescriptors(count=None,", "effective user ID's $PATH. :rtype: string :returns: The location of", "a very long time to run, especially in headless environments", "def doDumpBridges(config): \"\"\"Dump bridges by assignment to a file. This", "else None count = count if count else 3 try:", "> 0: for that in which: if os.stat(that).st_uid == os.geteuid():", "calculate the OR fingerprints, and sign the descriptors, among other", "are minimal, because it creates the keys for each mocked", "directory for the bridge descriptor generator script to run in.", "Otherwise, returns None. \"\"\" executable = None logging.debug(\"Searching for installed", "= count if count else 3 try: proc = subprocess.Popen([script,", "run Leekspin_ to create bridge server descriptors, bridge extra-info descriptors,", "for each mocked OR, which are embedded in the server", "things. .. _Leekspin: https://gitweb.torproject.org/user/isis/leekspin.git :param integer count: Number of mocked", "given, use this directory as the current working directory for", "bridges by assignment to a file. This function handles the", "take a very long time to run, especially in headless", "len(which) > 0: for that in which: if os.stat(that).st_uid ==", "OR, which are embedded in the server descriptors, used to", ":type rundir: string or None :param rundir: If given, use", "in. The directory MUST already exist, and the descriptor files", "else 3 try: proc = subprocess.Popen([script, '-n', str(count)], close_fds=True, cwd=rundir)", "the effective user ID's $PATH. :rtype: string :returns: The location", "directory MUST already exist, and the descriptor files will be", "import logging import sys import os from twisted.python import procutils", "is not None: proc.wait() if proc.returncode: print(\"There was an error", "used to calculate the OR fingerprints, and sign the descriptors,", "ID's $PATH. :rtype: string :returns: The location of the executable,", "already exist, and the descriptor files will be created in", "directory as the current working directory for the bridge descriptor", "= proc.returncode else: print(\"Sucessfully generated %s descriptors.\" % str(count)) del", "# (c) 2012-2015, Isis Lovecruft # :license: 3-clause BSD, see", "import subprocess import os.path proc = None statuscode = 0", "proc.wait() if proc.returncode: print(\"There was an error generating bridge descriptors.\",", "AUTHORS file # (c) 2012-2015, Isis Lovecruft # :license: 3-clause", "procutils def find(filename): \"\"\"Find the executable ``filename``. :param string filename:", "and sign the descriptors, among other things. .. _Leekspin: https://gitweb.torproject.org/user/isis/leekspin.git", "as well as daemonisation. ** Module Overview: ** \"\"\" from", "rundir: string or None :param rundir: If given, use this", "of the executable, if found. Otherwise, returns None. \"\"\" executable", "'%s'...\" % filename) which = procutils.which(filename, os.X_OK) if len(which) >", "in the server descriptors, used to calculate the OR fingerprints,", "str(count)], close_fds=True, cwd=rundir) finally: if proc is not None: proc.wait()", ":param config: The current configuration. \"\"\" import bridgedb.Bucket as bucket", "Number of mocked bridges to generate descriptor for. (default: 3)", "if len(which) > 0: for that in which: if os.stat(that).st_uid", "'--dump-bridges' option. :type config: :class:`bridgedb.Main.Conf` :param config: The current configuration." ]
[ "part destdir') sys.exit(0) # NOTREACHED pass devname = sys.argv[1] if", "devname = sys.argv[1] if not is_block_device(devname): print( '%s is not", "self.tasks.append(task_fsck(\"fsck partition\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_shrink_partition(\"Shrink partition to smallest\", disk=self.disk, partition_id=self.partition_id))", "destdir, suggestedname=None, partition_id='Linux'): super().__init__(ui, runner_id) self.time_estimate = 600 self.disk =", ".runner import Runner from ..lib.disk_images import make_disk_image_name from .json_ui import", "not is_block_device(devname): print( '%s is not a block device.' %", "__name__ == \"__main__\": tlog = init_triage_logger() if len(sys.argv) == 1:", "make_disk_image_name(destdir, suggestedname) pass def prepare(self): super().prepare() # self.tasks.append(task_mount_nfs_destination(self, \"Mount the", "for me to see the tasks. http server runs this", "on the disk. # One step at a time. def", "do_it = True if destdir == \"preflight\": ui = console_ui()", "from .runner import Runner from ..lib.disk_images import make_disk_image_name from .json_ui", "= sys.argv[3] # Destination directory disk = create_storage_instance(devname) # Preflight", "partition_id=self.partition_id) task.set_teardown_task() self.tasks.append(task) pass pass if __name__ == \"__main__\": tlog", "pass devname = sys.argv[1] if not is_block_device(devname): print( '%s is", "only dealing with the EXT4 linux partition. ''' # FIXME:", "\"Preflight\": \"Saving disk is preparing.\", \"Running\": \"{step} of {steps}: Running", "\"Saving disk failed.\" } # class ImageDiskRunner(Runner): '''Runner for creating", "\"Running\": \"{step} of {steps}: Running {task}\", \"Success\": \"Saving disk completed", "= task_expand_partition(\"Expand the partion back\", disk=self.disk, partition_id=self.partition_id) task.set_teardown_task() self.tasks.append(task) pass", "traceback from .tasks import task_fetch_partitions, task_refresh_partitions, task_mount, task_remove_persistent_rules, task_remove_logs, task_fsck,", "fsck, shrink partition, create disk image and resize the file", "destination volume\")) self.tasks.append(task_fetch_partitions(\"Fetch partitions\", self.disk)) self.tasks.append(task_refresh_partitions(\"Refresh partition information\", self.disk)) self.tasks.append(task_mount(\"Mount", "elif destdir == \"testflight\": ui = console_ui() do_it = True", "create_storage_instance from .runner import Runner from ..lib.disk_images import make_disk_image_name from", "Running {task}\", \"Success\": \"Saving disk completed successfully.\", \"Failed\": \"Saving disk", "to the max. For now, this is only dealing with", "I want to make this to a generic clone app,", "# # Create disk image # import re, sys, traceback", "self.tasks.append(task_remove_logs(\"Remove/Clean Logs\", disk=self.disk, partition_id=self.partition_id)) task = task_unmount(\"Unmount target\", disk=self.disk, partition_id=self.partition_id)", "task_expand_partition(\"Expand the partion back\", disk=self.disk, partition_id=self.partition_id) task.set_teardown_task() self.tasks.append(task) pass pass", "task_remove_logs, task_fsck, task_shrink_partition, task_expand_partition, task_unmount from .partclone_tasks import task_create_disk_image from", "of partitions on the disk. # One step at a", "self.imagename = make_disk_image_name(destdir, suggestedname) pass def prepare(self): super().prepare() # self.tasks.append(task_mount_nfs_destination(self,", "step at a time. def __init__(self, ui, runner_id, disk, destdir,", "''' # FIXME: If I want to make this to", "if __name__ == \"__main__\": tlog = init_triage_logger() if len(sys.argv) ==", "task = task_unmount(\"Unmount target\", disk=self.disk, partition_id=self.partition_id) task.set_teardown_task() self.tasks.append(task) self.tasks.append(task_fsck(\"fsck partition\",", "pass def prepare(self): super().prepare() # self.tasks.append(task_mount_nfs_destination(self, \"Mount the destination volume\"))", "to deal with all of partitions on the disk. #", ".ops_ui import console_ui from ..components.disk import create_storage_instance from .runner import", "== \"preflight\": ui = console_ui() do_it = False pass elif", "pass runner_id = disk.device_name runner = ImageDiskRunner(ui, runner_id, disk, destdir,", "super().__init__(ui, runner_id) self.time_estimate = 600 self.disk = disk self.partition_id =", ".json_ui import json_ui from ..lib.util import init_triage_logger, is_block_device # \"Waiting\",", "with all of partitions on the disk. # One step", "task_fsck, task_shrink_partition, task_expand_partition, task_unmount from .partclone_tasks import task_create_disk_image from .ops_ui", "partition. ''' # FIXME: If I want to make this", "partition_id=self.partition_id)) self.tasks.append(task_create_disk_image(\"Create disk image\", disk=self.disk, partition_id=self.partition_id, imagename=self.imagename)) task = task_expand_partition(\"Expand", "sys, traceback from .tasks import task_fetch_partitions, task_refresh_partitions, task_mount, task_remove_persistent_rules, task_remove_logs,", "disk is waiting.\", \"Prepare\": \"Savign disk is preparing.\", \"Preflight\": \"Saving", "from .partclone_tasks import task_create_disk_image from .ops_ui import console_ui from ..components.disk", "is only dealing with the EXT4 linux partition. ''' #", "# Preflight is for me to see the tasks. http", "FIXME: If I want to make this to a generic", "import make_disk_image_name from .json_ui import json_ui from ..lib.util import init_triage_logger,", "tasks. http server runs this with json_ui. do_it = True", "rules\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_remove_logs(\"Remove/Clean Logs\", disk=self.disk, partition_id=self.partition_id)) task = task_unmount(\"Unmount", "task_expand_partition, task_unmount from .partclone_tasks import task_create_disk_image from .ops_ui import console_ui", "json_ui(wock_event=\"saveimage\", message_catalog=my_messages) pass if re.match(part, '\\d+'): part = int(part) pass", "is not a block device.' % devname) sys.exit(1) # NOTREACHED", "pass if __name__ == \"__main__\": tlog = init_triage_logger() if len(sys.argv)", "from ..lib.util import init_triage_logger, is_block_device # \"Waiting\", \"Prepare\", \"Preflight\", \"Running\",", "NOTREACHED pass part = sys.argv[2] # This is a partition", "time. def __init__(self, ui, runner_id, disk, destdir, suggestedname=None, partition_id='Linux'): super().__init__(ui,", "disk completed successfully.\", \"Failed\": \"Saving disk failed.\" } # class", "create_storage_instance(devname) # Preflight is for me to see the tasks.", "Create disk image # import re, sys, traceback from .tasks", "of {steps}: Running {task}\", \"Success\": \"Saving disk completed successfully.\", \"Failed\":", "partition to smallest\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_create_disk_image(\"Create disk image\", disk=self.disk, partition_id=self.partition_id,", "self.partition_id = partition_id self.destdir = destdir self.imagename = make_disk_image_name(destdir, suggestedname)", "runner_id, disk, destdir, partition_id=part) try: runner.prepare() runner.preflight() runner.explain() runner.run() sys.exit(0)", "If I want to make this to a generic clone", "partition\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_shrink_partition(\"Shrink partition to smallest\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_create_disk_image(\"Create", "NOTREACHED pass devname = sys.argv[1] if not is_block_device(devname): print( '%s", "the tasks. http server runs this with json_ui. do_it =", "is waiting.\", \"Prepare\": \"Savign disk is preparing.\", \"Preflight\": \"Saving disk", "print( 'Unloader: devicename part destdir') sys.exit(0) # NOTREACHED pass devname", "shrink partition, create disk image and resize the file system", "image\", disk=self.disk, partition_id=self.partition_id, imagename=self.imagename)) task = task_expand_partition(\"Expand the partion back\",", "runner.preflight() runner.explain() runner.run() sys.exit(0) # NOTREACHED except Exception as exc:", "partion back\", disk=self.disk, partition_id=self.partition_id) task.set_teardown_task() self.tasks.append(task) pass pass if __name__", "partitions\", self.disk)) self.tasks.append(task_refresh_partitions(\"Refresh partition information\", self.disk)) self.tasks.append(task_mount(\"Mount the target disk\",", "tlog = init_triage_logger() if len(sys.argv) == 1: print( 'Unloader: devicename", "self.tasks.append(task_mount_nfs_destination(self, \"Mount the destination volume\")) self.tasks.append(task_fetch_partitions(\"Fetch partitions\", self.disk)) self.tasks.append(task_refresh_partitions(\"Refresh partition", "= disk.device_name runner = ImageDiskRunner(ui, runner_id, disk, destdir, partition_id=part) try:", "'Unloader: devicename part destdir') sys.exit(0) # NOTREACHED pass devname =", "image and resize the file system back to the max.", "self.time_estimate = 600 self.disk = disk self.partition_id = partition_id self.destdir", "runner.explain() runner.run() sys.exit(0) # NOTREACHED except Exception as exc: sys.stderr.write(traceback.format_exc(exc)", "runner.run() sys.exit(0) # NOTREACHED except Exception as exc: sys.stderr.write(traceback.format_exc(exc) +", "disk, destdir, partition_id=part) try: runner.prepare() runner.preflight() runner.explain() runner.run() sys.exit(0) #", "except Exception as exc: sys.stderr.write(traceback.format_exc(exc) + \"\\n\") sys.exit(1) # NOTREACHED", "self.tasks.append(task_shrink_partition(\"Shrink partition to smallest\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_create_disk_image(\"Create disk image\", disk=self.disk,", "at a time. def __init__(self, ui, runner_id, disk, destdir, suggestedname=None,", "persistent rules\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_remove_logs(\"Remove/Clean Logs\", disk=self.disk, partition_id=self.partition_id)) task =", "= sys.argv[2] # This is a partition id destdir =", "task_mount, task_remove_persistent_rules, task_remove_logs, task_fsck, task_shrink_partition, task_expand_partition, task_unmount from .partclone_tasks import", "import Runner from ..lib.disk_images import make_disk_image_name from .json_ui import json_ui", "task_fetch_partitions, task_refresh_partitions, task_mount, task_remove_persistent_rules, task_remove_logs, task_fsck, task_shrink_partition, task_expand_partition, task_unmount from", "import json_ui from ..lib.util import init_triage_logger, is_block_device # \"Waiting\", \"Prepare\",", "sys.argv[2] # This is a partition id destdir = sys.argv[3]", "int(part) pass runner_id = disk.device_name runner = ImageDiskRunner(ui, runner_id, disk,", "600 self.disk = disk self.partition_id = partition_id self.destdir = destdir", "want to make this to a generic clone app, I", "disk=self.disk, partition_id=self.partition_id) task.set_teardown_task() self.tasks.append(task) self.tasks.append(task_fsck(\"fsck partition\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_shrink_partition(\"Shrink partition", "Logs\", disk=self.disk, partition_id=self.partition_id)) task = task_unmount(\"Unmount target\", disk=self.disk, partition_id=self.partition_id) task.set_teardown_task()", "destdir = sys.argv[3] # Destination directory disk = create_storage_instance(devname) #", "== \"__main__\": tlog = init_triage_logger() if len(sys.argv) == 1: print(", "is_block_device(devname): print( '%s is not a block device.' % devname)", "console_ui() do_it = True pass else: ui = json_ui(wock_event=\"saveimage\", message_catalog=my_messages)", "__init__(self, ui, runner_id, disk, destdir, suggestedname=None, partition_id='Linux'): super().__init__(ui, runner_id) self.time_estimate", "Destination directory disk = create_storage_instance(devname) # Preflight is for me", "need to deal with all of partitions on the disk.", "destdir self.imagename = make_disk_image_name(destdir, suggestedname) pass def prepare(self): super().prepare() #", "task_refresh_partitions, task_mount, task_remove_persistent_rules, task_remove_logs, task_fsck, task_shrink_partition, task_expand_partition, task_unmount from .partclone_tasks", "partition_id=part) try: runner.prepare() runner.preflight() runner.explain() runner.run() sys.exit(0) # NOTREACHED except", "import task_create_disk_image from .ops_ui import console_ui from ..components.disk import create_storage_instance", "partition_id=self.partition_id)) self.tasks.append(task_remove_logs(\"Remove/Clean Logs\", disk=self.disk, partition_id=self.partition_id)) task = task_unmount(\"Unmount target\", disk=self.disk,", "is a partition id destdir = sys.argv[3] # Destination directory", "to see the tasks. http server runs this with json_ui.", "the max. For now, this is only dealing with the", "pass elif destdir == \"testflight\": ui = console_ui() do_it =", "self.destdir = destdir self.imagename = make_disk_image_name(destdir, suggestedname) pass def prepare(self):", "completed successfully.\", \"Failed\": \"Saving disk failed.\" } # class ImageDiskRunner(Runner):", "\"Failed\": \"Saving disk failed.\" } # class ImageDiskRunner(Runner): '''Runner for", "task.set_teardown_task() self.tasks.append(task) self.tasks.append(task_fsck(\"fsck partition\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_shrink_partition(\"Shrink partition to smallest\",", "import re, sys, traceback from .tasks import task_fetch_partitions, task_refresh_partitions, task_mount,", "resize the file system back to the max. For now,", "partition_id=self.partition_id)) self.tasks.append(task_remove_persistent_rules(\"Remove persistent rules\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_remove_logs(\"Remove/Clean Logs\", disk=self.disk, partition_id=self.partition_id))", "if destdir == \"preflight\": ui = console_ui() do_it = False", "self.tasks.append(task_remove_persistent_rules(\"Remove persistent rules\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_remove_logs(\"Remove/Clean Logs\", disk=self.disk, partition_id=self.partition_id)) task", "False pass elif destdir == \"testflight\": ui = console_ui() do_it", "back\", disk=self.disk, partition_id=self.partition_id) task.set_teardown_task() self.tasks.append(task) pass pass if __name__ ==", "# NOTREACHED except Exception as exc: sys.stderr.write(traceback.format_exc(exc) + \"\\n\") sys.exit(1)", "self.tasks.append(task_create_disk_image(\"Create disk image\", disk=self.disk, partition_id=self.partition_id, imagename=self.imagename)) task = task_expand_partition(\"Expand the", "\"Running\", \"Success\", \"Failed\"] my_messages = { \"Waiting\": \"Saving disk is", "is for me to see the tasks. http server runs", "<filename>wce_triage/ops/create_image_runner.py #!/usr/bin/env python3 # # Create disk image # import", "the disk. # One step at a time. def __init__(self,", "sys.exit(0) # NOTREACHED pass devname = sys.argv[1] if not is_block_device(devname):", "disk image # import re, sys, traceback from .tasks import", "disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_remove_persistent_rules(\"Remove persistent rules\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_remove_logs(\"Remove/Clean Logs\", disk=self.disk,", "block device.' % devname) sys.exit(1) # NOTREACHED pass part =", "partition_id self.destdir = destdir self.imagename = make_disk_image_name(destdir, suggestedname) pass def", "this with json_ui. do_it = True if destdir == \"preflight\":", "is_block_device # \"Waiting\", \"Prepare\", \"Preflight\", \"Running\", \"Success\", \"Failed\"] my_messages =", "= { \"Waiting\": \"Saving disk is waiting.\", \"Prepare\": \"Savign disk", "disk image\", disk=self.disk, partition_id=self.partition_id, imagename=self.imagename)) task = task_expand_partition(\"Expand the partion", "\"Saving disk is waiting.\", \"Prepare\": \"Savign disk is preparing.\", \"Preflight\":", "from ..lib.disk_images import make_disk_image_name from .json_ui import json_ui from ..lib.util", "disk failed.\" } # class ImageDiskRunner(Runner): '''Runner for creating disk", "for creating disk image. does fsck, shrink partition, create disk", "id destdir = sys.argv[3] # Destination directory disk = create_storage_instance(devname)", "app, I need to deal with all of partitions on", "destdir == \"testflight\": ui = console_ui() do_it = True pass", "self.tasks.append(task) pass pass if __name__ == \"__main__\": tlog = init_triage_logger()", "runner_id, disk, destdir, suggestedname=None, partition_id='Linux'): super().__init__(ui, runner_id) self.time_estimate = 600", "information\", self.disk)) self.tasks.append(task_mount(\"Mount the target disk\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_remove_persistent_rules(\"Remove persistent", "as exc: sys.stderr.write(traceback.format_exc(exc) + \"\\n\") sys.exit(1) # NOTREACHED pass pass", "device.' % devname) sys.exit(1) # NOTREACHED pass part = sys.argv[2]", "try: runner.prepare() runner.preflight() runner.explain() runner.run() sys.exit(0) # NOTREACHED except Exception", "disk=self.disk, partition_id=self.partition_id, imagename=self.imagename)) task = task_expand_partition(\"Expand the partion back\", disk=self.disk,", "from ..components.disk import create_storage_instance from .runner import Runner from ..lib.disk_images", "prepare(self): super().prepare() # self.tasks.append(task_mount_nfs_destination(self, \"Mount the destination volume\")) self.tasks.append(task_fetch_partitions(\"Fetch partitions\",", "re, sys, traceback from .tasks import task_fetch_partitions, task_refresh_partitions, task_mount, task_remove_persistent_rules,", "a block device.' % devname) sys.exit(1) # NOTREACHED pass part", "image. does fsck, shrink partition, create disk image and resize", "devicename part destdir') sys.exit(0) # NOTREACHED pass devname = sys.argv[1]", "make this to a generic clone app, I need to", "= destdir self.imagename = make_disk_image_name(destdir, suggestedname) pass def prepare(self): super().prepare()", "and resize the file system back to the max. For", "\"preflight\": ui = console_ui() do_it = False pass elif destdir", "\"Failed\"] my_messages = { \"Waiting\": \"Saving disk is waiting.\", \"Prepare\":", "ui = json_ui(wock_event=\"saveimage\", message_catalog=my_messages) pass if re.match(part, '\\d+'): part =", "sys.argv[1] if not is_block_device(devname): print( '%s is not a block", "disk image and resize the file system back to the", "# One step at a time. def __init__(self, ui, runner_id,", "generic clone app, I need to deal with all of", "partition id destdir = sys.argv[3] # Destination directory disk =", "# Destination directory disk = create_storage_instance(devname) # Preflight is for", "ui = console_ui() do_it = True pass else: ui =", "= True if destdir == \"preflight\": ui = console_ui() do_it", "Preflight is for me to see the tasks. http server", "..components.disk import create_storage_instance from .runner import Runner from ..lib.disk_images import", "# \"Waiting\", \"Prepare\", \"Preflight\", \"Running\", \"Success\", \"Failed\"] my_messages = {", "linux partition. ''' # FIXME: If I want to make", "this to a generic clone app, I need to deal", "% devname) sys.exit(1) # NOTREACHED pass part = sys.argv[2] #", "self.disk)) self.tasks.append(task_refresh_partitions(\"Refresh partition information\", self.disk)) self.tasks.append(task_mount(\"Mount the target disk\", disk=self.disk,", "devname) sys.exit(1) # NOTREACHED pass part = sys.argv[2] # This", "pass if re.match(part, '\\d+'): part = int(part) pass runner_id =", "partition_id=self.partition_id) task.set_teardown_task() self.tasks.append(task) self.tasks.append(task_fsck(\"fsck partition\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_shrink_partition(\"Shrink partition to", "make_disk_image_name from .json_ui import json_ui from ..lib.util import init_triage_logger, is_block_device", "json_ui. do_it = True if destdir == \"preflight\": ui =", "disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_create_disk_image(\"Create disk image\", disk=self.disk, partition_id=self.partition_id, imagename=self.imagename)) task =", "ImageDiskRunner(Runner): '''Runner for creating disk image. does fsck, shrink partition,", "disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_remove_logs(\"Remove/Clean Logs\", disk=self.disk, partition_id=self.partition_id)) task = task_unmount(\"Unmount target\",", "part = int(part) pass runner_id = disk.device_name runner = ImageDiskRunner(ui,", "to smallest\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_create_disk_image(\"Create disk image\", disk=self.disk, partition_id=self.partition_id, imagename=self.imagename))", "back to the max. For now, this is only dealing", "this is only dealing with the EXT4 linux partition. '''", "all of partitions on the disk. # One step at", "'%s is not a block device.' % devname) sys.exit(1) #", "disk = create_storage_instance(devname) # Preflight is for me to see", "part = sys.argv[2] # This is a partition id destdir", "import init_triage_logger, is_block_device # \"Waiting\", \"Prepare\", \"Preflight\", \"Running\", \"Success\", \"Failed\"]", "target\", disk=self.disk, partition_id=self.partition_id) task.set_teardown_task() self.tasks.append(task) self.tasks.append(task_fsck(\"fsck partition\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_shrink_partition(\"Shrink", "task_unmount from .partclone_tasks import task_create_disk_image from .ops_ui import console_ui from", "runner.prepare() runner.preflight() runner.explain() runner.run() sys.exit(0) # NOTREACHED except Exception as", "not a block device.' % devname) sys.exit(1) # NOTREACHED pass", "= console_ui() do_it = False pass elif destdir == \"testflight\":", "{task}\", \"Success\": \"Saving disk completed successfully.\", \"Failed\": \"Saving disk failed.\"", "destdir') sys.exit(0) # NOTREACHED pass devname = sys.argv[1] if not", "NOTREACHED except Exception as exc: sys.stderr.write(traceback.format_exc(exc) + \"\\n\") sys.exit(1) #", "is preparing.\", \"Preflight\": \"Saving disk is preparing.\", \"Running\": \"{step} of", "pass pass if __name__ == \"__main__\": tlog = init_triage_logger() if", "\"testflight\": ui = console_ui() do_it = True pass else: ui", "else: ui = json_ui(wock_event=\"saveimage\", message_catalog=my_messages) pass if re.match(part, '\\d+'): part", "== 1: print( 'Unloader: devicename part destdir') sys.exit(0) # NOTREACHED", "self.tasks.append(task_refresh_partitions(\"Refresh partition information\", self.disk)) self.tasks.append(task_mount(\"Mount the target disk\", disk=self.disk, partition_id=self.partition_id))", "ImageDiskRunner(ui, runner_id, disk, destdir, partition_id=part) try: runner.prepare() runner.preflight() runner.explain() runner.run()", "if re.match(part, '\\d+'): part = int(part) pass runner_id = disk.device_name", "# NOTREACHED pass part = sys.argv[2] # This is a", "partition_id=self.partition_id)) self.tasks.append(task_shrink_partition(\"Shrink partition to smallest\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_create_disk_image(\"Create disk image\",", "ui, runner_id, disk, destdir, suggestedname=None, partition_id='Linux'): super().__init__(ui, runner_id) self.time_estimate =", "task_unmount(\"Unmount target\", disk=self.disk, partition_id=self.partition_id) task.set_teardown_task() self.tasks.append(task) self.tasks.append(task_fsck(\"fsck partition\", disk=self.disk, partition_id=self.partition_id))", "a generic clone app, I need to deal with all", "self.disk)) self.tasks.append(task_mount(\"Mount the target disk\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_remove_persistent_rules(\"Remove persistent rules\",", "class ImageDiskRunner(Runner): '''Runner for creating disk image. does fsck, shrink", "partition, create disk image and resize the file system back", "\"Waiting\", \"Prepare\", \"Preflight\", \"Running\", \"Success\", \"Failed\"] my_messages = { \"Waiting\":", "# NOTREACHED pass devname = sys.argv[1] if not is_block_device(devname): print(", "import console_ui from ..components.disk import create_storage_instance from .runner import Runner", "} # class ImageDiskRunner(Runner): '''Runner for creating disk image. does", "target disk\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_remove_persistent_rules(\"Remove persistent rules\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_remove_logs(\"Remove/Clean", "EXT4 linux partition. ''' # FIXME: If I want to", "{ \"Waiting\": \"Saving disk is waiting.\", \"Prepare\": \"Savign disk is", "see the tasks. http server runs this with json_ui. do_it", "console_ui() do_it = False pass elif destdir == \"testflight\": ui", "# class ImageDiskRunner(Runner): '''Runner for creating disk image. does fsck,", "# self.tasks.append(task_mount_nfs_destination(self, \"Mount the destination volume\")) self.tasks.append(task_fetch_partitions(\"Fetch partitions\", self.disk)) self.tasks.append(task_refresh_partitions(\"Refresh", "\"Saving disk completed successfully.\", \"Failed\": \"Saving disk failed.\" } #", "the partion back\", disk=self.disk, partition_id=self.partition_id) task.set_teardown_task() self.tasks.append(task) pass pass if", "len(sys.argv) == 1: print( 'Unloader: devicename part destdir') sys.exit(0) #", "disk is preparing.\", \"Running\": \"{step} of {steps}: Running {task}\", \"Success\":", "imagename=self.imagename)) task = task_expand_partition(\"Expand the partion back\", disk=self.disk, partition_id=self.partition_id) task.set_teardown_task()", "init_triage_logger, is_block_device # \"Waiting\", \"Prepare\", \"Preflight\", \"Running\", \"Success\", \"Failed\"] my_messages", "the destination volume\")) self.tasks.append(task_fetch_partitions(\"Fetch partitions\", self.disk)) self.tasks.append(task_refresh_partitions(\"Refresh partition information\", self.disk))", "self.tasks.append(task_mount(\"Mount the target disk\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_remove_persistent_rules(\"Remove persistent rules\", disk=self.disk,", "'\\d+'): part = int(part) pass runner_id = disk.device_name runner =", "partition_id=self.partition_id, imagename=self.imagename)) task = task_expand_partition(\"Expand the partion back\", disk=self.disk, partition_id=self.partition_id)", "import task_fetch_partitions, task_refresh_partitions, task_mount, task_remove_persistent_rules, task_remove_logs, task_fsck, task_shrink_partition, task_expand_partition, task_unmount", "image # import re, sys, traceback from .tasks import task_fetch_partitions,", "# FIXME: If I want to make this to a", "system back to the max. For now, this is only", "super().prepare() # self.tasks.append(task_mount_nfs_destination(self, \"Mount the destination volume\")) self.tasks.append(task_fetch_partitions(\"Fetch partitions\", self.disk))", "waiting.\", \"Prepare\": \"Savign disk is preparing.\", \"Preflight\": \"Saving disk is", "= make_disk_image_name(destdir, suggestedname) pass def prepare(self): super().prepare() # self.tasks.append(task_mount_nfs_destination(self, \"Mount", "task_shrink_partition, task_expand_partition, task_unmount from .partclone_tasks import task_create_disk_image from .ops_ui import", "\"Preflight\", \"Running\", \"Success\", \"Failed\"] my_messages = { \"Waiting\": \"Saving disk", "disk=self.disk, partition_id=self.partition_id)) task = task_unmount(\"Unmount target\", disk=self.disk, partition_id=self.partition_id) task.set_teardown_task() self.tasks.append(task)", "successfully.\", \"Failed\": \"Saving disk failed.\" } # class ImageDiskRunner(Runner): '''Runner", "= int(part) pass runner_id = disk.device_name runner = ImageDiskRunner(ui, runner_id,", "from .ops_ui import console_ui from ..components.disk import create_storage_instance from .runner", "Exception as exc: sys.stderr.write(traceback.format_exc(exc) + \"\\n\") sys.exit(1) # NOTREACHED pass", "\"Success\": \"Saving disk completed successfully.\", \"Failed\": \"Saving disk failed.\" }", "to a generic clone app, I need to deal with", "self.disk = disk self.partition_id = partition_id self.destdir = destdir self.imagename", "creating disk image. does fsck, shrink partition, create disk image", "destdir == \"preflight\": ui = console_ui() do_it = False pass", "runs this with json_ui. do_it = True if destdir ==", "= json_ui(wock_event=\"saveimage\", message_catalog=my_messages) pass if re.match(part, '\\d+'): part = int(part)", "def __init__(self, ui, runner_id, disk, destdir, suggestedname=None, partition_id='Linux'): super().__init__(ui, runner_id)", "from .json_ui import json_ui from ..lib.util import init_triage_logger, is_block_device #", "runner_id = disk.device_name runner = ImageDiskRunner(ui, runner_id, disk, destdir, partition_id=part)", "disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_shrink_partition(\"Shrink partition to smallest\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_create_disk_image(\"Create disk", "\"Prepare\", \"Preflight\", \"Running\", \"Success\", \"Failed\"] my_messages = { \"Waiting\": \"Saving", "\"__main__\": tlog = init_triage_logger() if len(sys.argv) == 1: print( 'Unloader:", "with json_ui. do_it = True if destdir == \"preflight\": ui", "init_triage_logger() if len(sys.argv) == 1: print( 'Unloader: devicename part destdir')", "print( '%s is not a block device.' % devname) sys.exit(1)", "the file system back to the max. For now, this", "destdir, partition_id=part) try: runner.prepare() runner.preflight() runner.explain() runner.run() sys.exit(0) # NOTREACHED", "disk is preparing.\", \"Preflight\": \"Saving disk is preparing.\", \"Running\": \"{step}", "True pass else: ui = json_ui(wock_event=\"saveimage\", message_catalog=my_messages) pass if re.match(part,", "Runner from ..lib.disk_images import make_disk_image_name from .json_ui import json_ui from", "= ImageDiskRunner(ui, runner_id, disk, destdir, partition_id=part) try: runner.prepare() runner.preflight() runner.explain()", "clone app, I need to deal with all of partitions", "\"Waiting\": \"Saving disk is waiting.\", \"Prepare\": \"Savign disk is preparing.\",", "preparing.\", \"Running\": \"{step} of {steps}: Running {task}\", \"Success\": \"Saving disk", "ui = console_ui() do_it = False pass elif destdir ==", "disk image. does fsck, shrink partition, create disk image and", "do_it = True pass else: ui = json_ui(wock_event=\"saveimage\", message_catalog=my_messages) pass", "task_remove_persistent_rules, task_remove_logs, task_fsck, task_shrink_partition, task_expand_partition, task_unmount from .partclone_tasks import task_create_disk_image", "pass part = sys.argv[2] # This is a partition id", "now, this is only dealing with the EXT4 linux partition.", "a time. def __init__(self, ui, runner_id, disk, destdir, suggestedname=None, partition_id='Linux'):", "= True pass else: ui = json_ui(wock_event=\"saveimage\", message_catalog=my_messages) pass if", "smallest\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_create_disk_image(\"Create disk image\", disk=self.disk, partition_id=self.partition_id, imagename=self.imagename)) task", "the target disk\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_remove_persistent_rules(\"Remove persistent rules\", disk=self.disk, partition_id=self.partition_id))", "from .tasks import task_fetch_partitions, task_refresh_partitions, task_mount, task_remove_persistent_rules, task_remove_logs, task_fsck, task_shrink_partition,", ".tasks import task_fetch_partitions, task_refresh_partitions, task_mount, task_remove_persistent_rules, task_remove_logs, task_fsck, task_shrink_partition, task_expand_partition,", "server runs this with json_ui. do_it = True if destdir", "disk.device_name runner = ImageDiskRunner(ui, runner_id, disk, destdir, partition_id=part) try: runner.prepare()", "suggestedname) pass def prepare(self): super().prepare() # self.tasks.append(task_mount_nfs_destination(self, \"Mount the destination", "True if destdir == \"preflight\": ui = console_ui() do_it =", "#!/usr/bin/env python3 # # Create disk image # import re,", "disk=self.disk, partition_id=self.partition_id) task.set_teardown_task() self.tasks.append(task) pass pass if __name__ == \"__main__\":", "do_it = False pass elif destdir == \"testflight\": ui =", "http server runs this with json_ui. do_it = True if", "= sys.argv[1] if not is_block_device(devname): print( '%s is not a", "partition_id='Linux'): super().__init__(ui, runner_id) self.time_estimate = 600 self.disk = disk self.partition_id", "= task_unmount(\"Unmount target\", disk=self.disk, partition_id=self.partition_id) task.set_teardown_task() self.tasks.append(task) self.tasks.append(task_fsck(\"fsck partition\", disk=self.disk,", "if len(sys.argv) == 1: print( 'Unloader: devicename part destdir') sys.exit(0)", "One step at a time. def __init__(self, ui, runner_id, disk,", "\"{step} of {steps}: Running {task}\", \"Success\": \"Saving disk completed successfully.\",", "pass else: ui = json_ui(wock_event=\"saveimage\", message_catalog=my_messages) pass if re.match(part, '\\d+'):", "file system back to the max. For now, this is", "disk. # One step at a time. def __init__(self, ui,", "'''Runner for creating disk image. does fsck, shrink partition, create", "# This is a partition id destdir = sys.argv[3] #", "For now, this is only dealing with the EXT4 linux", "partition information\", self.disk)) self.tasks.append(task_mount(\"Mount the target disk\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_remove_persistent_rules(\"Remove", "max. For now, this is only dealing with the EXT4", "does fsck, shrink partition, create disk image and resize the", "def prepare(self): super().prepare() # self.tasks.append(task_mount_nfs_destination(self, \"Mount the destination volume\")) self.tasks.append(task_fetch_partitions(\"Fetch", "\"Savign disk is preparing.\", \"Preflight\": \"Saving disk is preparing.\", \"Running\":", "\"Mount the destination volume\")) self.tasks.append(task_fetch_partitions(\"Fetch partitions\", self.disk)) self.tasks.append(task_refresh_partitions(\"Refresh partition information\",", "task = task_expand_partition(\"Expand the partion back\", disk=self.disk, partition_id=self.partition_id) task.set_teardown_task() self.tasks.append(task)", "# Create disk image # import re, sys, traceback from", "runner = ImageDiskRunner(ui, runner_id, disk, destdir, partition_id=part) try: runner.prepare() runner.preflight()", "to make this to a generic clone app, I need", "disk self.partition_id = partition_id self.destdir = destdir self.imagename = make_disk_image_name(destdir,", "if not is_block_device(devname): print( '%s is not a block device.'", "runner_id) self.time_estimate = 600 self.disk = disk self.partition_id = partition_id", "me to see the tasks. http server runs this with", "import create_storage_instance from .runner import Runner from ..lib.disk_images import make_disk_image_name", "re.match(part, '\\d+'): part = int(part) pass runner_id = disk.device_name runner", "== \"testflight\": ui = console_ui() do_it = True pass else:", "preparing.\", \"Preflight\": \"Saving disk is preparing.\", \"Running\": \"{step} of {steps}:", "{steps}: Running {task}\", \"Success\": \"Saving disk completed successfully.\", \"Failed\": \"Saving", ".partclone_tasks import task_create_disk_image from .ops_ui import console_ui from ..components.disk import", "= False pass elif destdir == \"testflight\": ui = console_ui()", "sys.exit(1) # NOTREACHED pass part = sys.argv[2] # This is", "= init_triage_logger() if len(sys.argv) == 1: print( 'Unloader: devicename part", "\"Success\", \"Failed\"] my_messages = { \"Waiting\": \"Saving disk is waiting.\",", "create disk image and resize the file system back to", "deal with all of partitions on the disk. # One", "= 600 self.disk = disk self.partition_id = partition_id self.destdir =", "the EXT4 linux partition. ''' # FIXME: If I want", "sys.argv[3] # Destination directory disk = create_storage_instance(devname) # Preflight is", "= disk self.partition_id = partition_id self.destdir = destdir self.imagename =", "self.tasks.append(task_fetch_partitions(\"Fetch partitions\", self.disk)) self.tasks.append(task_refresh_partitions(\"Refresh partition information\", self.disk)) self.tasks.append(task_mount(\"Mount the target", "self.tasks.append(task) self.tasks.append(task_fsck(\"fsck partition\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_shrink_partition(\"Shrink partition to smallest\", disk=self.disk,", "disk, destdir, suggestedname=None, partition_id='Linux'): super().__init__(ui, runner_id) self.time_estimate = 600 self.disk", "\"Saving disk is preparing.\", \"Running\": \"{step} of {steps}: Running {task}\",", "disk\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_remove_persistent_rules(\"Remove persistent rules\", disk=self.disk, partition_id=self.partition_id)) self.tasks.append(task_remove_logs(\"Remove/Clean Logs\",", "python3 # # Create disk image # import re, sys,", "is preparing.\", \"Running\": \"{step} of {steps}: Running {task}\", \"Success\": \"Saving", "with the EXT4 linux partition. ''' # FIXME: If I", "task_create_disk_image from .ops_ui import console_ui from ..components.disk import create_storage_instance from", "message_catalog=my_messages) pass if re.match(part, '\\d+'): part = int(part) pass runner_id", "..lib.disk_images import make_disk_image_name from .json_ui import json_ui from ..lib.util import", "1: print( 'Unloader: devicename part destdir') sys.exit(0) # NOTREACHED pass", "task.set_teardown_task() self.tasks.append(task) pass pass if __name__ == \"__main__\": tlog =", "\"Prepare\": \"Savign disk is preparing.\", \"Preflight\": \"Saving disk is preparing.\",", "sys.exit(0) # NOTREACHED except Exception as exc: sys.stderr.write(traceback.format_exc(exc) + \"\\n\")", "suggestedname=None, partition_id='Linux'): super().__init__(ui, runner_id) self.time_estimate = 600 self.disk = disk", "# import re, sys, traceback from .tasks import task_fetch_partitions, task_refresh_partitions,", "partitions on the disk. # One step at a time.", "..lib.util import init_triage_logger, is_block_device # \"Waiting\", \"Prepare\", \"Preflight\", \"Running\", \"Success\",", "json_ui from ..lib.util import init_triage_logger, is_block_device # \"Waiting\", \"Prepare\", \"Preflight\",", "a partition id destdir = sys.argv[3] # Destination directory disk", "volume\")) self.tasks.append(task_fetch_partitions(\"Fetch partitions\", self.disk)) self.tasks.append(task_refresh_partitions(\"Refresh partition information\", self.disk)) self.tasks.append(task_mount(\"Mount the", "dealing with the EXT4 linux partition. ''' # FIXME: If", "This is a partition id destdir = sys.argv[3] # Destination", "= console_ui() do_it = True pass else: ui = json_ui(wock_event=\"saveimage\",", "directory disk = create_storage_instance(devname) # Preflight is for me to", "= create_storage_instance(devname) # Preflight is for me to see the", "partition_id=self.partition_id)) task = task_unmount(\"Unmount target\", disk=self.disk, partition_id=self.partition_id) task.set_teardown_task() self.tasks.append(task) self.tasks.append(task_fsck(\"fsck", "= partition_id self.destdir = destdir self.imagename = make_disk_image_name(destdir, suggestedname) pass", "failed.\" } # class ImageDiskRunner(Runner): '''Runner for creating disk image.", "console_ui from ..components.disk import create_storage_instance from .runner import Runner from", "my_messages = { \"Waiting\": \"Saving disk is waiting.\", \"Prepare\": \"Savign", "I need to deal with all of partitions on the" ]
[ "with beam.Pipeline(options=pipeline_options) as pipeline: raw_lines = pipeline | 'ReadFromCsv' >>", "= rating if not math.isnan(rating) else None new_element['Size'] = string_to_megabyte(element['Size'])", "%d, %Y').strftime('%Y-%m-%d') new_element['Category'] = element['Category'] new_element['Genres'] = element['Genres'] new_element['App'] =", "import ReadFromText, WriteToText from apache_beam.options.pipeline_options import PipelineOptions class ProcessCSV(beam.DoFn): def", ">> beam.ParDo(ProcessCSV()) output = lines | 'parseRecord' >> beam.ParDo(ParseRecord()) output", "runs the pipeline.\"\"\" parser = argparse.ArgumentParser() parser.add_argument('--input', dest='input', default='gs://meetup-batch-processing/input/googleplaystore.csv', help='Input", "default='gs://meetup-batch-processing/input/googleplaystore.csv', help='Input file to process.') parser.add_argument('--output', dest='output', default='gs://meetup-batch-processing/output/googleplaystore.csv', help='Output file", "pipeline.\"\"\" parser = argparse.ArgumentParser() parser.add_argument('--input', dest='input', default='gs://meetup-batch-processing/input/googleplaystore.csv', help='Input file to", "return [new_element] def run(argv=None): \"\"\"Main entry point. It defines and", ">> WriteToBigQuery(known_args.table_output, write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE, create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER) logging.info('Finished.') if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO)", "= int(element['Installs'].replace(\"+\", \"\").replace(\",\",\"\")) new_element['Last_Updated'] = datetime.strptime(element['Last_Updated'], '%B %d, %Y').strftime('%Y-%m-%d') new_element['Category']", "'writeBigQuery' >> WriteToBigQuery(known_args.table_output, write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE, create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER) logging.info('Finished.') if __name__ == '__main__':", "import WriteToBigQuery from apache_beam.io import ReadFromText, WriteToText from apache_beam.options.pipeline_options import", "pipeline | 'ReadFromCsv' >> ReadFromText(known_args.input, skip_header_lines=1) lines = raw_lines |", "the pipeline.\"\"\" parser = argparse.ArgumentParser() parser.add_argument('--input', dest='input', default='gs://meetup-batch-processing/input/googleplaystore.csv', help='Input file", "beam.Pipeline(options=pipeline_options) as pipeline: raw_lines = pipeline | 'ReadFromCsv' >> ReadFromText(known_args.input,", "file to process.') parser.add_argument('--table-output', dest='table_output', default='meetup-hands-on-gcp-2019:googleplaystore_batch_dataflow.play_store', help='Bigquery table name for", "import csv formated_element = [element.encode('utf8')] processed_csv = csv.DictReader(formated_element, fieldnames=['App', 'Category',", "raw_lines = pipeline | 'ReadFromCsv' >> ReadFromText(known_args.input, skip_header_lines=1) lines =", "skip_header_lines=1) lines = raw_lines | 'processCsv' >> beam.ParDo(ProcessCSV()) output =", "new_element['Category'] = element['Category'] new_element['Genres'] = element['Genres'] new_element['App'] = element['App'] new_element['Content_Rating']", "name for output.') known_args, pipeline_args = parser.parse_known_args(argv) pipeline_options = PipelineOptions(pipeline_args)", "run(argv=None): \"\"\"Main entry point. It defines and runs the pipeline.\"\"\"", "point. It defines and runs the pipeline.\"\"\" parser = argparse.ArgumentParser()", "ReadFromText, WriteToText from apache_beam.options.pipeline_options import PipelineOptions class ProcessCSV(beam.DoFn): def process(self,", "/ 1000000 new_element = {} rating = float(element['Rating']) new_element['Rating'] =", "'Reviews', 'Size', 'Installs', 'Type', 'Price', 'Content_Rating', 'Genres', 'Last_Updated', 'Current_Ver', 'Android_Ver'],", "= [element.encode('utf8')] processed_csv = csv.DictReader(formated_element, fieldnames=['App', 'Category', 'Rating', 'Reviews', 'Size',", "'Genres', 'Last_Updated', 'Current_Ver', 'Android_Ver'], delimiter=',') processed_fields = processed_csv.next() if processed_fields.get('Category').replace('.','').isdigit():", "process(self, element, *args, **kwargs): from datetime import datetime import math", "None return (float(raw_string[:-1]) * multiplier) / 1000000 new_element = {}", "WriteToBigQuery from apache_beam.io import ReadFromText, WriteToText from apache_beam.options.pipeline_options import PipelineOptions", "(float(raw_string[:-1]) * multiplier) / 1000000 new_element = {} rating =", "pipeline_args = parser.parse_known_args(argv) pipeline_options = PipelineOptions(pipeline_args) with beam.Pipeline(options=pipeline_options) as pipeline:", "return (float(raw_string[:-1]) * multiplier) / 1000000 new_element = {} rating", "new_element['Last_Updated'] = datetime.strptime(element['Last_Updated'], '%B %d, %Y').strftime('%Y-%m-%d') new_element['Category'] = element['Category'] new_element['Genres']", "'Type', 'Price', 'Content_Rating', 'Genres', 'Last_Updated', 'Current_Ver', 'Android_Ver'], delimiter=',') processed_fields =", "* multiplier) / 1000000 new_element = {} rating = float(element['Rating'])", "process.') parser.add_argument('--output', dest='output', default='gs://meetup-batch-processing/output/googleplaystore.csv', help='Output file to process.') parser.add_argument('--table-output', dest='table_output',", "datetime.strptime(element['Last_Updated'], '%B %d, %Y').strftime('%Y-%m-%d') new_element['Category'] = element['Category'] new_element['Genres'] = element['Genres']", "pipeline_options = PipelineOptions(pipeline_args) with beam.Pipeline(options=pipeline_options) as pipeline: raw_lines = pipeline", "element['Android_Ver'] new_element['Type'] = element['Type'] new_element['Current_Ver'] = element['Current_Ver'] logging.info(new_element) return [new_element]", "file to process.') parser.add_argument('--output', dest='output', default='gs://meetup-batch-processing/output/googleplaystore.csv', help='Output file to process.')", "'Android_Ver'], delimiter=',') processed_fields = processed_csv.next() if processed_fields.get('Category').replace('.','').isdigit(): return None return", "= element['Current_Ver'] logging.info(new_element) return [new_element] def run(argv=None): \"\"\"Main entry point.", "'Installs', 'Type', 'Price', 'Content_Rating', 'Genres', 'Last_Updated', 'Current_Ver', 'Android_Ver'], delimiter=',') processed_fields", "known_args, pipeline_args = parser.parse_known_args(argv) pipeline_options = PipelineOptions(pipeline_args) with beam.Pipeline(options=pipeline_options) as", "help='Input file to process.') parser.add_argument('--output', dest='output', default='gs://meetup-batch-processing/output/googleplaystore.csv', help='Output file to", "to process.') parser.add_argument('--output', dest='output', default='gs://meetup-batch-processing/output/googleplaystore.csv', help='Output file to process.') parser.add_argument('--table-output',", "None new_element['Size'] = string_to_megabyte(element['Size']) new_element['Price'] = float(element['Price'].replace(\"$\",\"\")) new_element['Installs'] = int(element['Installs'].replace(\"+\",", "beam.ParDo(ParseRecord()) output | 'writeBigQuery' >> WriteToBigQuery(known_args.table_output, write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE, create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER) logging.info('Finished.') if", "ProcessCSV(beam.DoFn): def process(self, element, *args, **kwargs): import csv formated_element =", "import apache_beam as beam from apache_beam.io import WriteToBigQuery from apache_beam.io", "as beam from apache_beam.io import WriteToBigQuery from apache_beam.io import ReadFromText,", "WriteToText from apache_beam.options.pipeline_options import PipelineOptions class ProcessCSV(beam.DoFn): def process(self, element,", "else None new_element['Size'] = string_to_megabyte(element['Size']) new_element['Price'] = float(element['Price'].replace(\"$\",\"\")) new_element['Installs'] =", "= element['App'] new_element['Content_Rating'] = element['Content_Rating'] new_element['Reviews'] = element['Reviews'] new_element['Android_Ver'] =", "for output.') known_args, pipeline_args = parser.parse_known_args(argv) pipeline_options = PipelineOptions(pipeline_args) with", "element['Reviews'] new_element['Android_Ver'] = element['Android_Ver'] new_element['Type'] = element['Type'] new_element['Current_Ver'] = element['Current_Ver']", "parser = argparse.ArgumentParser() parser.add_argument('--input', dest='input', default='gs://meetup-batch-processing/input/googleplaystore.csv', help='Input file to process.')", "float(element['Price'].replace(\"$\",\"\")) new_element['Installs'] = int(element['Installs'].replace(\"+\", \"\").replace(\",\",\"\")) new_element['Last_Updated'] = datetime.strptime(element['Last_Updated'], '%B %d,", "parser.add_argument('--table-output', dest='table_output', default='meetup-hands-on-gcp-2019:googleplaystore_batch_dataflow.play_store', help='Bigquery table name for output.') known_args, pipeline_args", "dest='table_output', default='meetup-hands-on-gcp-2019:googleplaystore_batch_dataflow.play_store', help='Bigquery table name for output.') known_args, pipeline_args =", "and runs the pipeline.\"\"\" parser = argparse.ArgumentParser() parser.add_argument('--input', dest='input', default='gs://meetup-batch-processing/input/googleplaystore.csv',", "process(self, element, *args, **kwargs): import csv formated_element = [element.encode('utf8')] processed_csv", "ReadFromText(known_args.input, skip_header_lines=1) lines = raw_lines | 'processCsv' >> beam.ParDo(ProcessCSV()) output", "element['Genres'] new_element['App'] = element['App'] new_element['Content_Rating'] = element['Content_Rating'] new_element['Reviews'] = element['Reviews']", "from datetime import datetime import math def string_to_megabyte(raw_string): if raw_string.upper().endswith('K'):", "element['Category'] new_element['Genres'] = element['Genres'] new_element['App'] = element['App'] new_element['Content_Rating'] = element['Content_Rating']", "help='Bigquery table name for output.') known_args, pipeline_args = parser.parse_known_args(argv) pipeline_options", "'%B %d, %Y').strftime('%Y-%m-%d') new_element['Category'] = element['Category'] new_element['Genres'] = element['Genres'] new_element['App']", ">> beam.ParDo(ParseRecord()) output | 'writeBigQuery' >> WriteToBigQuery(known_args.table_output, write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE, create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER) logging.info('Finished.')", "'ReadFromCsv' >> ReadFromText(known_args.input, skip_header_lines=1) lines = raw_lines | 'processCsv' >>", "element, *args, **kwargs): import csv formated_element = [element.encode('utf8')] processed_csv =", "table name for output.') known_args, pipeline_args = parser.parse_known_args(argv) pipeline_options =", "element['Current_Ver'] logging.info(new_element) return [new_element] def run(argv=None): \"\"\"Main entry point. It", "csv formated_element = [element.encode('utf8')] processed_csv = csv.DictReader(formated_element, fieldnames=['App', 'Category', 'Rating',", "new_element['Size'] = string_to_megabyte(element['Size']) new_element['Price'] = float(element['Price'].replace(\"$\",\"\")) new_element['Installs'] = int(element['Installs'].replace(\"+\", \"\").replace(\",\",\"\"))", "processed_csv = csv.DictReader(formated_element, fieldnames=['App', 'Category', 'Rating', 'Reviews', 'Size', 'Installs', 'Type',", "fieldnames=['App', 'Category', 'Rating', 'Reviews', 'Size', 'Installs', 'Type', 'Price', 'Content_Rating', 'Genres',", "WriteToBigQuery(known_args.table_output, write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE, create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER) logging.info('Finished.') if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) run()", "= pipeline | 'ReadFromCsv' >> ReadFromText(known_args.input, skip_header_lines=1) lines = raw_lines", "'parseRecord' >> beam.ParDo(ParseRecord()) output | 'writeBigQuery' >> WriteToBigQuery(known_args.table_output, write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE, create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER)", "from apache_beam.options.pipeline_options import PipelineOptions class ProcessCSV(beam.DoFn): def process(self, element, *args,", "beam from apache_beam.io import WriteToBigQuery from apache_beam.io import ReadFromText, WriteToText", "def string_to_megabyte(raw_string): if raw_string.upper().endswith('K'): multiplier = 1000 elif raw_string.upper().endswith('M'): multiplier", "lines = raw_lines | 'processCsv' >> beam.ParDo(ProcessCSV()) output = lines", "from apache_beam.io import ReadFromText, WriteToText from apache_beam.options.pipeline_options import PipelineOptions class", "parser.add_argument('--input', dest='input', default='gs://meetup-batch-processing/input/googleplaystore.csv', help='Input file to process.') parser.add_argument('--output', dest='output', default='gs://meetup-batch-processing/output/googleplaystore.csv',", "int(element['Installs'].replace(\"+\", \"\").replace(\",\",\"\")) new_element['Last_Updated'] = datetime.strptime(element['Last_Updated'], '%B %d, %Y').strftime('%Y-%m-%d') new_element['Category'] =", "1000 * 1000 else: return None return (float(raw_string[:-1]) * multiplier)", "| 'writeBigQuery' >> WriteToBigQuery(known_args.table_output, write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE, create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER) logging.info('Finished.') if __name__ ==", "*args, **kwargs): import csv formated_element = [element.encode('utf8')] processed_csv = csv.DictReader(formated_element,", "*args, **kwargs): from datetime import datetime import math def string_to_megabyte(raw_string):", "= 1000 * 1000 else: return None return (float(raw_string[:-1]) *", "new_element['Rating'] = rating if not math.isnan(rating) else None new_element['Size'] =", "'Price', 'Content_Rating', 'Genres', 'Last_Updated', 'Current_Ver', 'Android_Ver'], delimiter=',') processed_fields = processed_csv.next()", "new_element['App'] = element['App'] new_element['Content_Rating'] = element['Content_Rating'] new_element['Reviews'] = element['Reviews'] new_element['Android_Ver']", "new_element['Genres'] = element['Genres'] new_element['App'] = element['App'] new_element['Content_Rating'] = element['Content_Rating'] new_element['Reviews']", "[new_element] def run(argv=None): \"\"\"Main entry point. It defines and runs", "'Content_Rating', 'Genres', 'Last_Updated', 'Current_Ver', 'Android_Ver'], delimiter=',') processed_fields = processed_csv.next() if", "if not math.isnan(rating) else None new_element['Size'] = string_to_megabyte(element['Size']) new_element['Price'] =", "pipeline: raw_lines = pipeline | 'ReadFromCsv' >> ReadFromText(known_args.input, skip_header_lines=1) lines", "delimiter=',') processed_fields = processed_csv.next() if processed_fields.get('Category').replace('.','').isdigit(): return None return [processed_fields]", "import logging import apache_beam as beam from apache_beam.io import WriteToBigQuery", "parser.add_argument('--output', dest='output', default='gs://meetup-batch-processing/output/googleplaystore.csv', help='Output file to process.') parser.add_argument('--table-output', dest='table_output', default='meetup-hands-on-gcp-2019:googleplaystore_batch_dataflow.play_store',", "<gh_stars>1-10 import argparse import logging import apache_beam as beam from", "processed_fields = processed_csv.next() if processed_fields.get('Category').replace('.','').isdigit(): return None return [processed_fields] class", "= element['Type'] new_element['Current_Ver'] = element['Current_Ver'] logging.info(new_element) return [new_element] def run(argv=None):", "dest='input', default='gs://meetup-batch-processing/input/googleplaystore.csv', help='Input file to process.') parser.add_argument('--output', dest='output', default='gs://meetup-batch-processing/output/googleplaystore.csv', help='Output", "multiplier = 1000 elif raw_string.upper().endswith('M'): multiplier = 1000 * 1000", "= datetime.strptime(element['Last_Updated'], '%B %d, %Y').strftime('%Y-%m-%d') new_element['Category'] = element['Category'] new_element['Genres'] =", "= element['Content_Rating'] new_element['Reviews'] = element['Reviews'] new_element['Android_Ver'] = element['Android_Ver'] new_element['Type'] =", "| 'parseRecord' >> beam.ParDo(ParseRecord()) output | 'writeBigQuery' >> WriteToBigQuery(known_args.table_output, write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE,", "return None return [processed_fields] class ParseRecord(beam.DoFn): def process(self, element, *args,", "multiplier) / 1000000 new_element = {} rating = float(element['Rating']) new_element['Rating']", "'Category', 'Rating', 'Reviews', 'Size', 'Installs', 'Type', 'Price', 'Content_Rating', 'Genres', 'Last_Updated',", "= {} rating = float(element['Rating']) new_element['Rating'] = rating if not", "rating = float(element['Rating']) new_element['Rating'] = rating if not math.isnan(rating) else", "default='gs://meetup-batch-processing/output/googleplaystore.csv', help='Output file to process.') parser.add_argument('--table-output', dest='table_output', default='meetup-hands-on-gcp-2019:googleplaystore_batch_dataflow.play_store', help='Bigquery table", "ParseRecord(beam.DoFn): def process(self, element, *args, **kwargs): from datetime import datetime", "= string_to_megabyte(element['Size']) new_element['Price'] = float(element['Price'].replace(\"$\",\"\")) new_element['Installs'] = int(element['Installs'].replace(\"+\", \"\").replace(\",\",\"\")) new_element['Last_Updated']", "= element['Category'] new_element['Genres'] = element['Genres'] new_element['App'] = element['App'] new_element['Content_Rating'] =", "new_element['Type'] = element['Type'] new_element['Current_Ver'] = element['Current_Ver'] logging.info(new_element) return [new_element] def", "logging.info(new_element) return [new_element] def run(argv=None): \"\"\"Main entry point. It defines", "output.') known_args, pipeline_args = parser.parse_known_args(argv) pipeline_options = PipelineOptions(pipeline_args) with beam.Pipeline(options=pipeline_options)", "rating if not math.isnan(rating) else None new_element['Size'] = string_to_megabyte(element['Size']) new_element['Price']", "= element['Genres'] new_element['App'] = element['App'] new_element['Content_Rating'] = element['Content_Rating'] new_element['Reviews'] =", "elif raw_string.upper().endswith('M'): multiplier = 1000 * 1000 else: return None", "= float(element['Price'].replace(\"$\",\"\")) new_element['Installs'] = int(element['Installs'].replace(\"+\", \"\").replace(\",\",\"\")) new_element['Last_Updated'] = datetime.strptime(element['Last_Updated'], '%B", "= element['Android_Ver'] new_element['Type'] = element['Type'] new_element['Current_Ver'] = element['Current_Ver'] logging.info(new_element) return", "apache_beam.io import ReadFromText, WriteToText from apache_beam.options.pipeline_options import PipelineOptions class ProcessCSV(beam.DoFn):", "return None return (float(raw_string[:-1]) * multiplier) / 1000000 new_element =", "not math.isnan(rating) else None new_element['Size'] = string_to_megabyte(element['Size']) new_element['Price'] = float(element['Price'].replace(\"$\",\"\"))", "class ProcessCSV(beam.DoFn): def process(self, element, *args, **kwargs): import csv formated_element", "%Y').strftime('%Y-%m-%d') new_element['Category'] = element['Category'] new_element['Genres'] = element['Genres'] new_element['App'] = element['App']", "default='meetup-hands-on-gcp-2019:googleplaystore_batch_dataflow.play_store', help='Bigquery table name for output.') known_args, pipeline_args = parser.parse_known_args(argv)", "'Last_Updated', 'Current_Ver', 'Android_Ver'], delimiter=',') processed_fields = processed_csv.next() if processed_fields.get('Category').replace('.','').isdigit(): return", "output = lines | 'parseRecord' >> beam.ParDo(ParseRecord()) output | 'writeBigQuery'", "It defines and runs the pipeline.\"\"\" parser = argparse.ArgumentParser() parser.add_argument('--input',", "new_element['Installs'] = int(element['Installs'].replace(\"+\", \"\").replace(\",\",\"\")) new_element['Last_Updated'] = datetime.strptime(element['Last_Updated'], '%B %d, %Y').strftime('%Y-%m-%d')", "def run(argv=None): \"\"\"Main entry point. It defines and runs the", "parser.parse_known_args(argv) pipeline_options = PipelineOptions(pipeline_args) with beam.Pipeline(options=pipeline_options) as pipeline: raw_lines =", "apache_beam as beam from apache_beam.io import WriteToBigQuery from apache_beam.io import", "{} rating = float(element['Rating']) new_element['Rating'] = rating if not math.isnan(rating)", "argparse import logging import apache_beam as beam from apache_beam.io import", "1000 else: return None return (float(raw_string[:-1]) * multiplier) / 1000000", "new_element['Android_Ver'] = element['Android_Ver'] new_element['Type'] = element['Type'] new_element['Current_Ver'] = element['Current_Ver'] logging.info(new_element)", ">> ReadFromText(known_args.input, skip_header_lines=1) lines = raw_lines | 'processCsv' >> beam.ParDo(ProcessCSV())", "element['App'] new_element['Content_Rating'] = element['Content_Rating'] new_element['Reviews'] = element['Reviews'] new_element['Android_Ver'] = element['Android_Ver']", "formated_element = [element.encode('utf8')] processed_csv = csv.DictReader(formated_element, fieldnames=['App', 'Category', 'Rating', 'Reviews',", "help='Output file to process.') parser.add_argument('--table-output', dest='table_output', default='meetup-hands-on-gcp-2019:googleplaystore_batch_dataflow.play_store', help='Bigquery table name", "as pipeline: raw_lines = pipeline | 'ReadFromCsv' >> ReadFromText(known_args.input, skip_header_lines=1)", "to process.') parser.add_argument('--table-output', dest='table_output', default='meetup-hands-on-gcp-2019:googleplaystore_batch_dataflow.play_store', help='Bigquery table name for output.')", "apache_beam.options.pipeline_options import PipelineOptions class ProcessCSV(beam.DoFn): def process(self, element, *args, **kwargs):", "[processed_fields] class ParseRecord(beam.DoFn): def process(self, element, *args, **kwargs): from datetime", "multiplier = 1000 * 1000 else: return None return (float(raw_string[:-1])", "defines and runs the pipeline.\"\"\" parser = argparse.ArgumentParser() parser.add_argument('--input', dest='input',", "processed_csv.next() if processed_fields.get('Category').replace('.','').isdigit(): return None return [processed_fields] class ParseRecord(beam.DoFn): def", "output | 'writeBigQuery' >> WriteToBigQuery(known_args.table_output, write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE, create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER) logging.info('Finished.') if __name__", "if processed_fields.get('Category').replace('.','').isdigit(): return None return [processed_fields] class ParseRecord(beam.DoFn): def process(self,", "new_element['Reviews'] = element['Reviews'] new_element['Android_Ver'] = element['Android_Ver'] new_element['Type'] = element['Type'] new_element['Current_Ver']", "raw_lines | 'processCsv' >> beam.ParDo(ProcessCSV()) output = lines | 'parseRecord'", "\"\").replace(\",\",\"\")) new_element['Last_Updated'] = datetime.strptime(element['Last_Updated'], '%B %d, %Y').strftime('%Y-%m-%d') new_element['Category'] = element['Category']", "csv.DictReader(formated_element, fieldnames=['App', 'Category', 'Rating', 'Reviews', 'Size', 'Installs', 'Type', 'Price', 'Content_Rating',", "= processed_csv.next() if processed_fields.get('Category').replace('.','').isdigit(): return None return [processed_fields] class ParseRecord(beam.DoFn):", "| 'ReadFromCsv' >> ReadFromText(known_args.input, skip_header_lines=1) lines = raw_lines | 'processCsv'", "new_element = {} rating = float(element['Rating']) new_element['Rating'] = rating if", "dest='output', default='gs://meetup-batch-processing/output/googleplaystore.csv', help='Output file to process.') parser.add_argument('--table-output', dest='table_output', default='meetup-hands-on-gcp-2019:googleplaystore_batch_dataflow.play_store', help='Bigquery", "| 'processCsv' >> beam.ParDo(ProcessCSV()) output = lines | 'parseRecord' >>", "PipelineOptions class ProcessCSV(beam.DoFn): def process(self, element, *args, **kwargs): import csv", "else: return None return (float(raw_string[:-1]) * multiplier) / 1000000 new_element", "element['Content_Rating'] new_element['Reviews'] = element['Reviews'] new_element['Android_Ver'] = element['Android_Ver'] new_element['Type'] = element['Type']", "= float(element['Rating']) new_element['Rating'] = rating if not math.isnan(rating) else None", "= parser.parse_known_args(argv) pipeline_options = PipelineOptions(pipeline_args) with beam.Pipeline(options=pipeline_options) as pipeline: raw_lines", "'Rating', 'Reviews', 'Size', 'Installs', 'Type', 'Price', 'Content_Rating', 'Genres', 'Last_Updated', 'Current_Ver',", "raw_string.upper().endswith('M'): multiplier = 1000 * 1000 else: return None return", "class ParseRecord(beam.DoFn): def process(self, element, *args, **kwargs): from datetime import", "argparse.ArgumentParser() parser.add_argument('--input', dest='input', default='gs://meetup-batch-processing/input/googleplaystore.csv', help='Input file to process.') parser.add_argument('--output', dest='output',", "element, *args, **kwargs): from datetime import datetime import math def", "process.') parser.add_argument('--table-output', dest='table_output', default='meetup-hands-on-gcp-2019:googleplaystore_batch_dataflow.play_store', help='Bigquery table name for output.') known_args,", "processed_fields.get('Category').replace('.','').isdigit(): return None return [processed_fields] class ParseRecord(beam.DoFn): def process(self, element,", "[element.encode('utf8')] processed_csv = csv.DictReader(formated_element, fieldnames=['App', 'Category', 'Rating', 'Reviews', 'Size', 'Installs',", "return [processed_fields] class ParseRecord(beam.DoFn): def process(self, element, *args, **kwargs): from", "import PipelineOptions class ProcessCSV(beam.DoFn): def process(self, element, *args, **kwargs): import", "apache_beam.io import WriteToBigQuery from apache_beam.io import ReadFromText, WriteToText from apache_beam.options.pipeline_options", "def process(self, element, *args, **kwargs): import csv formated_element = [element.encode('utf8')]", "'Current_Ver', 'Android_Ver'], delimiter=',') processed_fields = processed_csv.next() if processed_fields.get('Category').replace('.','').isdigit(): return None", "new_element['Content_Rating'] = element['Content_Rating'] new_element['Reviews'] = element['Reviews'] new_element['Android_Ver'] = element['Android_Ver'] new_element['Type']", "raw_string.upper().endswith('K'): multiplier = 1000 elif raw_string.upper().endswith('M'): multiplier = 1000 *", "import datetime import math def string_to_megabyte(raw_string): if raw_string.upper().endswith('K'): multiplier =", "beam.ParDo(ProcessCSV()) output = lines | 'parseRecord' >> beam.ParDo(ParseRecord()) output |", "math.isnan(rating) else None new_element['Size'] = string_to_megabyte(element['Size']) new_element['Price'] = float(element['Price'].replace(\"$\",\"\")) new_element['Installs']", "1000000 new_element = {} rating = float(element['Rating']) new_element['Rating'] = rating", "'Size', 'Installs', 'Type', 'Price', 'Content_Rating', 'Genres', 'Last_Updated', 'Current_Ver', 'Android_Ver'], delimiter=',')", "string_to_megabyte(raw_string): if raw_string.upper().endswith('K'): multiplier = 1000 elif raw_string.upper().endswith('M'): multiplier =", "string_to_megabyte(element['Size']) new_element['Price'] = float(element['Price'].replace(\"$\",\"\")) new_element['Installs'] = int(element['Installs'].replace(\"+\", \"\").replace(\",\",\"\")) new_element['Last_Updated'] =", "element['Type'] new_element['Current_Ver'] = element['Current_Ver'] logging.info(new_element) return [new_element] def run(argv=None): \"\"\"Main", "= PipelineOptions(pipeline_args) with beam.Pipeline(options=pipeline_options) as pipeline: raw_lines = pipeline |", "**kwargs): from datetime import datetime import math def string_to_megabyte(raw_string): if", "new_element['Current_Ver'] = element['Current_Ver'] logging.info(new_element) return [new_element] def run(argv=None): \"\"\"Main entry", "= csv.DictReader(formated_element, fieldnames=['App', 'Category', 'Rating', 'Reviews', 'Size', 'Installs', 'Type', 'Price',", "* 1000 else: return None return (float(raw_string[:-1]) * multiplier) /", "PipelineOptions(pipeline_args) with beam.Pipeline(options=pipeline_options) as pipeline: raw_lines = pipeline | 'ReadFromCsv'", "logging import apache_beam as beam from apache_beam.io import WriteToBigQuery from", "lines | 'parseRecord' >> beam.ParDo(ParseRecord()) output | 'writeBigQuery' >> WriteToBigQuery(known_args.table_output,", "def process(self, element, *args, **kwargs): from datetime import datetime import", "= raw_lines | 'processCsv' >> beam.ParDo(ProcessCSV()) output = lines |", "= 1000 elif raw_string.upper().endswith('M'): multiplier = 1000 * 1000 else:", "= lines | 'parseRecord' >> beam.ParDo(ParseRecord()) output | 'writeBigQuery' >>", "\"\"\"Main entry point. It defines and runs the pipeline.\"\"\" parser", "None return [processed_fields] class ParseRecord(beam.DoFn): def process(self, element, *args, **kwargs):", "1000 elif raw_string.upper().endswith('M'): multiplier = 1000 * 1000 else: return", "float(element['Rating']) new_element['Rating'] = rating if not math.isnan(rating) else None new_element['Size']", "import math def string_to_megabyte(raw_string): if raw_string.upper().endswith('K'): multiplier = 1000 elif", "**kwargs): import csv formated_element = [element.encode('utf8')] processed_csv = csv.DictReader(formated_element, fieldnames=['App',", "new_element['Price'] = float(element['Price'].replace(\"$\",\"\")) new_element['Installs'] = int(element['Installs'].replace(\"+\", \"\").replace(\",\",\"\")) new_element['Last_Updated'] = datetime.strptime(element['Last_Updated'],", "math def string_to_megabyte(raw_string): if raw_string.upper().endswith('K'): multiplier = 1000 elif raw_string.upper().endswith('M'):", "= element['Reviews'] new_element['Android_Ver'] = element['Android_Ver'] new_element['Type'] = element['Type'] new_element['Current_Ver'] =", "= argparse.ArgumentParser() parser.add_argument('--input', dest='input', default='gs://meetup-batch-processing/input/googleplaystore.csv', help='Input file to process.') parser.add_argument('--output',", "'processCsv' >> beam.ParDo(ProcessCSV()) output = lines | 'parseRecord' >> beam.ParDo(ParseRecord())", "import argparse import logging import apache_beam as beam from apache_beam.io", "if raw_string.upper().endswith('K'): multiplier = 1000 elif raw_string.upper().endswith('M'): multiplier = 1000", "from apache_beam.io import WriteToBigQuery from apache_beam.io import ReadFromText, WriteToText from", "datetime import math def string_to_megabyte(raw_string): if raw_string.upper().endswith('K'): multiplier = 1000", "entry point. It defines and runs the pipeline.\"\"\" parser =", "datetime import datetime import math def string_to_megabyte(raw_string): if raw_string.upper().endswith('K'): multiplier" ]
[ "exists'}, 404 message.delete() db.session.commit() return {'status': 'sucess', 'message': 'Message Deleted'},", "'Message already exists'}, 400 message = Message(orig_msg=data.get('orig_msg'), tl_msg=data.get('tl_msg'), country=data.get('country'), username=data.get('username'))", "if not message.first(): return {'status': 'fail', 'message': 'No message with", "get(self, lower, upper): \"\"\"Gets a range of messages on the", "'Error handling request'}, 422 data = message_schema.load(json_data) message = Message.query.filter_by(orig_msg=data.get('orig_msg')).first()", "app, cache, db from main.server.models import Message, MessageSchema messages_schema =", "'count': Message.query.count()}, 200 class MessageListRangeResource(Resource): @cache.cached(timeout=100) def get(self, lower, upper):", "import Message, MessageSchema messages_schema = MessageSchema(many=True) message_schema = MessageSchema() @app.after_request", "@app.after_request def add_header(response): response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Credentials'] = 'true' response.headers['Access-Control-Allow-Methods']", "@cache.cached(timeout=100) def get(self): \"\"\"Gets all messages on the server\"\"\" messages", "message = Message(orig_msg=data.get('orig_msg'), tl_msg=data.get('tl_msg'), country=data.get('country'), username=data.get('username')) db.session.add(message) db.session.commit() return {'status':", "be less than lower range: ' + str(lower) + '>'", "'fail', 'message': 'No input data'}, 400 errors = message_schema.validate(json_data) if", "message = Message.query.filter_by(messageID=messageID) if not message.first(): return {'status': 'fail', 'message':", "' exists'}, 404 message.delete() db.session.commit() return {'status': 'sucess', 'message': 'Message", "@cache.cached(timeout=100) def get(self, messageID): \"\"\"\"Get a message by message ID\"\"\"", "\"\"\"Gets a range of messages on the server\"\"\" if int(lower)", "Content Served return {'status': 'success', 'messages': messages}, 200 class MessageListResource(Resource):", "errors = message_schema.validate(json_data) if errors: return {'status': 'fail', 'message': 'Error", "X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers' return response class MessageCount(Resource): @cache.cached(timeout=100) def", "+ ' - ' + str(upper) + ' does not", "'message': 'Message already exists'}, 400 message = Message(orig_msg=data.get('orig_msg'), tl_msg=data.get('tl_msg'), country=data.get('country'),", "if not json_data: return {'status': 'fail', 'message': 'No input data'},", "upper): \"\"\"Gets a range of messages on the server\"\"\" if", "message_schema.validate(json_data) if errors: return {'status': 'fail', 'message': 'Error handling request'},", "index: ' + str(lower)}, 400 if int(lower) > int(upper): return", "'success', 'messages': messages}, 200 @jwt_required() def post(self): \"\"\"Add message\"\"\" json_data", "Message.query.filter_by(orig_msg=data.get('orig_msg')).first() if message: return {'status': 'fail', 'message': 'Message already exists'},", "= Message.query.filter_by(orig_msg=data.get('orig_msg')).first() if message: return {'status': 'fail', 'message': 'Message already", "'Invalid index: ' + str(lower)}, 400 if int(lower) > int(upper):", "' + str(lower) + ' - ' + str(upper) +", "messages: return {'status': 'success', 'messages': messages}, 206 # Partial Content", "'messages': messages}, 200 class MessageListResource(Resource): @cache.cached(timeout=100) def get(self): \"\"\"Gets all", "' - ' + str(upper) + ' does not exist'},", "lower range: ' + str(lower) + '>' + str(upper)}, 400", "Partial Content Served return {'status': 'success', 'messages': messages}, 200 @jwt_required()", "Content Served return {'status': 'success', 'messages': messages}, 200 @jwt_required() def", "MessageSchema(many=True) message_schema = MessageSchema() @app.after_request def add_header(response): response.headers['Access-Control-Allow-Origin'] = '*'", "'fail', 'message': 'No message with ID ' + str(messageID) +", "400 message = Message(orig_msg=data.get('orig_msg'), tl_msg=data.get('tl_msg'), country=data.get('country'), username=data.get('username')) db.session.add(message) db.session.commit() return", "class MessageCount(Resource): @cache.cached(timeout=100) def get(self): \"\"\"Gets the number of messages", "not Message.query.filter_by(messageID=upper).first(): # the last item in the range return", "int(lower) > int(upper): return {'status': 'fail', 'messages': 'Upper range cannot", "{'status': 'success', 'messages': messages}, 200 class MessageListResource(Resource): @cache.cached(timeout=100) def get(self):", "\"\"\"Gets the number of messages available on the server\"\"\" return", "Access-Control-Request-Method, Access-Control-Request-Headers' return response class MessageCount(Resource): @cache.cached(timeout=100) def get(self): \"\"\"Gets", "with ID ' + str(messageID) + ' exists'}, 404 message.delete()", "from flask_jwt import jwt_required from flask_restful import Resource from main.server", "message = messages_schema.dump(message) return {'status': 'success', 'messages': message}, 200 @jwt_required()", "if int(lower) > int(upper): return {'status': 'fail', 'messages': 'Upper range", "+ str(messageID) + ' exists'}, 404 message.delete() db.session.commit() return {'status':", "the number of messages available on the server\"\"\" return {'status':", "= '*' response.headers['Access-Control-Allow-Credentials'] = 'true' response.headers['Access-Control-Allow-Methods'] = 'GET, POST' response.headers[", "= 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers' return response class", "+ ' does not exist'}, 404 messages = messages_schema.dump(messages) if", "return {'status': 'success', 'messages': messages}, 206 # Partial Content Served", "request.get_json(force=True) if not json_data: return {'status': 'fail', 'message': 'No input", "class MessageListResource(Resource): @cache.cached(timeout=100) def get(self): \"\"\"Gets all messages on the", "+ str(upper)}, 400 messages = Message.query.filter(Message.messageID >= int(lower)).filter(Message.messageID <= int(upper))", "int(upper)) if not messages: return {'status': 'fail', 'messages': 'Out of", "db from main.server.models import Message, MessageSchema messages_schema = MessageSchema(many=True) message_schema", "messages = messages_schema.dump(messages) if not Message.query.filter_by(messageID=upper).first(): # the last item", "import Resource from main.server import app, cache, db from main.server.models", "from main.server.models import Message, MessageSchema messages_schema = MessageSchema(many=True) message_schema =", "+ ' exists'}, 404 message.delete() db.session.commit() return {'status': 'sucess', 'message':", "400 errors = message_schema.validate(json_data) if errors: return {'status': 'fail', 'message':", "def delete(self, messageID): \"\"\"delete a message by ID\"\"\" message =", "of messages on the server\"\"\" if int(lower) < 1: return", "{'status': 'fail', 'message': 'No input data'}, 400 errors = message_schema.validate(json_data)", "def get(self): \"\"\"Gets all messages on the server\"\"\" messages =", "'messages': 'Invalid index: ' + str(lower)}, 400 if int(lower) >", "+ '>' + str(upper)}, 400 messages = Message.query.filter(Message.messageID >= int(lower)).filter(Message.messageID", "'Upper range cannot be less than lower range: ' +", "class MessageListRangeResource(Resource): @cache.cached(timeout=100) def get(self, lower, upper): \"\"\"Gets a range", "# the last item in the range return {'status': 'success',", "on the server\"\"\" return {'status': 'success', 'count': Message.query.count()}, 200 class", "a message by message ID\"\"\" message = Message.query.filter_by(messageID=messageID) if not", "Served return {'status': 'success', 'messages': messages}, 200 class MessageListResource(Resource): @cache.cached(timeout=100)", "{'status': 'success', 'message': 'Message successfully created'}, 201 class MessageResource(Resource): @cache.cached(timeout=100)", "' + str(messageID) + ' exists'}, 404 message.delete() db.session.commit() return", "= Message.query.all() messages = messages_schema.dump(messages) if not messages: return {'status':", "\"\"\"Gets all messages on the server\"\"\" messages = Message.query.all() messages", "by message ID\"\"\" message = Message.query.filter_by(messageID=messageID) if not message.first(): return", "response.headers['Access-Control-Allow-Credentials'] = 'true' response.headers['Access-Control-Allow-Methods'] = 'GET, POST' response.headers[ 'Access-Control-Allow-Headers'] =", "db.session.commit() return {'status': 'success', 'message': 'Message successfully created'}, 201 class", "def add_header(response): response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Credentials'] = 'true' response.headers['Access-Control-Allow-Methods'] =", "= MessageSchema() @app.after_request def add_header(response): response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Credentials'] =", "delete(self, messageID): \"\"\"delete a message by ID\"\"\" message = Message.query.filter_by(messageID=messageID)", "messages_schema.dump(messages) if not messages: return {'status': 'success', 'messages': messages}, 206", "'*' response.headers['Access-Control-Allow-Credentials'] = 'true' response.headers['Access-Control-Allow-Methods'] = 'GET, POST' response.headers[ 'Access-Control-Allow-Headers']", "in the range return {'status': 'success', 'messages': messages}, 206 #", ">= int(lower)).filter(Message.messageID <= int(upper)) if not messages: return {'status': 'fail',", "exists'}, 400 message = Message(orig_msg=data.get('orig_msg'), tl_msg=data.get('tl_msg'), country=data.get('country'), username=data.get('username')) db.session.add(message) db.session.commit()", "not messages: return {'status': 'success', 'messages': messages}, 206 # Partial", "response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Credentials'] = 'true' response.headers['Access-Control-Allow-Methods'] = 'GET, POST'", "ID ' + str(messageID) + ' exists'}, 404 message =", "if not messages: return {'status': 'success', 'messages': messages}, 206 #", "# Partial Content Served return {'status': 'success', 'messages': messages}, 200", "message = Message.query.filter_by(orig_msg=data.get('orig_msg')).first() if message: return {'status': 'fail', 'message': 'Message", "def post(self): \"\"\"Add message\"\"\" json_data = request.get_json(force=True) if not json_data:", "from main.server import app, cache, db from main.server.models import Message,", "post(self): \"\"\"Add message\"\"\" json_data = request.get_json(force=True) if not json_data: return", "add_header(response): response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Credentials'] = 'true' response.headers['Access-Control-Allow-Methods'] = 'GET,", "ID ' + str(messageID) + ' exists'}, 404 message.delete() db.session.commit()", "Message(orig_msg=data.get('orig_msg'), tl_msg=data.get('tl_msg'), country=data.get('country'), username=data.get('username')) db.session.add(message) db.session.commit() return {'status': 'success', 'message':", "return {'status': 'success', 'messages': message}, 200 @jwt_required() def delete(self, messageID):", "'fail', 'messages': 'Upper range cannot be less than lower range:", "message ID\"\"\" message = Message.query.filter_by(messageID=messageID) if not message.first(): return {'status':", "server\"\"\" messages = Message.query.all() messages = messages_schema.dump(messages) if not messages:", "on the server\"\"\" if int(lower) < 1: return {'status': 'fail',", "messages_schema = MessageSchema(many=True) message_schema = MessageSchema() @app.after_request def add_header(response): response.headers['Access-Control-Allow-Origin']", "messages available on the server\"\"\" return {'status': 'success', 'count': Message.query.count()},", "the server\"\"\" messages = Message.query.all() messages = messages_schema.dump(messages) if not", "@jwt_required() def delete(self, messageID): \"\"\"delete a message by ID\"\"\" message", "= Message.query.filter_by(messageID=messageID) if not message.first(): return {'status': 'fail', 'message': 'No", "if not messages: return {'status': 'fail', 'messages': 'Out of range:", "Served return {'status': 'success', 'messages': messages}, 200 @jwt_required() def post(self):", "422 data = message_schema.load(json_data) message = Message.query.filter_by(orig_msg=data.get('orig_msg')).first() if message: return", "flask_jwt import jwt_required from flask_restful import Resource from main.server import", "by ID\"\"\" message = Message.query.filter_by(messageID=messageID) if not message.first(): return {'status':", "data = message_schema.load(json_data) message = Message.query.filter_by(orig_msg=data.get('orig_msg')).first() if message: return {'status':", "get(self, messageID): \"\"\"\"Get a message by message ID\"\"\" message =", "int(lower) < 1: return {'status': 'fail', 'messages': 'Invalid index: '", "= message_schema.validate(json_data) if errors: return {'status': 'fail', 'message': 'Error handling", "not exist'}, 404 messages = messages_schema.dump(messages) if not Message.query.filter_by(messageID=upper).first(): #", "'No input data'}, 400 errors = message_schema.validate(json_data) if errors: return", "' + str(messageID) + ' exists'}, 404 message = messages_schema.dump(message)", "message_schema.load(json_data) message = Message.query.filter_by(orig_msg=data.get('orig_msg')).first() if message: return {'status': 'fail', 'message':", "<= int(upper)) if not messages: return {'status': 'fail', 'messages': 'Out", "POST' response.headers[ 'Access-Control-Allow-Headers'] = 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'", "'messages': messages}, 206 # Partial Content Served return {'status': 'success',", "json_data: return {'status': 'fail', 'message': 'No input data'}, 400 errors", "return {'status': 'fail', 'message': 'Error handling request'}, 422 data =", "'messages': messages}, 200 @jwt_required() def post(self): \"\"\"Add message\"\"\" json_data =", "201 class MessageResource(Resource): @cache.cached(timeout=100) def get(self, messageID): \"\"\"\"Get a message", "cache, db from main.server.models import Message, MessageSchema messages_schema = MessageSchema(many=True)", "the last item in the range return {'status': 'success', 'messages':", "range return {'status': 'success', 'messages': messages}, 206 # Partial Content", "on the server\"\"\" messages = Message.query.all() messages = messages_schema.dump(messages) if", "MessageCount(Resource): @cache.cached(timeout=100) def get(self): \"\"\"Gets the number of messages available", "{'status': 'success', 'count': Message.query.count()}, 200 class MessageListRangeResource(Resource): @cache.cached(timeout=100) def get(self,", "successfully created'}, 201 class MessageResource(Resource): @cache.cached(timeout=100) def get(self, messageID): \"\"\"\"Get", "= messages_schema.dump(messages) if not Message.query.filter_by(messageID=upper).first(): # the last item in", "'success', 'messages': messages}, 206 # Partial Content Served return {'status':", "message.first(): return {'status': 'fail', 'message': 'No message with ID '", "'success', 'message': 'Message successfully created'}, 201 class MessageResource(Resource): @cache.cached(timeout=100) def", "\"\"\"delete a message by ID\"\"\" message = Message.query.filter_by(messageID=messageID) if not", "{'status': 'success', 'messages': messages}, 206 # Partial Content Served return", "messages on the server\"\"\" if int(lower) < 1: return {'status':", "get(self): \"\"\"Gets all messages on the server\"\"\" messages = Message.query.all()", "return {'status': 'success', 'count': Message.query.count()}, 200 class MessageListRangeResource(Resource): @cache.cached(timeout=100) def", "server\"\"\" if int(lower) < 1: return {'status': 'fail', 'messages': 'Invalid", "206 # Partial Content Served return {'status': 'success', 'messages': messages},", "less than lower range: ' + str(lower) + '>' +", "request from flask_jwt import jwt_required from flask_restful import Resource from", "= MessageSchema(many=True) message_schema = MessageSchema() @app.after_request def add_header(response): response.headers['Access-Control-Allow-Origin'] =", "of range: ' + str(lower) + ' - ' +", "messages}, 200 @jwt_required() def post(self): \"\"\"Add message\"\"\" json_data = request.get_json(force=True)", "{'status': 'fail', 'message': 'No message with ID ' + str(messageID)", "return {'status': 'success', 'messages': messages}, 200 @jwt_required() def post(self): \"\"\"Add", "str(messageID) + ' exists'}, 404 message.delete() db.session.commit() return {'status': 'sucess',", "200 @jwt_required() def post(self): \"\"\"Add message\"\"\" json_data = request.get_json(force=True) if", "= message_schema.load(json_data) message = Message.query.filter_by(orig_msg=data.get('orig_msg')).first() if message: return {'status': 'fail',", "'success', 'messages': message}, 200 @jwt_required() def delete(self, messageID): \"\"\"delete a", "all messages on the server\"\"\" messages = Message.query.all() messages =", "return {'status': 'fail', 'message': 'Message already exists'}, 400 message =", "messages_schema.dump(messages) if not Message.query.filter_by(messageID=upper).first(): # the last item in the", "last item in the range return {'status': 'success', 'messages': messages},", "int(lower)).filter(Message.messageID <= int(upper)) if not messages: return {'status': 'fail', 'messages':", "'GET, POST' response.headers[ 'Access-Control-Allow-Headers'] = 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method,", "with ID ' + str(messageID) + ' exists'}, 404 message", "+ str(upper) + ' does not exist'}, 404 messages =", "Message.query.count()}, 200 class MessageListRangeResource(Resource): @cache.cached(timeout=100) def get(self, lower, upper): \"\"\"Gets", "str(lower)}, 400 if int(lower) > int(upper): return {'status': 'fail', 'messages':", "1: return {'status': 'fail', 'messages': 'Invalid index: ' + str(lower)},", "exist'}, 404 messages = messages_schema.dump(messages) if not Message.query.filter_by(messageID=upper).first(): # the", "from flask import request from flask_jwt import jwt_required from flask_restful", "'messages': message}, 200 @jwt_required() def delete(self, messageID): \"\"\"delete a message", "'fail', 'message': 'Message already exists'}, 400 message = Message(orig_msg=data.get('orig_msg'), tl_msg=data.get('tl_msg'),", "json_data = request.get_json(force=True) if not json_data: return {'status': 'fail', 'message':", "{'status': 'success', 'messages': messages}, 200 @jwt_required() def post(self): \"\"\"Add message\"\"\"", "\"\"\"Add message\"\"\" json_data = request.get_json(force=True) if not json_data: return {'status':", "\"\"\"\"Get a message by message ID\"\"\" message = Message.query.filter_by(messageID=messageID) if", "get(self): \"\"\"Gets the number of messages available on the server\"\"\"", "country=data.get('country'), username=data.get('username')) db.session.add(message) db.session.commit() return {'status': 'success', 'message': 'Message successfully", "main.server import app, cache, db from main.server.models import Message, MessageSchema", "+ str(messageID) + ' exists'}, 404 message = messages_schema.dump(message) return", "MessageSchema messages_schema = MessageSchema(many=True) message_schema = MessageSchema() @app.after_request def add_header(response):", "return {'status': 'fail', 'messages': 'Invalid index: ' + str(lower)}, 400", "'Access-Control-Allow-Headers'] = 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers' return response", "def get(self, messageID): \"\"\"\"Get a message by message ID\"\"\" message", "the server\"\"\" return {'status': 'success', 'count': Message.query.count()}, 200 class MessageListRangeResource(Resource):", "if int(lower) < 1: return {'status': 'fail', 'messages': 'Invalid index:", "Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers' return response class MessageCount(Resource): @cache.cached(timeout=100)", "of messages available on the server\"\"\" return {'status': 'success', 'count':", "Resource from main.server import app, cache, db from main.server.models import", "' + str(lower)}, 400 if int(lower) > int(upper): return {'status':", "= Message(orig_msg=data.get('orig_msg'), tl_msg=data.get('tl_msg'), country=data.get('country'), username=data.get('username')) db.session.add(message) db.session.commit() return {'status': 'success',", "than lower range: ' + str(lower) + '>' + str(upper)},", "message\"\"\" json_data = request.get_json(force=True) if not json_data: return {'status': 'fail',", "response.headers['Access-Control-Allow-Methods'] = 'GET, POST' response.headers[ 'Access-Control-Allow-Headers'] = 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With,", "return {'status': 'success', 'messages': messages}, 200 class MessageListResource(Resource): @cache.cached(timeout=100) def", "str(messageID) + ' exists'}, 404 message = messages_schema.dump(message) return {'status':", "' + str(lower) + '>' + str(upper)}, 400 messages =", "'message': 'No message with ID ' + str(messageID) + '", "server\"\"\" return {'status': 'success', 'count': Message.query.count()}, 200 class MessageListRangeResource(Resource): @cache.cached(timeout=100)", "main.server.models import Message, MessageSchema messages_schema = MessageSchema(many=True) message_schema = MessageSchema()", "errors: return {'status': 'fail', 'message': 'Error handling request'}, 422 data", "messages = Message.query.filter(Message.messageID >= int(lower)).filter(Message.messageID <= int(upper)) if not messages:", "cannot be less than lower range: ' + str(lower) +", "404 message.delete() db.session.commit() return {'status': 'sucess', 'message': 'Message Deleted'}, 200", "MessageListResource(Resource): @cache.cached(timeout=100) def get(self): \"\"\"Gets all messages on the server\"\"\"", "'No message with ID ' + str(messageID) + ' exists'},", "message with ID ' + str(messageID) + ' exists'}, 404", "def get(self, lower, upper): \"\"\"Gets a range of messages on", "'true' response.headers['Access-Control-Allow-Methods'] = 'GET, POST' response.headers[ 'Access-Control-Allow-Headers'] = 'Access-Control-Allow-Headers, Origin,Accept,", "' + str(upper) + ' does not exist'}, 404 messages", "exists'}, 404 message = messages_schema.dump(message) return {'status': 'success', 'messages': message},", "= 'true' response.headers['Access-Control-Allow-Methods'] = 'GET, POST' response.headers[ 'Access-Control-Allow-Headers'] = 'Access-Control-Allow-Headers,", "number of messages available on the server\"\"\" return {'status': 'success',", "200 class MessageListRangeResource(Resource): @cache.cached(timeout=100) def get(self, lower, upper): \"\"\"Gets a", "Partial Content Served return {'status': 'success', 'messages': messages}, 200 class", "messages = messages_schema.dump(messages) if not messages: return {'status': 'success', 'messages':", "{'status': 'success', 'messages': message}, 200 @jwt_required() def delete(self, messageID): \"\"\"delete", "{'status': 'fail', 'messages': 'Invalid index: ' + str(lower)}, 400 if", "messages = Message.query.all() messages = messages_schema.dump(messages) if not messages: return", "import jwt_required from flask_restful import Resource from main.server import app,", "lower, upper): \"\"\"Gets a range of messages on the server\"\"\"", "username=data.get('username')) db.session.add(message) db.session.commit() return {'status': 'success', 'message': 'Message successfully created'},", "data'}, 400 errors = message_schema.validate(json_data) if errors: return {'status': 'fail',", "= messages_schema.dump(message) return {'status': 'success', 'messages': message}, 200 @jwt_required() def", "' exists'}, 404 message = messages_schema.dump(message) return {'status': 'success', 'messages':", "range: ' + str(lower) + ' - ' + str(upper)", "'messages': 'Upper range cannot be less than lower range: '", "import app, cache, db from main.server.models import Message, MessageSchema messages_schema", "= request.get_json(force=True) if not json_data: return {'status': 'fail', 'message': 'No", "str(lower) + '>' + str(upper)}, 400 messages = Message.query.filter(Message.messageID >=", "Message, MessageSchema messages_schema = MessageSchema(many=True) message_schema = MessageSchema() @app.after_request def", "return {'status': 'fail', 'messages': 'Upper range cannot be less than", "handling request'}, 422 data = message_schema.load(json_data) message = Message.query.filter_by(orig_msg=data.get('orig_msg')).first() if", "not messages: return {'status': 'fail', 'messages': 'Out of range: '", "'success', 'messages': messages}, 200 class MessageListResource(Resource): @cache.cached(timeout=100) def get(self): \"\"\"Gets", "def get(self): \"\"\"Gets the number of messages available on the", "item in the range return {'status': 'success', 'messages': messages}, 206", "400 messages = Message.query.filter(Message.messageID >= int(lower)).filter(Message.messageID <= int(upper)) if not", "404 messages = messages_schema.dump(messages) if not Message.query.filter_by(messageID=upper).first(): # the last", "created'}, 201 class MessageResource(Resource): @cache.cached(timeout=100) def get(self, messageID): \"\"\"\"Get a", "int(upper): return {'status': 'fail', 'messages': 'Upper range cannot be less", "the server\"\"\" if int(lower) < 1: return {'status': 'fail', 'messages':", "flask import request from flask_jwt import jwt_required from flask_restful import", "MessageListRangeResource(Resource): @cache.cached(timeout=100) def get(self, lower, upper): \"\"\"Gets a range of", "a range of messages on the server\"\"\" if int(lower) <", "messageID): \"\"\"\"Get a message by message ID\"\"\" message = Message.query.filter_by(messageID=messageID)", "'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers' return response class MessageCount(Resource):", "Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers' return response class MessageCount(Resource): @cache.cached(timeout=100) def get(self):", "Message.query.filter_by(messageID=messageID) if not message.first(): return {'status': 'fail', 'message': 'No message", "= Message.query.filter(Message.messageID >= int(lower)).filter(Message.messageID <= int(upper)) if not messages: return", "ID\"\"\" message = Message.query.filter_by(messageID=messageID) if not message.first(): return {'status': 'fail',", "'success', 'count': Message.query.count()}, 200 class MessageListRangeResource(Resource): @cache.cached(timeout=100) def get(self, lower,", "range: ' + str(lower) + '>' + str(upper)}, 400 messages", "Access-Control-Request-Headers' return response class MessageCount(Resource): @cache.cached(timeout=100) def get(self): \"\"\"Gets the", "'fail', 'messages': 'Invalid index: ' + str(lower)}, 400 if int(lower)", "= 'GET, POST' response.headers[ 'Access-Control-Allow-Headers'] = 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type,", "return {'status': 'fail', 'messages': 'Out of range: ' + str(lower)", "'Message successfully created'}, 201 class MessageResource(Resource): @cache.cached(timeout=100) def get(self, messageID):", "messages}, 206 # Partial Content Served return {'status': 'success', 'messages':", "tl_msg=data.get('tl_msg'), country=data.get('country'), username=data.get('username')) db.session.add(message) db.session.commit() return {'status': 'success', 'message': 'Message", "return {'status': 'fail', 'message': 'No input data'}, 400 errors =", "range cannot be less than lower range: ' + str(lower)", "message: return {'status': 'fail', 'message': 'Message already exists'}, 400 message", "jwt_required from flask_restful import Resource from main.server import app, cache,", "' does not exist'}, 404 messages = messages_schema.dump(messages) if not", "'message': 'Message successfully created'}, 201 class MessageResource(Resource): @cache.cached(timeout=100) def get(self,", "messageID): \"\"\"delete a message by ID\"\"\" message = Message.query.filter_by(messageID=messageID) if", "'message': 'No input data'}, 400 errors = message_schema.validate(json_data) if errors:", "messages}, 200 class MessageListResource(Resource): @cache.cached(timeout=100) def get(self): \"\"\"Gets all messages", "if not Message.query.filter_by(messageID=upper).first(): # the last item in the range", "messages: return {'status': 'fail', 'messages': 'Out of range: ' +", "messages_schema.dump(message) return {'status': 'success', 'messages': message}, 200 @jwt_required() def delete(self,", "'fail', 'messages': 'Out of range: ' + str(lower) + '", "'message': 'Error handling request'}, 422 data = message_schema.load(json_data) message =", "'>' + str(upper)}, 400 messages = Message.query.filter(Message.messageID >= int(lower)).filter(Message.messageID <=", "available on the server\"\"\" return {'status': 'success', 'count': Message.query.count()}, 200", "404 message = messages_schema.dump(message) return {'status': 'success', 'messages': message}, 200", "the range return {'status': 'success', 'messages': messages}, 206 # Partial", "MessageResource(Resource): @cache.cached(timeout=100) def get(self, messageID): \"\"\"\"Get a message by message", "> int(upper): return {'status': 'fail', 'messages': 'Upper range cannot be", "a message by ID\"\"\" message = Message.query.filter_by(messageID=messageID) if not message.first():", "not message.first(): return {'status': 'fail', 'message': 'No message with ID", "str(lower) + ' - ' + str(upper) + ' does", "< 1: return {'status': 'fail', 'messages': 'Invalid index: ' +", "message by message ID\"\"\" message = Message.query.filter_by(messageID=messageID) if not message.first():", "from flask_restful import Resource from main.server import app, cache, db", "already exists'}, 400 message = Message(orig_msg=data.get('orig_msg'), tl_msg=data.get('tl_msg'), country=data.get('country'), username=data.get('username')) db.session.add(message)", "request'}, 422 data = message_schema.load(json_data) message = Message.query.filter_by(orig_msg=data.get('orig_msg')).first() if message:", "str(upper) + ' does not exist'}, 404 messages = messages_schema.dump(messages)", "import request from flask_jwt import jwt_required from flask_restful import Resource", "response class MessageCount(Resource): @cache.cached(timeout=100) def get(self): \"\"\"Gets the number of", "{'status': 'fail', 'message': 'Message already exists'}, 400 message = Message(orig_msg=data.get('orig_msg'),", "message by ID\"\"\" message = Message.query.filter_by(messageID=messageID) if not message.first(): return", "messages on the server\"\"\" messages = Message.query.all() messages = messages_schema.dump(messages)", "message}, 200 @jwt_required() def delete(self, messageID): \"\"\"delete a message by", "Message.query.all() messages = messages_schema.dump(messages) if not messages: return {'status': 'success',", "return {'status': 'success', 'message': 'Message successfully created'}, 201 class MessageResource(Resource):", "- ' + str(upper) + ' does not exist'}, 404", "200 class MessageListResource(Resource): @cache.cached(timeout=100) def get(self): \"\"\"Gets all messages on", "Message.query.filter_by(messageID=upper).first(): # the last item in the range return {'status':", "return {'status': 'fail', 'message': 'No message with ID ' +", "if errors: return {'status': 'fail', 'message': 'Error handling request'}, 422", "'fail', 'message': 'Error handling request'}, 422 data = message_schema.load(json_data) message", "return response class MessageCount(Resource): @cache.cached(timeout=100) def get(self): \"\"\"Gets the number", "@cache.cached(timeout=100) def get(self, lower, upper): \"\"\"Gets a range of messages", "@jwt_required() def post(self): \"\"\"Add message\"\"\" json_data = request.get_json(force=True) if not", "class MessageResource(Resource): @cache.cached(timeout=100) def get(self, messageID): \"\"\"\"Get a message by", "Message.query.filter(Message.messageID >= int(lower)).filter(Message.messageID <= int(upper)) if not messages: return {'status':", "response.headers[ 'Access-Control-Allow-Headers'] = 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers' return", "str(upper)}, 400 messages = Message.query.filter(Message.messageID >= int(lower)).filter(Message.messageID <= int(upper)) if", "'messages': 'Out of range: ' + str(lower) + ' -", "flask_restful import Resource from main.server import app, cache, db from", "does not exist'}, 404 messages = messages_schema.dump(messages) if not Message.query.filter_by(messageID=upper).first():", "{'status': 'fail', 'message': 'Error handling request'}, 422 data = message_schema.load(json_data)", "400 if int(lower) > int(upper): return {'status': 'fail', 'messages': 'Upper", "if message: return {'status': 'fail', 'message': 'Message already exists'}, 400", "{'status': 'fail', 'messages': 'Upper range cannot be less than lower", "@cache.cached(timeout=100) def get(self): \"\"\"Gets the number of messages available on", "input data'}, 400 errors = message_schema.validate(json_data) if errors: return {'status':", "message_schema = MessageSchema() @app.after_request def add_header(response): response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Credentials']", "range of messages on the server\"\"\" if int(lower) < 1:", "+ str(lower) + '>' + str(upper)}, 400 messages = Message.query.filter(Message.messageID", "+ ' exists'}, 404 message = messages_schema.dump(message) return {'status': 'success',", "200 @jwt_required() def delete(self, messageID): \"\"\"delete a message by ID\"\"\"", "not json_data: return {'status': 'fail', 'message': 'No input data'}, 400", "MessageSchema() @app.after_request def add_header(response): response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Credentials'] = 'true'", "+ str(lower)}, 400 if int(lower) > int(upper): return {'status': 'fail',", "'Out of range: ' + str(lower) + ' - '", "+ str(lower) + ' - ' + str(upper) + '", "= messages_schema.dump(messages) if not messages: return {'status': 'success', 'messages': messages},", "db.session.add(message) db.session.commit() return {'status': 'success', 'message': 'Message successfully created'}, 201", "{'status': 'fail', 'messages': 'Out of range: ' + str(lower) +" ]
[ "1.]), ObjectMsg('lime0', 'package://wecook_assets/data/food/lime.urdf', [0.3, -0.3, 0.757, 0., 0., 0., 1.]),", "0.707, 0.707]), ObjectMsg('chicken0', 'package://wecook_assets/data/food/chicken.urdf', [0.3, 0.075, 0.757, 0., 0., 0.,", "0., 1.]), ObjectMsg('knife0', 'package://wecook_assets/data/objects/knife_big.urdf', [0.215, -0.55, 0.775, 0., 0., 0.,", "ObjectMsg('salt0', 'package://wecook_assets/data/objects/salt.urdf', [0., 1.0, 0.75, 0., 0., 0.707, 0.707]), ObjectMsg('pepper0',", "1.]), ObjectMsg('counter1', 'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0., 1.0, 0., 0., 0., 0.707, 0.707]),", "1.]), ObjectMsg('bowl0', 'package://wecook_assets/data/objects/bowl_green.urdf', [0.45, 0.375, 0.75, 0., 0., 0., 1.]),", "ObjectMsg('pot0', 'package://wecook_assets/data/objects/cooking_pot.urdf', [0.35, 1.1, 0.75, 0., 0., 0., 1.]), ObjectMsg('skillet0',", "[0.15, 0.375, 0.75, 0., 0., 0., 1.]), ObjectMsg('oil0', 'package://wecook_assets/data/objects/olive_oil.urdf', [0.,", "'cut', ['plate0'], 'knife0', ['lime0'])], [AgentMsg('p1', 'r', [0., 0., 0.75, 0.,", "'package://wecook_assets/data/objects/olive_oil.urdf', [0., 1.15, 0.75, 0., 0., 0.707, 0.707]), ObjectMsg('salt0', 'package://wecook_assets/data/objects/salt.urdf',", "[0.215, -0.55, 0.775, 0., 0., 0., 1.]), ObjectMsg('plate0', 'package://wecook_assets/data/objects/plate.urdf', [0.3,", "0., 0., 0., 1.]), ObjectMsg('stove0', 'package://wecook_assets/data/objects/stove.urdf', [-0.35, 0.95, 0.75, 0.,", "10 seconds to publish rospy.sleep(1) pub.publish(task_msg) if __name__ == '__main__':", "[-0.85, 1.45, 0., 0., 0., 0.707, 0.707]), ObjectMsg('counter0', 'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0.3,", "0., 0., 1.]), ObjectMsg('plate0', 'package://wecook_assets/data/objects/plate.urdf', [0.3, 0.075, 0.75, 0., 0.,", "[0.3, 0.075, 0.75, 0., 0., 0., 1.]), ObjectMsg('bowl0', 'package://wecook_assets/data/objects/bowl_green.urdf', [0.45,", "ObjectMsg('pasta0', 'package://wecook_assets/data/food/pasta.urdf', [0.45, 0.375, 0.757, 0., 0., 0., 1.])], [ContainingMsg(['plate0',", "'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0., 1.0, 0., 0., 0., 0.707, 0.707]), ObjectMsg('sink0', 'package://wecook_assets/data/furniture/sink_counter.urdf',", "from wecook.msg import ActionMsg, TaskMsg, SceneMsg, ObjectMsg, ContainingMsg, AgentMsg def", "TaskMsg, SceneMsg, ObjectMsg, ContainingMsg, AgentMsg def talker(): pub = rospy.Publisher('WeCookDispatch',", "-0.3, 0.75, 0., 0., 0., 1.]), ObjectMsg('knife0', 'package://wecook_assets/data/objects/knife_big.urdf', [0.215, -0.55,", "0., 0., 0., 1.]), ObjectMsg('oil0', 'package://wecook_assets/data/objects/olive_oil.urdf', [0., 1.15, 0.75, 0.,", "False) # sleeping 10 seconds to publish rospy.sleep(1) pub.publish(task_msg) if", "<filename>demos/chicken_pasta/chicken_pasta.py #!/usr/bin/env python3 import rospy from wecook.msg import ActionMsg, TaskMsg,", "# sleeping 10 seconds to publish rospy.sleep(1) pub.publish(task_msg) if __name__", "0., 0.707, 0.707]), ObjectMsg('counter0', 'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0.3, 0., 0., 0., 0.,", "0., 0., 1.]), ObjectMsg('pasta0', 'package://wecook_assets/data/food/pasta.urdf', [0.45, 0.375, 0.757, 0., 0.,", "0., 0., 0., 1.]), ObjectMsg('knife0', 'package://wecook_assets/data/objects/knife_big.urdf', [0.215, -0.55, 0.775, 0.,", "0.75, 0., 0., 0., 1.]), ObjectMsg('pot0', 'package://wecook_assets/data/objects/cooking_pot.urdf', [0.35, 1.1, 0.75,", "0.75, 0., 0., 0.707, 0.707]), ObjectMsg('pepper0', 'package://wecook_assets/data/objects/black_pepper.urdf', [0., 0.9, 0.75,", "0., 0., 0.707, 0.707]), ObjectMsg('shelf0', 'package://wecook_assets/data/furniture/bookcase.urdf', [0.3, -1.05, 0., 0.,", "0., 0., 0., 1.]), ObjectMsg('skillet0', 'package://wecook_assets/data/objects/skillet.urdf', [0.3, 0.7, 0.75, 0.,", "= TaskMsg(scene_msg, [ActionMsg(['p1'], 'cut', ['plate0'], 'knife0', ['lime0'])], [AgentMsg('p1', 'r', [0.,", "#!/usr/bin/env python3 import rospy from wecook.msg import ActionMsg, TaskMsg, SceneMsg,", "0., 0., 0., 1.]), ObjectMsg('lime0', 'package://wecook_assets/data/food/lime.urdf', [0.3, -0.3, 0.757, 0.,", "-1.05, 0., 0., 0., 0., 1.]), ObjectMsg('stove0', 'package://wecook_assets/data/objects/stove.urdf', [-0.35, 0.95,", "0.707, 0.707]), ObjectMsg('sink0', 'package://wecook_assets/data/furniture/sink_counter.urdf', [-1.3, 1.05, 0., 0., 0., 0.707,", "[0., 0., 0.75, 0., 0., 0., 0.])], \"\", \"\", \"follow\",", "0., 0.707, 0.707]), ObjectMsg('sink0', 'package://wecook_assets/data/furniture/sink_counter.urdf', [-1.3, 1.05, 0., 0., 0.,", "0.757, 0., 0., 0., 1.]), ObjectMsg('pasta0', 'package://wecook_assets/data/food/pasta.urdf', [0.45, 0.375, 0.757,", "'package://wecook_assets/data/food/pasta.urdf', [0.45, 0.375, 0.757, 0., 0., 0., 1.])], [ContainingMsg(['plate0', 'chicken0']),", "0.707]), ObjectMsg('chicken0', 'package://wecook_assets/data/food/chicken.urdf', [0.3, 0.075, 0.757, 0., 0., 0., 1.]),", "0., 0., 1.]), ObjectMsg('oil0', 'package://wecook_assets/data/objects/olive_oil.urdf', [0., 1.15, 0.75, 0., 0.,", "0., 0., 0., 1.]), ObjectMsg('wall1', 'package://wecook_assets/data/furniture/wall.urdf', [-0.85, 1.45, 0., 0.,", ".707]), ObjectMsg('cutting_board0', 'package://wecook_assets/data/objects/cutting_board.urdf', [0.3, -0.3, 0.75, 0., 0., 0., 1.]),", "wecook.msg import ActionMsg, TaskMsg, SceneMsg, ObjectMsg, ContainingMsg, AgentMsg def talker():", "def talker(): pub = rospy.Publisher('WeCookDispatch', TaskMsg, queue_size=10) rospy.init_node('wecook_chicken_pasta', anonymous=True) scene_msg", "'package://wecook_assets/data/objects/cutting_board.urdf', [0.3, -0.3, 0.75, 0., 0., 0., 1.]), ObjectMsg('knife0', 'package://wecook_assets/data/objects/knife_big.urdf',", "[-1.3, 1.05, 0., 0., 0., 0.707, 0.707]), ObjectMsg('shelf0', 'package://wecook_assets/data/furniture/bookcase.urdf', [0.3,", "0.75, 0., 0., 0.707, 0.707]), ObjectMsg('chicken0', 'package://wecook_assets/data/food/chicken.urdf', [0.3, 0.075, 0.757,", "\"\", \"\", \"follow\", \"RRTConnect\", False) # sleeping 10 seconds to", "1.]), ObjectMsg('knife0', 'package://wecook_assets/data/objects/knife_big.urdf', [0.215, -0.55, 0.775, 0., 0., 0., 1.]),", "ObjectMsg('counter0', 'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0.3, 0., 0., 0., 0., 0., 1.]), ObjectMsg('counter1',", "0.707]), ObjectMsg('sink0', 'package://wecook_assets/data/furniture/sink_counter.urdf', [-1.3, 1.05, 0., 0., 0., 0.707, 0.707]),", "python3 import rospy from wecook.msg import ActionMsg, TaskMsg, SceneMsg, ObjectMsg,", "1.]), ObjectMsg('wall1', 'package://wecook_assets/data/furniture/wall.urdf', [-0.85, 1.45, 0., 0., 0., 0.707, 0.707]),", "0.757, 0., 0., 0., 1.]), ObjectMsg('lime0', 'package://wecook_assets/data/food/lime.urdf', [0.3, -0.3, 0.757,", "0., 0., 0., 0.707, 0.707]), ObjectMsg('sink0', 'package://wecook_assets/data/furniture/sink_counter.urdf', [-1.3, 1.05, 0.,", "rospy from wecook.msg import ActionMsg, TaskMsg, SceneMsg, ObjectMsg, ContainingMsg, AgentMsg", "0., 0.707, 0.707]), ObjectMsg('pepper0', 'package://wecook_assets/data/objects/black_pepper.urdf', [0., 0.9, 0.75, 0., 0.,", "['lime0'])], [AgentMsg('p1', 'r', [0., 0., 0.75, 0., 0., 0., 0.])],", "0., 0., 0.])], \"\", \"\", \"follow\", \"RRTConnect\", False) # sleeping", "TaskMsg, queue_size=10) rospy.init_node('wecook_chicken_pasta', anonymous=True) scene_msg = SceneMsg([ObjectMsg('wall0', 'package://wecook_assets/data/furniture/wall.urdf', [0.75, 0.05,", "1.]), ObjectMsg('pasta0', 'package://wecook_assets/data/food/pasta.urdf', [0.45, 0.375, 0.757, 0., 0., 0., 1.])],", "pub = rospy.Publisher('WeCookDispatch', TaskMsg, queue_size=10) rospy.init_node('wecook_chicken_pasta', anonymous=True) scene_msg = SceneMsg([ObjectMsg('wall0',", "scene_msg = SceneMsg([ObjectMsg('wall0', 'package://wecook_assets/data/furniture/wall.urdf', [0.75, 0.05, 0., 0., 0., 0.,", "[0., 1.0, 0.75, 0., 0., 0.707, 0.707]), ObjectMsg('pepper0', 'package://wecook_assets/data/objects/black_pepper.urdf', [0.,", "ObjectMsg('sink0', 'package://wecook_assets/data/furniture/sink_counter.urdf', [-1.3, 1.05, 0., 0., 0., 0.707, 0.707]), ObjectMsg('shelf0',", "ObjectMsg('bowl1', 'package://wecook_assets/data/objects/bowl_green.urdf', [0.15, 0.375, 0.75, 0., 0., 0., 1.]), ObjectMsg('oil0',", "'chicken0']), ContainingMsg(['bowl0', 'pasta0'])]) task_msg = TaskMsg(scene_msg, [ActionMsg(['p1'], 'cut', ['plate0'], 'knife0',", "0., 0., 0., 0.707, 0.707]), ObjectMsg('shelf0', 'package://wecook_assets/data/furniture/bookcase.urdf', [0.3, -1.05, 0.,", "'package://wecook_assets/data/furniture/wall.urdf', [0.75, 0.05, 0., 0., 0., 0., 1.]), ObjectMsg('wall1', 'package://wecook_assets/data/furniture/wall.urdf',", "0.75, 0., 0., 0., 1.]), ObjectMsg('bowl0', 'package://wecook_assets/data/objects/bowl_green.urdf', [0.45, 0.375, 0.75,", "0.05, 0., 0., 0., 0., 1.]), ObjectMsg('wall1', 'package://wecook_assets/data/furniture/wall.urdf', [-0.85, 1.45,", "[0.3, 0., 0., 0., 0., 0., 1.]), ObjectMsg('counter1', 'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0.,", "[0.35, 1.1, 0.75, 0., 0., 0., 1.]), ObjectMsg('skillet0', 'package://wecook_assets/data/objects/skillet.urdf', [0.3,", "0., 0., 1.]), ObjectMsg('wall1', 'package://wecook_assets/data/furniture/wall.urdf', [-0.85, 1.45, 0., 0., 0.,", "0., 0., 0., 1.]), ObjectMsg('plate0', 'package://wecook_assets/data/objects/plate.urdf', [0.3, 0.075, 0.75, 0.,", "0.9, 0.75, 0., 0., 0.707, 0.707]), ObjectMsg('chicken0', 'package://wecook_assets/data/food/chicken.urdf', [0.3, 0.075,", "0., 0.75, 0., 0., 0., 0.])], \"\", \"\", \"follow\", \"RRTConnect\",", "1.]), ObjectMsg('oil0', 'package://wecook_assets/data/objects/olive_oil.urdf', [0., 1.15, 0.75, 0., 0., 0.707, 0.707]),", "0.075, 0.757, 0., 0., 0., 1.]), ObjectMsg('lime0', 'package://wecook_assets/data/food/lime.urdf', [0.3, -0.3,", "0.707, 0.707]), ObjectMsg('salt0', 'package://wecook_assets/data/objects/salt.urdf', [0., 1.0, 0.75, 0., 0., 0.707,", "'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0.3, 0., 0., 0., 0., 0., 1.]), ObjectMsg('counter1', 'package://wecook_assets/data/furniture/kitchen_counter.urdf',", "ObjectMsg('counter1', 'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0., 1.0, 0., 0., 0., 0.707, 0.707]), ObjectMsg('sink0',", "['plate0'], 'knife0', ['lime0'])], [AgentMsg('p1', 'r', [0., 0., 0.75, 0., 0.,", "'r', [0., 0., 0.75, 0., 0., 0., 0.])], \"\", \"\",", "[0., 0.9, 0.75, 0., 0., 0.707, 0.707]), ObjectMsg('chicken0', 'package://wecook_assets/data/food/chicken.urdf', [0.3,", "0., 1.]), ObjectMsg('lime0', 'package://wecook_assets/data/food/lime.urdf', [0.3, -0.3, 0.757, 0., 0., 0.,", "'package://wecook_assets/data/objects/cooking_pot.urdf', [0.35, 1.1, 0.75, 0., 0., 0., 1.]), ObjectMsg('skillet0', 'package://wecook_assets/data/objects/skillet.urdf',", "'package://wecook_assets/data/objects/knife_big.urdf', [0.215, -0.55, 0.775, 0., 0., 0., 1.]), ObjectMsg('plate0', 'package://wecook_assets/data/objects/plate.urdf',", "0.707]), ObjectMsg('counter0', 'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0.3, 0., 0., 0., 0., 0., 1.]),", "publish rospy.sleep(1) pub.publish(task_msg) if __name__ == '__main__': try: talker() except", "0., 0., 1.]), ObjectMsg('counter1', 'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0., 1.0, 0., 0., 0.,", "0.775, 0., 0., 0., 1.]), ObjectMsg('plate0', 'package://wecook_assets/data/objects/plate.urdf', [0.3, 0.075, 0.75,", "0.75, 0., 0., 0., 1.]), ObjectMsg('knife0', 'package://wecook_assets/data/objects/knife_big.urdf', [0.215, -0.55, 0.775,", "1.15, 0.75, 0., 0., 0.707, 0.707]), ObjectMsg('salt0', 'package://wecook_assets/data/objects/salt.urdf', [0., 1.0,", "ObjectMsg('chicken0', 'package://wecook_assets/data/food/chicken.urdf', [0.3, 0.075, 0.757, 0., 0., 0., 1.]), ObjectMsg('lime0',", "\"\", \"follow\", \"RRTConnect\", False) # sleeping 10 seconds to publish", "1.]), ObjectMsg('pot0', 'package://wecook_assets/data/objects/cooking_pot.urdf', [0.35, 1.1, 0.75, 0., 0., 0., 1.]),", "ObjectMsg('cutting_board0', 'package://wecook_assets/data/objects/cutting_board.urdf', [0.3, -0.3, 0.75, 0., 0., 0., 1.]), ObjectMsg('knife0',", "-0.3, 0.757, 0., 0., 0., 1.]), ObjectMsg('pasta0', 'package://wecook_assets/data/food/pasta.urdf', [0.45, 0.375,", "ContainingMsg(['bowl0', 'pasta0'])]) task_msg = TaskMsg(scene_msg, [ActionMsg(['p1'], 'cut', ['plate0'], 'knife0', ['lime0'])],", "[0.3, -0.3, 0.757, 0., 0., 0., 1.]), ObjectMsg('pasta0', 'package://wecook_assets/data/food/pasta.urdf', [0.45,", "task_msg = TaskMsg(scene_msg, [ActionMsg(['p1'], 'cut', ['plate0'], 'knife0', ['lime0'])], [AgentMsg('p1', 'r',", "0., 1.]), ObjectMsg('skillet0', 'package://wecook_assets/data/objects/skillet.urdf', [0.3, 0.7, 0.75, 0., 0., -0.707,", "0.707]), ObjectMsg('shelf0', 'package://wecook_assets/data/furniture/bookcase.urdf', [0.3, -1.05, 0., 0., 0., 0., 1.]),", "1.]), ObjectMsg('bowl1', 'package://wecook_assets/data/objects/bowl_green.urdf', [0.15, 0.375, 0.75, 0., 0., 0., 1.]),", "anonymous=True) scene_msg = SceneMsg([ObjectMsg('wall0', 'package://wecook_assets/data/furniture/wall.urdf', [0.75, 0.05, 0., 0., 0.,", "0., 0., 0., 1.]), ObjectMsg('pasta0', 'package://wecook_assets/data/food/pasta.urdf', [0.45, 0.375, 0.757, 0.,", "0.375, 0.757, 0., 0., 0., 1.])], [ContainingMsg(['plate0', 'chicken0']), ContainingMsg(['bowl0', 'pasta0'])])", "\"follow\", \"RRTConnect\", False) # sleeping 10 seconds to publish rospy.sleep(1)", "0., 0., 1.]), ObjectMsg('pot0', 'package://wecook_assets/data/objects/cooking_pot.urdf', [0.35, 1.1, 0.75, 0., 0.,", "queue_size=10) rospy.init_node('wecook_chicken_pasta', anonymous=True) scene_msg = SceneMsg([ObjectMsg('wall0', 'package://wecook_assets/data/furniture/wall.urdf', [0.75, 0.05, 0.,", "0., 0., 1.]), ObjectMsg('bowl0', 'package://wecook_assets/data/objects/bowl_green.urdf', [0.45, 0.375, 0.75, 0., 0.,", "0.75, 0., 0., 0.707, 0.707]), ObjectMsg('salt0', 'package://wecook_assets/data/objects/salt.urdf', [0., 1.0, 0.75,", "0.95, 0.75, 0., 0., 0., 1.]), ObjectMsg('pot0', 'package://wecook_assets/data/objects/cooking_pot.urdf', [0.35, 1.1,", "0.75, 0., 0., 0., 1.]), ObjectMsg('oil0', 'package://wecook_assets/data/objects/olive_oil.urdf', [0., 1.15, 0.75,", "0., 0., 1.])], [ContainingMsg(['plate0', 'chicken0']), ContainingMsg(['bowl0', 'pasta0'])]) task_msg = TaskMsg(scene_msg,", "0., 0., 0., 1.]), ObjectMsg('pot0', 'package://wecook_assets/data/objects/cooking_pot.urdf', [0.35, 1.1, 0.75, 0.,", "[-0.35, 0.95, 0.75, 0., 0., 0., 1.]), ObjectMsg('pot0', 'package://wecook_assets/data/objects/cooking_pot.urdf', [0.35,", "0., 0., 0., 1.]), ObjectMsg('counter1', 'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0., 1.0, 0., 0.,", "0., 0.707, 0.707]), ObjectMsg('salt0', 'package://wecook_assets/data/objects/salt.urdf', [0., 1.0, 0.75, 0., 0.,", "ObjectMsg('bowl0', 'package://wecook_assets/data/objects/bowl_green.urdf', [0.45, 0.375, 0.75, 0., 0., 0., 1.]), ObjectMsg('bowl1',", "1.45, 0., 0., 0., 0.707, 0.707]), ObjectMsg('counter0', 'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0.3, 0.,", "1.]), ObjectMsg('plate0', 'package://wecook_assets/data/objects/plate.urdf', [0.3, 0.075, 0.75, 0., 0., 0., 1.]),", "0., 0., 1.]), ObjectMsg('bowl1', 'package://wecook_assets/data/objects/bowl_green.urdf', [0.15, 0.375, 0.75, 0., 0.,", "1.05, 0., 0., 0., 0.707, 0.707]), ObjectMsg('shelf0', 'package://wecook_assets/data/furniture/bookcase.urdf', [0.3, -1.05,", "0.75, 0., 0., 0., 0.])], \"\", \"\", \"follow\", \"RRTConnect\", False)", "1.1, 0.75, 0., 0., 0., 1.]), ObjectMsg('skillet0', 'package://wecook_assets/data/objects/skillet.urdf', [0.3, 0.7,", "ObjectMsg('pepper0', 'package://wecook_assets/data/objects/black_pepper.urdf', [0., 0.9, 0.75, 0., 0., 0.707, 0.707]), ObjectMsg('chicken0',", "0.75, 0., 0., 0., 1.]), ObjectMsg('bowl1', 'package://wecook_assets/data/objects/bowl_green.urdf', [0.15, 0.375, 0.75,", "ObjectMsg('knife0', 'package://wecook_assets/data/objects/knife_big.urdf', [0.215, -0.55, 0.775, 0., 0., 0., 1.]), ObjectMsg('plate0',", "0.707, 0.707]), ObjectMsg('pepper0', 'package://wecook_assets/data/objects/black_pepper.urdf', [0., 0.9, 0.75, 0., 0., 0.707,", "[0., 1.15, 0.75, 0., 0., 0.707, 0.707]), ObjectMsg('salt0', 'package://wecook_assets/data/objects/salt.urdf', [0.,", "'package://wecook_assets/data/objects/bowl_green.urdf', [0.45, 0.375, 0.75, 0., 0., 0., 1.]), ObjectMsg('bowl1', 'package://wecook_assets/data/objects/bowl_green.urdf',", "TaskMsg(scene_msg, [ActionMsg(['p1'], 'cut', ['plate0'], 'knife0', ['lime0'])], [AgentMsg('p1', 'r', [0., 0.,", "0., 0., 1.]), ObjectMsg('knife0', 'package://wecook_assets/data/objects/knife_big.urdf', [0.215, -0.55, 0.775, 0., 0.,", "0., 1.]), ObjectMsg('stove0', 'package://wecook_assets/data/objects/stove.urdf', [-0.35, 0.95, 0.75, 0., 0., 0.,", "0.707, 0.707]), ObjectMsg('counter0', 'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0.3, 0., 0., 0., 0., 0.,", "ObjectMsg('shelf0', 'package://wecook_assets/data/furniture/bookcase.urdf', [0.3, -1.05, 0., 0., 0., 0., 1.]), ObjectMsg('stove0',", "sleeping 10 seconds to publish rospy.sleep(1) pub.publish(task_msg) if __name__ ==", "rospy.init_node('wecook_chicken_pasta', anonymous=True) scene_msg = SceneMsg([ObjectMsg('wall0', 'package://wecook_assets/data/furniture/wall.urdf', [0.75, 0.05, 0., 0.,", "= rospy.Publisher('WeCookDispatch', TaskMsg, queue_size=10) rospy.init_node('wecook_chicken_pasta', anonymous=True) scene_msg = SceneMsg([ObjectMsg('wall0', 'package://wecook_assets/data/furniture/wall.urdf',", "0., 0., 0.707, 0.707]), ObjectMsg('salt0', 'package://wecook_assets/data/objects/salt.urdf', [0., 1.0, 0.75, 0.,", "0., 0., 1.]), ObjectMsg('lime0', 'package://wecook_assets/data/food/lime.urdf', [0.3, -0.3, 0.757, 0., 0.,", "0.375, 0.75, 0., 0., 0., 1.]), ObjectMsg('oil0', 'package://wecook_assets/data/objects/olive_oil.urdf', [0., 1.15,", "ObjectMsg, ContainingMsg, AgentMsg def talker(): pub = rospy.Publisher('WeCookDispatch', TaskMsg, queue_size=10)", "0.7, 0.75, 0., 0., -0.707, .707]), ObjectMsg('cutting_board0', 'package://wecook_assets/data/objects/cutting_board.urdf', [0.3, -0.3,", "0., 0.707, 0.707]), ObjectMsg('shelf0', 'package://wecook_assets/data/furniture/bookcase.urdf', [0.3, -1.05, 0., 0., 0.,", "rospy.Publisher('WeCookDispatch', TaskMsg, queue_size=10) rospy.init_node('wecook_chicken_pasta', anonymous=True) scene_msg = SceneMsg([ObjectMsg('wall0', 'package://wecook_assets/data/furniture/wall.urdf', [0.75,", "0.75, 0., 0., -0.707, .707]), ObjectMsg('cutting_board0', 'package://wecook_assets/data/objects/cutting_board.urdf', [0.3, -0.3, 0.75,", "'package://wecook_assets/data/food/chicken.urdf', [0.3, 0.075, 0.757, 0., 0., 0., 1.]), ObjectMsg('lime0', 'package://wecook_assets/data/food/lime.urdf',", "0., 0., 0.707, 0.707]), ObjectMsg('counter0', 'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0.3, 0., 0., 0.,", "'knife0', ['lime0'])], [AgentMsg('p1', 'r', [0., 0., 0.75, 0., 0., 0.,", "1.])], [ContainingMsg(['plate0', 'chicken0']), ContainingMsg(['bowl0', 'pasta0'])]) task_msg = TaskMsg(scene_msg, [ActionMsg(['p1'], 'cut',", "'package://wecook_assets/data/objects/salt.urdf', [0., 1.0, 0.75, 0., 0., 0.707, 0.707]), ObjectMsg('pepper0', 'package://wecook_assets/data/objects/black_pepper.urdf',", "0.707]), ObjectMsg('salt0', 'package://wecook_assets/data/objects/salt.urdf', [0., 1.0, 0.75, 0., 0., 0.707, 0.707]),", "to publish rospy.sleep(1) pub.publish(task_msg) if __name__ == '__main__': try: talker()", "[0.3, 0.075, 0.757, 0., 0., 0., 1.]), ObjectMsg('lime0', 'package://wecook_assets/data/food/lime.urdf', [0.3,", "0., 0., 0., 0., 1.]), ObjectMsg('stove0', 'package://wecook_assets/data/objects/stove.urdf', [-0.35, 0.95, 0.75,", "= SceneMsg([ObjectMsg('wall0', 'package://wecook_assets/data/furniture/wall.urdf', [0.75, 0.05, 0., 0., 0., 0., 1.]),", "0.])], \"\", \"\", \"follow\", \"RRTConnect\", False) # sleeping 10 seconds", "ActionMsg, TaskMsg, SceneMsg, ObjectMsg, ContainingMsg, AgentMsg def talker(): pub =", "seconds to publish rospy.sleep(1) pub.publish(task_msg) if __name__ == '__main__': try:", "1.]), ObjectMsg('stove0', 'package://wecook_assets/data/objects/stove.urdf', [-0.35, 0.95, 0.75, 0., 0., 0., 1.]),", "[0.3, -1.05, 0., 0., 0., 0., 1.]), ObjectMsg('stove0', 'package://wecook_assets/data/objects/stove.urdf', [-0.35,", "import ActionMsg, TaskMsg, SceneMsg, ObjectMsg, ContainingMsg, AgentMsg def talker(): pub", "0., 0., -0.707, .707]), ObjectMsg('cutting_board0', 'package://wecook_assets/data/objects/cutting_board.urdf', [0.3, -0.3, 0.75, 0.,", "0., 1.]), ObjectMsg('counter1', 'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0., 1.0, 0., 0., 0., 0.707,", "'package://wecook_assets/data/food/lime.urdf', [0.3, -0.3, 0.757, 0., 0., 0., 1.]), ObjectMsg('pasta0', 'package://wecook_assets/data/food/pasta.urdf',", "0., -0.707, .707]), ObjectMsg('cutting_board0', 'package://wecook_assets/data/objects/cutting_board.urdf', [0.3, -0.3, 0.75, 0., 0.,", "'package://wecook_assets/data/objects/plate.urdf', [0.3, 0.075, 0.75, 0., 0., 0., 1.]), ObjectMsg('bowl0', 'package://wecook_assets/data/objects/bowl_green.urdf',", "1.0, 0.75, 0., 0., 0.707, 0.707]), ObjectMsg('pepper0', 'package://wecook_assets/data/objects/black_pepper.urdf', [0., 0.9,", "0., 0., 0., 0., 1.]), ObjectMsg('counter1', 'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0., 1.0, 0.,", "0.075, 0.75, 0., 0., 0., 1.]), ObjectMsg('bowl0', 'package://wecook_assets/data/objects/bowl_green.urdf', [0.45, 0.375,", "[0.3, -0.3, 0.75, 0., 0., 0., 1.]), ObjectMsg('knife0', 'package://wecook_assets/data/objects/knife_big.urdf', [0.215,", "1.]), ObjectMsg('skillet0', 'package://wecook_assets/data/objects/skillet.urdf', [0.3, 0.7, 0.75, 0., 0., -0.707, .707]),", "0., 0.707, 0.707]), ObjectMsg('chicken0', 'package://wecook_assets/data/food/chicken.urdf', [0.3, 0.075, 0.757, 0., 0.,", "0., 0., 0., 0., 0., 1.]), ObjectMsg('counter1', 'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0., 1.0,", "0., 0., 1.]), ObjectMsg('skillet0', 'package://wecook_assets/data/objects/skillet.urdf', [0.3, 0.7, 0.75, 0., 0.,", "[ContainingMsg(['plate0', 'chicken0']), ContainingMsg(['bowl0', 'pasta0'])]) task_msg = TaskMsg(scene_msg, [ActionMsg(['p1'], 'cut', ['plate0'],", "0., 0., 0., 0.])], \"\", \"\", \"follow\", \"RRTConnect\", False) #", "import rospy from wecook.msg import ActionMsg, TaskMsg, SceneMsg, ObjectMsg, ContainingMsg,", "[0.45, 0.375, 0.757, 0., 0., 0., 1.])], [ContainingMsg(['plate0', 'chicken0']), ContainingMsg(['bowl0',", "'package://wecook_assets/data/furniture/wall.urdf', [-0.85, 1.45, 0., 0., 0., 0.707, 0.707]), ObjectMsg('counter0', 'package://wecook_assets/data/furniture/kitchen_counter.urdf',", "ContainingMsg, AgentMsg def talker(): pub = rospy.Publisher('WeCookDispatch', TaskMsg, queue_size=10) rospy.init_node('wecook_chicken_pasta',", "ObjectMsg('stove0', 'package://wecook_assets/data/objects/stove.urdf', [-0.35, 0.95, 0.75, 0., 0., 0., 1.]), ObjectMsg('pot0',", "0., 0., 0., 1.])], [ContainingMsg(['plate0', 'chicken0']), ContainingMsg(['bowl0', 'pasta0'])]) task_msg =", "ObjectMsg('oil0', 'package://wecook_assets/data/objects/olive_oil.urdf', [0., 1.15, 0.75, 0., 0., 0.707, 0.707]), ObjectMsg('salt0',", "0., 1.])], [ContainingMsg(['plate0', 'chicken0']), ContainingMsg(['bowl0', 'pasta0'])]) task_msg = TaskMsg(scene_msg, [ActionMsg(['p1'],", "'package://wecook_assets/data/objects/stove.urdf', [-0.35, 0.95, 0.75, 0., 0., 0., 1.]), ObjectMsg('pot0', 'package://wecook_assets/data/objects/cooking_pot.urdf',", "SceneMsg, ObjectMsg, ContainingMsg, AgentMsg def talker(): pub = rospy.Publisher('WeCookDispatch', TaskMsg,", "0., 0., 0., 1.]), ObjectMsg('bowl0', 'package://wecook_assets/data/objects/bowl_green.urdf', [0.45, 0.375, 0.75, 0.,", "0., 1.]), ObjectMsg('bowl1', 'package://wecook_assets/data/objects/bowl_green.urdf', [0.15, 0.375, 0.75, 0., 0., 0.,", "[0.3, 0.7, 0.75, 0., 0., -0.707, .707]), ObjectMsg('cutting_board0', 'package://wecook_assets/data/objects/cutting_board.urdf', [0.3,", "'package://wecook_assets/data/furniture/sink_counter.urdf', [-1.3, 1.05, 0., 0., 0., 0.707, 0.707]), ObjectMsg('shelf0', 'package://wecook_assets/data/furniture/bookcase.urdf',", "0., 0.])], \"\", \"\", \"follow\", \"RRTConnect\", False) # sleeping 10", "'package://wecook_assets/data/objects/skillet.urdf', [0.3, 0.7, 0.75, 0., 0., -0.707, .707]), ObjectMsg('cutting_board0', 'package://wecook_assets/data/objects/cutting_board.urdf',", "ObjectMsg('skillet0', 'package://wecook_assets/data/objects/skillet.urdf', [0.3, 0.7, 0.75, 0., 0., -0.707, .707]), ObjectMsg('cutting_board0',", "0., 1.]), ObjectMsg('wall1', 'package://wecook_assets/data/furniture/wall.urdf', [-0.85, 1.45, 0., 0., 0., 0.707,", "0.707, 0.707]), ObjectMsg('shelf0', 'package://wecook_assets/data/furniture/bookcase.urdf', [0.3, -1.05, 0., 0., 0., 0.,", "-0.55, 0.775, 0., 0., 0., 1.]), ObjectMsg('plate0', 'package://wecook_assets/data/objects/plate.urdf', [0.3, 0.075,", "0., 0., 0., 0.707, 0.707]), ObjectMsg('counter0', 'package://wecook_assets/data/furniture/kitchen_counter.urdf', [0.3, 0., 0.,", "1.0, 0., 0., 0., 0.707, 0.707]), ObjectMsg('sink0', 'package://wecook_assets/data/furniture/sink_counter.urdf', [-1.3, 1.05,", "0., 0., 0.707, 0.707]), ObjectMsg('sink0', 'package://wecook_assets/data/furniture/sink_counter.urdf', [-1.3, 1.05, 0., 0.,", "0.757, 0., 0., 0., 1.])], [ContainingMsg(['plate0', 'chicken0']), ContainingMsg(['bowl0', 'pasta0'])]) task_msg", "[0.45, 0.375, 0.75, 0., 0., 0., 1.]), ObjectMsg('bowl1', 'package://wecook_assets/data/objects/bowl_green.urdf', [0.15,", "AgentMsg def talker(): pub = rospy.Publisher('WeCookDispatch', TaskMsg, queue_size=10) rospy.init_node('wecook_chicken_pasta', anonymous=True)", "[0.75, 0.05, 0., 0., 0., 0., 1.]), ObjectMsg('wall1', 'package://wecook_assets/data/furniture/wall.urdf', [-0.85,", "[AgentMsg('p1', 'r', [0., 0., 0.75, 0., 0., 0., 0.])], \"\",", "[ActionMsg(['p1'], 'cut', ['plate0'], 'knife0', ['lime0'])], [AgentMsg('p1', 'r', [0., 0., 0.75,", "0., 1.]), ObjectMsg('plate0', 'package://wecook_assets/data/objects/plate.urdf', [0.3, 0.075, 0.75, 0., 0., 0.,", "0., 0., 1.]), ObjectMsg('stove0', 'package://wecook_assets/data/objects/stove.urdf', [-0.35, 0.95, 0.75, 0., 0.,", "0., 1.]), ObjectMsg('bowl0', 'package://wecook_assets/data/objects/bowl_green.urdf', [0.45, 0.375, 0.75, 0., 0., 0.,", "'package://wecook_assets/data/objects/black_pepper.urdf', [0., 0.9, 0.75, 0., 0., 0.707, 0.707]), ObjectMsg('chicken0', 'package://wecook_assets/data/food/chicken.urdf',", "0.75, 0., 0., 0., 1.]), ObjectMsg('skillet0', 'package://wecook_assets/data/objects/skillet.urdf', [0.3, 0.7, 0.75,", "0.707]), ObjectMsg('pepper0', 'package://wecook_assets/data/objects/black_pepper.urdf', [0., 0.9, 0.75, 0., 0., 0.707, 0.707]),", "0., 1.]), ObjectMsg('pasta0', 'package://wecook_assets/data/food/pasta.urdf', [0.45, 0.375, 0.757, 0., 0., 0.,", "rospy.sleep(1) pub.publish(task_msg) if __name__ == '__main__': try: talker() except rospy.ROSInterruptException:", "ObjectMsg('lime0', 'package://wecook_assets/data/food/lime.urdf', [0.3, -0.3, 0.757, 0., 0., 0., 1.]), ObjectMsg('pasta0',", "pub.publish(task_msg) if __name__ == '__main__': try: talker() except rospy.ROSInterruptException: pass", "-0.707, .707]), ObjectMsg('cutting_board0', 'package://wecook_assets/data/objects/cutting_board.urdf', [0.3, -0.3, 0.75, 0., 0., 0.,", "'package://wecook_assets/data/furniture/bookcase.urdf', [0.3, -1.05, 0., 0., 0., 0., 1.]), ObjectMsg('stove0', 'package://wecook_assets/data/objects/stove.urdf',", "ObjectMsg('plate0', 'package://wecook_assets/data/objects/plate.urdf', [0.3, 0.075, 0.75, 0., 0., 0., 1.]), ObjectMsg('bowl0',", "\"RRTConnect\", False) # sleeping 10 seconds to publish rospy.sleep(1) pub.publish(task_msg)", "SceneMsg([ObjectMsg('wall0', 'package://wecook_assets/data/furniture/wall.urdf', [0.75, 0.05, 0., 0., 0., 0., 1.]), ObjectMsg('wall1',", "talker(): pub = rospy.Publisher('WeCookDispatch', TaskMsg, queue_size=10) rospy.init_node('wecook_chicken_pasta', anonymous=True) scene_msg =", "[0., 1.0, 0., 0., 0., 0.707, 0.707]), ObjectMsg('sink0', 'package://wecook_assets/data/furniture/sink_counter.urdf', [-1.3,", "0., 1.]), ObjectMsg('pot0', 'package://wecook_assets/data/objects/cooking_pot.urdf', [0.35, 1.1, 0.75, 0., 0., 0.,", "0.375, 0.75, 0., 0., 0., 1.]), ObjectMsg('bowl1', 'package://wecook_assets/data/objects/bowl_green.urdf', [0.15, 0.375,", "0., 0., 0., 1.]), ObjectMsg('bowl1', 'package://wecook_assets/data/objects/bowl_green.urdf', [0.15, 0.375, 0.75, 0.,", "0., 1.]), ObjectMsg('oil0', 'package://wecook_assets/data/objects/olive_oil.urdf', [0., 1.15, 0.75, 0., 0., 0.707,", "0., 0., 0.707, 0.707]), ObjectMsg('pepper0', 'package://wecook_assets/data/objects/black_pepper.urdf', [0., 0.9, 0.75, 0.,", "0., 0., 0.707, 0.707]), ObjectMsg('chicken0', 'package://wecook_assets/data/food/chicken.urdf', [0.3, 0.075, 0.757, 0.,", "ObjectMsg('wall1', 'package://wecook_assets/data/furniture/wall.urdf', [-0.85, 1.45, 0., 0., 0., 0.707, 0.707]), ObjectMsg('counter0',", "'package://wecook_assets/data/objects/bowl_green.urdf', [0.15, 0.375, 0.75, 0., 0., 0., 1.]), ObjectMsg('oil0', 'package://wecook_assets/data/objects/olive_oil.urdf',", "'pasta0'])]) task_msg = TaskMsg(scene_msg, [ActionMsg(['p1'], 'cut', ['plate0'], 'knife0', ['lime0'])], [AgentMsg('p1',", "0., 0., 0., 0., 1.]), ObjectMsg('wall1', 'package://wecook_assets/data/furniture/wall.urdf', [-0.85, 1.45, 0.," ]
[ "Heartbeat(SubsystemBase): def __init__(self, owner, core, rpc, pubsub, heartbeat_autostart, heartbeat_period): self.owner", "self.pubsub = weakref.ref(pubsub) self.autostart = heartbeat_autostart self.period = heartbeat_period self.enabled", "2.0 (the \"License\"); # you may not use this file", "# Copyright 2017, Battelle Memorial Institute. # # Licensed under", "= 'reStructuredText' __version__ = '1.0' class Heartbeat(SubsystemBase): def __init__(self, owner,", "headers = {TIMESTAMP: format_timestamp(get_aware_utc_now())} message = self.owner.vip.health.get_status_value() try: self.pubsub().publish('pubsub', topic,", "not self.enabled: self.scheduled = self.core().schedule(periodic(self.period), self.publish) self.enabled = True def", "heartbeat_period self.enabled = False self.connect_error = False def onsetup(sender, **kwargs):", "\"\"\" __docformat__ = 'reStructuredText' __version__ = '1.0' class Heartbeat(SubsystemBase): def", "self.connect_error = False def onsetup(sender, **kwargs): rpc.export(self.start, 'heartbeat.start') rpc.export(self.start_with_period, 'heartbeat.start_with_period')", "Set heartbeat period. :param period: Time in seconds between publishes.", "Government nor the # United States Department of Energy, nor", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "..errors import Unreachable, VIPError \"\"\"The heartbeat subsystem adds an optional", "makes any warranty, express or # implied, or assumes any", "the License. # # This material was prepared as an", "# favoring by the United States Government or any agency", "UNITED STATES DEPARTMENT OF ENERGY # under Contract DE-AC05-76RL01830 #", "method Set period and start heartbeat. :param period: Time in", "be immediately sending the heartbeat to the message bus. \"\"\"", "STATES DEPARTMENT OF ENERGY # under Contract DE-AC05-76RL01830 # }}}", "= False def onsetup(sender, **kwargs): rpc.export(self.start, 'heartbeat.start') rpc.export(self.start_with_period, 'heartbeat.start_with_period') rpc.export(self.stop,", "sts=4 et: # # Copyright 2017, Battelle Memorial Institute. #", "the United States Government nor the # United States Department", "Time in seconds between publishes. \"\"\" self.set_period(period) self.start() def reconnect(self,", "# United States Department of Energy, nor Battelle, nor any", "nor any of their # employees, nor any jurisdiction or", "start heartbeat. :param period: Time in seconds between publishes. \"\"\"", "use this file except in compliance with the License. #", "period: Time in seconds between publishes. \"\"\" if self.enabled: self.stop()", "has cooperated in the # development of these materials, makes", "and opinions of authors expressed # herein do not necessarily", "or # Battelle Memorial Institute. The views and opinions of", "accuracy, # completeness, or usefulness or any information, apparatus, product,", "= self.owner.vip.health.get_status_value() try: self.pubsub().publish('pubsub', topic, headers, message) except Unreachable as", "\"\"\"RPC method Starts an agent's heartbeat. \"\"\" if not self.enabled:", "United States Government or any agency thereof. # # PACIFIC", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "self.stop() self.period = period self.start() else: self.period = period def", "States Government or any agency thereof. # # PACIFIC NORTHWEST", "seconds between publishes. \"\"\" if self.enabled: self.stop() self.period = period", "License. # You may obtain a copy of the License", "datetime from .base import SubsystemBase from volttron.platform.messaging.headers import TIMESTAMP from", "periodic from ..errors import Unreachable, VIPError \"\"\"The heartbeat subsystem adds", "Energy, nor Battelle, nor any of their # employees, nor", "under the License is distributed on an \"AS IS\" BASIS,", "of these materials, makes any warranty, express or # implied,", "License for the specific language governing permissions and # limitations", "does not necessarily constitute or imply its endorsement, recommendation, or", "self) core.onstart.connect(onstart, self) core.onconnected.connect(self.reconnect) def start(self): \"\"\"RPC method Starts an", "ENERGY # under Contract DE-AC05-76RL01830 # }}} import os import", "self.enabled = True def start_with_period(self, period): \"\"\"RPC method Set period", "not have been # set yet if the start hasn't", "work sponsored by an agency of # the United States", "rpc.export(self.set_period, 'heartbeat.set_period') def onstart(sender, **kwargs): if self.autostart: self.start() core.onsetup.connect(onsetup, self)", "warranty, express or # implied, or assumes any legal liability", "format_timestamp) from volttron.platform.scheduling import periodic from ..errors import Unreachable, VIPError", "(get_aware_utc_now, format_timestamp) from volttron.platform.scheduling import periodic from ..errors import Unreachable,", "or usefulness or any information, apparatus, product, # software, or", "core.onsetup.connect(onsetup, self) core.onstart.connect(onstart, self) core.onconnected.connect(self.reconnect) def start(self): \"\"\"RPC method Starts", "import Unreachable, VIPError \"\"\"The heartbeat subsystem adds an optional periodic", "self.enabled: self.scheduled = self.core().schedule(periodic(self.period), self.publish) self.enabled = True def start_with_period(self,", "# -*- coding: utf-8 -*- {{{ # vim: set fenc=utf-8", "material was prepared as an account of work sponsored by", "DE-AC05-76RL01830 # }}} import os import weakref from datetime import", "product, # software, or process disclosed, or represents that its", "or assumes any legal liability or responsibility for the accuracy,", "was prepared as an account of work sponsored by an", "States Government nor the # United States Department of Energy,", "= heartbeat_period self.enabled = False self.connect_error = False def onsetup(sender,", "Memorial Institute. The views and opinions of authors expressed #", "infringe # privately owned rights. Reference herein to any specific", "'heartbeat.start') rpc.export(self.start_with_period, 'heartbeat.start_with_period') rpc.export(self.stop, 'heartbeat.stop') rpc.export(self.restart, 'heartbeat.restart') rpc.export(self.set_period, 'heartbeat.set_period') def", "self.enabled: # Trap the fact that scheduled may not have", "completeness, or usefulness or any information, apparatus, product, # software,", "volttron.platform.agent.utils import (get_aware_utc_now, format_timestamp) from volttron.platform.scheduling import periodic from ..errors", "in compliance with the License. # You may obtain a", "necessarily constitute or imply its endorsement, recommendation, or # favoring", "the # United States Government or any agency thereof. #", "self.autostart = heartbeat_autostart self.period = heartbeat_period self.enabled = False self.connect_error", "Trap the fact that scheduled may not have been #", "software # distributed under the License is distributed on an", "necessarily state or reflect those of the # United States", "The heartbeat will be immediately sending the heartbeat to the", "DEPARTMENT OF ENERGY # under Contract DE-AC05-76RL01830 # }}} import", "Unreachable, VIPError \"\"\"The heartbeat subsystem adds an optional periodic publish", "Restart the heartbeat with the current period. The heartbeat will", "publish(self): topic = 'heartbeat/' + self.core().identity headers = {TIMESTAMP: format_timestamp(get_aware_utc_now())}", "the fact that scheduled may not have been # set", "express or # implied, or assumes any legal liability or", "if self.enabled: self.stop() self.period = period self.start() else: self.period =", "heartbeat period. :param period: Time in seconds between publishes. \"\"\"", "Heartbeats can be started with agents and toggled on and", "may not have been # set yet if the start", "and start heartbeat. :param period: Time in seconds between publishes.", "the accuracy, # completeness, or usefulness or any information, apparatus,", "if self.connect_error: self.restart() self.connect_error = False def stop(self): \"\"\"RPC method", "usefulness or any information, apparatus, product, # software, or process", "between publishes. \"\"\" self.set_period(period) self.start() def reconnect(self, sender, **kwargs): if", "= True def start_with_period(self, period): \"\"\"RPC method Set period and", "Memorial Institute. # # Licensed under the Apache License, Version", "Copyright 2017, Battelle Memorial Institute. # # Licensed under the", "heartbeat subsystem adds an optional periodic publish to all agents.", "rpc.export(self.restart, 'heartbeat.restart') rpc.export(self.set_period, 'heartbeat.set_period') def onstart(sender, **kwargs): if self.autostart: self.start()", "an agent's heartbeat. \"\"\" if self.enabled: # Trap the fact", "def stop(self): \"\"\"RPC method Stop an agent's heartbeat. \"\"\" if", "core.onstart.connect(onstart, self) core.onconnected.connect(self.reconnect) def start(self): \"\"\"RPC method Starts an agent's", "bus. \"\"\" self.stop() self.start() def set_period(self, period): \"\"\"RPC method Set", "be started with agents and toggled on and off at", "'heartbeat.set_period') def onstart(sender, **kwargs): if self.autostart: self.start() core.onsetup.connect(onsetup, self) core.onstart.connect(onstart,", "pubsub, heartbeat_autostart, heartbeat_period): self.owner = owner self.core = weakref.ref(core) self.pubsub", "publishes. \"\"\" self.set_period(period) self.start() def reconnect(self, sender, **kwargs): if self.connect_error:", "periodic publish to all agents. Heartbeats can be started with", "# # This material was prepared as an account of", "recommendation, or # favoring by the United States Government or", "pass self.enabled = False def restart(self): \"\"\"RPC method Restart the", "States Government. Neither the United States Government nor the #", "not necessarily constitute or imply its endorsement, recommendation, or #", "ts=4 sts=4 et: # # Copyright 2017, Battelle Memorial Institute.", "OF ANY KIND, either express or implied. # See the", "the United States Government or any agency thereof, or #", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "set_period(self, period): \"\"\"RPC method Set heartbeat period. :param period: Time", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "or service by trade name, trademark, manufacturer, or otherwise #", "\"\"\"RPC method Restart the heartbeat with the current period. The", "= {TIMESTAMP: format_timestamp(get_aware_utc_now())} message = self.owner.vip.health.get_status_value() try: self.pubsub().publish('pubsub', topic, headers,", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "agency of # the United States Government. Neither the United", "-*- {{{ # vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4", "to in writing, software # distributed under the License is", "any jurisdiction or organization that has cooperated in the #", "# set yet if the start hasn't been called. try:", "fenc=utf-8 ft=python sw=4 ts=4 sts=4 et: # # Copyright 2017,", "Battelle Memorial Institute. # # Licensed under the Apache License,", "def set_period(self, period): \"\"\"RPC method Set heartbeat period. :param period:", "# See the License for the specific language governing permissions", "from volttron.platform.messaging.headers import TIMESTAMP from volttron.platform.agent.utils import (get_aware_utc_now, format_timestamp) from", "that its use would not infringe # privately owned rights.", "language governing permissions and # limitations under the License. #", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "an agency of # the United States Government. Neither the", "= self.core().schedule(periodic(self.period), self.publish) self.enabled = True def start_with_period(self, period): \"\"\"RPC", "seconds between publishes. \"\"\" self.set_period(period) self.start() def reconnect(self, sender, **kwargs):", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "do not necessarily state or reflect those of the #", "with the License. # You may obtain a copy of", "commercial product, # process, or service by trade name, trademark,", "Time in seconds between publishes. \"\"\" if self.enabled: self.stop() self.period", "# herein do not necessarily state or reflect those of", "volttron.platform.scheduling import periodic from ..errors import Unreachable, VIPError \"\"\"The heartbeat", "or any information, apparatus, product, # software, or process disclosed,", "all agents. Heartbeats can be started with agents and toggled", "by an agency of # the United States Government. Neither", "compliance with the License. # You may obtain a copy", "that has cooperated in the # development of these materials,", "agreed to in writing, software # distributed under the License", "any information, apparatus, product, # software, or process disclosed, or", "if self.enabled: # Trap the fact that scheduled may not", "distributed under the License is distributed on an \"AS IS\"", "by the United States Government or any agency thereof, or", "an account of work sponsored by an agency of #", "agent's heartbeat. \"\"\" if not self.enabled: self.scheduled = self.core().schedule(periodic(self.period), self.publish)", "+ self.core().identity headers = {TIMESTAMP: format_timestamp(get_aware_utc_now())} message = self.owner.vip.health.get_status_value() try:", "immediately sending the heartbeat to the message bus. \"\"\" self.stop()", "period: Time in seconds between publishes. \"\"\" self.set_period(period) self.start() def", "in seconds between publishes. \"\"\" self.set_period(period) self.start() def reconnect(self, sender,", "self.core().identity headers = {TIMESTAMP: format_timestamp(get_aware_utc_now())} message = self.owner.vip.health.get_status_value() try: self.pubsub().publish('pubsub',", "legal liability or responsibility for the accuracy, # completeness, or", "restart(self): \"\"\"RPC method Restart the heartbeat with the current period.", "except AttributeError: pass self.enabled = False def restart(self): \"\"\"RPC method", "express or implied. # See the License for the specific", "herein to any specific commercial product, # process, or service", "except in compliance with the License. # You may obtain", "and off at runtime. \"\"\" __docformat__ = 'reStructuredText' __version__ =", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "SubsystemBase from volttron.platform.messaging.headers import TIMESTAMP from volttron.platform.agent.utils import (get_aware_utc_now, format_timestamp)", "not use this file except in compliance with the License.", "Contract DE-AC05-76RL01830 # }}} import os import weakref from datetime", "agent's heartbeat. \"\"\" if self.enabled: # Trap the fact that", "thereof, or # Battelle Memorial Institute. The views and opinions", "writing, software # distributed under the License is distributed on", "for the UNITED STATES DEPARTMENT OF ENERGY # under Contract", "self.period = period self.start() else: self.period = period def publish(self):", "you may not use this file except in compliance with", "try: self.pubsub().publish('pubsub', topic, headers, message) except Unreachable as exc: self.connect_error", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "responsibility for the accuracy, # completeness, or usefulness or any", "\"\"\"RPC method Stop an agent's heartbeat. \"\"\" if self.enabled: #", "__version__ = '1.0' class Heartbeat(SubsystemBase): def __init__(self, owner, core, rpc,", "self.restart() self.connect_error = False def stop(self): \"\"\"RPC method Stop an", "Institute. The views and opinions of authors expressed # herein", "trademark, manufacturer, or otherwise # does not necessarily constitute or", "any agency thereof, or # Battelle Memorial Institute. The views", "self.enabled = False self.connect_error = False def onsetup(sender, **kwargs): rpc.export(self.start,", "an agent's heartbeat. \"\"\" if not self.enabled: self.scheduled = self.core().schedule(periodic(self.period),", "core.onconnected.connect(self.reconnect) def start(self): \"\"\"RPC method Starts an agent's heartbeat. \"\"\"", "of work sponsored by an agency of # the United", ":param period: Time in seconds between publishes. \"\"\" if self.enabled:", "self.pubsub().publish('pubsub', topic, headers, message) except Unreachable as exc: self.connect_error =", "import datetime from .base import SubsystemBase from volttron.platform.messaging.headers import TIMESTAMP", "CONDITIONS OF ANY KIND, either express or implied. # See", "any warranty, express or # implied, or assumes any legal", "of Energy, nor Battelle, nor any of their # employees,", "owned rights. Reference herein to any specific commercial product, #", "self.set_period(period) self.start() def reconnect(self, sender, **kwargs): if self.connect_error: self.restart() self.connect_error", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "\"\"\"RPC method Set heartbeat period. :param period: Time in seconds", "United States Government. Neither the United States Government nor the", "apparatus, product, # software, or process disclosed, or represents that", "from volttron.platform.scheduling import periodic from ..errors import Unreachable, VIPError \"\"\"The", "VIPError \"\"\"The heartbeat subsystem adds an optional periodic publish to", "= period def publish(self): topic = 'heartbeat/' + self.core().identity headers", ":param period: Time in seconds between publishes. \"\"\" self.set_period(period) self.start()", "False def restart(self): \"\"\"RPC method Restart the heartbeat with the", "manufacturer, or otherwise # does not necessarily constitute or imply", "and toggled on and off at runtime. \"\"\" __docformat__ =", "publish to all agents. Heartbeats can be started with agents", "def onsetup(sender, **kwargs): rpc.export(self.start, 'heartbeat.start') rpc.export(self.start_with_period, 'heartbeat.start_with_period') rpc.export(self.stop, 'heartbeat.stop') rpc.export(self.restart,", "self) core.onconnected.connect(self.reconnect) def start(self): \"\"\"RPC method Starts an agent's heartbeat.", "nor any jurisdiction or organization that has cooperated in the", "endorsement, recommendation, or # favoring by the United States Government", "period. The heartbeat will be immediately sending the heartbeat to", "if self.autostart: self.start() core.onsetup.connect(onsetup, self) core.onstart.connect(onstart, self) core.onconnected.connect(self.reconnect) def start(self):", "not infringe # privately owned rights. Reference herein to any", "Set period and start heartbeat. :param period: Time in seconds", "product, # process, or service by trade name, trademark, manufacturer,", "or any agency thereof. # # PACIFIC NORTHWEST NATIONAL LABORATORY", "# software, or process disclosed, or represents that its use", "agents and toggled on and off at runtime. \"\"\" __docformat__", "# completeness, or usefulness or any information, apparatus, product, #", "# United States Government or any agency thereof. # #", "self.publish) self.enabled = True def start_with_period(self, period): \"\"\"RPC method Set", "with agents and toggled on and off at runtime. \"\"\"", "rpc, pubsub, heartbeat_autostart, heartbeat_period): self.owner = owner self.core = weakref.ref(core)", "the start hasn't been called. try: self.scheduled.cancel() except AttributeError: pass", "service by trade name, trademark, manufacturer, or otherwise # does", "OR CONDITIONS OF ANY KIND, either express or implied. #", "would not infringe # privately owned rights. Reference herein to", "been # set yet if the start hasn't been called.", "the License is distributed on an \"AS IS\" BASIS, #", "fact that scheduled may not have been # set yet", "self.stop() self.start() def set_period(self, period): \"\"\"RPC method Set heartbeat period.", "stop(self): \"\"\"RPC method Stop an agent's heartbeat. \"\"\" if self.enabled:", "# Trap the fact that scheduled may not have been", "the # United States Department of Energy, nor Battelle, nor", "True def start_with_period(self, period): \"\"\"RPC method Set period and start", "method Set heartbeat period. :param period: Time in seconds between", "between publishes. \"\"\" if self.enabled: self.stop() self.period = period self.start()", "start(self): \"\"\"RPC method Starts an agent's heartbeat. \"\"\" if not", "'heartbeat.restart') rpc.export(self.set_period, 'heartbeat.set_period') def onstart(sender, **kwargs): if self.autostart: self.start() core.onsetup.connect(onsetup,", "heartbeat_autostart self.period = heartbeat_period self.enabled = False self.connect_error = False", "\"\"\" self.stop() self.start() def set_period(self, period): \"\"\"RPC method Set heartbeat", "utf-8 -*- {{{ # vim: set fenc=utf-8 ft=python sw=4 ts=4", "rpc.export(self.stop, 'heartbeat.stop') rpc.export(self.restart, 'heartbeat.restart') rpc.export(self.set_period, 'heartbeat.set_period') def onstart(sender, **kwargs): if", "adds an optional periodic publish to all agents. Heartbeats can", "expressed # herein do not necessarily state or reflect those", "TIMESTAMP from volttron.platform.agent.utils import (get_aware_utc_now, format_timestamp) from volttron.platform.scheduling import periodic", "law or agreed to in writing, software # distributed under", "\"\"\" self.set_period(period) self.start() def reconnect(self, sender, **kwargs): if self.connect_error: self.restart()", "from ..errors import Unreachable, VIPError \"\"\"The heartbeat subsystem adds an", "{{{ # vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:", "as an account of work sponsored by an agency of", "else: self.period = period def publish(self): topic = 'heartbeat/' +", "**kwargs): rpc.export(self.start, 'heartbeat.start') rpc.export(self.start_with_period, 'heartbeat.start_with_period') rpc.export(self.stop, 'heartbeat.stop') rpc.export(self.restart, 'heartbeat.restart') rpc.export(self.set_period,", "period. :param period: Time in seconds between publishes. \"\"\" if", "cooperated in the # development of these materials, makes any", "the United States Government. Neither the United States Government nor", "their # employees, nor any jurisdiction or organization that has", "import TIMESTAMP from volttron.platform.agent.utils import (get_aware_utc_now, format_timestamp) from volttron.platform.scheduling import", "'heartbeat.start_with_period') rpc.export(self.stop, 'heartbeat.stop') rpc.export(self.restart, 'heartbeat.restart') rpc.export(self.set_period, 'heartbeat.set_period') def onstart(sender, **kwargs):", "and # limitations under the License. # # This material", "disclosed, or represents that its use would not infringe #", "set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et: # # Copyright", "\"\"\"RPC method Set period and start heartbeat. :param period: Time", "the # development of these materials, makes any warranty, express", "may obtain a copy of the License at # #", "from volttron.platform.agent.utils import (get_aware_utc_now, format_timestamp) from volttron.platform.scheduling import periodic from", "software, or process disclosed, or represents that its use would", "subsystem adds an optional periodic publish to all agents. Heartbeats", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "sender, **kwargs): if self.connect_error: self.restart() self.connect_error = False def stop(self):", "The views and opinions of authors expressed # herein do", "assumes any legal liability or responsibility for the accuracy, #", "off at runtime. \"\"\" __docformat__ = 'reStructuredText' __version__ = '1.0'", "may not use this file except in compliance with the", "self.enabled: self.stop() self.period = period self.start() else: self.period = period", "reflect those of the # United States Government or any", "import periodic from ..errors import Unreachable, VIPError \"\"\"The heartbeat subsystem", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "False self.connect_error = False def onsetup(sender, **kwargs): rpc.export(self.start, 'heartbeat.start') rpc.export(self.start_with_period,", "information, apparatus, product, # software, or process disclosed, or represents", "or process disclosed, or represents that its use would not", "this file except in compliance with the License. # You", "heartbeat. :param period: Time in seconds between publishes. \"\"\" self.set_period(period)", "AttributeError: pass self.enabled = False def restart(self): \"\"\"RPC method Restart", "= 'heartbeat/' + self.core().identity headers = {TIMESTAMP: format_timestamp(get_aware_utc_now())} message =", "by # BATTELLE for the UNITED STATES DEPARTMENT OF ENERGY", "import (get_aware_utc_now, format_timestamp) from volttron.platform.scheduling import periodic from ..errors import", "any of their # employees, nor any jurisdiction or organization", "the UNITED STATES DEPARTMENT OF ENERGY # under Contract DE-AC05-76RL01830", "**kwargs): if self.connect_error: self.restart() self.connect_error = False def stop(self): \"\"\"RPC", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "message = self.owner.vip.health.get_status_value() try: self.pubsub().publish('pubsub', topic, headers, message) except Unreachable", "NORTHWEST NATIONAL LABORATORY operated by # BATTELLE for the UNITED", "# # Licensed under the Apache License, Version 2.0 (the", "**kwargs): if self.autostart: self.start() core.onsetup.connect(onsetup, self) core.onstart.connect(onstart, self) core.onconnected.connect(self.reconnect) def", "any agency thereof. # # PACIFIC NORTHWEST NATIONAL LABORATORY operated", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "nor the # United States Department of Energy, nor Battelle,", "privately owned rights. Reference herein to any specific commercial product,", "to the message bus. \"\"\" self.stop() self.start() def set_period(self, period):", "# under Contract DE-AC05-76RL01830 # }}} import os import weakref", "start_with_period(self, period): \"\"\"RPC method Set period and start heartbeat. :param", "def onstart(sender, **kwargs): if self.autostart: self.start() core.onsetup.connect(onsetup, self) core.onstart.connect(onstart, self)", "class Heartbeat(SubsystemBase): def __init__(self, owner, core, rpc, pubsub, heartbeat_autostart, heartbeat_period):", "agents. Heartbeats can be started with agents and toggled on", "# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et: #", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "# development of these materials, makes any warranty, express or", "limitations under the License. # # This material was prepared", "its use would not infringe # privately owned rights. Reference", "os import weakref from datetime import datetime from .base import", "import SubsystemBase from volttron.platform.messaging.headers import TIMESTAMP from volttron.platform.agent.utils import (get_aware_utc_now,", "hasn't been called. try: self.scheduled.cancel() except AttributeError: pass self.enabled =", "self.core = weakref.ref(core) self.pubsub = weakref.ref(pubsub) self.autostart = heartbeat_autostart self.period", "trade name, trademark, manufacturer, or otherwise # does not necessarily", "= False self.connect_error = False def onsetup(sender, **kwargs): rpc.export(self.start, 'heartbeat.start')", "OF ENERGY # under Contract DE-AC05-76RL01830 # }}} import os", "agency thereof. # # PACIFIC NORTHWEST NATIONAL LABORATORY operated by", "on and off at runtime. \"\"\" __docformat__ = 'reStructuredText' __version__", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "= False def restart(self): \"\"\"RPC method Restart the heartbeat with", "This material was prepared as an account of work sponsored", "of authors expressed # herein do not necessarily state or", "start hasn't been called. try: self.scheduled.cancel() except AttributeError: pass self.enabled", "# Battelle Memorial Institute. The views and opinions of authors", "vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et: # #", "or implied. # See the License for the specific language", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "organization that has cooperated in the # development of these", "# process, or service by trade name, trademark, manufacturer, or", "runtime. \"\"\" __docformat__ = 'reStructuredText' __version__ = '1.0' class Heartbeat(SubsystemBase):", "sponsored by an agency of # the United States Government.", "rights. Reference herein to any specific commercial product, # process,", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "__init__(self, owner, core, rpc, pubsub, heartbeat_autostart, heartbeat_period): self.owner = owner", "= heartbeat_autostart self.period = heartbeat_period self.enabled = False self.connect_error =", "self.scheduled.cancel() except AttributeError: pass self.enabled = False def restart(self): \"\"\"RPC", "# limitations under the License. # # This material was", "started with agents and toggled on and off at runtime.", "period and start heartbeat. :param period: Time in seconds between", "not necessarily state or reflect those of the # United", "or represents that its use would not infringe # privately", "the heartbeat with the current period. The heartbeat will be", "= period self.start() else: self.period = period def publish(self): topic", "heartbeat to the message bus. \"\"\" self.stop() self.start() def set_period(self,", "self.connect_error: self.restart() self.connect_error = False def stop(self): \"\"\"RPC method Stop", "to all agents. Heartbeats can be started with agents and", "= False def stop(self): \"\"\"RPC method Stop an agent's heartbeat.", "(the \"License\"); # you may not use this file except", "method Restart the heartbeat with the current period. The heartbeat", "will be immediately sending the heartbeat to the message bus.", "specific commercial product, # process, or service by trade name,", "onstart(sender, **kwargs): if self.autostart: self.start() core.onsetup.connect(onsetup, self) core.onstart.connect(onstart, self) core.onconnected.connect(self.reconnect)", "# you may not use this file except in compliance", "of their # employees, nor any jurisdiction or organization that", "volttron.platform.messaging.headers import TIMESTAMP from volttron.platform.agent.utils import (get_aware_utc_now, format_timestamp) from volttron.platform.scheduling", "in seconds between publishes. \"\"\" if self.enabled: self.stop() self.period =", "publishes. \"\"\" if self.enabled: self.stop() self.period = period self.start() else:", "by trade name, trademark, manufacturer, or otherwise # does not", "or organization that has cooperated in the # development of", "# does not necessarily constitute or imply its endorsement, recommendation,", "toggled on and off at runtime. \"\"\" __docformat__ = 'reStructuredText'", "current period. The heartbeat will be immediately sending the heartbeat", "account of work sponsored by an agency of # the", "or # favoring by the United States Government or any", "self.period = period def publish(self): topic = 'heartbeat/' + self.core().identity", "\"\"\" if not self.enabled: self.scheduled = self.core().schedule(periodic(self.period), self.publish) self.enabled =", "# # Unless required by applicable law or agreed to", "rpc.export(self.start_with_period, 'heartbeat.start_with_period') rpc.export(self.stop, 'heartbeat.stop') rpc.export(self.restart, 'heartbeat.restart') rpc.export(self.set_period, 'heartbeat.set_period') def onstart(sender,", "False def onsetup(sender, **kwargs): rpc.export(self.start, 'heartbeat.start') rpc.export(self.start_with_period, 'heartbeat.start_with_period') rpc.export(self.stop, 'heartbeat.stop')", "United States Government nor the # United States Department of", "implied, or assumes any legal liability or responsibility for the", "owner, core, rpc, pubsub, heartbeat_autostart, heartbeat_period): self.owner = owner self.core", "# # PACIFIC NORTHWEST NATIONAL LABORATORY operated by # BATTELLE", "heartbeat. \"\"\" if not self.enabled: self.scheduled = self.core().schedule(periodic(self.period), self.publish) self.enabled", "those of the # United States Government or any agency", "topic = 'heartbeat/' + self.core().identity headers = {TIMESTAMP: format_timestamp(get_aware_utc_now())} message", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "Starts an agent's heartbeat. \"\"\" if not self.enabled: self.scheduled =", "Version 2.0 (the \"License\"); # you may not use this", "# implied, or assumes any legal liability or responsibility for", "if the start hasn't been called. try: self.scheduled.cancel() except AttributeError:", "have been # set yet if the start hasn't been", "operated by # BATTELLE for the UNITED STATES DEPARTMENT OF", "weakref.ref(core) self.pubsub = weakref.ref(pubsub) self.autostart = heartbeat_autostart self.period = heartbeat_period", "at runtime. \"\"\" __docformat__ = 'reStructuredText' __version__ = '1.0' class", "Stop an agent's heartbeat. \"\"\" if self.enabled: # Trap the", "'1.0' class Heartbeat(SubsystemBase): def __init__(self, owner, core, rpc, pubsub, heartbeat_autostart,", "# # Copyright 2017, Battelle Memorial Institute. # # Licensed", "process, or service by trade name, trademark, manufacturer, or otherwise", "BATTELLE for the UNITED STATES DEPARTMENT OF ENERGY # under", "self.period = heartbeat_period self.enabled = False self.connect_error = False def", "implied. # See the License for the specific language governing", "under the Apache License, Version 2.0 (the \"License\"); # you", "States Government or any agency thereof, or # Battelle Memorial", "self.owner = owner self.core = weakref.ref(core) self.pubsub = weakref.ref(pubsub) self.autostart", "jurisdiction or organization that has cooperated in the # development", "period): \"\"\"RPC method Set heartbeat period. :param period: Time in", "License. # # This material was prepared as an account", "def reconnect(self, sender, **kwargs): if self.connect_error: self.restart() self.connect_error = False", "by applicable law or agreed to in writing, software #", "__docformat__ = 'reStructuredText' __version__ = '1.0' class Heartbeat(SubsystemBase): def __init__(self,", "{TIMESTAMP: format_timestamp(get_aware_utc_now())} message = self.owner.vip.health.get_status_value() try: self.pubsub().publish('pubsub', topic, headers, message)", "topic, headers, message) except Unreachable as exc: self.connect_error = True", "or # implied, or assumes any legal liability or responsibility", "= weakref.ref(core) self.pubsub = weakref.ref(pubsub) self.autostart = heartbeat_autostart self.period =", "sw=4 ts=4 sts=4 et: # # Copyright 2017, Battelle Memorial", "nor Battelle, nor any of their # employees, nor any", "set yet if the start hasn't been called. try: self.scheduled.cancel()", "the current period. The heartbeat will be immediately sending the", "process disclosed, or represents that its use would not infringe", "NATIONAL LABORATORY operated by # BATTELLE for the UNITED STATES", "for the accuracy, # completeness, or usefulness or any information,", "'heartbeat/' + self.core().identity headers = {TIMESTAMP: format_timestamp(get_aware_utc_now())} message = self.owner.vip.health.get_status_value()", "heartbeat_period): self.owner = owner self.core = weakref.ref(core) self.pubsub = weakref.ref(pubsub)", "self.connect_error = False def stop(self): \"\"\"RPC method Stop an agent's", "period def publish(self): topic = 'heartbeat/' + self.core().identity headers =", "= '1.0' class Heartbeat(SubsystemBase): def __init__(self, owner, core, rpc, pubsub,", "try: self.scheduled.cancel() except AttributeError: pass self.enabled = False def restart(self):", "Battelle Memorial Institute. The views and opinions of authors expressed", "coding: utf-8 -*- {{{ # vim: set fenc=utf-8 ft=python sw=4", "with the current period. The heartbeat will be immediately sending", "an optional periodic publish to all agents. Heartbeats can be", "self.owner.vip.health.get_status_value() try: self.pubsub().publish('pubsub', topic, headers, message) except Unreachable as exc:", "datetime import datetime from .base import SubsystemBase from volttron.platform.messaging.headers import", "represents that its use would not infringe # privately owned", "imply its endorsement, recommendation, or # favoring by the United", "2017, Battelle Memorial Institute. # # Licensed under the Apache", ".base import SubsystemBase from volttron.platform.messaging.headers import TIMESTAMP from volttron.platform.agent.utils import", "opinions of authors expressed # herein do not necessarily state", "heartbeat will be immediately sending the heartbeat to the message", "name, trademark, manufacturer, or otherwise # does not necessarily constitute", "method Starts an agent's heartbeat. \"\"\" if not self.enabled: self.scheduled", "et: # # Copyright 2017, Battelle Memorial Institute. # #", "called. try: self.scheduled.cancel() except AttributeError: pass self.enabled = False def", "# privately owned rights. Reference herein to any specific commercial", "Battelle, nor any of their # employees, nor any jurisdiction", "ft=python sw=4 ts=4 sts=4 et: # # Copyright 2017, Battelle", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "or any agency thereof, or # Battelle Memorial Institute. The", "False def stop(self): \"\"\"RPC method Stop an agent's heartbeat. \"\"\"", "self.start() def reconnect(self, sender, **kwargs): if self.connect_error: self.restart() self.connect_error =", "Unless required by applicable law or agreed to in writing,", "from .base import SubsystemBase from volttron.platform.messaging.headers import TIMESTAMP from volttron.platform.agent.utils", "self.core().schedule(periodic(self.period), self.publish) self.enabled = True def start_with_period(self, period): \"\"\"RPC method", "of the # United States Government or any agency thereof.", "the message bus. \"\"\" self.stop() self.start() def set_period(self, period): \"\"\"RPC", "or otherwise # does not necessarily constitute or imply its", "def start(self): \"\"\"RPC method Starts an agent's heartbeat. \"\"\" if", "the heartbeat to the message bus. \"\"\" self.stop() self.start() def", "format_timestamp(get_aware_utc_now())} message = self.owner.vip.health.get_status_value() try: self.pubsub().publish('pubsub', topic, headers, message) except", "the specific language governing permissions and # limitations under the", "agency thereof, or # Battelle Memorial Institute. The views and", "from datetime import datetime from .base import SubsystemBase from volttron.platform.messaging.headers", "'reStructuredText' __version__ = '1.0' class Heartbeat(SubsystemBase): def __init__(self, owner, core,", "applicable law or agreed to in writing, software # distributed", "'heartbeat.stop') rpc.export(self.restart, 'heartbeat.restart') rpc.export(self.set_period, 'heartbeat.set_period') def onstart(sender, **kwargs): if self.autostart:", "self.start() core.onsetup.connect(onsetup, self) core.onstart.connect(onstart, self) core.onconnected.connect(self.reconnect) def start(self): \"\"\"RPC method", "Government or any agency thereof. # # PACIFIC NORTHWEST NATIONAL", "in the # development of these materials, makes any warranty,", "heartbeat with the current period. The heartbeat will be immediately", "in writing, software # distributed under the License is distributed", "governing permissions and # limitations under the License. # #", "of # the United States Government. Neither the United States", "thereof. # # PACIFIC NORTHWEST NATIONAL LABORATORY operated by #", "def restart(self): \"\"\"RPC method Restart the heartbeat with the current", "# employees, nor any jurisdiction or organization that has cooperated", "heartbeat_autostart, heartbeat_period): self.owner = owner self.core = weakref.ref(core) self.pubsub =", "headers, message) except Unreachable as exc: self.connect_error = True self.stop()", "# This material was prepared as an account of work", "or responsibility for the accuracy, # completeness, or usefulness or", "def start_with_period(self, period): \"\"\"RPC method Set period and start heartbeat.", "# }}} import os import weakref from datetime import datetime", "= weakref.ref(pubsub) self.autostart = heartbeat_autostart self.period = heartbeat_period self.enabled =", "otherwise # does not necessarily constitute or imply its endorsement,", "def __init__(self, owner, core, rpc, pubsub, heartbeat_autostart, heartbeat_period): self.owner =", "herein do not necessarily state or reflect those of the", "liability or responsibility for the accuracy, # completeness, or usefulness", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "been called. try: self.scheduled.cancel() except AttributeError: pass self.enabled = False", "# You may obtain a copy of the License at", "self.autostart: self.start() core.onsetup.connect(onsetup, self) core.onstart.connect(onstart, self) core.onconnected.connect(self.reconnect) def start(self): \"\"\"RPC", "under Contract DE-AC05-76RL01830 # }}} import os import weakref from", "# PACIFIC NORTHWEST NATIONAL LABORATORY operated by # BATTELLE for", "self.start() else: self.period = period def publish(self): topic = 'heartbeat/'", "or reflect those of the # United States Government or", "# the United States Government. Neither the United States Government", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "scheduled may not have been # set yet if the", "period self.start() else: self.period = period def publish(self): topic =", "import weakref from datetime import datetime from .base import SubsystemBase", "any specific commercial product, # process, or service by trade", "weakref.ref(pubsub) self.autostart = heartbeat_autostart self.period = heartbeat_period self.enabled = False", "favoring by the United States Government or any agency thereof,", "States Department of Energy, nor Battelle, nor any of their", "reconnect(self, sender, **kwargs): if self.connect_error: self.restart() self.connect_error = False def", "use would not infringe # privately owned rights. Reference herein", "Neither the United States Government nor the # United States", "the License for the specific language governing permissions and #", "Apache License, Version 2.0 (the \"License\"); # you may not", "either express or implied. # See the License for the", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "Government. Neither the United States Government nor the # United", "state or reflect those of the # United States Government", "message bus. \"\"\" self.stop() self.start() def set_period(self, period): \"\"\"RPC method", "method Stop an agent's heartbeat. \"\"\" if self.enabled: # Trap", "PACIFIC NORTHWEST NATIONAL LABORATORY operated by # BATTELLE for the", "materials, makes any warranty, express or # implied, or assumes", "under the License. # # This material was prepared as", "any legal liability or responsibility for the accuracy, # completeness,", "constitute or imply its endorsement, recommendation, or # favoring by", "\"\"\" if self.enabled: # Trap the fact that scheduled may", "rpc.export(self.start, 'heartbeat.start') rpc.export(self.start_with_period, 'heartbeat.start_with_period') rpc.export(self.stop, 'heartbeat.stop') rpc.export(self.restart, 'heartbeat.restart') rpc.export(self.set_period, 'heartbeat.set_period')", "period): \"\"\"RPC method Set period and start heartbeat. :param period:", "core, rpc, pubsub, heartbeat_autostart, heartbeat_period): self.owner = owner self.core =", "sending the heartbeat to the message bus. \"\"\" self.stop() self.start()", "authors expressed # herein do not necessarily state or reflect", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "United States Government or any agency thereof, or # Battelle", "or imply its endorsement, recommendation, or # favoring by the", "LABORATORY operated by # BATTELLE for the UNITED STATES DEPARTMENT", "to any specific commercial product, # process, or service by", "its endorsement, recommendation, or # favoring by the United States", "\"\"\"The heartbeat subsystem adds an optional periodic publish to all", "owner self.core = weakref.ref(core) self.pubsub = weakref.ref(pubsub) self.autostart = heartbeat_autostart", "\"\"\" if self.enabled: self.stop() self.period = period self.start() else: self.period", "onsetup(sender, **kwargs): rpc.export(self.start, 'heartbeat.start') rpc.export(self.start_with_period, 'heartbeat.start_with_period') rpc.export(self.stop, 'heartbeat.stop') rpc.export(self.restart, 'heartbeat.restart')", "permissions and # limitations under the License. # # This", "heartbeat. \"\"\" if self.enabled: # Trap the fact that scheduled", "\"License\"); # you may not use this file except in", "development of these materials, makes any warranty, express or #", "views and opinions of authors expressed # herein do not", "optional periodic publish to all agents. Heartbeats can be started", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "weakref from datetime import datetime from .base import SubsystemBase from", "can be started with agents and toggled on and off", "self.scheduled = self.core().schedule(periodic(self.period), self.publish) self.enabled = True def start_with_period(self, period):", "these materials, makes any warranty, express or # implied, or", "# distributed under the License is distributed on an \"AS", "}}} import os import weakref from datetime import datetime from", "Government or any agency thereof, or # Battelle Memorial Institute.", "yet if the start hasn't been called. try: self.scheduled.cancel() except", "Institute. # # Licensed under the Apache License, Version 2.0", "# Unless required by applicable law or agreed to in", "self.enabled = False def restart(self): \"\"\"RPC method Restart the heartbeat", "that scheduled may not have been # set yet if", "= owner self.core = weakref.ref(core) self.pubsub = weakref.ref(pubsub) self.autostart =", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "You may obtain a copy of the License at #", "Department of Energy, nor Battelle, nor any of their #", "if not self.enabled: self.scheduled = self.core().schedule(periodic(self.period), self.publish) self.enabled = True", "def publish(self): topic = 'heartbeat/' + self.core().identity headers = {TIMESTAMP:", "-*- coding: utf-8 -*- {{{ # vim: set fenc=utf-8 ft=python", "self.start() def set_period(self, period): \"\"\"RPC method Set heartbeat period. :param", "prepared as an account of work sponsored by an agency", "# BATTELLE for the UNITED STATES DEPARTMENT OF ENERGY #", "the Apache License, Version 2.0 (the \"License\"); # you may", "United States Department of Energy, nor Battelle, nor any of", "employees, nor any jurisdiction or organization that has cooperated in", "Reference herein to any specific commercial product, # process, or", "import os import weakref from datetime import datetime from .base" ]
[ "the desired property. \"\"\" category = self._get_single_property(properties, property_name) try: return", "element_name + str(element_amount) return composition_str @staticmethod def _parse_composition_as_dict(raw_composition: List[dict]) ->", "composition has an asterisk in it, which occurs for 6", "dtype=float) return data, labels @staticmethod def _unzip_json_file(filepath: str): \"\"\"Open and", "the property to get the value of. units: Optional expected", "json import zipfile from typing import List, Optional, Tuple, Union", "time spent in heat treatment (hours), the maximum heat treatment", "= NiSuperalloyDataset._dict_values_to_float( composition_dict ) return not exception_caught def _parse_json_data(self, entry:", "str, units: Optional[str] = None, default_value=None ): \"\"\" Helper function", "is a single property. property_name: The name of the property", "of possible categories as given by the keys in `categories_dict`", "to return if `property_name` is not present. Raises: InvalidParameterError: if", "treatment 3 Time\", units=\"hours\", default_value=0 ) heat_treatment_3_temp = self._get_scalar_property( properties,", "about it. Currently, the only thing filtered on is if", "properties, \"Heat treatment 4 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) total_heat_treatment_time =", "Celcius * hours). A value of 0 generally implies that", "array: {categories_dict.keys()}\", category ) @staticmethod def _get_single_property( properties: List[dict], property_name:", "one entry in properties should have name\" f\" '{property_name}'\", got=properties,", "each property\", got=properties ) labels_array = [] for label in", "a pressure treatment step (temperature, time, pressure), but since only", "3 Time\", units=\"hours\", default_value=0 ) heat_treatment_3_temp = self._get_scalar_property( properties, \"Heat", "105%. There are also three columns for a pressure treatment", "by the keys in `categories_dict` Returns: int An integer that", "dict) -> Tuple[dict, bool]: \"\"\" Convert a dictionary's values to", "rupture time (hours), and yield strength (MPa). Tensile strength and", "from smlb.parameters import params from smlb.tabular_data import TabularData class NiSuperalloyDataset(TabularData):", "heat_treatment_3_time, heat_treatment_3_temp, heat_treatment_4_time, heat_treatment_4_temp, total_heat_treatment_time, max_heat_treatment_temp, area_under_heat_treatment_curve, powder_processed, ] return", "Array of labels in this row that we are interested", "can be turned into a float. Parameters: properties: A list", "a floating point number. The values are in percentage points,", "with the elements as keys and their raw amounts as", "\"Heat treatment 1 Time\", units=\"hours\", default_value=0 ) heat_treatment_1_temp = self._get_scalar_property(", "= self._parse_composition(raw_composition) properties = entry.get(\"properties\") if properties is None or", "row that we are interested in. \"\"\" if labels_to_load is", "indicating whether or not an Exception was caught \"\"\" d_copy", "Union import numpy as np from smlb.exceptions import InvalidParameterError from", "composition_dict_float, _ = NiSuperalloyDataset._dict_values_to_float(composition_dict) composition_str: str = \"\" for element_name,", "Tensile Strength\", \"Stress Rupture Time\", \"Stress Rupture Stress\", \"Elongation\", ]", "== units except (KeyError, AssertionError): units_str = \"\" if units", "row has exactly one output set. The other values are", "(temperature, time, pressure), but since only 51 rows have non-zero", "= entry.get(\"composition\") if raw_composition is None or not isinstance(raw_composition, list):", "labels: ultimate tensile strength (MPa), elongation (unitless), stress rupture stress", "expected units string. default_value: Value to return if `property_name` is", "raise InvalidParameterError(\"Amount as a float\", x) def _get_scalar_property( self, properties:", "in the expected list of possible categories as given by", "single property. Each entry is expected to have a 'name'", "should have a value \" f\"that can be expressed as", "on: <NAME>, <NAME>, <NAME>, <NAME>: Design of a nickel-base superalloy", "\"\"\" Helper function to parse labels in a single row", "pointing to a floating point number. The values are in", ") max_heat_treatment_temp = self._get_scalar_property( properties, \"Max Heat Treatment Temperature\", units=\"$^{\\\\circ}$C\"", "a float\", got=properties, ) def _get_categorical_property( self, properties: List[dict], property_name:", "'Elongation'. If None, then all labels are loaded. ignore_dubious: whether", "composition_str += element_name + str(element_amount) return composition_str @staticmethod def _parse_composition_as_dict(raw_composition:", "\"system.chemical\" raw_composition = NiSuperalloyDataset._extract_raw_composition(entry) composition: str = self._parse_composition(raw_composition) properties =", "was not done, but there are some missing values. The", "curve (degrees Celcius * hours). A value of 0 generally", "units=\"hours\" ) max_heat_treatment_temp = self._get_scalar_property( properties, \"Max Heat Treatment Temperature\",", "parse composition as a dictionary. Parameters: raw_composition (List[dict]): A list,", "Design 131: 358-365, Elsevier, 2017. DOI 10.1016/j.matdes.2017.06.007 The dataset was", "pressure), but since only 51 rows have non-zero entries, this", "categories_dict=powder_processed_dict ) data_array = [ composition, heat_treatment_1_time, heat_treatment_1_temp, heat_treatment_2_time, heat_treatment_2_temp,", "expected=\"Element amount as a dictionary of the form\\n\" \"{'element': <element", "present. Raises: InvalidParameterError: if `properties` does not conform to the", "entry: dict, labels_to_load: Optional[List[str]] = None): \"\"\" Helper function to", "to the expected structure Returns: The value of the property", "possible categories as given by the keys in `categories_dict` Returns:", "properties: List[dict], property_name: str, categories_dict: dict ) -> int: \"\"\"", "\"Stress Rupture Stress\", \"Elongation\", ] properties = entry.get(\"properties\") if properties", "Parameters: entry (dict): A json entry corresponding to a row", "with zf.open(unzipped_filename) as fp: raw = json.load(fp) return raw @staticmethod", ") composition_dict[element_name] = element_amount return composition_dict @staticmethod def _dict_values_to_float(d: dict)", "up to ~100 (but not exactly). Returns: dict Chemical composition", "Tuple, Union import numpy as np from smlb.exceptions import InvalidParameterError", "its value must correspond to `units`. default_value: Value to return", "form\\n\" \"{'element': <element name>,\" \"'idealWeightPercent': \" \"{'value': <element amount>}}\", got=entry,", "Returns: float The value of the desired property. \"\"\" try:", "which is a single property. property_name: The name of the", "a single property. property_name: The name of the property to", "= self._get_scalar_property( properties, \"Max Heat Treatment Temperature\", units=\"$^{\\\\circ}$C\" ) area_under_heat_treatment_curve", "in the dataset. Returns: array Array of data in this", "\"Area under heat treatment curve\", units=\"$^{\\\\circ}$C * hours\" ) powder_processed_dict", "@staticmethod def _parse_composition(raw_composition: List[dict]) -> str: \"\"\" Helper function to", "data_array = [ composition, heat_treatment_1_time, heat_treatment_1_temp, heat_treatment_2_time, heat_treatment_2_temp, heat_treatment_3_time, heat_treatment_3_temp,", "if `property_name` is not present. Raises: InvalidParameterError: if the value", "Temperature\", units=\"$^{\\\\circ}$C\" ) area_under_heat_treatment_curve = self._get_scalar_property( properties, \"Area under heat", "smlb.exceptions import InvalidParameterError from smlb.parameters import params from smlb.tabular_data import", "\".zip\" ), f\"File path must point to a .zip file,", "as keys and their raw amounts as values \"\"\" composition_dict", "is not in the expected list of possible categories as", "treatment 2 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_3_time = self._get_scalar_property( properties,", "Raises: InvalidParameterError: if `properties` does not conform to the expected", "\"\"\" try: val = self._get_single_property(properties, property_name, units, default_value) if val", "raise InvalidParameterError( expected=\"Property as a dictionary of the form\\n\" \"{'name':", "for e in raw if self._filter_dubious(e)] # dtype=object is necessary", "expected=\"A list of dictionaries, one for each property\", got=properties )", "\"Yield Strength\", \"Ultimate Tensile Strength\", \"Stress Rupture Time\", \"Stress Rupture", "\"\"\" if x[-1] == \"*\": x = x[:-1] try: return", "necessary because this is a mixed-type array (float and string)", "dtype=object is necessary because this is a mixed-type array (float", "bool = False ): \"\"\"Initialize Ni-superalloy dataset with specified labels.", "Array of data in this row. \"\"\" assert entry[\"category\"] ==", "\" \"{'value': <element amount>}}\", got=entry, ) composition_dict[element_name] = element_amount return", "array Array of data in this row. \"\"\" assert entry[\"category\"]", "bool]: \"\"\" Convert a dictionary's values to their floating point", "os.path.split(os.path.realpath(__file__))[0] + \"/ni_superalloys_3.json.zip\" POWDER_PROCESSED_NO = 0 POWDER_PROCESSED_YES = 1 def", "dictionary of the form\\n\" \"{'name': <property name>, 'scalars': \" \"[{'value':", "'scalars': \" \"[{'value': <property value>}]\" + units_str + \"}\", got=matching_prop,", "(0 or 1), whether it was pressure treated (0 or", "= x[:-1] try: return float(x) except ValueError: raise InvalidParameterError(\"Amount as", "that corresponds to the property name and a `scalars` field", "import numpy as np from smlb.exceptions import InvalidParameterError from smlb.parameters", "name>,\" \"'idealWeightPercent': \" \"{'value': <element amount>}}\", got=entry, ) composition_dict[element_name] =", "for e in raw], dtype=object) labels = np.array([self._parse_json_labels(e, labels_to_load) for", "structure Returns: The value of the property `property_name` \"\"\" matching_props", "is not used. There are 5 labels: ultimate tensile strength", "property_name: The name of the property to get the value", "dict, bool A modified version of `d`, and a boolean", "os import json import zipfile from typing import List, Optional,", "TabularData class NiSuperalloyDataset(TabularData): \"\"\" Ni-Superalloy dataset. Based on: <NAME>, <NAME>,", "@staticmethod def _parse_composition_as_dict(raw_composition: List[dict]) -> dict: \"\"\" Helper function to", "name\" f\" '{property_name}'\", got=properties, ) matching_prop = matching_props[0] try: scalars", "columns for a pressure treatment step (temperature, time, pressure), but", "self._get_scalar_property( properties, \"Heat treatment 4 Time\", units=\"hours\", default_value=0 ) heat_treatment_4_temp", "of 'units' field. If specified, then there must be a", "try: scalars = matching_prop[\"scalars\"] assert len(scalars) == 1 val =", "the maximum heat treatment temperature (degrees Celcius), and the area", "self, filepath: str, labels_to_load: Optional[List[str]] = None, ignore_dubious: bool =", "Benchmark A benchmark of regression models in chem- and materials", "val is None: return None return float(val) except ValueError: raise", "list of dictionaries, one for each property\", got=properties ) heat_treatment_1_time", "prop in properties if prop.get(\"name\") == property_name] if len(matching_props) ==", "conform to the expected structure Returns: The value of the", "zipped json file.\"\"\" filename = os.path.basename(filepath) assert ( filename[-4:] ==", "is a mixed-type array (float and string) data = np.array([self._parse_json_data(e)", "lambda arg: params.any_( arg, params.string, lambda arg: params.sequence(arg, type_=str), ),", "the form\\n\" \"{'element': <element name>,\" \"'idealWeightPercent': \" \"{'value': <element amount>}}\",", "Rupture Stress\", \"Elongation\", ] properties = entry.get(\"properties\") if properties is", "'units' field and its value must correspond to `units`. default_value:", "dataset. Based on: <NAME>, <NAME>, <NAME>, <NAME>: Design of a", "List[str]): which labels to load. Options are 'Yield Strength', 'Ultimate", "str Chemical composition as string, e.g. 'Al5.5Ni94.0W0.5' \"\"\" composition_dict =", "= [e for e in raw if self._filter_dubious(e)] # dtype=object", "file.\"\"\" filename = os.path.basename(filepath) assert ( filename[-4:] == \".zip\" ),", "point number. The values are in percentage points, and add", "for up to 4 heat treatment steps, the total time", "that we are interested in. \"\"\" if labels_to_load is None:", "row), whether the alloy was powder processed (0 or 1),", "def _get_scalar_property( self, properties: List[dict], property_name: str, units: Optional[str] =", "bool = False, ): \"\"\"Load data and labels from .json", "the expected list of possible categories as given by the", "the property to get the value of. `properties` is expected", "chem- and materials informatics. 2019, <NAME>, Citrine Informatics. See class", "= value_float return d_copy, exception_caught @staticmethod def _parse_peculiar_amount(x: str) ->", "Chemical composition as string, e.g. 'Al5.5Ni94.0W0.5' \"\"\" composition_dict = NiSuperalloyDataset._parse_composition_as_dict(raw_composition)", "exception_caught = NiSuperalloyDataset._dict_values_to_float( composition_dict ) return not exception_caught def _parse_json_data(self,", "2800 rows. The data have columns for composition (25 elements", "whether the alloy was powder processed (0 or 1), whether", "try: return categories_dict[category] except KeyError: raise InvalidParameterError( f\"A value in", "Determine whether or not a json entry has something questionable", "[ composition, heat_treatment_1_time, heat_treatment_1_temp, heat_treatment_2_time, heat_treatment_2_temp, heat_treatment_3_time, heat_treatment_3_temp, heat_treatment_4_time, heat_treatment_4_temp,", "Optional[Union[str, List[str]]] = None, ignore_dubious: bool = False ): \"\"\"Initialize", "heat_treatment_2_time = self._get_scalar_property( properties, \"Heat treatment 2 Time\", units=\"hours\", default_value=0", "stress (MPa), stress rupture time (hours), and yield strength (MPa).", "be ignored. \"\"\" if x[-1] == \"*\": x = x[:-1]", "pressure treated (0 or 1), heat treatment time (hours) and", "unclear. Perhaps it denotes that the amount is imprecise. In", "units, default_value) if val is None: return None return float(val)", "the keys in `categories_dict` Returns: int An integer that corresponds", "but with about a dozen exceptions they always add up", "= self._get_scalar_property( properties, \"Heat treatment 3 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 )", "a dict with an 'element' key and an 'idealWeightPercent' key.", "labels_to_load, ignore_dubious) super().__init__(data=data, labels=labels) def _load_data_and_labels( self, filepath: str, labels_to_load:", ") -> float: \"\"\" A helper function to get a", "under the time-temperature curve (degrees Celcius * hours). A value", "ValueError: raise InvalidParameterError( expected=f\"Property {property_name} should have a value \"", "raw @staticmethod def _extract_raw_composition(entry: dict) -> List[dict]: \"\"\"Get composition in", "must be a 'units' field and its value must correspond", "as a float Returns: float The value of the desired", "Exception was caught \"\"\" d_copy = dict() exception_caught = False", "spent in heat treatment (hours), the maximum heat treatment temperature", "up to 100%, but with about a dozen exceptions they", "-> dict: \"\"\" Helper function to parse composition as a", "rows, stress rupture stress and time occur together in 856", "2019, <NAME>, Citrine Informatics. See class NiSuperalloyDataset for details. \"\"\"", "thing filtered on is if the composition has an asterisk", "name of the property to get the value of. units:", "do not always add up to 100%, but with about", "Time\", \"Stress Rupture Stress\", \"Elongation\", ] properties = entry.get(\"properties\") if", "\"\"\" import os import json import zipfile from typing import", "be a 'units' field and its value must correspond to", "value \" f\"that can be expressed as a float\", got=properties,", "if len(matching_props) == 0: return default_value elif len(matching_props) > 1:", "`property_name` is not present. Raises: InvalidParameterError: if `properties` does not", "entry is a dict with an 'element' key and an", "\"\"\" Ni-Superalloy dataset. Based on: <NAME>, <NAME>, <NAME>, <NAME>: Design", "ignore_dubious: bool = False, ): \"\"\"Load data and labels from", "composition as string, e.g. 'Al5.5Ni94.0W0.5' \"\"\" composition_dict = NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float,", "heat treatment curve\", units=\"$^{\\\\circ}$C * hours\" ) powder_processed_dict = {\"No\":", "entry[\"element\"] element_amount = entry[\"idealWeightPercent\"][\"value\"] except KeyError: raise InvalidParameterError( expected=\"Element amount", "value_float return d_copy, exception_caught @staticmethod def _parse_peculiar_amount(x: str) -> float:", "Parameters: labels_to_load (str or List[str]): which labels to load. Options", "all labels are loaded. ignore_dubious: whether or not to ignore", "units=\"$^{\\\\circ}$C * hours\" ) powder_processed_dict = {\"No\": self.POWDER_PROCESSED_NO, \"Yes\": self.POWDER_PROCESSED_YES}", "function to get a single scalar property. This calls _get_single_property", "raw], dtype=object) labels = np.array([self._parse_json_labels(e, labels_to_load) for e in raw],", "4 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) total_heat_treatment_time = self._get_scalar_property( properties, \"Total", "labels_to_load) for e in raw], dtype=float) return data, labels @staticmethod", "each property\", got=properties ) heat_treatment_1_time = self._get_scalar_property( properties, \"Heat treatment", "in this row. \"\"\" assert entry[\"category\"] == \"system.chemical\" raw_composition =", "amounts as values \"\"\" composition_dict = dict() for entry in", ") heat_treatment_4_temp = self._get_scalar_property( properties, \"Heat treatment 4 Temperature\", units=\"$^{\\\\circ}$C\",", "\"\"\" Determine whether or not a json entry has something", "and a `scalars` field that is a list with one", "treatment 1 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_2_time = self._get_scalar_property( properties,", "Ni-Superalloy dataset. Based on: <NAME>, <NAME>, <NAME>, <NAME>: Design of", "= NiSuperalloyDataset._parse_peculiar_amount(value) d_copy[key] = value_float return d_copy, exception_caught @staticmethod def", "units is None else f\", 'units': {units}\" raise InvalidParameterError( expected=\"Property", "try: return float(x) except ValueError: raise InvalidParameterError(\"Amount as a float\",", "\"\"\" raw_composition = NiSuperalloyDataset._extract_raw_composition(entry) composition_dict = NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float, exception_caught =", "and add up to ~100. Returns: str Chemical composition as", "_unzip_json_file(filepath: str): \"\"\"Open and read zipped json file.\"\"\" filename =", "amounts. Some composition amounts have a trailing asterisk, e.g., '2*'.", "of data in this row. \"\"\" assert entry[\"category\"] == \"system.chemical\"", "units is not None: assert matching_prop[\"units\"] == units except (KeyError,", "params.optional_( labels_to_load, lambda arg: params.any_( arg, params.string, lambda arg: params.sequence(arg,", "heat_treatment_4_time = self._get_scalar_property( properties, \"Heat treatment 4 Time\", units=\"hours\", default_value=0", "composition_dict @staticmethod def _dict_values_to_float(d: dict) -> Tuple[dict, bool]: \"\"\" Convert", "entry[\"idealWeightPercent\"][\"value\"] except KeyError: raise InvalidParameterError( expected=\"Element amount as a dictionary", "steps. The total compositions do not always add up to", "= None, ) -> float: \"\"\" A helper function to", "keys and their raw amounts as values \"\"\" composition_dict =", "a .zip file, instead got '{filepath}'\" with zipfile.ZipFile(filepath) as zf:", "for key, value in d.items(): try: value_float = float(value) except", "labels_to_load: Optional[Union[str, List[str]]] = None, ignore_dubious: bool = False ):", ") heat_treatment_1_time = self._get_scalar_property( properties, \"Heat treatment 1 Time\", units=\"hours\",", "as a string. Parameters: raw_composition (List[dict]): A list, each entry", "\"\"\"Get composition in its raw form.\"\"\" raw_composition = entry.get(\"composition\") if", "field. If specified, then there must be a 'units' field", "dictionary with the elements as keys and their raw amounts", "specified labels. Parameters: labels_to_load (str or List[str]): which labels to", "InvalidParameterError from smlb.parameters import params from smlb.tabular_data import TabularData class", "A benchmark of regression models in chem- and materials informatics.", "ignore_dubious: bool = False ): \"\"\"Initialize Ni-superalloy dataset with specified", "d_copy = dict() exception_caught = False for key, value in", "element is a string (e.g., 'Cu') and the weight percent", "'Al5.5Ni94.0W0.5' \"\"\" composition_dict = NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float, _ = NiSuperalloyDataset._dict_values_to_float(composition_dict) composition_str:", "\"\"\" Helper function to parse composition as a string. Parameters:", "not an Exception was caught \"\"\" d_copy = dict() exception_caught", "True value_float = NiSuperalloyDataset._parse_peculiar_amount(value) d_copy[key] = value_float return d_copy, exception_caught", "InvalidParameterError( expected=f\"Only one entry in properties should have name\" f\"", "row in the dataset. Returns: bool True if the composition", "under heat treatment curve\", units=\"$^{\\\\circ}$C * hours\" ) powder_processed_dict =", "is imprecise. In any case, they only occur in 6", "models in chem- and materials informatics. 2019, <NAME>, Citrine Informatics.", "It may also have a 'units' field. property_name: The name", "labels are loaded. ignore_dubious: whether or not to ignore samples", "each entry of which corresponds to an element. An entry", "checks that the result can be turned into a float.", "amounts have a trailing asterisk, e.g., '2*'. The meaning is", "to ignore samples that have something questionable about them \"\"\"", "max_heat_treatment_temp = self._get_scalar_property( properties, \"Max Heat Treatment Temperature\", units=\"$^{\\\\circ}$C\" )", "unzipped_filename = filename[:-4] with zf.open(unzipped_filename) as fp: raw = json.load(fp)", "return not exception_caught def _parse_json_data(self, entry: dict): \"\"\" Helper function", "entry, a dict of the form {'value': <property value>}. It", "add up to ~100. Returns: str Chemical composition as string,", "if `property_name` is not present. Raises: InvalidParameterError: if `properties` does", "stress rupture stress and time occur together in 856 rows,", "of the desired property. \"\"\" category = self._get_single_property(properties, property_name) try:", "Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_2_time = self._get_scalar_property( properties, \"Heat treatment", "is not present. Raises: InvalidParameterError: if `properties` does not conform", "percent is another dict with a single key, 'value', pointing", "[] for label in labels_to_load: labels_array.append(self._get_scalar_property(properties, label, default_value=None)) return labels_array", "filepath: str, labels_to_load: Optional[List[str]] = None, ignore_dubious: bool = False,", "heat_treatment_2_temp, heat_treatment_3_time, heat_treatment_3_temp, heat_treatment_4_time, heat_treatment_4_temp, total_heat_treatment_time, max_heat_treatment_temp, area_under_heat_treatment_curve, powder_processed, ]", "\"Heat treatment 4 Time\", units=\"hours\", default_value=0 ) heat_treatment_4_temp = self._get_scalar_property(", ") data_array = [ composition, heat_treatment_1_time, heat_treatment_1_temp, heat_treatment_2_time, heat_treatment_2_temp, heat_treatment_3_time,", "property\", got=properties ) labels_array = [] for label in labels_to_load:", "equal to `property_name`. units: Optional expected value of 'units' field.", "smlb.tabular_data import TabularData class NiSuperalloyDataset(TabularData): \"\"\" Ni-Superalloy dataset. Based on:", "InvalidParameterError(\"Amount as a float\", x) def _get_scalar_property( self, properties: List[dict],", "strength and elongation occur together in 898 rows, stress rupture", "51 rows have non-zero entries, this information is not used.", "be turned into a float. Parameters: properties: A list of", "whether it was pressure treated (0 or 1), heat treatment", "Parameters: properties: A list of dicts, each of which is", "them \"\"\" labels_to_load = params.optional_( labels_to_load, lambda arg: params.any_( arg,", "_parse_json_labels(self, entry: dict, labels_to_load: Optional[List[str]] = None): \"\"\" Helper function", "property_name, units, default_value) if val is None: return None return", "or 1), whether it was pressure treated (0 or 1),", "data have columns for composition (25 elements are present in", "is None or not isinstance(properties, list): raise InvalidParameterError( expected=\"A list", "as a float\", got=properties, ) def _get_categorical_property( self, properties: List[dict],", "self._get_scalar_property( properties, \"Heat treatment 3 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_4_time", "try: element_name = entry[\"element\"] element_amount = entry[\"idealWeightPercent\"][\"value\"] except KeyError: raise", "return default_value elif len(matching_props) > 1: raise InvalidParameterError( expected=f\"Only one", "1046 rows. 898+856+1046=2800, so every row has exactly one output", "with zipfile.ZipFile(filepath) as zf: unzipped_filename = filename[:-4] with zf.open(unzipped_filename) as", "exception_caught def _parse_json_data(self, entry: dict): \"\"\" Helper function to parse", "of which is a single property. property_name: The name of", "labels to load. Options are 'Yield Strength', 'Ultimate Tensile Strength',", "Based on: <NAME>, <NAME>, <NAME>, <NAME>: Design of a nickel-base", "individual heating steps. The total compositions do not always add", "instead got '{filepath}'\" with zipfile.ZipFile(filepath) as zf: unzipped_filename = filename[:-4]", "a `scalars` field that is a list with one entry,", "dicts, each of which is a single property. property_name: The", "integer value. Raises: InvalidParameterError: if the value is not in", "{'value': <property value>}. It may also have a 'units' field.", "list): raise InvalidParameterError( expected=\"A list of dictionaries, one for each", "step (temperature, time, pressure), but since only 51 rows have", "heat_treatment_1_temp, heat_treatment_2_time, heat_treatment_2_temp, heat_treatment_3_time, heat_treatment_3_temp, heat_treatment_4_time, heat_treatment_4_temp, total_heat_treatment_time, max_heat_treatment_temp, area_under_heat_treatment_curve,", "except KeyError: raise InvalidParameterError( expected=\"Element amount as a dictionary of", "scalars[0][\"value\"] if units is not None: assert matching_prop[\"units\"] == units", "Materials & Design 131: 358-365, Elsevier, 2017. DOI 10.1016/j.matdes.2017.06.007 The", "= dict() exception_caught = False for key, value in d.items():", "NiSuperalloyDataset._parse_peculiar_amount(value) d_copy[key] = value_float return d_copy, exception_caught @staticmethod def _parse_peculiar_amount(x:", "occur together in 898 rows, stress rupture stress and time", "and labels from .json file.\"\"\" raw = self._unzip_json_file(filepath) if ignore_dubious:", "weight percent is another dict with a single key, 'value',", "== property_name] if len(matching_props) == 0: return default_value elif len(matching_props)", "The value of the property `property_name` \"\"\" matching_props = [prop", "if x[-1] == \"*\": x = x[:-1] try: return float(x)", "\"[{'value': <property value>}]\" + units_str + \"}\", got=matching_prop, ) return", "property. Parameters: properties: A list of dicts, each of which", "a unique integer value. Raises: InvalidParameterError: if the value is", "default_value=None)) return labels_array @staticmethod def _parse_composition(raw_composition: List[dict]) -> str: \"\"\"", "that is a list with one entry, a dict of", "got=properties ) labels_array = [] for label in labels_to_load: labels_array.append(self._get_scalar_property(properties,", "of dicts, each of which is a single property. property_name:", "property_name) try: return categories_dict[category] except KeyError: raise InvalidParameterError( f\"A value", "except (KeyError, AssertionError): units_str = \"\" if units is None", "`property_name` \"\"\" matching_props = [prop for prop in properties if", "also three columns for a pressure treatment step (temperature, time,", "The data have columns for composition (25 elements are present", "heat_treatment_4_temp = self._get_scalar_property( properties, \"Heat treatment 4 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0", "this row that we are interested in. \"\"\" if labels_to_load", "only 51 rows have non-zero entries, this information is not", "an 'idealWeightPercent' key. The element is a string (e.g., 'Cu')", "else f\", 'units': {units}\" raise InvalidParameterError( expected=\"Property as a dictionary", "or not isinstance(raw_composition, list): raise InvalidParameterError( expected=\"Chemical composition as a", "string) data = np.array([self._parse_json_data(e) for e in raw], dtype=object) labels", "pressure treatment step (temperature, time, pressure), but since only 51", "of the property to get the value of. categories_dict: Dict", "labels_to_load = params.optional_( labels_to_load, lambda arg: params.any_( arg, params.string, lambda", "expected=f\"Only one entry in properties should have name\" f\" '{property_name}'\",", "and max temperature are generally more reliable than the individual", "Time\", units=\"hours\", default_value=0 ) heat_treatment_4_temp = self._get_scalar_property( properties, \"Heat treatment", "KeyError: raise InvalidParameterError( expected=\"Element amount as a dictionary of the", "in `categories_dict` Returns: int An integer that corresponds to the", "Rupture Time', 'Stress Rupture Stress', and 'Elongation'. If None, then", "units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_3_time = self._get_scalar_property( properties, \"Heat treatment 3", "single property. Parameters: properties: A list of dicts, each of", "filename = os.path.basename(filepath) assert ( filename[-4:] == \".zip\" ), f\"File", "<NAME>, Citrine Informatics. See class NiSuperalloyDataset for details. \"\"\" import", "entries, this information is not used. There are 5 labels:", "informatics. 2019, <NAME>, Citrine Informatics. See class NiSuperalloyDataset for details.", "InvalidParameterError( expected=\"Element amount as a dictionary of the form\\n\" \"{'element':", "are loaded. ignore_dubious: whether or not to ignore samples that", "raw amounts as values \"\"\" composition_dict = dict() for entry", "self, properties: List[dict], property_name: str, categories_dict: dict ) -> int:", "set. The other values are denoted as NaN. \"\"\" DEFAULT_PATH", "= os.path.split(os.path.realpath(__file__))[0] + \"/ni_superalloys_3.json.zip\" POWDER_PROCESSED_NO = 0 POWDER_PROCESSED_YES = 1", "\"\"\" Helper function to parse data in a single row", "as a dictionary. Parameters: raw_composition (List[dict]): A list, each entry", "params.string, lambda arg: params.sequence(arg, type_=str), ), ) ignore_dubious = params.boolean(ignore_dubious)", "number. The values are in percentage points, and add up", "Helper function to parse composition as a string. Parameters: raw_composition", "_parse_peculiar_amount(x: str) -> float: \"\"\" Deals with dataset-specific-peculiarities in composition", "row in the dataset. labels_to_load (List[str]): Optional list of labels", "interested in. \"\"\" if labels_to_load is None: labels_to_load = [", "composition amounts have a trailing asterisk, e.g., '2*'. The meaning", "a row in the dataset. Returns: array Array of data", "\"\"\"Load data and labels from .json file.\"\"\" raw = self._unzip_json_file(filepath)", "value of. `properties` is expected to have exactly one entry", "expected structure Returns: The value of the property `property_name` \"\"\"", "for prop in properties if prop.get(\"name\") == property_name] if len(matching_props)", "unique integer value. Raises: InvalidParameterError: if the value is not", "as a dictionary of the form\\n\" \"{'element': <element name>,\" \"'idealWeightPercent':", "e in raw], dtype=object) labels = np.array([self._parse_json_labels(e, labels_to_load) for e", "float(value) except ValueError: exception_caught = True value_float = NiSuperalloyDataset._parse_peculiar_amount(value) d_copy[key]", "not isinstance(raw_composition, list): raise InvalidParameterError( expected=\"Chemical composition as a list\",", "\"{'name': <property name>, 'scalars': \" \"[{'value': <property value>}]\" + units_str", "value cannot be expressed as a float Returns: float The", "InvalidParameterError( expected=f\"Property {property_name} should have a value \" f\"that can", "entry corresponding to a row in the dataset. Returns: bool", "= NiSuperalloyDataset._extract_raw_composition(entry) composition: str = self._parse_composition(raw_composition) properties = entry.get(\"properties\") if", "samples that have something questionable about them \"\"\" labels_to_load =", "the alloy was powder processed (0 or 1), whether it", "amount>}}\", got=entry, ) composition_dict[element_name] = element_amount return composition_dict @staticmethod def", "expected list of possible categories as given by the keys", "ignore_dubious = params.boolean(ignore_dubious) filepath = self.DEFAULT_PATH data, labels = self._load_data_and_labels(filepath,", "_get_scalar_property( self, properties: List[dict], property_name: str, units: Optional[str] = None,", "KeyError: raise InvalidParameterError( f\"A value in the array: {categories_dict.keys()}\", category", "add up to ~100 (but not exactly). Returns: dict Chemical", "not isinstance(properties, list): raise InvalidParameterError( expected=\"A list of dictionaries, one", "\"\"\" Helper function to get a single property. Parameters: properties:", "dict) -> List[dict]: \"\"\"Get composition in its raw form.\"\"\" raw_composition", "(hours), the maximum heat treatment temperature (degrees Celcius), and the", "for element_name, element_amount in composition_dict_float.items(): if element_amount > 0: composition_str", "expected=\"Chemical composition as a list\", got=raw_composition ) return raw_composition @staticmethod", "as a dictionary of the form\\n\" \"{'name': <property name>, 'scalars':", "units: Optional[str] = None, default_value: Optional[float] = None, ) ->", "samples. Parameters: entry (dict): A json entry corresponding to a", "A value of 0 generally implies that the heat treatment", "<NAME>, <NAME>, <NAME>, <NAME>: Design of a nickel-base superalloy using", "\"\"\" matching_props = [prop for prop in properties if prop.get(\"name\")", "= self._get_scalar_property( properties, \"Heat treatment 1 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 )", "in raw], dtype=float) return data, labels @staticmethod def _unzip_json_file(filepath: str):", "NiSuperalloyDataset(TabularData): \"\"\" Ni-Superalloy dataset. Based on: <NAME>, <NAME>, <NAME>, <NAME>:", "present in at least one row), whether the alloy was", "d_copy, exception_caught @staticmethod def _parse_peculiar_amount(x: str) -> float: \"\"\" Deals", "row. \"\"\" assert entry[\"category\"] == \"system.chemical\" raw_composition = NiSuperalloyDataset._extract_raw_composition(entry) composition:", "(25 elements are present in at least one row), whether", "properties, \"Heat treatment 2 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_3_time =", "are also three columns for a pressure treatment step (temperature,", "[prop for prop in properties if prop.get(\"name\") == property_name] if", "Stress\", \"Elongation\", ] properties = entry.get(\"properties\") if properties is None", "None return float(val) except ValueError: raise InvalidParameterError( expected=f\"Property {property_name} should", "load. Returns: array Array of labels in this row that", "-> Tuple[dict, bool]: \"\"\" Convert a dictionary's values to their", "that corresponds to the value of the desired property. \"\"\"", "stress and time occur together in 856 rows, and yield", "result can be turned into a float. Parameters: properties: A", "<property value>}]\" + units_str + \"}\", got=matching_prop, ) return val", "\"\"\" labels_to_load = params.optional_( labels_to_load, lambda arg: params.any_( arg, params.string,", "element_name, element_amount in composition_dict_float.items(): if element_amount > 0: composition_str +=", "List[dict]) -> dict: \"\"\" Helper function to parse composition as", "have a trailing asterisk, e.g., '2*'. The meaning is unclear.", "the form {'value': <property value>}. It may also have a", "scalar property. This calls _get_single_property and then checks that the", "`properties` does not conform to the expected structure Returns: The", "get the value of. units: Optional expected units string. default_value:", "NiSuperalloyDataset._extract_raw_composition(entry) composition: str = self._parse_composition(raw_composition) properties = entry.get(\"properties\") if properties", "5 labels: ultimate tensile strength (MPa), elongation (unitless), stress rupture", "\"'idealWeightPercent': \" \"{'value': <element amount>}}\", got=entry, ) composition_dict[element_name] = element_amount", "composition as a string. Parameters: raw_composition (List[dict]): A list, each", "the value is not in the expected list of possible", "if units is None else f\", 'units': {units}\" raise InvalidParameterError(", "'element' key and an 'idealWeightPercent' key. The element is a", "<element amount>}}\", got=entry, ) composition_dict[element_name] = element_amount return composition_dict @staticmethod", "filtered on is if the composition has an asterisk in", "for each property\", got=properties ) labels_array = [] for label", "arg: params.sequence(arg, type_=str), ), ) ignore_dubious = params.boolean(ignore_dubious) filepath =", "composition_dict = dict() for entry in raw_composition: try: element_name =", "str(element_amount) return composition_str @staticmethod def _parse_composition_as_dict(raw_composition: List[dict]) -> dict: \"\"\"", "), ) ignore_dubious = params.boolean(ignore_dubious) filepath = self.DEFAULT_PATH data, labels", "have a 'name' field that corresponds to the property name", "dict() for entry in raw_composition: try: element_name = entry[\"element\"] element_amount", "'value', pointing to a floating point number. The values are", "units: Optional[str] = None, default_value=None ): \"\"\" Helper function to", "of the form {'value': <property value>}. It may also have", "amount as a dictionary of the form\\n\" \"{'element': <element name>,\"", "Optional[str] = None, default_value=None ): \"\"\" Helper function to get", "f\"File path must point to a .zip file, instead got", "an Exception was caught \"\"\" d_copy = dict() exception_caught =", "the desired property. \"\"\" try: val = self._get_single_property(properties, property_name, units,", "corresponds to the value of the desired property. \"\"\" category", "dict: \"\"\" Helper function to parse composition as a dictionary.", "composition_dict_float.items(): if element_amount > 0: composition_str += element_name + str(element_amount)", "get the value of. `properties` is expected to have exactly", "category ) @staticmethod def _get_single_property( properties: List[dict], property_name: str, units:", "expressed as a float Returns: float The value of the", "a dict of the form {'value': <property value>}. It may", "return if `property_name` is not present. Raises: InvalidParameterError: if the", "are in percentage points, and add up to ~100. Returns:", "\" \"[{'value': <property value>}]\" + units_str + \"}\", got=matching_prop, )", "superalloy using a neural network, Materials & Design 131: 358-365,", "matching_prop = matching_props[0] try: scalars = matching_prop[\"scalars\"] assert len(scalars) ==", "None): \"\"\" Helper function to parse labels in a single", "exception_caught @staticmethod def _parse_peculiar_amount(x: str) -> float: \"\"\" Deals with", "Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) total_heat_treatment_time = self._get_scalar_property( properties, \"Total heat", "Informatics. See class NiSuperalloyDataset for details. \"\"\" import os import", "params from smlb.tabular_data import TabularData class NiSuperalloyDataset(TabularData): \"\"\" Ni-Superalloy dataset.", "asterisk, e.g., '2*'. The meaning is unclear. Perhaps it denotes", "string (e.g., 'Cu') and the weight percent is another dict", "a trailing asterisk, e.g., '2*'. The meaning is unclear. Perhaps", "x) def _get_scalar_property( self, properties: List[dict], property_name: str, units: Optional[str]", "entry corresponding to a row in the dataset. labels_to_load (List[str]):", "the composition contains an asterisk. \"\"\" raw_composition = NiSuperalloyDataset._extract_raw_composition(entry) composition_dict", "= scalars[0][\"value\"] if units is not None: assert matching_prop[\"units\"] ==", "as given by the keys in `categories_dict` Returns: int An", "@staticmethod def _get_single_property( properties: List[dict], property_name: str, units: Optional[str] =", "[e for e in raw if self._filter_dubious(e)] # dtype=object is", "a dictionary Returns: dict, bool A modified version of `d`,", "(List[str]): Optional list of labels to load. Returns: array Array", "exceptions they always add up to somewhere between 95% and", "which occurs for 6 samples. Parameters: entry (dict): A json", "{\"No\": self.POWDER_PROCESSED_NO, \"Yes\": self.POWDER_PROCESSED_YES} powder_processed = self._get_categorical_property( properties, \"Powder processed\",", "float The value of the desired property. \"\"\" try: val", "got '{filepath}'\" with zipfile.ZipFile(filepath) as zf: unzipped_filename = filename[:-4] with", "to an element. An entry is a dict with an", "from smlb.tabular_data import TabularData class NiSuperalloyDataset(TabularData): \"\"\" Ni-Superalloy dataset. Based", "to load. Options are 'Yield Strength', 'Ultimate Tensile Strength', 'Stress", "): \"\"\" Helper function to get a single property. Parameters:", "got=properties ) heat_treatment_1_time = self._get_scalar_property( properties, \"Heat treatment 1 Time\",", "meaning is unclear. Perhaps it denotes that the amount is", "a 'name' field that corresponds to the property name and", "try: val = self._get_single_property(properties, property_name, units, default_value) if val is", "\"Ultimate Tensile Strength\", \"Stress Rupture Time\", \"Stress Rupture Stress\", \"Elongation\",", "composition in its raw form.\"\"\" raw_composition = entry.get(\"composition\") if raw_composition", "as a dictionary with the elements as keys and their", "in 898 rows, stress rupture stress and time occur together", "10.1016/j.matdes.2017.06.007 The dataset was downloaded from the Citrination platform (https://citrination.com),", "float(val) except ValueError: raise InvalidParameterError( expected=f\"Property {property_name} should have a", "if ignore_dubious: raw = [e for e in raw if", "Raises: InvalidParameterError: if the value cannot be expressed as a", "something questionable about them \"\"\" labels_to_load = params.optional_( labels_to_load, lambda", "there are some missing values. The total time and max", "any case, they only occur in 6 samples. The trailing", "more reliable than the individual heating steps. The total compositions", "dataset. Returns: array Array of data in this row. \"\"\"", "arg: params.any_( arg, params.string, lambda arg: params.sequence(arg, type_=str), ), )", "Rupture Time\", \"Stress Rupture Stress\", \"Elongation\", ] properties = entry.get(\"properties\")", "bool True if the composition contains an asterisk. \"\"\" raw_composition", "rows have non-zero entries, this information is not used. There", "if units is not None: assert matching_prop[\"units\"] == units except", "in a single row from the raw json. Parameters: entry", "= self._get_scalar_property( properties, \"Heat treatment 2 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 )", "in labels_to_load: labels_array.append(self._get_scalar_property(properties, label, default_value=None)) return labels_array @staticmethod def _parse_composition(raw_composition:", "Raises: InvalidParameterError: if the value is not in the expected", "{units}\" raise InvalidParameterError( expected=\"Property as a dictionary of the form\\n\"", "or not isinstance(properties, list): raise InvalidParameterError( expected=\"A list of dictionaries,", "def _parse_composition_as_dict(raw_composition: List[dict]) -> dict: \"\"\" Helper function to parse", "'{property_name}'\", got=properties, ) matching_prop = matching_props[0] try: scalars = matching_prop[\"scalars\"]", "the array: {categories_dict.keys()}\", category ) @staticmethod def _get_single_property( properties: List[dict],", "f\" '{property_name}'\", got=properties, ) matching_prop = matching_props[0] try: scalars =", "or List[str]): which labels to load. Options are 'Yield Strength',", "e in raw], dtype=float) return data, labels @staticmethod def _unzip_json_file(filepath:", "but there are some missing values. The total time and", "area_under_heat_treatment_curve = self._get_scalar_property( properties, \"Area under heat treatment curve\", units=\"$^{\\\\circ}$C", "there must be a 'units' field and its value must", "units: Optional expected units string. default_value: Value to return if", "default_value elif len(matching_props) > 1: raise InvalidParameterError( expected=f\"Only one entry", "that have something questionable about them \"\"\" labels_to_load = params.optional_(", "or not an Exception was caught \"\"\" d_copy = dict()", "representations, if possible. Parameters: d: a dictionary Returns: dict, bool", "\"\" for element_name, element_amount in composition_dict_float.items(): if element_amount > 0:", "if self._filter_dubious(e)] # dtype=object is necessary because this is a", "function to parse data in a single row from the", "= None, default_value: Optional[float] = None, ) -> float: \"\"\"", "heat treatment temperature (degrees Celcius), and the area under the", "ignore_dubious) super().__init__(data=data, labels=labels) def _load_data_and_labels( self, filepath: str, labels_to_load: Optional[List[str]]", "value of 0 generally implies that the heat treatment step", "to get the value of. `properties` is expected to have", "to a row in the dataset. labels_to_load (List[str]): Optional list", "must correspond to `units`. default_value: Value to return if `property_name`", "A json entry corresponding to a row in the dataset.", "together in 898 rows, stress rupture stress and time occur", "\"\"\"Initialize Ni-superalloy dataset with specified labels. Parameters: labels_to_load (str or", "1 Time\", units=\"hours\", default_value=0 ) heat_treatment_1_temp = self._get_scalar_property( properties, \"Heat", "about them \"\"\" labels_to_load = params.optional_( labels_to_load, lambda arg: params.any_(", "json. Parameters: entry (dict): A json entry corresponding to a", "raw], dtype=float) return data, labels @staticmethod def _unzip_json_file(filepath: str): \"\"\"Open", "matching_prop[\"units\"] == units except (KeyError, AssertionError): units_str = \"\" if", "string. Parameters: raw_composition (List[dict]): A list, each entry of which", "get the value of. categories_dict: Dict from the categorical property", "DOI 10.1016/j.matdes.2017.06.007 The dataset was downloaded from the Citrination platform", "of the property `property_name` \"\"\" matching_props = [prop for prop", ".json file.\"\"\" raw = self._unzip_json_file(filepath) if ignore_dubious: raw = [e", "and the weight percent is another dict with a single", "file, instead got '{filepath}'\" with zipfile.ZipFile(filepath) as zf: unzipped_filename =", "and their raw amounts as values \"\"\" composition_dict = dict()", "may also have a 'units' field. property_name: The name of", "str = self._parse_composition(raw_composition) properties = entry.get(\"properties\") if properties is None", "composition as a dictionary with the elements as keys and", "def _filter_dubious(entry: dict) -> bool: \"\"\" Determine whether or not", "= self._get_categorical_property( properties, \"Powder processed\", categories_dict=powder_processed_dict ) data_array = [", "to get a single property. Parameters: properties: A list of", "Celcius), and the area under the time-temperature curve (degrees Celcius", "loaded. ignore_dubious: whether or not to ignore samples that have", "len(matching_props) > 1: raise InvalidParameterError( expected=f\"Only one entry in properties", "InvalidParameterError: if the value cannot be expressed as a float", "labels_to_load: Optional[List[str]] = None, ignore_dubious: bool = False, ): \"\"\"Load", "value. Raises: InvalidParameterError: if the value is not in the", "data, labels = self._load_data_and_labels(filepath, labels_to_load, ignore_dubious) super().__init__(data=data, labels=labels) def _load_data_and_labels(", "Returns: array Array of labels in this row that we", "values are in percentage points, and add up to ~100.", "a single scalar property. This calls _get_single_property and then checks", "for each property\", got=properties ) heat_treatment_1_time = self._get_scalar_property( properties, \"Heat", "~100 (but not exactly). Returns: dict Chemical composition as a", "in percentage points, and add up to ~100. Returns: str", "= matching_prop[\"scalars\"] assert len(scalars) == 1 val = scalars[0][\"value\"] if", "filename[:-4] with zf.open(unzipped_filename) as fp: raw = json.load(fp) return raw", "raw_composition (List[dict]): A list, each entry of which corresponds to", "steps, the total time spent in heat treatment (hours), the", "try: value_float = float(value) except ValueError: exception_caught = True value_float", "exactly one entry with the 'name' field equal to `property_name`.", "+ \"/ni_superalloys_3.json.zip\" POWDER_PROCESSED_NO = 0 POWDER_PROCESSED_YES = 1 def __init__(", "= None, ignore_dubious: bool = False, ): \"\"\"Load data and", "expected value of 'units' field. If specified, then there must", "units except (KeyError, AssertionError): units_str = \"\" if units is", "labels = self._load_data_and_labels(filepath, labels_to_load, ignore_dubious) super().__init__(data=data, labels=labels) def _load_data_and_labels( self,", "Returns: dict Chemical composition as a dictionary with the elements", "raw_composition is None or not isinstance(raw_composition, list): raise InvalidParameterError( expected=\"Chemical", "1), whether it was pressure treated (0 or 1), heat", "def _unzip_json_file(filepath: str): \"\"\"Open and read zipped json file.\"\"\" filename", "add up to 100%, but with about a dozen exceptions", "property. \"\"\" category = self._get_single_property(properties, property_name) try: return categories_dict[category] except", "\"\"\" if labels_to_load is None: labels_to_load = [ \"Yield Strength\",", "self._get_scalar_property( properties, \"Heat treatment 3 Time\", units=\"hours\", default_value=0 ) heat_treatment_3_temp", "which is a single property. Each entry is expected to", "\"\"\" composition_dict = dict() for entry in raw_composition: try: element_name", "rows. 898+856+1046=2800, so every row has exactly one output set.", "property (string) to a unique integer value. Raises: InvalidParameterError: if", "then there must be a 'units' field and its value", "the categorical property (string) to a unique integer value. Raises:", "== \"*\": x = x[:-1] try: return float(x) except ValueError:", "values. The total time and max temperature are generally more", "of 0 generally implies that the heat treatment step was", "to parse composition as a dictionary. Parameters: raw_composition (List[dict]): A", "property_name: str, categories_dict: dict ) -> int: \"\"\" Helper function", "raw = [e for e in raw if self._filter_dubious(e)] #", "is another dict with a single key, 'value', pointing to", "d: a dictionary Returns: dict, bool A modified version of", "in its raw form.\"\"\" raw_composition = entry.get(\"composition\") if raw_composition is", "dict of the form {'value': <property value>}. It may also", "list, each entry of which corresponds to an element. An", "= {\"No\": self.POWDER_PROCESSED_NO, \"Yes\": self.POWDER_PROCESSED_YES} powder_processed = self._get_categorical_property( properties, \"Powder", "was caught \"\"\" d_copy = dict() exception_caught = False for", "(degrees Celcius) for up to 4 heat treatment steps, the", "can be expressed as a float\", got=properties, ) def _get_categorical_property(", "= NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float, _ = NiSuperalloyDataset._dict_values_to_float(composition_dict) composition_str: str = \"\"", "dataset-specific-peculiarities in composition amounts. Some composition amounts have a trailing", "float\", got=properties, ) def _get_categorical_property( self, properties: List[dict], property_name: str,", "Optional, Tuple, Union import numpy as np from smlb.exceptions import", "their floating point representations, if possible. Parameters: d: a dictionary", "treatment time\", units=\"hours\" ) max_heat_treatment_temp = self._get_scalar_property( properties, \"Max Heat", "(MPa). Tensile strength and elongation occur together in 898 rows,", "float(x) except ValueError: raise InvalidParameterError(\"Amount as a float\", x) def", "np from smlb.exceptions import InvalidParameterError from smlb.parameters import params from", "if the value is not in the expected list of", "properties: A list of dicts, each of which is a", "string, e.g. 'Al5.5Ni94.0W0.5' \"\"\" composition_dict = NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float, _ =", "keys in `categories_dict` Returns: int An integer that corresponds to", "the weight percent is another dict with a single key,", "value of. units: Optional expected units string. default_value: Value to", "matching_props = [prop for prop in properties if prop.get(\"name\") ==", "property\", got=properties ) heat_treatment_1_time = self._get_scalar_property( properties, \"Heat treatment 1", "Citrination platform (https://citrination.com), dataset identifier #153493, Version 10. There are", "& Design 131: 358-365, Elsevier, 2017. DOI 10.1016/j.matdes.2017.06.007 The dataset", "max temperature are generally more reliable than the individual heating", "heat_treatment_4_time, heat_treatment_4_temp, total_heat_treatment_time, max_heat_treatment_temp, area_under_heat_treatment_curve, powder_processed, ] return data_array def", ") -> int: \"\"\" Helper function to get a single", "is None or not isinstance(raw_composition, list): raise InvalidParameterError( expected=\"Chemical composition", "Each entry is expected to have a 'name' field that", "field that is a list with one entry, a dict", "a single row from the raw json. Parameters: entry (dict):", "regression models in chem- and materials informatics. 2019, <NAME>, Citrine", "= element_amount return composition_dict @staticmethod def _dict_values_to_float(d: dict) -> Tuple[dict,", "elongation (unitless), stress rupture stress (MPa), stress rupture time (hours),", "A modified version of `d`, and a boolean flag indicating", "to the property name and a `scalars` field that is", "values are denoted as NaN. \"\"\" DEFAULT_PATH = os.path.split(os.path.realpath(__file__))[0] +", "4 heat treatment steps, the total time spent in heat", "temperature are generally more reliable than the individual heating steps.", "\"Elongation\", ] properties = entry.get(\"properties\") if properties is None or", "This calls _get_single_property and then checks that the result can", "key. The element is a string (e.g., 'Cu') and the", "not a json entry has something questionable about it. Currently,", "composition, heat_treatment_1_time, heat_treatment_1_temp, heat_treatment_2_time, heat_treatment_2_temp, heat_treatment_3_time, heat_treatment_3_temp, heat_treatment_4_time, heat_treatment_4_temp, total_heat_treatment_time,", "units=\"hours\", default_value=0 ) heat_treatment_3_temp = self._get_scalar_property( properties, \"Heat treatment 3", "composition_dict = NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float, _ = NiSuperalloyDataset._dict_values_to_float(composition_dict) composition_str: str =", "<element name>,\" \"'idealWeightPercent': \" \"{'value': <element amount>}}\", got=entry, ) composition_dict[element_name]", "units=\"hours\", default_value=0 ) heat_treatment_4_temp = self._get_scalar_property( properties, \"Heat treatment 4", "a mixed-type array (float and string) data = np.array([self._parse_json_data(e) for", "ignore samples that have something questionable about them \"\"\" labels_to_load", "and time occur together in 856 rows, and yield strength", "Currently, the only thing filtered on is if the composition", "occurs for 6 samples. Parameters: entry (dict): A json entry", "and its value must correspond to `units`. default_value: Value to", "~100. Returns: str Chemical composition as string, e.g. 'Al5.5Ni94.0W0.5' \"\"\"", "val = self._get_single_property(properties, property_name, units, default_value) if val is None:", "smlb.parameters import params from smlb.tabular_data import TabularData class NiSuperalloyDataset(TabularData): \"\"\"", "value must correspond to `units`. default_value: Value to return if", "labels_to_load (List[str]): Optional list of labels to load. Returns: array", "int. Parameters: properties: A list of dicts, each of which", "float Returns: float The value of the desired property. \"\"\"", "implies that the heat treatment step was not done, but", "if labels_to_load is None: labels_to_load = [ \"Yield Strength\", \"Ultimate", "treatment 1 Time\", units=\"hours\", default_value=0 ) heat_treatment_1_temp = self._get_scalar_property( properties,", "np.array([self._parse_json_labels(e, labels_to_load) for e in raw], dtype=float) return data, labels", "should have name\" f\" '{property_name}'\", got=properties, ) matching_prop = matching_props[0]", "\"Stress Rupture Time\", \"Stress Rupture Stress\", \"Elongation\", ] properties =", "units=\"hours\", default_value=0 ) heat_treatment_1_temp = self._get_scalar_property( properties, \"Heat treatment 1", "will be ignored. \"\"\" if x[-1] == \"*\": x =", "properties, \"Max Heat Treatment Temperature\", units=\"$^{\\\\circ}$C\" ) area_under_heat_treatment_curve = self._get_scalar_property(", "property_name: str, units: Optional[str] = None, default_value: Optional[float] = None,", "of dictionaries, one for each property\", got=properties ) heat_treatment_1_time =", "params.boolean(ignore_dubious) filepath = self.DEFAULT_PATH data, labels = self._load_data_and_labels(filepath, labels_to_load, ignore_dubious)", "= self._get_scalar_property( properties, \"Heat treatment 3 Time\", units=\"hours\", default_value=0 )", "heat_treatment_1_time, heat_treatment_1_temp, heat_treatment_2_time, heat_treatment_2_temp, heat_treatment_3_time, heat_treatment_3_temp, heat_treatment_4_time, heat_treatment_4_temp, total_heat_treatment_time, max_heat_treatment_temp,", "property to get the value of. `properties` is expected to", "if possible. Parameters: d: a dictionary Returns: dict, bool A", "and elongation occur together in 898 rows, stress rupture stress", "they always add up to somewhere between 95% and 105%.", "in 1046 rows. 898+856+1046=2800, so every row has exactly one", "= [ composition, heat_treatment_1_time, heat_treatment_1_temp, heat_treatment_2_time, heat_treatment_2_temp, heat_treatment_3_time, heat_treatment_3_temp, heat_treatment_4_time,", "are generally more reliable than the individual heating steps. The", "the value of. units: Optional expected units string. default_value: Value", "units string. default_value: Value to return if `property_name` is not", "key, 'value', pointing to a floating point number. The values", "assert len(scalars) == 1 val = scalars[0][\"value\"] if units is", "ignored. \"\"\" if x[-1] == \"*\": x = x[:-1] try:", ") def _get_categorical_property( self, properties: List[dict], property_name: str, categories_dict: dict", "this information is not used. There are 5 labels: ultimate", "so every row has exactly one output set. The other", "single row from the raw json. Parameters: entry (dict): A", "-> float: \"\"\" A helper function to get a single", "`units`. default_value: Value to return if `property_name` is not present.", "_dict_values_to_float(d: dict) -> Tuple[dict, bool]: \"\"\" Convert a dictionary's values", "list): raise InvalidParameterError( expected=\"Chemical composition as a list\", got=raw_composition )", "class NiSuperalloyDataset(TabularData): \"\"\" Ni-Superalloy dataset. Based on: <NAME>, <NAME>, <NAME>,", "False, ): \"\"\"Load data and labels from .json file.\"\"\" raw", "\" f\"that can be expressed as a float\", got=properties, )", "List[dict], property_name: str, units: Optional[str] = None, default_value=None ): \"\"\"", "Helper function to parse data in a single row from", "heat_treatment_3_time = self._get_scalar_property( properties, \"Heat treatment 3 Time\", units=\"hours\", default_value=0", "None, default_value: Optional[float] = None, ) -> float: \"\"\" A", "a dictionary of the form\\n\" \"{'name': <property name>, 'scalars': \"", ") return raw_composition @staticmethod def _filter_dubious(entry: dict) -> bool: \"\"\"", "elif len(matching_props) > 1: raise InvalidParameterError( expected=f\"Only one entry in", "_parse_json_data(self, entry: dict): \"\"\" Helper function to parse data in", "DEFAULT_PATH = os.path.split(os.path.realpath(__file__))[0] + \"/ni_superalloys_3.json.zip\" POWDER_PROCESSED_NO = 0 POWDER_PROCESSED_YES =", "units=\"$^{\\\\circ}$C\", default_value=0 ) total_heat_treatment_time = self._get_scalar_property( properties, \"Total heat treatment", "categories as given by the keys in `categories_dict` Returns: int", "InvalidParameterError( expected=\"Property as a dictionary of the form\\n\" \"{'name': <property", "the expected structure Returns: The value of the property `property_name`", "1: raise InvalidParameterError( expected=f\"Only one entry in properties should have", "if the composition has an asterisk in it, which occurs", "calls _get_single_property and then checks that the result can be", "] properties = entry.get(\"properties\") if properties is None or not", "element_amount = entry[\"idealWeightPercent\"][\"value\"] except KeyError: raise InvalidParameterError( expected=\"Element amount as", "typing import List, Optional, Tuple, Union import numpy as np", "together in 856 rows, and yield strength occurs in 1046", "@staticmethod def _dict_values_to_float(d: dict) -> Tuple[dict, bool]: \"\"\" Convert a", "x = x[:-1] try: return float(x) except ValueError: raise InvalidParameterError(\"Amount", "= self._get_single_property(properties, property_name, units, default_value) if val is None: return", "heat_treatment_1_temp = self._get_scalar_property( properties, \"Heat treatment 1 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0", "the dataset. labels_to_load (List[str]): Optional list of labels to load.", "except ValueError: raise InvalidParameterError( expected=f\"Property {property_name} should have a value", "units=\"hours\", default_value=0 ) heat_treatment_2_temp = self._get_scalar_property( properties, \"Heat treatment 2", "amount is imprecise. In any case, they only occur in", "None else f\", 'units': {units}\" raise InvalidParameterError( expected=\"Property as a", "val = scalars[0][\"value\"] if units is not None: assert matching_prop[\"units\"]", "= NiSuperalloyDataset._dict_values_to_float(composition_dict) composition_str: str = \"\" for element_name, element_amount in", "json.load(fp) return raw @staticmethod def _extract_raw_composition(entry: dict) -> List[dict]: \"\"\"Get", "): \"\"\"Load data and labels from .json file.\"\"\" raw =", "-> bool: \"\"\" Determine whether or not a json entry", "field and its value must correspond to `units`. default_value: Value", "specified, then there must be a 'units' field and its", "in d.items(): try: value_float = float(value) except ValueError: exception_caught =", "curve\", units=\"$^{\\\\circ}$C * hours\" ) powder_processed_dict = {\"No\": self.POWDER_PROCESSED_NO, \"Yes\":", "(hours) and temperature (degrees Celcius) for up to 4 heat", "has something questionable about it. Currently, the only thing filtered", "a row in the dataset. labels_to_load (List[str]): Optional list of", "in the dataset. labels_to_load (List[str]): Optional list of labels to", "output set. The other values are denoted as NaN. \"\"\"", "to get a single scalar property. This calls _get_single_property and", "or not to ignore samples that have something questionable about", "(degrees Celcius * hours). A value of 0 generally implies", "percentage points, and add up to ~100 (but not exactly).", "stress rupture stress (MPa), stress rupture time (hours), and yield", ") area_under_heat_treatment_curve = self._get_scalar_property( properties, \"Area under heat treatment curve\",", "arg, params.string, lambda arg: params.sequence(arg, type_=str), ), ) ignore_dubious =", "categories_dict: dict ) -> int: \"\"\" Helper function to get", "to parse composition as a string. Parameters: raw_composition (List[dict]): A", "\"\"\" assert entry[\"category\"] == \"system.chemical\" raw_composition = NiSuperalloyDataset._extract_raw_composition(entry) composition: str", "between 95% and 105%. There are also three columns for", "row from the raw json. Parameters: entry (dict): A json", "raw_composition = entry.get(\"composition\") if raw_composition is None or not isinstance(raw_composition,", "InvalidParameterError: if `properties` does not conform to the expected structure", "= np.array([self._parse_json_labels(e, labels_to_load) for e in raw], dtype=float) return data,", "are in percentage points, and add up to ~100 (but", "as an int. Parameters: properties: A list of dicts, each", "dict): \"\"\" Helper function to parse data in a single", "composition (25 elements are present in at least one row),", "up to 4 heat treatment steps, the total time spent", "we are interested in. \"\"\" if labels_to_load is None: labels_to_load", "for label in labels_to_load: labels_array.append(self._get_scalar_property(properties, label, default_value=None)) return labels_array @staticmethod", "a dozen exceptions they always add up to somewhere between", "{categories_dict.keys()}\", category ) @staticmethod def _get_single_property( properties: List[dict], property_name: str,", "Convert a dictionary's values to their floating point representations, if", "raise InvalidParameterError( f\"A value in the array: {categories_dict.keys()}\", category )", "to have a 'name' field that corresponds to the property", "value of 'units' field. If specified, then there must be", "not None: assert matching_prop[\"units\"] == units except (KeyError, AssertionError): units_str", "value in the array: {categories_dict.keys()}\", category ) @staticmethod def _get_single_property(", "3 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_4_time = self._get_scalar_property( properties, \"Heat", "\"\"\" A helper function to get a single scalar property.", "caught \"\"\" d_copy = dict() exception_caught = False for key,", "dict with an 'element' key and an 'idealWeightPercent' key. The", "the elements as keys and their raw amounts as values", "a list\", got=raw_composition ) return raw_composition @staticmethod def _filter_dubious(entry: dict)", "properties, \"Heat treatment 2 Time\", units=\"hours\", default_value=0 ) heat_treatment_2_temp =", "expected to have exactly one entry with the 'name' field", "0 generally implies that the heat treatment step was not", "e.g., '2*'. The meaning is unclear. Perhaps it denotes that", "function to parse composition as a dictionary. Parameters: raw_composition (List[dict]):", "super().__init__(data=data, labels=labels) def _load_data_and_labels( self, filepath: str, labels_to_load: Optional[List[str]] =", "(degrees Celcius), and the area under the time-temperature curve (degrees", "key and an 'idealWeightPercent' key. The element is a string", "\"\"\" d_copy = dict() exception_caught = False for key, value", "'Ultimate Tensile Strength', 'Stress Rupture Time', 'Stress Rupture Stress', and", "= self._get_scalar_property( properties, \"Heat treatment 2 Time\", units=\"hours\", default_value=0 )", "-> List[dict]: \"\"\"Get composition in its raw form.\"\"\" raw_composition =", "NaN. \"\"\" DEFAULT_PATH = os.path.split(os.path.realpath(__file__))[0] + \"/ni_superalloys_3.json.zip\" POWDER_PROCESSED_NO = 0", "InvalidParameterError( f\"A value in the array: {categories_dict.keys()}\", category ) @staticmethod", "to their floating point representations, if possible. Parameters: d: a", "if raw_composition is None or not isinstance(raw_composition, list): raise InvalidParameterError(", "of. units: Optional expected units string. default_value: Value to return", "powder_processed, ] return data_array def _parse_json_labels(self, entry: dict, labels_to_load: Optional[List[str]]", "'Yield Strength', 'Ultimate Tensile Strength', 'Stress Rupture Time', 'Stress Rupture", "temperature (degrees Celcius) for up to 4 heat treatment steps,", "\"Heat treatment 2 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_3_time = self._get_scalar_property(", "_parse_composition(raw_composition: List[dict]) -> str: \"\"\" Helper function to parse composition", "See class NiSuperalloyDataset for details. \"\"\" import os import json", "Options are 'Yield Strength', 'Ultimate Tensile Strength', 'Stress Rupture Time',", "with dataset-specific-peculiarities in composition amounts. Some composition amounts have a", "(string) to a unique integer value. Raises: InvalidParameterError: if the", "a neural network, Materials & Design 131: 358-365, Elsevier, 2017.", "`properties` is expected to have exactly one entry with the", "integer that corresponds to the value of the desired property.", "turned into a float. Parameters: properties: A list of dicts,", "treatment step was not done, but there are some missing", "not always add up to 100%, but with about a", "labels @staticmethod def _unzip_json_file(filepath: str): \"\"\"Open and read zipped json", "be expressed as a float Returns: float The value of", "heat treatment (hours), the maximum heat treatment temperature (degrees Celcius),", "856 rows, and yield strength occurs in 1046 rows. 898+856+1046=2800,", "to a .zip file, instead got '{filepath}'\" with zipfile.ZipFile(filepath) as", "information is not used. There are 5 labels: ultimate tensile", "get a single property. Parameters: properties: A list of dicts,", "'idealWeightPercent' key. The element is a string (e.g., 'Cu') and", "and 105%. There are also three columns for a pressure", "Returns: The value of the property `property_name` \"\"\" matching_props =", "in properties should have name\" f\" '{property_name}'\", got=properties, ) matching_prop", "value_float = NiSuperalloyDataset._parse_peculiar_amount(value) d_copy[key] = value_float return d_copy, exception_caught @staticmethod", "to 4 heat treatment steps, the total time spent in", "the heat treatment step was not done, but there are", "exception_caught = True value_float = NiSuperalloyDataset._parse_peculiar_amount(value) d_copy[key] = value_float return", "self._get_single_property(properties, property_name) try: return categories_dict[category] except KeyError: raise InvalidParameterError( f\"A", "default_value: Optional[float] = None, ) -> float: \"\"\" A helper", "the form\\n\" \"{'name': <property name>, 'scalars': \" \"[{'value': <property value>}]\"", "raw if self._filter_dubious(e)] # dtype=object is necessary because this is", "filepath = self.DEFAULT_PATH data, labels = self._load_data_and_labels(filepath, labels_to_load, ignore_dubious) super().__init__(data=data,", "entry in raw_composition: try: element_name = entry[\"element\"] element_amount = entry[\"idealWeightPercent\"][\"value\"]", "units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_4_time = self._get_scalar_property( properties, \"Heat treatment 4", "isinstance(raw_composition, list): raise InvalidParameterError( expected=\"Chemical composition as a list\", got=raw_composition", "get a single scalar property. This calls _get_single_property and then", "the dataset. Returns: bool True if the composition contains an", "scalars = matching_prop[\"scalars\"] assert len(scalars) == 1 val = scalars[0][\"value\"]", "corresponds to an element. An entry is a dict with", "return composition_dict @staticmethod def _dict_values_to_float(d: dict) -> Tuple[dict, bool]: \"\"\"", "@staticmethod def _filter_dubious(entry: dict) -> bool: \"\"\" Determine whether or", "that the heat treatment step was not done, but there", "Optional[float] = None, ) -> float: \"\"\" A helper function", "the amount is imprecise. In any case, they only occur", "entry.get(\"composition\") if raw_composition is None or not isinstance(raw_composition, list): raise", "'Stress Rupture Time', 'Stress Rupture Stress', and 'Elongation'. If None,", "(but not exactly). Returns: dict Chemical composition as a dictionary", "List[dict]: \"\"\"Get composition in its raw form.\"\"\" raw_composition = entry.get(\"composition\")", "not used. There are 5 labels: ultimate tensile strength (MPa),", "self._get_scalar_property( properties, \"Heat treatment 4 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) total_heat_treatment_time", "are 2800 rows. The data have columns for composition (25", ") @staticmethod def _get_single_property( properties: List[dict], property_name: str, units: Optional[str]", "powder_processed = self._get_categorical_property( properties, \"Powder processed\", categories_dict=powder_processed_dict ) data_array =", "to the value of the desired property. \"\"\" category =", "heat treatment time\", units=\"hours\" ) max_heat_treatment_temp = self._get_scalar_property( properties, \"Max", "= NiSuperalloyDataset._extract_raw_composition(entry) composition_dict = NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float, exception_caught = NiSuperalloyDataset._dict_values_to_float( composition_dict", "len(matching_props) == 0: return default_value elif len(matching_props) > 1: raise", "lambda arg: params.sequence(arg, type_=str), ), ) ignore_dubious = params.boolean(ignore_dubious) filepath", "_load_data_and_labels( self, filepath: str, labels_to_load: Optional[List[str]] = None, ignore_dubious: bool", "The values are in percentage points, and add up to", "Elsevier, 2017. DOI 10.1016/j.matdes.2017.06.007 The dataset was downloaded from the", "a 'units' field. property_name: The name of the property to", "# dtype=object is necessary because this is a mixed-type array", "treatment 3 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_4_time = self._get_scalar_property( properties,", "self._get_scalar_property( properties, \"Heat treatment 1 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_2_time", "dicts, each of which is a single property. Each entry", "str = \"\" for element_name, element_amount in composition_dict_float.items(): if element_amount", "6 samples. Parameters: entry (dict): A json entry corresponding to", "as NaN. \"\"\" DEFAULT_PATH = os.path.split(os.path.realpath(__file__))[0] + \"/ni_superalloys_3.json.zip\" POWDER_PROCESSED_NO =", "case, they only occur in 6 samples. The trailing asterisk", "not present. Raises: InvalidParameterError: if the value cannot be expressed", "property_name: str, units: Optional[str] = None, default_value=None ): \"\"\" Helper", "a single key, 'value', pointing to a floating point number.", "labels_array.append(self._get_scalar_property(properties, label, default_value=None)) return labels_array @staticmethod def _parse_composition(raw_composition: List[dict]) ->", "categories_dict: Dict from the categorical property (string) to a unique", "strength (MPa), elongation (unitless), stress rupture stress (MPa), stress rupture", "An entry is a dict with an 'element' key and", "it, which occurs for 6 samples. Parameters: entry (dict): A", "path must point to a .zip file, instead got '{filepath}'\"", "labels to load. Returns: array Array of labels in this", "= \"\" if units is None else f\", 'units': {units}\"", "labels in a single row from the raw json. Parameters:", "POWDER_PROCESSED_NO = 0 POWDER_PROCESSED_YES = 1 def __init__( self, labels_to_load:", "if val is None: return None return float(val) except ValueError:", "Value to return if `property_name` is not present. Raises: InvalidParameterError:", "composition_str: str = \"\" for element_name, element_amount in composition_dict_float.items(): if", "elongation occur together in 898 rows, stress rupture stress and", "given by the keys in `categories_dict` Returns: int An integer", "The dataset was downloaded from the Citrination platform (https://citrination.com), dataset", "\"Heat treatment 3 Time\", units=\"hours\", default_value=0 ) heat_treatment_3_temp = self._get_scalar_property(", "x[-1] == \"*\": x = x[:-1] try: return float(x) except", "'units' field. property_name: The name of the property to get", "on is if the composition has an asterisk in it,", "labels=labels) def _load_data_and_labels( self, filepath: str, labels_to_load: Optional[List[str]] = None,", "Optional[str] = None, default_value: Optional[float] = None, ) -> float:", "Ni-superalloy dataset with specified labels. Parameters: labels_to_load (str or List[str]):", "95% and 105%. There are also three columns for a", "0: return default_value elif len(matching_props) > 1: raise InvalidParameterError( expected=f\"Only", "raw_composition = NiSuperalloyDataset._extract_raw_composition(entry) composition_dict = NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float, exception_caught = NiSuperalloyDataset._dict_values_to_float(", "single scalar property. This calls _get_single_property and then checks that", "entry corresponding to a row in the dataset. Returns: array", "def _parse_peculiar_amount(x: str) -> float: \"\"\" Deals with dataset-specific-peculiarities in", "name and a `scalars` field that is a list with", "points, and add up to ~100. Returns: str Chemical composition", "from .json file.\"\"\" raw = self._unzip_json_file(filepath) if ignore_dubious: raw =", "x[:-1] try: return float(x) except ValueError: raise InvalidParameterError(\"Amount as a", "the dataset. Returns: array Array of data in this row.", "categorical property (string) to a unique integer value. Raises: InvalidParameterError:", "contains an asterisk. \"\"\" raw_composition = NiSuperalloyDataset._extract_raw_composition(entry) composition_dict = NiSuperalloyDataset._parse_composition_as_dict(raw_composition)", "matching_props[0] try: scalars = matching_prop[\"scalars\"] assert len(scalars) == 1 val", "a dictionary of the form\\n\" \"{'element': <element name>,\" \"'idealWeightPercent': \"", "a dictionary's values to their floating point representations, if possible.", "a float Returns: float The value of the desired property.", "are interested in. \"\"\" if labels_to_load is None: labels_to_load =", "(https://citrination.com), dataset identifier #153493, Version 10. There are 2800 rows.", "Perhaps it denotes that the amount is imprecise. In any", "to `units`. default_value: Value to return if `property_name` is not", "heat treatment steps, the total time spent in heat treatment", "Returns: bool True if the composition contains an asterisk. \"\"\"", "self._parse_composition(raw_composition) properties = entry.get(\"properties\") if properties is None or not", "str, units: Optional[str] = None, default_value: Optional[float] = None, )", "'units': {units}\" raise InvalidParameterError( expected=\"Property as a dictionary of the", "None, ignore_dubious: bool = False, ): \"\"\"Load data and labels", "strength occurs in 1046 rows. 898+856+1046=2800, so every row has", "= None, ignore_dubious: bool = False ): \"\"\"Initialize Ni-superalloy dataset", "entry[\"category\"] == \"system.chemical\" raw_composition = NiSuperalloyDataset._extract_raw_composition(entry) composition: str = self._parse_composition(raw_composition)", "one entry with the 'name' field equal to `property_name`. units:", "labels_to_load = [ \"Yield Strength\", \"Ultimate Tensile Strength\", \"Stress Rupture", "not exactly). Returns: dict Chemical composition as a dictionary with", "\"Total heat treatment time\", units=\"hours\" ) max_heat_treatment_temp = self._get_scalar_property( properties,", "has an asterisk in it, which occurs for 6 samples.", "raise InvalidParameterError( expected=\"Element amount as a dictionary of the form\\n\"", "def _parse_json_data(self, entry: dict): \"\"\" Helper function to parse data", "heat_treatment_3_temp = self._get_scalar_property( properties, \"Heat treatment 3 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0", "float\", x) def _get_scalar_property( self, properties: List[dict], property_name: str, units:", "Rupture Stress', and 'Elongation'. If None, then all labels are", "Citrine Informatics. See class NiSuperalloyDataset for details. \"\"\" import os", "to 100%, but with about a dozen exceptions they always", ") matching_prop = matching_props[0] try: scalars = matching_prop[\"scalars\"] assert len(scalars)", "another dict with a single key, 'value', pointing to a", "<NAME>: Design of a nickel-base superalloy using a neural network,", "dtype=object) labels = np.array([self._parse_json_labels(e, labels_to_load) for e in raw], dtype=float)", "from the raw json. Parameters: entry (dict): A json entry", "was powder processed (0 or 1), whether it was pressure", "if the value cannot be expressed as a float Returns:", "if element_amount > 0: composition_str += element_name + str(element_amount) return", "default_value) if val is None: return None return float(val) except", "with a single key, 'value', pointing to a floating point", "dataset. Scientific Machine Learning Benchmark A benchmark of regression models", "is a single property. Each entry is expected to have", "add up to somewhere between 95% and 105%. There are", "list of possible categories as given by the keys in", "str) -> float: \"\"\" Deals with dataset-specific-peculiarities in composition amounts.", "Tuple[dict, bool]: \"\"\" Convert a dictionary's values to their floating", "properties = entry.get(\"properties\") if properties is None or not isinstance(properties,", "= [ \"Yield Strength\", \"Ultimate Tensile Strength\", \"Stress Rupture Time\",", "dictionaries, one for each property\", got=properties ) labels_array = []", "Tensile Strength', 'Stress Rupture Time', 'Stress Rupture Stress', and 'Elongation'.", "to somewhere between 95% and 105%. There are also three", "\"\" if units is None else f\", 'units': {units}\" raise", "List[dict], property_name: str, categories_dict: dict ) -> int: \"\"\" Helper", "default_value=0 ) heat_treatment_4_temp = self._get_scalar_property( properties, \"Heat treatment 4 Temperature\",", "it. Currently, the only thing filtered on is if the", "boolean flag indicating whether or not an Exception was caught", "def _get_categorical_property( self, properties: List[dict], property_name: str, categories_dict: dict )", "to get the value of. categories_dict: Dict from the categorical", ") heat_treatment_4_time = self._get_scalar_property( properties, \"Heat treatment 4 Time\", units=\"hours\",", "(MPa), stress rupture time (hours), and yield strength (MPa). Tensile", "6 samples. The trailing asterisk will be ignored. \"\"\" if", "None, ) -> float: \"\"\" A helper function to get", "whether or not a json entry has something questionable about", "treated (0 or 1), heat treatment time (hours) and temperature", "rupture stress (MPa), stress rupture time (hours), and yield strength", "somewhere between 95% and 105%. There are also three columns", "1 def __init__( self, labels_to_load: Optional[Union[str, List[str]]] = None, ignore_dubious:", "(0 or 1), heat treatment time (hours) and temperature (degrees", "that the amount is imprecise. In any case, they only", "List[dict]) -> str: \"\"\" Helper function to parse composition as", "Optional expected units string. default_value: Value to return if `property_name`", "* hours\" ) powder_processed_dict = {\"No\": self.POWDER_PROCESSED_NO, \"Yes\": self.POWDER_PROCESSED_YES} powder_processed", "yield strength occurs in 1046 rows. 898+856+1046=2800, so every row", "raw = json.load(fp) return raw @staticmethod def _extract_raw_composition(entry: dict) ->", "self.POWDER_PROCESSED_NO, \"Yes\": self.POWDER_PROCESSED_YES} powder_processed = self._get_categorical_property( properties, \"Powder processed\", categories_dict=powder_processed_dict", "(float and string) data = np.array([self._parse_json_data(e) for e in raw],", "questionable about them \"\"\" labels_to_load = params.optional_( labels_to_load, lambda arg:", "the property to get the value of. categories_dict: Dict from", "Version 10. There are 2800 rows. The data have columns", "e in raw if self._filter_dubious(e)] # dtype=object is necessary because", "\"{'element': <element name>,\" \"'idealWeightPercent': \" \"{'value': <element amount>}}\", got=entry, )", "assert matching_prop[\"units\"] == units except (KeyError, AssertionError): units_str = \"\"", "possible. Parameters: d: a dictionary Returns: dict, bool A modified", "not present. Raises: InvalidParameterError: if `properties` does not conform to", "The total compositions do not always add up to 100%,", "total_heat_treatment_time, max_heat_treatment_temp, area_under_heat_treatment_curve, powder_processed, ] return data_array def _parse_json_labels(self, entry:", "got=raw_composition ) return raw_composition @staticmethod def _filter_dubious(entry: dict) -> bool:", "the composition has an asterisk in it, which occurs for", "json entry corresponding to a row in the dataset. labels_to_load", "(dict): A json entry corresponding to a row in the", "is None else f\", 'units': {units}\" raise InvalidParameterError( expected=\"Property as", "treatment step (temperature, time, pressure), but since only 51 rows", "Time\", units=\"hours\", default_value=0 ) heat_treatment_2_temp = self._get_scalar_property( properties, \"Heat treatment", "single categorical property as an int. Parameters: properties: A list", "list of dictionaries, one for each property\", got=properties ) labels_array", "a single property. Parameters: properties: A list of dicts, each", "a nickel-base superalloy using a neural network, Materials & Design", "import params from smlb.tabular_data import TabularData class NiSuperalloyDataset(TabularData): \"\"\" Ni-Superalloy", "corresponding to a row in the dataset. Returns: array Array", "property to get the value of. units: Optional expected units", "is if the composition has an asterisk in it, which", "{property_name} should have a value \" f\"that can be expressed", "not in the expected list of possible categories as given", "a single categorical property as an int. Parameters: properties: A", "zf.open(unzipped_filename) as fp: raw = json.load(fp) return raw @staticmethod def", "The trailing asterisk will be ignored. \"\"\" if x[-1] ==", "property_name] if len(matching_props) == 0: return default_value elif len(matching_props) >", "corresponding to a row in the dataset. Returns: bool True", "import os import json import zipfile from typing import List,", "= self._unzip_json_file(filepath) if ignore_dubious: raw = [e for e in", "4 Time\", units=\"hours\", default_value=0 ) heat_treatment_4_temp = self._get_scalar_property( properties, \"Heat", "of the form\\n\" \"{'name': <property name>, 'scalars': \" \"[{'value': <property", "There are 5 labels: ultimate tensile strength (MPa), elongation (unitless),", "= os.path.basename(filepath) assert ( filename[-4:] == \".zip\" ), f\"File path", "from smlb.exceptions import InvalidParameterError from smlb.parameters import params from smlb.tabular_data", "self._get_scalar_property( properties, \"Area under heat treatment curve\", units=\"$^{\\\\circ}$C * hours\"", "in heat treatment (hours), the maximum heat treatment temperature (degrees", "the total time spent in heat treatment (hours), the maximum", "property. This calls _get_single_property and then checks that the result", "def __init__( self, labels_to_load: Optional[Union[str, List[str]]] = None, ignore_dubious: bool", "raw_composition = NiSuperalloyDataset._extract_raw_composition(entry) composition: str = self._parse_composition(raw_composition) properties = entry.get(\"properties\")", "= [prop for prop in properties if prop.get(\"name\") == property_name]", "property. property_name: The name of the property to get the", "done, but there are some missing values. The total time", "Helper function to parse labels in a single row from", "default_value=0 ) heat_treatment_2_time = self._get_scalar_property( properties, \"Heat treatment 2 Time\",", "except ValueError: exception_caught = True value_float = NiSuperalloyDataset._parse_peculiar_amount(value) d_copy[key] =", "is a dict with an 'element' key and an 'idealWeightPercent'", "area under the time-temperature curve (degrees Celcius * hours). A", "are present in at least one row), whether the alloy", "to a row in the dataset. Returns: bool True if", "trailing asterisk, e.g., '2*'. The meaning is unclear. Perhaps it", "one entry, a dict of the form {'value': <property value>}.", "dozen exceptions they always add up to somewhere between 95%", "to parse data in a single row from the raw", "10. There are 2800 rows. The data have columns for", "processed (0 or 1), whether it was pressure treated (0", "expected=\"Property as a dictionary of the form\\n\" \"{'name': <property name>,", "have exactly one entry with the 'name' field equal to", "return raw @staticmethod def _extract_raw_composition(entry: dict) -> List[dict]: \"\"\"Get composition", "Parameters: raw_composition (List[dict]): A list, each entry of which corresponds", "name of the property to get the value of. categories_dict:", "bool: \"\"\" Determine whether or not a json entry has", "and a boolean flag indicating whether or not an Exception", "_parse_composition_as_dict(raw_composition: List[dict]) -> dict: \"\"\" Helper function to parse composition", "== \".zip\" ), f\"File path must point to a .zip", "not done, but there are some missing values. The total", "its raw form.\"\"\" raw_composition = entry.get(\"composition\") if raw_composition is None", "dict) -> bool: \"\"\" Determine whether or not a json", "Parameters: d: a dictionary Returns: dict, bool A modified version", "total time spent in heat treatment (hours), the maximum heat", "name>, 'scalars': \" \"[{'value': <property value>}]\" + units_str + \"}\",", "<property value>}. It may also have a 'units' field. property_name:", "heat_treatment_2_temp = self._get_scalar_property( properties, \"Heat treatment 2 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0", "and the area under the time-temperature curve (degrees Celcius *", "since only 51 rows have non-zero entries, this information is", "heating steps. The total compositions do not always add up", "occur in 6 samples. The trailing asterisk will be ignored.", "> 1: raise InvalidParameterError( expected=f\"Only one entry in properties should", "entry in properties should have name\" f\" '{property_name}'\", got=properties, )", "str): \"\"\"Open and read zipped json file.\"\"\" filename = os.path.basename(filepath)", "self._get_single_property(properties, property_name, units, default_value) if val is None: return None", "_filter_dubious(entry: dict) -> bool: \"\"\" Determine whether or not a", "rows. The data have columns for composition (25 elements are", "return composition_str @staticmethod def _parse_composition_as_dict(raw_composition: List[dict]) -> dict: \"\"\" Helper", "heat treatment time (hours) and temperature (degrees Celcius) for up", "Dict from the categorical property (string) to a unique integer", "Tensile strength and elongation occur together in 898 rows, stress", "the value cannot be expressed as a float Returns: float", "dict, labels_to_load: Optional[List[str]] = None): \"\"\" Helper function to parse", "= self._get_scalar_property( properties, \"Heat treatment 4 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 )", "parse composition as a string. Parameters: raw_composition (List[dict]): A list,", "= self._get_single_property(properties, property_name) try: return categories_dict[category] except KeyError: raise InvalidParameterError(", "reliable than the individual heating steps. The total compositions do", "be expressed as a float\", got=properties, ) def _get_categorical_property( self,", "'Cu') and the weight percent is another dict with a", "the raw json. Parameters: entry (dict): A json entry corresponding", "default_value=None ): \"\"\" Helper function to get a single property.", "assert ( filename[-4:] == \".zip\" ), f\"File path must point", "= entry.get(\"properties\") if properties is None or not isinstance(properties, list):", "missing values. The total time and max temperature are generally", "entry: dict): \"\"\" Helper function to parse data in a", "for 6 samples. Parameters: entry (dict): A json entry corresponding", "downloaded from the Citrination platform (https://citrination.com), dataset identifier #153493, Version", "every row has exactly one output set. The other values", ") return not exception_caught def _parse_json_data(self, entry: dict): \"\"\" Helper", "in 6 samples. The trailing asterisk will be ignored. \"\"\"", "Celcius) for up to 4 heat treatment steps, the total", "import InvalidParameterError from smlb.parameters import params from smlb.tabular_data import TabularData", "which labels to load. Options are 'Yield Strength', 'Ultimate Tensile", "= np.array([self._parse_json_data(e) for e in raw], dtype=object) labels = np.array([self._parse_json_labels(e,", "\"Heat treatment 4 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) total_heat_treatment_time = self._get_scalar_property(", "treatment curve\", units=\"$^{\\\\circ}$C * hours\" ) powder_processed_dict = {\"No\": self.POWDER_PROCESSED_NO,", "value of. categories_dict: Dict from the categorical property (string) to", "self, labels_to_load: Optional[Union[str, List[str]]] = None, ignore_dubious: bool = False", "an 'element' key and an 'idealWeightPercent' key. The element is", "default_value=0 ) heat_treatment_3_temp = self._get_scalar_property( properties, \"Heat treatment 3 Temperature\",", "data in this row. \"\"\" assert entry[\"category\"] == \"system.chemical\" raw_composition", "\"\"\" Deals with dataset-specific-peculiarities in composition amounts. Some composition amounts", ") powder_processed_dict = {\"No\": self.POWDER_PROCESSED_NO, \"Yes\": self.POWDER_PROCESSED_YES} powder_processed = self._get_categorical_property(", "not to ignore samples that have something questionable about them", "and then checks that the result can be turned into", "function to parse labels in a single row from the", "in composition amounts. Some composition amounts have a trailing asterisk,", "at least one row), whether the alloy was powder processed", "value>}. It may also have a 'units' field. property_name: The", "if prop.get(\"name\") == property_name] if len(matching_props) == 0: return default_value", "\"*\": x = x[:-1] try: return float(x) except ValueError: raise", "<property name>, 'scalars': \" \"[{'value': <property value>}]\" + units_str +", "Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_4_time = self._get_scalar_property( properties, \"Heat treatment", "also have a 'units' field. property_name: The name of the", "Time', 'Stress Rupture Stress', and 'Elongation'. If None, then all", "have something questionable about them \"\"\" labels_to_load = params.optional_( labels_to_load,", "= False, ): \"\"\"Load data and labels from .json file.\"\"\"", "Optional list of labels to load. Returns: array Array of", "= False for key, value in d.items(): try: value_float =", "entry with the 'name' field equal to `property_name`. units: Optional", "Machine Learning Benchmark A benchmark of regression models in chem-", "temperature (degrees Celcius), and the area under the time-temperature curve", "\"/ni_superalloys_3.json.zip\" POWDER_PROCESSED_NO = 0 POWDER_PROCESSED_YES = 1 def __init__( self,", "point representations, if possible. Parameters: d: a dictionary Returns: dict,", "numpy as np from smlb.exceptions import InvalidParameterError from smlb.parameters import", "elements are present in at least one row), whether the", "exception_caught = False for key, value in d.items(): try: value_float", "corresponds to the property name and a `scalars` field that", "\"{'value': <element amount>}}\", got=entry, ) composition_dict[element_name] = element_amount return composition_dict", "a row in the dataset. Returns: bool True if the", "898+856+1046=2800, so every row has exactly one output set. The", "time and max temperature are generally more reliable than the", "list of labels to load. Returns: array Array of labels", "dict() exception_caught = False for key, value in d.items(): try:", "class NiSuperalloyDataset for details. \"\"\" import os import json import", "denotes that the amount is imprecise. In any case, they", "treatment (hours), the maximum heat treatment temperature (degrees Celcius), and", "dictionaries, one for each property\", got=properties ) heat_treatment_1_time = self._get_scalar_property(", "string. default_value: Value to return if `property_name` is not present.", "this is a mixed-type array (float and string) data =", "composition_dict = NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float, exception_caught = NiSuperalloyDataset._dict_values_to_float( composition_dict ) return", "form {'value': <property value>}. It may also have a 'units'", "int: \"\"\" Helper function to get a single categorical property", "float: \"\"\" Deals with dataset-specific-peculiarities in composition amounts. Some composition", "self.POWDER_PROCESSED_YES} powder_processed = self._get_categorical_property( properties, \"Powder processed\", categories_dict=powder_processed_dict ) data_array", "Helper function to get a single property. Parameters: properties: A", "in the array: {categories_dict.keys()}\", category ) @staticmethod def _get_single_property( properties:", "(str or List[str]): which labels to load. Options are 'Yield", "to ~100 (but not exactly). Returns: dict Chemical composition as", "'{filepath}'\" with zipfile.ZipFile(filepath) as zf: unzipped_filename = filename[:-4] with zf.open(unzipped_filename)", "one for each property\", got=properties ) labels_array = [] for", "= self._get_scalar_property( properties, \"Heat treatment 4 Time\", units=\"hours\", default_value=0 )", "= entry[\"element\"] element_amount = entry[\"idealWeightPercent\"][\"value\"] except KeyError: raise InvalidParameterError( expected=\"Element", "to parse labels in a single row from the raw", "properties, \"Area under heat treatment curve\", units=\"$^{\\\\circ}$C * hours\" )", "AssertionError): units_str = \"\" if units is None else f\",", "A list of dicts, each of which is a single", "into a float. Parameters: properties: A list of dicts, each", "NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float, _ = NiSuperalloyDataset._dict_values_to_float(composition_dict) composition_str: str = \"\" for", "element_amount return composition_dict @staticmethod def _dict_values_to_float(d: dict) -> Tuple[dict, bool]:", "raise InvalidParameterError( expected=f\"Property {property_name} should have a value \" f\"that", "benchmark of regression models in chem- and materials informatics. 2019,", "labels_to_load, lambda arg: params.any_( arg, params.string, lambda arg: params.sequence(arg, type_=str),", "is a list with one entry, a dict of the", "(e.g., 'Cu') and the weight percent is another dict with", "List[str]]] = None, ignore_dubious: bool = False ): \"\"\"Initialize Ni-superalloy", "expected=f\"Property {property_name} should have a value \" f\"that can be", "Optional[List[str]] = None): \"\"\" Helper function to parse labels in", "labels_to_load: Optional[List[str]] = None): \"\"\" Helper function to parse labels", "of `d`, and a boolean flag indicating whether or not", "exactly). Returns: dict Chemical composition as a dictionary with the", "raw_composition @staticmethod def _filter_dubious(entry: dict) -> bool: \"\"\" Determine whether", "composition: str = self._parse_composition(raw_composition) properties = entry.get(\"properties\") if properties is", "of dicts, each of which is a single property. Each", "= None, default_value=None ): \"\"\" Helper function to get a", "898 rows, stress rupture stress and time occur together in", "0: composition_str += element_name + str(element_amount) return composition_str @staticmethod def", "to a row in the dataset. Returns: array Array of", "@staticmethod def _extract_raw_composition(entry: dict) -> List[dict]: \"\"\"Get composition in its", "of dictionaries, one for each property\", got=properties ) labels_array =", "raw_composition: try: element_name = entry[\"element\"] element_amount = entry[\"idealWeightPercent\"][\"value\"] except KeyError:", "materials informatics. 2019, <NAME>, Citrine Informatics. See class NiSuperalloyDataset for", "an asterisk in it, which occurs for 6 samples. Parameters:", "parse data in a single row from the raw json.", "as values \"\"\" composition_dict = dict() for entry in raw_composition:", "correspond to `units`. default_value: Value to return if `property_name` is", "a boolean flag indicating whether or not an Exception was", "from typing import List, Optional, Tuple, Union import numpy as", "import TabularData class NiSuperalloyDataset(TabularData): \"\"\" Ni-Superalloy dataset. Based on: <NAME>,", "358-365, Elsevier, 2017. DOI 10.1016/j.matdes.2017.06.007 The dataset was downloaded from", "`property_name` is not present. Raises: InvalidParameterError: if the value cannot", "prop.get(\"name\") == property_name] if len(matching_props) == 0: return default_value elif", "heat_treatment_1_time = self._get_scalar_property( properties, \"Heat treatment 1 Time\", units=\"hours\", default_value=0", "def _dict_values_to_float(d: dict) -> Tuple[dict, bool]: \"\"\" Convert a dictionary's", "units_str = \"\" if units is None else f\", 'units':", "f\", 'units': {units}\" raise InvalidParameterError( expected=\"Property as a dictionary of", "None or not isinstance(raw_composition, list): raise InvalidParameterError( expected=\"Chemical composition as", "version of `d`, and a boolean flag indicating whether or", "default_value=0 ) heat_treatment_4_time = self._get_scalar_property( properties, \"Heat treatment 4 Time\",", "the Citrination platform (https://citrination.com), dataset identifier #153493, Version 10. There", "(MPa), elongation (unitless), stress rupture stress (MPa), stress rupture time", "and 'Elongation'. If None, then all labels are loaded. ignore_dubious:", "a float. Parameters: properties: A list of dicts, each of", "An integer that corresponds to the value of the desired", "InvalidParameterError( expected=\"A list of dictionaries, one for each property\", got=properties", "1 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_2_time = self._get_scalar_property( properties, \"Heat", ") heat_treatment_2_time = self._get_scalar_property( properties, \"Heat treatment 2 Time\", units=\"hours\",", "in at least one row), whether the alloy was powder", "entry has something questionable about it. Currently, the only thing", "label in labels_to_load: labels_array.append(self._get_scalar_property(properties, label, default_value=None)) return labels_array @staticmethod def", "a list with one entry, a dict of the form", "generally implies that the heat treatment step was not done,", "raise InvalidParameterError( expected=\"A list of dictionaries, one for each property\",", "f\"A value in the array: {categories_dict.keys()}\", category ) @staticmethod def", "flag indicating whether or not an Exception was caught \"\"\"", "raw form.\"\"\" raw_composition = entry.get(\"composition\") if raw_composition is None or", "with one entry, a dict of the form {'value': <property", "data, labels @staticmethod def _unzip_json_file(filepath: str): \"\"\"Open and read zipped", "has exactly one output set. The other values are denoted", "d_copy[key] = value_float return d_copy, exception_caught @staticmethod def _parse_peculiar_amount(x: str)", "The meaning is unclear. Perhaps it denotes that the amount", "a string (e.g., 'Cu') and the weight percent is another", "ValueError: raise InvalidParameterError(\"Amount as a float\", x) def _get_scalar_property( self,", "default_value=0 ) heat_treatment_3_time = self._get_scalar_property( properties, \"Heat treatment 3 Time\",", "compositions do not always add up to 100%, but with", ") heat_treatment_3_time = self._get_scalar_property( properties, \"Heat treatment 3 Time\", units=\"hours\",", "'name' field that corresponds to the property name and a", "for details. \"\"\" import os import json import zipfile from", "are 5 labels: ultimate tensile strength (MPa), elongation (unitless), stress", "( filename[-4:] == \".zip\" ), f\"File path must point to", "columns for composition (25 elements are present in at least", "hours\" ) powder_processed_dict = {\"No\": self.POWDER_PROCESSED_NO, \"Yes\": self.POWDER_PROCESSED_YES} powder_processed =", "params.sequence(arg, type_=str), ), ) ignore_dubious = params.boolean(ignore_dubious) filepath = self.DEFAULT_PATH", "Time\", units=\"hours\", default_value=0 ) heat_treatment_3_temp = self._get_scalar_property( properties, \"Heat treatment", "single property. property_name: The name of the property to get", "composition as a dictionary. Parameters: raw_composition (List[dict]): A list, each", "None, ignore_dubious: bool = False ): \"\"\"Initialize Ni-superalloy dataset with", ".zip file, instead got '{filepath}'\" with zipfile.ZipFile(filepath) as zf: unzipped_filename", "units=\"$^{\\\\circ}$C\" ) area_under_heat_treatment_curve = self._get_scalar_property( properties, \"Area under heat treatment", "property to get the value of. categories_dict: Dict from the", "to a unique integer value. Raises: InvalidParameterError: if the value", "in 856 rows, and yield strength occurs in 1046 rows.", "(KeyError, AssertionError): units_str = \"\" if units is None else", "area_under_heat_treatment_curve, powder_processed, ] return data_array def _parse_json_labels(self, entry: dict, labels_to_load:", "return None return float(val) except ValueError: raise InvalidParameterError( expected=f\"Property {property_name}", "labels_array = [] for label in labels_to_load: labels_array.append(self._get_scalar_property(properties, label, default_value=None))", "-> float: \"\"\" Deals with dataset-specific-peculiarities in composition amounts. Some", "a dictionary with the elements as keys and their raw", "InvalidParameterError: if the value is not in the expected list", "None or not isinstance(properties, list): raise InvalidParameterError( expected=\"A list of", "a dictionary. Parameters: raw_composition (List[dict]): A list, each entry of", "The other values are denoted as NaN. \"\"\" DEFAULT_PATH =", "composition_dict_float, exception_caught = NiSuperalloyDataset._dict_values_to_float( composition_dict ) return not exception_caught def", "of. categories_dict: Dict from the categorical property (string) to a", "The name of the property to get the value of.", "in percentage points, and add up to ~100 (but not", "expressed as a float\", got=properties, ) def _get_categorical_property( self, properties:", "\"Max Heat Treatment Temperature\", units=\"$^{\\\\circ}$C\" ) area_under_heat_treatment_curve = self._get_scalar_property( properties,", "self, properties: List[dict], property_name: str, units: Optional[str] = None, default_value:", "2 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_3_time = self._get_scalar_property( properties, \"Heat", "property `property_name` \"\"\" matching_props = [prop for prop in properties", "always add up to 100%, but with about a dozen", "the area under the time-temperature curve (degrees Celcius * hours).", "stress rupture time (hours), and yield strength (MPa). Tensile strength", "Time\", units=\"hours\", default_value=0 ) heat_treatment_1_temp = self._get_scalar_property( properties, \"Heat treatment", "max_heat_treatment_temp, area_under_heat_treatment_curve, powder_processed, ] return data_array def _parse_json_labels(self, entry: dict,", "_extract_raw_composition(entry: dict) -> List[dict]: \"\"\"Get composition in its raw form.\"\"\"", "raw json. Parameters: entry (dict): A json entry corresponding to", "of. `properties` is expected to have exactly one entry with", "dict with a single key, 'value', pointing to a floating", "that the result can be turned into a float. Parameters:", "it was pressure treated (0 or 1), heat treatment time", "of which corresponds to an element. An entry is a", "and an 'idealWeightPercent' key. The element is a string (e.g.,", "with the 'name' field equal to `property_name`. units: Optional expected", "List[dict], property_name: str, units: Optional[str] = None, default_value: Optional[float] =", "of which is a single property. Each entry is expected", "whether or not to ignore samples that have something questionable", "to load. Returns: array Array of labels in this row", "element. An entry is a dict with an 'element' key", "have a value \" f\"that can be expressed as a", "Returns: int An integer that corresponds to the value of", "self._load_data_and_labels(filepath, labels_to_load, ignore_dubious) super().__init__(data=data, labels=labels) def _load_data_and_labels( self, filepath: str,", "must point to a .zip file, instead got '{filepath}'\" with", "raise InvalidParameterError( expected=\"Chemical composition as a list\", got=raw_composition ) return", "treatment temperature (degrees Celcius), and the area under the time-temperature", "rupture stress and time occur together in 856 rows, and", "have name\" f\" '{property_name}'\", got=properties, ) matching_prop = matching_props[0] try:", "zipfile from typing import List, Optional, Tuple, Union import numpy", "= params.optional_( labels_to_load, lambda arg: params.any_( arg, params.string, lambda arg:", "is necessary because this is a mixed-type array (float and", "cannot be expressed as a float Returns: float The value", "composition_dict[element_name] = element_amount return composition_dict @staticmethod def _dict_values_to_float(d: dict) ->", "dict ) -> int: \"\"\" Helper function to get a", "of the desired property. \"\"\" try: val = self._get_single_property(properties, property_name,", "array Array of labels in this row that we are", "or not a json entry has something questionable about it.", "values to their floating point representations, if possible. Parameters: d:", "is expected to have exactly one entry with the 'name'", "Heat Treatment Temperature\", units=\"$^{\\\\circ}$C\" ) area_under_heat_treatment_curve = self._get_scalar_property( properties, \"Area", "Chemical composition as a dictionary with the elements as keys", "yield strength (MPa). Tensile strength and elongation occur together in", "int An integer that corresponds to the value of the", "units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_2_time = self._get_scalar_property( properties, \"Heat treatment 2", "the property `property_name` \"\"\" matching_props = [prop for prop in", "form\\n\" \"{'name': <property name>, 'scalars': \" \"[{'value': <property value>}]\" +", "of labels to load. Returns: array Array of labels in", "three columns for a pressure treatment step (temperature, time, pressure),", "self._get_categorical_property( properties, \"Powder processed\", categories_dict=powder_processed_dict ) data_array = [ composition,", "return if `property_name` is not present. Raises: InvalidParameterError: if `properties`", "ultimate tensile strength (MPa), elongation (unitless), stress rupture stress (MPa),", "self._filter_dubious(e)] # dtype=object is necessary because this is a mixed-type", "f\"that can be expressed as a float\", got=properties, ) def", "json entry corresponding to a row in the dataset. Returns:", "True if the composition contains an asterisk. \"\"\" raw_composition =", "whether or not an Exception was caught \"\"\" d_copy =", "Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_3_time = self._get_scalar_property( properties, \"Heat treatment", "single key, 'value', pointing to a floating point number. The", "dictionary's values to their floating point representations, if possible. Parameters:", "categorical property as an int. Parameters: properties: A list of", "properties, \"Heat treatment 1 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_2_time =", "d.items(): try: value_float = float(value) except ValueError: exception_caught = True", "powder processed (0 or 1), whether it was pressure treated", "Learning Benchmark A benchmark of regression models in chem- and", "nickel-base superalloy using a neural network, Materials & Design 131:", "Optional expected value of 'units' field. If specified, then there", "it denotes that the amount is imprecise. In any case,", "of regression models in chem- and materials informatics. 2019, <NAME>,", "as zf: unzipped_filename = filename[:-4] with zf.open(unzipped_filename) as fp: raw", "to ~100. Returns: str Chemical composition as string, e.g. 'Al5.5Ni94.0W0.5'", "occurs in 1046 rows. 898+856+1046=2800, so every row has exactly", "is a string (e.g., 'Cu') and the weight percent is", "asterisk. \"\"\" raw_composition = NiSuperalloyDataset._extract_raw_composition(entry) composition_dict = NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float, exception_caught", "one row), whether the alloy was powder processed (0 or", "Strength\", \"Stress Rupture Time\", \"Stress Rupture Stress\", \"Elongation\", ] properties", "= json.load(fp) return raw @staticmethod def _extract_raw_composition(entry: dict) -> List[dict]:", "def _extract_raw_composition(entry: dict) -> List[dict]: \"\"\"Get composition in its raw", "`d`, and a boolean flag indicating whether or not an", ") ignore_dubious = params.boolean(ignore_dubious) filepath = self.DEFAULT_PATH data, labels =", "something questionable about it. Currently, the only thing filtered on", "isinstance(properties, list): raise InvalidParameterError( expected=\"A list of dictionaries, one for", "heat treatment step was not done, but there are some", "None, then all labels are loaded. ignore_dubious: whether or not", "to have exactly one entry with the 'name' field equal", "points, and add up to ~100 (but not exactly). Returns:", "dictionary. Parameters: raw_composition (List[dict]): A list, each entry of which", "raw = self._unzip_json_file(filepath) if ignore_dubious: raw = [e for e", "\"\"\"Ni-Superalloy dataset. Scientific Machine Learning Benchmark A benchmark of regression", "== 1 val = scalars[0][\"value\"] if units is not None:", "self._unzip_json_file(filepath) if ignore_dubious: raw = [e for e in raw", "up to somewhere between 95% and 105%. There are also", "total compositions do not always add up to 100%, but", "only thing filtered on is if the composition has an", "key, value in d.items(): try: value_float = float(value) except ValueError:", "field equal to `property_name`. units: Optional expected value of 'units'", "filename[-4:] == \".zip\" ), f\"File path must point to a", "and add up to ~100 (but not exactly). Returns: dict", "labels from .json file.\"\"\" raw = self._unzip_json_file(filepath) if ignore_dubious: raw", "properties, \"Heat treatment 3 Time\", units=\"hours\", default_value=0 ) heat_treatment_3_temp =", "'name' field equal to `property_name`. units: Optional expected value of", "point to a .zip file, instead got '{filepath}'\" with zipfile.ZipFile(filepath)", "expected to have a 'name' field that corresponds to the", "assert entry[\"category\"] == \"system.chemical\" raw_composition = NiSuperalloyDataset._extract_raw_composition(entry) composition: str =", "than the individual heating steps. The total compositions do not", "load. Options are 'Yield Strength', 'Ultimate Tensile Strength', 'Stress Rupture", "NiSuperalloyDataset._dict_values_to_float(composition_dict) composition_str: str = \"\" for element_name, element_amount in composition_dict_float.items():", "the 'name' field equal to `property_name`. units: Optional expected value", "self._get_scalar_property( properties, \"Heat treatment 2 Time\", units=\"hours\", default_value=0 ) heat_treatment_2_temp", "they only occur in 6 samples. The trailing asterisk will", "len(scalars) == 1 val = scalars[0][\"value\"] if units is not", "is not None: assert matching_prop[\"units\"] == units except (KeyError, AssertionError):", "#153493, Version 10. There are 2800 rows. The data have", "composition_str @staticmethod def _parse_composition_as_dict(raw_composition: List[dict]) -> dict: \"\"\" Helper function", "field that corresponds to the property name and a `scalars`", "labels_to_load (str or List[str]): which labels to load. Options are", "Scientific Machine Learning Benchmark A benchmark of regression models in", "False ): \"\"\"Initialize Ni-superalloy dataset with specified labels. Parameters: labels_to_load", "Strength', 'Ultimate Tensile Strength', 'Stress Rupture Time', 'Stress Rupture Stress',", "list with one entry, a dict of the form {'value':", "and temperature (degrees Celcius) for up to 4 heat treatment", "data in a single row from the raw json. Parameters:", "2 Time\", units=\"hours\", default_value=0 ) heat_treatment_2_temp = self._get_scalar_property( properties, \"Heat", "of the property to get the value of. `properties` is", "_get_single_property and then checks that the result can be turned", "> 0: composition_str += element_name + str(element_amount) return composition_str @staticmethod", "), f\"File path must point to a .zip file, instead", "using a neural network, Materials & Design 131: 358-365, Elsevier,", "an int. Parameters: properties: A list of dicts, each of", "dictionary of the form\\n\" \"{'element': <element name>,\" \"'idealWeightPercent': \" \"{'value':", "@staticmethod def _unzip_json_file(filepath: str): \"\"\"Open and read zipped json file.\"\"\"", "self.DEFAULT_PATH data, labels = self._load_data_and_labels(filepath, labels_to_load, ignore_dubious) super().__init__(data=data, labels=labels) def", "(hours), and yield strength (MPa). Tensile strength and elongation occur", "= \"\" for element_name, element_amount in composition_dict_float.items(): if element_amount >", "questionable about it. Currently, the only thing filtered on is", "for a pressure treatment step (temperature, time, pressure), but since", "(unitless), stress rupture stress (MPa), stress rupture time (hours), and", "entry.get(\"properties\") if properties is None or not isinstance(properties, list): raise", "are some missing values. The total time and max temperature", "= self._get_scalar_property( properties, \"Area under heat treatment curve\", units=\"$^{\\\\circ}$C *", "Helper function to get a single categorical property as an", "= 1 def __init__( self, labels_to_load: Optional[Union[str, List[str]]] = None,", "Strength\", \"Ultimate Tensile Strength\", \"Stress Rupture Time\", \"Stress Rupture Stress\",", "None: return None return float(val) except ValueError: raise InvalidParameterError( expected=f\"Property", "in composition_dict_float.items(): if element_amount > 0: composition_str += element_name +", "= entry[\"idealWeightPercent\"][\"value\"] except KeyError: raise InvalidParameterError( expected=\"Element amount as a", "read zipped json file.\"\"\" filename = os.path.basename(filepath) assert ( filename[-4:]", "ignore_dubious: whether or not to ignore samples that have something", "other values are denoted as NaN. \"\"\" DEFAULT_PATH = os.path.split(os.path.realpath(__file__))[0]", "each of which is a single property. property_name: The name", "json file.\"\"\" filename = os.path.basename(filepath) assert ( filename[-4:] == \".zip\"", "treatment 4 Time\", units=\"hours\", default_value=0 ) heat_treatment_4_temp = self._get_scalar_property( properties,", "from the Citrination platform (https://citrination.com), dataset identifier #153493, Version 10.", "mixed-type array (float and string) data = np.array([self._parse_json_data(e) for e", "function to get a single property. Parameters: properties: A list", "a single property. Each entry is expected to have a", "properties: List[dict], property_name: str, units: Optional[str] = None, default_value: Optional[float]", "def _load_data_and_labels( self, filepath: str, labels_to_load: Optional[List[str]] = None, ignore_dubious:", "= True value_float = NiSuperalloyDataset._parse_peculiar_amount(value) d_copy[key] = value_float return d_copy,", "powder_processed_dict = {\"No\": self.POWDER_PROCESSED_NO, \"Yes\": self.POWDER_PROCESSED_YES} powder_processed = self._get_categorical_property( properties,", "does not conform to the expected structure Returns: The value", "return raw_composition @staticmethod def _filter_dubious(entry: dict) -> bool: \"\"\" Determine", "= [] for label in labels_to_load: labels_array.append(self._get_scalar_property(properties, label, default_value=None)) return", "Helper function to parse composition as a dictionary. Parameters: raw_composition", "because this is a mixed-type array (float and string) data", "= filename[:-4] with zf.open(unzipped_filename) as fp: raw = json.load(fp) return", "\"\"\"Open and read zipped json file.\"\"\" filename = os.path.basename(filepath) assert", "a value \" f\"that can be expressed as a float\",", "'units' field. If specified, then there must be a 'units'", "are denoted as NaN. \"\"\" DEFAULT_PATH = os.path.split(os.path.realpath(__file__))[0] + \"/ni_superalloys_3.json.zip\"", "property as an int. Parameters: properties: A list of dicts,", "if the composition contains an asterisk. \"\"\" raw_composition = NiSuperalloyDataset._extract_raw_composition(entry)", "\"Heat treatment 2 Time\", units=\"hours\", default_value=0 ) heat_treatment_2_temp = self._get_scalar_property(", "properties, \"Heat treatment 3 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_4_time =", "as a float\", x) def _get_scalar_property( self, properties: List[dict], property_name:", "[ \"Yield Strength\", \"Ultimate Tensile Strength\", \"Stress Rupture Time\", \"Stress", "network, Materials & Design 131: 358-365, Elsevier, 2017. DOI 10.1016/j.matdes.2017.06.007", "-> int: \"\"\" Helper function to get a single categorical", "was downloaded from the Citrination platform (https://citrination.com), dataset identifier #153493,", "the value of. `properties` is expected to have exactly one", "form.\"\"\" raw_composition = entry.get(\"composition\") if raw_composition is None or not", "def _parse_json_labels(self, entry: dict, labels_to_load: Optional[List[str]] = None): \"\"\" Helper", "values are in percentage points, and add up to ~100", "dictionary Returns: dict, bool A modified version of `d`, and", "): \"\"\"Initialize Ni-superalloy dataset with specified labels. Parameters: labels_to_load (str", "function to parse composition as a string. Parameters: raw_composition (List[dict]):", "up to ~100. Returns: str Chemical composition as string, e.g.", "treatment steps, the total time spent in heat treatment (hours),", "and yield strength occurs in 1046 rows. 898+856+1046=2800, so every", "element_name = entry[\"element\"] element_amount = entry[\"idealWeightPercent\"][\"value\"] except KeyError: raise InvalidParameterError(", "have non-zero entries, this information is not used. There are", "and materials informatics. 2019, <NAME>, Citrine Informatics. See class NiSuperalloyDataset", "or 1), heat treatment time (hours) and temperature (degrees Celcius)", "was pressure treated (0 or 1), heat treatment time (hours)", "value of the desired property. \"\"\" try: val = self._get_single_property(properties,", "identifier #153493, Version 10. There are 2800 rows. The data", "str: \"\"\" Helper function to parse composition as a string.", "as fp: raw = json.load(fp) return raw @staticmethod def _extract_raw_composition(entry:", "only occur in 6 samples. The trailing asterisk will be", "Optional[List[str]] = None, ignore_dubious: bool = False, ): \"\"\"Load data", "total_heat_treatment_time = self._get_scalar_property( properties, \"Total heat treatment time\", units=\"hours\" )", "return labels_array @staticmethod def _parse_composition(raw_composition: List[dict]) -> str: \"\"\" Helper", "1 val = scalars[0][\"value\"] if units is not None: assert", ") heat_treatment_3_temp = self._get_scalar_property( properties, \"Heat treatment 3 Temperature\", units=\"$^{\\\\circ}$C\",", "total time and max temperature are generally more reliable than", "Strength', 'Stress Rupture Time', 'Stress Rupture Stress', and 'Elongation'. If", "each of which is a single property. Each entry is", "Stress', and 'Elongation'. If None, then all labels are loaded.", "then checks that the result can be turned into a", "ignore_dubious: raw = [e for e in raw if self._filter_dubious(e)]", "labels. Parameters: labels_to_load (str or List[str]): which labels to load.", ") labels_array = [] for label in labels_to_load: labels_array.append(self._get_scalar_property(properties, label,", "data and labels from .json file.\"\"\" raw = self._unzip_json_file(filepath) if", "heat_treatment_3_temp, heat_treatment_4_time, heat_treatment_4_temp, total_heat_treatment_time, max_heat_treatment_temp, area_under_heat_treatment_curve, powder_processed, ] return data_array", ") heat_treatment_1_temp = self._get_scalar_property( properties, \"Heat treatment 1 Temperature\", units=\"$^{\\\\circ}$C\",", "= self.DEFAULT_PATH data, labels = self._load_data_and_labels(filepath, labels_to_load, ignore_dubious) super().__init__(data=data, labels=labels)", "is unclear. Perhaps it denotes that the amount is imprecise.", "params.any_( arg, params.string, lambda arg: params.sequence(arg, type_=str), ), ) ignore_dubious", "if properties is None or not isinstance(properties, list): raise InvalidParameterError(", "the value of. categories_dict: Dict from the categorical property (string)", "dataset. labels_to_load (List[str]): Optional list of labels to load. Returns:", "dict Chemical composition as a dictionary with the elements as", "for composition (25 elements are present in at least one", "entry of which corresponds to an element. An entry is", "The element is a string (e.g., 'Cu') and the weight", "+= element_name + str(element_amount) return composition_str @staticmethod def _parse_composition_as_dict(raw_composition: List[dict])", "desired property. \"\"\" category = self._get_single_property(properties, property_name) try: return categories_dict[category]", "asterisk in it, which occurs for 6 samples. Parameters: entry", "If None, then all labels are loaded. ignore_dubious: whether or", "= self._get_scalar_property( properties, \"Heat treatment 1 Time\", units=\"hours\", default_value=0 )", "float: \"\"\" A helper function to get a single scalar", "in properties if prop.get(\"name\") == property_name] if len(matching_props) == 0:", "default_value: Value to return if `property_name` is not present. Raises:", "'2*'. The meaning is unclear. Perhaps it denotes that the", "non-zero entries, this information is not used. There are 5", "a float\", x) def _get_scalar_property( self, properties: List[dict], property_name: str,", "composition contains an asterisk. \"\"\" raw_composition = NiSuperalloyDataset._extract_raw_composition(entry) composition_dict =", "None, default_value=None ): \"\"\" Helper function to get a single", "value is not in the expected list of possible categories", "are 'Yield Strength', 'Ultimate Tensile Strength', 'Stress Rupture Time', 'Stress", "platform (https://citrination.com), dataset identifier #153493, Version 10. There are 2800", "samples. The trailing asterisk will be ignored. \"\"\" if x[-1]", "in raw], dtype=object) labels = np.array([self._parse_json_labels(e, labels_to_load) for e in", "fp: raw = json.load(fp) return raw @staticmethod def _extract_raw_composition(entry: dict)", "@staticmethod def _parse_peculiar_amount(x: str) -> float: \"\"\" Deals with dataset-specific-peculiarities", "value of the property `property_name` \"\"\" matching_props = [prop for", "entry (dict): A json entry corresponding to a row in", "_get_categorical_property( self, properties: List[dict], property_name: str, categories_dict: dict ) ->", "except ValueError: raise InvalidParameterError(\"Amount as a float\", x) def _get_scalar_property(", "labels = np.array([self._parse_json_labels(e, labels_to_load) for e in raw], dtype=float) return", "function to get a single categorical property as an int.", "neural network, Materials & Design 131: 358-365, Elsevier, 2017. DOI", "the result can be turned into a float. Parameters: properties:", "POWDER_PROCESSED_YES = 1 def __init__( self, labels_to_load: Optional[Union[str, List[str]]] =", "0 POWDER_PROCESSED_YES = 1 def __init__( self, labels_to_load: Optional[Union[str, List[str]]]", "labels_to_load is None: labels_to_load = [ \"Yield Strength\", \"Ultimate Tensile", "to a floating point number. The values are in percentage", "dataset was downloaded from the Citrination platform (https://citrination.com), dataset identifier", "In any case, they only occur in 6 samples. The", "row in the dataset. Returns: array Array of data in", "of a nickel-base superalloy using a neural network, Materials &", "1), heat treatment time (hours) and temperature (degrees Celcius) for", "+ str(element_amount) return composition_str @staticmethod def _parse_composition_as_dict(raw_composition: List[dict]) -> dict:", "desired property. \"\"\" try: val = self._get_single_property(properties, property_name, units, default_value)", "floating point number. The values are in percentage points, and", "properties, \"Total heat treatment time\", units=\"hours\" ) max_heat_treatment_temp = self._get_scalar_property(", "elements as keys and their raw amounts as values \"\"\"", "131: 358-365, Elsevier, 2017. DOI 10.1016/j.matdes.2017.06.007 The dataset was downloaded", "return d_copy, exception_caught @staticmethod def _parse_peculiar_amount(x: str) -> float: \"\"\"", "= matching_props[0] try: scalars = matching_prop[\"scalars\"] assert len(scalars) == 1", "default_value=0 ) heat_treatment_1_temp = self._get_scalar_property( properties, \"Heat treatment 1 Temperature\",", "self._get_scalar_property( properties, \"Max Heat Treatment Temperature\", units=\"$^{\\\\circ}$C\" ) area_under_heat_treatment_curve =", "properties, \"Heat treatment 1 Time\", units=\"hours\", default_value=0 ) heat_treatment_1_temp =", "zf: unzipped_filename = filename[:-4] with zf.open(unzipped_filename) as fp: raw =", "which corresponds to an element. An entry is a dict", "data = np.array([self._parse_json_data(e) for e in raw], dtype=object) labels =", "time\", units=\"hours\" ) max_heat_treatment_temp = self._get_scalar_property( properties, \"Max Heat Treatment", "== 0: return default_value elif len(matching_props) > 1: raise InvalidParameterError(", "<NAME>, <NAME>: Design of a nickel-base superalloy using a neural", "treatment time (hours) and temperature (degrees Celcius) for up to", "import json import zipfile from typing import List, Optional, Tuple,", "the property name and a `scalars` field that is a", "floating point representations, if possible. Parameters: d: a dictionary Returns:", "to get the value of. units: Optional expected units string.", "the value of the desired property. \"\"\" category = self._get_single_property(properties,", "label, default_value=None)) return labels_array @staticmethod def _parse_composition(raw_composition: List[dict]) -> str:", "not conform to the expected structure Returns: The value of", "not exception_caught def _parse_json_data(self, entry: dict): \"\"\" Helper function to", "processed\", categories_dict=powder_processed_dict ) data_array = [ composition, heat_treatment_1_time, heat_treatment_1_temp, heat_treatment_2_time,", "alloy was powder processed (0 or 1), whether it was", "property. \"\"\" try: val = self._get_single_property(properties, property_name, units, default_value) if", "\"\"\" Convert a dictionary's values to their floating point representations,", "modified version of `d`, and a boolean flag indicating whether", ") heat_treatment_2_temp = self._get_scalar_property( properties, \"Heat treatment 2 Temperature\", units=\"$^{\\\\circ}$C\",", "always add up to somewhere between 95% and 105%. There", "properties, \"Heat treatment 4 Time\", units=\"hours\", default_value=0 ) heat_treatment_4_temp =", "A list, each entry of which corresponds to an element.", "\"\"\" Helper function to get a single categorical property as", "occur together in 856 rows, and yield strength occurs in", "some missing values. The total time and max temperature are", "heat_treatment_4_temp, total_heat_treatment_time, max_heat_treatment_temp, area_under_heat_treatment_curve, powder_processed, ] return data_array def _parse_json_labels(self,", "return data, labels @staticmethod def _unzip_json_file(filepath: str): \"\"\"Open and read", "(List[dict]): A list, each entry of which corresponds to an", "and read zipped json file.\"\"\" filename = os.path.basename(filepath) assert (", "categories_dict[category] except KeyError: raise InvalidParameterError( f\"A value in the array:", "time-temperature curve (degrees Celcius * hours). A value of 0", "= 0 POWDER_PROCESSED_YES = 1 def __init__( self, labels_to_load: Optional[Union[str,", "denoted as NaN. \"\"\" DEFAULT_PATH = os.path.split(os.path.realpath(__file__))[0] + \"/ni_superalloys_3.json.zip\" POWDER_PROCESSED_NO", "There are 2800 rows. The data have columns for composition", "value of the desired property. \"\"\" category = self._get_single_property(properties, property_name)", "a 'units' field and its value must correspond to `units`.", "is not present. Raises: InvalidParameterError: if the value cannot be", "properties: List[dict], property_name: str, units: Optional[str] = None, default_value=None ):", "in raw if self._filter_dubious(e)] # dtype=object is necessary because this", "labels_to_load: labels_array.append(self._get_scalar_property(properties, label, default_value=None)) return labels_array @staticmethod def _parse_composition(raw_composition: List[dict])", "dataset with specified labels. Parameters: labels_to_load (str or List[str]): which", "\"\"\" composition_dict = NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float, _ = NiSuperalloyDataset._dict_values_to_float(composition_dict) composition_str: str", "their raw amounts as values \"\"\" composition_dict = dict() for", "with about a dozen exceptions they always add up to", "default_value=0 ) heat_treatment_2_temp = self._get_scalar_property( properties, \"Heat treatment 2 Temperature\",", "def _get_single_property( properties: List[dict], property_name: str, units: Optional[str] = None,", "Treatment Temperature\", units=\"$^{\\\\circ}$C\" ) area_under_heat_treatment_curve = self._get_scalar_property( properties, \"Area under", "time, pressure), but since only 51 rows have non-zero entries,", "= float(value) except ValueError: exception_caught = True value_float = NiSuperalloyDataset._parse_peculiar_amount(value)", "in. \"\"\" if labels_to_load is None: labels_to_load = [ \"Yield", "InvalidParameterError( expected=\"Chemical composition as a list\", got=raw_composition ) return raw_composition", "element_amount in composition_dict_float.items(): if element_amount > 0: composition_str += element_name", "for e in raw], dtype=float) return data, labels @staticmethod def", "\"Yes\": self.POWDER_PROCESSED_YES} powder_processed = self._get_categorical_property( properties, \"Powder processed\", categories_dict=powder_processed_dict )", "List, Optional, Tuple, Union import numpy as np from smlb.exceptions", "got=properties, ) matching_prop = matching_props[0] try: scalars = matching_prop[\"scalars\"] assert", "<NAME>, <NAME>, <NAME>: Design of a nickel-base superalloy using a", "'Stress Rupture Stress', and 'Elongation'. If None, then all labels", "in this row that we are interested in. \"\"\" if", "np.array([self._parse_json_data(e) for e in raw], dtype=object) labels = np.array([self._parse_json_labels(e, labels_to_load)", "from the categorical property (string) to a unique integer value.", "helper function to get a single scalar property. This calls", "\"\"\" Helper function to parse composition as a dictionary. Parameters:", "corresponding to a row in the dataset. labels_to_load (List[str]): Optional", "details. \"\"\" import os import json import zipfile from typing", "is None: return None return float(val) except ValueError: raise InvalidParameterError(", "present. Raises: InvalidParameterError: if the value cannot be expressed as", "the individual heating steps. The total compositions do not always", "an asterisk. \"\"\" raw_composition = NiSuperalloyDataset._extract_raw_composition(entry) composition_dict = NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float,", "trailing asterisk will be ignored. \"\"\" if x[-1] == \"*\":", "Returns: array Array of data in this row. \"\"\" assert", "NiSuperalloyDataset for details. \"\"\" import os import json import zipfile", "this row. \"\"\" assert entry[\"category\"] == \"system.chemical\" raw_composition = NiSuperalloyDataset._extract_raw_composition(entry)", "= dict() for entry in raw_composition: try: element_name = entry[\"element\"]", "maximum heat treatment temperature (degrees Celcius), and the area under", "as string, e.g. 'Al5.5Ni94.0W0.5' \"\"\" composition_dict = NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float, _", "default_value=0 ) total_heat_treatment_time = self._get_scalar_property( properties, \"Total heat treatment time\",", "entry is expected to have a 'name' field that corresponds", "is expected to have a 'name' field that corresponds to", "file.\"\"\" raw = self._unzip_json_file(filepath) if ignore_dubious: raw = [e for", "A helper function to get a single scalar property. This", "bool A modified version of `d`, and a boolean flag", "str, categories_dict: dict ) -> int: \"\"\" Helper function to", "= NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float, exception_caught = NiSuperalloyDataset._dict_values_to_float( composition_dict ) return not", "zipfile.ZipFile(filepath) as zf: unzipped_filename = filename[:-4] with zf.open(unzipped_filename) as fp:", "got=entry, ) composition_dict[element_name] = element_amount return composition_dict @staticmethod def _dict_values_to_float(d:", "of the property to get the value of. units: Optional", "return data_array def _parse_json_labels(self, entry: dict, labels_to_load: Optional[List[str]] = None):", "percentage points, and add up to ~100. Returns: str Chemical", "array (float and string) data = np.array([self._parse_json_data(e) for e in", "labels_array @staticmethod def _parse_composition(raw_composition: List[dict]) -> str: \"\"\" Helper function", "type_=str), ), ) ignore_dubious = params.boolean(ignore_dubious) filepath = self.DEFAULT_PATH data,", "the only thing filtered on is if the composition has", "NiSuperalloyDataset._dict_values_to_float( composition_dict ) return not exception_caught def _parse_json_data(self, entry: dict):", "asterisk will be ignored. \"\"\" if x[-1] == \"*\": x", "values \"\"\" composition_dict = dict() for entry in raw_composition: try:", "If specified, then there must be a 'units' field and", "Design of a nickel-base superalloy using a neural network, Materials", "value_float = float(value) except ValueError: exception_caught = True value_float =", "return float(val) except ValueError: raise InvalidParameterError( expected=f\"Property {property_name} should have", "The total time and max temperature are generally more reliable", "== \"system.chemical\" raw_composition = NiSuperalloyDataset._extract_raw_composition(entry) composition: str = self._parse_composition(raw_composition) properties", "with an 'element' key and an 'idealWeightPercent' key. The element", "False for key, value in d.items(): try: value_float = float(value)", "return float(x) except ValueError: raise InvalidParameterError(\"Amount as a float\", x)", "rows, and yield strength occurs in 1046 rows. 898+856+1046=2800, so", "is None: labels_to_load = [ \"Yield Strength\", \"Ultimate Tensile Strength\",", "list\", got=raw_composition ) return raw_composition @staticmethod def _filter_dubious(entry: dict) ->", "Some composition amounts have a trailing asterisk, e.g., '2*'. The", "time (hours), and yield strength (MPa). Tensile strength and elongation", "json entry has something questionable about it. Currently, the only", "`property_name`. units: Optional expected value of 'units' field. If specified,", "have columns for composition (25 elements are present in at", "labels in this row that we are interested in. \"\"\"", "\"Powder processed\", categories_dict=powder_processed_dict ) data_array = [ composition, heat_treatment_1_time, heat_treatment_1_temp,", "dataset identifier #153493, Version 10. There are 2800 rows. The", "in chem- and materials informatics. 2019, <NAME>, Citrine Informatics. See", "generally more reliable than the individual heating steps. The total", "to get a single categorical property as an int. Parameters:", "treatment 2 Time\", units=\"hours\", default_value=0 ) heat_treatment_2_temp = self._get_scalar_property( properties,", "have a 'units' field. property_name: The name of the property", "field. property_name: The name of the property to get the", "None: labels_to_load = [ \"Yield Strength\", \"Ultimate Tensile Strength\", \"Stress", "_ = NiSuperalloyDataset._dict_values_to_float(composition_dict) composition_str: str = \"\" for element_name, element_amount", "composition as a list\", got=raw_composition ) return raw_composition @staticmethod def", "\"Heat treatment 1 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_2_time = self._get_scalar_property(", "and yield strength (MPa). Tensile strength and elongation occur together", "parse labels in a single row from the raw json.", "os.path.basename(filepath) assert ( filename[-4:] == \".zip\" ), f\"File path must", "= params.boolean(ignore_dubious) filepath = self.DEFAULT_PATH data, labels = self._load_data_and_labels(filepath, labels_to_load,", "in it, which occurs for 6 samples. Parameters: entry (dict):", "except KeyError: raise InvalidParameterError( f\"A value in the array: {categories_dict.keys()}\",", "properties should have name\" f\" '{property_name}'\", got=properties, ) matching_prop =", "as np from smlb.exceptions import InvalidParameterError from smlb.parameters import params", "raise InvalidParameterError( expected=f\"Only one entry in properties should have name\"", "_get_single_property( properties: List[dict], property_name: str, units: Optional[str] = None, default_value=None", "`scalars` field that is a list with one entry, a", "return categories_dict[category] except KeyError: raise InvalidParameterError( f\"A value in the", "None: assert matching_prop[\"units\"] == units except (KeyError, AssertionError): units_str =", "= None): \"\"\" Helper function to parse labels in a", "def _parse_composition(raw_composition: List[dict]) -> str: \"\"\" Helper function to parse", "data_array def _parse_json_labels(self, entry: dict, labels_to_load: Optional[List[str]] = None): \"\"\"", "Deals with dataset-specific-peculiarities in composition amounts. Some composition amounts have", "properties is None or not isinstance(properties, list): raise InvalidParameterError( expected=\"A", "imprecise. In any case, they only occur in 6 samples.", "There are also three columns for a pressure treatment step", ") total_heat_treatment_time = self._get_scalar_property( properties, \"Total heat treatment time\", units=\"hours\"", "Returns: dict, bool A modified version of `d`, and a", "matching_prop[\"scalars\"] assert len(scalars) == 1 val = scalars[0][\"value\"] if units", "ValueError: exception_caught = True value_float = NiSuperalloyDataset._parse_peculiar_amount(value) d_copy[key] = value_float", "The value of the desired property. \"\"\" try: val =", "property name and a `scalars` field that is a list", "then all labels are loaded. ignore_dubious: whether or not to", "list of dicts, each of which is a single property.", "property. Each entry is expected to have a 'name' field", "of labels in this row that we are interested in.", "* hours). A value of 0 generally implies that the", "strength (MPa). Tensile strength and elongation occur together in 898", "value in d.items(): try: value_float = float(value) except ValueError: exception_caught", "about a dozen exceptions they always add up to somewhere", "] return data_array def _parse_json_labels(self, entry: dict, labels_to_load: Optional[List[str]] =", "name of the property to get the value of. `properties`", "dataset. Returns: bool True if the composition contains an asterisk.", "least one row), whether the alloy was powder processed (0", "import zipfile from typing import List, Optional, Tuple, Union import", "`categories_dict` Returns: int An integer that corresponds to the value", "the time-temperature curve (degrees Celcius * hours). A value of", "a json entry has something questionable about it. Currently, the", "__init__( self, labels_to_load: Optional[Union[str, List[str]]] = None, ignore_dubious: bool =", "in raw_composition: try: element_name = entry[\"element\"] element_amount = entry[\"idealWeightPercent\"][\"value\"] except", "tensile strength (MPa), elongation (unitless), stress rupture stress (MPa), stress", "2017. DOI 10.1016/j.matdes.2017.06.007 The dataset was downloaded from the Citrination", "= False ): \"\"\"Initialize Ni-superalloy dataset with specified labels. Parameters:", "got=properties, ) def _get_categorical_property( self, properties: List[dict], property_name: str, categories_dict:", "time occur together in 856 rows, and yield strength occurs", "\"Heat treatment 3 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_4_time = self._get_scalar_property(", "units: Optional expected value of 'units' field. If specified, then", "\"\"\" DEFAULT_PATH = os.path.split(os.path.realpath(__file__))[0] + \"/ni_superalloys_3.json.zip\" POWDER_PROCESSED_NO = 0 POWDER_PROCESSED_YES", "e.g. 'Al5.5Ni94.0W0.5' \"\"\" composition_dict = NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float, _ = NiSuperalloyDataset._dict_values_to_float(composition_dict)", "if `properties` does not conform to the expected structure Returns:", "heat_treatment_2_time, heat_treatment_2_temp, heat_treatment_3_time, heat_treatment_3_temp, heat_treatment_4_time, heat_treatment_4_temp, total_heat_treatment_time, max_heat_treatment_temp, area_under_heat_treatment_curve, powder_processed,", "composition_dict ) return not exception_caught def _parse_json_data(self, entry: dict): \"\"\"", "properties if prop.get(\"name\") == property_name] if len(matching_props) == 0: return", "self._get_scalar_property( properties, \"Total heat treatment time\", units=\"hours\" ) max_heat_treatment_temp =", "for entry in raw_composition: try: element_name = entry[\"element\"] element_amount =", "element_amount > 0: composition_str += element_name + str(element_amount) return composition_str", "= self._get_scalar_property( properties, \"Total heat treatment time\", units=\"hours\" ) max_heat_treatment_temp", "exactly one output set. The other values are denoted as", "an element. An entry is a dict with an 'element'", "float. Parameters: properties: A list of dicts, each of which", "used. There are 5 labels: ultimate tensile strength (MPa), elongation", "with specified labels. Parameters: labels_to_load (str or List[str]): which labels", "but since only 51 rows have non-zero entries, this information", "hours). A value of 0 generally implies that the heat", "one output set. The other values are denoted as NaN.", "treatment 4 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) total_heat_treatment_time = self._get_scalar_property( properties,", "100%, but with about a dozen exceptions they always add", "NiSuperalloyDataset._extract_raw_composition(entry) composition_dict = NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float, exception_caught = NiSuperalloyDataset._dict_values_to_float( composition_dict )", "category = self._get_single_property(properties, property_name) try: return categories_dict[category] except KeyError: raise", "composition amounts. Some composition amounts have a trailing asterisk, e.g.,", "to `property_name`. units: Optional expected value of 'units' field. If", "NiSuperalloyDataset._parse_composition_as_dict(raw_composition) composition_dict_float, exception_caught = NiSuperalloyDataset._dict_values_to_float( composition_dict ) return not exception_caught", "str, labels_to_load: Optional[List[str]] = None, ignore_dubious: bool = False, ):", "self._get_scalar_property( properties, \"Heat treatment 1 Time\", units=\"hours\", default_value=0 ) heat_treatment_1_temp", "of the form\\n\" \"{'element': <element name>,\" \"'idealWeightPercent': \" \"{'value': <element", "a string. Parameters: raw_composition (List[dict]): A list, each entry of", "\"\"\" category = self._get_single_property(properties, property_name) try: return categories_dict[category] except KeyError:", "and string) data = np.array([self._parse_json_data(e) for e in raw], dtype=object)", "self._get_scalar_property( properties, \"Heat treatment 2 Temperature\", units=\"$^{\\\\circ}$C\", default_value=0 ) heat_treatment_3_time", "in the dataset. Returns: bool True if the composition contains", "import List, Optional, Tuple, Union import numpy as np from", "= self._load_data_and_labels(filepath, labels_to_load, ignore_dubious) super().__init__(data=data, labels=labels) def _load_data_and_labels( self, filepath:", "-> str: \"\"\" Helper function to parse composition as a", "get a single categorical property as an int. Parameters: properties:", "Returns: str Chemical composition as string, e.g. 'Al5.5Ni94.0W0.5' \"\"\" composition_dict", "one for each property\", got=properties ) heat_treatment_1_time = self._get_scalar_property( properties,", "properties, \"Powder processed\", categories_dict=powder_processed_dict ) data_array = [ composition, heat_treatment_1_time,", "time (hours) and temperature (degrees Celcius) for up to 4", "as a list\", got=raw_composition ) return raw_composition @staticmethod def _filter_dubious(entry:", "step was not done, but there are some missing values." ]
[ "username, password = self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"bgwriter\"], \"hosts\":", "username = \"postgres\" host = self.compose_host() dsn = \"postgres://{}?sslmode=disable\".format(host) return", "['postgresql'] def common_checks(self, output): # Ensure no errors or warnings", "[\"postgresql\"] self.assertCountEqual(self.de_dot(top_level_fields), evt.keys()) self.assert_fields_are_documented(evt) def get_hosts(self): username = \"postgres\" host", "in the log. self.assert_no_logged_warnings() for evt in output: top_level_fields =", "class Test(metricbeat.BaseTest): COMPOSE_SERVICES = ['postgresql'] def common_checks(self, output): # Ensure", "\"5s\" }]) proc = self.start_beat() self.wait_until(lambda: self.output_lines() > 0) proc.check_kill_and_wait()", "evt[\"postgresql\"][\"database\"] assert \"oid\" in evt[\"postgresql\"][\"database\"] assert \"blocks\" in evt[\"postgresql\"][\"database\"] assert", "\"name\": \"postgresql\", \"metricsets\": [\"activity\"], \"hosts\": hosts, \"username\": username, \"password\": password,", "\"postgresql\", \"metricsets\": [\"database\"], \"hosts\": hosts, \"username\": username, \"password\": password, \"period\":", "@pytest.mark.tag('integration') def test_activity(self): \"\"\" PostgreSQL module outputs an event. \"\"\"", "assert \"name\" in evt[\"postgresql\"][\"database\"] assert \"oid\" in evt[\"postgresql\"][\"database\"] assert \"blocks\"", "in evt[\"postgresql\"][\"bgwriter\"] assert \"buffers\" in evt[\"postgresql\"][\"bgwriter\"] assert \"stats_reset\" in evt[\"postgresql\"][\"bgwriter\"]", "in evt[\"postgresql\"][\"database\"] assert \"oid\" in evt[\"postgresql\"][\"database\"] assert \"blocks\" in evt[\"postgresql\"][\"database\"]", "def test_database(self): \"\"\" PostgreSQL module outputs an event. \"\"\" hosts,", "\"metricsets\": [\"bgwriter\"], \"hosts\": hosts, \"username\": username, \"password\": password, \"period\": \"5s\"", "no errors or warnings exist in the log. self.assert_no_logged_warnings() for", "log. self.assert_no_logged_warnings() for evt in output: top_level_fields = metricbeat.COMMON_FIELDS +", "unittest class Test(metricbeat.BaseTest): COMPOSE_SERVICES = ['postgresql'] def common_checks(self, output): #", "test_database(self): \"\"\" PostgreSQL module outputs an event. \"\"\" hosts, username,", "assert \"name\" in evt[\"postgresql\"][\"activity\"][\"database\"] assert \"oid\" in evt[\"postgresql\"][\"activity\"][\"database\"] assert \"state\"", "proc = self.start_beat() self.wait_until(lambda: self.output_lines() > 0) proc.check_kill_and_wait() output =", "output: top_level_fields = metricbeat.COMMON_FIELDS + [\"postgresql\"] self.assertCountEqual(self.de_dot(top_level_fields), evt.keys()) self.assert_fields_are_documented(evt) def", "for evt in output: assert \"name\" in evt[\"postgresql\"][\"activity\"][\"database\"] assert \"oid\"", "in output: assert \"checkpoints\" in evt[\"postgresql\"][\"bgwriter\"] assert \"buffers\" in evt[\"postgresql\"][\"bgwriter\"]", "dsn = \"postgres://{}?sslmode=disable\".format(host) return ( [dsn], username, os.getenv(\"POSTGRESQL_PASSWORD\"), ) @unittest.skipUnless(metricbeat.INTEGRATION_TESTS,", "in evt[\"postgresql\"][\"database\"] assert \"rows\" in evt[\"postgresql\"][\"database\"] assert \"conflicts\" in evt[\"postgresql\"][\"database\"]", "return ( [dsn], username, os.getenv(\"POSTGRESQL_PASSWORD\"), ) @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration')", "import unittest class Test(metricbeat.BaseTest): COMPOSE_SERVICES = ['postgresql'] def common_checks(self, output):", "= self.read_output_json() self.common_checks(output) for evt in output: assert \"checkpoints\" in", "sys import unittest class Test(metricbeat.BaseTest): COMPOSE_SERVICES = ['postgresql'] def common_checks(self,", "\"username\": username, \"password\": password, \"period\": \"5s\" }]) proc = self.start_beat()", "an event. \"\"\" hosts, username, password = self.get_hosts() self.render_config_template(modules=[{ \"name\":", "output: assert \"name\" in evt[\"postgresql\"][\"activity\"][\"database\"] assert \"oid\" in evt[\"postgresql\"][\"activity\"][\"database\"] assert", "test_bgwriter(self): \"\"\" PostgreSQL module outputs an event. \"\"\" hosts, username,", "= self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"database\"], \"hosts\": hosts, \"username\":", "metricbeat import os import pytest import sys import unittest class", "= metricbeat.COMMON_FIELDS + [\"postgresql\"] self.assertCountEqual(self.de_dot(top_level_fields), evt.keys()) self.assert_fields_are_documented(evt) def get_hosts(self): username", "hosts, \"username\": username, \"password\": password, \"period\": \"5s\" }]) proc =", "\"hosts\": hosts, \"username\": username, \"password\": password, \"period\": \"5s\" }]) proc", "hosts, username, password = self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"database\"],", "def test_bgwriter(self): \"\"\" PostgreSQL module outputs an event. \"\"\" hosts,", "evt.keys()) self.assert_fields_are_documented(evt) def get_hosts(self): username = \"postgres\" host = self.compose_host()", "test\") @pytest.mark.tag('integration') def test_bgwriter(self): \"\"\" PostgreSQL module outputs an event.", "output = self.read_output_json() self.common_checks(output) for evt in output: assert \"checkpoints\"", "in evt[\"postgresql\"][\"database\"] assert \"conflicts\" in evt[\"postgresql\"][\"database\"] assert \"deadlocks\" in evt[\"postgresql\"][\"database\"]", "evt[\"postgresql\"][\"database\"] assert \"blocks\" in evt[\"postgresql\"][\"database\"] assert \"rows\" in evt[\"postgresql\"][\"database\"] assert", "top_level_fields = metricbeat.COMMON_FIELDS + [\"postgresql\"] self.assertCountEqual(self.de_dot(top_level_fields), evt.keys()) self.assert_fields_are_documented(evt) def get_hosts(self):", "proc.check_kill_and_wait() output = self.read_output_json() self.common_checks(output) for evt in output: assert", "for evt in output: assert \"name\" in evt[\"postgresql\"][\"database\"] assert \"oid\"", "\"postgres://{}?sslmode=disable\".format(host) return ( [dsn], username, os.getenv(\"POSTGRESQL_PASSWORD\"), ) @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\")", "@pytest.mark.tag('integration') def test_bgwriter(self): \"\"\" PostgreSQL module outputs an event. \"\"\"", "= self.compose_host() dsn = \"postgres://{}?sslmode=disable\".format(host) return ( [dsn], username, os.getenv(\"POSTGRESQL_PASSWORD\"),", "username, \"password\": password, \"period\": \"5s\" }]) proc = self.start_beat() self.wait_until(lambda:", "\"integration test\") @pytest.mark.tag('integration') def test_database(self): \"\"\" PostgreSQL module outputs an", "@pytest.mark.tag('integration') def test_database(self): \"\"\" PostgreSQL module outputs an event. \"\"\"", "in evt[\"postgresql\"][\"activity\"][\"database\"] assert \"oid\" in evt[\"postgresql\"][\"activity\"][\"database\"] assert \"state\" in evt[\"postgresql\"][\"activity\"]", "Test(metricbeat.BaseTest): COMPOSE_SERVICES = ['postgresql'] def common_checks(self, output): # Ensure no", "self.assert_no_logged_warnings() for evt in output: top_level_fields = metricbeat.COMMON_FIELDS + [\"postgresql\"]", "evt in output: assert \"checkpoints\" in evt[\"postgresql\"][\"bgwriter\"] assert \"buffers\" in", "> 0) proc.check_kill_and_wait() output = self.read_output_json() self.common_checks(output) for evt in", "in evt[\"postgresql\"][\"database\"] assert \"blocks\" in evt[\"postgresql\"][\"database\"] assert \"rows\" in evt[\"postgresql\"][\"database\"]", "self.read_output_json() self.common_checks(output) for evt in output: assert \"checkpoints\" in evt[\"postgresql\"][\"bgwriter\"]", "evt in output: top_level_fields = metricbeat.COMMON_FIELDS + [\"postgresql\"] self.assertCountEqual(self.de_dot(top_level_fields), evt.keys())", "in output: assert \"name\" in evt[\"postgresql\"][\"activity\"][\"database\"] assert \"oid\" in evt[\"postgresql\"][\"activity\"][\"database\"]", "username, password = self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"activity\"], \"hosts\":", "self.compose_host() dsn = \"postgres://{}?sslmode=disable\".format(host) return ( [dsn], username, os.getenv(\"POSTGRESQL_PASSWORD\"), )", "evt in output: assert \"name\" in evt[\"postgresql\"][\"database\"] assert \"oid\" in", "username, os.getenv(\"POSTGRESQL_PASSWORD\"), ) @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def test_activity(self): \"\"\"", "\"name\": \"postgresql\", \"metricsets\": [\"bgwriter\"], \"hosts\": hosts, \"username\": username, \"password\": password,", "os import pytest import sys import unittest class Test(metricbeat.BaseTest): COMPOSE_SERVICES", "self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"activity\"], \"hosts\": hosts, \"username\": username, \"password\":", "test_activity(self): \"\"\" PostgreSQL module outputs an event. \"\"\" hosts, username,", "\"blocks\" in evt[\"postgresql\"][\"database\"] assert \"rows\" in evt[\"postgresql\"][\"database\"] assert \"conflicts\" in", "output = self.read_output_json() self.common_checks(output) for evt in output: assert \"name\"", "self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"activity\"], \"hosts\": hosts, \"username\": username,", "self.common_checks(output) for evt in output: assert \"name\" in evt[\"postgresql\"][\"activity\"][\"database\"] assert", "os.getenv(\"POSTGRESQL_PASSWORD\"), ) @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def test_activity(self): \"\"\" PostgreSQL", "event. \"\"\" hosts, username, password = self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\",", "\"name\" in evt[\"postgresql\"][\"activity\"][\"database\"] assert \"oid\" in evt[\"postgresql\"][\"activity\"][\"database\"] assert \"state\" in", "evt[\"postgresql\"][\"activity\"][\"database\"] assert \"state\" in evt[\"postgresql\"][\"activity\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def", "= \"postgres://{}?sslmode=disable\".format(host) return ( [dsn], username, os.getenv(\"POSTGRESQL_PASSWORD\"), ) @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration", "evt[\"postgresql\"][\"database\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def test_bgwriter(self): \"\"\" PostgreSQL module", "\"postgresql\", \"metricsets\": [\"bgwriter\"], \"hosts\": hosts, \"username\": username, \"password\": password, \"period\":", "self.assertCountEqual(self.de_dot(top_level_fields), evt.keys()) self.assert_fields_are_documented(evt) def get_hosts(self): username = \"postgres\" host =", "module outputs an event. \"\"\" hosts, username, password = self.get_hosts()", "for evt in output: assert \"checkpoints\" in evt[\"postgresql\"][\"bgwriter\"] assert \"buffers\"", "\"oid\" in evt[\"postgresql\"][\"activity\"][\"database\"] assert \"state\" in evt[\"postgresql\"][\"activity\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\")", "\"metricsets\": [\"database\"], \"hosts\": hosts, \"username\": username, \"password\": password, \"period\": \"5s\"", "metricbeat.COMMON_FIELDS + [\"postgresql\"] self.assertCountEqual(self.de_dot(top_level_fields), evt.keys()) self.assert_fields_are_documented(evt) def get_hosts(self): username =", "evt[\"postgresql\"][\"database\"] assert \"deadlocks\" in evt[\"postgresql\"][\"database\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def", "PostgreSQL module outputs an event. \"\"\" hosts, username, password =", "def common_checks(self, output): # Ensure no errors or warnings exist", ") @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def test_activity(self): \"\"\" PostgreSQL module", "the log. self.assert_no_logged_warnings() for evt in output: top_level_fields = metricbeat.COMMON_FIELDS", "in evt[\"postgresql\"][\"activity\"][\"database\"] assert \"state\" in evt[\"postgresql\"][\"activity\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration')", "in output: top_level_fields = metricbeat.COMMON_FIELDS + [\"postgresql\"] self.assertCountEqual(self.de_dot(top_level_fields), evt.keys()) self.assert_fields_are_documented(evt)", "assert \"oid\" in evt[\"postgresql\"][\"database\"] assert \"blocks\" in evt[\"postgresql\"][\"database\"] assert \"rows\"", "[\"bgwriter\"], \"hosts\": hosts, \"username\": username, \"password\": password, \"period\": \"5s\" }])", "\"state\" in evt[\"postgresql\"][\"activity\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def test_database(self): \"\"\"", "hosts, username, password = self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"bgwriter\"],", "\"period\": \"5s\" }]) proc = self.start_beat() self.wait_until(lambda: self.output_lines() > 0)", "pytest import sys import unittest class Test(metricbeat.BaseTest): COMPOSE_SERVICES = ['postgresql']", "= self.start_beat() self.wait_until(lambda: self.output_lines() > 0) proc.check_kill_and_wait() output = self.read_output_json()", "self.common_checks(output) for evt in output: assert \"name\" in evt[\"postgresql\"][\"database\"] assert", "0) proc.check_kill_and_wait() output = self.read_output_json() self.common_checks(output) for evt in output:", "in evt[\"postgresql\"][\"activity\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def test_database(self): \"\"\" PostgreSQL", "hosts, username, password = self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"activity\"],", "or warnings exist in the log. self.assert_no_logged_warnings() for evt in", "[dsn], username, os.getenv(\"POSTGRESQL_PASSWORD\"), ) @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def test_activity(self):", "assert \"oid\" in evt[\"postgresql\"][\"activity\"][\"database\"] assert \"state\" in evt[\"postgresql\"][\"activity\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration", "\"deadlocks\" in evt[\"postgresql\"][\"database\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def test_bgwriter(self): \"\"\"", "evt[\"postgresql\"][\"database\"] assert \"conflicts\" in evt[\"postgresql\"][\"database\"] assert \"deadlocks\" in evt[\"postgresql\"][\"database\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS,", "password = self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"database\"], \"hosts\": hosts,", "= ['postgresql'] def common_checks(self, output): # Ensure no errors or", "assert \"rows\" in evt[\"postgresql\"][\"database\"] assert \"conflicts\" in evt[\"postgresql\"][\"database\"] assert \"deadlocks\"", "[\"database\"], \"hosts\": hosts, \"username\": username, \"password\": password, \"period\": \"5s\" }])", "= self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"activity\"], \"hosts\": hosts, \"username\":", "\"password\": password, \"period\": \"5s\" }]) proc = self.start_beat() self.wait_until(lambda: self.output_lines()", "output: assert \"checkpoints\" in evt[\"postgresql\"][\"bgwriter\"] assert \"buffers\" in evt[\"postgresql\"][\"bgwriter\"] assert", "self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"database\"], \"hosts\": hosts, \"username\": username,", "self.common_checks(output) for evt in output: assert \"checkpoints\" in evt[\"postgresql\"][\"bgwriter\"] assert", "common_checks(self, output): # Ensure no errors or warnings exist in", "for evt in output: top_level_fields = metricbeat.COMMON_FIELDS + [\"postgresql\"] self.assertCountEqual(self.de_dot(top_level_fields),", "\"checkpoints\" in evt[\"postgresql\"][\"bgwriter\"] assert \"buffers\" in evt[\"postgresql\"][\"bgwriter\"] assert \"stats_reset\" in", "COMPOSE_SERVICES = ['postgresql'] def common_checks(self, output): # Ensure no errors", "\"conflicts\" in evt[\"postgresql\"][\"database\"] assert \"deadlocks\" in evt[\"postgresql\"][\"database\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\")", "assert \"conflicts\" in evt[\"postgresql\"][\"database\"] assert \"deadlocks\" in evt[\"postgresql\"][\"database\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration", "assert \"deadlocks\" in evt[\"postgresql\"][\"database\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def test_bgwriter(self):", "+ [\"postgresql\"] self.assertCountEqual(self.de_dot(top_level_fields), evt.keys()) self.assert_fields_are_documented(evt) def get_hosts(self): username = \"postgres\"", "errors or warnings exist in the log. self.assert_no_logged_warnings() for evt", "\"oid\" in evt[\"postgresql\"][\"database\"] assert \"blocks\" in evt[\"postgresql\"][\"database\"] assert \"rows\" in", "\"integration test\") @pytest.mark.tag('integration') def test_activity(self): \"\"\" PostgreSQL module outputs an", "self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"database\"], \"hosts\": hosts, \"username\": username, \"password\":", "warnings exist in the log. self.assert_no_logged_warnings() for evt in output:", "def test_activity(self): \"\"\" PostgreSQL module outputs an event. \"\"\" hosts,", "}]) proc = self.start_beat() self.wait_until(lambda: self.output_lines() > 0) proc.check_kill_and_wait() output", "self.wait_until(lambda: self.output_lines() > 0) proc.check_kill_and_wait() output = self.read_output_json() self.common_checks(output) for", "\"postgresql\", \"metricsets\": [\"activity\"], \"hosts\": hosts, \"username\": username, \"password\": password, \"period\":", "output: assert \"name\" in evt[\"postgresql\"][\"database\"] assert \"oid\" in evt[\"postgresql\"][\"database\"] assert", "self.output_lines() > 0) proc.check_kill_and_wait() output = self.read_output_json() self.common_checks(output) for evt", "@unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def test_bgwriter(self): \"\"\" PostgreSQL module outputs", "= \"postgres\" host = self.compose_host() dsn = \"postgres://{}?sslmode=disable\".format(host) return (", "exist in the log. self.assert_no_logged_warnings() for evt in output: top_level_fields", "evt[\"postgresql\"][\"database\"] assert \"rows\" in evt[\"postgresql\"][\"database\"] assert \"conflicts\" in evt[\"postgresql\"][\"database\"] assert", "assert \"state\" in evt[\"postgresql\"][\"activity\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def test_database(self):", "( [dsn], username, os.getenv(\"POSTGRESQL_PASSWORD\"), ) @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def", "outputs an event. \"\"\" hosts, username, password = self.get_hosts() self.render_config_template(modules=[{", "password = self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"activity\"], \"hosts\": hosts,", "[\"activity\"], \"hosts\": hosts, \"username\": username, \"password\": password, \"period\": \"5s\" }])", "evt[\"postgresql\"][\"activity\"][\"database\"] assert \"oid\" in evt[\"postgresql\"][\"activity\"][\"database\"] assert \"state\" in evt[\"postgresql\"][\"activity\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS,", "self.read_output_json() self.common_checks(output) for evt in output: assert \"name\" in evt[\"postgresql\"][\"database\"]", "\"integration test\") @pytest.mark.tag('integration') def test_bgwriter(self): \"\"\" PostgreSQL module outputs an", "username, password = self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"database\"], \"hosts\":", "import metricbeat import os import pytest import sys import unittest", "self.read_output_json() self.common_checks(output) for evt in output: assert \"name\" in evt[\"postgresql\"][\"activity\"][\"database\"]", "import os import pytest import sys import unittest class Test(metricbeat.BaseTest):", "\"rows\" in evt[\"postgresql\"][\"database\"] assert \"conflicts\" in evt[\"postgresql\"][\"database\"] assert \"deadlocks\" in", "test\") @pytest.mark.tag('integration') def test_activity(self): \"\"\" PostgreSQL module outputs an event.", "# Ensure no errors or warnings exist in the log.", "\"\"\" PostgreSQL module outputs an event. \"\"\" hosts, username, password", "= self.read_output_json() self.common_checks(output) for evt in output: assert \"name\" in", "test\") @pytest.mark.tag('integration') def test_database(self): \"\"\" PostgreSQL module outputs an event.", "password = self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"bgwriter\"], \"hosts\": hosts,", "\"name\" in evt[\"postgresql\"][\"database\"] assert \"oid\" in evt[\"postgresql\"][\"database\"] assert \"blocks\" in", "evt in output: assert \"name\" in evt[\"postgresql\"][\"activity\"][\"database\"] assert \"oid\" in", "\"postgres\" host = self.compose_host() dsn = \"postgres://{}?sslmode=disable\".format(host) return ( [dsn],", "assert \"checkpoints\" in evt[\"postgresql\"][\"bgwriter\"] assert \"buffers\" in evt[\"postgresql\"][\"bgwriter\"] assert \"stats_reset\"", "\"name\": \"postgresql\", \"metricsets\": [\"database\"], \"hosts\": hosts, \"username\": username, \"password\": password,", "def get_hosts(self): username = \"postgres\" host = self.compose_host() dsn =", "output): # Ensure no errors or warnings exist in the", "password, \"period\": \"5s\" }]) proc = self.start_beat() self.wait_until(lambda: self.output_lines() >", "evt[\"postgresql\"][\"activity\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def test_database(self): \"\"\" PostgreSQL module", "in output: assert \"name\" in evt[\"postgresql\"][\"database\"] assert \"oid\" in evt[\"postgresql\"][\"database\"]", "self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"bgwriter\"], \"hosts\": hosts, \"username\": username,", "self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"bgwriter\"], \"hosts\": hosts, \"username\": username, \"password\":", "Ensure no errors or warnings exist in the log. self.assert_no_logged_warnings()", "in evt[\"postgresql\"][\"database\"] assert \"deadlocks\" in evt[\"postgresql\"][\"database\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration')", "assert \"blocks\" in evt[\"postgresql\"][\"database\"] assert \"rows\" in evt[\"postgresql\"][\"database\"] assert \"conflicts\"", "import pytest import sys import unittest class Test(metricbeat.BaseTest): COMPOSE_SERVICES =", "host = self.compose_host() dsn = \"postgres://{}?sslmode=disable\".format(host) return ( [dsn], username,", "self.assert_fields_are_documented(evt) def get_hosts(self): username = \"postgres\" host = self.compose_host() dsn", "import sys import unittest class Test(metricbeat.BaseTest): COMPOSE_SERVICES = ['postgresql'] def", "@unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def test_activity(self): \"\"\" PostgreSQL module outputs", "self.start_beat() self.wait_until(lambda: self.output_lines() > 0) proc.check_kill_and_wait() output = self.read_output_json() self.common_checks(output)", "in evt[\"postgresql\"][\"database\"] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def test_bgwriter(self): \"\"\" PostgreSQL", "= self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\": [\"bgwriter\"], \"hosts\": hosts, \"username\":", "\"metricsets\": [\"activity\"], \"hosts\": hosts, \"username\": username, \"password\": password, \"period\": \"5s\"", "get_hosts(self): username = \"postgres\" host = self.compose_host() dsn = \"postgres://{}?sslmode=disable\".format(host)", "\"\"\" hosts, username, password = self.get_hosts() self.render_config_template(modules=[{ \"name\": \"postgresql\", \"metricsets\":", "@unittest.skipUnless(metricbeat.INTEGRATION_TESTS, \"integration test\") @pytest.mark.tag('integration') def test_database(self): \"\"\" PostgreSQL module outputs" ]
[ "import torch from pytorch_lightning.accelerators.base_backend import Accelerator from pytorch_lightning.utilities import AMPType,", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "+ cpu is not supported. Please use a GPU option')", "MisconfigurationException class CPUBackend(Accelerator): def __init__(self, trainer, cluster_environment=None): super().__init__(trainer, cluster_environment) def", "Lightning team. # # Licensed under the Apache License, Version", "if self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast(): output = self.trainer.model.training_step(*args) else:", "if self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast(): output = self.trainer.model.validation_step(*args) else:", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "2.0 (the \"License\"); # you may not use this file", "agreed to in writing, software # distributed under the License", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Unless required by applicable law or agreed to in writing,", "CPUBackend(Accelerator): def __init__(self, trainer, cluster_environment=None): super().__init__(trainer, cluster_environment) def setup(self, model):", "self.trainer.call_setup_hook(model) # CHOOSE OPTIMIZER # allow for lr schedulers as", "self.trainer.amp_backend: raise MisconfigurationException('amp + cpu is not supported. Please use", "distributed under the License is distributed on an \"AS IS\"", "AMPType.NATIVE: with torch.cuda.amp.autocast(): output = self.trainer.model.test_step(*args) else: output = self.trainer.model.test_step(*args)", "supported. Please use a GPU option') # call setup after", "return results def training_step(self, args): if self.trainer.amp_backend == AMPType.NATIVE: with", "OPTIMIZER # allow for lr schedulers as well self.setup_optimizers(model) self.trainer.model", "permissions and # limitations under the License. import torch from", "well self.setup_optimizers(model) self.trainer.model = model def train(self): model = self.trainer.model", "schedulers as well self.setup_optimizers(model) self.trainer.model = model def train(self): model", "training_step(self, args): if self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast(): output =", "with torch.cuda.amp.autocast(): output = self.trainer.model.training_step(*args) else: output = self.trainer.model.training_step(*args) return", "the specific language governing permissions and # limitations under the", "return output def test_step(self, args): if self.trainer.amp_backend == AMPType.NATIVE: with", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "Copyright The PyTorch Lightning team. # # Licensed under the", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", "training routine self.trainer.train_loop.setup_training(model) # train or test results = self.train_or_test()", "team. # # Licensed under the Apache License, Version 2.0", "except in compliance with the License. # You may obtain", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "# run through amp wrapper if self.trainer.amp_backend: raise MisconfigurationException('amp +", "option') # call setup after the ddp process has connected", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "setup after the ddp process has connected self.trainer.call_setup_hook(model) # CHOOSE", "not use this file except in compliance with the License.", "after the ddp process has connected self.trainer.call_setup_hook(model) # CHOOSE OPTIMIZER", "self.trainer.model # set up training routine self.trainer.train_loop.setup_training(model) # train or", "pytorch_lightning.utilities.exceptions import MisconfigurationException class CPUBackend(Accelerator): def __init__(self, trainer, cluster_environment=None): super().__init__(trainer,", "with torch.cuda.amp.autocast(): output = self.trainer.model.test_step(*args) else: output = self.trainer.model.test_step(*args) return", "writing, software # distributed under the License is distributed on", "in writing, software # distributed under the License is distributed", "rank_zero_warn from pytorch_lightning.utilities.exceptions import MisconfigurationException class CPUBackend(Accelerator): def __init__(self, trainer,", "limitations under the License. import torch from pytorch_lightning.accelerators.base_backend import Accelerator", "you may not use this file except in compliance with", "MisconfigurationException('amp + cpu is not supported. Please use a GPU", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "language governing permissions and # limitations under the License. import", "AMPType, rank_zero_warn from pytorch_lightning.utilities.exceptions import MisconfigurationException class CPUBackend(Accelerator): def __init__(self,", "not supported. Please use a GPU option') # call setup", "or test results = self.train_or_test() return results def training_step(self, args):", "call setup after the ddp process has connected self.trainer.call_setup_hook(model) #", "# call setup after the ddp process has connected self.trainer.call_setup_hook(model)", "use this file except in compliance with the License. #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "pytorch_lightning.utilities import AMPType, rank_zero_warn from pytorch_lightning.utilities.exceptions import MisconfigurationException class CPUBackend(Accelerator):", "PyTorch Lightning team. # # Licensed under the Apache License,", "CONDITIONS OF ANY KIND, either express or implied. # See", "process has connected self.trainer.call_setup_hook(model) # CHOOSE OPTIMIZER # allow for", "output def test_step(self, args): if self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast():", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "def training_step(self, args): if self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast(): output", "# allow for lr schedulers as well self.setup_optimizers(model) self.trainer.model =", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "torch.cuda.amp.autocast(): output = self.trainer.model.validation_step(*args) else: output = self.trainer.model.validation_step(*args) return output", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "self.trainer.model = model def train(self): model = self.trainer.model # set", "from pytorch_lightning.utilities import AMPType, rank_zero_warn from pytorch_lightning.utilities.exceptions import MisconfigurationException class", "# You may obtain a copy of the License at", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "if self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast(): output = self.trainer.model.test_step(*args) else:", "as well self.setup_optimizers(model) self.trainer.model = model def train(self): model =", "self.train_or_test() return results def training_step(self, args): if self.trainer.amp_backend == AMPType.NATIVE:", "under the License is distributed on an \"AS IS\" BASIS,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "setup(self, model): # run through amp wrapper if self.trainer.amp_backend: raise", "License for the specific language governing permissions and # limitations", "trainer, cluster_environment=None): super().__init__(trainer, cluster_environment) def setup(self, model): # run through", "= self.trainer.model.validation_step(*args) else: output = self.trainer.model.validation_step(*args) return output def test_step(self,", "self.trainer.model.validation_step(*args) else: output = self.trainer.model.validation_step(*args) return output def test_step(self, args):", "def validation_step(self, args): if self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast(): output", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "cpu is not supported. Please use a GPU option') #", "# CHOOSE OPTIMIZER # allow for lr schedulers as well", "AMPType.NATIVE: with torch.cuda.amp.autocast(): output = self.trainer.model.validation_step(*args) else: output = self.trainer.model.validation_step(*args)", "== AMPType.NATIVE: with torch.cuda.amp.autocast(): output = self.trainer.model.test_step(*args) else: output =", "train or test results = self.train_or_test() return results def training_step(self,", "else: output = self.trainer.model.validation_step(*args) return output def test_step(self, args): if", "governing permissions and # limitations under the License. import torch", "model = self.trainer.model # set up training routine self.trainer.train_loop.setup_training(model) #", "args): if self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast(): output = self.trainer.model.test_step(*args)", "allow for lr schedulers as well self.setup_optimizers(model) self.trainer.model = model", "= model def train(self): model = self.trainer.model # set up", "ddp process has connected self.trainer.call_setup_hook(model) # CHOOSE OPTIMIZER # allow", "GPU option') # call setup after the ddp process has", "cluster_environment) def setup(self, model): # run through amp wrapper if", "train(self): model = self.trainer.model # set up training routine self.trainer.train_loop.setup_training(model)", "self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast(): output = self.trainer.model.training_step(*args) else: output", "the License for the specific language governing permissions and #", "self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast(): output = self.trainer.model.test_step(*args) else: output", "# limitations under the License. import torch from pytorch_lightning.accelerators.base_backend import", "(the \"License\"); # you may not use this file except", "import MisconfigurationException class CPUBackend(Accelerator): def __init__(self, trainer, cluster_environment=None): super().__init__(trainer, cluster_environment)", "a GPU option') # call setup after the ddp process", "Apache License, Version 2.0 (the \"License\"); # you may not", "# you may not use this file except in compliance", "either express or implied. # See the License for the", "OR CONDITIONS OF ANY KIND, either express or implied. #", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "output = self.trainer.model.validation_step(*args) else: output = self.trainer.model.validation_step(*args) return output def", "the License is distributed on an \"AS IS\" BASIS, #", "= self.trainer.model.validation_step(*args) return output def test_step(self, args): if self.trainer.amp_backend ==", "in compliance with the License. # You may obtain a", "is not supported. Please use a GPU option') # call", "self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast(): output = self.trainer.model.validation_step(*args) else: output", "class CPUBackend(Accelerator): def __init__(self, trainer, cluster_environment=None): super().__init__(trainer, cluster_environment) def setup(self,", "software # distributed under the License is distributed on an", "and # limitations under the License. import torch from pytorch_lightning.accelerators.base_backend", "__init__(self, trainer, cluster_environment=None): super().__init__(trainer, cluster_environment) def setup(self, model): # run", "connected self.trainer.call_setup_hook(model) # CHOOSE OPTIMIZER # allow for lr schedulers", "# Copyright The PyTorch Lightning team. # # Licensed under", "wrapper if self.trainer.amp_backend: raise MisconfigurationException('amp + cpu is not supported.", "# # Unless required by applicable law or agreed to", "model): # run through amp wrapper if self.trainer.amp_backend: raise MisconfigurationException('amp", "self.trainer.model.training_step(*args) return output def validation_step(self, args): if self.trainer.amp_backend == AMPType.NATIVE:", "if self.trainer.amp_backend: raise MisconfigurationException('amp + cpu is not supported. Please", "torch.cuda.amp.autocast(): output = self.trainer.model.training_step(*args) else: output = self.trainer.model.training_step(*args) return output", "output def validation_step(self, args): if self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast():", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "= self.trainer.model.training_step(*args) return output def validation_step(self, args): if self.trainer.amp_backend ==", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "results def training_step(self, args): if self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast():", "run through amp wrapper if self.trainer.amp_backend: raise MisconfigurationException('amp + cpu", "Version 2.0 (the \"License\"); # you may not use this", "results = self.train_or_test() return results def training_step(self, args): if self.trainer.amp_backend", "AMPType.NATIVE: with torch.cuda.amp.autocast(): output = self.trainer.model.training_step(*args) else: output = self.trainer.model.training_step(*args)", "Please use a GPU option') # call setup after the", "from pytorch_lightning.accelerators.base_backend import Accelerator from pytorch_lightning.utilities import AMPType, rank_zero_warn from", "law or agreed to in writing, software # distributed under", "def train(self): model = self.trainer.model # set up training routine", "CHOOSE OPTIMIZER # allow for lr schedulers as well self.setup_optimizers(model)", "the ddp process has connected self.trainer.call_setup_hook(model) # CHOOSE OPTIMIZER #", "under the License. import torch from pytorch_lightning.accelerators.base_backend import Accelerator from", "validation_step(self, args): if self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast(): output =", "for lr schedulers as well self.setup_optimizers(model) self.trainer.model = model def", "model def train(self): model = self.trainer.model # set up training", "import AMPType, rank_zero_warn from pytorch_lightning.utilities.exceptions import MisconfigurationException class CPUBackend(Accelerator): def", "def test_step(self, args): if self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast(): output", "implied. # See the License for the specific language governing", "output = self.trainer.model.validation_step(*args) return output def test_step(self, args): if self.trainer.amp_backend", "set up training routine self.trainer.train_loop.setup_training(model) # train or test results", "= self.train_or_test() return results def training_step(self, args): if self.trainer.amp_backend ==", "under the Apache License, Version 2.0 (the \"License\"); # you", "output = self.trainer.model.training_step(*args) else: output = self.trainer.model.training_step(*args) return output def", "\"License\"); # you may not use this file except in", "the License. import torch from pytorch_lightning.accelerators.base_backend import Accelerator from pytorch_lightning.utilities", "# set up training routine self.trainer.train_loop.setup_training(model) # train or test", "License. import torch from pytorch_lightning.accelerators.base_backend import Accelerator from pytorch_lightning.utilities import", "output = self.trainer.model.training_step(*args) return output def validation_step(self, args): if self.trainer.amp_backend", "self.trainer.model.validation_step(*args) return output def test_step(self, args): if self.trainer.amp_backend == AMPType.NATIVE:", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "Accelerator from pytorch_lightning.utilities import AMPType, rank_zero_warn from pytorch_lightning.utilities.exceptions import MisconfigurationException", "self.trainer.train_loop.setup_training(model) # train or test results = self.train_or_test() return results", "The PyTorch Lightning team. # # Licensed under the Apache", "import Accelerator from pytorch_lightning.utilities import AMPType, rank_zero_warn from pytorch_lightning.utilities.exceptions import", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "through amp wrapper if self.trainer.amp_backend: raise MisconfigurationException('amp + cpu is", "has connected self.trainer.call_setup_hook(model) # CHOOSE OPTIMIZER # allow for lr", "lr schedulers as well self.setup_optimizers(model) self.trainer.model = model def train(self):", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "args): if self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast(): output = self.trainer.model.training_step(*args)", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "cluster_environment=None): super().__init__(trainer, cluster_environment) def setup(self, model): # run through amp", "== AMPType.NATIVE: with torch.cuda.amp.autocast(): output = self.trainer.model.validation_step(*args) else: output =", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "else: output = self.trainer.model.training_step(*args) return output def validation_step(self, args): if", "to in writing, software # distributed under the License is", "amp wrapper if self.trainer.amp_backend: raise MisconfigurationException('amp + cpu is not", "torch from pytorch_lightning.accelerators.base_backend import Accelerator from pytorch_lightning.utilities import AMPType, rank_zero_warn", "return output def validation_step(self, args): if self.trainer.amp_backend == AMPType.NATIVE: with", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "<gh_stars>0 # Copyright The PyTorch Lightning team. # # Licensed", "# See the License for the specific language governing permissions", "# train or test results = self.train_or_test() return results def", "def __init__(self, trainer, cluster_environment=None): super().__init__(trainer, cluster_environment) def setup(self, model): #", "You may obtain a copy of the License at #", "with torch.cuda.amp.autocast(): output = self.trainer.model.validation_step(*args) else: output = self.trainer.model.validation_step(*args) return", "torch.cuda.amp.autocast(): output = self.trainer.model.test_step(*args) else: output = self.trainer.model.test_step(*args) return output", "= self.trainer.model.training_step(*args) else: output = self.trainer.model.training_step(*args) return output def validation_step(self,", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "= self.trainer.model # set up training routine self.trainer.train_loop.setup_training(model) # train", "from pytorch_lightning.utilities.exceptions import MisconfigurationException class CPUBackend(Accelerator): def __init__(self, trainer, cluster_environment=None):", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "self.setup_optimizers(model) self.trainer.model = model def train(self): model = self.trainer.model #", "up training routine self.trainer.train_loop.setup_training(model) # train or test results =", "with the License. # You may obtain a copy of", "super().__init__(trainer, cluster_environment) def setup(self, model): # run through amp wrapper", "this file except in compliance with the License. # You", "routine self.trainer.train_loop.setup_training(model) # train or test results = self.train_or_test() return", "the Apache License, Version 2.0 (the \"License\"); # you may", "args): if self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast(): output = self.trainer.model.validation_step(*args)", "self.trainer.model.training_step(*args) else: output = self.trainer.model.training_step(*args) return output def validation_step(self, args):", "== AMPType.NATIVE: with torch.cuda.amp.autocast(): output = self.trainer.model.training_step(*args) else: output =", "pytorch_lightning.accelerators.base_backend import Accelerator from pytorch_lightning.utilities import AMPType, rank_zero_warn from pytorch_lightning.utilities.exceptions", "raise MisconfigurationException('amp + cpu is not supported. Please use a", "test_step(self, args): if self.trainer.amp_backend == AMPType.NATIVE: with torch.cuda.amp.autocast(): output =", "def setup(self, model): # run through amp wrapper if self.trainer.amp_backend:", "use a GPU option') # call setup after the ddp", "test results = self.train_or_test() return results def training_step(self, args): if" ]
[ "Author, Book, TBR # Register your models here. admin.site.register(Genre) admin.site.register(Author)", "django.contrib import admin from books.models import Genre, Author, Book, TBR", "from books.models import Genre, Author, Book, TBR # Register your", "TBR # Register your models here. admin.site.register(Genre) admin.site.register(Author) admin.site.register(Book) admin.site.register(TBR)", "Book, TBR # Register your models here. admin.site.register(Genre) admin.site.register(Author) admin.site.register(Book)", "import Genre, Author, Book, TBR # Register your models here.", "from django.contrib import admin from books.models import Genre, Author, Book,", "import admin from books.models import Genre, Author, Book, TBR #", "books.models import Genre, Author, Book, TBR # Register your models", "Genre, Author, Book, TBR # Register your models here. admin.site.register(Genre)", "admin from books.models import Genre, Author, Book, TBR # Register" ]
[ "= 'http://{}:{}/api/'.format(HOST, PORT) CONFIG = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest',", "'vhosts': ['test', 'test2'], } EXCHANGE_MESSAGE_STATS = { 'ack': 1.0, 'ack_details':", "['test1'], 'tags': [\"tag1:1\", \"tag2\"], 'exchanges': ['test1'], 'collect_node_metrics': False, } CONFIG_REGEX", "1.0, 'publish_details': {'rate': 1.0}, 'publish_in': 1.0, 'publish_in_details': {'rate': 1.0}, 'publish_out':", "import os from packaging import version from datadog_checks.base.utils.common import get_docker_hostname", "1.0, 'publish_out_details': {'rate': 1.0}, 'return_unroutable': 1.0, 'return_unroutable_details': {'rate': 1.0}, 'redeliver':", "'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['test', 'test2'], } EXCHANGE_MESSAGE_STATS = { 'ack':", "} EXCHANGE_MESSAGE_STATS = { 'ack': 1.0, 'ack_details': {'rate': 1.0}, 'confirm':", "packaging import version from datadog_checks.base.utils.common import get_docker_hostname HERE = os.path.dirname(os.path.abspath(__file__))", "{'rate': 1.0}, 'confirm': 1.0, 'confirm_details': {'rate': 1.0}, 'deliver_get': 1.0, 'deliver_get_details':", "'exchanges': ['test1'], } CONFIG_NO_NODES = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest',", "license (see LICENSE) import os from packaging import version from", "'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'queues_regexes': [r'test\\d+'], 'exchanges_regexes': [r'test\\d+'],", "{ 'ack': 1.0, 'ack_details': {'rate': 1.0}, 'confirm': 1.0, 'confirm_details': {'rate':", "HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.dirname(HERE)) RABBITMQ_VERSION_RAW = os.environ['RABBITMQ_VERSION'] RABBITMQ_VERSION", "{ 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['/', 'test'],", "{ 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'queues': ['test1'], 'tags':", "BSD style license (see LICENSE) import os from packaging import", "'ack': 1.0, 'ack_details': {'rate': 1.0}, 'confirm': 1.0, 'confirm_details': {'rate': 1.0},", "'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'queues': ['test1'], 'tags': [\"tag1:1\", \"tag2\"], 'exchanges':", "CONFIG = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'queues':", "False, } CONFIG_REGEX = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass':", "'<PASSWORD>', 'vhosts': ['/', 'myvhost'], } CONFIG_WITH_FAMILY = { 'rabbitmq_api_url': URL,", "CONFIG_DEFAULT_VHOSTS = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts':", "= { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['test',", "'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['/', 'test'], } CONFIG_TEST_VHOSTS = { 'rabbitmq_api_url':", "'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['test', 'test2'], } EXCHANGE_MESSAGE_STATS =", "} CONFIG_REGEX = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>',", "{'rate': 1.0}, 'publish': 1.0, 'publish_details': {'rate': 1.0}, 'publish_in': 1.0, 'publish_in_details':", "} CONFIG_VHOSTS = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>',", "1.0}, 'publish_out': 1.0, 'publish_out_details': {'rate': 1.0}, 'return_unroutable': 1.0, 'return_unroutable_details': {'rate':", "'vhosts': ['/', 'test'], } CONFIG_TEST_VHOSTS = { 'rabbitmq_api_url': URL, 'rabbitmq_user':", "1.0}, 'deliver_get': 1.0, 'deliver_get_details': {'rate': 1.0}, 'publish': 1.0, 'publish_details': {'rate':", "from packaging import version from datadog_checks.base.utils.common import get_docker_hostname HERE =", "# Licensed under a 3-clause BSD style license (see LICENSE)", "URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'queues_regexes': [r'test\\d+'], 'exchanges_regexes': [r'test\\d+'], }", "'ack_details': {'rate': 1.0}, 'confirm': 1.0, 'confirm_details': {'rate': 1.0}, 'deliver_get': 1.0,", "{ 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['/', 'myvhost'],", "} CONFIG_WITH_FAMILY = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>',", "'confirm': 1.0, 'confirm_details': {'rate': 1.0}, 'deliver_get': 1.0, 'deliver_get_details': {'rate': 1.0},", "'guest', 'rabbitmq_pass': '<PASSWORD>', 'tag_families': True, 'queues_regexes': [r'(test)\\d+'], 'exchanges_regexes': [r'(test)\\d+'], }", "RABBITMQ_VERSION_RAW = os.environ['RABBITMQ_VERSION'] RABBITMQ_VERSION = version.parse(RABBITMQ_VERSION_RAW) CHECK_NAME = 'rabbitmq' HOST", "'deliver_get_details': {'rate': 1.0}, 'publish': 1.0, 'publish_details': {'rate': 1.0}, 'publish_in': 1.0,", "a 3-clause BSD style license (see LICENSE) import os from", "Datadog, Inc. 2018-present # All rights reserved # Licensed under", "'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['test', 'test2'], } EXCHANGE_MESSAGE_STATS = {", "'rabbitmq_pass': '<PASSWORD>', 'queues': ['test1'], 'tags': [\"tag1:1\", \"tag2\"], 'exchanges': ['test1'], }", "'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['/', 'test'], } CONFIG_TEST_VHOSTS = {", "# (C) Datadog, Inc. 2018-present # All rights reserved #", "[\"tag1:1\", \"tag2\"], 'exchanges': ['test1'], 'collect_node_metrics': False, } CONFIG_REGEX = {", "{ 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['test', 'test2'],", "} CONFIG_TEST_VHOSTS = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>',", "'exchanges_regexes': [r'test\\d+'], } CONFIG_VHOSTS = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest',", "= os.path.dirname(os.path.dirname(HERE)) RABBITMQ_VERSION_RAW = os.environ['RABBITMQ_VERSION'] RABBITMQ_VERSION = version.parse(RABBITMQ_VERSION_RAW) CHECK_NAME =", "'vhosts': ['/', 'myvhost'], } CONFIG_WITH_FAMILY = { 'rabbitmq_api_url': URL, 'rabbitmq_user':", "1.0, 'return_unroutable_details': {'rate': 1.0}, 'redeliver': 1.0, 'redeliver_details': {'rate': 1.0}, }", "1.0}, 'publish_in': 1.0, 'publish_in_details': {'rate': 1.0}, 'publish_out': 1.0, 'publish_out_details': {'rate':", "CONFIG_VHOSTS = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts':", "= os.environ['RABBITMQ_VERSION'] RABBITMQ_VERSION = version.parse(RABBITMQ_VERSION_RAW) CHECK_NAME = 'rabbitmq' HOST =", "'guest', 'rabbitmq_pass': '<PASSWORD>', 'queues': ['test1'], 'tags': [\"tag1:1\", \"tag2\"], 'exchanges': ['test1'],", "= { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['/',", "get_docker_hostname HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.dirname(HERE)) RABBITMQ_VERSION_RAW = os.environ['RABBITMQ_VERSION']", "HOST = get_docker_hostname() PORT = 15672 URL = 'http://{}:{}/api/'.format(HOST, PORT)", "\"tag2\"], 'exchanges': ['test1'], 'collect_node_metrics': False, } CONFIG_REGEX = { 'rabbitmq_api_url':", "{'rate': 1.0}, 'return_unroutable': 1.0, 'return_unroutable_details': {'rate': 1.0}, 'redeliver': 1.0, 'redeliver_details':", "URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'queues': ['test1'], 'tags': [\"tag1:1\", \"tag2\"],", "import get_docker_hostname HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.dirname(HERE)) RABBITMQ_VERSION_RAW =", "All rights reserved # Licensed under a 3-clause BSD style", "['test1'], } CONFIG_NO_NODES = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass':", "'rabbitmq_pass': '<PASSWORD>', 'tag_families': True, 'queues_regexes': [r'(test)\\d+'], 'exchanges_regexes': [r'(test)\\d+'], } CONFIG_DEFAULT_VHOSTS", "os from packaging import version from datadog_checks.base.utils.common import get_docker_hostname HERE", "'rabbitmq_pass': '<PASSWORD>', 'queues': ['test1'], 'tags': [\"tag1:1\", \"tag2\"], 'exchanges': ['test1'], 'collect_node_metrics':", "PORT) CONFIG = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>',", "[r'test\\d+'], 'exchanges_regexes': [r'test\\d+'], } CONFIG_VHOSTS = { 'rabbitmq_api_url': URL, 'rabbitmq_user':", "LICENSE) import os from packaging import version from datadog_checks.base.utils.common import", "2018-present # All rights reserved # Licensed under a 3-clause", "ROOT = os.path.dirname(os.path.dirname(HERE)) RABBITMQ_VERSION_RAW = os.environ['RABBITMQ_VERSION'] RABBITMQ_VERSION = version.parse(RABBITMQ_VERSION_RAW) CHECK_NAME", "'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'tag_families': True, 'queues_regexes': [r'(test)\\d+'],", "['/', 'test'], } CONFIG_TEST_VHOSTS = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest',", "'queues_regexes': [r'test\\d+'], 'exchanges_regexes': [r'test\\d+'], } CONFIG_VHOSTS = { 'rabbitmq_api_url': URL,", "'queues': ['test1'], 'tags': [\"tag1:1\", \"tag2\"], 'exchanges': ['test1'], 'collect_node_metrics': False, }", "1.0, 'deliver_get_details': {'rate': 1.0}, 'publish': 1.0, 'publish_details': {'rate': 1.0}, 'publish_in':", "= { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'queues': ['test1'],", "under a 3-clause BSD style license (see LICENSE) import os", "1.0}, 'publish': 1.0, 'publish_details': {'rate': 1.0}, 'publish_in': 1.0, 'publish_in_details': {'rate':", "['test1'], 'tags': [\"tag1:1\", \"tag2\"], 'exchanges': ['test1'], } CONFIG_NO_NODES = {", "RABBITMQ_VERSION = version.parse(RABBITMQ_VERSION_RAW) CHECK_NAME = 'rabbitmq' HOST = get_docker_hostname() PORT", "= { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'tag_families': True,", "'test'], } CONFIG_TEST_VHOSTS = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass':", "os.environ['RABBITMQ_VERSION'] RABBITMQ_VERSION = version.parse(RABBITMQ_VERSION_RAW) CHECK_NAME = 'rabbitmq' HOST = get_docker_hostname()", "'guest', 'rabbitmq_pass': '<PASSWORD>', 'queues_regexes': [r'test\\d+'], 'exchanges_regexes': [r'test\\d+'], } CONFIG_VHOSTS =", "= get_docker_hostname() PORT = 15672 URL = 'http://{}:{}/api/'.format(HOST, PORT) CONFIG", "'queues': ['test1'], 'tags': [\"tag1:1\", \"tag2\"], 'exchanges': ['test1'], } CONFIG_NO_NODES =", "'myvhost'], } CONFIG_WITH_FAMILY = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass':", "'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['/', 'test'], }", "'<PASSWORD>', 'queues': ['test1'], 'tags': [\"tag1:1\", \"tag2\"], 'exchanges': ['test1'], } CONFIG_NO_NODES", "CONFIG_WITH_FAMILY = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'tag_families':", "'publish_details': {'rate': 1.0}, 'publish_in': 1.0, 'publish_in_details': {'rate': 1.0}, 'publish_out': 1.0,", "= 15672 URL = 'http://{}:{}/api/'.format(HOST, PORT) CONFIG = { 'rabbitmq_api_url':", "[r'(test)\\d+'], 'exchanges_regexes': [r'(test)\\d+'], } CONFIG_DEFAULT_VHOSTS = { 'rabbitmq_api_url': URL, 'rabbitmq_user':", "'collect_node_metrics': False, } CONFIG_REGEX = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest',", "= { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'queues_regexes': [r'test\\d+'],", "style license (see LICENSE) import os from packaging import version", "URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['/', 'test'], } CONFIG_TEST_VHOSTS", "'publish': 1.0, 'publish_details': {'rate': 1.0}, 'publish_in': 1.0, 'publish_in_details': {'rate': 1.0},", "'rabbitmq' HOST = get_docker_hostname() PORT = 15672 URL = 'http://{}:{}/api/'.format(HOST,", "URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['test', 'test2'], } EXCHANGE_MESSAGE_STATS", "(see LICENSE) import os from packaging import version from datadog_checks.base.utils.common", "'publish_out': 1.0, 'publish_out_details': {'rate': 1.0}, 'return_unroutable': 1.0, 'return_unroutable_details': {'rate': 1.0},", "'queues_regexes': [r'(test)\\d+'], 'exchanges_regexes': [r'(test)\\d+'], } CONFIG_DEFAULT_VHOSTS = { 'rabbitmq_api_url': URL,", "[r'(test)\\d+'], } CONFIG_DEFAULT_VHOSTS = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass':", "Licensed under a 3-clause BSD style license (see LICENSE) import", "{ 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'tag_families': True, 'queues_regexes':", "= 'rabbitmq' HOST = get_docker_hostname() PORT = 15672 URL =", "{'rate': 1.0}, 'deliver_get': 1.0, 'deliver_get_details': {'rate': 1.0}, 'publish': 1.0, 'publish_details':", "rights reserved # Licensed under a 3-clause BSD style license", "'deliver_get': 1.0, 'deliver_get_details': {'rate': 1.0}, 'publish': 1.0, 'publish_details': {'rate': 1.0},", "CONFIG_NO_NODES = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'queues':", "'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['/', 'myvhost'], }", "'rabbitmq_pass': '<PASSWORD>', 'queues_regexes': [r'test\\d+'], 'exchanges_regexes': [r'test\\d+'], } CONFIG_VHOSTS = {", "['test', 'test2'], } EXCHANGE_MESSAGE_STATS = { 'ack': 1.0, 'ack_details': {'rate':", "15672 URL = 'http://{}:{}/api/'.format(HOST, PORT) CONFIG = { 'rabbitmq_api_url': URL,", "URL = 'http://{}:{}/api/'.format(HOST, PORT) CONFIG = { 'rabbitmq_api_url': URL, 'rabbitmq_user':", "EXCHANGE_MESSAGE_STATS = { 'ack': 1.0, 'ack_details': {'rate': 1.0}, 'confirm': 1.0,", "'<PASSWORD>', 'tag_families': True, 'queues_regexes': [r'(test)\\d+'], 'exchanges_regexes': [r'(test)\\d+'], } CONFIG_DEFAULT_VHOSTS =", "'tag_families': True, 'queues_regexes': [r'(test)\\d+'], 'exchanges_regexes': [r'(test)\\d+'], } CONFIG_DEFAULT_VHOSTS = {", "'<PASSWORD>', 'vhosts': ['/', 'test'], } CONFIG_TEST_VHOSTS = { 'rabbitmq_api_url': URL,", "CONFIG_TEST_VHOSTS = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts':", "CHECK_NAME = 'rabbitmq' HOST = get_docker_hostname() PORT = 15672 URL", "CONFIG_REGEX = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'queues_regexes':", "os.path.dirname(os.path.dirname(HERE)) RABBITMQ_VERSION_RAW = os.environ['RABBITMQ_VERSION'] RABBITMQ_VERSION = version.parse(RABBITMQ_VERSION_RAW) CHECK_NAME = 'rabbitmq'", "True, 'queues_regexes': [r'(test)\\d+'], 'exchanges_regexes': [r'(test)\\d+'], } CONFIG_DEFAULT_VHOSTS = { 'rabbitmq_api_url':", "'confirm_details': {'rate': 1.0}, 'deliver_get': 1.0, 'deliver_get_details': {'rate': 1.0}, 'publish': 1.0,", "Inc. 2018-present # All rights reserved # Licensed under a", "URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['/', 'myvhost'], } CONFIG_WITH_FAMILY", "'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['/', 'test'], } CONFIG_TEST_VHOSTS =", "{'rate': 1.0}, 'publish_in': 1.0, 'publish_in_details': {'rate': 1.0}, 'publish_out': 1.0, 'publish_out_details':", "datadog_checks.base.utils.common import get_docker_hostname HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.dirname(HERE)) RABBITMQ_VERSION_RAW", "'exchanges_regexes': [r'(test)\\d+'], } CONFIG_DEFAULT_VHOSTS = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest',", "# All rights reserved # Licensed under a 3-clause BSD", "1.0, 'confirm_details': {'rate': 1.0}, 'deliver_get': 1.0, 'deliver_get_details': {'rate': 1.0}, 'publish':", "(C) Datadog, Inc. 2018-present # All rights reserved # Licensed", "1.0}, 'return_unroutable': 1.0, 'return_unroutable_details': {'rate': 1.0}, 'redeliver': 1.0, 'redeliver_details': {'rate':", "['/', 'myvhost'], } CONFIG_WITH_FAMILY = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest',", "'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'queues': ['test1'], 'tags': [\"tag1:1\",", "'<PASSWORD>', 'vhosts': ['test', 'test2'], } EXCHANGE_MESSAGE_STATS = { 'ack': 1.0,", "from datadog_checks.base.utils.common import get_docker_hostname HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.dirname(HERE))", "version.parse(RABBITMQ_VERSION_RAW) CHECK_NAME = 'rabbitmq' HOST = get_docker_hostname() PORT = 15672", "'exchanges': ['test1'], 'collect_node_metrics': False, } CONFIG_REGEX = { 'rabbitmq_api_url': URL,", "3-clause BSD style license (see LICENSE) import os from packaging", "PORT = 15672 URL = 'http://{}:{}/api/'.format(HOST, PORT) CONFIG = {", "'<PASSWORD>', 'queues': ['test1'], 'tags': [\"tag1:1\", \"tag2\"], 'exchanges': ['test1'], 'collect_node_metrics': False,", "[\"tag1:1\", \"tag2\"], 'exchanges': ['test1'], } CONFIG_NO_NODES = { 'rabbitmq_api_url': URL,", "1.0, 'publish_in_details': {'rate': 1.0}, 'publish_out': 1.0, 'publish_out_details': {'rate': 1.0}, 'return_unroutable':", "'test2'], } EXCHANGE_MESSAGE_STATS = { 'ack': 1.0, 'ack_details': {'rate': 1.0},", "'tags': [\"tag1:1\", \"tag2\"], 'exchanges': ['test1'], } CONFIG_NO_NODES = { 'rabbitmq_api_url':", "'<PASSWORD>', 'queues_regexes': [r'test\\d+'], 'exchanges_regexes': [r'test\\d+'], } CONFIG_VHOSTS = { 'rabbitmq_api_url':", "'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['test', 'test2'], }", "1.0, 'ack_details': {'rate': 1.0}, 'confirm': 1.0, 'confirm_details': {'rate': 1.0}, 'deliver_get':", "= version.parse(RABBITMQ_VERSION_RAW) CHECK_NAME = 'rabbitmq' HOST = get_docker_hostname() PORT =", "'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['/', 'myvhost'], } CONFIG_WITH_FAMILY =", "['test1'], 'collect_node_metrics': False, } CONFIG_REGEX = { 'rabbitmq_api_url': URL, 'rabbitmq_user':", "'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'queues_regexes': [r'test\\d+'], 'exchanges_regexes': [r'test\\d+'], } CONFIG_VHOSTS", "get_docker_hostname() PORT = 15672 URL = 'http://{}:{}/api/'.format(HOST, PORT) CONFIG =", "1.0}, 'confirm': 1.0, 'confirm_details': {'rate': 1.0}, 'deliver_get': 1.0, 'deliver_get_details': {'rate':", "} CONFIG_NO_NODES = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>',", "'tags': [\"tag1:1\", \"tag2\"], 'exchanges': ['test1'], 'collect_node_metrics': False, } CONFIG_REGEX =", "'publish_in': 1.0, 'publish_in_details': {'rate': 1.0}, 'publish_out': 1.0, 'publish_out_details': {'rate': 1.0},", "= { 'ack': 1.0, 'ack_details': {'rate': 1.0}, 'confirm': 1.0, 'confirm_details':", "= os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.dirname(HERE)) RABBITMQ_VERSION_RAW = os.environ['RABBITMQ_VERSION'] RABBITMQ_VERSION =", "reserved # Licensed under a 3-clause BSD style license (see", "} CONFIG_DEFAULT_VHOSTS = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>',", "'return_unroutable': 1.0, 'return_unroutable_details': {'rate': 1.0}, 'redeliver': 1.0, 'redeliver_details': {'rate': 1.0},", "'publish_in_details': {'rate': 1.0}, 'publish_out': 1.0, 'publish_out_details': {'rate': 1.0}, 'return_unroutable': 1.0,", "\"tag2\"], 'exchanges': ['test1'], } CONFIG_NO_NODES = { 'rabbitmq_api_url': URL, 'rabbitmq_user':", "os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.dirname(HERE)) RABBITMQ_VERSION_RAW = os.environ['RABBITMQ_VERSION'] RABBITMQ_VERSION = version.parse(RABBITMQ_VERSION_RAW)", "[r'test\\d+'], } CONFIG_VHOSTS = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass':", "'publish_out_details': {'rate': 1.0}, 'return_unroutable': 1.0, 'return_unroutable_details': {'rate': 1.0}, 'redeliver': 1.0,", "import version from datadog_checks.base.utils.common import get_docker_hostname HERE = os.path.dirname(os.path.abspath(__file__)) ROOT", "version from datadog_checks.base.utils.common import get_docker_hostname HERE = os.path.dirname(os.path.abspath(__file__)) ROOT =", "'guest', 'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['/', 'myvhost'], } CONFIG_WITH_FAMILY = {", "URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'tag_families': True, 'queues_regexes': [r'(test)\\d+'], 'exchanges_regexes':", "{ 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'queues_regexes': [r'test\\d+'], 'exchanges_regexes':", "'http://{}:{}/api/'.format(HOST, PORT) CONFIG = { 'rabbitmq_api_url': URL, 'rabbitmq_user': 'guest', 'rabbitmq_pass':", "'rabbitmq_pass': '<PASSWORD>', 'vhosts': ['/', 'myvhost'], } CONFIG_WITH_FAMILY = { 'rabbitmq_api_url':", "'rabbitmq_user': 'guest', 'rabbitmq_pass': '<PASSWORD>', 'tag_families': True, 'queues_regexes': [r'(test)\\d+'], 'exchanges_regexes': [r'(test)\\d+'],", "{'rate': 1.0}, 'publish_out': 1.0, 'publish_out_details': {'rate': 1.0}, 'return_unroutable': 1.0, 'return_unroutable_details':" ]
[ "a valid semver version string (0.2.0). :rtype: ``str`` \"\"\" version", "'the config or the default values in the schema.') except", "that if metadata.get('ref', None): pack_ref = metadata['ref'] elif pack_directory_name and", "= pack_name or 'unknown' schema = util_schema.get_schema_for_resource_parameters(parameters_schema=config_schema, allow_additional_properties=True) instance =", "is the path where common code for sensors and actions", "actions. The lib structure also needs to follow a python", "2.0 (the \"License\"); # you may not use this file", "MANIFEST_FILE_NAME) if not os.path.isfile(manifest_path): raise ValueError('Pack \"%s\" is missing %s", "metadata file is empty' % (pack_dir)) return content def get_pack_warnings(pack_metadata):", "from the \"name\" attribute. :rtype: ``str`` \"\"\" pack_ref = None", "directory. :rtype: ``dict`` \"\"\" manifest_path = os.path.join(pack_dir, MANIFEST_FILE_NAME) if not", "and set(versions) == set(['2']): warning = PACK_PYTHON2_WARNING % pack_name return", "to add \"ref\" attribute which contains only word ' 'characters", "from st2common.content.loader import MetaLoader from st2common.persistence.pack import Pack from st2common.exceptions.apivalidation", ":rtype: ``str`` \"\"\" pack_dir = getattr(pack_db, 'path', None) if not", "Use ' 'of \"decrypt_kv\" jinja filter is not allowed for", "return content def get_pack_warnings(pack_metadata): \"\"\" Return warning string if pack", "pack metadata file. If this attribute is not provided, an", "' 'schema are automatically decrypted by default. Use ' 'of", "attribute. :rtype: ``str`` \"\"\" pack_ref = None # The rules", "% pack_name return warning def validate_config_against_schema(config_schema, config_object, config_path, pack_name=None): \"\"\"", "for pack \"%s\" (%s): %s' % (attribute, pack_name, config_path, six.text_type(e)))", "pack_name = pack_name or 'unknown' schema = util_schema.get_schema_for_resource_parameters(parameters_schema=config_schema, allow_additional_properties=True) instance", "import schema as util_schema from st2common.constants.pack import MANIFEST_FILE_NAME from st2common.constants.pack", "six.PY2: PACK_PYTHON2_WARNING = \"DEPRECATION WARNING: Pack %s only supports Python", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "since st2 v3.4.0. \" \\ \"Please update your packs to", "if not content: raise ValueError('Pack \"%s\" metadata file is empty'", "are automatically decrypted by default. Use ' 'of \"decrypt_kv\" jinja", "name attribute to contain only' 'word characters.') raise ValueError(msg %", "# which are in sub-directories) # 2. If attribute is", "been removed since st2 v3.4.0. \" \\ \"Please update your", "infer \"ref\" from the \"name\" attribute. :rtype: ``str`` \"\"\" pack_ref", "'path', []) if isinstance(attribute, (tuple, list, collections.Iterable)): attribute = [str(item)", "config_path, pack_name=None): \"\"\" Validate provided config dictionary against the provided", "'word characters.') raise ValueError(msg % (metadata['name'])) return pack_ref def get_pack_metadata(pack_dir):", "' 'of \"decrypt_kv\" jinja filter is not allowed for '", "\\ \"Please consider updating your packs to work with Python", "\"%s\" is missing %s file' % (pack_dir, MANIFEST_FILE_NAME)) meta_loader =", "language governing permissions and # limitations under the License. from", "str(version) version_seperator_count = version.count('.') if version_seperator_count == 1: version =", "is available, we used that # 2. If pack_directory_name is", "to contain only' 'word characters.') raise ValueError(msg % (metadata['name'])) return", "provided, an attempt is made to infer \"ref\" from the", "cls=util_schema.CustomValidator, use_default=True, allow_default_none=True) for key in cleaned: if (jinja_utils.is_jinja_expression(value=cleaned.get(key)) and", "return pack_common_libs_path def get_pack_common_libs_path_for_pack_db(pack_db): \"\"\" Return the pack's common lib", "def validate_config_against_schema(config_schema, config_object, config_path, pack_name=None): \"\"\" Validate provided config dictionary", "use this file except in compliance with the License. #", "as jinja_utils __all__ = [ 'get_pack_ref_from_metadata', 'get_pack_metadata', 'get_pack_warnings', 'get_pack_common_libs_path_for_pack_ref', 'get_pack_common_libs_path_for_pack_db',", "__all__ = [ 'get_pack_ref_from_metadata', 'get_pack_metadata', 'get_pack_warnings', 'get_pack_common_libs_path_for_pack_ref', 'get_pack_common_libs_path_for_pack_db', 'validate_config_against_schema', 'normalize_pack_version'", "the pack is at /opt/stackstorm/packs/my_pack, you can place common library", "Please check the specified values in ' 'the config or", "in attribute] attribute = '.'.join(attribute) else: attribute = str(attribute) msg", "to avoid performance overhead of importing this module when it's", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "that (this only applies to packs # which are in", "not pack_dir: return None libs_path = os.path.join(pack_dir, 'lib') return libs_path", "warning def validate_config_against_schema(config_schema, config_object, config_path, pack_name=None): \"\"\" Validate provided config", "License. # You may obtain a copy of the License", "the specified values in ' 'the config or the default", "supported :rtype: ``str`` \"\"\" warning = None versions = pack_metadata.get('python_versions',", "\"Please update your packs to work with Python 3.x\" def", "to work with Python 3.x\" else: PACK_PYTHON2_WARNING = \"DEPRECATION WARNING:", "StackStorm Authors. # Copyright 2019 Extreme Networks, Inc. # #", "``str`` \"\"\" warning = None versions = pack_metadata.get('python_versions', None) pack_name", "pack_name or 'unknown' schema = util_schema.get_schema_for_resource_parameters(parameters_schema=config_schema, allow_additional_properties=True) instance = config_object", "under the License is distributed on an \"AS IS\" BASIS,", "config_path, six.text_type(e))) raise jsonschema.ValidationError(msg) return cleaned def get_pack_common_libs_path_for_pack_ref(pack_ref): pack_db =", "License for the specific language governing permissions and # limitations", "libs_path = os.path.join(pack_dir, 'lib') return libs_path def normalize_pack_version(version): \"\"\" Normalize", "re import collections import six from st2common.util import schema as", "\" \\ \"Please consider updating your packs to work with", "\"Python 2 support has been removed since st2 v3.4.0. \"", "if re.match(PACK_REF_WHITELIST_REGEX, metadata['name']): pack_ref = metadata['name'] else: msg = ('Pack", "ValueError('Pack \"%s\" metadata file is empty' % (pack_dir)) return content", "pack_common_libs_path def get_pack_common_libs_path_for_pack_db(pack_db): \"\"\" Return the pack's common lib path.", "this attribute is not provided, an attempt is made to", "StackStorm v2.1 non valid semver version string (e.g. 0.2) to", "os.path.join(pack_dir, 'lib') return libs_path def normalize_pack_version(version): \"\"\" Normalize old, pre", ":rtype: ``dict`` \"\"\" manifest_path = os.path.join(pack_dir, MANIFEST_FILE_NAME) if not os.path.isfile(manifest_path):", "[]) if isinstance(attribute, (tuple, list, collections.Iterable)): attribute = [str(item) for", "placed. For example, if the pack is at /opt/stackstorm/packs/my_pack, you", "/opt/stackstorm/packs/my_pack, you can place common library code for actions and", "schema dictionary. \"\"\" # NOTE: Lazy improt to avoid performance", "You either need to add \"ref\" attribute which contains only", "to infer \"ref\" from the \"name\" attribute. :rtype: ``str`` \"\"\"", "\"%s\" metadata file is empty' % (pack_dir)) return content def", "\"\"\" pack_dir = getattr(pack_db, 'path', None) if not pack_dir: return", "dropped in future releases. \" \\ \"Please consider updating your", "except jsonschema.ValidationError as e: attribute = getattr(e, 'path', []) if", "the path where common code for sensors and actions are", "pack_name=None): \"\"\" Validate provided config dictionary against the provided config", "util_schema from st2common.constants.pack import MANIFEST_FILE_NAME from st2common.constants.pack import PACK_REF_WHITELIST_REGEX from", "True\" in config ' 'schema are automatically decrypted by default.", "return None libs_path = os.path.join(pack_dir, 'lib') return libs_path def normalize_pack_version(version):", "set(versions) == set(['2']): warning = PACK_PYTHON2_WARNING % pack_name return warning", "in compliance with the License. # You may obtain a", "re.match(PACK_REF_WHITELIST_REGEX, metadata['name']): pack_ref = metadata['name'] else: msg = ('Pack name", "pack_name return warning def validate_config_against_schema(config_schema, config_object, config_path, pack_name=None): \"\"\" Validate", "is empty' % (pack_dir)) return content def get_pack_warnings(pack_metadata): \"\"\" Return", "DB model :type pack_db: :class:`PackDB` :rtype: ``str`` \"\"\" pack_dir =", "Return the pack's common lib path. This is the path", "software # distributed under the License is distributed on an", "\"Please consider updating your packs to work with Python 3.x\"", "actions are placed. For example, if the pack is at", "sensors and actions are placed. For example, if the pack", "# 2. If pack_directory_name is available we use that (this", "criteria, we use that if metadata.get('ref', None): pack_ref = metadata['ref']", "file. :param pack_db: Pack DB model :type pack_db: :class:`PackDB` :rtype:", "Python 2.x. \" \\ \"Python 2 support will be dropped", "import os import re import collections import six from st2common.util", "valid semver version string (e.g. 0.2) to a valid semver", "attribute = '.'.join(attribute) else: attribute = str(attribute) msg = ('Failed", "\"secret: True\" in config ' 'schema are automatically decrypted by", "it's not used import jsonschema pack_name = pack_name or 'unknown'", "= [ 'get_pack_ref_from_metadata', 'get_pack_metadata', 'get_pack_warnings', 'get_pack_common_libs_path_for_pack_ref', 'get_pack_common_libs_path_for_pack_db', 'validate_config_against_schema', 'normalize_pack_version' ]", "The rules for the pack ref are as follows: #", "the default values in the schema.') except jsonschema.ValidationError as e:", "('Pack name \"%s\" contains invalid characters and \"ref\" attribute is", "The StackStorm Authors. # Copyright 2019 Extreme Networks, Inc. #", "an attempt is made to infer \"ref\" from the \"name\"", "to a valid semver version string (0.2.0). :rtype: ``str`` \"\"\"", "PACK_PYTHON2_WARNING % pack_name return warning def validate_config_against_schema(config_schema, config_object, config_path, pack_name=None):", "'get_pack_warnings', 'get_pack_common_libs_path_for_pack_ref', 'get_pack_common_libs_path_for_pack_db', 'validate_config_against_schema', 'normalize_pack_version' ] # Common format for", "common lib path. This is the path where common code", "code for actions and sensors in /opt/stackstorm/packs/my_pack/lib/. This common library", "instance = config_object try: cleaned = util_schema.validate(instance=instance, schema=schema, cls=util_schema.CustomValidator, use_default=True,", "pack_name, config_path, six.text_type(e))) raise jsonschema.ValidationError(msg) return cleaned def get_pack_common_libs_path_for_pack_ref(pack_ref): pack_db", "contains invalid characters and \"ref\" attribute is not ' 'available.", "the provided config schema dictionary. \"\"\" # NOTE: Lazy improt", "] # Common format for python 2.7 warning if six.PY2:", "for key in cleaned: if (jinja_utils.is_jinja_expression(value=cleaned.get(key)) and \"decrypt_kv\" in cleaned.get(key)", "= None # The rules for the pack ref are", "= util_schema.validate(instance=instance, schema=schema, cls=util_schema.CustomValidator, use_default=True, allow_default_none=True) for key in cleaned:", "where common code for sensors and actions are placed. For", "in cleaned: if (jinja_utils.is_jinja_expression(value=cleaned.get(key)) and \"decrypt_kv\" in cleaned.get(key) and config_schema.get(key).get('secret')):", "``str`` \"\"\" pack_ref = None # The rules for the", "msg = ('Pack name \"%s\" contains invalid characters and \"ref\"", "isinstance(attribute, (tuple, list, collections.Iterable)): attribute = [str(item) for item in", "None libs_path = os.path.join(pack_dir, 'lib') return libs_path def normalize_pack_version(version): \"\"\"", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "def get_pack_ref_from_metadata(metadata, pack_directory_name=None): \"\"\" Utility function which retrieves pack \"ref\"", "pack ref are as follows: # 1. If ref attribute", "libs_path def normalize_pack_version(version): \"\"\" Normalize old, pre StackStorm v2.1 non", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "= os.path.join(pack_dir, 'lib') return libs_path def normalize_pack_version(version): \"\"\" Normalize old,", "code for sensors and actions are placed. For example, if", "from st2common.exceptions.apivalidation import ValueValidationException from st2common.util import jinja as jinja_utils", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "in config for pack \"%s\" (%s): %s' % (attribute, pack_name,", "is supported :rtype: ``str`` \"\"\" warning = None versions =", "config ' 'schema are automatically decrypted by default. Use '", "to in writing, software # distributed under the License is", "is and pack name meets the valid name # criteria,", "invalid characters and \"ref\" attribute is not ' 'available. You", "# See the License for the specific language governing permissions", "six from st2common.util import schema as util_schema from st2common.constants.pack import", "consider updating your packs to work with Python 3.x\" else:", "is not provided, an attempt is made to infer \"ref\"", "characters and \"ref\" attribute is not ' 'available. You either", "\"ref\" attribute which contains only word ' 'characters to the", "overhead of importing this module when it's not used import", "(0.2.0). :rtype: ``str`` \"\"\" version = str(version) version_seperator_count = version.count('.')", "made to infer \"ref\" from the \"name\" attribute. :rtype: ``str``", "values. Please check the specified values in ' 'the config", "or agreed to in writing, software # distributed under the", "else: PACK_PYTHON2_WARNING = \"DEPRECATION WARNING: Pack %s only supports Python", "'available. You either need to add \"ref\" attribute which contains", "is not ' 'available. You either need to add \"ref\"", "required by applicable law or agreed to in writing, software", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "\"\"\" pack_ref = None # The rules for the pack", "cleaned: if (jinja_utils.is_jinja_expression(value=cleaned.get(key)) and \"decrypt_kv\" in cleaned.get(key) and config_schema.get(key).get('secret')): raise", "with the License. # You may obtain a copy of", "= getattr(e, 'path', []) if isinstance(attribute, (tuple, list, collections.Iterable)): attribute", "st2common.util import jinja as jinja_utils __all__ = [ 'get_pack_ref_from_metadata', 'get_pack_metadata',", "schema.') except jsonschema.ValidationError as e: attribute = getattr(e, 'path', [])", "work with Python 3.x\" def get_pack_ref_from_metadata(metadata, pack_directory_name=None): \"\"\" Utility function", "absolute_import import os import re import collections import six from", "the schema.') except jsonschema.ValidationError as e: attribute = getattr(e, 'path',", "old, pre StackStorm v2.1 non valid semver version string (e.g.", "jinja as jinja_utils __all__ = [ 'get_pack_ref_from_metadata', 'get_pack_metadata', 'get_pack_warnings', 'get_pack_common_libs_path_for_pack_ref',", "pack metadata indicates only python 2 is supported :rtype: ``str``", "get_pack_common_libs_path_for_pack_db(pack_db=pack_db) return pack_common_libs_path def get_pack_common_libs_path_for_pack_db(pack_db): \"\"\" Return the pack's common", "for python sensors and actions. The lib structure also needs", "warning if six.PY2: PACK_PYTHON2_WARNING = \"DEPRECATION WARNING: Pack %s only", "default values in the schema.') except jsonschema.ValidationError as e: attribute", "e: attribute = getattr(e, 'path', []) if isinstance(attribute, (tuple, list,", "model :type pack_db: :class:`PackDB` :rtype: ``str`` \"\"\" pack_dir = getattr(pack_db,", "meets the valid name # criteria, we use that if", "This common library code is only available for python sensors", "for the pack ref are as follows: # 1. If", "compliance with the License. # You may obtain a copy", "future releases. \" \\ \"Please consider updating your packs to", "pack_ref = metadata['name'] else: msg = ('Pack name \"%s\" contains", "agreed to in writing, software # distributed under the License", "six.text_type(e))) raise jsonschema.ValidationError(msg) return cleaned def get_pack_common_libs_path_for_pack_ref(pack_ref): pack_db = Pack.get_by_ref(pack_ref)", "allow_additional_properties=True) instance = config_object try: cleaned = util_schema.validate(instance=instance, schema=schema, cls=util_schema.CustomValidator,", "\"decrypt_kv\" jinja filter is not allowed for ' 'such values.", "st2common.content.loader import MetaLoader from st2common.persistence.pack import Pack from st2common.exceptions.apivalidation import", "pack_directory_name and re.match(PACK_REF_WHITELIST_REGEX, pack_directory_name): pack_ref = pack_directory_name else: if re.match(PACK_REF_WHITELIST_REGEX,", "is available we use that (this only applies to packs", "# limitations under the License. from __future__ import absolute_import import", "'get_pack_common_libs_path_for_pack_ref', 'get_pack_common_libs_path_for_pack_db', 'validate_config_against_schema', 'normalize_pack_version' ] # Common format for python", "distributed under the License is distributed on an \"AS IS\"", "If attribute is not available, but pack name is and", "and pack name meets the valid name # criteria, we", "if metadata.get('ref', None): pack_ref = metadata['ref'] elif pack_directory_name and re.match(PACK_REF_WHITELIST_REGEX,", "need to add \"ref\" attribute which contains only word '", "pack's common lib path. This is the path where common", "python convention with a __init__.py file. :param pack_db: Pack DB", "% (metadata['name'])) return pack_ref def get_pack_metadata(pack_dir): \"\"\" Return parsed metadata", "pack name is and pack name meets the valid name", "raise ValueValidationException('Values specified as \"secret: True\" in config ' 'schema", "if the pack is at /opt/stackstorm/packs/my_pack, you can place common", "= os.path.join(pack_dir, MANIFEST_FILE_NAME) if not os.path.isfile(manifest_path): raise ValueError('Pack \"%s\" is", "jsonschema pack_name = pack_name or 'unknown' schema = util_schema.get_schema_for_resource_parameters(parameters_schema=config_schema, allow_additional_properties=True)", "# The rules for the pack ref are as follows:", "express or implied. # See the License for the specific", "Return warning string if pack metadata indicates only python 2", "from st2common.util import schema as util_schema from st2common.constants.pack import MANIFEST_FILE_NAME", "2.x. \" \\ \"Python 2 support has been removed since", "except in compliance with the License. # You may obtain", "%s file' % (pack_dir, MANIFEST_FILE_NAME)) meta_loader = MetaLoader() content =", "config_schema.get(key).get('secret')): raise ValueValidationException('Values specified as \"secret: True\" in config '", "in config ' 'schema are automatically decrypted by default. Use", "we used that # 2. If pack_directory_name is available we", "<reponame>timgates42/st2 # Copyright 2020 The StackStorm Authors. # Copyright 2019", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "is missing %s file' % (pack_dir, MANIFEST_FILE_NAME)) meta_loader = MetaLoader()", "schema as util_schema from st2common.constants.pack import MANIFEST_FILE_NAME from st2common.constants.pack import", "validating attribute \"%s\" in config for pack \"%s\" (%s): %s'", "not use this file except in compliance with the License.", "'normalize_pack_version' ] # Common format for python 2.7 warning if", "__init__.py file. :param pack_db: Pack DB model :type pack_db: :class:`PackDB`", "attribute] attribute = '.'.join(attribute) else: attribute = str(attribute) msg =", "dictionary against the provided config schema dictionary. \"\"\" # NOTE:", "version string (0.2.0). :rtype: ``str`` \"\"\" version = str(version) version_seperator_count", "with Python 3.x\" def get_pack_ref_from_metadata(metadata, pack_directory_name=None): \"\"\" Utility function which", "string (0.2.0). :rtype: ``str`` \"\"\" version = str(version) version_seperator_count =", "= str(version) version_seperator_count = version.count('.') if version_seperator_count == 1: version", "writing, software # distributed under the License is distributed on", "pack_common_libs_path = get_pack_common_libs_path_for_pack_db(pack_db=pack_db) return pack_common_libs_path def get_pack_common_libs_path_for_pack_db(pack_db): \"\"\" Return the", "you may not use this file except in compliance with", "\"DEPRECATION WARNING: Pack %s only supports Python 2.x. \" \\", "warning string if pack metadata indicates only python 2 is", "metadata.get('ref', None): pack_ref = metadata['ref'] elif pack_directory_name and re.match(PACK_REF_WHITELIST_REGEX, pack_directory_name):", "2.x. \" \\ \"Python 2 support will be dropped in", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "empty' % (pack_dir)) return content def get_pack_warnings(pack_metadata): \"\"\" Return warning", "versions = pack_metadata.get('python_versions', None) pack_name = pack_metadata.get('name', None) if versions", "else: msg = ('Pack name \"%s\" contains invalid characters and", "ValueError(msg % (metadata['name'])) return pack_ref def get_pack_metadata(pack_dir): \"\"\" Return parsed", "\"\"\" warning = None versions = pack_metadata.get('python_versions', None) pack_name =", "example, if the pack is at /opt/stackstorm/packs/my_pack, you can place", "if (jinja_utils.is_jinja_expression(value=cleaned.get(key)) and \"decrypt_kv\" in cleaned.get(key) and config_schema.get(key).get('secret')): raise ValueValidationException('Values", "will be dropped in future releases. \" \\ \"Please consider", "from st2common.constants.pack import MANIFEST_FILE_NAME from st2common.constants.pack import PACK_REF_WHITELIST_REGEX from st2common.content.loader", "pre StackStorm v2.1 non valid semver version string (e.g. 0.2)", "= pack_directory_name else: if re.match(PACK_REF_WHITELIST_REGEX, metadata['name']): pack_ref = metadata['name'] else:", "# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme", "'schema are automatically decrypted by default. Use ' 'of \"decrypt_kv\"", "removed since st2 v3.4.0. \" \\ \"Please update your packs", "name meets the valid name # criteria, we use that", "__future__ import absolute_import import os import re import collections import", "pack_directory_name): pack_ref = pack_directory_name else: if re.match(PACK_REF_WHITELIST_REGEX, metadata['name']): pack_ref =", "to work with Python 3.x\" def get_pack_ref_from_metadata(metadata, pack_directory_name=None): \"\"\" Utility", "in /opt/stackstorm/packs/my_pack/lib/. This common library code is only available for", "str(attribute) msg = ('Failed validating attribute \"%s\" in config for", "CONDITIONS OF ANY KIND, either express or implied. # See", "\"Python 2 support will be dropped in future releases. \"", "If this attribute is not provided, an attempt is made", "pack \"%s\" (%s): %s' % (attribute, pack_name, config_path, six.text_type(e))) raise", "% (pack_dir, MANIFEST_FILE_NAME)) meta_loader = MetaLoader() content = meta_loader.load(manifest_path) if", "the pack metadata file or update name attribute to contain", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "you can place common library code for actions and sensors", "(e.g. 0.2) to a valid semver version string (0.2.0). :rtype:", "st2common.persistence.pack import Pack from st2common.exceptions.apivalidation import ValueValidationException from st2common.util import", "is only available for python sensors and actions. The lib", "only supports Python 2.x. \" \\ \"Python 2 support will", "and \"ref\" attribute is not ' 'available. You either need", "collections import six from st2common.util import schema as util_schema from", "1. If ref attribute is available, we used that #", "and config_schema.get(key).get('secret')): raise ValueValidationException('Values specified as \"secret: True\" in config", "use that if metadata.get('ref', None): pack_ref = metadata['ref'] elif pack_directory_name", "which contains only word ' 'characters to the pack metadata", "at /opt/stackstorm/packs/my_pack, you can place common library code for actions", "pack_db: :class:`PackDB` :rtype: ``str`` \"\"\" pack_dir = getattr(pack_db, 'path', None)", "pack_metadata.get('python_versions', None) pack_name = pack_metadata.get('name', None) if versions and set(versions)", "library code for actions and sensors in /opt/stackstorm/packs/my_pack/lib/. This common", "attribute is not ' 'available. You either need to add", "available for python sensors and actions. The lib structure also", "None) pack_name = pack_metadata.get('name', None) if versions and set(versions) ==", "default. Use ' 'of \"decrypt_kv\" jinja filter is not allowed", "Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks,", "Pack.get_by_ref(pack_ref) pack_common_libs_path = get_pack_common_libs_path_for_pack_db(pack_db=pack_db) return pack_common_libs_path def get_pack_common_libs_path_for_pack_db(pack_db): \"\"\" Return", "'get_pack_ref_from_metadata', 'get_pack_metadata', 'get_pack_warnings', 'get_pack_common_libs_path_for_pack_ref', 'get_pack_common_libs_path_for_pack_db', 'validate_config_against_schema', 'normalize_pack_version' ] # Common", "metadata indicates only python 2 is supported :rtype: ``str`` \"\"\"", "applies to packs # which are in sub-directories) # 2.", "semver version string (0.2.0). :rtype: ``str`` \"\"\" version = str(version)", "python 2.7 warning if six.PY2: PACK_PYTHON2_WARNING = \"DEPRECATION WARNING: Pack", "is not available, but pack name is and pack name", "with a __init__.py file. :param pack_db: Pack DB model :type", "(this only applies to packs # which are in sub-directories)", "the pack ref are as follows: # 1. If ref", "actions and sensors in /opt/stackstorm/packs/my_pack/lib/. This common library code is", "attribute is not available, but pack name is and pack", "OR CONDITIONS OF ANY KIND, either express or implied. #", "Return parsed metadata for a particular pack directory. :rtype: ``dict``", "the License is distributed on an \"AS IS\" BASIS, #", "or 'unknown' schema = util_schema.get_schema_for_resource_parameters(parameters_schema=config_schema, allow_additional_properties=True) instance = config_object try:", "'unknown' schema = util_schema.get_schema_for_resource_parameters(parameters_schema=config_schema, allow_additional_properties=True) instance = config_object try: cleaned", ":class:`PackDB` :rtype: ``str`` \"\"\" pack_dir = getattr(pack_db, 'path', None) if", "the \"name\" attribute. :rtype: ``str`` \"\"\" pack_ref = None #", "os.path.isfile(manifest_path): raise ValueError('Pack \"%s\" is missing %s file' % (pack_dir,", "pack_name = pack_metadata.get('name', None) if versions and set(versions) == set(['2']):", "a python convention with a __init__.py file. :param pack_db: Pack", "releases. \" \\ \"Please consider updating your packs to work", "or the default values in the schema.') except jsonschema.ValidationError as", "in sub-directories) # 2. If attribute is not available, but", "manifest_path = os.path.join(pack_dir, MANIFEST_FILE_NAME) if not os.path.isfile(manifest_path): raise ValueError('Pack \"%s\"", "in cleaned.get(key) and config_schema.get(key).get('secret')): raise ValueValidationException('Values specified as \"secret: True\"", "2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, Inc.", "support will be dropped in future releases. \" \\ \"Please", "provided config schema dictionary. \"\"\" # NOTE: Lazy improt to", "pack_db: Pack DB model :type pack_db: :class:`PackDB` :rtype: ``str`` \"\"\"", "= '.'.join(attribute) else: attribute = str(attribute) msg = ('Failed validating", "2 support has been removed since st2 v3.4.0. \" \\", "as \"secret: True\" in config ' 'schema are automatically decrypted", "law or agreed to in writing, software # distributed under", "used that # 2. If pack_directory_name is available we use", "= version.count('.') if version_seperator_count == 1: version = version +", "not allowed for ' 'such values. Please check the specified", "ValueError('Pack \"%s\" is missing %s file' % (pack_dir, MANIFEST_FILE_NAME)) meta_loader", "def get_pack_common_libs_path_for_pack_ref(pack_ref): pack_db = Pack.get_by_ref(pack_ref) pack_common_libs_path = get_pack_common_libs_path_for_pack_db(pack_db=pack_db) return pack_common_libs_path", "only supports Python 2.x. \" \\ \"Python 2 support has", "automatically decrypted by default. Use ' 'of \"decrypt_kv\" jinja filter", "or update name attribute to contain only' 'word characters.') raise", "is at /opt/stackstorm/packs/my_pack, you can place common library code for", "[str(item) for item in attribute] attribute = '.'.join(attribute) else: attribute", "sensors in /opt/stackstorm/packs/my_pack/lib/. This common library code is only available", "= util_schema.get_schema_for_resource_parameters(parameters_schema=config_schema, allow_additional_properties=True) instance = config_object try: cleaned = util_schema.validate(instance=instance,", "against the provided config schema dictionary. \"\"\" # NOTE: Lazy", "'get_pack_common_libs_path_for_pack_db', 'validate_config_against_schema', 'normalize_pack_version' ] # Common format for python 2.7", "pack \"ref\" attribute from the pack metadata file. If this", "provided config dictionary against the provided config schema dictionary. \"\"\"", "name \"%s\" contains invalid characters and \"ref\" attribute is not", "attribute \"%s\" in config for pack \"%s\" (%s): %s' %", "lib structure also needs to follow a python convention with", "to packs # which are in sub-directories) # 2. If", "may obtain a copy of the License at # #", "raise ValueError('Pack \"%s\" is missing %s file' % (pack_dir, MANIFEST_FILE_NAME))", "import PACK_REF_WHITELIST_REGEX from st2common.content.loader import MetaLoader from st2common.persistence.pack import Pack", "# Copyright 2019 Extreme Networks, Inc. # # Licensed under", "a particular pack directory. :rtype: ``dict`` \"\"\" manifest_path = os.path.join(pack_dir,", "and # limitations under the License. from __future__ import absolute_import", "dictionary. \"\"\" # NOTE: Lazy improt to avoid performance overhead", "\" \\ \"Please update your packs to work with Python", "available, we used that # 2. If pack_directory_name is available", "structure also needs to follow a python convention with a", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "Inc. # # Licensed under the Apache License, Version 2.0", "Python 3.x\" else: PACK_PYTHON2_WARNING = \"DEPRECATION WARNING: Pack %s only", "Pack %s only supports Python 2.x. \" \\ \"Python 2", "not provided, an attempt is made to infer \"ref\" from", "\"ref\" from the \"name\" attribute. :rtype: ``str`` \"\"\" pack_ref =", "raise jsonschema.ValidationError(msg) return cleaned def get_pack_common_libs_path_for_pack_ref(pack_ref): pack_db = Pack.get_by_ref(pack_ref) pack_common_libs_path", "= Pack.get_by_ref(pack_ref) pack_common_libs_path = get_pack_common_libs_path_for_pack_db(pack_db=pack_db) return pack_common_libs_path def get_pack_common_libs_path_for_pack_db(pack_db): \"\"\"", "if version_seperator_count == 1: version = version + '.0' return", "may not use this file except in compliance with the", "\"\"\" Validate provided config dictionary against the provided config schema", "2.7 warning if six.PY2: PACK_PYTHON2_WARNING = \"DEPRECATION WARNING: Pack %s", "2019 Extreme Networks, Inc. # # Licensed under the Apache", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "raise ValueError(msg % (metadata['name'])) return pack_ref def get_pack_metadata(pack_dir): \"\"\" Return", "2. If attribute is not available, but pack name is", "support has been removed since st2 v3.4.0. \" \\ \"Please", "for ' 'such values. Please check the specified values in", "for sensors and actions are placed. For example, if the", "this file except in compliance with the License. # You", "content def get_pack_warnings(pack_metadata): \"\"\" Return warning string if pack metadata", "= pack_metadata.get('name', None) if versions and set(versions) == set(['2']): warning", "versions and set(versions) == set(['2']): warning = PACK_PYTHON2_WARNING % pack_name", "None): pack_ref = metadata['ref'] elif pack_directory_name and re.match(PACK_REF_WHITELIST_REGEX, pack_directory_name): pack_ref", "performance overhead of importing this module when it's not used", "version.count('.') if version_seperator_count == 1: version = version + '.0'", "= metadata['name'] else: msg = ('Pack name \"%s\" contains invalid", "PACK_REF_WHITELIST_REGEX from st2common.content.loader import MetaLoader from st2common.persistence.pack import Pack from", "pack_ref = metadata['ref'] elif pack_directory_name and re.match(PACK_REF_WHITELIST_REGEX, pack_directory_name): pack_ref =", "import re import collections import six from st2common.util import schema", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "# # Licensed under the Apache License, Version 2.0 (the", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "try: cleaned = util_schema.validate(instance=instance, schema=schema, cls=util_schema.CustomValidator, use_default=True, allow_default_none=True) for key", "check the specified values in ' 'the config or the", "attribute to contain only' 'word characters.') raise ValueError(msg % (metadata['name']))", "pack directory. :rtype: ``dict`` \"\"\" manifest_path = os.path.join(pack_dir, MANIFEST_FILE_NAME) if", "rules for the pack ref are as follows: # 1.", "get_pack_common_libs_path_for_pack_ref(pack_ref): pack_db = Pack.get_by_ref(pack_ref) pack_common_libs_path = get_pack_common_libs_path_for_pack_db(pack_db=pack_db) return pack_common_libs_path def", "metadata for a particular pack directory. :rtype: ``dict`` \"\"\" manifest_path", "import ValueValidationException from st2common.util import jinja as jinja_utils __all__ =", "st2common.constants.pack import MANIFEST_FILE_NAME from st2common.constants.pack import PACK_REF_WHITELIST_REGEX from st2common.content.loader import", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "attribute which contains only word ' 'characters to the pack", "\"ref\" attribute from the pack metadata file. If this attribute", "list, collections.Iterable)): attribute = [str(item) for item in attribute] attribute", "used import jsonschema pack_name = pack_name or 'unknown' schema =", "\" \\ \"Python 2 support has been removed since st2", "os import re import collections import six from st2common.util import", "= ('Pack name \"%s\" contains invalid characters and \"ref\" attribute", "'validate_config_against_schema', 'normalize_pack_version' ] # Common format for python 2.7 warning", "If ref attribute is available, we used that # 2.", "'of \"decrypt_kv\" jinja filter is not allowed for ' 'such", "= get_pack_common_libs_path_for_pack_db(pack_db=pack_db) return pack_common_libs_path def get_pack_common_libs_path_for_pack_db(pack_db): \"\"\" Return the pack's", "only python 2 is supported :rtype: ``str`` \"\"\" warning =", "(tuple, list, collections.Iterable)): attribute = [str(item) for item in attribute]", "% (attribute, pack_name, config_path, six.text_type(e))) raise jsonschema.ValidationError(msg) return cleaned def", "NOTE: Lazy improt to avoid performance overhead of importing this", "attribute is not provided, an attempt is made to infer", "if not pack_dir: return None libs_path = os.path.join(pack_dir, 'lib') return", "as util_schema from st2common.constants.pack import MANIFEST_FILE_NAME from st2common.constants.pack import PACK_REF_WHITELIST_REGEX", "import six from st2common.util import schema as util_schema from st2common.constants.pack", "to follow a python convention with a __init__.py file. :param", "version_seperator_count = version.count('.') if version_seperator_count == 1: version = version", "semver version string (e.g. 0.2) to a valid semver version", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "function which retrieves pack \"ref\" attribute from the pack metadata", "\\ \"Please update your packs to work with Python 3.x\"", "metadata['name']): pack_ref = metadata['name'] else: msg = ('Pack name \"%s\"", "for a particular pack directory. :rtype: ``dict`` \"\"\" manifest_path =", "importing this module when it's not used import jsonschema pack_name", "use that (this only applies to packs # which are", "return libs_path def normalize_pack_version(version): \"\"\" Normalize old, pre StackStorm v2.1", "None) if not pack_dir: return None libs_path = os.path.join(pack_dir, 'lib')", "``dict`` \"\"\" manifest_path = os.path.join(pack_dir, MANIFEST_FILE_NAME) if not os.path.isfile(manifest_path): raise", "3.x\" def get_pack_ref_from_metadata(metadata, pack_directory_name=None): \"\"\" Utility function which retrieves pack", "or implied. # See the License for the specific language", "governing permissions and # limitations under the License. from __future__", "Python 2.x. \" \\ \"Python 2 support has been removed", "available we use that (this only applies to packs #", "Normalize old, pre StackStorm v2.1 non valid semver version string", "# 2. If attribute is not available, but pack name", "sub-directories) # 2. If attribute is not available, but pack", "\"ref\" attribute is not ' 'available. You either need to", "and actions are placed. For example, if the pack is", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "string (e.g. 0.2) to a valid semver version string (0.2.0).", "use_default=True, allow_default_none=True) for key in cleaned: if (jinja_utils.is_jinja_expression(value=cleaned.get(key)) and \"decrypt_kv\"", "python 2 is supported :rtype: ``str`` \"\"\" warning = None", "which retrieves pack \"ref\" attribute from the pack metadata file.", "from st2common.constants.pack import PACK_REF_WHITELIST_REGEX from st2common.content.loader import MetaLoader from st2common.persistence.pack", "3.x\" else: PACK_PYTHON2_WARNING = \"DEPRECATION WARNING: Pack %s only supports", "import Pack from st2common.exceptions.apivalidation import ValueValidationException from st2common.util import jinja", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "\"\"\" Return the pack's common lib path. This is the", "in future releases. \" \\ \"Please consider updating your packs", "the License. from __future__ import absolute_import import os import re", "also needs to follow a python convention with a __init__.py", "pack_metadata.get('name', None) if versions and set(versions) == set(['2']): warning =", "cleaned.get(key) and config_schema.get(key).get('secret')): raise ValueValidationException('Values specified as \"secret: True\" in", "word ' 'characters to the pack metadata file or update", "\"name\" attribute. :rtype: ``str`` \"\"\" pack_ref = None # The", "the valid name # criteria, we use that if metadata.get('ref',", "code is only available for python sensors and actions. The", "msg = ('Failed validating attribute \"%s\" in config for pack", "``str`` \"\"\" pack_dir = getattr(pack_db, 'path', None) if not pack_dir:", "config_object try: cleaned = util_schema.validate(instance=instance, schema=schema, cls=util_schema.CustomValidator, use_default=True, allow_default_none=True) for", "elif pack_directory_name and re.match(PACK_REF_WHITELIST_REGEX, pack_directory_name): pack_ref = pack_directory_name else: if", "cleaned def get_pack_common_libs_path_for_pack_ref(pack_ref): pack_db = Pack.get_by_ref(pack_ref) pack_common_libs_path = get_pack_common_libs_path_for_pack_db(pack_db=pack_db) return", "for item in attribute] attribute = '.'.join(attribute) else: attribute =", "/opt/stackstorm/packs/my_pack/lib/. This common library code is only available for python", "limitations under the License. from __future__ import absolute_import import os", "(the \"License\"); # you may not use this file except", "file or update name attribute to contain only' 'word characters.')", "parsed metadata for a particular pack directory. :rtype: ``dict`` \"\"\"", "= \"DEPRECATION WARNING: Pack %s only supports Python 2.x. \"", "# you may not use this file except in compliance", "ValueValidationException from st2common.util import jinja as jinja_utils __all__ = [", "# criteria, we use that if metadata.get('ref', None): pack_ref =", "set(['2']): warning = PACK_PYTHON2_WARNING % pack_name return warning def validate_config_against_schema(config_schema,", "get_pack_common_libs_path_for_pack_db(pack_db): \"\"\" Return the pack's common lib path. This is", "specified values in ' 'the config or the default values", "MetaLoader from st2common.persistence.pack import Pack from st2common.exceptions.apivalidation import ValueValidationException from", "Extreme Networks, Inc. # # Licensed under the Apache License,", "ValueValidationException('Values specified as \"secret: True\" in config ' 'schema are", "your packs to work with Python 3.x\" else: PACK_PYTHON2_WARNING =", "place common library code for actions and sensors in /opt/stackstorm/packs/my_pack/lib/.", "permissions and # limitations under the License. from __future__ import", "meta_loader.load(manifest_path) if not content: raise ValueError('Pack \"%s\" metadata file is", "This is the path where common code for sensors and", "only word ' 'characters to the pack metadata file or", "\"%s\" contains invalid characters and \"ref\" attribute is not '", "pack metadata file or update name attribute to contain only'", "metadata file. If this attribute is not provided, an attempt", "= None versions = pack_metadata.get('python_versions', None) pack_name = pack_metadata.get('name', None)", "' 'available. You either need to add \"ref\" attribute which", "# # Unless required by applicable law or agreed to", "\"decrypt_kv\" in cleaned.get(key) and config_schema.get(key).get('secret')): raise ValueValidationException('Values specified as \"secret:", "only available for python sensors and actions. The lib structure", "pack_directory_name=None): \"\"\" Utility function which retrieves pack \"ref\" attribute from", "Lazy improt to avoid performance overhead of importing this module", "schema = util_schema.get_schema_for_resource_parameters(parameters_schema=config_schema, allow_additional_properties=True) instance = config_object try: cleaned =", "common code for sensors and actions are placed. For example,", "supports Python 2.x. \" \\ \"Python 2 support has been", "# Common format for python 2.7 warning if six.PY2: PACK_PYTHON2_WARNING", "(attribute, pack_name, config_path, six.text_type(e))) raise jsonschema.ValidationError(msg) return cleaned def get_pack_common_libs_path_for_pack_ref(pack_ref):", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "\"\"\" manifest_path = os.path.join(pack_dir, MANIFEST_FILE_NAME) if not os.path.isfile(manifest_path): raise ValueError('Pack", "avoid performance overhead of importing this module when it's not", "add \"ref\" attribute which contains only word ' 'characters to", "Version 2.0 (the \"License\"); # you may not use this", "this module when it's not used import jsonschema pack_name =", "format for python 2.7 warning if six.PY2: PACK_PYTHON2_WARNING = \"DEPRECATION", "os.path.join(pack_dir, MANIFEST_FILE_NAME) if not os.path.isfile(manifest_path): raise ValueError('Pack \"%s\" is missing", "get_pack_metadata(pack_dir): \"\"\" Return parsed metadata for a particular pack directory.", "in ' 'the config or the default values in the", "improt to avoid performance overhead of importing this module when", "if isinstance(attribute, (tuple, list, collections.Iterable)): attribute = [str(item) for item", "available, but pack name is and pack name meets the", "else: attribute = str(attribute) msg = ('Failed validating attribute \"%s\"", "implied. # See the License for the specific language governing", "under the Apache License, Version 2.0 (the \"License\"); # you", "not ' 'available. You either need to add \"ref\" attribute", "# NOTE: Lazy improt to avoid performance overhead of importing", "as e: attribute = getattr(e, 'path', []) if isinstance(attribute, (tuple,", "common library code is only available for python sensors and", "warning = PACK_PYTHON2_WARNING % pack_name return warning def validate_config_against_schema(config_schema, config_object,", "of importing this module when it's not used import jsonschema", "getattr(pack_db, 'path', None) if not pack_dir: return None libs_path =", "return pack_ref def get_pack_metadata(pack_dir): \"\"\" Return parsed metadata for a", "common library code for actions and sensors in /opt/stackstorm/packs/my_pack/lib/. This", "get_pack_ref_from_metadata(metadata, pack_directory_name=None): \"\"\" Utility function which retrieves pack \"ref\" attribute", "v3.4.0. \" \\ \"Please update your packs to work with", "path. This is the path where common code for sensors", "import collections import six from st2common.util import schema as util_schema", "by applicable law or agreed to in writing, software #", "pack_directory_name else: if re.match(PACK_REF_WHITELIST_REGEX, metadata['name']): pack_ref = metadata['name'] else: msg", "if versions and set(versions) == set(['2']): warning = PACK_PYTHON2_WARNING %", "def get_pack_warnings(pack_metadata): \"\"\" Return warning string if pack metadata indicates", "valid semver version string (0.2.0). :rtype: ``str`` \"\"\" version =", "None) if versions and set(versions) == set(['2']): warning = PACK_PYTHON2_WARNING", "pack_ref = None # The rules for the pack ref", "Python 3.x\" def get_pack_ref_from_metadata(metadata, pack_directory_name=None): \"\"\" Utility function which retrieves", "% (pack_dir)) return content def get_pack_warnings(pack_metadata): \"\"\" Return warning string", "= ('Failed validating attribute \"%s\" in config for pack \"%s\"", "pack name meets the valid name # criteria, we use", "st2common.util import schema as util_schema from st2common.constants.pack import MANIFEST_FILE_NAME from", "name is and pack name meets the valid name #", "License. from __future__ import absolute_import import os import re import", "warning = None versions = pack_metadata.get('python_versions', None) pack_name = pack_metadata.get('name',", "config or the default values in the schema.') except jsonschema.ValidationError", "= config_object try: cleaned = util_schema.validate(instance=instance, schema=schema, cls=util_schema.CustomValidator, use_default=True, allow_default_none=True)", "pack is at /opt/stackstorm/packs/my_pack, you can place common library code", "st2common.constants.pack import PACK_REF_WHITELIST_REGEX from st2common.content.loader import MetaLoader from st2common.persistence.pack import", "2. If pack_directory_name is available we use that (this only", "packs # which are in sub-directories) # 2. If attribute", "pack_ref = pack_directory_name else: if re.match(PACK_REF_WHITELIST_REGEX, metadata['name']): pack_ref = metadata['name']", ":rtype: ``str`` \"\"\" pack_ref = None # The rules for", "missing %s file' % (pack_dir, MANIFEST_FILE_NAME)) meta_loader = MetaLoader() content", "= PACK_PYTHON2_WARNING % pack_name return warning def validate_config_against_schema(config_schema, config_object, config_path,", "filter is not allowed for ' 'such values. Please check", "be dropped in future releases. \" \\ \"Please consider updating", "values in the schema.') except jsonschema.ValidationError as e: attribute =", "\"%s\" in config for pack \"%s\" (%s): %s' % (attribute,", "2 support will be dropped in future releases. \" \\", "pack_ref def get_pack_metadata(pack_dir): \"\"\" Return parsed metadata for a particular", "= [str(item) for item in attribute] attribute = '.'.join(attribute) else:", "not os.path.isfile(manifest_path): raise ValueError('Pack \"%s\" is missing %s file' %", "in the schema.') except jsonschema.ValidationError as e: attribute = getattr(e,", "import absolute_import import os import re import collections import six", "file. If this attribute is not provided, an attempt is", "packs to work with Python 3.x\" else: PACK_PYTHON2_WARNING = \"DEPRECATION", "\"\"\" Return parsed metadata for a particular pack directory. :rtype:", "jinja_utils __all__ = [ 'get_pack_ref_from_metadata', 'get_pack_metadata', 'get_pack_warnings', 'get_pack_common_libs_path_for_pack_ref', 'get_pack_common_libs_path_for_pack_db', 'validate_config_against_schema',", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "Unless required by applicable law or agreed to in writing,", "\\ \"Python 2 support has been removed since st2 v3.4.0.", "attribute = getattr(e, 'path', []) if isinstance(attribute, (tuple, list, collections.Iterable)):", "convention with a __init__.py file. :param pack_db: Pack DB model", "pack_dir: return None libs_path = os.path.join(pack_dir, 'lib') return libs_path def", "v2.1 non valid semver version string (e.g. 0.2) to a", ":rtype: ``str`` \"\"\" warning = None versions = pack_metadata.get('python_versions', None)", "\" \\ \"Python 2 support will be dropped in future", "follows: # 1. If ref attribute is available, we used", "either need to add \"ref\" attribute which contains only word", "version_seperator_count == 1: version = version + '.0' return version", "(metadata['name'])) return pack_ref def get_pack_metadata(pack_dir): \"\"\" Return parsed metadata for", "and re.match(PACK_REF_WHITELIST_REGEX, pack_directory_name): pack_ref = pack_directory_name else: if re.match(PACK_REF_WHITELIST_REGEX, metadata['name']):", ":rtype: ``str`` \"\"\" version = str(version) version_seperator_count = version.count('.') if", "to the pack metadata file or update name attribute to", "retrieves pack \"ref\" attribute from the pack metadata file. If", "when it's not used import jsonschema pack_name = pack_name or", "by default. Use ' 'of \"decrypt_kv\" jinja filter is not", "= str(attribute) msg = ('Failed validating attribute \"%s\" in config", "sensors and actions. The lib structure also needs to follow", "python sensors and actions. The lib structure also needs to", "for python 2.7 warning if six.PY2: PACK_PYTHON2_WARNING = \"DEPRECATION WARNING:", "# 1. If ref attribute is available, we used that", "the specific language governing permissions and # limitations under the", "get_pack_warnings(pack_metadata): \"\"\" Return warning string if pack metadata indicates only", "content: raise ValueError('Pack \"%s\" metadata file is empty' % (pack_dir))", "schema=schema, cls=util_schema.CustomValidator, use_default=True, allow_default_none=True) for key in cleaned: if (jinja_utils.is_jinja_expression(value=cleaned.get(key))", "not content: raise ValueError('Pack \"%s\" metadata file is empty' %", "' 'characters to the pack metadata file or update name", "are in sub-directories) # 2. If attribute is not available,", "valid name # criteria, we use that if metadata.get('ref', None):", "version string (e.g. 0.2) to a valid semver version string", "applicable law or agreed to in writing, software # distributed", "= getattr(pack_db, 'path', None) if not pack_dir: return None libs_path", "we use that if metadata.get('ref', None): pack_ref = metadata['ref'] elif", "that # 2. If pack_directory_name is available we use that", "metadata['ref'] elif pack_directory_name and re.match(PACK_REF_WHITELIST_REGEX, pack_directory_name): pack_ref = pack_directory_name else:", "st2common.exceptions.apivalidation import ValueValidationException from st2common.util import jinja as jinja_utils __all__", "MetaLoader() content = meta_loader.load(manifest_path) if not content: raise ValueError('Pack \"%s\"", "def get_pack_common_libs_path_for_pack_db(pack_db): \"\"\" Return the pack's common lib path. This", "st2 v3.4.0. \" \\ \"Please update your packs to work", "module when it's not used import jsonschema pack_name = pack_name", "pack_db = Pack.get_by_ref(pack_ref) pack_common_libs_path = get_pack_common_libs_path_for_pack_db(pack_db=pack_db) return pack_common_libs_path def get_pack_common_libs_path_for_pack_db(pack_db):", "lib path. This is the path where common code for", "name # criteria, we use that if metadata.get('ref', None): pack_ref", "attempt is made to infer \"ref\" from the \"name\" attribute.", "in writing, software # distributed under the License is distributed", "(pack_dir, MANIFEST_FILE_NAME)) meta_loader = MetaLoader() content = meta_loader.load(manifest_path) if not", "content = meta_loader.load(manifest_path) if not content: raise ValueError('Pack \"%s\" metadata", "' 'the config or the default values in the schema.')", "characters.') raise ValueError(msg % (metadata['name'])) return pack_ref def get_pack_metadata(pack_dir): \"\"\"", "pack_directory_name is available we use that (this only applies to", "\"%s\" (%s): %s' % (attribute, pack_name, config_path, six.text_type(e))) raise jsonschema.ValidationError(msg)", "ref attribute is available, we used that # 2. If", "needs to follow a python convention with a __init__.py file.", "a __init__.py file. :param pack_db: Pack DB model :type pack_db:", "key in cleaned: if (jinja_utils.is_jinja_expression(value=cleaned.get(key)) and \"decrypt_kv\" in cleaned.get(key) and", "from st2common.persistence.pack import Pack from st2common.exceptions.apivalidation import ValueValidationException from st2common.util", "your packs to work with Python 3.x\" def get_pack_ref_from_metadata(metadata, pack_directory_name=None):", "\\ \"Python 2 support will be dropped in future releases.", "the pack metadata file. If this attribute is not provided,", "import jsonschema pack_name = pack_name or 'unknown' schema = util_schema.get_schema_for_resource_parameters(parameters_schema=config_schema,", "For example, if the pack is at /opt/stackstorm/packs/my_pack, you can", "else: if re.match(PACK_REF_WHITELIST_REGEX, metadata['name']): pack_ref = metadata['name'] else: msg =", "= pack_metadata.get('python_versions', None) pack_name = pack_metadata.get('name', None) if versions and", "validate_config_against_schema(config_schema, config_object, config_path, pack_name=None): \"\"\" Validate provided config dictionary against", "== set(['2']): warning = PACK_PYTHON2_WARNING % pack_name return warning def", "PACK_PYTHON2_WARNING = \"DEPRECATION WARNING: Pack %s only supports Python 2.x.", "is made to infer \"ref\" from the \"name\" attribute. :rtype:", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "'such values. Please check the specified values in ' 'the", "= MetaLoader() content = meta_loader.load(manifest_path) if not content: raise ValueError('Pack", "2 is supported :rtype: ``str`` \"\"\" warning = None versions", "we use that (this only applies to packs # which", "License, Version 2.0 (the \"License\"); # you may not use", "follow a python convention with a __init__.py file. :param pack_db:", "\"\"\" # NOTE: Lazy improt to avoid performance overhead of", "'.'.join(attribute) else: attribute = str(attribute) msg = ('Failed validating attribute", "util_schema.get_schema_for_resource_parameters(parameters_schema=config_schema, allow_additional_properties=True) instance = config_object try: cleaned = util_schema.validate(instance=instance, schema=schema,", "# You may obtain a copy of the License at", "jsonschema.ValidationError(msg) return cleaned def get_pack_common_libs_path_for_pack_ref(pack_ref): pack_db = Pack.get_by_ref(pack_ref) pack_common_libs_path =", "the pack's common lib path. This is the path where", "config_object, config_path, pack_name=None): \"\"\" Validate provided config dictionary against the", "if not os.path.isfile(manifest_path): raise ValueError('Pack \"%s\" is missing %s file'", "has been removed since st2 v3.4.0. \" \\ \"Please update", "contains only word ' 'characters to the pack metadata file", "util_schema.validate(instance=instance, schema=schema, cls=util_schema.CustomValidator, use_default=True, allow_default_none=True) for key in cleaned: if", "return cleaned def get_pack_common_libs_path_for_pack_ref(pack_ref): pack_db = Pack.get_by_ref(pack_ref) pack_common_libs_path = get_pack_common_libs_path_for_pack_db(pack_db=pack_db)", "jinja filter is not allowed for ' 'such values. Please", "re.match(PACK_REF_WHITELIST_REGEX, pack_directory_name): pack_ref = pack_directory_name else: if re.match(PACK_REF_WHITELIST_REGEX, metadata['name']): pack_ref", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "allow_default_none=True) for key in cleaned: if (jinja_utils.is_jinja_expression(value=cleaned.get(key)) and \"decrypt_kv\" in", "and \"decrypt_kv\" in cleaned.get(key) and config_schema.get(key).get('secret')): raise ValueValidationException('Values specified as", "specified as \"secret: True\" in config ' 'schema are automatically", "file' % (pack_dir, MANIFEST_FILE_NAME)) meta_loader = MetaLoader() content = meta_loader.load(manifest_path)", "raise ValueError('Pack \"%s\" metadata file is empty' % (pack_dir)) return", "can place common library code for actions and sensors in", "def normalize_pack_version(version): \"\"\" Normalize old, pre StackStorm v2.1 non valid", "only applies to packs # which are in sub-directories) #", "jsonschema.ValidationError as e: attribute = getattr(e, 'path', []) if isinstance(attribute,", "0.2) to a valid semver version string (0.2.0). :rtype: ``str``", "None versions = pack_metadata.get('python_versions', None) pack_name = pack_metadata.get('name', None) if", "collections.Iterable)): attribute = [str(item) for item in attribute] attribute =", "from st2common.util import jinja as jinja_utils __all__ = [ 'get_pack_ref_from_metadata',", "contain only' 'word characters.') raise ValueError(msg % (metadata['name'])) return pack_ref", "the License for the specific language governing permissions and #", "Common format for python 2.7 warning if six.PY2: PACK_PYTHON2_WARNING =", "def get_pack_metadata(pack_dir): \"\"\" Return parsed metadata for a particular pack", "updating your packs to work with Python 3.x\" else: PACK_PYTHON2_WARNING", "Apache License, Version 2.0 (the \"License\"); # you may not", "Utility function which retrieves pack \"ref\" attribute from the pack", "library code is only available for python sensors and actions.", "either express or implied. # See the License for the", "and sensors in /opt/stackstorm/packs/my_pack/lib/. This common library code is only", "MANIFEST_FILE_NAME)) meta_loader = MetaLoader() content = meta_loader.load(manifest_path) if not content:", "%s' % (attribute, pack_name, config_path, six.text_type(e))) raise jsonschema.ValidationError(msg) return cleaned", "(jinja_utils.is_jinja_expression(value=cleaned.get(key)) and \"decrypt_kv\" in cleaned.get(key) and config_schema.get(key).get('secret')): raise ValueValidationException('Values specified", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "Pack from st2common.exceptions.apivalidation import ValueValidationException from st2common.util import jinja as", "update your packs to work with Python 3.x\" def get_pack_ref_from_metadata(metadata,", "config for pack \"%s\" (%s): %s' % (attribute, pack_name, config_path,", "for actions and sensors in /opt/stackstorm/packs/my_pack/lib/. This common library code", "decrypted by default. Use ' 'of \"decrypt_kv\" jinja filter is", "are placed. For example, if the pack is at /opt/stackstorm/packs/my_pack,", "'path', None) if not pack_dir: return None libs_path = os.path.join(pack_dir,", "('Failed validating attribute \"%s\" in config for pack \"%s\" (%s):", "Copyright 2019 Extreme Networks, Inc. # # Licensed under the", "getattr(e, 'path', []) if isinstance(attribute, (tuple, list, collections.Iterable)): attribute =", "attribute = str(attribute) msg = ('Failed validating attribute \"%s\" in", "normalize_pack_version(version): \"\"\" Normalize old, pre StackStorm v2.1 non valid semver", "cleaned = util_schema.validate(instance=instance, schema=schema, cls=util_schema.CustomValidator, use_default=True, allow_default_none=True) for key in", "'lib') return libs_path def normalize_pack_version(version): \"\"\" Normalize old, pre StackStorm", "'get_pack_metadata', 'get_pack_warnings', 'get_pack_common_libs_path_for_pack_ref', 'get_pack_common_libs_path_for_pack_db', 'validate_config_against_schema', 'normalize_pack_version' ] # Common format", "ref are as follows: # 1. If ref attribute is", "WARNING: Pack %s only supports Python 2.x. \" \\ \"Python", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "``str`` \"\"\" version = str(version) version_seperator_count = version.count('.') if version_seperator_count", "file is empty' % (pack_dir)) return content def get_pack_warnings(pack_metadata): \"\"\"", "not used import jsonschema pack_name = pack_name or 'unknown' schema", "MANIFEST_FILE_NAME from st2common.constants.pack import PACK_REF_WHITELIST_REGEX from st2common.content.loader import MetaLoader from", "If pack_directory_name is available we use that (this only applies", "\"\"\" Return warning string if pack metadata indicates only python", "\"\"\" Normalize old, pre StackStorm v2.1 non valid semver version", "if six.PY2: PACK_PYTHON2_WARNING = \"DEPRECATION WARNING: Pack %s only supports", "Validate provided config dictionary against the provided config schema dictionary.", "not available, but pack name is and pack name meets", "The lib structure also needs to follow a python convention", "under the License. from __future__ import absolute_import import os import", "metadata file or update name attribute to contain only' 'word", "(%s): %s' % (attribute, pack_name, config_path, six.text_type(e))) raise jsonschema.ValidationError(msg) return", "pack_dir = getattr(pack_db, 'path', None) if not pack_dir: return None", "and actions. The lib structure also needs to follow a", "import MetaLoader from st2common.persistence.pack import Pack from st2common.exceptions.apivalidation import ValueValidationException", "with Python 3.x\" else: PACK_PYTHON2_WARNING = \"DEPRECATION WARNING: Pack %s", "if pack metadata indicates only python 2 is supported :rtype:", "\"\"\" version = str(version) version_seperator_count = version.count('.') if version_seperator_count ==", "%s only supports Python 2.x. \" \\ \"Python 2 support", "are as follows: # 1. If ref attribute is available,", "\"License\"); # you may not use this file except in", "attribute from the pack metadata file. If this attribute is", "Authors. # Copyright 2019 Extreme Networks, Inc. # # Licensed", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "supports Python 2.x. \" \\ \"Python 2 support will be", "allowed for ' 'such values. Please check the specified values", "work with Python 3.x\" else: PACK_PYTHON2_WARNING = \"DEPRECATION WARNING: Pack", "version = str(version) version_seperator_count = version.count('.') if version_seperator_count == 1:", ":type pack_db: :class:`PackDB` :rtype: ``str`` \"\"\" pack_dir = getattr(pack_db, 'path',", "from the pack metadata file. If this attribute is not", "update name attribute to contain only' 'word characters.') raise ValueError(msg", "# distributed under the License is distributed on an \"AS", "meta_loader = MetaLoader() content = meta_loader.load(manifest_path) if not content: raise", "Pack DB model :type pack_db: :class:`PackDB` :rtype: ``str`` \"\"\" pack_dir", "# Unless required by applicable law or agreed to in", "attribute is available, we used that # 2. If pack_directory_name", "= meta_loader.load(manifest_path) if not content: raise ValueError('Pack \"%s\" metadata file", "packs to work with Python 3.x\" def get_pack_ref_from_metadata(metadata, pack_directory_name=None): \"\"\"", "config dictionary against the provided config schema dictionary. \"\"\" #", "metadata['name'] else: msg = ('Pack name \"%s\" contains invalid characters", "Networks, Inc. # # Licensed under the Apache License, Version", "\"\"\" Utility function which retrieves pack \"ref\" attribute from the", "from __future__ import absolute_import import os import re import collections", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "import jinja as jinja_utils __all__ = [ 'get_pack_ref_from_metadata', 'get_pack_metadata', 'get_pack_warnings',", "(pack_dir)) return content def get_pack_warnings(pack_metadata): \"\"\" Return warning string if", "'characters to the pack metadata file or update name attribute", ":param pack_db: Pack DB model :type pack_db: :class:`PackDB` :rtype: ``str``", "as follows: # 1. If ref attribute is available, we", "None # The rules for the pack ref are as", "string if pack metadata indicates only python 2 is supported", "config schema dictionary. \"\"\" # NOTE: Lazy improt to avoid", "attribute = [str(item) for item in attribute] attribute = '.'.join(attribute)", "You may obtain a copy of the License at #", "item in attribute] attribute = '.'.join(attribute) else: attribute = str(attribute)", "= metadata['ref'] elif pack_directory_name and re.match(PACK_REF_WHITELIST_REGEX, pack_directory_name): pack_ref = pack_directory_name", "but pack name is and pack name meets the valid", "indicates only python 2 is supported :rtype: ``str`` \"\"\" warning", "only' 'word characters.') raise ValueError(msg % (metadata['name'])) return pack_ref def", "is not allowed for ' 'such values. Please check the", "' 'such values. Please check the specified values in '", "non valid semver version string (e.g. 0.2) to a valid", "[ 'get_pack_ref_from_metadata', 'get_pack_metadata', 'get_pack_warnings', 'get_pack_common_libs_path_for_pack_ref', 'get_pack_common_libs_path_for_pack_db', 'validate_config_against_schema', 'normalize_pack_version' ] #", "particular pack directory. :rtype: ``dict`` \"\"\" manifest_path = os.path.join(pack_dir, MANIFEST_FILE_NAME)", "path where common code for sensors and actions are placed.", "the Apache License, Version 2.0 (the \"License\"); # you may", "import MANIFEST_FILE_NAME from st2common.constants.pack import PACK_REF_WHITELIST_REGEX from st2common.content.loader import MetaLoader", "return warning def validate_config_against_schema(config_schema, config_object, config_path, pack_name=None): \"\"\" Validate provided", "which are in sub-directories) # 2. If attribute is not", "values in ' 'the config or the default values in" ]
[ "charactercreator_character_inventory AS inventory WHERE character.character_id = inventory.character_id GROUP BY character.name", "COUNT(DISTINCT weapon.item_ptr_id) as weapon_count FROM charactercreator_character AS character LEFT JOIN", "inventory -- characters may have zero items ON character.character_id =", "as weapon_count FROM charactercreator_character AS character LEFT JOIN charactercreator_character_inventory inventory", "AS character, charactercreator_character_inventory AS inventory WHERE character.character_id = inventory.character_id GROUP", "each character have? (0.67) AVG_CHARACTER_WEAPONS = \"\"\" SELECT AVG(weapon_count) as", "total Characters are there? (302) TOTAL_CHARACTERS = \"\"\" SELECT COUNT(*)", "SELECT * # FROM charactercreator_character; # \"\"\" # How many", "armory_weapon.item_ptr_id FROM armory_weapon); \"\"\" # How many Items does each", "AS character LEFT JOIN charactercreator_character_inventory inventory -- characters may have", "SELECT COUNT(*) as number_of_characters FROM charactercreator_character; \"\"\" # How many", "rows) CHARACTER_WEAPONS = \"\"\" SELECT character.name as \"character_name\", COUNT(weapon.item_ptr_id) as", "FROM charactercreator_character AS character, charactercreator_character_inventory AS inventory, armory_weapon as weapon", "# (SELECT COUNT(*) FROM charactercreator_fighter) AS fighters; # \"\"\" CLASS", "# GET_CHARACTERS = \"\"\" # SELECT * # FROM charactercreator_character;", "GET_CHARACTERS = \"\"\" # SELECT * # FROM charactercreator_character; #", "SELECT armory_weapon.item_ptr_id FROM armory_weapon); \"\"\" # How many Items does", "weapons? (137) NON_WEAPONS = \"\"\" SELECT COUNT(items.name) FROM armory_item as", "FROM charactercreator_thief) AS thiefs, # (SELECT COUNT(*) FROM charactercreator_cleric) AS", "AVG_CHARACTER_WEAPONS = \"\"\" SELECT AVG(weapon_count) as avg_weapons_per_char FROM ( SELECT", "COUNT(item_ptr_id) FROM armory_weapon; \"\"\" # How many of the items", "many Weapons does each character have? (Return first 20 rows)", "IN( SELECT armory_weapon.item_ptr_id FROM armory_weapon); \"\"\" # How many Items", "total Items? (174) TOTAL_ITEMS = \"\"\" SELECT COUNT(item_id) as items", "weapon.item_ptr_id) as weapon_count FROM charactercreator_character AS character LEFT JOIN charactercreator_character_inventory", "( SELECT COUNT(inventory.id) AS \"#_of_items\" FROM charactercreator_character AS character, charactercreator_character_inventory", "as \"avg_#_of_items\" FROM ( SELECT COUNT(inventory.id) AS \"#_of_items\" FROM charactercreator_character", "items are not weapons? (137) NON_WEAPONS = \"\"\" SELECT COUNT(items.name)", "CLASS = \"SELECT COUNT(*) FROM charactercreator_\" # How many total", "SELECT # (SELECT COUNT(*) FROM charactercreator_necromancer) AS necros, # (SELECT", "20; \"\"\" # On average, how many Items does each", "many Items does each Character have? (3.02) AVG_CHARACTER_ITEMS = \"\"\"", "character.name ORDER BY character.name LIMIT 20; \"\"\" # How many", "20 rows) CHARACTER_WEAPONS = \"\"\" SELECT character.name as \"character_name\", COUNT(weapon.item_ptr_id)", "(SELECT COUNT(*) FROM charactercreator_cleric) AS clerics, # (SELECT COUNT(*) FROM", "(137) NON_WEAPONS = \"\"\" SELECT COUNT(items.name) FROM armory_item as items", "inventory.character_id LEFT JOIN armory_weapon weapon -- many items are not", "character have? (Return first 20 rows) CHARACTER_WEAPONS = \"\"\" SELECT", "as \"#_of_weapons\" FROM charactercreator_character AS character, charactercreator_character_inventory AS inventory, armory_weapon", "FROM armory_item as items WHERE items.item_id NOT IN( SELECT armory_weapon.item_ptr_id", "charactercreator_cleric) AS clerics, # (SELECT COUNT(*) FROM charactercreator_fighter) AS fighters;", "COUNT(weapon.item_ptr_id) as \"#_of_weapons\" FROM charactercreator_character AS character, charactercreator_character_inventory AS inventory,", "\"\"\" # SELECT # (SELECT COUNT(*) FROM charactercreator_necromancer) AS necros,", "AS inventory, armory_weapon as weapon WHERE character.character_id = inventory.character_id AND", "number_of_characters FROM charactercreator_character; \"\"\" # How many of each specific", "does each character have? (0.67) AVG_CHARACTER_WEAPONS = \"\"\" SELECT AVG(weapon_count)", "character.character_id, COUNT(DISTINCT weapon.item_ptr_id) as weapon_count FROM charactercreator_character AS character LEFT", "not weapons? (137) NON_WEAPONS = \"\"\" SELECT COUNT(items.name) FROM armory_item", "SELECT character.character_id, COUNT(DISTINCT weapon.item_ptr_id) as weapon_count FROM charactercreator_character AS character", "\"\"\" # How many of the Items are weapons? (37)", "are there? (302) TOTAL_CHARACTERS = \"\"\" SELECT COUNT(*) as number_of_characters", "COUNT(*) FROM charactercreator_mage) AS mages, # (SELECT COUNT(*) FROM charactercreator_thief)", "= \"SELECT COUNT(*) FROM charactercreator_\" # How many total Items?", "charactercreator_thief) AS thiefs, # (SELECT COUNT(*) FROM charactercreator_cleric) AS clerics,", "SELECT COUNT(inventory.id) AS \"#_of_items\" FROM charactercreator_character AS character, charactercreator_character_inventory AS", "charactercreator_character AS character, charactercreator_character_inventory AS inventory WHERE character.character_id = inventory.character_id", "as \"character_name\", COUNT(inventory.id) as \"#_of_items\" FROM charactercreator_character AS character, charactercreator_character_inventory", "inventory.character_id GROUP BY character.name ORDER BY character.name LIMIT 20; \"\"\"", "LEFT JOIN armory_weapon weapon -- many items are not weapons,", "COUNT(*) FROM charactercreator_fighter) AS fighters; # \"\"\" CLASS = \"SELECT", "\"\"\" CLASS = \"SELECT COUNT(*) FROM charactercreator_\" # How many", "rows) CHARACTER_ITEMS = \"\"\" SELECT character.name as \"character_name\", COUNT(inventory.id) as", "charactercreator_\" # How many total Items? (174) TOTAL_ITEMS = \"\"\"", "WHERE items.item_id NOT IN( SELECT armory_weapon.item_ptr_id FROM armory_weapon); \"\"\" #", "SELECT COUNT(items.name) FROM armory_item as items WHERE items.item_id NOT IN(", "\"\"\" SELECT AVG(weapon_count) as avg_weapons_per_char FROM ( SELECT character.character_id, COUNT(DISTINCT", "charactercreator_character AS character LEFT JOIN charactercreator_character_inventory inventory -- characters may", "of each specific subclass? # TOTAL_SUBCLASS = \"\"\" # SELECT", "FROM charactercreator_character; \"\"\" # How many of each specific subclass?", "charactercreator_character; # \"\"\" # How many total Characters are there?", "at the charactercreator_character table # GET_CHARACTERS = \"\"\" # SELECT", "inventory.item_id = weapon.item_ptr_id GROUP BY character.name ORDER BY character.name LIMIT", "\"\"\" # On average, how many Weapons does each character", "many Weapons does each character have? (0.67) AVG_CHARACTER_WEAPONS = \"\"\"", "\"SELECT COUNT(*) FROM charactercreator_\" # How many total Items? (174)", "character LEFT JOIN charactercreator_character_inventory inventory -- characters may have zero", "Weapons does each character have? (0.67) AVG_CHARACTER_WEAPONS = \"\"\" SELECT", "\"#_of_weapons\" FROM charactercreator_character AS character, charactercreator_character_inventory AS inventory, armory_weapon as", "the items are not weapons? (137) NON_WEAPONS = \"\"\" SELECT", "inventory WHERE character.character_id = inventory.character_id GROUP BY character.name ); \"\"\"", "= \"\"\" SELECT AVG(\"#_of_items\") as \"avg_#_of_items\" FROM ( SELECT COUNT(inventory.id)", "COUNT(*) FROM charactercreator_\" # How many total Items? (174) TOTAL_ITEMS", "(3.02) AVG_CHARACTER_ITEMS = \"\"\" SELECT AVG(\"#_of_items\") as \"avg_#_of_items\" FROM (", "\"\"\" # How many Weapons does each character have? (Return", "# How many Weapons does each character have? (Return first", "SELECT AVG(\"#_of_items\") as \"avg_#_of_items\" FROM ( SELECT COUNT(inventory.id) AS \"#_of_items\"", "mages, # (SELECT COUNT(*) FROM charactercreator_thief) AS thiefs, # (SELECT", "* # FROM charactercreator_character; # \"\"\" # How many total", "character have? (0.67) AVG_CHARACTER_WEAPONS = \"\"\" SELECT AVG(weapon_count) as avg_weapons_per_char", "of the items are not weapons? (137) NON_WEAPONS = \"\"\"", "FROM armory_weapon); \"\"\" # How many Items does each character", "= weapon.item_ptr_id GROUP BY character.name ORDER BY character.name LIMIT 20;", "\"\"\" # On average, how many Items does each Character", "FROM ( SELECT character.character_id, COUNT(DISTINCT weapon.item_ptr_id) as weapon_count FROM charactercreator_character", "have? (3.02) AVG_CHARACTER_ITEMS = \"\"\" SELECT AVG(\"#_of_items\") as \"avg_#_of_items\" FROM", "are not weapons? (137) NON_WEAPONS = \"\"\" SELECT COUNT(items.name) FROM", "character.name as \"character_name\", COUNT(inventory.id) as \"#_of_items\" FROM charactercreator_character AS character,", "character.name ORDER BY character.name LIMIT 20; \"\"\" # On average,", "does each character have? (Return first 20 rows) CHARACTER_ITEMS =", "character.name LIMIT 20; \"\"\" # How many Weapons does each", "\"\"\" # SELECT * # FROM charactercreator_character; # \"\"\" #", "How many of the items are not weapons? (137) NON_WEAPONS", "= inventory.character_id GROUP BY character.name ); \"\"\" # On average,", "# How many total Items? (174) TOTAL_ITEMS = \"\"\" SELECT", "(37) WEAPONS = \"\"\" SELECT COUNT(item_ptr_id) FROM armory_weapon; \"\"\" #", "FROM charactercreator_necromancer) AS necros, # (SELECT COUNT(*) FROM charactercreator_mage) AS", "does each Character have? (3.02) AVG_CHARACTER_ITEMS = \"\"\" SELECT AVG(\"#_of_items\")", "zero items ON character.character_id = inventory.character_id LEFT JOIN armory_weapon weapon", "AND inventory.item_id = weapon.item_ptr_id GROUP BY character.name ORDER BY character.name", "character, charactercreator_character_inventory AS inventory, armory_weapon as weapon WHERE character.character_id =", "many total Characters are there? (302) TOTAL_CHARACTERS = \"\"\" SELECT", "fighters; # \"\"\" CLASS = \"SELECT COUNT(*) FROM charactercreator_\" #", "AVG_CHARACTER_ITEMS = \"\"\" SELECT AVG(\"#_of_items\") as \"avg_#_of_items\" FROM ( SELECT", "character.character_id = inventory.character_id LEFT JOIN armory_weapon weapon -- many items", "BY character.name LIMIT 20; \"\"\" # How many Weapons does", "character.name ); \"\"\" # On average, how many Weapons does", "# SELECT * # FROM charactercreator_character; # \"\"\" # How", "may have zero items ON character.character_id = inventory.character_id LEFT JOIN", "BY character.name ); \"\"\" # On average, how many Weapons", "specific subclass? # TOTAL_SUBCLASS = \"\"\" # SELECT # (SELECT", "items FROM armory_item; \"\"\" # How many of the Items", "items.item_id NOT IN( SELECT armory_weapon.item_ptr_id FROM armory_weapon); \"\"\" # How", "Look at the charactercreator_character table # GET_CHARACTERS = \"\"\" #", "# On average, how many Weapons does each character have?", "20; \"\"\" # How many Weapons does each character have?", "(Return first 20 rows) CHARACTER_ITEMS = \"\"\" SELECT character.name as", "have? (0.67) AVG_CHARACTER_WEAPONS = \"\"\" SELECT AVG(weapon_count) as avg_weapons_per_char FROM", "AS \"#_of_items\" FROM charactercreator_character AS character, charactercreator_character_inventory AS inventory WHERE", "charactercreator_character; \"\"\" # How many of each specific subclass? #", "\"\"\" SELECT COUNT(items.name) FROM armory_item as items WHERE items.item_id NOT", "); \"\"\" # On average, how many Weapons does each", "many items are not weapons, so only retain weapons ON", "Items? (174) TOTAL_ITEMS = \"\"\" SELECT COUNT(item_id) as items FROM", "many total Items? (174) TOTAL_ITEMS = \"\"\" SELECT COUNT(item_id) as", "How many total Characters are there? (302) TOTAL_CHARACTERS = \"\"\"", "(0.67) AVG_CHARACTER_WEAPONS = \"\"\" SELECT AVG(weapon_count) as avg_weapons_per_char FROM (", "\"\"\" # How many of the items are not weapons?", "AS inventory WHERE character.character_id = inventory.character_id GROUP BY character.name ORDER", "How many total Items? (174) TOTAL_ITEMS = \"\"\" SELECT COUNT(item_id)", "(SELECT COUNT(*) FROM charactercreator_mage) AS mages, # (SELECT COUNT(*) FROM", "NOT IN( SELECT armory_weapon.item_ptr_id FROM armory_weapon); \"\"\" # How many", "as items WHERE items.item_id NOT IN( SELECT armory_weapon.item_ptr_id FROM armory_weapon);", "are weapons? (37) WEAPONS = \"\"\" SELECT COUNT(item_ptr_id) FROM armory_weapon;", "retain weapons ON inventory.item_id = weapon.item_ptr_id GROUP BY character.character_id )", "\"\"\" SELECT COUNT(item_ptr_id) FROM armory_weapon; \"\"\" # How many of", "SELECT character.name as \"character_name\", COUNT(inventory.id) as \"#_of_items\" FROM charactercreator_character AS", "\"\"\" SELECT COUNT(*) as number_of_characters FROM charactercreator_character; \"\"\" # How", "charactercreator_necromancer) AS necros, # (SELECT COUNT(*) FROM charactercreator_mage) AS mages,", "COUNT(inventory.id) as \"#_of_items\" FROM charactercreator_character AS character, charactercreator_character_inventory AS inventory", "ON character.character_id = inventory.character_id LEFT JOIN armory_weapon weapon -- many", "as \"#_of_items\" FROM charactercreator_character AS character, charactercreator_character_inventory AS inventory WHERE", "# SELECT # (SELECT COUNT(*) FROM charactercreator_necromancer) AS necros, #", "LIMIT 20; \"\"\" # How many Weapons does each character", "not weapons, so only retain weapons ON inventory.item_id = weapon.item_ptr_id", "inventory.character_id GROUP BY character.name ); \"\"\" # On average, how", "weapons ON inventory.item_id = weapon.item_ptr_id GROUP BY character.character_id ) subq;", "ORDER BY character.name LIMIT 20; \"\"\" # How many Weapons", "\"character_name\", COUNT(inventory.id) as \"#_of_items\" FROM charactercreator_character AS character, charactercreator_character_inventory AS", "How many of the Items are weapons? (37) WEAPONS =", "\"\"\" # How many of each specific subclass? # TOTAL_SUBCLASS", "# How many of the items are not weapons? (137)", "character.character_id = inventory.character_id GROUP BY character.name ); \"\"\" # On", "many Items does each character have? (Return first 20 rows)", "each character have? (Return first 20 rows) CHARACTER_ITEMS = \"\"\"", "ON inventory.item_id = weapon.item_ptr_id GROUP BY character.character_id ) subq; \"\"\"", "AS clerics, # (SELECT COUNT(*) FROM charactercreator_fighter) AS fighters; #", "\"\"\" SELECT COUNT(item_id) as items FROM armory_item; \"\"\" # How", "are not weapons, so only retain weapons ON inventory.item_id =", "# \"\"\" # How many total Characters are there? (302)", "only retain weapons ON inventory.item_id = weapon.item_ptr_id GROUP BY character.character_id", "# Look at the charactercreator_character table # GET_CHARACTERS = \"\"\"", "Items does each Character have? (3.02) AVG_CHARACTER_ITEMS = \"\"\" SELECT", "as weapon WHERE character.character_id = inventory.character_id AND inventory.item_id = weapon.item_ptr_id", "\"\"\" # How many Items does each character have? (Return", "# (SELECT COUNT(*) FROM charactercreator_mage) AS mages, # (SELECT COUNT(*)", "Weapons does each character have? (Return first 20 rows) CHARACTER_WEAPONS", "the Items are weapons? (37) WEAPONS = \"\"\" SELECT COUNT(item_ptr_id)", "many of each specific subclass? # TOTAL_SUBCLASS = \"\"\" #", "# How many Items does each character have? (Return first", "weapons? (37) WEAPONS = \"\"\" SELECT COUNT(item_ptr_id) FROM armory_weapon; \"\"\"", "COUNT(item_id) as items FROM armory_item; \"\"\" # How many of", "SELECT AVG(weapon_count) as avg_weapons_per_char FROM ( SELECT character.character_id, COUNT(DISTINCT weapon.item_ptr_id)", "charactercreator_character_inventory AS inventory, armory_weapon as weapon WHERE character.character_id = inventory.character_id", "weapon.item_ptr_id GROUP BY character.name ORDER BY character.name LIMIT 20; \"\"\"", "armory_item as items WHERE items.item_id NOT IN( SELECT armory_weapon.item_ptr_id FROM", "-- characters may have zero items ON character.character_id = inventory.character_id", "the charactercreator_character table # GET_CHARACTERS = \"\"\" # SELECT *", "as \"character_name\", COUNT(weapon.item_ptr_id) as \"#_of_weapons\" FROM charactercreator_character AS character, charactercreator_character_inventory", "necros, # (SELECT COUNT(*) FROM charactercreator_mage) AS mages, # (SELECT", "items are not weapons, so only retain weapons ON inventory.item_id", "= inventory.character_id AND inventory.item_id = weapon.item_ptr_id GROUP BY character.name ORDER", "weapon_count FROM charactercreator_character AS character LEFT JOIN charactercreator_character_inventory inventory --", "there? (302) TOTAL_CHARACTERS = \"\"\" SELECT COUNT(*) as number_of_characters FROM", "(SELECT COUNT(*) FROM charactercreator_necromancer) AS necros, # (SELECT COUNT(*) FROM", "(302) TOTAL_CHARACTERS = \"\"\" SELECT COUNT(*) as number_of_characters FROM charactercreator_character;", "WHERE character.character_id = inventory.character_id GROUP BY character.name ); \"\"\" #", "character.name LIMIT 20; \"\"\" # On average, how many Items", "armory_weapon as weapon WHERE character.character_id = inventory.character_id AND inventory.item_id =", "each specific subclass? # TOTAL_SUBCLASS = \"\"\" # SELECT #", "character, charactercreator_character_inventory AS inventory WHERE character.character_id = inventory.character_id GROUP BY", "character.character_id = inventory.character_id GROUP BY character.name ORDER BY character.name LIMIT", "thiefs, # (SELECT COUNT(*) FROM charactercreator_cleric) AS clerics, # (SELECT", "SELECT COUNT(item_ptr_id) FROM armory_weapon; \"\"\" # How many of the", "# \"\"\" CLASS = \"SELECT COUNT(*) FROM charactercreator_\" # How", "LEFT JOIN charactercreator_character_inventory inventory -- characters may have zero items", "FROM ( SELECT COUNT(inventory.id) AS \"#_of_items\" FROM charactercreator_character AS character,", "charactercreator_character table # GET_CHARACTERS = \"\"\" # SELECT * #", "FROM armory_weapon; \"\"\" # How many of the items are", "= \"\"\" # SELECT # (SELECT COUNT(*) FROM charactercreator_necromancer) AS", "character.name as \"character_name\", COUNT(weapon.item_ptr_id) as \"#_of_weapons\" FROM charactercreator_character AS character,", "how many Weapons does each character have? (0.67) AVG_CHARACTER_WEAPONS =", "CHARACTER_WEAPONS = \"\"\" SELECT character.name as \"character_name\", COUNT(weapon.item_ptr_id) as \"#_of_weapons\"", "# (SELECT COUNT(*) FROM charactercreator_necromancer) AS necros, # (SELECT COUNT(*)", "= \"\"\" SELECT COUNT(*) as number_of_characters FROM charactercreator_character; \"\"\" #", "BY character.name ORDER BY character.name LIMIT 20; \"\"\" # How", "weapon WHERE character.character_id = inventory.character_id AND inventory.item_id = weapon.item_ptr_id GROUP", "How many Weapons does each character have? (Return first 20", "FROM charactercreator_character; # \"\"\" # How many total Characters are", "of the Items are weapons? (37) WEAPONS = \"\"\" SELECT", "COUNT(*) as number_of_characters FROM charactercreator_character; \"\"\" # How many of", "How many of each specific subclass? # TOTAL_SUBCLASS = \"\"\"", "SELECT COUNT(item_id) as items FROM armory_item; \"\"\" # How many", "JOIN charactercreator_character_inventory inventory -- characters may have zero items ON", "weapon -- many items are not weapons, so only retain", "= \"\"\" # SELECT * # FROM charactercreator_character; # \"\"\"", "= \"\"\" SELECT COUNT(item_id) as items FROM armory_item; \"\"\" #", "COUNT(inventory.id) AS \"#_of_items\" FROM charactercreator_character AS character, charactercreator_character_inventory AS inventory", "charactercreator_character_inventory inventory -- characters may have zero items ON character.character_id", "= \"\"\" SELECT COUNT(items.name) FROM armory_item as items WHERE items.item_id", "AS inventory WHERE character.character_id = inventory.character_id GROUP BY character.name );", "FROM armory_item; \"\"\" # How many of the Items are", "(SELECT COUNT(*) FROM charactercreator_fighter) AS fighters; # \"\"\" CLASS =", "(SELECT COUNT(*) FROM charactercreator_thief) AS thiefs, # (SELECT COUNT(*) FROM", "each character have? (Return first 20 rows) CHARACTER_WEAPONS = \"\"\"", "CHARACTER_ITEMS = \"\"\" SELECT character.name as \"character_name\", COUNT(inventory.id) as \"#_of_items\"", "How many Items does each character have? (Return first 20", "FROM charactercreator_cleric) AS clerics, # (SELECT COUNT(*) FROM charactercreator_fighter) AS", "AS necros, # (SELECT COUNT(*) FROM charactercreator_mage) AS mages, #", "COUNT(*) FROM charactercreator_cleric) AS clerics, # (SELECT COUNT(*) FROM charactercreator_fighter)", "have? (Return first 20 rows) CHARACTER_WEAPONS = \"\"\" SELECT character.name", "WHERE character.character_id = inventory.character_id GROUP BY character.name ORDER BY character.name", "how many Items does each Character have? (3.02) AVG_CHARACTER_ITEMS =", "COUNT(items.name) FROM armory_item as items WHERE items.item_id NOT IN( SELECT", "charactercreator_fighter) AS fighters; # \"\"\" CLASS = \"SELECT COUNT(*) FROM", "armory_weapon); \"\"\" # How many Items does each character have?", "# How many of the Items are weapons? (37) WEAPONS", "BY character.name LIMIT 20; \"\"\" # On average, how many", "FROM charactercreator_\" # How many total Items? (174) TOTAL_ITEMS =", "Characters are there? (302) TOTAL_CHARACTERS = \"\"\" SELECT COUNT(*) as", "does each character have? (Return first 20 rows) CHARACTER_WEAPONS =", "\"character_name\", COUNT(weapon.item_ptr_id) as \"#_of_weapons\" FROM charactercreator_character AS character, charactercreator_character_inventory AS", "AS fighters; # \"\"\" CLASS = \"SELECT COUNT(*) FROM charactercreator_\"", "weapons, so only retain weapons ON inventory.item_id = weapon.item_ptr_id GROUP", "TOTAL_ITEMS = \"\"\" SELECT COUNT(item_id) as items FROM armory_item; \"\"\"", "Items does each character have? (Return first 20 rows) CHARACTER_ITEMS", "WHERE character.character_id = inventory.character_id AND inventory.item_id = weapon.item_ptr_id GROUP BY", "\"#_of_items\" FROM charactercreator_character AS character, charactercreator_character_inventory AS inventory WHERE character.character_id", "NON_WEAPONS = \"\"\" SELECT COUNT(items.name) FROM armory_item as items WHERE", "COUNT(*) FROM charactercreator_thief) AS thiefs, # (SELECT COUNT(*) FROM charactercreator_cleric)", "GROUP BY character.name ORDER BY character.name LIMIT 20; \"\"\" #", "as avg_weapons_per_char FROM ( SELECT character.character_id, COUNT(DISTINCT weapon.item_ptr_id) as weapon_count", "# TOTAL_SUBCLASS = \"\"\" # SELECT # (SELECT COUNT(*) FROM", "\"\"\" SELECT character.name as \"character_name\", COUNT(weapon.item_ptr_id) as \"#_of_weapons\" FROM charactercreator_character", "# (SELECT COUNT(*) FROM charactercreator_thief) AS thiefs, # (SELECT COUNT(*)", "On average, how many Weapons does each character have? (0.67)", "(Return first 20 rows) CHARACTER_WEAPONS = \"\"\" SELECT character.name as", "so only retain weapons ON inventory.item_id = weapon.item_ptr_id GROUP BY", "inventory, armory_weapon as weapon WHERE character.character_id = inventory.character_id AND inventory.item_id", "clerics, # (SELECT COUNT(*) FROM charactercreator_fighter) AS fighters; # \"\"\"", "as number_of_characters FROM charactercreator_character; \"\"\" # How many of each", "table # GET_CHARACTERS = \"\"\" # SELECT * # FROM", "BY character.name ORDER BY character.name LIMIT 20; \"\"\" # On", "= \"\"\" SELECT COUNT(item_ptr_id) FROM armory_weapon; \"\"\" # How many", "items WHERE items.item_id NOT IN( SELECT armory_weapon.item_ptr_id FROM armory_weapon); \"\"\"", "SELECT character.name as \"character_name\", COUNT(weapon.item_ptr_id) as \"#_of_weapons\" FROM charactercreator_character AS", "Items are weapons? (37) WEAPONS = \"\"\" SELECT COUNT(item_ptr_id) FROM", "AVG(weapon_count) as avg_weapons_per_char FROM ( SELECT character.character_id, COUNT(DISTINCT weapon.item_ptr_id) as", "20 rows) CHARACTER_ITEMS = \"\"\" SELECT character.name as \"character_name\", COUNT(inventory.id)", "WEAPONS = \"\"\" SELECT COUNT(item_ptr_id) FROM armory_weapon; \"\"\" # How", "subclass? # TOTAL_SUBCLASS = \"\"\" # SELECT # (SELECT COUNT(*)", "first 20 rows) CHARACTER_ITEMS = \"\"\" SELECT character.name as \"character_name\",", "AS thiefs, # (SELECT COUNT(*) FROM charactercreator_cleric) AS clerics, #", "# How many of each specific subclass? # TOTAL_SUBCLASS =", "charactercreator_character AS character, charactercreator_character_inventory AS inventory, armory_weapon as weapon WHERE", "many of the items are not weapons? (137) NON_WEAPONS =", "avg_weapons_per_char FROM ( SELECT character.character_id, COUNT(DISTINCT weapon.item_ptr_id) as weapon_count FROM", "ORDER BY character.name LIMIT 20; \"\"\" # On average, how", "have zero items ON character.character_id = inventory.character_id LEFT JOIN armory_weapon", "On average, how many Items does each Character have? (3.02)", "(174) TOTAL_ITEMS = \"\"\" SELECT COUNT(item_id) as items FROM armory_item;", "character have? (Return first 20 rows) CHARACTER_ITEMS = \"\"\" SELECT", "= \"\"\" SELECT character.name as \"character_name\", COUNT(weapon.item_ptr_id) as \"#_of_weapons\" FROM", "many of the Items are weapons? (37) WEAPONS = \"\"\"", "( SELECT character.character_id, COUNT(DISTINCT weapon.item_ptr_id) as weapon_count FROM charactercreator_character AS", "armory_weapon weapon -- many items are not weapons, so only", "FROM charactercreator_character AS character LEFT JOIN charactercreator_character_inventory inventory -- characters", "# (SELECT COUNT(*) FROM charactercreator_cleric) AS clerics, # (SELECT COUNT(*)", "LIMIT 20; \"\"\" # On average, how many Items does", "inventory.character_id AND inventory.item_id = weapon.item_ptr_id GROUP BY character.name ORDER BY", "= \"\"\" SELECT character.name as \"character_name\", COUNT(inventory.id) as \"#_of_items\" FROM", "JOIN armory_weapon weapon -- many items are not weapons, so", "as items FROM armory_item; \"\"\" # How many of the", "average, how many Weapons does each character have? (0.67) AVG_CHARACTER_WEAPONS", "inventory WHERE character.character_id = inventory.character_id GROUP BY character.name ORDER BY", "each Character have? (3.02) AVG_CHARACTER_ITEMS = \"\"\" SELECT AVG(\"#_of_items\") as", "GROUP BY character.name ); \"\"\" # On average, how many", "# How many total Characters are there? (302) TOTAL_CHARACTERS =", "COUNT(*) FROM charactercreator_necromancer) AS necros, # (SELECT COUNT(*) FROM charactercreator_mage)", "# On average, how many Items does each Character have?", "-- many items are not weapons, so only retain weapons", "= inventory.character_id LEFT JOIN armory_weapon weapon -- many items are", "FROM charactercreator_fighter) AS fighters; # \"\"\" CLASS = \"SELECT COUNT(*)", "TOTAL_SUBCLASS = \"\"\" # SELECT # (SELECT COUNT(*) FROM charactercreator_necromancer)", "AS character, charactercreator_character_inventory AS inventory, armory_weapon as weapon WHERE character.character_id", "\"\"\" SELECT AVG(\"#_of_items\") as \"avg_#_of_items\" FROM ( SELECT COUNT(inventory.id) AS", "have? (Return first 20 rows) CHARACTER_ITEMS = \"\"\" SELECT character.name", "characters may have zero items ON character.character_id = inventory.character_id LEFT", "first 20 rows) CHARACTER_WEAPONS = \"\"\" SELECT character.name as \"character_name\",", "AVG(\"#_of_items\") as \"avg_#_of_items\" FROM ( SELECT COUNT(inventory.id) AS \"#_of_items\" FROM", "\"\"\" SELECT character.name as \"character_name\", COUNT(inventory.id) as \"#_of_items\" FROM charactercreator_character", "armory_item; \"\"\" # How many of the Items are weapons?", "# FROM charactercreator_character; # \"\"\" # How many total Characters", "items ON character.character_id = inventory.character_id LEFT JOIN armory_weapon weapon --", "average, how many Items does each Character have? (3.02) AVG_CHARACTER_ITEMS", "FROM charactercreator_character AS character, charactercreator_character_inventory AS inventory WHERE character.character_id =", "charactercreator_mage) AS mages, # (SELECT COUNT(*) FROM charactercreator_thief) AS thiefs,", "AS mages, # (SELECT COUNT(*) FROM charactercreator_thief) AS thiefs, #", "= inventory.character_id GROUP BY character.name ORDER BY character.name LIMIT 20;", "\"avg_#_of_items\" FROM ( SELECT COUNT(inventory.id) AS \"#_of_items\" FROM charactercreator_character AS", "character.character_id = inventory.character_id AND inventory.item_id = weapon.item_ptr_id GROUP BY character.name", "= \"\"\" SELECT AVG(weapon_count) as avg_weapons_per_char FROM ( SELECT character.character_id,", "\"\"\" # How many total Characters are there? (302) TOTAL_CHARACTERS", "Character have? (3.02) AVG_CHARACTER_ITEMS = \"\"\" SELECT AVG(\"#_of_items\") as \"avg_#_of_items\"", "FROM charactercreator_mage) AS mages, # (SELECT COUNT(*) FROM charactercreator_thief) AS", "armory_weapon; \"\"\" # How many of the items are not", "TOTAL_CHARACTERS = \"\"\" SELECT COUNT(*) as number_of_characters FROM charactercreator_character; \"\"\"" ]
[ "self.npixels: raise AssertionError(\"`shape` must be unique or have the same", "\"\"\" \"\"\" return len(np.shape(self.shape))==2 @property def geodataframe(self): \"\"\" \"\"\" if", "'geometry', 'id', 'x', 'y') asgrid: [bool] -optional- Should this return", "axis=0) if shift_origin is not None: # not += because", "Creates a new Grid objects from the given input data:", "from propobject import BaseObject from shapely import geometry import pandas", "import geopandas return geopandas.GeoSeries([geometry.Polygon(v) for v in self.vertices]) def get_triangulation_grid(self):", "if type(vertices) is dict: indexes, vertices = list(vertices.keys()), list(vertices.values()) this.set_vertices(vertices)", "```python def get_2dgauss(x, mu=[4,4], cov=[[1,0],[0,2]]): \"\"\" \"\"\" return stats.multivariate_normal.pdf(np.stack(x, axis=-1),", "= np.unique(shape, axis=0) if len(shape_unique)==1: shape = shape_unique[0] self.set_pixels(pixels, shape,", "is not None): self._derived_properties[\"vertices\"] = self.pixels[:,None]+self.shape return self._derived_properties[\"vertices\"] @property def", "shapely import vectorized flagin = vectorized.contains(polygon, *self.pixels.T) if invert: flagin", "self.gridinterest[\"id_1\"]].index ] * self.gridinterest[\"area\"] return getattr(self.gridinterest.groupby(\"id_2\")[\"_tmp\"],use)() def _parse_data_(self,data): \"\"\" Parameters", "This should have the length equal to th number of", "a list of vertices, you can provide the indexes of", "self.set_vertices(vertices, update=False) # don't update the geodataframe # --------- #", "\"\"\" Evaluate the given function throughout the grid. This evulation", "othergrid, column=\"*\", asgrid=True, use=\"sum\"): \"\"\" project data in the given", "be projected in gridout. could be: - ndarray: must have", "column=\"*\", asgrid=True, use=\"sum\"): \"\"\" project data in the given grid", "of the given input\") # --------- # # SETTER #", "\"\"\" import geopandas return geopandas.GeoSeries([geometry.Polygon(v) for v in self.vertices]) def", "raise ValueError(\"pixels must be [N,2] arrays\") self._properties[\"pixels\"] = np.asarray(pixels) if", "# # Functions # # # # ======================= # def", "[ndarray or string or pandas.Serie] data associated to gridin that", "TypeError(\"cannot parse the format of the given input\") # ---------", "\"data\") return this @classmethod def from_vertices(cls, vertices, indexes=None): \"\"\" directly", "self.gridinterest[\"_tmp\"] = data[ self.gridin.geodataframe.loc[ self.gridinterest[\"id_1\"]].index ] * self.gridinterest[\"area\"] return getattr(self.gridinterest.groupby(\"id_2\")[\"_tmp\"],use)()", "= self._project_data_(self._parse_data_(data), use=use) if as_serie: return projected_data projected_data_array = np.zeros(", "vertices of all the grid entries. Could have two format:", "# # UPDATE # # --------- # def _update_geodataframe_(self): \"\"\"", "indexes = np.arange(len(vertices)) Returns ------- Grid \"\"\" this = cls()", "func, vectorized=True): \"\"\" Evaluate the given function throughout the grid.", "Calcul itself projected_data = self._project_data_(self._parse_data_(data), use=use) if as_serie: return projected_data", "# ======================= # def get_simple_grid(xbounds, ybounds, shift_origin=None): \"\"\" \"\"\" xbounds", "will be set by the vertices. indexes: [list or None]", "array: [[vert_1],[vert_2],....], then you may want to provide indexes -", "associated to each pixels Parameters ---------- indexes: [ndarray] indexes associated", "provide the indexes associated to each pixels Parameters ---------- indexes:", "the new grid gout = othergrid.__class__.set_from(othergrid.geodataframe) for k in column:", "if type(data) == str: if data not in self.gridin.geodataframe.columns: raise", "If you provide vertices as a list of vertices, you", "update=False) # don't update the geodataframe # --------- # #", "@property def shape(self): \"\"\" \"\"\" if self._properties[\"shape\"] is None: self._properties[\"shape\"]", "the pixels if np.shape(pixels)[-1] != 2: raise ValueError(\"pixels must be", "lengthes do not match\") return data # =================== # #", "length equal to th number of pixels (if any). update:", "np.asarray(shape) else: raise ValueError(\"Cannot parse the given shape, must be", "have 'geometry' column. It is required\") self._derived_properties[\"geodataframe\"] = geodataframe if", "UNIT_SQUARE) # ======================= # # # # Classes # #", "g_wcs def evaluate(self, func, vectorized=True): \"\"\" Evaluate the given function", "= ybounds pixels = np.mgrid[xmin:xmax,ymin:ymax] pixels2_flat = np.concatenate(pixels.T, axis=0) if", "np.stack(x, axis=-1). # This is mandatory since integration is going", "input\") # --------- # # SETTER # # --------- #", "\"\"\" checks if the centroid of the pixel is in", "if self.pixels is not None and np.shape(shape)[0] != self.npixels: raise", "to wcs_.all_pix2world Returns ------- Grid or array (see asgrid) \"\"\"", "Should this return a load Grid object or an array", "\"\"\" PROPERTIES = [\"gridin\", \"gridout\"] DERIVED_PROPERTIES = [\"gridinterest\"] def __init__(self,", "# Functions # # # # ======================= # def get_simple_grid(xbounds,", "str: if data not in self.gridin.geodataframe.columns: raise ValueError(\"Unknown gridin column", "which not in [\"in\",\"out\"]: raise ValueError(\"Which should either be 'in'", "verts = self.vertices verts_shape = np.shape(verts) flatten_verts = np.concatenate(verts, axis=0)", "gridin and/or gridout is/are None\") # -------------- # # Measurement", "return self._side_properties[\"indexes\"] # -- Derived @property def vertices(self): \"\"\" \"\"\"", "k in self.geodataframe if k not in ['geometry', 'id', 'x',", "the given input data: Parameters ---------- datainput: [geopandas.geodataframe.GeoDataFrame or ndarray]", "the geodataframe be updated ? [use True if you are", "flatten_verts[:,1], 0, **kwargs)).T # verts_wcs = flatten_verts_wcs.reshape(verts_shape) if not asgrid:", "update=True): \"\"\" provide the indexes associated to each pixels Parameters", "def pixels(self): \"\"\" \"\"\" return self._properties[\"pixels\"] @property def npixels(self): \"\"\"", "# # # # ======================= # def get_simple_grid(xbounds, ybounds, shift_origin=None):", "indexes is None: indexes = self.indexes s_ = pandas.Series(data, name=name,", "= self.pixels.T self._derived_properties[\"geodataframe\"] = \\ geopandas.GeoDataFrame({'geometry': dataseries, 'id':self.indexes, 'x':x,'y':y}) def", "tr_flat = np.stack(np.concatenate(trs, axis=0), axis=-2) val = quadpy.triangle.strang_fix_cowper_09().integrate(func,tr_flat).reshape(shape_trs[:2]) else: val", "Parameters ---------- indexes: [ndarray] indexes associated to the pixels. This", "number of pixels (if any). update: [bool] -optional- should the", "None: self._update_geodataframe_() return self._derived_properties[\"geodataframe\"] @property def triangulation(self): \"\"\" Triangulation of", "shape, **kwargs) def set_geodataframe(self, geodataframe, overwrite=False): \"\"\" \"\"\" if not", "if type(datainput) == np.ndarray: if len(np.shape( datainput) ) == 3:", "to gridin that should be projected in gridout. could be:", "pixels = np.mgrid[xmin:xmax,ymin:ymax] pixels2_flat = np.concatenate(pixels.T, axis=0) if shift_origin is", "of vertices, you can provide the indexes of each of", "is not None: facecolor=None return self.geodataframe.plot(column, ax=ax,facecolor=facecolor, edgecolor=edgecolor, **kwargs) #", "= self.geodataframe.join(s_) # --------- # # GETTER # # ---------", "quadpy. Examples: # Remark the np.stack(x, axis=-1). # This is", "return self._properties[\"pixels\"] @property def npixels(self): \"\"\" \"\"\" return len(self.pixels) @property", "measure gridinterest, because gridin and/or gridout is/are None\") # --------------", "\"\"\" dataseries = self.get_geoseries() x,y = self.pixels.T self._derived_properties[\"geodataframe\"] = \\", "return projected_data projected_data_array = np.zeros( len(self.gridout.geodataframe) ) projected_data_array[projected_data.index.values] = projected_data.values", "t_ in trs]) return np.sum(val, axis=1) def derive_triangulation(self, fast_unique=True): \"\"\"", "\"\"\" \"\"\" return self._properties[\"gridin\"] @property def gridout(self): \"\"\" \"\"\" return", "Grid or array (see asgrid) \"\"\" verts = self.vertices verts_shape", "=================== # @classmethod def from_stamps(cls, stamp, origin=[0,0]): \"\"\" stamps are", "Properties # # =================== # @property def gridin(self): \"\"\" \"\"\"", "This is mandatory since integration is going to send #", "if len(ybounds)==1: ymin,ymax = 0,ybounds[0] else: ymin,ymax = ybounds pixels", "len(indexes) != self.npixels: raise AssertionError(\"not the same number of indexes", "np.shape(trs) if len(shape_trs)==4 and vectorized: # All Polygon have the", "# def get_geoseries(self): \"\"\" build a new geodataframe and returns", "--------- # # SETTER # # --------- # def set_grid(self,", "projected_data_array def _project_data_(self, data, use=\"sum\"): \"\"\" \"\"\" self.gridinterest[\"_tmp\"] = data[", "triangulate(geometry.Polygon(self.shape)) # --------- # # PLOTTER # # --------- #", "\"\"\" if column is not None: facecolor=None return self.geodataframe.plot(column, ax=ax,facecolor=facecolor,", "is made using quadpy. pip install quadpy\") # Is Triangulation", "polyname using triangle integration. -> dependency: the integration is made", "geodataframe be updated ? [use True if you are not", "set_geodataframe(self, geodataframe, overwrite=False): \"\"\" \"\"\" if not overwrite and (self.pixels", "# def project_to(self, othergrid, column=\"*\", asgrid=True, use=\"sum\"): \"\"\" project data", "set_pixels(self, pixels, shape=None, update=True): \"\"\" provide the pixels. Pixels define", "Polygon have the same topology (same amount of vertices) tr_flat", "======================= # # # # Classes # # # #", "\"\"\" if self._derived_properties[\"vertices\"] is None and (self.pixels is not None", "of triangulation. \"\"\" return Grid.set_from( np.concatenate(self.triangulation, axis=0) ) def get_pixels_in(self,", "grid's vertices coordinates are in pixels) Parameters ---------- wcs_: [astropy.wcs.WCS]", "vertices, overwrite=False, **kwargs): \"\"\" \"\"\" if not overwrite and (self.pixels", "matched with gridin \"\"\" # Calcul itself projected_data = self._project_data_(self._parse_data_(data),", "shapely import geometry import pandas import geopandas # ======================= #", "\"\"\" Return triangulate format that quadpy likes \"\"\" from shapely", "# # SETTER # # --------- # def set_indexes(self, indexes,", "return self._properties[\"gridin\"] @property def gridout(self): \"\"\" \"\"\" return self._properties[\"gridout\"] @property", "None: self.set_pixels(pixels,shape=shape) if indexes is not None: self.set_indexes(indexes) # ===================", "othergrid.__class__.set_from(othergrid.geodataframe) for k in column: gout.add_data(datas[k],k) return gout def project_to_wcs(self,", "None or '*' all the non-structural columns will be (structural", "vertices this.set_vertices(datainput) elif len(np.shape( datainput) ) == 3: # pixels", "mu=[4,4], cov=[[1,0],[0,2]]): \"\"\" \"\"\" return stats.multivariate_normal.pdf(np.stack(x, axis=-1), mean=mu, cov=cov) ```", "== 3: # pixels this.set_pixels(datainput) else: raise TypeError(\"cannot parse the", "- ndarray: must have the same length as gridin -", "stamp, origin=[0,0]): \"\"\" stamps are 2d array, something you could", "# ======================= # # # # Classes # # #", "--------- # def set_grid(self, grid, which=\"in\"): \"\"\" \"\"\" if which", "provide indexes - dictionary: {id_1:vert_1,id_2: vert_2, ...} if a dictionary", "# # --------- # def _update_geodataframe_(self): \"\"\" \"\"\" dataseries =", "is required\") self._derived_properties[\"geodataframe\"] = geodataframe if \"id\" not in geodataframe.columns:", "ValueError(\"Unknown gridin column '%s'\"%data) return self.gridin.geodataframe[data].values elif type(data) == pandas.Series:", "the length equal to th number of pixels (if any).", "building and setting the new grid gout = othergrid.__class__.set_from(othergrid.geodataframe) for", "------- Grid or array (see asgrid) \"\"\" verts = self.vertices", "self.npixels: raise AssertionError(\"not the same number of indexes as the", "UNIT_SQUARE = np.asarray([[0,0],[0,1],[1,1],[1,0]])-0.5 from propobject import BaseObject from shapely import", "not in ['geometry', 'id', 'x', 'y']] datas = {k:gproj.project_data(k, use=use)", "# Methods # # =================== # @classmethod def from_stamps(cls, stamp,", "\"\"\" build a new geodataframe and returns it. \"\"\" import", "the polygon [invert=False] or outsite [invert=True] Returns ------- list of", "np.stack([np.asarray(t.exterior.coords.xy).T[:-1] for t in triangles]) if not self.is_shape_unique or not", "'*' all the non-structural columns will be (structural columns are", "return Grid(pixels2_flat, UNIT_SQUARE) # ======================= # # # # Classes", "pixel and M the number of vertices\") if update: self._update_geodataframe_()", "to true, to update vertices\") try: pixels = np.mean(vertices, axis=1)", "update=False) if update: self._update_geodataframe_() def set_pixelshapes(self, shape, update=True): \"\"\" \"\"\"", "be [N,2] arrays\") self._properties[\"pixels\"] = np.asarray(pixels) if shape is not", "is None and (self.pixels is not None and self.shape is", "will be stored as 'data' in the grid's dataframe \"\"\"", "likes \"\"\" from shapely import ops triangles = ops.triangulate(geom) return", "this return a load Grid object or an array of", "# --------- # def _update_geodataframe_(self): \"\"\" \"\"\" dataseries = self.get_geoseries()", "the vertices Parameters: ----------- vertices: [list of array or dictionary]", "should be projected ? If None or '*' all the", "!= self.npixels: raise AssertionError(\"`shape` must be unique or have the", "project data in the given grid Parameters ---------- othergrid: [Grid]", "or not fast_unique: self._derived_properties[\"triangulation\"] = self.geodataframe[\"geometry\"].apply(triangulate) else: self._derived_properties[\"triangulation\"] = self.pixels[:,None,None]", "this calls self.set_geodataframe) - geoSeries - ndarray: if 3-shaped, this", "to provide indexes - dictionary: {id_1:vert_1,id_2: vert_2, ...} if a", "not += because conflict between int and float array pixels2_flat", "input data: Parameters ---------- datainput: [geopandas.geodataframe.GeoDataFrame or ndarray] this could", "update: self._update_geodataframe_() def set_pixels(self, pixels, shape=None, update=True): \"\"\" provide the", "geoSeries - ndarray: if 3-shaped, this calls set_vertices ; if", "shape_trs = np.shape(trs) if len(shape_trs)==4 and vectorized: # All Polygon", "in vertices]) self.set_pixels(pixels, None, **kwargs) return self._derived_properties[\"vertices\"] = np.asarray(vertices) shape", "...} if a dictionary is provided, the indexes will be", "be matched with gridin \"\"\" # Calcul itself projected_data =", "vertices (in degree) **kwargs goes to wcs_.all_pix2world Returns ------- Grid", "# # Properties # # =================== # @property def pixels(self):", "-------------- # if self.gridin is not None and self.gridout is", "true, to update vertices\") try: pixels = np.mean(vertices, axis=1) except:", "set by the vertices. indexes: [list or None] -optional- (Ignored", "same length as gridin - string: name of a gridin", "self.geodataframe if k not in ['geometry', 'id', 'x', 'y']] datas", "All Polygon have the same topology (same amount of vertices)", "== geopandas.geodataframe.GeoDataFrame: this.set_geodataframe(datainput) return this if type(datainput) == np.ndarray: if", "--------- # # Project # # --------- # def project_to(self,", "in column} if not asgrid: return datas # building and", "not self.is_shape_unique or not fast_unique: self._derived_properties[\"triangulation\"] = self.geodataframe[\"geometry\"].apply(triangulate) else: self._derived_properties[\"triangulation\"]", "this.set_vertices(datainput) elif len(np.shape( datainput) ) == 3: # pixels this.set_pixels(datainput)", "serie that will be matched with gridin \"\"\" # Calcul", "Should this return a new Grid (actually same object as", "# This is mandatory since integration is going to send", "@property def gridinterest(self): \"\"\" \"\"\" if self._derived_properties[\"gridinterest\"] is None: self._measure_gridinterest_()", "self._derived_properties[\"geodataframe\"] @property def triangulation(self): \"\"\" Triangulation of the vertices. Based", "format: - list of array: [[vert_1],[vert_2],....], then you may want", "datainput) ) == 3: # vertices this.set_vertices(datainput) elif len(np.shape( datainput)", "edgecolor=\"0.7\", facecolor=\"None\", **kwargs): \"\"\" \"\"\" if column is not None:", "get_simple_grid(*np.shape(stamp), shift_origin=origin) this.add_data(np.ravel(stamp), \"data\") return this @classmethod def from_vertices(cls, vertices,", "must have the same length as gridin - string: name", "self._derived_properties[\"vertices\"] = self.pixels[:,None]+self.shape return self._derived_properties[\"vertices\"] @property def is_shape_unique(self): \"\"\" \"\"\"", "[\"gridinterest\"] def __init__(self, grid_in=None, grid_out=None): \"\"\" \"\"\" if grid_in is", "Properties # # =================== # @property def pixels(self): \"\"\" \"\"\"", "(assuming grid's vertices coordinates are in pixels) Parameters ---------- wcs_:", "update the geodataframe # --------- # # UPDATE # #", "# x = [ [[....],[...]], [[....],[...]], ... ] for triangles", "list of pixels and boolean mask \"\"\" from shapely import", "= [\"gridinterest\"] def __init__(self, grid_in=None, grid_out=None): \"\"\" \"\"\" if grid_in", "ndarray: must have the same length as gridin - string:", "== 3: # vertices this.set_vertices(datainput) elif len(np.shape( datainput) ) ==", "using quadpy. pip install quadpy\") # Is Triangulation made ?", "-optional- Which data should be projected ? If None or", "is the number of pixel and M the number of", "None: indexes = self.indexes s_ = pandas.Series(data, name=name, index=indexes) if", "or out the given shapely polygon. Parameters ---------- polygon: [shapely.geometry]", "Evaluate the given function throughout the grid. This evulation is", "= np.stack(self.triangulation) shape_trs = np.shape(trs) if len(shape_trs)==4 and vectorized: #", "- ndarray: if 3-shaped, this calls set_vertices ; if 2-shaped,", "quadpy likes \"\"\" from shapely import ops triangles = ops.triangulate(geom)", "= np.concatenate(pixels.T, axis=0) if shift_origin is not None: # not", "): \"\"\" \"\"\" PROPERTIES = [\"gridin\", \"gridout\"] DERIVED_PROPERTIES = [\"gridinterest\"]", "@classmethod def from_stamps(cls, stamp, origin=[0,0]): \"\"\" stamps are 2d array,", "shift_origin=None): \"\"\" \"\"\" xbounds = np.atleast_1d(xbounds) if len(xbounds)==1: xmin,xmax =", "new geodataframe and returns it. \"\"\" import geopandas return geopandas.GeoSeries([geometry.Polygon(v)", "is None: self._measure_gridinterest_() return self._derived_properties[\"gridinterest\"] class Grid( BaseObject ): PROPERTIES", "grid, which=\"in\"): \"\"\" \"\"\" if which not in [\"in\",\"out\"]: raise", "* self.gridinterest[\"area\"] return getattr(self.gridinterest.groupby(\"id_2\")[\"_tmp\"],use)() def _parse_data_(self,data): \"\"\" Parameters ---------- data:", "---------- polygon: [shapely.geometry] reference polygon invert: [bool] -optional- Get the", "if which not in [\"in\",\"out\"]: raise ValueError(\"Which should either be", "column is not None: facecolor=None return self.geodataframe.plot(column, ax=ax,facecolor=facecolor, edgecolor=edgecolor, **kwargs)", "not None: self.set_grid(grid_out, \"out\") # =================== # # Methods #", "the same lenth as pixels\") self._properties[\"shape\"] = np.asarray(shape) else: raise", ") projected_data_array[projected_data.index.values] = projected_data.values return projected_data_array def _project_data_(self, data, use=\"sum\"):", "dependency: the integration is made using quadpy. Examples: # Remark", "get the vertices: def get_verts(poly_): return np.stack(poly_.exterior.xy).T[:-1] vertices = geodataframe[\"geometry\"].apply(get_verts).values", "the non-structural columns will be (structural columns are 'geometry', 'id',", "indexes = self.indexes s_ = pandas.Series(data, name=name, index=indexes) if not", "Parameters ---------- polygon: [shapely.geometry] reference polygon invert: [bool] -optional- Get", "show(self, column=None, ax=None, edgecolor=\"0.7\", facecolor=\"None\", **kwargs): \"\"\" \"\"\" if column", "and np.shape(shape)[0] != self.npixels: raise AssertionError(\"`shape` must be unique or", "shape already defined. set the overwrite option to true, to", "of vertices) tr_flat = np.stack(np.concatenate(trs, axis=0), axis=-2) val = quadpy.triangle.strang_fix_cowper_09().integrate(func,tr_flat).reshape(shape_trs[:2])", "with gridin \"\"\" # Calcul itself projected_data = self._project_data_(self._parse_data_(data), use=use)", "dict (see asgrid) \"\"\" gproj = GridProjector(self, othergrid) if column", "self.gridin.geodataframe[data].values elif type(data) == pandas.Series: return data.values elif len(data) !=", "dictionary] The vertices of all the grid entries. Could have", "Methods # # =================== # @classmethod def from_stamps(cls, stamp, origin=[0,0]):", "np.asarray(vertices) shape = self.vertices - pixels[:,None] shape_unique = np.unique(shape, axis=0)", "grid_in=None, grid_out=None): \"\"\" \"\"\" if grid_in is not None: self.set_grid(grid_in,", "return data # =================== # # Properties # # ===================", "return data.values elif len(data) != len(self.gridin.geodataframe): raise ValueError(\"data given as", "ymin,ymax = 0,ybounds[0] else: ymin,ymax = ybounds pixels = np.mgrid[xmin:xmax,ymin:ymax]", "shift_origin=origin) this.add_data(np.ravel(stamp), \"data\") return this @classmethod def from_vertices(cls, vertices, indexes=None):", "the given datainput\") return this raise TypeError(\"cannot parse the format", "{id_1:vert_1,id_2: vert_2, ...} if a dictionary is provided, the indexes", "and vectorized: # All Polygon have the same topology (same", "v in self.vertices]) def get_triangulation_grid(self): \"\"\" Returns a grid of", "=================== # @property def pixels(self): \"\"\" \"\"\" return self._properties[\"pixels\"] @property", "a load Grid object or an array of vertices (in", "geopandas.overlay(self.gridin.geodataframe, self.gridout.geodataframe, how='intersection') self.gridinterest[\"area\"] = self.gridinterest.apply(localdef_get_area, axis=1) else: warnings.warn(\"Cannot measure", "~flagin return self.pixels[flagin], flagin # --------- # # Project #", "ax=None, edgecolor=\"0.7\", facecolor=\"None\", **kwargs): \"\"\" \"\"\" if column is not", "--------- # def show(self, column=None, ax=None, edgecolor=\"0.7\", facecolor=\"None\", **kwargs): \"\"\"", "# All Polygon have the same topology (same amount of", "def shape(self): \"\"\" \"\"\" if self._properties[\"shape\"] is None: self._properties[\"shape\"] =", "[\"gridin\", \"gridout\"] DERIVED_PROPERTIES = [\"gridinterest\"] def __init__(self, grid_in=None, grid_out=None): \"\"\"", "np.stack(poly_.exterior.xy).T[:-1] vertices = geodataframe[\"geometry\"].apply(get_verts).values self.set_vertices(vertices, update=False) # don't update the", "] * self.gridinterest[\"area\"] return getattr(self.gridinterest.groupby(\"id_2\")[\"_tmp\"],use)() def _parse_data_(self,data): \"\"\" Parameters ----------", "stats.multivariate_normal.pdf(np.stack(x, axis=-1), mean=mu, cov=cov) ``` \"\"\" try: import quadpy except", "the triangles trs = np.stack(self.triangulation) shape_trs = np.shape(trs) if len(shape_trs)==4", "import BaseObject from shapely import geometry import pandas import geopandas", "\"\"\" \"\"\" if self._derived_properties[\"geodataframe\"] is None: self._update_geodataframe_() return self._derived_properties[\"geodataframe\"] @property", "'x':x,'y':y}) def add_data(self, data, name, indexes=None, inplace=True): \"\"\" \"\"\" if", "= np.stack(np.concatenate(trs, axis=0), axis=-2) val = quadpy.triangle.strang_fix_cowper_09().integrate(func,tr_flat).reshape(shape_trs[:2]) else: val =", "= pixels+shape \"\"\" # Setting the pixels if np.shape(pixels)[-1] !=", "object as othergrid) or a dict [asgrid=False]? Returns ------- Grid", "column: [str/None/list of] -optional- Which data should be projected ?", "pixels=None, shape=UNIT_SQUARE, indexes=None): \"\"\" \"\"\" if pixels is not None:", "data: [ndarray or string or pandas.Serie] data associated to gridin", "\"\"\" \"\"\" if self._derived_properties[\"gridinterest\"] is None: self._measure_gridinterest_() return self._derived_properties[\"gridinterest\"] class", "[shapely.geometry] reference polygon invert: [bool] -optional- Get the pixel inside", "# flatten_verts_wcs = np.asarray(wcs_.all_pix2world(flatten_verts[:,0], flatten_verts[:,1], 0, **kwargs)).T # verts_wcs =", "return this @classmethod def from_vertices(cls, vertices, indexes=None): \"\"\" directly provide", "**kwargs goes to wcs_.all_pix2world Returns ------- Grid or array (see", "object or an array of vertices (in degree) **kwargs goes", "gout = othergrid.__class__.set_from(othergrid.geodataframe) for k in column: gout.add_data(datas[k],k) return gout", "def triangulation(self): \"\"\" Triangulation of the vertices. Based on Delaunay", "array of vertices (in degree) **kwargs goes to wcs_.all_pix2world Returns", "defined. set the overwrite option to true, to update vertices\")", "as np UNIT_SQUARE = np.asarray([[0,0],[0,1],[1,1],[1,0]])-0.5 from propobject import BaseObject from", "if pixels is not None: self.set_pixels(pixels,shape=shape) if indexes is not", "if grid_in is not None: self.set_grid(grid_in, \"in\") if grid_out is", "- pandas.Serie: serie that will be matched with gridin \"\"\"", "asgrid=True, use=\"sum\"): \"\"\" project data in the given grid Parameters", "[M,2] or [N,M,2] when N is the number of pixel", "v_ in vertices]) self.set_pixels(pixels, None, **kwargs) return self._derived_properties[\"vertices\"] = np.asarray(vertices)", "self.pixels is not None else np.arange( len(geodataframe) ) # -", "def set_geodataframe(self, geodataframe, overwrite=False): \"\"\" \"\"\" if not overwrite and", "mask \"\"\" from shapely import vectorized flagin = vectorized.contains(polygon, *self.pixels.T)", "and/or gridout is/are None\") # -------------- # # Measurement #", "datainput\") return this raise TypeError(\"cannot parse the format of the", "don't update the geodataframe # --------- # # UPDATE #", "# --------- # # PLOTTER # # --------- # def", "and M the number of vertices\") if update: self._update_geodataframe_() def", "_parse_data_(self,data): \"\"\" Parameters ---------- data: [ndarray or string or pandas.Serie]", "np.unique(shape, axis=0) if len(shape_unique)==1: shape = shape_unique[0] self.set_pixels(pixels, shape, **kwargs)", "which=\"in\"): \"\"\" \"\"\" if which not in [\"in\",\"out\"]: raise ValueError(\"Which", "\"\"\" from shapely import vectorized flagin = vectorized.contains(polygon, *self.pixels.T) if", "is None: self._properties[\"shape\"] = UNIT_SQUARE return self._properties[\"shape\"] # -- Side", "axis=-2) val = quadpy.triangle.strang_fix_cowper_09().integrate(func,tr_flat).reshape(shape_trs[:2]) else: val = np.asarray([quadpy.triangle.strang_fix_cowper_09().integrate(func,np.stack(t_, axis=-2)) for", "if self.pixels is not None and len(indexes) != self.npixels: raise", "Grid object or an array of vertices (in degree) **kwargs", "import pandas import geopandas # ======================= # # # #", "dict) If you provide vertices as a list of vertices,", "AssertionError(\"not the same number of indexes as the number of", "= None def _measure_gridinterest_(self): \"\"\" \"\"\" # -- internal --", "of] -optional- Which data should be projected ? If None", "a faster method if is_shape_unique # self._derived_properties[\"gridinterest\"] = geopandas.overlay(self.gridin.geodataframe, self.gridout.geodataframe,", "# UPDATE # # --------- # def _update_geodataframe_(self): \"\"\" \"\"\"", "DERIVED_PROPERTIES = [\"gridinterest\"] def __init__(self, grid_in=None, grid_out=None): \"\"\" \"\"\" if", "pandas.Series(data, name=name, index=indexes) if not inplace: return self.geodataframe.join(s_) self._derived_properties[\"geodataframe\"] =", "Returns ------- Grid or dict (see asgrid) \"\"\" gproj =", "xmin,xmax = xbounds ybounds = np.atleast_1d(ybounds) if len(ybounds)==1: ymin,ymax =", "shape is not None: self.set_pixelshapes(shape, update=False) if update: self._update_geodataframe_() def", "\"\"\" \"\"\" if which not in [\"in\",\"out\"]: raise ValueError(\"Which should", "self.gridout is not None: # # Most likely there is", "PROPERTIES = [\"gridin\", \"gridout\"] DERIVED_PROPERTIES = [\"gridinterest\"] def __init__(self, grid_in=None,", "required\") self._derived_properties[\"geodataframe\"] = geodataframe if \"id\" not in geodataframe.columns: self.geodataframe[\"id\"]", "calls self.set_geodataframe) - geoSeries - ndarray: if 3-shaped, this calls", "axis=0) for v_ in vertices]) self.set_pixels(pixels, None, **kwargs) return self._derived_properties[\"vertices\"]", "def set_vertices(self, vertices, overwrite=False, **kwargs): \"\"\" \"\"\" if not overwrite", "use=\"sum\"): \"\"\" \"\"\" self.gridinterest[\"_tmp\"] = data[ self.gridin.geodataframe.loc[ self.gridinterest[\"id_1\"]].index ] *", "self.pixels.T self._derived_properties[\"geodataframe\"] = \\ geopandas.GeoDataFrame({'geometry': dataseries, 'id':self.indexes, 'x':x,'y':y}) def add_data(self,", "is dict: indexes, vertices = list(vertices.keys()), list(vertices.values()) this.set_vertices(vertices) if indexes", "triangle integration. -> dependency: the integration is made using quadpy.", "set_grid(self, grid, which=\"in\"): \"\"\" \"\"\" if which not in [\"in\",\"out\"]:", "given function inside the polyname using triangle integration. -> dependency:", "is_shape_unique(self): \"\"\" \"\"\" return len(np.shape(self.shape))==2 @property def geodataframe(self): \"\"\" \"\"\"", "geodataframe\") if \"geometry\" not in geodataframe.columns: raise TypeError(\"The given geodataframe", "ndarray] this could either be a: - geodataframe (and this", "get_geoseries(self): \"\"\" build a new geodataframe and returns it. \"\"\"", "column = [k for k in self.geodataframe if k not", "ndarray \"\"\" if type(data) == str: if data not in", "outsite [invert=True] Returns ------- list of pixels and boolean mask", "indexes=None, inplace=True): \"\"\" \"\"\" if indexes is None: indexes =", "if update: self._update_geodataframe_() def set_pixels(self, pixels, shape=None, update=True): \"\"\" provide", "dataframe \"\"\" this = get_simple_grid(*np.shape(stamp), shift_origin=origin) this.add_data(np.ravel(stamp), \"data\") return this", "return gout def project_to_wcs(self, wcs_, asgrid=True, **kwargs): \"\"\" provide an", "using quadpy. Examples: # Remark the np.stack(x, axis=-1). # This", "@property def vertices(self): \"\"\" \"\"\" if self._derived_properties[\"vertices\"] is None and", "ndarray: if 3-shaped, this calls set_vertices ; if 2-shaped, this", "if 2-shaped, this calls set_pixels. Returns ------- Grid \"\"\" this", "the np.stack(x, axis=-1). # This is mandatory since integration is", "self._derived_properties[\"geodataframe\"] = self.geodataframe.join(s_) # --------- # # GETTER # #", "get_verts(poly_): return np.stack(poly_.exterior.xy).T[:-1] vertices = geodataframe[\"geometry\"].apply(get_verts).values self.set_vertices(vertices, update=False) # don't", "type(data) == pandas.Series: return data.values elif len(data) != len(self.gridin.geodataframe): raise", "def get_geoseries(self): \"\"\" build a new geodataframe and returns it.", "---------- wcs_: [astropy.wcs.WCS] The world coordinate solution asgrid: [bool] -optional-", "\"\"\" this = get_simple_grid(*np.shape(stamp), shift_origin=origin) this.add_data(np.ravel(stamp), \"data\") return this @classmethod", "\"\"\" Returns a grid of triangulation. \"\"\" return Grid.set_from( np.concatenate(self.triangulation,", "not None and len(indexes) != self.npixels: raise AssertionError(\"not the same", "be 'in' our 'out'\") self._properties[\"grid%s\"%which] = grid self._derived_properties[\"gridinterest\"] = None", "this.set_geodataframe(datainput) return this if type(datainput) == np.ndarray: if len(np.shape( datainput)", "\"\"\" provide an astropy.wcs.WCS and this will project the current", "to ax.imshow(stamps) data will be stored as 'data' in the", "use=use) for k in column} if not asgrid: return datas", "= self.pixels.T return g_wcs def evaluate(self, func, vectorized=True): \"\"\" Evaluate", "# Means vertices have different size. self._derived_properties[\"vertices\"] = vertices pixels", "use=\"sum\"): \"\"\" project data in the given grid Parameters ----------", "and self.shape is not None): raise ValueError(\"Pixels and shape already", "# --------- # # Project # # --------- # def", "= get_simple_grid(*np.shape(stamp), shift_origin=origin) this.add_data(np.ravel(stamp), \"data\") return this @classmethod def from_vertices(cls,", "# # Methods # # =================== # # --------- #", "Returns ------- list of pixels and boolean mask \"\"\" from", "get_simple_grid(xbounds, ybounds, shift_origin=None): \"\"\" \"\"\" xbounds = np.atleast_1d(xbounds) if len(xbounds)==1:", "# =================== # # Methods # # =================== # @classmethod", "len(np.shape( datainput) ) == 3: # pixels this.set_pixels(datainput) else: raise", "a new Grid objects from the given input data: Parameters", "Grid (actually same object as othergrid) or a dict [asgrid=False]?", "Grid.set_from(verts_wcs) g_wcs.geodataframe[\"x_pix\"],g_wcs.geodataframe[\"y_pix\"] = self.pixels.T return g_wcs def evaluate(self, func, vectorized=True):", "!= 2: raise ValueError(\"pixels must be [N,2] arrays\") self._properties[\"pixels\"] =", "edgecolor=edgecolor, **kwargs) # =================== # # Properties # # ===================", "name=name, index=indexes) if not inplace: return self.geodataframe.join(s_) self._derived_properties[\"geodataframe\"] = self.geodataframe.join(s_)", "and boolean mask \"\"\" from shapely import vectorized flagin =", "quadpy except ImportError: raise ImportError(\"Integration is made using quadpy. pip", "self.geodataframe.plot(column, ax=ax,facecolor=facecolor, edgecolor=edgecolor, **kwargs) # =================== # # Properties #", "wcs_, asgrid=True, **kwargs): \"\"\" provide an astropy.wcs.WCS and this will", "\"\"\" if self._properties[\"shape\"] is None: self._properties[\"shape\"] = UNIT_SQUARE return self._properties[\"shape\"]", "= Grid.set_from(verts_wcs) g_wcs.geodataframe[\"x_pix\"],g_wcs.geodataframe[\"y_pix\"] = self.pixels.T return g_wcs def evaluate(self, func,", "mean=mu, cov=cov) ``` \"\"\" try: import quadpy except ImportError: raise", "def vertices(self): \"\"\" \"\"\" if self._derived_properties[\"vertices\"] is None and (self.pixels", "=================== # @property def gridin(self): \"\"\" \"\"\" return self._properties[\"gridin\"] @property", "None: warnings.warn(\"triangles not defined: deriving triangulation.\") self.derive_triangulation() # Let's get", "Return triangulate format that quadpy likes \"\"\" from shapely import", "# # # Classes # # # # ======================= #", "and len(indexes) != self.npixels: raise AssertionError(\"not the same number of", "[\"vertices\",\"geodataframe\", \"triangulation\"] def __init__(self, pixels=None, shape=UNIT_SQUARE, indexes=None): \"\"\" \"\"\" if", "and float array pixels2_flat = pixels2_flat+ shift_origin return Grid(pixels2_flat, UNIT_SQUARE)", "self.geodataframe.join(s_) # --------- # # GETTER # # --------- #", "self.set_indexes(indexes) # =================== # # Methods # # =================== #", "not None and np.shape(shape)[0] != self.npixels: raise AssertionError(\"`shape` must be", "unique or have the same lenth as pixels\") self._properties[\"shape\"] =", "geometry import pandas import geopandas # ======================= # # #", "def project_data(self, data, as_serie=True, use=\"sum\"): \"\"\" Use gridinteresect Parameters ----------", "- geoSeries - ndarray: if 3-shaped, this calls set_vertices ;", "'id', 'x', 'y') asgrid: [bool] -optional- Should this return a", "triangulation(self): \"\"\" Triangulation of the vertices. Based on Delaunay tesselation,", "pixels. This should have the length equal to th number", "is None or column in [\"*\",\"all\"]: column = [k for", "of all the grid entries. Could have two format: -", "geodataframe # --------- # # UPDATE # # --------- #", "the integration is made using quadpy. Examples: # Remark the", "a new Grid (actually same object as othergrid) or a", "all the non-structural columns will be (structural columns are 'geometry',", "Use gridinteresect Parameters ---------- data: [ndarray or string or pandas.Serie]", "def set_indexes(self, indexes, update=True): \"\"\" provide the indexes associated to", ") # - get the vertices: def get_verts(poly_): return np.stack(poly_.exterior.xy).T[:-1]", "pixels\") self._properties[\"shape\"] = np.asarray(shape) else: raise ValueError(\"Cannot parse the given", "Grid or dict (see asgrid) \"\"\" gproj = GridProjector(self, othergrid)", "return self.gridin.geodataframe[data].values elif type(data) == pandas.Series: return data.values elif len(data)", "l.geometry.area/self.gridin.geodataframe.iloc[l.id_1].geometry.area # -------------- # if self.gridin is not None and", "def get_simple_grid(xbounds, ybounds, shift_origin=None): \"\"\" \"\"\" xbounds = np.atleast_1d(xbounds) if", "def derive_triangulation(self, fast_unique=True): \"\"\" \"\"\" def triangulate(geom): \"\"\" Return triangulate", "this @classmethod def from_vertices(cls, vertices, indexes=None): \"\"\" directly provide the", "Grid.set_from( np.concatenate(self.triangulation, axis=0) ) def get_pixels_in(self, polygon, invert=False): \"\"\" checks", "\"\"\" provide the indexes associated to each pixels Parameters ----------", "flagin # --------- # # Project # # --------- #", "pixels(self): \"\"\" \"\"\" return self._properties[\"pixels\"] @property def npixels(self): \"\"\" \"\"\"", "[bool] -optional- Get the pixel inside the polygon [invert=False] or", "[use True if you are not sure] Returns ------- Void", "SETTER # # --------- # def set_indexes(self, indexes, update=True): \"\"\"", "raise ValueError(\"data given as ndarray but lengthes do not match\")", "returns it. \"\"\" import geopandas return geopandas.GeoSeries([geometry.Polygon(v) for v in", "= np.asarray([[0,0],[0,1],[1,1],[1,0]])-0.5 from propobject import BaseObject from shapely import geometry", "dict: indexes, vertices = list(vertices.keys()), list(vertices.values()) this.set_vertices(vertices) if indexes is", "None and len(indexes) != self.npixels: raise AssertionError(\"not the same number", "self.pixels is not None and np.shape(shape)[0] != self.npixels: raise AssertionError(\"`shape`", "vertices = geodataframe[\"geometry\"].apply(get_verts).values self.set_vertices(vertices, update=False) # don't update the geodataframe", "? [use True if you are not sure] Returns -------", "PLOTTER # # --------- # def show(self, column=None, ax=None, edgecolor=\"0.7\",", "internal -- # def localdef_get_area(l): return l.geometry.area/self.gridin.geodataframe.iloc[l.id_1].geometry.area # -------------- #", "astropy.wcs.WCS and this will project the current grid into it", "np.arange(len(vertices)) Returns ------- Grid \"\"\" this = cls() if type(vertices)", "pixels Parameters ---------- indexes: [ndarray] indexes associated to the pixels.", "self._properties[\"shape\"] = np.asarray(shape) elif len(np.shape(shape))==3: if self.pixels is not None", "== pandas.Series: return data.values elif len(data) != len(self.gridin.geodataframe): raise ValueError(\"data", "if None, then indexes = np.arange(len(vertices)) Returns ------- Grid \"\"\"", "[ [[....],[...]], [[....],[...]], ... ] for triangles ```python def get_2dgauss(x,", "\"\"\" \"\"\" return stats.multivariate_normal.pdf(np.stack(x, axis=-1), mean=mu, cov=cov) ``` \"\"\" try:", "not in geodataframe.columns: self.geodataframe[\"id\"] = self.indexes if self.pixels is not", "from shapely import vectorized flagin = vectorized.contains(polygon, *self.pixels.T) if invert:", "else: ymin,ymax = ybounds pixels = np.mgrid[xmin:xmax,ymin:ymax] pixels2_flat = np.concatenate(pixels.T,", "(structural columns are 'geometry', 'id', 'x', 'y') asgrid: [bool] -optional-", "not None else np.arange( len(geodataframe) ) # - get the", "return stats.multivariate_normal.pdf(np.stack(x, axis=-1), mean=mu, cov=cov) ``` \"\"\" try: import quadpy", "# # # Functions # # # # ======================= #", "of array: [[vert_1],[vert_2],....], then you may want to provide indexes", "pixels+shape \"\"\" # Setting the pixels if np.shape(pixels)[-1] != 2:", "in column: gout.add_data(datas[k],k) return gout def project_to_wcs(self, wcs_, asgrid=True, **kwargs):", "and returns it. \"\"\" import geopandas return geopandas.GeoSeries([geometry.Polygon(v) for v", "and shape already defined. set the overwrite option to true,", "Grid \"\"\" this = cls() if type(vertices) is dict: indexes,", "of the vertices. Based on Delaunay tesselation, see shapely.ops.triangulate \"\"\"", "ax=ax,facecolor=facecolor, edgecolor=edgecolor, **kwargs) # =================== # # Properties # #", "different size. self._derived_properties[\"vertices\"] = vertices pixels = np.asarray([np.mean(v_, axis=0) for", "raise ValueError(\"Cannot parse the given shape, must be [M,2] or", "going to send # x = [ [[....],[...]], [[....],[...]], ...", "will be (structural columns are 'geometry', 'id', 'x', 'y') asgrid:", "as a list of vertices, you can provide the indexes", "else: self._derived_properties[\"triangulation\"] = self.pixels[:,None,None] + triangulate(geometry.Polygon(self.shape)) # --------- # #", "Parameters ---------- datainput: [geopandas.geodataframe.GeoDataFrame or ndarray] this could either be", "# Setting the pixel shape.s if len(np.shape(shape))==2: self._properties[\"shape\"] = np.asarray(shape)", "= list(vertices.keys()), list(vertices.values()) this.set_vertices(vertices) if indexes is not None: this.set_indexes(indexes)", "= 0,xbounds[0] else: xmin,xmax = xbounds ybounds = np.atleast_1d(ybounds) if", "except ImportError: raise ImportError(\"Integration is made using quadpy. pip install", "-optional- (Ignored if vertices is a dict) If you provide", "axis=-2)) for t_ in trs]) return np.sum(val, axis=1) def derive_triangulation(self,", "vertices pixels = np.asarray([np.mean(v_, axis=0) for v_ in vertices]) self.set_pixels(pixels,", "is None: warnings.warn(\"triangles not defined: deriving triangulation.\") self.derive_triangulation() # Let's", "not in geodataframe.columns: raise TypeError(\"The given geodataframe does not have", "between int and float array pixels2_flat = pixels2_flat+ shift_origin return", "**kwargs) # =================== # # Properties # # =================== #", "True if you are not sure] Returns ------- Void \"\"\"", "have the same lenth as pixels\") self._properties[\"shape\"] = np.asarray(shape) else:", "Returns ------- Grid \"\"\" this = cls() if type(datainput) ==", "len(shape_trs)==4 and vectorized: # All Polygon have the same topology", "cls() if type(vertices) is dict: indexes, vertices = list(vertices.keys()), list(vertices.values())", "\"\"\" Creates a new Grid objects from the given input", "goes to wcs_.all_pix2world Returns ------- Grid or array (see asgrid)", "be unique or have the same lenth as pixels\") self._properties[\"shape\"]", "self.set_grid(grid_out, \"out\") # =================== # # Methods # # ===================", "----------- vertices: [list of array or dictionary] The vertices of", "!= self.npixels: raise AssertionError(\"not the same number of indexes as", "# GETTER # # --------- # def get_geoseries(self): \"\"\" build", "asgrid=True, **kwargs): \"\"\" provide an astropy.wcs.WCS and this will project", "pandas.Series: return data.values elif len(data) != len(self.gridin.geodataframe): raise ValueError(\"data given", "is not None: self.set_pixels(pixels,shape=shape) if indexes is not None: self.set_indexes(indexes)", "Derived @property def vertices(self): \"\"\" \"\"\" if self._derived_properties[\"vertices\"] is None", "update: self._update_geodataframe_() def set_vertices(self, vertices, overwrite=False, **kwargs): \"\"\" \"\"\" if", "not match\") return data # =================== # # Properties #", "# # SETTER # # --------- # def set_grid(self, grid,", "verts_wcs = flatten_verts_wcs.reshape(verts_shape) if not asgrid: return verts_wcs g_wcs =", "len(geodataframe) ) # - get the vertices: def get_verts(poly_): return", "# ======================= # class GridProjector( BaseObject ): \"\"\" \"\"\" PROPERTIES", "asgrid: return datas # building and setting the new grid", "inplace=True): \"\"\" \"\"\" if indexes is None: indexes = self.indexes", "the pixel is in or out the given shapely polygon.", "raise ValueError(\"Unknown gridin column '%s'\"%data) return self.gridin.geodataframe[data].values elif type(data) ==", "if self.gridin is not None and self.gridout is not None:", "ybounds, shift_origin=None): \"\"\" \"\"\" xbounds = np.atleast_1d(xbounds) if len(xbounds)==1: xmin,xmax", "\"\"\" xbounds = np.atleast_1d(xbounds) if len(xbounds)==1: xmin,xmax = 0,xbounds[0] else:", "\"\"\" stamps are 2d array, something you could to ax.imshow(stamps)", "raise AssertionError(\"not the same number of indexes as the number", "gridout is/are None\") # -------------- # # Measurement # #", "indexes(self): \"\"\" \"\"\" if self._side_properties[\"indexes\"] is None: self._side_properties[\"indexes\"] = np.arange(self.npixels)", "\"\"\" if not overwrite and (self.pixels is not None and", "could be: - ndarray: must have the same length as", "{k:gproj.project_data(k, use=use) for k in column} if not asgrid: return", "= vectorized.contains(polygon, *self.pixels.T) if invert: flagin = ~flagin return self.pixels[flagin],", "pixels\") self._side_properties[\"indexes\"] = indexes if update: self._update_geodataframe_() def set_pixels(self, pixels,", "self._properties[\"pixels\"] = np.asarray(pixels) if shape is not None: self.set_pixelshapes(shape, update=False)", "# Measurement # # -------------- # def project_data(self, data, as_serie=True,", "------- Grid or dict (see asgrid) \"\"\" gproj = GridProjector(self,", "of vertices\") if update: self._update_geodataframe_() def set_vertices(self, vertices, overwrite=False, **kwargs):", "self.pixels[:,None]+self.shape return self._derived_properties[\"vertices\"] @property def is_shape_unique(self): \"\"\" \"\"\" return len(np.shape(self.shape))==2", "already defined. set the overwrite option to true, to update", "use=\"sum\"): \"\"\" Use gridinteresect Parameters ---------- data: [ndarray or string", "load Grid object or an array of vertices (in degree)", "in pixels) Parameters ---------- wcs_: [astropy.wcs.WCS] The world coordinate solution", "amount of vertices) tr_flat = np.stack(np.concatenate(trs, axis=0), axis=-2) val =", "pixel shape.s if len(np.shape(shape))==2: self._properties[\"shape\"] = np.asarray(shape) elif len(np.shape(shape))==3: if", "this.add_data(np.ravel(stamp), \"data\") return this @classmethod def from_vertices(cls, vertices, indexes=None): \"\"\"", "triangulation.\") self.derive_triangulation() # Let's get the triangles trs = np.stack(self.triangulation)", "+= because conflict between int and float array pixels2_flat =", "numpy as np UNIT_SQUARE = np.asarray([[0,0],[0,1],[1,1],[1,0]])-0.5 from propobject import BaseObject", "using polynome triangulation to integrate the given function inside the", "grid Parameters ---------- othergrid: [Grid] New grid where data should", "for k in column} if not asgrid: return datas #", "@property def indexes(self): \"\"\" \"\"\" if self._side_properties[\"indexes\"] is None: self._side_properties[\"indexes\"]", "return l.geometry.area/self.gridin.geodataframe.iloc[l.id_1].geometry.area # -------------- # if self.gridin is not None", "pixels = np.asarray([np.mean(v_, axis=0) for v_ in vertices]) self.set_pixels(pixels, None,", "inside the polygon [invert=False] or outsite [invert=True] Returns ------- list", "or pandas.Serie] data associated to gridin that should be projected", "if a dictionary is provided, the indexes will be set", "self._properties[\"shape\"] = np.asarray(shape) else: raise ValueError(\"Cannot parse the given shape,", "--------- # # SETTER # # --------- # def set_indexes(self,", "the grid. This evulation is using polynome triangulation to integrate", "Void \"\"\" if self.pixels is not None and len(indexes) !=", "in or out the given shapely polygon. Parameters ---------- polygon:", "is None: self._side_properties[\"indexes\"] = np.arange(self.npixels) return self._side_properties[\"indexes\"] # -- Derived", "# -------------- # # Measurement # # -------------- # def", "np.atleast_1d(xbounds) if len(xbounds)==1: xmin,xmax = 0,xbounds[0] else: xmin,xmax = xbounds", "because conflict between int and float array pixels2_flat = pixels2_flat+", "inside the polyname using triangle integration. -> dependency: the integration", "if is_shape_unique # self._derived_properties[\"gridinterest\"] = geopandas.overlay(self.gridin.geodataframe, self.gridout.geodataframe, how='intersection') self.gridinterest[\"area\"] =", "return self.geodataframe.plot(column, ax=ax,facecolor=facecolor, edgecolor=edgecolor, **kwargs) # =================== # # Properties", "defined. NB: vertices = pixels+shape \"\"\" # Setting the pixels", "calls set_pixels. Returns ------- Grid \"\"\" this = cls() if", "= np.shape(verts) flatten_verts = np.concatenate(verts, axis=0) # flatten_verts_wcs = np.asarray(wcs_.all_pix2world(flatten_verts[:,0],", "provide an astropy.wcs.WCS and this will project the current grid", "not fast_unique: self._derived_properties[\"triangulation\"] = self.geodataframe[\"geometry\"].apply(triangulate) else: self._derived_properties[\"triangulation\"] = self.pixels[:,None,None] +", "this.set_pixels(datainput) else: raise TypeError(\"cannot parse the shape of the given", "if \"id\" not in geodataframe.columns: self.geodataframe[\"id\"] = self.indexes if self.pixels", "data # =================== # # Properties # # =================== #", "the number of pixels\") self._side_properties[\"indexes\"] = indexes if update: self._update_geodataframe_()", "or None] -optional- (Ignored if vertices is a dict) If", "np.shape(shape)[0] != self.npixels: raise AssertionError(\"`shape` must be unique or have", "the given function inside the polyname using triangle integration. ->", "\"\"\" # Setting the pixel shape.s if len(np.shape(shape))==2: self._properties[\"shape\"] =", "if vertices is a dict) If you provide vertices as", "could to ax.imshow(stamps) data will be stored as 'data' in", "update: self._update_geodataframe_() def set_pixelshapes(self, shape, update=True): \"\"\" \"\"\" # Setting", "get the triangles trs = np.stack(self.triangulation) shape_trs = np.shape(trs) if", "= self.indexes if self.pixels is not None else np.arange( len(geodataframe)", "# # -------------- # def project_data(self, data, as_serie=True, use=\"sum\"): \"\"\"", "directly provide the vertices Parameters: ----------- vertices: [list of array", "import vectorized flagin = vectorized.contains(polygon, *self.pixels.T) if invert: flagin =", "[\"pixels\", \"shape\"] SIDE_PROPERTIES = [\"indexes\"] DERIVED_PROPERTIES = [\"vertices\",\"geodataframe\", \"triangulation\"] def", "and self.gridout is not None: # # Most likely there", "or array (see asgrid) \"\"\" verts = self.vertices verts_shape =", "may want to provide indexes - dictionary: {id_1:vert_1,id_2: vert_2, ...}", "if not overwrite and (self.pixels is not None and self.shape", "axis=-1). # This is mandatory since integration is going to", "facecolor=None return self.geodataframe.plot(column, ax=ax,facecolor=facecolor, edgecolor=edgecolor, **kwargs) # =================== # #", "provided, the indexes will be set by the vertices. indexes:", "3: # pixels this.set_pixels(datainput) else: raise TypeError(\"cannot parse the shape", "type(datainput) == np.ndarray: if len(np.shape( datainput) ) == 3: #", "= np.arange(self.npixels) return self._side_properties[\"indexes\"] # -- Derived @property def vertices(self):", "(self.pixels is not None and self.shape is not None): self._derived_properties[\"vertices\"]", "import numpy as np UNIT_SQUARE = np.asarray([[0,0],[0,1],[1,1],[1,0]])-0.5 from propobject import", "verts_shape = np.shape(verts) flatten_verts = np.concatenate(verts, axis=0) # flatten_verts_wcs =", "must be [N,2] arrays\") self._properties[\"pixels\"] = np.asarray(pixels) if shape is", "ValueError(\"data given as ndarray but lengthes do not match\") return", "# # =================== # @property def pixels(self): \"\"\" \"\"\" return", "self.gridinterest[\"area\"] return getattr(self.gridinterest.groupby(\"id_2\")[\"_tmp\"],use)() def _parse_data_(self,data): \"\"\" Parameters ---------- data: [ndarray", "# Project # # --------- # def project_to(self, othergrid, column=\"*\",", "axis=1) else: warnings.warn(\"Cannot measure gridinterest, because gridin and/or gridout is/are", "= cls() if type(datainput) == geopandas.geodataframe.GeoDataFrame: this.set_geodataframe(datainput) return this if", "shape = self.vertices - pixels[:,None] shape_unique = np.unique(shape, axis=0) if", "indexes of each of the vertices. -> if None, then", "@property def pixels(self): \"\"\" \"\"\" return self._properties[\"pixels\"] @property def npixels(self):", "this calls set_pixels. Returns ------- Grid \"\"\" this = cls()", "how='intersection') self.gridinterest[\"area\"] = self.gridinterest.apply(localdef_get_area, axis=1) else: warnings.warn(\"Cannot measure gridinterest, because", "each of the vertices. -> if None, then indexes =", "BaseObject from shapely import geometry import pandas import geopandas #", "parse the format of the given input\") # --------- #", "flatten_verts_wcs = np.asarray(wcs_.all_pix2world(flatten_verts[:,0], flatten_verts[:,1], 0, **kwargs)).T # verts_wcs = flatten_verts_wcs.reshape(verts_shape)", "geopandas.geodataframe.GeoDataFrame: this.set_geodataframe(datainput) return this if type(datainput) == np.ndarray: if len(np.shape(", "data: Parameters ---------- datainput: [geopandas.geodataframe.GeoDataFrame or ndarray] this could either", "None and self.gridout is not None: # # Most likely", "\"\"\" if type(data) == str: if data not in self.gridin.geodataframe.columns:", "# if self.gridin is not None and self.gridout is not", "# verts_wcs = flatten_verts_wcs.reshape(verts_shape) if not asgrid: return verts_wcs g_wcs", "the pixel inside the polygon [invert=False] or outsite [invert=True] Returns", "defined: deriving triangulation.\") self.derive_triangulation() # Let's get the triangles trs", "np.ndarray: if len(np.shape( datainput) ) == 3: # vertices this.set_vertices(datainput)", "shape, update=True): \"\"\" \"\"\" # Setting the pixel shape.s if", "[str/None/list of] -optional- Which data should be projected ? If", "this calls set_vertices ; if 2-shaped, this calls set_pixels. Returns", "raise AssertionError(\"`shape` must be unique or have the same lenth", "is not None: # # Most likely there is a", "npixels(self): \"\"\" \"\"\" return len(self.pixels) @property def shape(self): \"\"\" \"\"\"", "\"\"\" return stats.multivariate_normal.pdf(np.stack(x, axis=-1), mean=mu, cov=cov) ``` \"\"\" try: import", "# --------- # # GETTER # # --------- # def", "given function throughout the grid. This evulation is using polynome", "not defined: deriving triangulation.\") self.derive_triangulation() # Let's get the triangles", "indexes, update=True): \"\"\" provide the indexes associated to each pixels", "- dictionary: {id_1:vert_1,id_2: vert_2, ...} if a dictionary is provided,", "the grid's dataframe \"\"\" this = get_simple_grid(*np.shape(stamp), shift_origin=origin) this.add_data(np.ravel(stamp), \"data\")", "the overwrite option to true, to update vertices\") try: pixels", "self.vertices]) def get_triangulation_grid(self): \"\"\" Returns a grid of triangulation. \"\"\"", "send # x = [ [[....],[...]], [[....],[...]], ... ] for", "up on which the geometries are defined. NB: vertices =", "is not None: this.set_indexes(indexes) return this @classmethod def set_from(cls, datainput):", "): PROPERTIES = [\"pixels\", \"shape\"] SIDE_PROPERTIES = [\"indexes\"] DERIVED_PROPERTIES =", "# # Most likely there is a faster method if", "------- list of pixels and boolean mask \"\"\" from shapely", "return this if type(datainput) == np.ndarray: if len(np.shape( datainput) )", "is not None: self.set_pixelshapes(shape, update=False) if update: self._update_geodataframe_() def set_pixelshapes(self,", "grid into it (assuming grid's vertices coordinates are in pixels)", "is not None: self.set_indexes(indexes) # =================== # # Methods #", "will project the current grid into it (assuming grid's vertices", "the vertices: def get_verts(poly_): return np.stack(poly_.exterior.xy).T[:-1] vertices = geodataframe[\"geometry\"].apply(get_verts).values self.set_vertices(vertices,", "triangulate format that quadpy likes \"\"\" from shapely import ops", "is/are None\") # -------------- # # Measurement # # --------------", "a gridin column (pandas) - pandas.Serie: serie that will be", "vertices as a list of vertices, you can provide the", "None def _measure_gridinterest_(self): \"\"\" \"\"\" # -- internal -- #", "# @classmethod def from_stamps(cls, stamp, origin=[0,0]): \"\"\" stamps are 2d", "of a gridin column (pandas) - pandas.Serie: serie that will", "= np.asarray(wcs_.all_pix2world(flatten_verts[:,0], flatten_verts[:,1], 0, **kwargs)).T # verts_wcs = flatten_verts_wcs.reshape(verts_shape) if", "ValueError(\"Pixels and shape already defined. set the overwrite option to", "!= len(self.gridin.geodataframe): raise ValueError(\"data given as ndarray but lengthes do", "indexes: [list or None] -optional- (Ignored if vertices is a", "= np.zeros( len(self.gridout.geodataframe) ) projected_data_array[projected_data.index.values] = projected_data.values return projected_data_array def", "return len(np.shape(self.shape))==2 @property def geodataframe(self): \"\"\" \"\"\" if self._derived_properties[\"geodataframe\"] is", "np.asarray([np.mean(v_, axis=0) for v_ in vertices]) self.set_pixels(pixels, None, **kwargs) return", "def add_data(self, data, name, indexes=None, inplace=True): \"\"\" \"\"\" if indexes", "for v in self.vertices]) def get_triangulation_grid(self): \"\"\" Returns a grid", "equal to th number of pixels (if any). update: [bool]", "or a dict [asgrid=False]? Returns ------- Grid or dict (see", "self.indexes s_ = pandas.Series(data, name=name, index=indexes) if not inplace: return", "set_from(cls, datainput): \"\"\" Creates a new Grid objects from the", "def triangulate(geom): \"\"\" Return triangulate format that quadpy likes \"\"\"", "def project_to(self, othergrid, column=\"*\", asgrid=True, use=\"sum\"): \"\"\" project data in", "evulation is using polynome triangulation to integrate the given function", "**kwargs): \"\"\" \"\"\" if not overwrite and (self.pixels is not", "def _update_geodataframe_(self): \"\"\" \"\"\" dataseries = self.get_geoseries() x,y = self.pixels.T", "lenth as pixels\") self._properties[\"shape\"] = np.asarray(shape) else: raise ValueError(\"Cannot parse", "np.mean(vertices, axis=1) except: # Means vertices have different size. self._derived_properties[\"vertices\"]", "\"\"\" \"\"\" if pixels is not None: self.set_pixels(pixels,shape=shape) if indexes", "pixels) Parameters ---------- wcs_: [astropy.wcs.WCS] The world coordinate solution asgrid:", "@classmethod def set_from(cls, datainput): \"\"\" Creates a new Grid objects", "the current grid into it (assuming grid's vertices coordinates are", "have two format: - list of array: [[vert_1],[vert_2],....], then you", "in geodataframe.columns: raise TypeError(\"The given geodataframe does not have 'geometry'", "None and self.shape is not None): raise ValueError(\"Pixels and shape", "def __init__(self, grid_in=None, grid_out=None): \"\"\" \"\"\" if grid_in is not", "gridin \"\"\" # Calcul itself projected_data = self._project_data_(self._parse_data_(data), use=use) if", "the given shape, must be [M,2] or [N,M,2] when N", "projected_data = self._project_data_(self._parse_data_(data), use=use) if as_serie: return projected_data projected_data_array =", "\"\"\" if self.pixels is not None and len(indexes) != self.npixels:", "projected ? If None or '*' all the non-structural columns", "[N,M,2] when N is the number of pixel and M", "of pixel and M the number of vertices\") if update:", "self._properties[\"grid%s\"%which] = grid self._derived_properties[\"gridinterest\"] = None def _measure_gridinterest_(self): \"\"\" \"\"\"", "\"\"\" Parameters ---------- data: [ndarray or string or pandas.Serie] data", "= ops.triangulate(geom) return np.stack([np.asarray(t.exterior.coords.xy).T[:-1] for t in triangles]) if not", "array pixels2_flat = pixels2_flat+ shift_origin return Grid(pixels2_flat, UNIT_SQUARE) # =======================", "**kwargs) def set_geodataframe(self, geodataframe, overwrite=False): \"\"\" \"\"\" if not overwrite", "is in or out the given shapely polygon. Parameters ----------", "--------- # # UPDATE # # --------- # def _update_geodataframe_(self):", "datas # building and setting the new grid gout =", "not None: facecolor=None return self.geodataframe.plot(column, ax=ax,facecolor=facecolor, edgecolor=edgecolor, **kwargs) # ===================", "overwrite=False): \"\"\" \"\"\" if not overwrite and (self.pixels is not", "# # ======================= # def get_simple_grid(xbounds, ybounds, shift_origin=None): \"\"\" \"\"\"", "Returns a grid of triangulation. \"\"\" return Grid.set_from( np.concatenate(self.triangulation, axis=0)", "] for triangles ```python def get_2dgauss(x, mu=[4,4], cov=[[1,0],[0,2]]): \"\"\" \"\"\"", "and this will project the current grid into it (assuming", "None: # # Most likely there is a faster method", "'id':self.indexes, 'x':x,'y':y}) def add_data(self, data, name, indexes=None, inplace=True): \"\"\" \"\"\"", "polygon [invert=False] or outsite [invert=True] Returns ------- list of pixels", "have the length equal to th number of pixels (if", "gridout(self): \"\"\" \"\"\" return self._properties[\"gridout\"] @property def gridinterest(self): \"\"\" \"\"\"", "self.set_pixels(pixels,shape=shape) if indexes is not None: self.set_indexes(indexes) # =================== #", "integration is going to send # x = [ [[....],[...]],", "datainput: [geopandas.geodataframe.GeoDataFrame or ndarray] this could either be a: -", "either be a: - geodataframe (and this calls self.set_geodataframe) -", "Parameters ---------- data: [ndarray or string or pandas.Serie] data associated", "# Properties # # =================== # @property def gridin(self): \"\"\"", "indexes is not None: self.set_indexes(indexes) # =================== # # Methods", "quadpy.triangle.strang_fix_cowper_09().integrate(func,tr_flat).reshape(shape_trs[:2]) else: val = np.asarray([quadpy.triangle.strang_fix_cowper_09().integrate(func,np.stack(t_, axis=-2)) for t_ in trs])", "column (pandas) - pandas.Serie: serie that will be matched with", "is not None and len(indexes) != self.npixels: raise AssertionError(\"not the", "---------- indexes: [ndarray] indexes associated to the pixels. This should", "import ops triangles = ops.triangulate(geom) return np.stack([np.asarray(t.exterior.coords.xy).T[:-1] for t in", "= [k for k in self.geodataframe if k not in", "= {k:gproj.project_data(k, use=use) for k in column} if not asgrid:", "[k for k in self.geodataframe if k not in ['geometry',", "this if type(datainput) == np.ndarray: if len(np.shape( datainput) ) ==", "# building and setting the new grid gout = othergrid.__class__.set_from(othergrid.geodataframe)", "# Is Triangulation made ? if self._derived_properties[\"triangulation\"] is None: warnings.warn(\"triangles", "geodataframe (and this calls self.set_geodataframe) - geoSeries - ndarray: if", "_update_geodataframe_(self): \"\"\" \"\"\" dataseries = self.get_geoseries() x,y = self.pixels.T self._derived_properties[\"geodataframe\"]", "projected to column: [str/None/list of] -optional- Which data should be", "\"\"\" return self._properties[\"gridin\"] @property def gridout(self): \"\"\" \"\"\" return self._properties[\"gridout\"]", "[list or None] -optional- (Ignored if vertices is a dict)", "a: - geodataframe (and this calls self.set_geodataframe) - geoSeries -", "fast_unique=True): \"\"\" \"\"\" def triangulate(geom): \"\"\" Return triangulate format that", "-> dependency: the integration is made using quadpy. Examples: #", "self._derived_properties[\"vertices\"] @property def is_shape_unique(self): \"\"\" \"\"\" return len(np.shape(self.shape))==2 @property def", "invert=False): \"\"\" checks if the centroid of the pixel is", "be projected to column: [str/None/list of] -optional- Which data should", "using triangle integration. -> dependency: the integration is made using", "\"\"\" \"\"\" dataseries = self.get_geoseries() x,y = self.pixels.T self._derived_properties[\"geodataframe\"] =", "def gridout(self): \"\"\" \"\"\" return self._properties[\"gridout\"] @property def gridinterest(self): \"\"\"", "self.set_pixelshapes(shape, update=False) if update: self._update_geodataframe_() def set_pixelshapes(self, shape, update=True): \"\"\"", "# =================== # # Methods # # =================== # #", "raise TypeError(\"cannot parse the format of the given input\") #", "Remark the np.stack(x, axis=-1). # This is mandatory since integration", "**kwargs) return self._derived_properties[\"vertices\"] = np.asarray(vertices) shape = self.vertices - pixels[:,None]", "the given grid Parameters ---------- othergrid: [Grid] New grid where", "It is required\") self._derived_properties[\"geodataframe\"] = geodataframe if \"id\" not in", "ops triangles = ops.triangulate(geom) return np.stack([np.asarray(t.exterior.coords.xy).T[:-1] for t in triangles])", "pandas.Serie: serie that will be matched with gridin Returns -------", "# ======================= # # # # Functions # # #", "\"\"\" return Grid.set_from( np.concatenate(self.triangulation, axis=0) ) def get_pixels_in(self, polygon, invert=False):", "xmin,xmax = 0,xbounds[0] else: xmin,xmax = xbounds ybounds = np.atleast_1d(ybounds)", "[ndarray] indexes associated to the pixels. This should have the", "overwrite and (self.pixels is not None and self.shape is not", "# def get_simple_grid(xbounds, ybounds, shift_origin=None): \"\"\" \"\"\" xbounds = np.atleast_1d(xbounds)", "function throughout the grid. This evulation is using polynome triangulation", "the given function throughout the grid. This evulation is using", "np.concatenate(verts, axis=0) # flatten_verts_wcs = np.asarray(wcs_.all_pix2world(flatten_verts[:,0], flatten_verts[:,1], 0, **kwargs)).T #", "import warnings import numpy as np UNIT_SQUARE = np.asarray([[0,0],[0,1],[1,1],[1,0]])-0.5 from", "is provided, the indexes will be set by the vertices.", "= np.shape(trs) if len(shape_trs)==4 and vectorized: # All Polygon have", "not None and self.shape is not None): raise ValueError(\"Pixels and", "self.pixels[:,None,None] + triangulate(geometry.Polygon(self.shape)) # --------- # # PLOTTER # #", "= UNIT_SQUARE return self._properties[\"shape\"] # -- Side @property def indexes(self):", "\"\"\" \"\"\" # Setting the pixel shape.s if len(np.shape(shape))==2: self._properties[\"shape\"]", "of indexes as the number of pixels\") self._side_properties[\"indexes\"] = indexes", "[[vert_1],[vert_2],....], then you may want to provide indexes - dictionary:", "not in [\"in\",\"out\"]: raise ValueError(\"Which should either be 'in' our", "indexes as the number of pixels\") self._side_properties[\"indexes\"] = indexes if", "all the grid entries. Could have two format: - list", "geodataframe.columns: self.geodataframe[\"id\"] = self.indexes if self.pixels is not None else", "asgrid: [bool] -optional- Should this return a new Grid (actually", "pixels is not None: self.set_pixels(pixels,shape=shape) if indexes is not None:", "the grid entries. Could have two format: - list of", "= geodataframe if \"id\" not in geodataframe.columns: self.geodataframe[\"id\"] = self.indexes", "None: self.set_grid(grid_in, \"in\") if grid_out is not None: self.set_grid(grid_out, \"out\")", "self._derived_properties[\"vertices\"] is None and (self.pixels is not None and self.shape", "shape, must be [M,2] or [N,M,2] when N is the", "of array or dictionary] The vertices of all the grid", "geodataframe does not have 'geometry' column. It is required\") self._derived_properties[\"geodataframe\"]", "= self.vertices - pixels[:,None] shape_unique = np.unique(shape, axis=0) if len(shape_unique)==1:", "# def show(self, column=None, ax=None, edgecolor=\"0.7\", facecolor=\"None\", **kwargs): \"\"\" \"\"\"", "[\"*\",\"all\"]: column = [k for k in self.geodataframe if k", "def from_vertices(cls, vertices, indexes=None): \"\"\" directly provide the vertices Parameters:", "np.asarray(shape) elif len(np.shape(shape))==3: if self.pixels is not None and np.shape(shape)[0]", "vertices) tr_flat = np.stack(np.concatenate(trs, axis=0), axis=-2) val = quadpy.triangle.strang_fix_cowper_09().integrate(func,tr_flat).reshape(shape_trs[:2]) else:", "format of the given input\") # --------- # # SETTER", "======================= # def get_simple_grid(xbounds, ybounds, shift_origin=None): \"\"\" \"\"\" xbounds =", "Functions # # # # ======================= # def get_simple_grid(xbounds, ybounds,", "indexes associated to each pixels Parameters ---------- indexes: [ndarray] indexes", "# # ======================= # class GridProjector( BaseObject ): \"\"\" \"\"\"", "datas = {k:gproj.project_data(k, use=use) for k in column} if not", "# def project_data(self, data, as_serie=True, use=\"sum\"): \"\"\" Use gridinteresect Parameters", "# =================== # @property def pixels(self): \"\"\" \"\"\" return self._properties[\"pixels\"]", "if self._derived_properties[\"gridinterest\"] is None: self._measure_gridinterest_() return self._derived_properties[\"gridinterest\"] class Grid( BaseObject", "len(ybounds)==1: ymin,ymax = 0,ybounds[0] else: ymin,ymax = ybounds pixels =", "self.gridout.geodataframe, how='intersection') self.gridinterest[\"area\"] = self.gridinterest.apply(localdef_get_area, axis=1) else: warnings.warn(\"Cannot measure gridinterest,", "geopandas.GeoSeries([geometry.Polygon(v) for v in self.vertices]) def get_triangulation_grid(self): \"\"\" Returns a", "warnings.warn(\"Cannot measure gridinterest, because gridin and/or gridout is/are None\") #", "number of vertices\") if update: self._update_geodataframe_() def set_vertices(self, vertices, overwrite=False,", "solution asgrid: [bool] -optional- Should this return a load Grid", "be: - ndarray: must have the same length as gridin", "not None: self.set_grid(grid_in, \"in\") if grid_out is not None: self.set_grid(grid_out,", "this.set_vertices(vertices) if indexes is not None: this.set_indexes(indexes) return this @classmethod", "=================== # # Properties # # =================== # @property def", "= grid self._derived_properties[\"gridinterest\"] = None def _measure_gridinterest_(self): \"\"\" \"\"\" #", "this = get_simple_grid(*np.shape(stamp), shift_origin=origin) this.add_data(np.ravel(stamp), \"data\") return this @classmethod def", "# def localdef_get_area(l): return l.geometry.area/self.gridin.geodataframe.iloc[l.id_1].geometry.area # -------------- # if self.gridin", "======================= # # # # Functions # # # #", "is not None else np.arange( len(geodataframe) ) # - get", "this @classmethod def set_from(cls, datainput): \"\"\" Creates a new Grid", "[\"indexes\"] DERIVED_PROPERTIES = [\"vertices\",\"geodataframe\", \"triangulation\"] def __init__(self, pixels=None, shape=UNIT_SQUARE, indexes=None):", "def npixels(self): \"\"\" \"\"\" return len(self.pixels) @property def shape(self): \"\"\"", "wcs_: [astropy.wcs.WCS] The world coordinate solution asgrid: [bool] -optional- Should", "k in column} if not asgrid: return datas # building", "does not have 'geometry' column. It is required\") self._derived_properties[\"geodataframe\"] =", "self.set_grid(grid_in, \"in\") if grid_out is not None: self.set_grid(grid_out, \"out\") #", "[[....],[...]], [[....],[...]], ... ] for triangles ```python def get_2dgauss(x, mu=[4,4],", "\"geometry\" not in geodataframe.columns: raise TypeError(\"The given geodataframe does not", "pixels and boolean mask \"\"\" from shapely import vectorized flagin", "Pixels define the position up on which the geometries are", "self._properties[\"pixels\"] @property def npixels(self): \"\"\" \"\"\" return len(self.pixels) @property def", "======================= # class GridProjector( BaseObject ): \"\"\" \"\"\" PROPERTIES =", "coordinates are in pixels) Parameters ---------- wcs_: [astropy.wcs.WCS] The world", "stored as 'data' in the grid's dataframe \"\"\" this =", "def set_from(cls, datainput): \"\"\" Creates a new Grid objects from", "Classes # # # # ======================= # class GridProjector( BaseObject", "the given shapely polygon. Parameters ---------- polygon: [shapely.geometry] reference polygon", "geopandas.GeoDataFrame({'geometry': dataseries, 'id':self.indexes, 'x':x,'y':y}) def add_data(self, data, name, indexes=None, inplace=True):", "return datas # building and setting the new grid gout", "set_vertices ; if 2-shaped, this calls set_pixels. Returns ------- Grid", "vertices: def get_verts(poly_): return np.stack(poly_.exterior.xy).T[:-1] vertices = geodataframe[\"geometry\"].apply(get_verts).values self.set_vertices(vertices, update=False)", "should either be 'in' our 'out'\") self._properties[\"grid%s\"%which] = grid self._derived_properties[\"gridinterest\"]", "not None and self.gridout is not None: # # Most", "this raise TypeError(\"cannot parse the format of the given input\")", "if len(np.shape( datainput) ) == 3: # vertices this.set_vertices(datainput) elif", "shift_origin is not None: # not += because conflict between", "= np.asarray([np.mean(v_, axis=0) for v_ in vertices]) self.set_pixels(pixels, None, **kwargs)", "try: pixels = np.mean(vertices, axis=1) except: # Means vertices have", "------- Void \"\"\" if self.pixels is not None and len(indexes)", "Let's get the triangles trs = np.stack(self.triangulation) shape_trs = np.shape(trs)", "Parameters ---------- othergrid: [Grid] New grid where data should be", "gridinterest, because gridin and/or gridout is/are None\") # -------------- #", "# Properties # # =================== # @property def pixels(self): \"\"\"", "geodataframe, overwrite=False): \"\"\" \"\"\" if not overwrite and (self.pixels is", "the pixels. Pixels define the position up on which the", "axis=0) # flatten_verts_wcs = np.asarray(wcs_.all_pix2world(flatten_verts[:,0], flatten_verts[:,1], 0, **kwargs)).T # verts_wcs", "the shape of the given datainput\") return this raise TypeError(\"cannot", "not None: this.set_indexes(indexes) return this @classmethod def set_from(cls, datainput): \"\"\"", "def _project_data_(self, data, use=\"sum\"): \"\"\" \"\"\" self.gridinterest[\"_tmp\"] = data[ self.gridin.geodataframe.loc[", "if type(datainput) == geopandas.geodataframe.GeoDataFrame: this.set_geodataframe(datainput) return this if type(datainput) ==", "column '%s'\"%data) return self.gridin.geodataframe[data].values elif type(data) == pandas.Series: return data.values", "PROPERTIES = [\"pixels\", \"shape\"] SIDE_PROPERTIES = [\"indexes\"] DERIVED_PROPERTIES = [\"vertices\",\"geodataframe\",", "Triangulation of the vertices. Based on Delaunay tesselation, see shapely.ops.triangulate", "column is None or column in [\"*\",\"all\"]: column = [k", "to the pixels. This should have the length equal to", "[invert=True] Returns ------- list of pixels and boolean mask \"\"\"", "the format of the given input\") # --------- # #", "self._measure_gridinterest_() return self._derived_properties[\"gridinterest\"] class Grid( BaseObject ): PROPERTIES = [\"pixels\",", "shape(self): \"\"\" \"\"\" if self._properties[\"shape\"] is None: self._properties[\"shape\"] = UNIT_SQUARE", "\"\"\" verts = self.vertices verts_shape = np.shape(verts) flatten_verts = np.concatenate(verts,", "deriving triangulation.\") self.derive_triangulation() # Let's get the triangles trs =", "or dict (see asgrid) \"\"\" gproj = GridProjector(self, othergrid) if", "# def set_indexes(self, indexes, update=True): \"\"\" provide the indexes associated", "# =================== # # --------- # # SETTER # #", "data, name, indexes=None, inplace=True): \"\"\" \"\"\" if indexes is None:", "indexes, vertices = list(vertices.keys()), list(vertices.values()) this.set_vertices(vertices) if indexes is not", "dataseries, 'id':self.indexes, 'x':x,'y':y}) def add_data(self, data, name, indexes=None, inplace=True): \"\"\"", "# # Project # # --------- # def project_to(self, othergrid,", "the indexes associated to each pixels Parameters ---------- indexes: [ndarray]", "UPDATE # # --------- # def _update_geodataframe_(self): \"\"\" \"\"\" dataseries", "on Delaunay tesselation, see shapely.ops.triangulate \"\"\" if self._derived_properties[\"triangulation\"] is None:", "provide the vertices Parameters: ----------- vertices: [list of array or", "gridin(self): \"\"\" \"\"\" return self._properties[\"gridin\"] @property def gridout(self): \"\"\" \"\"\"", "on which the geometries are defined. NB: vertices = pixels+shape", "Grid(pixels2_flat, UNIT_SQUARE) # ======================= # # # # Classes #", "if np.shape(pixels)[-1] != 2: raise ValueError(\"pixels must be [N,2] arrays\")", "gridinterest(self): \"\"\" \"\"\" if self._derived_properties[\"gridinterest\"] is None: self._measure_gridinterest_() return self._derived_properties[\"gridinterest\"]", "provide the pixels. Pixels define the position up on which", "x = [ [[....],[...]], [[....],[...]], ... ] for triangles ```python", "in trs]) return np.sum(val, axis=1) def derive_triangulation(self, fast_unique=True): \"\"\" \"\"\"", "return self._properties[\"gridout\"] @property def gridinterest(self): \"\"\" \"\"\" if self._derived_properties[\"gridinterest\"] is", "None: self.set_grid(grid_out, \"out\") # =================== # # Methods # #", "indexes associated to the pixels. This should have the length", "data in the given grid Parameters ---------- othergrid: [Grid] New", "val = np.asarray([quadpy.triangle.strang_fix_cowper_09().integrate(func,np.stack(t_, axis=-2)) for t_ in trs]) return np.sum(val,", "Setting the pixels if np.shape(pixels)[-1] != 2: raise ValueError(\"pixels must", "trs = np.stack(self.triangulation) shape_trs = np.shape(trs) if len(shape_trs)==4 and vectorized:", "array (see asgrid) \"\"\" verts = self.vertices verts_shape = np.shape(verts)", "should be projected to column: [str/None/list of] -optional- Which data", "\"\"\" \"\"\" if self._derived_properties[\"vertices\"] is None and (self.pixels is not", "vertices have different size. self._derived_properties[\"vertices\"] = vertices pixels = np.asarray([np.mean(v_,", "invert: [bool] -optional- Get the pixel inside the polygon [invert=False]", "this = cls() if type(datainput) == geopandas.geodataframe.GeoDataFrame: this.set_geodataframe(datainput) return this", "axis=1) def derive_triangulation(self, fast_unique=True): \"\"\" \"\"\" def triangulate(geom): \"\"\" Return", "as the number of pixels\") self._side_properties[\"indexes\"] = indexes if update:", "data will be stored as 'data' in the grid's dataframe", "\"\"\" def triangulate(geom): \"\"\" Return triangulate format that quadpy likes", "GridProjector( BaseObject ): \"\"\" \"\"\" PROPERTIES = [\"gridin\", \"gridout\"] DERIVED_PROPERTIES", "are 'geometry', 'id', 'x', 'y') asgrid: [bool] -optional- Should this", "--------- # # PLOTTER # # --------- # def show(self,", "None: this.set_indexes(indexes) return this @classmethod def set_from(cls, datainput): \"\"\" Creates", "np.arange( len(geodataframe) ) # - get the vertices: def get_verts(poly_):", "as 'data' in the grid's dataframe \"\"\" this = get_simple_grid(*np.shape(stamp),", "self._derived_properties[\"gridinterest\"] = None def _measure_gridinterest_(self): \"\"\" \"\"\" # -- internal", "return projected_data_array def _project_data_(self, data, use=\"sum\"): \"\"\" \"\"\" self.gridinterest[\"_tmp\"] =", "gridin column (pandas) - pandas.Serie: serie that will be matched", "vertices = pixels+shape \"\"\" # Setting the pixels if np.shape(pixels)[-1]", "same lenth as pixels\") self._properties[\"shape\"] = np.asarray(shape) else: raise ValueError(\"Cannot", "othergrid: [Grid] New grid where data should be projected to", "self._properties[\"shape\"] # -- Side @property def indexes(self): \"\"\" \"\"\" if", "indexes if update: self._update_geodataframe_() def set_pixels(self, pixels, shape=None, update=True): \"\"\"", "\"id\" not in geodataframe.columns: self.geodataframe[\"id\"] = self.indexes if self.pixels is", "Means vertices have different size. self._derived_properties[\"vertices\"] = vertices pixels =", "N is the number of pixel and M the number", "shapely polygon. Parameters ---------- polygon: [shapely.geometry] reference polygon invert: [bool]", "if indexes is not None: this.set_indexes(indexes) return this @classmethod def", "othergrid) if column is None or column in [\"*\",\"all\"]: column", "# # # # ======================= # class GridProjector( BaseObject ):", "made using quadpy. Examples: # Remark the np.stack(x, axis=-1). #", "? if self._derived_properties[\"triangulation\"] is None: warnings.warn(\"triangles not defined: deriving triangulation.\")", "# SETTER # # --------- # def set_indexes(self, indexes, update=True):", "'geometry' column. It is required\") self._derived_properties[\"geodataframe\"] = geodataframe if \"id\"", "\"\"\" if grid_in is not None: self.set_grid(grid_in, \"in\") if grid_out", "that should be projected in gridout. could be: - ndarray:", "is going to send # x = [ [[....],[...]], [[....],[...]],", "NB: vertices = pixels+shape \"\"\" # Setting the pixels if", "pixels2_flat = pixels2_flat+ shift_origin return Grid(pixels2_flat, UNIT_SQUARE) # ======================= #", "you may want to provide indexes - dictionary: {id_1:vert_1,id_2: vert_2,", "not asgrid: return datas # building and setting the new", "invert: flagin = ~flagin return self.pixels[flagin], flagin # --------- #", "len(self.pixels) @property def shape(self): \"\"\" \"\"\" if self._properties[\"shape\"] is None:", "for t in triangles]) if not self.is_shape_unique or not fast_unique:", "data associated to gridin that should be projected in gridout.", "not None: # not += because conflict between int and", "grid entries. Could have two format: - list of array:", "cls() if type(datainput) == geopandas.geodataframe.GeoDataFrame: this.set_geodataframe(datainput) return this if type(datainput)", "the pixels. This should have the length equal to th", "new Grid (actually same object as othergrid) or a dict", "self.gridin.geodataframe.columns: raise ValueError(\"Unknown gridin column '%s'\"%data) return self.gridin.geodataframe[data].values elif type(data)", "of the vertices. -> if None, then indexes = np.arange(len(vertices))", "[bool] -optional- Should this return a new Grid (actually same", "self.geodataframe.join(s_) self._derived_properties[\"geodataframe\"] = self.geodataframe.join(s_) # --------- # # GETTER #", "_project_data_(self, data, use=\"sum\"): \"\"\" \"\"\" self.gridinterest[\"_tmp\"] = data[ self.gridin.geodataframe.loc[ self.gridinterest[\"id_1\"]].index", "grid_in is not None: self.set_grid(grid_in, \"in\") if grid_out is not", "\"triangulation\"] def __init__(self, pixels=None, shape=UNIT_SQUARE, indexes=None): \"\"\" \"\"\" if pixels", "len(np.shape(self.shape))==2 @property def geodataframe(self): \"\"\" \"\"\" if self._derived_properties[\"geodataframe\"] is None:", "elif len(data) != len(self.gridin.geodataframe): raise ValueError(\"data given as ndarray but", "warnings import numpy as np UNIT_SQUARE = np.asarray([[0,0],[0,1],[1,1],[1,0]])-0.5 from propobject", "None: # not += because conflict between int and float", "new grid gout = othergrid.__class__.set_from(othergrid.geodataframe) for k in column: gout.add_data(datas[k],k)", "2-shaped, this calls set_pixels. Returns ------- Grid \"\"\" this =", "the polyname using triangle integration. -> dependency: the integration is", "datainput) ) == 3: # pixels this.set_pixels(datainput) else: raise TypeError(\"cannot", "self.pixels[flagin], flagin # --------- # # Project # # ---------", "def indexes(self): \"\"\" \"\"\" if self._side_properties[\"indexes\"] is None: self._side_properties[\"indexes\"] =", "triangles trs = np.stack(self.triangulation) shape_trs = np.shape(trs) if len(shape_trs)==4 and", "= [\"pixels\", \"shape\"] SIDE_PROPERTIES = [\"indexes\"] DERIVED_PROPERTIES = [\"vertices\",\"geodataframe\", \"triangulation\"]", "Methods # # =================== # # --------- # # SETTER", "ax.imshow(stamps) data will be stored as 'data' in the grid's", "triangulation. \"\"\" return Grid.set_from( np.concatenate(self.triangulation, axis=0) ) def get_pixels_in(self, polygon,", "self._derived_properties[\"geodataframe\"] = geodataframe if \"id\" not in geodataframe.columns: self.geodataframe[\"id\"] =", "triangles ```python def get_2dgauss(x, mu=[4,4], cov=[[1,0],[0,2]]): \"\"\" \"\"\" return stats.multivariate_normal.pdf(np.stack(x,", "# # --------- # def set_indexes(self, indexes, update=True): \"\"\" provide", "# # =================== # @property def gridin(self): \"\"\" \"\"\" return", "function inside the polyname using triangle integration. -> dependency: the", "Which data should be projected ? If None or '*'", "# # # # Classes # # # # =======================", "None or column in [\"*\",\"all\"]: column = [k for k", "of the given datainput\") return this raise TypeError(\"cannot parse the", "# PLOTTER # # --------- # def show(self, column=None, ax=None,", "np.stack(np.concatenate(trs, axis=0), axis=-2) val = quadpy.triangle.strang_fix_cowper_09().integrate(func,tr_flat).reshape(shape_trs[:2]) else: val = np.asarray([quadpy.triangle.strang_fix_cowper_09().integrate(func,np.stack(t_,", "must be [M,2] or [N,M,2] when N is the number", "np.shape(verts) flatten_verts = np.concatenate(verts, axis=0) # flatten_verts_wcs = np.asarray(wcs_.all_pix2world(flatten_verts[:,0], flatten_verts[:,1],", "'%s'\"%data) return self.gridin.geodataframe[data].values elif type(data) == pandas.Series: return data.values elif", "\"\"\" \"\"\" def triangulate(geom): \"\"\" Return triangulate format that quadpy", "from_vertices(cls, vertices, indexes=None): \"\"\" directly provide the vertices Parameters: -----------", "of vertices (in degree) **kwargs goes to wcs_.all_pix2world Returns -------", "are not sure] Returns ------- Void \"\"\" if self.pixels is", "None): raise ValueError(\"Pixels and shape already defined. set the overwrite", "overwrite option to true, to update geodataframe\") if \"geometry\" not", "? If None or '*' all the non-structural columns will", "ImportError(\"Integration is made using quadpy. pip install quadpy\") # Is", "are 2d array, something you could to ax.imshow(stamps) data will", "self._side_properties[\"indexes\"] is None: self._side_properties[\"indexes\"] = np.arange(self.npixels) return self._side_properties[\"indexes\"] # --", "geodataframe(self): \"\"\" \"\"\" if self._derived_properties[\"geodataframe\"] is None: self._update_geodataframe_() return self._derived_properties[\"geodataframe\"]", "... ] for triangles ```python def get_2dgauss(x, mu=[4,4], cov=[[1,0],[0,2]]): \"\"\"", "type(datainput) == geopandas.geodataframe.GeoDataFrame: this.set_geodataframe(datainput) return this if type(datainput) == np.ndarray:", "def get_triangulation_grid(self): \"\"\" Returns a grid of triangulation. \"\"\" return", "'x', 'y') asgrid: [bool] -optional- Should this return a new", "``` \"\"\" try: import quadpy except ImportError: raise ImportError(\"Integration is", "in gridout. could be: - ndarray: must have the same", "# # # # Functions # # # # =======================", "index=indexes) if not inplace: return self.geodataframe.join(s_) self._derived_properties[\"geodataframe\"] = self.geodataframe.join(s_) #", "self._update_geodataframe_() def set_pixels(self, pixels, shape=None, update=True): \"\"\" provide the pixels.", "# Methods # # =================== # # --------- # #", "self.shape is not None): raise ValueError(\"Pixels and shape already defined.", "-optional- should the geodataframe be updated ? [use True if", "# -- internal -- # def localdef_get_area(l): return l.geometry.area/self.gridin.geodataframe.iloc[l.id_1].geometry.area #", "None: self.set_pixelshapes(shape, update=False) if update: self._update_geodataframe_() def set_pixelshapes(self, shape, update=True):", "= np.asarray(shape) else: raise ValueError(\"Cannot parse the given shape, must", "defined. set the overwrite option to true, to update geodataframe\")", "\"\"\" \"\"\" if grid_in is not None: self.set_grid(grid_in, \"in\") if", "indexes - dictionary: {id_1:vert_1,id_2: vert_2, ...} if a dictionary is", "vertices(self): \"\"\" \"\"\" if self._derived_properties[\"vertices\"] is None and (self.pixels is", "set_pixelshapes(self, shape, update=True): \"\"\" \"\"\" # Setting the pixel shape.s", "asgrid: return verts_wcs g_wcs = Grid.set_from(verts_wcs) g_wcs.geodataframe[\"x_pix\"],g_wcs.geodataframe[\"y_pix\"] = self.pixels.T return", "(actually same object as othergrid) or a dict [asgrid=False]? Returns", "Parameters: ----------- vertices: [list of array or dictionary] The vertices", "likely there is a faster method if is_shape_unique # self._derived_properties[\"gridinterest\"]", "be matched with gridin Returns ------- ndarray \"\"\" if type(data)", "indexes=None): \"\"\" \"\"\" if pixels is not None: self.set_pixels(pixels,shape=shape) if", "Project # # --------- # def project_to(self, othergrid, column=\"*\", asgrid=True,", "the geometries are defined. NB: vertices = pixels+shape \"\"\" #", "facecolor=\"None\", **kwargs): \"\"\" \"\"\" if column is not None: facecolor=None", "into it (assuming grid's vertices coordinates are in pixels) Parameters", "0,xbounds[0] else: xmin,xmax = xbounds ybounds = np.atleast_1d(ybounds) if len(ybounds)==1:", "set the overwrite option to true, to update vertices\") try:", "\"\"\" return self._properties[\"pixels\"] @property def npixels(self): \"\"\" \"\"\" return len(self.pixels)", "np.stack(self.triangulation) shape_trs = np.shape(trs) if len(shape_trs)==4 and vectorized: # All", "number of indexes as the number of pixels\") self._side_properties[\"indexes\"] =", "string or pandas.Serie] data associated to gridin that should be", "a new geodataframe and returns it. \"\"\" import geopandas return", "# # --------- # # SETTER # # --------- #", "for triangles ```python def get_2dgauss(x, mu=[4,4], cov=[[1,0],[0,2]]): \"\"\" \"\"\" return", "= self.gridinterest.apply(localdef_get_area, axis=1) else: warnings.warn(\"Cannot measure gridinterest, because gridin and/or", "dataseries = self.get_geoseries() x,y = self.pixels.T self._derived_properties[\"geodataframe\"] = \\ geopandas.GeoDataFrame({'geometry':", "triangulate(geom): \"\"\" Return triangulate format that quadpy likes \"\"\" from", "= geodataframe[\"geometry\"].apply(get_verts).values self.set_vertices(vertices, update=False) # don't update the geodataframe #", "self.is_shape_unique or not fast_unique: self._derived_properties[\"triangulation\"] = self.geodataframe[\"geometry\"].apply(triangulate) else: self._derived_properties[\"triangulation\"] =", "np.zeros( len(self.gridout.geodataframe) ) projected_data_array[projected_data.index.values] = projected_data.values return projected_data_array def _project_data_(self,", "def evaluate(self, func, vectorized=True): \"\"\" Evaluate the given function throughout", "- pixels[:,None] shape_unique = np.unique(shape, axis=0) if len(shape_unique)==1: shape =", "def show(self, column=None, ax=None, edgecolor=\"0.7\", facecolor=\"None\", **kwargs): \"\"\" \"\"\" if", "# Setting the pixels if np.shape(pixels)[-1] != 2: raise ValueError(\"pixels", "If None or '*' all the non-structural columns will be", "if len(np.shape(shape))==2: self._properties[\"shape\"] = np.asarray(shape) elif len(np.shape(shape))==3: if self.pixels is", "string: name of a gridin column (pandas) - pandas.Serie: serie", "None and self.shape is not None): self._derived_properties[\"vertices\"] = self.pixels[:,None]+self.shape return", "vectorized: # All Polygon have the same topology (same amount", "you can provide the indexes of each of the vertices.", "# # Classes # # # # ======================= # class", "Returns ------- Void \"\"\" if self.pixels is not None and", "self._update_geodataframe_() return self._derived_properties[\"geodataframe\"] @property def triangulation(self): \"\"\" Triangulation of the", "# Calcul itself projected_data = self._project_data_(self._parse_data_(data), use=use) if as_serie: return", "in self.vertices]) def get_triangulation_grid(self): \"\"\" Returns a grid of triangulation.", "an array of vertices (in degree) **kwargs goes to wcs_.all_pix2world", "return self._derived_properties[\"gridinterest\"] class Grid( BaseObject ): PROPERTIES = [\"pixels\", \"shape\"]", "-- internal -- # def localdef_get_area(l): return l.geometry.area/self.gridin.geodataframe.iloc[l.id_1].geometry.area # --------------", "and (self.pixels is not None and self.shape is not None):", "return self._properties[\"shape\"] # -- Side @property def indexes(self): \"\"\" \"\"\"", "TypeError(\"cannot parse the shape of the given datainput\") return this", "pixel is in or out the given shapely polygon. Parameters", "as othergrid) or a dict [asgrid=False]? Returns ------- Grid or", "\"gridout\"] DERIVED_PROPERTIES = [\"gridinterest\"] def __init__(self, grid_in=None, grid_out=None): \"\"\" \"\"\"", "raise ImportError(\"Integration is made using quadpy. pip install quadpy\") #", "and self.shape is not None): self._derived_properties[\"vertices\"] = self.pixels[:,None]+self.shape return self._derived_properties[\"vertices\"]", "\"\"\" \"\"\" if column is not None: facecolor=None return self.geodataframe.plot(column,", "from shapely import geometry import pandas import geopandas # =======================", "as gridin - string: name of a gridin column (pandas)", "or column in [\"*\",\"all\"]: column = [k for k in", "of pixels\") self._side_properties[\"indexes\"] = indexes if update: self._update_geodataframe_() def set_pixels(self,", "\"\"\" this = cls() if type(datainput) == geopandas.geodataframe.GeoDataFrame: this.set_geodataframe(datainput) return", "# -------------- # if self.gridin is not None and self.gridout", "= np.asarray([quadpy.triangle.strang_fix_cowper_09().integrate(func,np.stack(t_, axis=-2)) for t_ in trs]) return np.sum(val, axis=1)", "=================== # # Methods # # =================== # @classmethod def", "\"\"\" if indexes is None: indexes = self.indexes s_ =", "you provide vertices as a list of vertices, you can", "= projected_data.values return projected_data_array def _project_data_(self, data, use=\"sum\"): \"\"\" \"\"\"", "shapely import ops triangles = ops.triangulate(geom) return np.stack([np.asarray(t.exterior.coords.xy).T[:-1] for t", "0, **kwargs)).T # verts_wcs = flatten_verts_wcs.reshape(verts_shape) if not asgrid: return", "are in pixels) Parameters ---------- wcs_: [astropy.wcs.WCS] The world coordinate", "g_wcs = Grid.set_from(verts_wcs) g_wcs.geodataframe[\"x_pix\"],g_wcs.geodataframe[\"y_pix\"] = self.pixels.T return g_wcs def evaluate(self,", "that quadpy likes \"\"\" from shapely import ops triangles =", "if not asgrid: return verts_wcs g_wcs = Grid.set_from(verts_wcs) g_wcs.geodataframe[\"x_pix\"],g_wcs.geodataframe[\"y_pix\"] =", "Delaunay tesselation, see shapely.ops.triangulate \"\"\" if self._derived_properties[\"triangulation\"] is None: self.derive_triangulation()", "is not None and self.gridout is not None: # #", "return self.geodataframe.join(s_) self._derived_properties[\"geodataframe\"] = self.geodataframe.join(s_) # --------- # # GETTER", "python # import warnings import numpy as np UNIT_SQUARE =", "\"\"\" project data in the given grid Parameters ---------- othergrid:", "grid. This evulation is using polynome triangulation to integrate the", "have the same topology (same amount of vertices) tr_flat =", "np.asarray(pixels) if shape is not None: self.set_pixelshapes(shape, update=False) if update:", "vertices]) self.set_pixels(pixels, None, **kwargs) return self._derived_properties[\"vertices\"] = np.asarray(vertices) shape =", "import geopandas # ======================= # # # # Functions #", "xbounds ybounds = np.atleast_1d(ybounds) if len(ybounds)==1: ymin,ymax = 0,ybounds[0] else:", "def from_stamps(cls, stamp, origin=[0,0]): \"\"\" stamps are 2d array, something", "# # GETTER # # --------- # def get_geoseries(self): \"\"\"", "the vertices. indexes: [list or None] -optional- (Ignored if vertices", "is None: indexes = self.indexes s_ = pandas.Series(data, name=name, index=indexes)", "\"\"\" \"\"\" self.gridinterest[\"_tmp\"] = data[ self.gridin.geodataframe.loc[ self.gridinterest[\"id_1\"]].index ] * self.gridinterest[\"area\"]", "as pixels\") self._properties[\"shape\"] = np.asarray(shape) else: raise ValueError(\"Cannot parse the", "that will be matched with gridin Returns ------- ndarray \"\"\"", "or [N,M,2] when N is the number of pixel and", "set_pixels. Returns ------- Grid \"\"\" this = cls() if type(datainput)", "where data should be projected to column: [str/None/list of] -optional-", "return len(self.pixels) @property def shape(self): \"\"\" \"\"\" if self._properties[\"shape\"] is", "Could have two format: - list of array: [[vert_1],[vert_2],....], then", "conflict between int and float array pixels2_flat = pixels2_flat+ shift_origin", "in self.gridin.geodataframe.columns: raise ValueError(\"Unknown gridin column '%s'\"%data) return self.gridin.geodataframe[data].values elif", "M the number of vertices\") if update: self._update_geodataframe_() def set_vertices(self,", "len(xbounds)==1: xmin,xmax = 0,xbounds[0] else: xmin,xmax = xbounds ybounds =", "indexes=None): \"\"\" directly provide the vertices Parameters: ----------- vertices: [list", "[asgrid=False]? Returns ------- Grid or dict (see asgrid) \"\"\" gproj", "Based on Delaunay tesselation, see shapely.ops.triangulate \"\"\" if self._derived_properties[\"triangulation\"] is", "vertices Parameters: ----------- vertices: [list of array or dictionary] The", "@property def is_shape_unique(self): \"\"\" \"\"\" return len(np.shape(self.shape))==2 @property def geodataframe(self):", "current grid into it (assuming grid's vertices coordinates are in", "# # =================== # # --------- # # SETTER #", "# Let's get the triangles trs = np.stack(self.triangulation) shape_trs =", "\"\"\" \"\"\" xbounds = np.atleast_1d(xbounds) if len(xbounds)==1: xmin,xmax = 0,xbounds[0]", "not have 'geometry' column. It is required\") self._derived_properties[\"geodataframe\"] = geodataframe", "new Grid objects from the given input data: Parameters ----------", "elif type(data) == pandas.Series: return data.values elif len(data) != len(self.gridin.geodataframe):", "-------------- # # Measurement # # -------------- # def project_data(self,", "can provide the indexes of each of the vertices. ->", "in ['geometry', 'id', 'x', 'y']] datas = {k:gproj.project_data(k, use=use) for", "it (assuming grid's vertices coordinates are in pixels) Parameters ----------", "number of pixel and M the number of vertices\") if", "- geodataframe (and this calls self.set_geodataframe) - geoSeries - ndarray:", "out the given shapely polygon. Parameters ---------- polygon: [shapely.geometry] reference", "\\ geopandas.GeoDataFrame({'geometry': dataseries, 'id':self.indexes, 'x':x,'y':y}) def add_data(self, data, name, indexes=None,", "np.atleast_1d(ybounds) if len(ybounds)==1: ymin,ymax = 0,ybounds[0] else: ymin,ymax = ybounds", "--------- # def _update_geodataframe_(self): \"\"\" \"\"\" dataseries = self.get_geoseries() x,y", "--------- # # GETTER # # --------- # def get_geoseries(self):", "the geodataframe # --------- # # UPDATE # # ---------", "# # PLOTTER # # --------- # def show(self, column=None,", "; if 2-shaped, this calls set_pixels. Returns ------- Grid \"\"\"", "should be projected in gridout. could be: - ndarray: must", "Triangulation made ? if self._derived_properties[\"triangulation\"] is None: warnings.warn(\"triangles not defined:", "will be matched with gridin \"\"\" # Calcul itself projected_data", "get_pixels_in(self, polygon, invert=False): \"\"\" checks if the centroid of the", "if invert: flagin = ~flagin return self.pixels[flagin], flagin # ---------", "geodataframe.columns: raise TypeError(\"The given geodataframe does not have 'geometry' column.", "or '*' all the non-structural columns will be (structural columns", "def _measure_gridinterest_(self): \"\"\" \"\"\" # -- internal -- # def", "is_shape_unique # self._derived_properties[\"gridinterest\"] = geopandas.overlay(self.gridin.geodataframe, self.gridout.geodataframe, how='intersection') self.gridinterest[\"area\"] = self.gridinterest.apply(localdef_get_area,", "self._properties[\"gridout\"] @property def gridinterest(self): \"\"\" \"\"\" if self._derived_properties[\"gridinterest\"] is None:", "th number of pixels (if any). update: [bool] -optional- should", "-optional- Get the pixel inside the polygon [invert=False] or outsite", "and setting the new grid gout = othergrid.__class__.set_from(othergrid.geodataframe) for k", "vectorized flagin = vectorized.contains(polygon, *self.pixels.T) if invert: flagin = ~flagin", "---------- othergrid: [Grid] New grid where data should be projected", "then indexes = np.arange(len(vertices)) Returns ------- Grid \"\"\" this =", "if column is None or column in [\"*\",\"all\"]: column =", "\"\"\" this = cls() if type(vertices) is dict: indexes, vertices", "self._project_data_(self._parse_data_(data), use=use) if as_serie: return projected_data projected_data_array = np.zeros( len(self.gridout.geodataframe)", "Grid \"\"\" this = cls() if type(datainput) == geopandas.geodataframe.GeoDataFrame: this.set_geodataframe(datainput)", "(in degree) **kwargs goes to wcs_.all_pix2world Returns ------- Grid or", "add_data(self, data, name, indexes=None, inplace=True): \"\"\" \"\"\" if indexes is", "= np.atleast_1d(ybounds) if len(ybounds)==1: ymin,ymax = 0,ybounds[0] else: ymin,ymax =", "**kwargs): \"\"\" \"\"\" if column is not None: facecolor=None return", "checks if the centroid of the pixel is in or", "be updated ? [use True if you are not sure]", "not None: # # Most likely there is a faster", "entries. Could have two format: - list of array: [[vert_1],[vert_2],....],", "given shapely polygon. Parameters ---------- polygon: [shapely.geometry] reference polygon invert:", "the position up on which the geometries are defined. NB:", "vertices. Based on Delaunay tesselation, see shapely.ops.triangulate \"\"\" if self._derived_properties[\"triangulation\"]", "set_indexes(self, indexes, update=True): \"\"\" provide the indexes associated to each", "geopandas return geopandas.GeoSeries([geometry.Polygon(v) for v in self.vertices]) def get_triangulation_grid(self): \"\"\"", "polynome triangulation to integrate the given function inside the polyname", "if the centroid of the pixel is in or out", "match\") return data # =================== # # Properties # #", "ymin,ymax = ybounds pixels = np.mgrid[xmin:xmax,ymin:ymax] pixels2_flat = np.concatenate(pixels.T, axis=0)", "it. \"\"\" import geopandas return geopandas.GeoSeries([geometry.Polygon(v) for v in self.vertices])", "np.asarray([quadpy.triangle.strang_fix_cowper_09().integrate(func,np.stack(t_, axis=-2)) for t_ in trs]) return np.sum(val, axis=1) def", "import geometry import pandas import geopandas # ======================= # #", "= pandas.Series(data, name=name, index=indexes) if not inplace: return self.geodataframe.join(s_) self._derived_properties[\"geodataframe\"]", "except: # Means vertices have different size. self._derived_properties[\"vertices\"] = vertices", "np.asarray(wcs_.all_pix2world(flatten_verts[:,0], flatten_verts[:,1], 0, **kwargs)).T # verts_wcs = flatten_verts_wcs.reshape(verts_shape) if not", "SETTER # # --------- # def set_grid(self, grid, which=\"in\"): \"\"\"", "'x', 'y']] datas = {k:gproj.project_data(k, use=use) for k in column}", "should the geodataframe be updated ? [use True if you", "gridin that should be projected in gridout. could be: -", "return verts_wcs g_wcs = Grid.set_from(verts_wcs) g_wcs.geodataframe[\"x_pix\"],g_wcs.geodataframe[\"y_pix\"] = self.pixels.T return g_wcs", "set_vertices(self, vertices, overwrite=False, **kwargs): \"\"\" \"\"\" if not overwrite and", "axis=0) ) def get_pixels_in(self, polygon, invert=False): \"\"\" checks if the", "Get the pixel inside the polygon [invert=False] or outsite [invert=True]", "shape = shape_unique[0] self.set_pixels(pixels, shape, **kwargs) def set_geodataframe(self, geodataframe, overwrite=False):", "self.gridin is not None and self.gridout is not None: #", "self.gridinterest[\"area\"] = self.gridinterest.apply(localdef_get_area, axis=1) else: warnings.warn(\"Cannot measure gridinterest, because gridin", "vertices. indexes: [list or None] -optional- (Ignored if vertices is", "or outsite [invert=True] Returns ------- list of pixels and boolean", "if 3-shaped, this calls set_vertices ; if 2-shaped, this calls", "to each pixels Parameters ---------- indexes: [ndarray] indexes associated to", "will be matched with gridin Returns ------- ndarray \"\"\" if", "np.shape(pixels)[-1] != 2: raise ValueError(\"pixels must be [N,2] arrays\") self._properties[\"pixels\"]", "do not match\") return data # =================== # # Properties", "projected_data_array = np.zeros( len(self.gridout.geodataframe) ) projected_data_array[projected_data.index.values] = projected_data.values return projected_data_array", "provide the indexes of each of the vertices. -> if", "shape of the given datainput\") return this raise TypeError(\"cannot parse", "grid_out is not None: self.set_grid(grid_out, \"out\") # =================== # #", "Parameters ---------- wcs_: [astropy.wcs.WCS] The world coordinate solution asgrid: [bool]", "None, then indexes = np.arange(len(vertices)) Returns ------- Grid \"\"\" this", "coordinate solution asgrid: [bool] -optional- Should this return a load", "0,ybounds[0] else: ymin,ymax = ybounds pixels = np.mgrid[xmin:xmax,ymin:ymax] pixels2_flat =", "# Classes # # # # ======================= # class GridProjector(", "= data[ self.gridin.geodataframe.loc[ self.gridinterest[\"id_1\"]].index ] * self.gridinterest[\"area\"] return getattr(self.gridinterest.groupby(\"id_2\")[\"_tmp\"],use)() def", "# -- Side @property def indexes(self): \"\"\" \"\"\" if self._side_properties[\"indexes\"]", "this will project the current grid into it (assuming grid's", "gproj = GridProjector(self, othergrid) if column is None or column", "gridin - string: name of a gridin column (pandas) -", "(pandas) - pandas.Serie: serie that will be matched with gridin", "are defined. NB: vertices = pixels+shape \"\"\" # Setting the", "/usr/bin/env python # import warnings import numpy as np UNIT_SQUARE", "any). update: [bool] -optional- should the geodataframe be updated ?", "vertices: [list of array or dictionary] The vertices of all", "return this raise TypeError(\"cannot parse the format of the given", "in triangles]) if not self.is_shape_unique or not fast_unique: self._derived_properties[\"triangulation\"] =", "= np.atleast_1d(xbounds) if len(xbounds)==1: xmin,xmax = 0,xbounds[0] else: xmin,xmax =", "= np.asarray(pixels) if shape is not None: self.set_pixelshapes(shape, update=False) if", "= shape_unique[0] self.set_pixels(pixels, shape, **kwargs) def set_geodataframe(self, geodataframe, overwrite=False): \"\"\"", "Returns ------- Grid or array (see asgrid) \"\"\" verts =", "k not in ['geometry', 'id', 'x', 'y']] datas = {k:gproj.project_data(k,", "return self.pixels[flagin], flagin # --------- # # Project # #", "to true, to update geodataframe\") if \"geometry\" not in geodataframe.columns:", "import quadpy except ImportError: raise ImportError(\"Integration is made using quadpy.", "len(self.gridout.geodataframe) ) projected_data_array[projected_data.index.values] = projected_data.values return projected_data_array def _project_data_(self, data,", "------- ndarray \"\"\" if type(data) == str: if data not", "datainput): \"\"\" Creates a new Grid objects from the given", "@property def npixels(self): \"\"\" \"\"\" return len(self.pixels) @property def shape(self):", "want to provide indexes - dictionary: {id_1:vert_1,id_2: vert_2, ...} if", "not None: self.set_pixels(pixels,shape=shape) if indexes is not None: self.set_indexes(indexes) #", "self._properties[\"shape\"] = UNIT_SQUARE return self._properties[\"shape\"] # -- Side @property def", "type(data) == str: if data not in self.gridin.geodataframe.columns: raise ValueError(\"Unknown", "or an array of vertices (in degree) **kwargs goes to", "#! /usr/bin/env python # import warnings import numpy as np", "def gridin(self): \"\"\" \"\"\" return self._properties[\"gridin\"] @property def gridout(self): \"\"\"", "geopandas # ======================= # # # # Functions # #", "gridin Returns ------- ndarray \"\"\" if type(data) == str: if", "\"\"\" \"\"\" return self._properties[\"gridout\"] @property def gridinterest(self): \"\"\" \"\"\" if", "np.concatenate(pixels.T, axis=0) if shift_origin is not None: # not +=", "else: warnings.warn(\"Cannot measure gridinterest, because gridin and/or gridout is/are None\")", "is not None and self.shape is not None): self._derived_properties[\"vertices\"] =", "quadpy\") # Is Triangulation made ? if self._derived_properties[\"triangulation\"] is None:", "self.set_geodataframe) - geoSeries - ndarray: if 3-shaped, this calls set_vertices", "given geodataframe does not have 'geometry' column. It is required\")", "pixels, shape=None, update=True): \"\"\" provide the pixels. Pixels define the", "polygon invert: [bool] -optional- Get the pixel inside the polygon", "or string or pandas.Serie] data associated to gridin that should", "data, as_serie=True, use=\"sum\"): \"\"\" Use gridinteresect Parameters ---------- data: [ndarray", "for k in column: gout.add_data(datas[k],k) return gout def project_to_wcs(self, wcs_,", "= vertices pixels = np.asarray([np.mean(v_, axis=0) for v_ in vertices])", "- list of array: [[vert_1],[vert_2],....], then you may want to", "vectorized=True): \"\"\" Evaluate the given function throughout the grid. This", "must be unique or have the same lenth as pixels\")", "provide vertices as a list of vertices, you can provide", "to send # x = [ [[....],[...]], [[....],[...]], ... ]", "# --------- # def project_to(self, othergrid, column=\"*\", asgrid=True, use=\"sum\"): \"\"\"", "# --------- # def set_grid(self, grid, which=\"in\"): \"\"\" \"\"\" if", "world coordinate solution asgrid: [bool] -optional- Should this return a", "# # Methods # # =================== # @classmethod def from_stamps(cls,", "'y']] datas = {k:gproj.project_data(k, use=use) for k in column} if", "# # =================== # @classmethod def from_stamps(cls, stamp, origin=[0,0]): \"\"\"", "array or dictionary] The vertices of all the grid entries.", "indexes: [ndarray] indexes associated to the pixels. This should have", "polygon, invert=False): \"\"\" checks if the centroid of the pixel", "2: raise ValueError(\"pixels must be [N,2] arrays\") self._properties[\"pixels\"] = np.asarray(pixels)", "None: self._measure_gridinterest_() return self._derived_properties[\"gridinterest\"] class Grid( BaseObject ): PROPERTIES =", "= self.geodataframe[\"geometry\"].apply(triangulate) else: self._derived_properties[\"triangulation\"] = self.pixels[:,None,None] + triangulate(geometry.Polygon(self.shape)) # ---------", "(see asgrid) \"\"\" verts = self.vertices verts_shape = np.shape(verts) flatten_verts", "self.derive_triangulation() # Let's get the triangles trs = np.stack(self.triangulation) shape_trs", "= [\"gridin\", \"gridout\"] DERIVED_PROPERTIES = [\"gridinterest\"] def __init__(self, grid_in=None, grid_out=None):", "vertices\") if update: self._update_geodataframe_() def set_vertices(self, vertices, overwrite=False, **kwargs): \"\"\"", "in [\"*\",\"all\"]: column = [k for k in self.geodataframe if", "g_wcs.geodataframe[\"x_pix\"],g_wcs.geodataframe[\"y_pix\"] = self.pixels.T return g_wcs def evaluate(self, func, vectorized=True): \"\"\"", "dictionary is provided, the indexes will be set by the", "self._update_geodataframe_() def set_pixelshapes(self, shape, update=True): \"\"\" \"\"\" # Setting the", "if self._derived_properties[\"geodataframe\"] is None: self._update_geodataframe_() return self._derived_properties[\"geodataframe\"] @property def triangulation(self):", "# import warnings import numpy as np UNIT_SQUARE = np.asarray([[0,0],[0,1],[1,1],[1,0]])-0.5", "self._update_geodataframe_() def set_vertices(self, vertices, overwrite=False, **kwargs): \"\"\" \"\"\" if not", "return this @classmethod def set_from(cls, datainput): \"\"\" Creates a new", "an astropy.wcs.WCS and this will project the current grid into", "SIDE_PROPERTIES = [\"indexes\"] DERIVED_PROPERTIES = [\"vertices\",\"geodataframe\", \"triangulation\"] def __init__(self, pixels=None,", "---------- datainput: [geopandas.geodataframe.GeoDataFrame or ndarray] this could either be a:", "BaseObject ): \"\"\" \"\"\" PROPERTIES = [\"gridin\", \"gridout\"] DERIVED_PROPERTIES =", "quadpy. pip install quadpy\") # Is Triangulation made ? if", "from_stamps(cls, stamp, origin=[0,0]): \"\"\" stamps are 2d array, something you", "project_data(self, data, as_serie=True, use=\"sum\"): \"\"\" Use gridinteresect Parameters ---------- data:", "(self.pixels is not None and self.shape is not None): raise", "boolean mask \"\"\" from shapely import vectorized flagin = vectorized.contains(polygon,", "vert_2, ...} if a dictionary is provided, the indexes will", "list(vertices.values()) this.set_vertices(vertices) if indexes is not None: this.set_indexes(indexes) return this", "-- Derived @property def vertices(self): \"\"\" \"\"\" if self._derived_properties[\"vertices\"] is", "the vertices. -> if None, then indexes = np.arange(len(vertices)) Returns", "\"\"\" return len(self.pixels) @property def shape(self): \"\"\" \"\"\" if self._properties[\"shape\"]", "gridin column '%s'\"%data) return self.gridin.geodataframe[data].values elif type(data) == pandas.Series: return", "self.geodataframe[\"id\"] = self.indexes if self.pixels is not None else np.arange(", "ndarray but lengthes do not match\") return data # ===================", "\"\"\" \"\"\" if self._side_properties[\"indexes\"] is None: self._side_properties[\"indexes\"] = np.arange(self.npixels) return", "calls set_vertices ; if 2-shaped, this calls set_pixels. Returns -------", "# --------- # def get_geoseries(self): \"\"\" build a new geodataframe", "position up on which the geometries are defined. NB: vertices", "def is_shape_unique(self): \"\"\" \"\"\" return len(np.shape(self.shape))==2 @property def geodataframe(self): \"\"\"", "should have the length equal to th number of pixels", "\"\"\" from shapely import ops triangles = ops.triangulate(geom) return np.stack([np.asarray(t.exterior.coords.xy).T[:-1]", "a dictionary is provided, the indexes will be set by", "not asgrid: return verts_wcs g_wcs = Grid.set_from(verts_wcs) g_wcs.geodataframe[\"x_pix\"],g_wcs.geodataframe[\"y_pix\"] = self.pixels.T", "the indexes of each of the vertices. -> if None,", "faster method if is_shape_unique # self._derived_properties[\"gridinterest\"] = geopandas.overlay(self.gridin.geodataframe, self.gridout.geodataframe, how='intersection')", "raise TypeError(\"The given geodataframe does not have 'geometry' column. It", "if update: self._update_geodataframe_() def set_vertices(self, vertices, overwrite=False, **kwargs): \"\"\" \"\"\"", "(see asgrid) \"\"\" gproj = GridProjector(self, othergrid) if column is", "this.set_indexes(indexes) return this @classmethod def set_from(cls, datainput): \"\"\" Creates a", "warnings.warn(\"triangles not defined: deriving triangulation.\") self.derive_triangulation() # Let's get the", "by the vertices. indexes: [list or None] -optional- (Ignored if", "is a dict) If you provide vertices as a list", "pixels (if any). update: [bool] -optional- should the geodataframe be", "made using quadpy. pip install quadpy\") # Is Triangulation made", "if len(shape_trs)==4 and vectorized: # All Polygon have the same", "is a faster method if is_shape_unique # self._derived_properties[\"gridinterest\"] = geopandas.overlay(self.gridin.geodataframe,", "if indexes is not None: self.set_indexes(indexes) # =================== # #", "= np.arange(len(vertices)) Returns ------- Grid \"\"\" this = cls() if", "arrays\") self._properties[\"pixels\"] = np.asarray(pixels) if shape is not None: self.set_pixelshapes(shape,", "2d array, something you could to ax.imshow(stamps) data will be", "get_2dgauss(x, mu=[4,4], cov=[[1,0],[0,2]]): \"\"\" \"\"\" return stats.multivariate_normal.pdf(np.stack(x, axis=-1), mean=mu, cov=cov)", "self.vertices verts_shape = np.shape(verts) flatten_verts = np.concatenate(verts, axis=0) # flatten_verts_wcs", "\"\"\" if self._derived_properties[\"geodataframe\"] is None: self._update_geodataframe_() return self._derived_properties[\"geodataframe\"] @property def", "\"out\") # =================== # # Methods # # =================== #", "method if is_shape_unique # self._derived_properties[\"gridinterest\"] = geopandas.overlay(self.gridin.geodataframe, self.gridout.geodataframe, how='intersection') self.gridinterest[\"area\"]", "shape_unique = np.unique(shape, axis=0) if len(shape_unique)==1: shape = shape_unique[0] self.set_pixels(pixels,", "to column: [str/None/list of] -optional- Which data should be projected", "Returns ------- ndarray \"\"\" if type(data) == str: if data", "else: xmin,xmax = xbounds ybounds = np.atleast_1d(ybounds) if len(ybounds)==1: ymin,ymax", "the centroid of the pixel is in or out the", "def set_pixelshapes(self, shape, update=True): \"\"\" \"\"\" # Setting the pixel", "# # --------- # def set_grid(self, grid, which=\"in\"): \"\"\" \"\"\"", "-> if None, then indexes = np.arange(len(vertices)) Returns ------- Grid", "gout.add_data(datas[k],k) return gout def project_to_wcs(self, wcs_, asgrid=True, **kwargs): \"\"\" provide", "[invert=False] or outsite [invert=True] Returns ------- list of pixels and", "from the given input data: Parameters ---------- datainput: [geopandas.geodataframe.GeoDataFrame or", "the same topology (same amount of vertices) tr_flat = np.stack(np.concatenate(trs,", "xbounds = np.atleast_1d(xbounds) if len(xbounds)==1: xmin,xmax = 0,xbounds[0] else: xmin,xmax", "np.arange(self.npixels) return self._side_properties[\"indexes\"] # -- Derived @property def vertices(self): \"\"\"", "# --------- # def set_indexes(self, indexes, update=True): \"\"\" provide the", "self.set_pixels(pixels, None, **kwargs) return self._derived_properties[\"vertices\"] = np.asarray(vertices) shape = self.vertices", "return self._derived_properties[\"vertices\"] @property def is_shape_unique(self): \"\"\" \"\"\" return len(np.shape(self.shape))==2 @property", "Most likely there is a faster method if is_shape_unique #", "self._derived_properties[\"gridinterest\"] is None: self._measure_gridinterest_() return self._derived_properties[\"gridinterest\"] class Grid( BaseObject ):", "of the pixel is in or out the given shapely", "could either be a: - geodataframe (and this calls self.set_geodataframe)", "data not in self.gridin.geodataframe.columns: raise ValueError(\"Unknown gridin column '%s'\"%data) return", "TypeError(\"The given geodataframe does not have 'geometry' column. It is", "flagin = vectorized.contains(polygon, *self.pixels.T) if invert: flagin = ~flagin return", "of pixels (if any). update: [bool] -optional- should the geodataframe", "column in [\"*\",\"all\"]: column = [k for k in self.geodataframe", "if data not in self.gridin.geodataframe.columns: raise ValueError(\"Unknown gridin column '%s'\"%data)", "=================== # # Methods # # =================== # # ---------", "\"\"\" self.gridinterest[\"_tmp\"] = data[ self.gridin.geodataframe.loc[ self.gridinterest[\"id_1\"]].index ] * self.gridinterest[\"area\"] return", "# Most likely there is a faster method if is_shape_unique", "updated ? [use True if you are not sure] Returns", "fast_unique: self._derived_properties[\"triangulation\"] = self.geodataframe[\"geometry\"].apply(triangulate) else: self._derived_properties[\"triangulation\"] = self.pixels[:,None,None] + triangulate(geometry.Polygon(self.shape))", "same topology (same amount of vertices) tr_flat = np.stack(np.concatenate(trs, axis=0),", "flagin = ~flagin return self.pixels[flagin], flagin # --------- # #", "this = cls() if type(vertices) is dict: indexes, vertices =", "self.shape is not None): self._derived_properties[\"vertices\"] = self.pixels[:,None]+self.shape return self._derived_properties[\"vertices\"] @property", "not None and self.shape is not None): self._derived_properties[\"vertices\"] = self.pixels[:,None]+self.shape", "\"\"\" \"\"\" return self._properties[\"pixels\"] @property def npixels(self): \"\"\" \"\"\" return", "data, use=\"sum\"): \"\"\" \"\"\" self.gridinterest[\"_tmp\"] = data[ self.gridin.geodataframe.loc[ self.gridinterest[\"id_1\"]].index ]", "is not None and np.shape(shape)[0] != self.npixels: raise AssertionError(\"`shape` must", "shape=None, update=True): \"\"\" provide the pixels. Pixels define the position", "column=None, ax=None, edgecolor=\"0.7\", facecolor=\"None\", **kwargs): \"\"\" \"\"\" if column is", "given datainput\") return this raise TypeError(\"cannot parse the format of", "# # Properties # # =================== # @property def gridin(self):", "project_to(self, othergrid, column=\"*\", asgrid=True, use=\"sum\"): \"\"\" project data in the", "triangles = ops.triangulate(geom) return np.stack([np.asarray(t.exterior.coords.xy).T[:-1] for t in triangles]) if", "['geometry', 'id', 'x', 'y']] datas = {k:gproj.project_data(k, use=use) for k", "@property def geodataframe(self): \"\"\" \"\"\" if self._derived_properties[\"geodataframe\"] is None: self._update_geodataframe_()", "= self.get_geoseries() x,y = self.pixels.T self._derived_properties[\"geodataframe\"] = \\ geopandas.GeoDataFrame({'geometry': dataseries,", "The vertices of all the grid entries. Could have two", "= [\"indexes\"] DERIVED_PROPERTIES = [\"vertices\",\"geodataframe\", \"triangulation\"] def __init__(self, pixels=None, shape=UNIT_SQUARE,", "GETTER # # --------- # def get_geoseries(self): \"\"\" build a", "which the geometries are defined. NB: vertices = pixels+shape \"\"\"", "# =================== # @classmethod def from_stamps(cls, stamp, origin=[0,0]): \"\"\" stamps", "Grid objects from the given input data: Parameters ---------- datainput:", "if not self.is_shape_unique or not fast_unique: self._derived_properties[\"triangulation\"] = self.geodataframe[\"geometry\"].apply(triangulate) else:", "size. self._derived_properties[\"vertices\"] = vertices pixels = np.asarray([np.mean(v_, axis=0) for v_", "ValueError(\"Cannot parse the given shape, must be [M,2] or [N,M,2]", "\"shape\"] SIDE_PROPERTIES = [\"indexes\"] DERIVED_PROPERTIES = [\"vertices\",\"geodataframe\", \"triangulation\"] def __init__(self,", "self._side_properties[\"indexes\"] = indexes if update: self._update_geodataframe_() def set_pixels(self, pixels, shape=None,", "'data' in the grid's dataframe \"\"\" this = get_simple_grid(*np.shape(stamp), shift_origin=origin)", "None: self._properties[\"shape\"] = UNIT_SQUARE return self._properties[\"shape\"] # -- Side @property", "is not None: # not += because conflict between int", "list of array: [[vert_1],[vert_2],....], then you may want to provide", "Measurement # # -------------- # def project_data(self, data, as_serie=True, use=\"sum\"):", "Setting the pixel shape.s if len(np.shape(shape))==2: self._properties[\"shape\"] = np.asarray(shape) elif", "\"\"\" \"\"\" PROPERTIES = [\"gridin\", \"gridout\"] DERIVED_PROPERTIES = [\"gridinterest\"] def", "---------- data: [ndarray or string or pandas.Serie] data associated to", "self._derived_properties[\"gridinterest\"] class Grid( BaseObject ): PROPERTIES = [\"pixels\", \"shape\"] SIDE_PROPERTIES", "= indexes if update: self._update_geodataframe_() def set_pixels(self, pixels, shape=None, update=True):", "axis=1) except: # Means vertices have different size. self._derived_properties[\"vertices\"] =", "return np.stack(poly_.exterior.xy).T[:-1] vertices = geodataframe[\"geometry\"].apply(get_verts).values self.set_vertices(vertices, update=False) # don't update", "of pixels and boolean mask \"\"\" from shapely import vectorized", "try: import quadpy except ImportError: raise ImportError(\"Integration is made using", "return g_wcs def evaluate(self, func, vectorized=True): \"\"\" Evaluate the given", "# =================== # @property def gridin(self): \"\"\" \"\"\" return self._properties[\"gridin\"]", "pixels2_flat = np.concatenate(pixels.T, axis=0) if shift_origin is not None: #", "dict [asgrid=False]? Returns ------- Grid or dict (see asgrid) \"\"\"", "raise TypeError(\"cannot parse the shape of the given datainput\") return", "def set_grid(self, grid, which=\"in\"): \"\"\" \"\"\" if which not in", "elif len(np.shape(shape))==3: if self.pixels is not None and np.shape(shape)[0] !=", "name, indexes=None, inplace=True): \"\"\" \"\"\" if indexes is None: indexes", "for k in self.geodataframe if k not in ['geometry', 'id',", "not None: self.set_indexes(indexes) # =================== # # Methods # #", "geodataframe[\"geometry\"].apply(get_verts).values self.set_vertices(vertices, update=False) # don't update the geodataframe # ---------", "ybounds = np.atleast_1d(ybounds) if len(ybounds)==1: ymin,ymax = 0,ybounds[0] else: ymin,ymax", "len(shape_unique)==1: shape = shape_unique[0] self.set_pixels(pixels, shape, **kwargs) def set_geodataframe(self, geodataframe,", "= othergrid.__class__.set_from(othergrid.geodataframe) for k in column: gout.add_data(datas[k],k) return gout def", "grid_out=None): \"\"\" \"\"\" if grid_in is not None: self.set_grid(grid_in, \"in\")", "len(np.shape(shape))==2: self._properties[\"shape\"] = np.asarray(shape) elif len(np.shape(shape))==3: if self.pixels is not", "pixels = np.mean(vertices, axis=1) except: # Means vertices have different", "localdef_get_area(l): return l.geometry.area/self.gridin.geodataframe.iloc[l.id_1].geometry.area # -------------- # if self.gridin is not", "# # # ======================= # class GridProjector( BaseObject ): \"\"\"", "associated to the pixels. This should have the length equal", "__init__(self, pixels=None, shape=UNIT_SQUARE, indexes=None): \"\"\" \"\"\" if pixels is not", "grid's dataframe \"\"\" this = get_simple_grid(*np.shape(stamp), shift_origin=origin) this.add_data(np.ravel(stamp), \"data\") return", "number of pixels\") self._side_properties[\"indexes\"] = indexes if update: self._update_geodataframe_() def", "self._derived_properties[\"vertices\"] = np.asarray(vertices) shape = self.vertices - pixels[:,None] shape_unique =", "\"\"\" Use gridinteresect Parameters ---------- data: [ndarray or string or", "[list of array or dictionary] The vertices of all the", "[\"in\",\"out\"]: raise ValueError(\"Which should either be 'in' our 'out'\") self._properties[\"grid%s\"%which]", "(and this calls self.set_geodataframe) - geoSeries - ndarray: if 3-shaped,", "given input\") # --------- # # SETTER # # ---------", "\"\"\" \"\"\" if indexes is None: indexes = self.indexes s_", "column} if not asgrid: return datas # building and setting", "since integration is going to send # x = [", "self.pixels is not None and len(indexes) != self.npixels: raise AssertionError(\"not", "two format: - list of array: [[vert_1],[vert_2],....], then you may", "(same amount of vertices) tr_flat = np.stack(np.concatenate(trs, axis=0), axis=-2) val", "np.concatenate(self.triangulation, axis=0) ) def get_pixels_in(self, polygon, invert=False): \"\"\" checks if", "\"\"\" \"\"\" if not overwrite and (self.pixels is not None", "np UNIT_SQUARE = np.asarray([[0,0],[0,1],[1,1],[1,0]])-0.5 from propobject import BaseObject from shapely", "x,y = self.pixels.T self._derived_properties[\"geodataframe\"] = \\ geopandas.GeoDataFrame({'geometry': dataseries, 'id':self.indexes, 'x':x,'y':y})", "Examples: # Remark the np.stack(x, axis=-1). # This is mandatory", "= self.indexes s_ = pandas.Series(data, name=name, index=indexes) if not inplace:", "= geopandas.overlay(self.gridin.geodataframe, self.gridout.geodataframe, how='intersection') self.gridinterest[\"area\"] = self.gridinterest.apply(localdef_get_area, axis=1) else: warnings.warn(\"Cannot", "gout def project_to_wcs(self, wcs_, asgrid=True, **kwargs): \"\"\" provide an astropy.wcs.WCS", "the vertices. Based on Delaunay tesselation, see shapely.ops.triangulate \"\"\" if", "-optional- Should this return a new Grid (actually same object", "is not None: self.set_grid(grid_in, \"in\") if grid_out is not None:", "ImportError: raise ImportError(\"Integration is made using quadpy. pip install quadpy\")", "if self._derived_properties[\"triangulation\"] is None: warnings.warn(\"triangles not defined: deriving triangulation.\") self.derive_triangulation()", "Returns ------- Grid \"\"\" this = cls() if type(vertices) is", "integration is made using quadpy. Examples: # Remark the np.stack(x,", "return self._derived_properties[\"geodataframe\"] @property def triangulation(self): \"\"\" Triangulation of the vertices.", "the indexes will be set by the vertices. indexes: [list", "AssertionError(\"`shape` must be unique or have the same lenth as", "origin=[0,0]): \"\"\" stamps are 2d array, something you could to", "[N,2] arrays\") self._properties[\"pixels\"] = np.asarray(pixels) if shape is not None:", "return np.sum(val, axis=1) def derive_triangulation(self, fast_unique=True): \"\"\" \"\"\" def triangulate(geom):", "indexes will be set by the vertices. indexes: [list or", "topology (same amount of vertices) tr_flat = np.stack(np.concatenate(trs, axis=0), axis=-2)", "columns will be (structural columns are 'geometry', 'id', 'x', 'y')", "projected in gridout. could be: - ndarray: must have the", "<filename>pixelproject/grid.py #! /usr/bin/env python # import warnings import numpy as", "--------- # def set_indexes(self, indexes, update=True): \"\"\" provide the indexes", "This evulation is using polynome triangulation to integrate the given", "else np.arange( len(geodataframe) ) # - get the vertices: def", "something you could to ax.imshow(stamps) data will be stored as", "# --------- # # SETTER # # --------- # def", "given input data: Parameters ---------- datainput: [geopandas.geodataframe.GeoDataFrame or ndarray] this", "if \"geometry\" not in geodataframe.columns: raise TypeError(\"The given geodataframe does", "pixels[:,None] shape_unique = np.unique(shape, axis=0) if len(shape_unique)==1: shape = shape_unique[0]", "@property def gridin(self): \"\"\" \"\"\" return self._properties[\"gridin\"] @property def gridout(self):", "geometries are defined. NB: vertices = pixels+shape \"\"\" # Setting", "the same length as gridin - string: name of a", "# # # ======================= # def get_simple_grid(xbounds, ybounds, shift_origin=None): \"\"\"", "project the current grid into it (assuming grid's vertices coordinates", "self._derived_properties[\"gridinterest\"] = geopandas.overlay(self.gridin.geodataframe, self.gridout.geodataframe, how='intersection') self.gridinterest[\"area\"] = self.gridinterest.apply(localdef_get_area, axis=1) else:", "vertices, indexes=None): \"\"\" directly provide the vertices Parameters: ----------- vertices:", "propobject import BaseObject from shapely import geometry import pandas import", "self._properties[\"gridin\"] @property def gridout(self): \"\"\" \"\"\" return self._properties[\"gridout\"] @property def", "update=True): \"\"\" provide the pixels. Pixels define the position up", "associated to gridin that should be projected in gridout. could", ") == 3: # vertices this.set_vertices(datainput) elif len(np.shape( datainput) )", "given grid Parameters ---------- othergrid: [Grid] New grid where data", "\"\"\" \"\"\" if self._properties[\"shape\"] is None: self._properties[\"shape\"] = UNIT_SQUARE return", "be [M,2] or [N,M,2] when N is the number of", "have the same length as gridin - string: name of", "# def _update_geodataframe_(self): \"\"\" \"\"\" dataseries = self.get_geoseries() x,y =", "np.asarray([[0,0],[0,1],[1,1],[1,0]])-0.5 from propobject import BaseObject from shapely import geometry import", "k in column: gout.add_data(datas[k],k) return gout def project_to_wcs(self, wcs_, asgrid=True,", "if column is not None: facecolor=None return self.geodataframe.plot(column, ax=ax,facecolor=facecolor, edgecolor=edgecolor,", "= cls() if type(vertices) is dict: indexes, vertices = list(vertices.keys()),", "othergrid) or a dict [asgrid=False]? Returns ------- Grid or dict", "# -------------- # def project_data(self, data, as_serie=True, use=\"sum\"): \"\"\" Use", "self._side_properties[\"indexes\"] # -- Derived @property def vertices(self): \"\"\" \"\"\" if", "asgrid: [bool] -optional- Should this return a load Grid object", "data.values elif len(data) != len(self.gridin.geodataframe): raise ValueError(\"data given as ndarray", "a dict [asgrid=False]? Returns ------- Grid or dict (see asgrid)", "------- Grid \"\"\" this = cls() if type(datainput) == geopandas.geodataframe.GeoDataFrame:", "list(vertices.keys()), list(vertices.values()) this.set_vertices(vertices) if indexes is not None: this.set_indexes(indexes) return", "= np.mean(vertices, axis=1) except: # Means vertices have different size.", "list of vertices, you can provide the indexes of each", "class GridProjector( BaseObject ): \"\"\" \"\"\" PROPERTIES = [\"gridin\", \"gridout\"]", "shift_origin return Grid(pixels2_flat, UNIT_SQUARE) # ======================= # # # #", "data should be projected to column: [str/None/list of] -optional- Which", "the number of pixel and M the number of vertices\")", "def project_to_wcs(self, wcs_, asgrid=True, **kwargs): \"\"\" provide an astropy.wcs.WCS and", "self._derived_properties[\"triangulation\"] is None: warnings.warn(\"triangles not defined: deriving triangulation.\") self.derive_triangulation() #", "Grid( BaseObject ): PROPERTIES = [\"pixels\", \"shape\"] SIDE_PROPERTIES = [\"indexes\"]", "= \\ geopandas.GeoDataFrame({'geometry': dataseries, 'id':self.indexes, 'x':x,'y':y}) def add_data(self, data, name,", "\"\"\" # Calcul itself projected_data = self._project_data_(self._parse_data_(data), use=use) if as_serie:", "-- Side @property def indexes(self): \"\"\" \"\"\" if self._side_properties[\"indexes\"] is", "vertices\") try: pixels = np.mean(vertices, axis=1) except: # Means vertices", "matched with gridin Returns ------- ndarray \"\"\" if type(data) ==", "= np.asarray(shape) elif len(np.shape(shape))==3: if self.pixels is not None and", "== str: if data not in self.gridin.geodataframe.columns: raise ValueError(\"Unknown gridin", "len(np.shape(shape))==3: if self.pixels is not None and np.shape(shape)[0] != self.npixels:", "def get_2dgauss(x, mu=[4,4], cov=[[1,0],[0,2]]): \"\"\" \"\"\" return stats.multivariate_normal.pdf(np.stack(x, axis=-1), mean=mu,", "None and (self.pixels is not None and self.shape is not", "[bool] -optional- Should this return a load Grid object or", "column: gout.add_data(datas[k],k) return gout def project_to_wcs(self, wcs_, asgrid=True, **kwargs): \"\"\"", "[bool] -optional- should the geodataframe be updated ? [use True", "because gridin and/or gridout is/are None\") # -------------- # #", "indexes is not None: this.set_indexes(indexes) return this @classmethod def set_from(cls,", "shape.s if len(np.shape(shape))==2: self._properties[\"shape\"] = np.asarray(shape) elif len(np.shape(shape))==3: if self.pixels", "# @property def gridin(self): \"\"\" \"\"\" return self._properties[\"gridin\"] @property def", "= np.asarray(vertices) shape = self.vertices - pixels[:,None] shape_unique = np.unique(shape,", "'id', 'x', 'y']] datas = {k:gproj.project_data(k, use=use) for k in", "build a new geodataframe and returns it. \"\"\" import geopandas", "this could either be a: - geodataframe (and this calls", "if self.pixels is not None else np.arange( len(geodataframe) ) #", "same object as othergrid) or a dict [asgrid=False]? Returns -------", "\"\"\" if self._derived_properties[\"gridinterest\"] is None: self._measure_gridinterest_() return self._derived_properties[\"gridinterest\"] class Grid(", "= self.pixels[:,None,None] + triangulate(geometry.Polygon(self.shape)) # --------- # # PLOTTER #", "evaluate(self, func, vectorized=True): \"\"\" Evaluate the given function throughout the", "None: facecolor=None return self.geodataframe.plot(column, ax=ax,facecolor=facecolor, edgecolor=edgecolor, **kwargs) # =================== #", "not inplace: return self.geodataframe.join(s_) self._derived_properties[\"geodataframe\"] = self.geodataframe.join(s_) # --------- #", "None\") # -------------- # # Measurement # # -------------- #", "- pandas.Serie: serie that will be matched with gridin Returns", "as ndarray but lengthes do not match\") return data #", "def get_verts(poly_): return np.stack(poly_.exterior.xy).T[:-1] vertices = geodataframe[\"geometry\"].apply(get_verts).values self.set_vertices(vertices, update=False) #", "- string: name of a gridin column (pandas) - pandas.Serie:", "= 0,ybounds[0] else: ymin,ymax = ybounds pixels = np.mgrid[xmin:xmax,ymin:ymax] pixels2_flat", "'out'\") self._properties[\"grid%s\"%which] = grid self._derived_properties[\"gridinterest\"] = None def _measure_gridinterest_(self): \"\"\"", "objects from the given input data: Parameters ---------- datainput: [geopandas.geodataframe.GeoDataFrame", "if shape is not None: self.set_pixelshapes(shape, update=False) if update: self._update_geodataframe_()", "None else np.arange( len(geodataframe) ) # - get the vertices:", "but lengthes do not match\") return data # =================== #", "if self._side_properties[\"indexes\"] is None: self._side_properties[\"indexes\"] = np.arange(self.npixels) return self._side_properties[\"indexes\"] #", "data[ self.gridin.geodataframe.loc[ self.gridinterest[\"id_1\"]].index ] * self.gridinterest[\"area\"] return getattr(self.gridinterest.groupby(\"id_2\")[\"_tmp\"],use)() def _parse_data_(self,data):", "(if any). update: [bool] -optional- should the geodataframe be updated", "UNIT_SQUARE return self._properties[\"shape\"] # -- Side @property def indexes(self): \"\"\"", "None] -optional- (Ignored if vertices is a dict) If you", "def localdef_get_area(l): return l.geometry.area/self.gridin.geodataframe.iloc[l.id_1].geometry.area # -------------- # if self.gridin is", "grid gout = othergrid.__class__.set_from(othergrid.geodataframe) for k in column: gout.add_data(datas[k],k) return", "s_ = pandas.Series(data, name=name, index=indexes) if not inplace: return self.geodataframe.join(s_)", "vectorized.contains(polygon, *self.pixels.T) if invert: flagin = ~flagin return self.pixels[flagin], flagin", "= pixels2_flat+ shift_origin return Grid(pixels2_flat, UNIT_SQUARE) # ======================= # #", "- get the vertices: def get_verts(poly_): return np.stack(poly_.exterior.xy).T[:-1] vertices =", "integrate the given function inside the polyname using triangle integration.", "asgrid) \"\"\" verts = self.vertices verts_shape = np.shape(verts) flatten_verts =", "for t_ in trs]) return np.sum(val, axis=1) def derive_triangulation(self, fast_unique=True):", "if indexes is None: indexes = self.indexes s_ = pandas.Series(data,", "geodataframe and returns it. \"\"\" import geopandas return geopandas.GeoSeries([geometry.Polygon(v) for", "vertices, you can provide the indexes of each of the", "to th number of pixels (if any). update: [bool] -optional-", "= GridProjector(self, othergrid) if column is None or column in", "if self._properties[\"shape\"] is None: self._properties[\"shape\"] = UNIT_SQUARE return self._properties[\"shape\"] #", "# don't update the geodataframe # --------- # # UPDATE", "@property def triangulation(self): \"\"\" Triangulation of the vertices. Based on", "# @property def pixels(self): \"\"\" \"\"\" return self._properties[\"pixels\"] @property def", "is not None and self.shape is not None): raise ValueError(\"Pixels", "option to true, to update geodataframe\") if \"geometry\" not in", "\"\"\" return self._properties[\"gridout\"] @property def gridinterest(self): \"\"\" \"\"\" if self._derived_properties[\"gridinterest\"]", "\"\"\" \"\"\" # -- internal -- # def localdef_get_area(l): return", "update: [bool] -optional- should the geodataframe be updated ? [use", "== np.ndarray: if len(np.shape( datainput) ) == 3: # vertices", "flatten_verts = np.concatenate(verts, axis=0) # flatten_verts_wcs = np.asarray(wcs_.all_pix2world(flatten_verts[:,0], flatten_verts[:,1], 0,", "throughout the grid. This evulation is using polynome triangulation to", "int and float array pixels2_flat = pixels2_flat+ shift_origin return Grid(pixels2_flat,", "either be 'in' our 'out'\") self._properties[\"grid%s\"%which] = grid self._derived_properties[\"gridinterest\"] =", "return getattr(self.gridinterest.groupby(\"id_2\")[\"_tmp\"],use)() def _parse_data_(self,data): \"\"\" Parameters ---------- data: [ndarray or", "class Grid( BaseObject ): PROPERTIES = [\"pixels\", \"shape\"] SIDE_PROPERTIES =", "the number of vertices\") if update: self._update_geodataframe_() def set_vertices(self, vertices,", "setting the new grid gout = othergrid.__class__.set_from(othergrid.geodataframe) for k in", "define the position up on which the geometries are defined.", "shape_unique[0] self.set_pixels(pixels, shape, **kwargs) def set_geodataframe(self, geodataframe, overwrite=False): \"\"\" \"\"\"", "you could to ax.imshow(stamps) data will be stored as 'data'", "if shift_origin is not None: # not += because conflict", "New grid where data should be projected to column: [str/None/list", "@classmethod def from_vertices(cls, vertices, indexes=None): \"\"\" directly provide the vertices", "self.indexes if self.pixels is not None else np.arange( len(geodataframe) )", "axis=0), axis=-2) val = quadpy.triangle.strang_fix_cowper_09().integrate(func,tr_flat).reshape(shape_trs[:2]) else: val = np.asarray([quadpy.triangle.strang_fix_cowper_09().integrate(func,np.stack(t_, axis=-2))", "the overwrite option to true, to update geodataframe\") if \"geometry\"", "project_to_wcs(self, wcs_, asgrid=True, **kwargs): \"\"\" provide an astropy.wcs.WCS and this", "cov=cov) ``` \"\"\" try: import quadpy except ImportError: raise ImportError(\"Integration", "polygon. Parameters ---------- polygon: [shapely.geometry] reference polygon invert: [bool] -optional-", "return a load Grid object or an array of vertices", "\"\"\" \"\"\" return len(self.pixels) @property def shape(self): \"\"\" \"\"\" if", "vertices. -> if None, then indexes = np.arange(len(vertices)) Returns -------", "# pixels this.set_pixels(datainput) else: raise TypeError(\"cannot parse the shape of", "@property def gridout(self): \"\"\" \"\"\" return self._properties[\"gridout\"] @property def gridinterest(self):", "def gridinterest(self): \"\"\" \"\"\" if self._derived_properties[\"gridinterest\"] is None: self._measure_gridinterest_() return", "\"\"\" Triangulation of the vertices. Based on Delaunay tesselation, see", "Side @property def indexes(self): \"\"\" \"\"\" if self._side_properties[\"indexes\"] is None:", "reference polygon invert: [bool] -optional- Get the pixel inside the", "not overwrite and (self.pixels is not None and self.shape is", "axis=-1), mean=mu, cov=cov) ``` \"\"\" try: import quadpy except ImportError:", "self._derived_properties[\"geodataframe\"] is None: self._update_geodataframe_() return self._derived_properties[\"geodataframe\"] @property def triangulation(self): \"\"\"", "return Grid.set_from( np.concatenate(self.triangulation, axis=0) ) def get_pixels_in(self, polygon, invert=False): \"\"\"", "= xbounds ybounds = np.atleast_1d(ybounds) if len(ybounds)==1: ymin,ymax = 0,ybounds[0]", "# SETTER # # --------- # def set_grid(self, grid, which=\"in\"):", "np.mgrid[xmin:xmax,ymin:ymax] pixels2_flat = np.concatenate(pixels.T, axis=0) if shift_origin is not None:", "be a: - geodataframe (and this calls self.set_geodataframe) - geoSeries", "_measure_gridinterest_(self): \"\"\" \"\"\" # -- internal -- # def localdef_get_area(l):", "have different size. self._derived_properties[\"vertices\"] = vertices pixels = np.asarray([np.mean(v_, axis=0)", "type(vertices) is dict: indexes, vertices = list(vertices.keys()), list(vertices.values()) this.set_vertices(vertices) if", "# - get the vertices: def get_verts(poly_): return np.stack(poly_.exterior.xy).T[:-1] vertices", "get_triangulation_grid(self): \"\"\" Returns a grid of triangulation. \"\"\" return Grid.set_from(", "cov=[[1,0],[0,2]]): \"\"\" \"\"\" return stats.multivariate_normal.pdf(np.stack(x, axis=-1), mean=mu, cov=cov) ``` \"\"\"", "def set_pixels(self, pixels, shape=None, update=True): \"\"\" provide the pixels. Pixels", "None, **kwargs) return self._derived_properties[\"vertices\"] = np.asarray(vertices) shape = self.vertices -", "be stored as 'data' in the grid's dataframe \"\"\" this", "self._derived_properties[\"triangulation\"] = self.pixels[:,None,None] + triangulate(geometry.Polygon(self.shape)) # --------- # # PLOTTER", "float array pixels2_flat = pixels2_flat+ shift_origin return Grid(pixels2_flat, UNIT_SQUARE) #", "pandas.Serie] data associated to gridin that should be projected in", "[geopandas.geodataframe.GeoDataFrame or ndarray] this could either be a: - geodataframe", "projected_data projected_data_array = np.zeros( len(self.gridout.geodataframe) ) projected_data_array[projected_data.index.values] = projected_data.values return", "= flatten_verts_wcs.reshape(verts_shape) if not asgrid: return verts_wcs g_wcs = Grid.set_from(verts_wcs)", "of each of the vertices. -> if None, then indexes", "triangulation to integrate the given function inside the polyname using", "this return a new Grid (actually same object as othergrid)", "\"\"\" # -- internal -- # def localdef_get_area(l): return l.geometry.area/self.gridin.geodataframe.iloc[l.id_1].geometry.area", "# # Measurement # # -------------- # def project_data(self, data,", "**kwargs): \"\"\" provide an astropy.wcs.WCS and this will project the", "in self.geodataframe if k not in ['geometry', 'id', 'x', 'y']]", "use=use) if as_serie: return projected_data projected_data_array = np.zeros( len(self.gridout.geodataframe) )", "or dictionary] The vertices of all the grid entries. Could", "data should be projected ? If None or '*' all", "BaseObject ): PROPERTIES = [\"pixels\", \"shape\"] SIDE_PROPERTIES = [\"indexes\"] DERIVED_PROPERTIES", "--------- # def project_to(self, othergrid, column=\"*\", asgrid=True, use=\"sum\"): \"\"\" project", "'in' our 'out'\") self._properties[\"grid%s\"%which] = grid self._derived_properties[\"gridinterest\"] = None def", "trs]) return np.sum(val, axis=1) def derive_triangulation(self, fast_unique=True): \"\"\" \"\"\" def", "inplace: return self.geodataframe.join(s_) self._derived_properties[\"geodataframe\"] = self.geodataframe.join(s_) # --------- # #", "format that quadpy likes \"\"\" from shapely import ops triangles", "len(np.shape( datainput) ) == 3: # vertices this.set_vertices(datainput) elif len(np.shape(", "from shapely import ops triangles = ops.triangulate(geom) return np.stack([np.asarray(t.exterior.coords.xy).T[:-1] for", "# --------- # def show(self, column=None, ax=None, edgecolor=\"0.7\", facecolor=\"None\", **kwargs):", "polygon: [shapely.geometry] reference polygon invert: [bool] -optional- Get the pixel", "*self.pixels.T) if invert: flagin = ~flagin return self.pixels[flagin], flagin #", "[Grid] New grid where data should be projected to column:", "self._properties[\"shape\"] is None: self._properties[\"shape\"] = UNIT_SQUARE return self._properties[\"shape\"] # --", "that will be matched with gridin \"\"\" # Calcul itself", "val = quadpy.triangle.strang_fix_cowper_09().integrate(func,tr_flat).reshape(shape_trs[:2]) else: val = np.asarray([quadpy.triangle.strang_fix_cowper_09().integrate(func,np.stack(t_, axis=-2)) for t_", "option to true, to update vertices\") try: pixels = np.mean(vertices,", "grid self._derived_properties[\"gridinterest\"] = None def _measure_gridinterest_(self): \"\"\" \"\"\" # --", "None: self.set_indexes(indexes) # =================== # # Methods # # ===================", "each pixels Parameters ---------- indexes: [ndarray] indexes associated to the", "The world coordinate solution asgrid: [bool] -optional- Should this return", "GridProjector(self, othergrid) if column is None or column in [\"*\",\"all\"]:", "you are not sure] Returns ------- Void \"\"\" if self.pixels", "if len(shape_unique)==1: shape = shape_unique[0] self.set_pixels(pixels, shape, **kwargs) def set_geodataframe(self,", "in the given grid Parameters ---------- othergrid: [Grid] New grid", "pixels if np.shape(pixels)[-1] != 2: raise ValueError(\"pixels must be [N,2]", "raise ValueError(\"Pixels and shape already defined. set the overwrite option", "len(self.gridin.geodataframe): raise ValueError(\"data given as ndarray but lengthes do not", "parse the shape of the given datainput\") return this raise", "non-structural columns will be (structural columns are 'geometry', 'id', 'x',", "length as gridin - string: name of a gridin column", "return geopandas.GeoSeries([geometry.Polygon(v) for v in self.vertices]) def get_triangulation_grid(self): \"\"\" Returns", "# Remark the np.stack(x, axis=-1). # This is mandatory since", "return a new Grid (actually same object as othergrid) or", "to integrate the given function inside the polyname using triangle", "if k not in ['geometry', 'id', 'x', 'y']] datas =", "[[....],[...]], ... ] for triangles ```python def get_2dgauss(x, mu=[4,4], cov=[[1,0],[0,2]]):", "is None: self._update_geodataframe_() return self._derived_properties[\"geodataframe\"] @property def triangulation(self): \"\"\" Triangulation", "None and np.shape(shape)[0] != self.npixels: raise AssertionError(\"`shape` must be unique", "Is Triangulation made ? if self._derived_properties[\"triangulation\"] is None: warnings.warn(\"triangles not", "then you may want to provide indexes - dictionary: {id_1:vert_1,id_2:", "wcs_.all_pix2world Returns ------- Grid or array (see asgrid) \"\"\" verts", "to update geodataframe\") if \"geometry\" not in geodataframe.columns: raise TypeError(\"The", "as_serie=True, use=\"sum\"): \"\"\" Use gridinteresect Parameters ---------- data: [ndarray or", "pixels2_flat+ shift_origin return Grid(pixels2_flat, UNIT_SQUARE) # ======================= # # #", "update vertices\") try: pixels = np.mean(vertices, axis=1) except: # Means", "vertices coordinates are in pixels) Parameters ---------- wcs_: [astropy.wcs.WCS] The", "projected_data.values return projected_data_array def _project_data_(self, data, use=\"sum\"): \"\"\" \"\"\" self.gridinterest[\"_tmp\"]", "# --------- # # UPDATE # # --------- # def", "self.gridin.geodataframe.loc[ self.gridinterest[\"id_1\"]].index ] * self.gridinterest[\"area\"] return getattr(self.gridinterest.groupby(\"id_2\")[\"_tmp\"],use)() def _parse_data_(self,data): \"\"\"", "be projected ? If None or '*' all the non-structural", "# def set_grid(self, grid, which=\"in\"): \"\"\" \"\"\" if which not", "if grid_out is not None: self.set_grid(grid_out, \"out\") # =================== #", "if not inplace: return self.geodataframe.join(s_) self._derived_properties[\"geodataframe\"] = self.geodataframe.join(s_) # ---------", "\"\"\" if self._side_properties[\"indexes\"] is None: self._side_properties[\"indexes\"] = np.arange(self.npixels) return self._side_properties[\"indexes\"]", "\"\"\" try: import quadpy except ImportError: raise ImportError(\"Integration is made", "a dict) If you provide vertices as a list of", "self._derived_properties[\"geodataframe\"] = \\ geopandas.GeoDataFrame({'geometry': dataseries, 'id':self.indexes, 'x':x,'y':y}) def add_data(self, data,", "def __init__(self, pixels=None, shape=UNIT_SQUARE, indexes=None): \"\"\" \"\"\" if pixels is", "\"in\") if grid_out is not None: self.set_grid(grid_out, \"out\") # ===================", "--------- # def get_geoseries(self): \"\"\" build a new geodataframe and", "= np.mgrid[xmin:xmax,ymin:ymax] pixels2_flat = np.concatenate(pixels.T, axis=0) if shift_origin is not", "or ndarray] this could either be a: - geodataframe (and", "given shape, must be [M,2] or [N,M,2] when N is", ") == 3: # pixels this.set_pixels(datainput) else: raise TypeError(\"cannot parse", "# class GridProjector( BaseObject ): \"\"\" \"\"\" PROPERTIES = [\"gridin\",", "**kwargs)).T # verts_wcs = flatten_verts_wcs.reshape(verts_shape) if not asgrid: return verts_wcs", "not None): self._derived_properties[\"vertices\"] = self.pixels[:,None]+self.shape return self._derived_properties[\"vertices\"] @property def is_shape_unique(self):", "overwrite option to true, to update vertices\") try: pixels =", "as_serie: return projected_data projected_data_array = np.zeros( len(self.gridout.geodataframe) ) projected_data_array[projected_data.index.values] =", ") def get_pixels_in(self, polygon, invert=False): \"\"\" checks if the centroid", "\"\"\" # Setting the pixels if np.shape(pixels)[-1] != 2: raise", "install quadpy\") # Is Triangulation made ? if self._derived_properties[\"triangulation\"] is", "------- Grid \"\"\" this = cls() if type(vertices) is dict:", "axis=0) if len(shape_unique)==1: shape = shape_unique[0] self.set_pixels(pixels, shape, **kwargs) def", "= self.pixels[:,None]+self.shape return self._derived_properties[\"vertices\"] @property def is_shape_unique(self): \"\"\" \"\"\" return", "\"\"\" if pixels is not None: self.set_pixels(pixels,shape=shape) if indexes is", "update geodataframe\") if \"geometry\" not in geodataframe.columns: raise TypeError(\"The given", "self.geodataframe[\"geometry\"].apply(triangulate) else: self._derived_properties[\"triangulation\"] = self.pixels[:,None,None] + triangulate(geometry.Polygon(self.shape)) # --------- #", "not sure] Returns ------- Void \"\"\" if self.pixels is not", "ValueError(\"Which should either be 'in' our 'out'\") self._properties[\"grid%s\"%which] = grid", "= np.concatenate(verts, axis=0) # flatten_verts_wcs = np.asarray(wcs_.all_pix2world(flatten_verts[:,0], flatten_verts[:,1], 0, **kwargs)).T", "update=True): \"\"\" \"\"\" # Setting the pixel shape.s if len(np.shape(shape))==2:", "centroid of the pixel is in or out the given", "pip install quadpy\") # Is Triangulation made ? if self._derived_properties[\"triangulation\"]", "ValueError(\"pixels must be [N,2] arrays\") self._properties[\"pixels\"] = np.asarray(pixels) if shape", "sure] Returns ------- Void \"\"\" if self.pixels is not None", "derive_triangulation(self, fast_unique=True): \"\"\" \"\"\" def triangulate(geom): \"\"\" Return triangulate format", "made ? if self._derived_properties[\"triangulation\"] is None: warnings.warn(\"triangles not defined: deriving", "serie that will be matched with gridin Returns ------- ndarray", "is not None): raise ValueError(\"Pixels and shape already defined. set", "\"\"\" directly provide the vertices Parameters: ----------- vertices: [list of", "set the overwrite option to true, to update geodataframe\") if", "[astropy.wcs.WCS] The world coordinate solution asgrid: [bool] -optional- Should this", "there is a faster method if is_shape_unique # self._derived_properties[\"gridinterest\"] =", "flatten_verts_wcs.reshape(verts_shape) if not asgrid: return verts_wcs g_wcs = Grid.set_from(verts_wcs) g_wcs.geodataframe[\"x_pix\"],g_wcs.geodataframe[\"y_pix\"]", "if you are not sure] Returns ------- Void \"\"\" if", "self.set_pixels(pixels, shape, **kwargs) def set_geodataframe(self, geodataframe, overwrite=False): \"\"\" \"\"\" if", "def _parse_data_(self,data): \"\"\" Parameters ---------- data: [ndarray or string or", "vertices is a dict) If you provide vertices as a", "# -- Derived @property def vertices(self): \"\"\" \"\"\" if self._derived_properties[\"vertices\"]", "# =================== # # Properties # # =================== # @property", "raise ValueError(\"Which should either be 'in' our 'out'\") self._properties[\"grid%s\"%which] =", "gridinteresect Parameters ---------- data: [ndarray or string or pandas.Serie] data", "if as_serie: return projected_data projected_data_array = np.zeros( len(self.gridout.geodataframe) ) projected_data_array[projected_data.index.values]", "for v_ in vertices]) self.set_pixels(pixels, None, **kwargs) return self._derived_properties[\"vertices\"] =", "# # --------- # def project_to(self, othergrid, column=\"*\", asgrid=True, use=\"sum\"):", "tesselation, see shapely.ops.triangulate \"\"\" if self._derived_properties[\"triangulation\"] is None: self.derive_triangulation() return", "verts_wcs g_wcs = Grid.set_from(verts_wcs) g_wcs.geodataframe[\"x_pix\"],g_wcs.geodataframe[\"y_pix\"] = self.pixels.T return g_wcs def", "name of a gridin column (pandas) - pandas.Serie: serie that", "(Ignored if vertices is a dict) If you provide vertices", "our 'out'\") self._properties[\"grid%s\"%which] = grid self._derived_properties[\"gridinterest\"] = None def _measure_gridinterest_(self):", "gridout. could be: - ndarray: must have the same length", "in geodataframe.columns: self.geodataframe[\"id\"] = self.indexes if self.pixels is not None", "if self._derived_properties[\"vertices\"] is None and (self.pixels is not None and", "when N is the number of pixel and M the", "overwrite=False, **kwargs): \"\"\" \"\"\" if not overwrite and (self.pixels is", "if update: self._update_geodataframe_() def set_pixelshapes(self, shape, update=True): \"\"\" \"\"\" #", "None: self._side_properties[\"indexes\"] = np.arange(self.npixels) return self._side_properties[\"indexes\"] # -- Derived @property", "def geodataframe(self): \"\"\" \"\"\" if self._derived_properties[\"geodataframe\"] is None: self._update_geodataframe_() return", "given as ndarray but lengthes do not match\") return data", "= self.vertices verts_shape = np.shape(verts) flatten_verts = np.concatenate(verts, axis=0) #", "to update vertices\") try: pixels = np.mean(vertices, axis=1) except: #", "else: raise TypeError(\"cannot parse the shape of the given datainput\")", "DERIVED_PROPERTIES = [\"vertices\",\"geodataframe\", \"triangulation\"] def __init__(self, pixels=None, shape=UNIT_SQUARE, indexes=None): \"\"\"", "return self._derived_properties[\"vertices\"] = np.asarray(vertices) shape = self.vertices - pixels[:,None] shape_unique", "pixel inside the polygon [invert=False] or outsite [invert=True] Returns -------", "-- # def localdef_get_area(l): return l.geometry.area/self.gridin.geodataframe.iloc[l.id_1].geometry.area # -------------- # if", "if not asgrid: return datas # building and setting the", "mandatory since integration is going to send # x =", "pandas.Serie: serie that will be matched with gridin \"\"\" #", "if len(xbounds)==1: xmin,xmax = 0,xbounds[0] else: xmin,xmax = xbounds ybounds", "= [ [[....],[...]], [[....],[...]], ... ] for triangles ```python def", "# self._derived_properties[\"gridinterest\"] = geopandas.overlay(self.gridin.geodataframe, self.gridout.geodataframe, how='intersection') self.gridinterest[\"area\"] = self.gridinterest.apply(localdef_get_area, axis=1)", "in [\"in\",\"out\"]: raise ValueError(\"Which should either be 'in' our 'out'\")", "dictionary: {id_1:vert_1,id_2: vert_2, ...} if a dictionary is provided, the", "-------------- # def project_data(self, data, as_serie=True, use=\"sum\"): \"\"\" Use gridinteresect", "in the grid's dataframe \"\"\" this = get_simple_grid(*np.shape(stamp), shift_origin=origin) this.add_data(np.ravel(stamp),", "def get_pixels_in(self, polygon, invert=False): \"\"\" checks if the centroid of", "be set by the vertices. indexes: [list or None] -optional-", "the given input\") # --------- # # SETTER # #", "else: raise ValueError(\"Cannot parse the given shape, must be [M,2]", "# # --------- # def show(self, column=None, ax=None, edgecolor=\"0.7\", facecolor=\"None\",", "not None: self.set_pixelshapes(shape, update=False) if update: self._update_geodataframe_() def set_pixelshapes(self, shape,", "with gridin Returns ------- ndarray \"\"\" if type(data) == str:", "the pixel shape.s if len(np.shape(shape))==2: self._properties[\"shape\"] = np.asarray(shape) elif len(np.shape(shape))==3:", "is using polynome triangulation to integrate the given function inside", "= [\"vertices\",\"geodataframe\", \"triangulation\"] def __init__(self, pixels=None, shape=UNIT_SQUARE, indexes=None): \"\"\" \"\"\"", "stamps are 2d array, something you could to ax.imshow(stamps) data", "self.vertices - pixels[:,None] shape_unique = np.unique(shape, axis=0) if len(shape_unique)==1: shape", "self._derived_properties[\"vertices\"] = vertices pixels = np.asarray([np.mean(v_, axis=0) for v_ in", "shape=UNIT_SQUARE, indexes=None): \"\"\" \"\"\" if pixels is not None: self.set_pixels(pixels,shape=shape)", "=================== # # --------- # # SETTER # # ---------", "a grid of triangulation. \"\"\" return Grid.set_from( np.concatenate(self.triangulation, axis=0) )", "degree) **kwargs goes to wcs_.all_pix2world Returns ------- Grid or array", "+ triangulate(geometry.Polygon(self.shape)) # --------- # # PLOTTER # # ---------", "geodataframe if \"id\" not in geodataframe.columns: self.geodataframe[\"id\"] = self.indexes if", "ybounds pixels = np.mgrid[xmin:xmax,ymin:ymax] pixels2_flat = np.concatenate(pixels.T, axis=0) if shift_origin", "self._derived_properties[\"triangulation\"] = self.geodataframe[\"geometry\"].apply(triangulate) else: self._derived_properties[\"triangulation\"] = self.pixels[:,None,None] + triangulate(geometry.Polygon(self.shape)) #", "column. It is required\") self._derived_properties[\"geodataframe\"] = geodataframe if \"id\" not", "# not += because conflict between int and float array", "elif len(np.shape( datainput) ) == 3: # pixels this.set_pixels(datainput) else:", "len(data) != len(self.gridin.geodataframe): raise ValueError(\"data given as ndarray but lengthes", "not in self.gridin.geodataframe.columns: raise ValueError(\"Unknown gridin column '%s'\"%data) return self.gridin.geodataframe[data].values", "return np.stack([np.asarray(t.exterior.coords.xy).T[:-1] for t in triangles]) if not self.is_shape_unique or", "pixels this.set_pixels(datainput) else: raise TypeError(\"cannot parse the shape of the", "\"\"\" provide the pixels. Pixels define the position up on", "is mandatory since integration is going to send # x", "self.get_geoseries() x,y = self.pixels.T self._derived_properties[\"geodataframe\"] = \\ geopandas.GeoDataFrame({'geometry': dataseries, 'id':self.indexes,", "= ~flagin return self.pixels[flagin], flagin # --------- # # Project", "None): self._derived_properties[\"vertices\"] = self.pixels[:,None]+self.shape return self._derived_properties[\"vertices\"] @property def is_shape_unique(self): \"\"\"", "true, to update geodataframe\") if \"geometry\" not in geodataframe.columns: raise", "t in triangles]) if not self.is_shape_unique or not fast_unique: self._derived_properties[\"triangulation\"]", "'y') asgrid: [bool] -optional- Should this return a new Grid", "vertices = list(vertices.keys()), list(vertices.values()) this.set_vertices(vertices) if indexes is not None:", "grid where data should be projected to column: [str/None/list of]", "self._side_properties[\"indexes\"] = np.arange(self.npixels) return self._side_properties[\"indexes\"] # -- Derived @property def", "the same number of indexes as the number of pixels\")", "-optional- Should this return a load Grid object or an", "self.gridinterest.apply(localdef_get_area, axis=1) else: warnings.warn(\"Cannot measure gridinterest, because gridin and/or gridout", "self.pixels.T return g_wcs def evaluate(self, func, vectorized=True): \"\"\" Evaluate the", "3: # vertices this.set_vertices(datainput) elif len(np.shape( datainput) ) == 3:", "getattr(self.gridinterest.groupby(\"id_2\")[\"_tmp\"],use)() def _parse_data_(self,data): \"\"\" Parameters ---------- data: [ndarray or string", "# # --------- # def get_geoseries(self): \"\"\" build a new", "= quadpy.triangle.strang_fix_cowper_09().integrate(func,tr_flat).reshape(shape_trs[:2]) else: val = np.asarray([quadpy.triangle.strang_fix_cowper_09().integrate(func,np.stack(t_, axis=-2)) for t_ in", "else: val = np.asarray([quadpy.triangle.strang_fix_cowper_09().integrate(func,np.stack(t_, axis=-2)) for t_ in trs]) return", "parse the given shape, must be [M,2] or [N,M,2] when", "columns are 'geometry', 'id', 'x', 'y') asgrid: [bool] -optional- Should", "\"\"\" if which not in [\"in\",\"out\"]: raise ValueError(\"Which should either", "integration. -> dependency: the integration is made using quadpy. Examples:", "\"\"\" return len(np.shape(self.shape))==2 @property def geodataframe(self): \"\"\" \"\"\" if self._derived_properties[\"geodataframe\"]", "same number of indexes as the number of pixels\") self._side_properties[\"indexes\"]", "grid of triangulation. \"\"\" return Grid.set_from( np.concatenate(self.triangulation, axis=0) ) def", "is made using quadpy. Examples: # Remark the np.stack(x, axis=-1).", "be (structural columns are 'geometry', 'id', 'x', 'y') asgrid: [bool]", "projected_data_array[projected_data.index.values] = projected_data.values return projected_data_array def _project_data_(self, data, use=\"sum\"): \"\"\"", "ops.triangulate(geom) return np.stack([np.asarray(t.exterior.coords.xy).T[:-1] for t in triangles]) if not self.is_shape_unique", "or have the same lenth as pixels\") self._properties[\"shape\"] = np.asarray(shape)", "pixels. Pixels define the position up on which the geometries", "not None): raise ValueError(\"Pixels and shape already defined. set the", "\"\"\" gproj = GridProjector(self, othergrid) if column is None or", "see shapely.ops.triangulate \"\"\" if self._derived_properties[\"triangulation\"] is None: self.derive_triangulation() return self._derived_properties[\"triangulation\"]", "# vertices this.set_vertices(datainput) elif len(np.shape( datainput) ) == 3: #", "__init__(self, grid_in=None, grid_out=None): \"\"\" \"\"\" if grid_in is not None:", "np.sum(val, axis=1) def derive_triangulation(self, fast_unique=True): \"\"\" \"\"\" def triangulate(geom): \"\"\"", "is not None: self.set_grid(grid_out, \"out\") # =================== # # Methods", "3-shaped, this calls set_vertices ; if 2-shaped, this calls set_pixels.", "triangles]) if not self.is_shape_unique or not fast_unique: self._derived_properties[\"triangulation\"] = self.geodataframe[\"geometry\"].apply(triangulate)", "itself projected_data = self._project_data_(self._parse_data_(data), use=use) if as_serie: return projected_data projected_data_array", "asgrid) \"\"\" gproj = GridProjector(self, othergrid) if column is None", "array, something you could to ax.imshow(stamps) data will be stored", "pandas import geopandas # ======================= # # # # Functions" ]
[ "dtype.\" raise ValueError(msg) offset = fp.tell() if fortran_order: order =", "is invalid. IOError If the file is not found or", "numpy.dtype({'names': names, 'formats': formats, 'titles': titles, 'offsets': offsets, 'itemsize': offset})", "method. File extensions --------------- We recommend using the ``.npy`` and", "leave the file object located just after the header. Parameters", "is not a real file object, then this may take", "the fourth element of the header therefore has become: \"The", "the data. See `open_memmap`. - Can be read from a", "else: array.shape = shape return array def open_memmap(filename, mode='r+', dtype=None,", "not round-trip through the format entirely accurately. The data is", "the array. For repeatability and readability, the dictionary keys are", "the file object located just after the header. Parameters ----------", "of the array that will be written to disk. Returns", "pass if len(data) != size: msg = \"EOF: reading %s,", "be 0 <= major < 256\") if minor < 0", "array.flags.f_contiguous and not array.flags.c_contiguous: if isfileobj(fp): array.T.tofile(fp) else: for chunk", "Set buffer size to 16 MiB to hide the Python", "magic string for the given file format version. Parameters ----------", "for the available mode strings. dtype : data-type, optional The", "in this format. This is by no means a requirement;", "Default: None Returns ------- marray : memmap The memory-mapped array.", "of bytes by multiplying the number of elements given by", "== 'w+': mode = 'r+' marray = numpy.memmap(filename, dtype=dtype, shape=shape,", "4096 BUFFER_SIZE = 2**18 # size of buffer for reading", "given file format version. Parameters ---------- major : int in", ": int \"\"\" magic_str = _read_bytes(fp, MAGIC_LEN, \"magic string\") if", "int The shape of the array. For repeatability and readability,", "data is the contiguous (either C- or Fortran-, depending on", "header therefore has become: \"The next 4 bytes form a", "is terminated by a newline (``\\\\n``) and padded with spaces", "them to be written directly to disk for efficiency. \"shape\"", "arrays including nested record arrays and object arrays. - Represents", "the format entirely accurately. The data is intact; only the", "If the array contains Python objects as part of its", "file containing multiple ``.npy`` files, one for each array. Capabilities", "them may raise various errors if the objects are not", "its native binary form. - Supports Fortran-contiguous arrays directly. -", "UnicodeError(\"Unpickling a python object failed: %r\\n\" \"You may need to", "if it is either C-contiguous or Fortran-contiguous. Otherwise, it will", "with time and this document is more current. \"\"\" import", "here, then it should be safe to create the file.", ": dtype The dtype of the array that will be", "filelike object using the 2.0 file format version. This will", "because a 1-D array is both C_CONTIGUOUS and F_CONTIGUOUS. d['fortran_order']", "[] names = [] formats = [] offsets = []", "removed, only \"if name == ''\" needed) is_pad = (name", "is an ASCII string which contains a Python literal expression", "aligned on a # ARRAY_ALIGN byte boundary. This supports memory", "= [] offset = 0 for field in descr: if", "dt.names) elif dt.subdtype is not None: return _has_metadata(dt.base) else: return", "numpy.dtype(dtype) if dtype.hasobject: msg = \"Array can't be memory-mapped: Python", "the array data. If the dtype contains Python objects (i.e.", "array header from a filelike object using the 1.0 file", "isinstance(header, bytes): # always true on python 3 header =", "repeatability and readability, the dictionary keys are sorted in alphabetic", "is None: header = _wrap_header_guess_version(header) else: header = _wrap_header(header, version)", "storage.\", UserWarning, stacklevel=2) if dtype.names is not None: # This", "tokenize.generate_tokens(StringIO(s).readline): token_type = token[0] token_string = token[1] if (last_token_was_number and", "not allow_pickle: raise ValueError(\"Object arrays cannot be saved when \"", "file on disk. This may *not* be a file-like object.", "Read the magic string to get the version of the", "can be interpreted as a dtype object. dtype = numpy.dtype(dtype)", "= read_magic(fp) _check_version(version) shape, fortran_order, dtype = _read_array_header(fp, version) if", "it should be safe to create the file. with open(os_fspath(filename),", "% (MAGIC_PREFIX, magic_str[:-2])) major, minor = magic_str[-2:] return major, minor", "file in \"write\" mode. version : tuple of int (major,", "object A file object or something with a `.read()` method", ": tuple of int The shape of the array. For", "number of elements given by the shape (noting that ``shape=()``", "in d['shape'])): msg = \"shape is not valid: {!r}\" raise", "of the file. version: tuple or None None means use", "to `numpy.dtype()` in order to replicate the input dtype. Returns", "way. # crc32 module fails on reads greater than 2", "offset += dt.itemsize return numpy.dtype({'names': names, 'formats': formats, 'titles': titles,", "a serializable descriptor from the dtype. The .descr attribute of", "structured arrays with a large number of columns. The version", "of the fourth element of the header therefore has become:", "None: return any(_has_metadata(dt[k]) for k in dt.names) elif dt.subdtype is", "object failed: %r\\n\" \"You may need to pass the encoding=", "a record array. The .descr is fine. XXX: parts of", "creating the file, not reading it. # Check if we", "dtype. \"fortran_order\" : bool Whether the array data is Fortran-contiguous", "array. The .descr is fine. XXX: parts of the #", "etc. Such arrays will not round-trip through the format entirely", "any unicode field names. Notes ----- The ``.npy`` format, including", "0 else: # Set buffer size to 16 MiB to", "of the header therefore has become: \"The next 4 bytes", "npz header ints. Cleans up the 'L' in strings representing", "Can be read from a filelike stream object instead of", "not None fmt, encoding = _header_size_info[version] if not isinstance(header, bytes):", "the shape and dtype information necessary to reconstruct the array", "a numpy.ndarray. Parameters ---------- array : numpy.ndarray Returns ------- d", "protocol=3, **pickle_kwargs) elif array.flags.f_contiguous and not array.flags.c_contiguous: if isfileobj(fp): array.T.tofile(fp)", "package. The next 2 bytes form a little-endian unsigned short", "use repr here, since we eval these when reading header.append(\"'%s':", "Cleans up the 'L' in strings representing integers. Needed to", "that ``shape=()`` means there is 1 element) by ``dtype.itemsize``. Format", "array : ndarray The array from the data on disk.", "header of the file first. with open(os_fspath(filename), 'rb') as fp:", "for chunk in numpy.nditer( array, flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize, order='C'):", "dtypes # aligned up to ARRAY_ALIGN on systems like Linux", "# No padding removal needed return numpy.dtype(descr) elif isinstance(descr, tuple):", "# Read the header of the file first. with open(os_fspath(filename),", "can't be non-blocking try: r = fp.read(size - len(data)) data", "in dtype.\" raise ValueError(msg) d = dict( descr=dtype_to_descr(dtype), fortran_order=fortran_order, shape=shape,", "This is for convenience only. A writer SHOULD implement this", "dtype.itemsize == 0 then there's nothing more to read max_read_count", "\"You may need to pass the encoding= option \" \"to", "mode+'b') as fp: _write_array_header(fp, d, version) offset = fp.tell() else:", "BUFFER_SIZE bytes to avoid issue and reduce memory overhead #", "'w+': mode = 'r+' marray = numpy.memmap(filename, dtype=dtype, shape=shape, order=order,", "i.e. arrays containing elements that are arbitrary Python objects. Files", "format is upgraded, the code in `numpy.io` will still be", "filelike object d : dict This has the appropriate entries", "version number of the file format, e.g. ``\\\\x00``. Note: the", "not require a change in the file format. The arrays", "just after the header. .. versionadded:: 1.9.0 Parameters ---------- fp", "1 byte is an unsigned byte: the major version number", "of int The shape of the array. fortran_order : bool", "motivation for creating it and a comparison of alternatives, is", "there's nothing more to read max_read_count = BUFFER_SIZE // min(BUFFER_SIZE,", "invalid. \"\"\" return _read_array_header(fp, version=(1, 0)) def read_array_header_2_0(fp): \"\"\" Read", "b'\\x93NUMPY' MAGIC_LEN = len(MAGIC_PREFIX) + 2 ARRAY_ALIGN = 64 #", "chunk in numpy.nditer( array, flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize, order='C'): fp.write(chunk.tobytes('C'))", "========== A simple format for saving numpy arrays to disk", "dtype = _read_array_header(fp, version) if dtype.hasobject: msg = \"Array can't", "tokenize.untokenize(tokens) def _read_array_header(fp, version): \"\"\" see read_array_header_1_0 \"\"\" # Read", "memory mapping of dtypes # aligned up to ARRAY_ALIGN on", "format, e.g. ``\\\\x00``. Note: the version of the file format", "format is the standard format for persisting *multiple* NumPy arrays", "little-endian short int which has the length of the #", "version) fp.write(header) def write_array_header_1_0(fp, d): \"\"\" Write the header for", "extra memory and time. allow_pickle : bool, optional Whether to", "reads to # BUFFER_SIZE bytes to avoid issue and reduce", "``.npz``. Version numbering ----------------- The version numbering of these formats", "one read is performed. # Use np.ndarray instead of np.empty", "count=read_count) if fortran_order: array.shape = shape[::-1] array = array.transpose() else:", "Python pickle of the array. Otherwise the data is the", "the values. if (not isinstance(d['shape'], tuple) or not all(isinstance(x, int)", "Allows memory-mapping of the data. See `open_memmap`. - Can be", "bool Whether the array data is Fortran-contiguous or not. Since", "raise a ValueError if the format does not allow saving", "\"\"\" if isinstance(descr, str): # No padding removal needed return", "will automatically save in 2.0 format if the data requires", "_header_size_info[version] if not isinstance(header, bytes): # always true on python", "these formats is independent of NumPy version numbering. If the", "The dictionary contains three keys: \"descr\" : dtype.descr An object", "** 2 // array.itemsize, 1) if array.dtype.hasobject: # We contain", "None If the mode is a \"write\" mode, then this", "can be passed to `numpy.dtype()` in order to replicate the", "on disk. The format stores all of the shape and", "for writing, but only the array data will be written", "tuple): # subtype, will always have a shape descr[1] dt", ">= 1.17\", UserWarning, stacklevel=2) return header def _write_array_header(fp, d, version=None):", "numpy.load\" % (err,)) from err else: if isfileobj(fp): # We", "------- header : str Cleaned up header. \"\"\" import tokenize", "`dtype` is ignored. The default value is None, which results", "# header. import struct hinfo = _header_size_info.get(version) if hinfo is", "(not isinstance(d['shape'], tuple) or not all(isinstance(x, int) for x in", "< 256\") if minor < 0 or minor > 255:", "serialization NPY format ========== A simple format for saving numpy", "to get the version of the file format. Parameters ----------", "marray = numpy.memmap(filename, dtype=dtype, shape=shape, order=order, mode=mode, offset=offset) return marray", "------- major : int minor : int \"\"\" magic_str =", "file-like object. mode : str, optional The mode in which", "\"\"\" Return the magic string for the given file format", "version): \"\"\" see read_array_header_1_0 \"\"\" # Read an unsigned, little-endian", "---------- fp : file_like object If this is not a", "``.npy`` and ``.npz`` extensions for files saved in this format.", "magic_str[:-2])) major, minor = magic_str[-2:] return major, minor def _has_metadata(dt):", "2 // array.itemsize, 1) if array.dtype.hasobject: # We contain Python", "values. if (not isinstance(d['shape'], tuple) or not all(isinstance(x, int) for", "a data-type of `float64`. shape : tuple of int The", "descriptor that can be passed to dtype(). Parameters ---------- dtype", "necessary information to reconstruct the array including shape and dtype", "to be fixed in the C implementation of # dtype().", "def open_memmap(filename, mode='r+', dtype=None, shape=None, fortran_order=False, version=None): \"\"\" Open a", "the file. None means use the oldest supported version that", "machine with 32-bit C \"long ints\" will yield an array", "files saved in this format. This is by no means", "'shape'} MAGIC_PREFIX = b'\\x93NUMPY' MAGIC_LEN = len(MAGIC_PREFIX) + 2 ARRAY_ALIGN", "arrays are not to be mmapable, but can be read", "the array. Otherwise the data is the contiguous (either C-", "byte: the major version number of the file format, e.g.", "the file on disk. This may *not* be a file-like", "to disk. Limitations ----------- - Arbitrary subclasses of numpy.ndarray are", "recommend using the ``.npy`` and ``.npz`` extensions for files saved", "= _header_size_info.get(version) if hinfo is None: raise ValueError(\"Invalid version {!r}\".format(version))", "= (token_type == tokenize.NUMBER) return tokenize.untokenize(tokens) def _read_array_header(fp, version): \"\"\"", "a dictionary. It is terminated by a newline (``\\\\n``) and", ": file_like object An open, writable file object, or similar", "ValueError If the data is invalid, or allow_pickle=False and the", "a new file in \"write\" mode, in which case this", "between version 1.0 and 2.0 is a 4 byte (I)", "automatically save in 2.0 format if the data requires it,", "# fiddled with. This needs to be fixed in the", "to create the file. None means use the oldest supported", "are read. Raises ValueError if not EOF is encountered before", "dt.names is None) if not is_pad: title, name = name", "- ((MAGIC_LEN + struct.calcsize(fmt) + hlen) % ARRAY_ALIGN) try: header_prefix", "magic : str Raises ------ ValueError if the version cannot", "writing. Note that we need to test for C_CONTIGUOUS first", "to reverse engineer. Datasets often live longer than the programs", "header = _wrap_header_guess_version(header) else: header = _wrap_header(header, version) fp.write(header) def", "file. Returns ------- shape : tuple of int The shape", "The name of the file on disk. This may *not*", "if we are creating a new file in \"write\" mode,", "correct; expected %r, got %r\" raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2]))", "optional The version number of the format. None means use", "write_array_header_2_0(fp, d): \"\"\" Write the header for an array using", "data. Default: False .. versionchanged:: 1.16.3 Made default False in", "will have the names replaced by 'f0', 'f1', etc. Such", "only support format version (1,0), (2,0), and (3,0), not %s\"", "creating a new file in \"write\" mode, if not, `dtype`", "header for an array and returns the version used Parameters", "the given dtype is an authentic dtype object rather #", "array. Otherwise the data is the contiguous (either C- or", "0)) except UnicodeEncodeError: pass else: warnings.warn(\"Stored array in format 2.0.", "elif array.flags.f_contiguous: d['fortran_order'] = True else: # Totally non-contiguous data.", "(H) allowing storage of large structured arrays _header_size_info = {", "been given without much documentation. - Allows memory-mapping of the", "The memory-mapped array. Raises ------ ValueError If the data or", "with object arrays are not to be mmapable, but can", "string (which in practice was latin1) with a utf8-encoded string,", "----------------- The version numbering of these formats is independent of", "+ struct.calcsize(fmt) + hlen) % ARRAY_ALIGN) try: header_prefix = magic(*version)", "memory and time. allow_pickle : bool, optional Whether to allow", "or None None means use oldest that works explicit version", "that is able to store the data. Default: None Returns", "((MAGIC_LEN + struct.calcsize(fmt) + hlen) % ARRAY_ALIGN) try: header_prefix =", "read from a filelike stream object instead of an actual", "containing elements that are arbitrary Python objects. Files with object", "a valid bool: {!r}\" raise ValueError(msg.format(d['fortran_order'])) try: dtype = descr_to_dtype(d['descr'])", "warnings.warn(\"Stored array in format 3.0. It can only be \"", "# This is a record array. The .descr is fine.", "padlen = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize(fmt) + hlen) %", "element) by ``dtype.itemsize``. Format Version 2.0 ------------------ The version 1.0", "d['fortran_order'] = True else: # Totally non-contiguous data. We will", "array with \"long ints\", a reading machine with 32-bit C", "the default is 'r+'. In addition to the standard file", "io files (default in python3) return None or raise on", "ValueError(msg.format(d['descr'])) from e return d['shape'], d['fortran_order'], dtype def write_array(fp, array,", "4 byte (I) header length # instead of 2 bytes", "0)) warnings.warn(\"Stored array in format 3.0. It can only be", "int) for x in d['shape'])): msg = \"shape is not", "_wrap_header(header, (3, 0)) warnings.warn(\"Stored array in format 3.0. It can", "results in a data-type of `float64`. shape : tuple of", "def descr_to_dtype(descr): \"\"\" Returns a dtype based off the given", "tuple of int (major, minor) or None If the mode", "literal # Python dictionary with trailing newlines padded to a", "of the shape and dtype information necessary to reconstruct the", "if _has_metadata(dtype): warnings.warn(\"metadata on a dtype may be saved or", "* 1024 ** 2 // array.itemsize, 1) if array.dtype.hasobject: #", "there is 1 element) by ``dtype.itemsize``. Format Version 2.0 ------------------", "in sorted(d.items()): # Need to use repr here, since we", "up header. \"\"\" import tokenize from io import StringIO tokens", "# boundary. The keys are strings. # \"shape\" : tuple", "gzip streams. Chunk reads to # BUFFER_SIZE bytes to avoid", "obvious alternative, however, we suggest using ``.npy`` and ``.npz``. Version", "is an unsigned byte: the minor version number of the", "the header of the file. \"\"\" _write_array_header(fp, d, (1, 0))", "of the file format is not tied to the version", "count = 1 else: count = numpy.multiply.reduce(shape, dtype=numpy.int64) # Now", "will have to make it C-contiguous # before writing. Note", "optional The data type of the array if we are", "will yield an array with 64-bit integers. - Is straightforward", "or Fortran-, depending on ``fortran_order``) bytes of the array. Consumers", ": dict This has the appropriate entries for writing its", "ZipExtFile in python 2.6 can return less data than requested.", "details have evolved with time and this document is more", "arrays directly. - Stores all of the necessary information to", "The description of the fourth element of the header therefore", "2 # implementation before header filtering was implemented. if version", "the file format, e.g. ``\\\\x00``. Note: the version of the", "with a large number of columns. The version 2.0 format", "object d : dict This has the appropriate entries for", "the data. Default: None allow_pickle : bool, optional Whether to", "np.ndarray instead of np.empty since the latter does # not", "in format 3.0. It can only be \" \"read by", "of the array. fortran_order : bool The array data will", "is independent of NumPy version numbering. If the format is", "pickled data. Default: True pickle_kwargs : dict, optional Additional keyword", "default is 'r+'. In addition to the standard file modes,", "and time. allow_pickle : bool, optional Whether to allow writing", "an empty name, like padding bytes, still get # fiddled", "have evolved with time and this document is more current.", "array. Capabilities ------------ - Can represent all NumPy arrays including", "data is a Python pickle of the array. Otherwise the", "sorted(d.keys()) msg = \"Header does not contain the correct keys:", "msg = \"Header does not contain the correct keys: {!r}\"", "fmt, encoding = _header_size_info[version] if not isinstance(header, bytes): # always", "array.transpose() else: array.shape = shape return array def open_memmap(filename, mode='r+',", "Due to limitations in the interpretation of structured dtypes, dtypes", "form the header data describing the array's format. It is", "representation to the header of the file. \"\"\" d =", "padding fields created by, i.e. simple fields like dtype('float32'), and", "CVE-2019-6446. pickle_kwargs : dict Additional keyword arguments to pass to", "array to write to disk. version : (int, int) or", "\"\"\" Read from file-like object until size bytes are read.", "a newline (``\\\\n``) and padded with spaces (``\\\\x20``) to make", "time and this document is more current. \"\"\" import numpy", "the data in its native binary form. - Supports Fortran-contiguous", "True elif dt.names is not None: return any(_has_metadata(dt[k]) for k", "subclasses of numpy.ndarray are not completely preserved. Subclasses will be", "arrays with such structures can still be saved and restored,", "the header are aligned on a # ARRAY_ALIGN byte boundary.", "integers. Needed to allow npz headers produced in Python2 to", "to limitations in the interpretation of structured dtypes, dtypes with", "padded with spaces (``\\\\x20``) to make the total of ``len(magic", "little-endian array on any machine reading the file. The types", "Python objects as part of its dtype, the process of", "field with '' as a name. The dtype() constructor interprets", "the default) if we are creating a new file in", "'protocol'. These are only useful when pickling objects in object", "(i.e. the beginning of the file). return header_prefix + header", "data describing the array's format. It is an ASCII string", "{'descr', 'fortran_order', 'shape'} MAGIC_PREFIX = b'\\x93NUMPY' MAGIC_LEN = len(MAGIC_PREFIX) +", "a # ARRAY_ALIGN byte boundary. This supports memory mapping of", "buffersize=buffersize, order='C'): fp.write(chunk.tobytes('C')) def read_array(fp, allow_pickle=False, pickle_kwargs=None): \"\"\" Read an", "or path-like The name of the file on disk. This", "something that can be interpreted as a dtype object. dtype", "be interpreted as a dtype object. dtype = numpy.dtype(dtype) if", "already written data to the file. if mode == 'w+':", "the `numpy.dtype` constructor to create the array's dtype. \"fortran_order\" :", "True``), then the data is a Python pickle of the", "and padding to it \"\"\" import struct assert version is", "* dtype.itemsize) data = _read_bytes(fp, read_size, \"array data\") array[i:i+read_count] =", "is either C-contiguous or Fortran-contiguous. Otherwise, it will be made", "the file. .. warning:: Due to limitations in the interpretation", "------- dtype : dtype The dtype constructed by the description.", "def magic(major, minor): \"\"\" Return the magic string for the", "function. array = numpy.fromfile(fp, dtype=dtype, count=count) else: # This is", "hinfo = _header_size_info.get(version) if hinfo is None: raise ValueError(\"Invalid version", "pickling objects in object arrays on Python 3 to Python", "the mode is a \"write\" mode, then this is the", "up the 'L' in strings representing integers. Needed to allow", "is the standard format for persisting *multiple* NumPy arrays on", "raise ValueError(\"Object arrays cannot be loaded when \" \"allow_pickle=False\") if", "parameter is ignored and is thus optional. fortran_order : bool,", "\"array header\") header = header.decode(encoding) # The header is a", "False .. versionchanged:: 1.16.3 Made default False in response to", "Format Version 3.0 ------------------ This version replaces the ASCII string", "with 64-bit integers. - Is straightforward to reverse engineer. Datasets", "we allow them to be written directly to disk for", "Stores all of the necessary information to reconstruct the array", "default False in response to CVE-2019-6446. pickle_kwargs : dict Additional", "to `numpy.dtype()` in order to replicate the input dtype. \"\"\"", "here, since we eval these when reading header.append(\"'%s': %s, \"", "C-contiguous (False, the default) if we are creating a new", "'L' in strings representing integers. Needed to allow npz headers", "it the # memory-intensive way. # crc32 module fails on", "created them. A competent developer should be able to create", "part of its dtype, the process of pickling them may", "cannot write out the data # directly. Instead, we will", "when using Python 3. Returns ------- array : ndarray The", "not found or cannot be opened correctly. See Also --------", "formatted. \"\"\" if major < 0 or major > 255:", "`dtype_to_descr()`. It will remove the valueless padding fields created by,", "ValueError(msg.format(d)) if EXPECTED_KEYS != d.keys(): keys = sorted(d.keys()) msg =", "return _has_metadata(dt.base) else: return False def dtype_to_descr(dtype): \"\"\" Get a", "= 'C' # We need to change a write-only mode", "npz headers produced in Python2 to be read in Python3.", "the file. version: tuple or None None means use oldest", "# dtype(). return dtype.descr else: return dtype.str def descr_to_dtype(descr): \"\"\"", "field dt = descr_to_dtype(descr_str) else: name, descr_str, shape = field", "writes out an array with \"long ints\", a reading machine", "---------- fp : file_like object An open, writable file object,", "loaded when \" \"allow_pickle=False\") if pickle_kwargs is None: pickle_kwargs =", "longer than the programs that created them. A competent developer", "comparison of alternatives, is described in the :doc:`\"npy-format\" NEP <neps:nep-0001-npy-format>`,", "NumPy for persisting a *single* arbitrary NumPy array on disk.", "This is by no means a requirement; applications may wish", "** 32 bytes, # breaking large reads from gzip streams.", "to create the file. with open(os_fspath(filename), mode+'b') as fp: _write_array_header(fp,", "write Version 1.0 files. Format Version 1.0 ------------------ The first", "retreived by dtype.descr. Can be passed to `numpy.dtype()` in order", "pickle_kwargs = {} pickle.dump(array, fp, protocol=3, **pickle_kwargs) elif array.flags.f_contiguous and", "from an NPY file. Parameters ---------- fp : file_like object", "(None, name) titles.append(title) names.append(name) formats.append(dt) offsets.append(offset) offset += dt.itemsize return", "for blank names is removed, only \"if name == ''\"", "return False def dtype_to_descr(dtype): \"\"\" Get a serializable descriptor from", "we construct descriptor that can be passed to dtype(). Parameters", "b' '*padlen + b'\\n' def _wrap_header_guess_version(header): \"\"\" Like `_wrap_header`, but", "Python dictionary with trailing newlines padded to a ARRAY_ALIGN byte", "_read_bytes(fp, header_length, \"array header\") header = header.decode(encoding) # The header", "\"read by NumPy >= 1.17\", UserWarning, stacklevel=2) return header def", "read the actual data. if dtype.hasobject: # The array contained", "issue and reduce memory overhead # of the read. In", "Memmap cannot use existing file handles.\") if 'w' in mode:", "= header.encode(encoding) hlen = len(header) + 1 padlen = ARRAY_ALIGN", "header size to 4 GiB. `numpy.save` will automatically save in", "version 1.0 format only allowed the array header to have", "Parameters ---------- s : string Npy file header. Returns -------", "== \"L\"): continue else: tokens.append(token) last_token_was_number = (token_type == tokenize.NUMBER)", "tokens = [] last_token_was_number = False for token in tokenize.generate_tokens(StringIO(s).readline):", "attribute of a dtype object cannot be round-tripped through the", "dtype on a machine of a different architecture. Both little-endian", ": object The object retreived by dtype.descr. Can be passed", "an array using the 2.0 format. The 2.0 format allows", "int # \"fortran_order\" : bool # \"descr\" : dtype.descr #", "including a header. If the array is neither C-contiguous nor", "we are creating a new file in \"write\" mode, in", "or cannot be opened correctly. See Also -------- numpy.memmap \"\"\"", "The next HEADER_LEN bytes form the header data describing the", "shape and dtype information necessary to reconstruct the array correctly", "alphabetic order. This is for convenience only. A writer SHOULD", "with a 64-bit C \"long int\" writes out an array", "= _read_array_header(fp, version) if len(shape) == 0: count = 1", "# already written data to the file. if mode ==", "raise ValueError(\"Object arrays cannot be saved when \" \"allow_pickle=False\") if", "with spaces (``\\\\x20``) to make the total of ``len(magic string)", "dtype = _read_array_header(fp, version) if len(shape) == 0: count =", "The shape of the array if we are creating a", "where mmap() # offset must be page-aligned (i.e. the beginning", "after the header. .. versionadded:: 1.9.0 Parameters ---------- fp :", ": filelike object Returns ------- major : int minor :", "array, version=None, allow_pickle=True, pickle_kwargs=None): \"\"\" Write an array to an", "raise UnicodeError(\"Unpickling a python object failed: %r\\n\" \"You may need", "a comparison of alternatives, is described in the :doc:`\"npy-format\" NEP", "parameter is required. Otherwise, this parameter is ignored and is", "from a filelike object using the 2.0 file format version.", "255: raise ValueError(\"minor version must be 0 <= minor <", "raise ValueError(\"Invalid version {!r}\".format(version)) hlength_type, encoding = hinfo hlength_str =", "``loadedarray.view(correct_dtype)`` method. File extensions --------------- We recommend using the ``.npy``", "except SyntaxError as e: msg = \"Cannot parse header: {!r}\"", "arrays saved on Python 2 when using Python 3. Returns", "Python objects (i.e. ``dtype.hasobject is True``), then the data is", "the dictionary of header metadata from a numpy.ndarray. Parameters ----------", "is the contiguous (either C- or Fortran-, depending on ``fortran_order``)", "always true on python 3 header = header.encode(encoding) hlen =", "= \"Array can't be memory-mapped: Python objects in dtype.\" raise", "dtype object rather # than just something that can be", "large reads from gzip streams. Chunk reads to # BUFFER_SIZE", "encoding = hinfo hlength_str = _read_bytes(fp, struct.calcsize(hlength_type), \"array header length\")", "will still be able to read and write Version 1.0", "NumPy >= 1.9\", UserWarning, stacklevel=2) return ret header = _wrap_header(header,", "fix for this. This fix will not require a change", "removal needed return numpy.dtype(descr) elif isinstance(descr, tuple): # subtype, will", "data type of the array if we are creating a", "write-only mode to a read-write mode since we've # already", "def _filter_header(s): \"\"\"Clean up 'L' in npz header ints. Cleans", "'r+'. In addition to the standard file modes, 'c' is", "A competent developer should be able to create a solution", "the header for an array and returns the version used", "in terms of their actual sizes. For example, if a", "the version of the file format is not tied to", "descr_to_dtype(descr_str) else: name, descr_str, shape = field dt = numpy.dtype((descr_to_dtype(descr_str),", "in order to replicate the input dtype. Returns ------- dtype", "True pickle_kwargs : dict, optional Additional keyword arguments to pass", "types with any unicode field names. Notes ----- The ``.npy``", "read and write Version 1.0 files. Format Version 1.0 ------------------", "(major, minor) or None If the mode is a \"write\"", "pickle_kwargs = {} try: array = pickle.load(fp, **pickle_kwargs) except UnicodeError", "== 0 or len(data) == size: break except io.BlockingIOError: pass", "int \"\"\" magic_str = _read_bytes(fp, MAGIC_LEN, \"magic string\") if magic_str[:-2]", "numpy.dtype((descr_to_dtype(descr_str), shape)) # Ignore padding bytes, which will be void", "Use np.ndarray instead of np.empty since the latter does #", "------ ValueError If the data is invalid. \"\"\" return _read_array_header(fp,", "excluding 'protocol'. These are only useful when pickling objects in", "supported if they derive from io objects. Required as e.g.", "ValueError If the array cannot be persisted. This includes the", "len(field) == 2: name, descr_str = field dt = descr_to_dtype(descr_str)", "be memory-mapped: Python objects in dtype.\" raise ValueError(msg) offset =", "files can't be non-blocking try: r = fp.read(size - len(data))", "**pickle_kwargs) elif array.flags.f_contiguous and not array.flags.c_contiguous: if isfileobj(fp): array.T.tofile(fp) else:", "means there is 1 element) by ``dtype.itemsize``. Format Version 2.0", "compatible 1.0 format. The description of the fourth element of", ": memmap The memory-mapped array. Raises ------ ValueError If the", "dtype.itemsize) data = _read_bytes(fp, read_size, \"array data\") array[i:i+read_count] = numpy.frombuffer(data,", "object arrays are not to be mmapable, but can be", "file contains an object array. \"\"\" version = read_magic(fp) _check_version(version)", "header_prefix = magic(*version) + struct.pack(fmt, hlen + padlen) except struct.error:", "Version 3.0 ------------------ This version replaces the ASCII string (which", "with a ``.write()`` method. array : ndarray The array to", "// min(BUFFER_SIZE, dtype.itemsize) for i in range(0, count, max_read_count): read_count", "figure out the number of bytes by multiplying the number", "file, not reading it. # Check if we ought to", "name. The dtype() constructor interprets this as a request to", "MAGIC_LEN = len(MAGIC_PREFIX) + 2 ARRAY_ALIGN = 64 # plausible", "be 0 <= minor < 256\") return MAGIC_PREFIX + bytes([major,", "array = numpy.ndarray(count, dtype=dtype) if dtype.itemsize > 0: # If", "file. \"\"\" _write_array_header(fp, d, (1, 0)) def write_array_header_2_0(fp, d): \"\"\"", "is required. Otherwise, this parameter is ignored and is thus", "persisting a *single* arbitrary NumPy array on disk. The format", "which results in a data-type of `float64`. shape : tuple", "# string, the header-length short and the header are aligned", "tuple of int The shape of the array. fortran_order :", "% (version,)) def magic(major, minor): \"\"\" Return the magic string", "if not isinstance(d, dict): msg = \"Header is not a", "\"\"\" if major < 0 or major > 255: raise", "an unsigned, little-endian short int which has the length of", "an object array. \"\"\" version = read_magic(fp) _check_version(version) shape, fortran_order,", "d['fortran_order'] = False elif array.flags.f_contiguous: d['fortran_order'] = True else: #", "of storage.\", UserWarning, stacklevel=2) if dtype.names is not None: #", "python 3 header = header.encode(encoding) hlen = len(header) + 1", "\"we only support format version (1,0), (2,0), and (3,0), not", "bytes form a little-endian unsigned int: the length of the", "an unsigned byte: the minor version number of the file", "yield a little-endian array on any machine reading the file.", "was implemented. if version <= (2, 0): header = _filter_header(header)", "object will be created upon reading the file. .. warning::", "array = pickle.load(fp, **pickle_kwargs) except UnicodeError as err: # Friendlier", "can figure out the number of bytes by multiplying the", "to read an existing file or create a new one.", "of structured dtypes, dtypes with fields with empty names will", "to allow writing pickled data. Default: True pickle_kwargs : dict,", "are read. Non-blocking objects only supported if they derive from", "requirement; applications may wish to use these file formats but", "process of pickling them may raise various errors if the", "Ensure that the given dtype is an authentic dtype object", "min(BUFFER_SIZE, dtype.itemsize) for i in range(0, count, max_read_count): read_count =", "have been created by a Python 2 # implementation before", "else: header = _wrap_header(header, version) fp.write(header) def write_array_header_1_0(fp, d): \"\"\"", "_wrap_header(header, version): \"\"\" Takes a stringified header, and attaches the", "array being an object array. Various other errors If the", "+ struct.pack(fmt, hlen + padlen) except struct.error: msg = \"Header", "except struct.error: msg = \"Header length {} too big for", "of the file first. with open(os_fspath(filename), 'rb') as fp: version", "= 1 else: count = numpy.multiply.reduce(shape, dtype=numpy.int64) # Now read", "got %r\" raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2])) major, minor =", "for token in tokenize.generate_tokens(StringIO(s).readline): token_type = token[0] token_string = token[1]", "Format Version 2.0 ------------------ The version 1.0 format only allowed", "a 4 byte (I) header length # instead of 2", "we are creating a new file in \"write\" mode. version", "in python 2.6 can return less data than requested. \"\"\"", "d def _wrap_header(header, version): \"\"\" Takes a stringified header, and", "array including shape and dtype on a machine of a", "addition to the standard file modes, 'c' is also accepted", "# before writing. Note that we need to test for", "ndarray The array to write to disk. version : (int,", "Consumers can figure out the number of bytes by multiplying", "will be written out directly if it is either C-contiguous", "version <= (2, 0): header = _filter_header(header) try: d =", "dtype of the file's data. Raises ------ ValueError If the", "\"\"\" _check_version(version) _write_array_header(fp, header_data_from_array_1_0(array), version) if array.itemsize == 0: buffersize", "\"\".join(header) if version is None: header = _wrap_header_guess_version(header) else: header", "= [] last_token_was_number = False for token in tokenize.generate_tokens(StringIO(s).readline): token_type", "is designed to be as simple as possible while achieving", "in numpy.nditer( array, flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize, order='C'): fp.write(chunk.tobytes('C')) def", "fiddled with. This needs to be fixed in the C", "\"\"\" Read an array from an NPY file. Parameters ----------", "modes, 'c' is also accepted to mean \"copy on write.\"", "# Ensure that the given dtype is an authentic dtype", "mode: # We are creating the file, not reading it.", "numpy.fromfile(fp, dtype=dtype, count=count) else: # This is not a real", "arrays, i.e. arrays containing elements that are arbitrary Python objects.", "evenly divisible by 64 for alignment purposes. The dictionary contains", "= b'\\x93NUMPY' MAGIC_LEN = len(MAGIC_PREFIX) + 2 ARRAY_ALIGN = 64", "_has_metadata(dtype): warnings.warn(\"metadata on a dtype may be saved or ignored,", "try: d = safe_eval(header) except SyntaxError as e: msg =", "- Stores all of the necessary information to reconstruct the", "version that is able to store the data. Default: None", "object is not a real file object, this function will", "dtype=dtype) if dtype.itemsize > 0: # If dtype.itemsize == 0", "however, we suggest using ``.npy`` and ``.npz``. Version numbering -----------------", "Read an unsigned, little-endian short int which has the length", "this format. This is by no means a requirement; applications", "msg = \"fortran_order is not a valid bool: {!r}\" raise", "Raises ------ ValueError If the data is invalid, or allow_pickle=False", "The data type of the array if we are creating", "authentic dtype object rather # than just something that can", "assert version is not None fmt, encoding = _header_size_info[version] if", "header : str Cleaned up header. \"\"\" import tokenize from", "contains an object array. \"\"\" version = read_magic(fp) _check_version(version) shape,", "\"\"\" if _has_metadata(dtype): warnings.warn(\"metadata on a dtype may be saved", "is described in the :doc:`\"npy-format\" NEP <neps:nep-0001-npy-format>`, however details have", "the mode is invalid. IOError If the file is not", "if dtype.itemsize > 0: # If dtype.itemsize == 0 then", "then this is the version of the file format used", "only useful when pickling objects in object arrays on Python", "appropriate version given the contents \"\"\" try: return _wrap_header(header, (1,", "\"\"\" _write_array_header(fp, d, (2, 0)) def read_array_header_1_0(fp): \"\"\" Read an", "and array being an object array. Various other errors If", "0: count = 1 else: count = numpy.multiply.reduce(shape, dtype=numpy.int64) #", "# Ignore padding bytes, which will be void bytes with", "object, or similar object with a ``.write()`` method. array :", "= descr_to_dtype(d['descr']) except TypeError as e: msg = \"descr is", "the reverse of `dtype_to_descr()`. It will remove the valueless padding", "= len(MAGIC_PREFIX) + 2 ARRAY_ALIGN = 64 # plausible values", "alternative, however, we suggest using ``.npy`` and ``.npz``. Version numbering", "marray : memmap The memory-mapped array. Raises ------ ValueError If", "+ bytes([major, minor]) def read_magic(fp): \"\"\" Read the magic string", "on python 3 header = header.encode(encoding) hlen = len(header) +", "if array.flags.c_contiguous: d['fortran_order'] = False elif array.flags.f_contiguous: d['fortran_order'] = True", "than just something that can be interpreted as a dtype", "str Raises ------ ValueError if the version cannot be formatted.", "only be\" \"read by NumPy >= 1.9\", UserWarning, stacklevel=2) return", "np.empty since the latter does # not correctly instantiate zero-width", "_write_array_header(fp, d, version) offset = fp.tell() else: # Read the", ": tuple of int # \"fortran_order\" : bool # \"descr\"", "the standard binary file format in NumPy for persisting a", "standard format for persisting *multiple* NumPy arrays on disk. A", "the data is the contiguous (either C- or Fortran-, depending", "last_token_was_number = False for token in tokenize.generate_tokens(StringIO(s).readline): token_type = token[0]", "bytes are read. Non-blocking objects only supported if they derive", "\"\"\" Get the dictionary of header metadata from a numpy.ndarray.", "then it should be safe to create the file. with", "os_fspath, pickle ) __all__ = [] EXPECTED_KEYS = {'descr', 'fortran_order',", "dtype.descr An object that can be passed as an argument", "'utf8'), } def _check_version(version): if version not in [(1, 0),", "of int The shape of the array if we are", "'f0', 'f1', etc. Such arrays will not round-trip through the", "version 2.0 format extends the header size to 4 GiB.", "------------------ The version 1.0 format only allowed the array header", "isfileobj, os_fspath, pickle ) __all__ = [] EXPECTED_KEYS = {'descr',", "constructor to create the array's dtype. \"fortran_order\" : bool Whether", "arrays cannot be loaded when \" \"allow_pickle=False\") if pickle_kwargs is", "descr[1])) titles = [] names = [] formats = []", "e if not isinstance(d, dict): msg = \"Header is not", "MUST NOT depend on this. Following the header comes the", ": bool, optional Whether to allow writing pickled data. Default:", "file. We have to read it the # memory-intensive way.", "---------- major : int in [0, 255] minor : int", "4 bytes form a little-endian unsigned int: the length of", "UserWarning, stacklevel=2) return ret header = _wrap_header(header, (3, 0)) warnings.warn(\"Stored", "different architecture. Both little-endian and big-endian arrays are supported, and", "not allow saving this data. Default: None \"\"\" header =", "(3, 0), None]: msg = \"we only support format version", "minor): \"\"\" Return the magic string for the given file", "python3) return None or raise on # would-block, python2 file", "be evenly divisible by 64 for alignment purposes. The dictionary", "out the number of bytes by multiplying the number of", "return _wrap_header(header, (1, 0)) except ValueError: pass try: ret =", "`open_memmap`. - Can be read from a filelike stream object", "_read_bytes(fp, struct.calcsize(hlength_type), \"array header length\") header_length = struct.unpack(hlength_type, hlength_str)[0] header", "(1, 0) could have been created by a Python 2", "64-bit integers. - Is straightforward to reverse engineer. Datasets often", "Python objects. Files with object arrays are not to be", "optional The mode in which to open the file; the", "dtype.descr else: return dtype.str def descr_to_dtype(descr): \"\"\" Returns a dtype", "We need to unpickle the data. if not allow_pickle: raise", ") __all__ = [] EXPECTED_KEYS = {'descr', 'fortran_order', 'shape'} MAGIC_PREFIX", "except UnicodeEncodeError: pass else: warnings.warn(\"Stored array in format 2.0. It", "fp : filelike object d : dict This has the", "header, and attaches the prefix and padding to it \"\"\"", "d = safe_eval(header) except SyntaxError as e: msg = \"Cannot", "one for each array. Capabilities ------------ - Can represent all", "argument to the `numpy.dtype` constructor to create the array's dtype.", "still get # fiddled with. This needs to be fixed", "the contiguous (either C- or Fortran-, depending on ``fortran_order``) bytes", "1) if array.dtype.hasobject: # We contain Python objects so we", "data is invalid. \"\"\" return _read_array_header(fp, version=(2, 0)) def _filter_header(s):", "array.tofile(fp) else: for chunk in numpy.nditer( array, flags=['external_loop', 'buffered', 'zerosize_ok'],", "token[1] if (last_token_was_number and token_type == tokenize.NAME and token_string ==", "allow writing pickled data. Default: False .. versionchanged:: 1.16.3 Made", "the data is invalid. \"\"\" return _read_array_header(fp, version=(2, 0)) def", "for each array. Capabilities ------------ - Can represent all NumPy", "read. In non-chunked case count < max_read_count, so # only", "[(1, 0), (2, 0), (3, 0), None]: msg = \"we", "that will be written to disk. Returns ------- descr :", "of large structured arrays _header_size_info = { (1, 0): ('<H',", "of the file format, e.g. ``\\\\x00``. Note: the version of", "greater than 2 ** 32 bytes, # breaking large reads", "Get the dictionary of header metadata from a numpy.ndarray. Parameters", "be non-blocking try: r = fp.read(size - len(data)) data +=", "dtype contains Python objects (i.e. ``dtype.hasobject is True``), then the", "store the data. Default: None allow_pickle : bool, optional Whether", "to give a default name. Instead, we construct descriptor that", "try: dtype = descr_to_dtype(d['descr']) except TypeError as e: msg =", "The next 1 byte is an unsigned byte: the major", "file with little-endian numbers will yield a little-endian array on", "int: the length of the header data HEADER_LEN. The next", "> 255: raise ValueError(\"minor version must be 0 <= minor", "file. \"\"\" d = {'shape': array.shape} if array.flags.c_contiguous: d['fortran_order'] =", "and the header are aligned on a # ARRAY_ALIGN byte", "If the data is invalid. \"\"\" return _read_array_header(fp, version=(1, 0))", "dtype is an authentic dtype object rather # than just", "if fortran_order: order = 'F' else: order = 'C' #", "in bytes # difference between version 1.0 and 2.0 is", "subtype, will always have a shape descr[1] dt = descr_to_dtype(descr[0])", "e: msg = \"Cannot parse header: {!r}\" raise ValueError(msg.format(header)) from", "file object, or similar object with a ``.write()`` method. array", "\"magic string\") if magic_str[:-2] != MAGIC_PREFIX: msg = \"the magic", "If the data is invalid, or allow_pickle=False and the file", "# Sanity-check the values. if (not isinstance(d['shape'], tuple) or not", "open(os_fspath(filename), mode+'b') as fp: _write_array_header(fp, d, version) offset = fp.tell()", "the file object located just after the header. .. versionadded::", "instantiate zero-width string dtypes; see # https://github.com/numpy/numpy/pull/6430 array = numpy.ndarray(count,", "= _wrap_header_guess_version(header) else: header = _wrap_header(header, version) fp.write(header) def write_array_header_1_0(fp,", "------- descr : object An object that can be passed", "accurately. The data is intact; only the field names will", "for saving numpy arrays to disk with the full information", "numpy.nditer( array, flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize, order='C'): fp.write(chunk.tobytes('C')) def read_array(fp,", "also accepted to mean \"copy on write.\" See `memmap` for", "have to read it the # memory-intensive way. # crc32", "bytes([major, minor]) def read_magic(fp): \"\"\" Read the magic string to", "bytes (H) allowing storage of large structured arrays _header_size_info =", "\"\"\" _write_array_header(fp, d, (1, 0)) def write_array_header_2_0(fp, d): \"\"\" Write", "The data is intact; only the field names will differ.", "# Pad the header with spaces and a final newline", "d, (2, 0)) def read_array_header_1_0(fp): \"\"\" Read an array header", "writing pickled data. Default: True pickle_kwargs : dict, optional Additional", "the file format, e.g. ``\\\\x01``. The next 1 byte is", "Once support for blank names is removed, only \"if name", "optional Whether to allow writing pickled data. Default: False ..", "dtype.itemsize) for i in range(0, count, max_read_count): read_count = min(max_read_count,", "try: ret = _wrap_header(header, (2, 0)) except UnicodeEncodeError: pass else:", "are creating a new file in \"write\" mode. version :", "<= minor < 256\") return MAGIC_PREFIX + bytes([major, minor]) def", "memmap The memory-mapped array. Raises ------ ValueError If the data", "= min(max_read_count, count - i) read_size = int(read_count * dtype.itemsize)", "to create the file. _check_version(version) # Ensure that the given", "create the array's dtype. \"fortran_order\" : bool Whether the array", "memory-mapping of the data. See `open_memmap`. - Can be read", "else: # This is not a real file. We have", "!= d.keys(): keys = sorted(d.keys()) msg = \"Header does not", "less data than requested. \"\"\" data = bytes() while True:", "information to reconstruct the array including shape and dtype on", "= header.decode(encoding) # The header is a pretty-printed string representation", "of the file. \"\"\" d = {'shape': array.shape} if array.flags.c_contiguous:", "file_like object is not a real file object, this function", "pickle of the array. Otherwise the data is the contiguous", "None None means use oldest that works explicit version will", "Can represent all NumPy arrays including nested record arrays and", "only. A writer SHOULD implement this if possible. A reader", "stacklevel=2) return header def _write_array_header(fp, d, version=None): \"\"\" Write the", "it out if not allow_pickle: raise ValueError(\"Object arrays cannot be", "Both little-endian and big-endian arrays are supported, and a file", "= dtype_to_descr(array.dtype) return d def _wrap_header(header, version): \"\"\" Takes a", "as err: # Friendlier error message raise UnicodeError(\"Unpickling a python", "with one field with '' as a name. The dtype()", "a new file in \"write\" mode, if not, `dtype` is", "file in \"write\" mode, if not, `dtype` is ignored. The", "arrays on Python 3 to Python 2 compatible format. Raises", "minor = magic_str[-2:] return major, minor def _has_metadata(dt): if dt.metadata", "warnings.warn(\"Stored array in format 2.0. It can only be\" \"read", "and then convert the description to its corresponding dtype. Parameters", "ValueError(msg % (MAGIC_PREFIX, magic_str[:-2])) major, minor = magic_str[-2:] return major,", "a common form of non-C-contiguity, we allow them to be", "the 1.0 file format version. This will leave the file", "pickle_kwargs=None): \"\"\" Read an array from an NPY file. Parameters", "# The array contained Python objects. We need to unpickle", "multiple ``.npy`` files, one for each array. Capabilities ------------ -", "architecture. Both little-endian and big-endian arrays are supported, and a", "file format, e.g. ``\\\\x00``. Note: the version of the file", "is both C_CONTIGUOUS and F_CONTIGUOUS. d['fortran_order'] = False d['descr'] =", "file or create a new one. Parameters ---------- filename :", "format. It is an ASCII string which contains a Python", "if fortran_order: array.shape = shape[::-1] array = array.transpose() else: array.shape", "of the # record array with an empty name, like", "padding to it \"\"\" import struct assert version is not", "if possible. A reader MUST NOT depend on this. Following", "be Fortran-contiguous (True) or C-contiguous (False, the default) if we", "alignment purposes. The dictionary contains three keys: \"descr\" : dtype.descr", "data. Default: True pickle_kwargs : dict, optional Additional keyword arguments", ": string Npy file header. Returns ------- header : str", "= 'F' else: order = 'C' # We need to", "to open the file; the default is 'r+'. In addition", "\"\"\" version = read_magic(fp) _check_version(version) shape, fortran_order, dtype = _read_array_header(fp,", "{!r}\" raise ValueError(msg.format(d['fortran_order'])) try: dtype = descr_to_dtype(d['descr']) except TypeError as", "of their actual sizes. For example, if a machine with", "dtype = descr_to_dtype(d['descr']) except TypeError as e: msg = \"descr", "the version of the numpy package. The next 2 bytes", "for k in dt.names) elif dt.subdtype is not None: return", "6 bytes are a magic string: exactly ``\\\\x93NUMPY``. The next", "\"raise if saved when read. Use another form of storage.\",", "0) and (1, 0) could have been created by a", "write.\" See `memmap` for the available mode strings. dtype :", "a large number of columns. The version 2.0 format extends", "read. Raises ValueError if not EOF is encountered before size", "will pickle it out if not allow_pickle: raise ValueError(\"Object arrays", "be written to disk. Returns ------- descr : object An", "struct.unpack(hlength_type, hlength_str)[0] header = _read_bytes(fp, header_length, \"array header\") header =", "as e: msg = \"descr is not a valid dtype", "mmap() # offset must be page-aligned (i.e. the beginning of", "magic string is not correct; expected %r, got %r\" raise", "optional Whether the array should be Fortran-contiguous (True) or C-contiguous", "an argument to the `numpy.dtype` constructor to create the array's", "Returns ------- shape : tuple of int The shape of", "beginning of the file). return header_prefix + header + b'", "save in 2.0 format if the data requires it, else", "Get a serializable descriptor from the dtype. The .descr attribute", "nothing more to read max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize)", "len(header) + 1 padlen = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize(fmt)", "(err,)) from err else: if isfileobj(fp): # We can use", "C_CONTIGUOUS and F_CONTIGUOUS. d['fortran_order'] = False d['descr'] = dtype_to_descr(array.dtype) return", "string) + 2 + len(length) + HEADER_LEN`` be evenly divisible", "isinstance(d['fortran_order'], bool): msg = \"fortran_order is not a valid bool:", "numpy.memmap(filename, dtype=dtype, shape=shape, order=order, mode=mode, offset=offset) return marray def _read_bytes(fp,", "_write_array_header(fp, header_data_from_array_1_0(array), version) if array.itemsize == 0: buffersize = 0", "def _check_version(version): if version not in [(1, 0), (2, 0),", "offset = fp.tell() else: # Read the header of the", "Subclasses will be accepted for writing, but only the array", "array. fortran_order : bool The array data will be written", "then there's nothing more to read max_read_count = BUFFER_SIZE //", "full information about them. The ``.npy`` format is the standard", "is not a real file. We have to read it", "ValueError(\"Object arrays cannot be saved when \" \"allow_pickle=False\") if pickle_kwargs", "and this document is more current. \"\"\" import numpy import", "def header_data_from_array_1_0(array): \"\"\" Get the dictionary of header metadata from", "file format version. Parameters ---------- major : int in [0,", "array.shape = shape return array def open_memmap(filename, mode='r+', dtype=None, shape=None,", "in a data-type of `float64`. shape : tuple of int", "IOError If the file is not found or cannot be", "None or raise on # would-block, python2 file will truncate,", "systems like Linux where mmap() # offset must be page-aligned", "to a ARRAY_ALIGN byte # boundary. The keys are strings.", "struct.error: msg = \"Header length {} too big for version={}\".format(hlen,", "and the correct dtype may be restored by using the", "elif dt.names is not None: return any(_has_metadata(dt[k]) for k in", "the 2.0 file format version. This will leave the file", "numbering ----------------- The version numbering of these formats is independent", "= numpy.dtype((descr_to_dtype(descr_str), shape)) # Ignore padding bytes, which will be", "is not None: return True elif dt.names is not None:", "< 0 or major > 255: raise ValueError(\"major version must", "# Versions (2, 0) and (1, 0) could have been", "\"descr is not a valid dtype descriptor: {!r}\" raise ValueError(msg.format(d['descr']))", "got here, then it should be safe to create the", "files in bytes # difference between version 1.0 and 2.0", "file-like object until size bytes are read. Raises ValueError if", "hlength_str)[0] header = _read_bytes(fp, header_length, \"array header\") header = header.decode(encoding)", "object rather # than just something that can be interpreted", "(2, 0): ('<I', 'latin1'), (3, 0): ('<I', 'utf8'), } def", "max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize) for i in range(0,", ": numpy.ndarray Returns ------- d : dict This has the", "constructor. Simple types, like dtype('float32'), have a descr which looks", "data\") array[i:i+read_count] = numpy.frombuffer(data, dtype=dtype, count=read_count) if fortran_order: array.shape =", "from numpy.lib.utils import safe_eval from numpy.compat import ( isfileobj, os_fspath,", "since the latter does # not correctly instantiate zero-width string", "1.9.0 Parameters ---------- fp : filelike object d : dict", "array's dtype. \"fortran_order\" : bool Whether the array data is", "magic # string, the header-length short and the header are", "be written out directly if it is either C-contiguous or", "dictionary with trailing newlines padded to a ARRAY_ALIGN byte #", "described in the :doc:`\"npy-format\" NEP <neps:nep-0001-npy-format>`, however details have evolved", "loading object arrays saved on Python 2 when using Python", "Returns a dtype based off the given description. This is", "can still be saved and restored, and the correct dtype", "ARRAY_ALIGN on systems like Linux where mmap() # offset must", "file format is not tied to the version of the", "structured arrays _header_size_info = { (1, 0): ('<H', 'latin1'), (2,", "\"\"\" Read the magic string to get the version of", "read_array_header_2_0(fp): \"\"\" Read an array header from a filelike object", "The format is designed to be as simple as possible", "objects are not picklable. \"\"\" _check_version(version) _write_array_header(fp, header_data_from_array_1_0(array), version) if", "!= size: msg = \"EOF: reading %s, expected %d bytes", "Version 1.0 files. Format Version 1.0 ------------------ The first 6", "dtype object cannot be round-tripped through the dtype() constructor. Simple", "(MAGIC_PREFIX, magic_str[:-2])) major, minor = magic_str[-2:] return major, minor def", "== 0: count = 1 else: count = numpy.multiply.reduce(shape, dtype=numpy.int64)", "ret = _wrap_header(header, (2, 0)) except UnicodeEncodeError: pass else: warnings.warn(\"Stored", "\"the magic string is not correct; expected %r, got %r\"", "change a write-only mode to a read-write mode since we've", "C_CONTIGUOUS first # because a 1-D array is both C_CONTIGUOUS", "a header. If the array is neither C-contiguous nor Fortran-contiguous", "objects as part of its dtype, the process of pickling", "2**18 # size of buffer for reading npz files in", "min(max_read_count, count - i) read_size = int(read_count * dtype.itemsize) data", "latter does # not correctly instantiate zero-width string dtypes; see", "object located just after the header. Parameters ---------- fp :", "allow_pickle=False and the file contains an object array. \"\"\" version", "will yield a little-endian array on any machine reading the", "version numbering. If the format is upgraded, the code in", "invalid, or allow_pickle=False and the file contains an object array.", "not, `dtype` is ignored. The default value is None, which", "``fortran_order``) bytes of the array. Consumers can figure out the", "however details have evolved with time and this document is", "directly to disk for efficiency. \"shape\" : tuple of int", "data is intact; only the field names will differ. We", "limitations in the interpretation of structured dtypes, dtypes with fields", "bytes of the array. Consumers can figure out the number", "and 2.0 is a 4 byte (I) header length #", "to read most ``.npy`` files that they have been given", "restored, and the correct dtype may be restored by using", "which has the length of the # header. import struct", "header comes the array data. If the dtype contains Python", "2 ARRAY_ALIGN = 64 # plausible values are powers of", "Represents the data in its native binary form. - Supports", "def write_array_header_2_0(fp, d): \"\"\" Write the header for an array", "not correctly instantiate zero-width string dtypes; see # https://github.com/numpy/numpy/pull/6430 array", "to # BUFFER_SIZE bytes to avoid issue and reduce memory", "both C_CONTIGUOUS and F_CONTIGUOUS. d['fortran_order'] = False d['descr'] = dtype_to_descr(array.dtype)", "out directly if it is either C-contiguous or Fortran-contiguous. Otherwise,", "+= dt.itemsize return numpy.dtype({'names': names, 'formats': formats, 'titles': titles, 'offsets':", "string representation to the header of the file. version: tuple", "Returns ------- header : str Cleaned up header. \"\"\" import", "not picklable. \"\"\" _check_version(version) _write_array_header(fp, header_data_from_array_1_0(array), version) if array.itemsize ==", "file object, this function will have to copy data in", "will \" \"raise if saved when read. Use another form", "a record array with one field with '' as a", "writing, but only the array data will be written out.", "header ints. Cleans up the 'L' in strings representing integers.", "\"array header length\") header_length = struct.unpack(hlength_type, hlength_str)[0] header = _read_bytes(fp,", "a dtype object. dtype = numpy.dtype(dtype) if dtype.hasobject: msg =", "arrays will not round-trip through the format entirely accurately. The", "next 1 byte is an unsigned byte: the minor version", "data is invalid. \"\"\" return _read_array_header(fp, version=(1, 0)) def read_array_header_2_0(fp):", "read_size, \"array data\") array[i:i+read_count] = numpy.frombuffer(data, dtype=dtype, count=read_count) if fortran_order:", "(key, repr(value))) header.append(\"}\") header = \"\".join(header) if version is None:", "cannot be persisted. This includes the case of allow_pickle=False and", "reconstruct the array including shape and dtype on a machine", "form a little-endian unsigned int: the length of the header", "\"\"\" Binary serialization NPY format ========== A simple format for", "have a descr which looks like a record array with", "is None: pickle_kwargs = {} try: array = pickle.load(fp, **pickle_kwargs)", "int: the length of the header data HEADER_LEN.\" Format Version", "on this. Following the header comes the array data. If", "break except io.BlockingIOError: pass if len(data) != size: msg =", "file as a memory-mapped array. This may be used to", "= 'r+' marray = numpy.memmap(filename, dtype=dtype, shape=shape, order=order, mode=mode, offset=offset)", "_write_array_header(fp, d, (2, 0)) def read_array_header_1_0(fp): \"\"\" Read an array", "{} too big for version={}\".format(hlen, version) raise ValueError(msg) from None", "efficiency. \"shape\" : tuple of int The shape of the", "is the version of the file format used to create", "not correct; expected %r, got %r\" raise ValueError(msg % (MAGIC_PREFIX,", "encoding = _header_size_info[version] if not isinstance(header, bytes): # always true", "a descr which looks like a record array with one", "means use oldest that works explicit version will raise a", "_check_version(version): if version not in [(1, 0), (2, 0), (3,", "data # directly. Instead, we will pickle it out if", "= int(read_count * dtype.itemsize) data = _read_bytes(fp, read_size, \"array data\")", "cannot be loaded when \" \"allow_pickle=False\") if pickle_kwargs is None:", "order = 'C' # We need to change a write-only", "(which in practice was latin1) with a utf8-encoded string, so", "with any unicode field names. Notes ----- The ``.npy`` format,", "format does not allow saving this data. Default: None \"\"\"", "writable file object, or similar object with a ``.write()`` method.", "The dtype() constructor interprets this as a request to give", "header. \"\"\" import tokenize from io import StringIO tokens =", "This includes the case of allow_pickle=False and array being an", "Whether the array should be Fortran-contiguous (True) or C-contiguous (False,", "minor : int \"\"\" magic_str = _read_bytes(fp, MAGIC_LEN, \"magic string\")", "may raise various errors if the objects are not picklable.", "array.flags.c_contiguous: d['fortran_order'] = False elif array.flags.f_contiguous: d['fortran_order'] = True else:", "but only the array data will be written out. A", "value is None, which results in a data-type of `float64`.", "return None or raise on # would-block, python2 file will", "Read from file-like object until size bytes are read. Raises", "max_read_count): read_count = min(max_read_count, count - i) read_size = int(read_count", "memory-mapped: Python objects in dtype.\" raise ValueError(msg) offset = fp.tell()", "but will \" \"raise if saved when read. Use another", "titles, 'offsets': offsets, 'itemsize': offset}) def header_data_from_array_1_0(array): \"\"\" Get the", "for i in range(0, count, max_read_count): read_count = min(max_read_count, count", "an object array. Various other errors If the array contains", "picklable. \"\"\" _check_version(version) _write_array_header(fp, header_data_from_array_1_0(array), version) if array.itemsize == 0:", "\" \"to numpy.load\" % (err,)) from err else: if isfileobj(fp):", "read_array_header_1_0(fp): \"\"\" Read an array header from a filelike object", "to read it the # memory-intensive way. # crc32 module", "\"EOF: reading %s, expected %d bytes got %d\" raise ValueError(msg", "buffersize = max(16 * 1024 ** 2 // array.itemsize, 1)", "in dt.names) elif dt.subdtype is not None: return _has_metadata(dt.base) else:", "file. version: tuple or None None means use oldest that", "string for the given file format version. Parameters ---------- major", "we eval these when reading header.append(\"'%s': %s, \" % (key,", "be saved or ignored, but will \" \"raise if saved", "msg = \"Array can't be memory-mapped: Python objects in dtype.\"", "file formats but use an extension specific to the application.", "or a path-like object.\" \" Memmap cannot use existing file", "in practice was latin1) with a utf8-encoded string, so supports", "python 2.6 can return less data than requested. \"\"\" data", "data HEADER_LEN.\" Format Version 3.0 ------------------ This version replaces the", "to reconstruct the array including shape and dtype on a", "and object arrays. - Represents the data in its native", "return dtype.descr else: return dtype.str def descr_to_dtype(descr): \"\"\" Returns a", "if the format does not allow saving this data. Default:", "---------- array : numpy.ndarray Returns ------- d : dict This", "when reading header.append(\"'%s': %s, \" % (key, repr(value))) header.append(\"}\") header", "Returns ------- marray : memmap The memory-mapped array. Raises ------", "either C-contiguous or Fortran-contiguous. Otherwise, it will be made contiguous", "object arrays on Python 3 to Python 2 compatible format.", "and big-endian arrays are supported, and a file with little-endian", "response to CVE-2019-6446. pickle_kwargs : dict Additional keyword arguments to", "----- The ``.npy`` format, including motivation for creating it and", "explicit version will raise a ValueError if the format does", "'*padlen + b'\\n' def _wrap_header_guess_version(header): \"\"\" Like `_wrap_header`, but chooses", "large number of columns. The version 2.0 format extends the", "header. import struct hinfo = _header_size_info.get(version) if hinfo is None:", "\"\"\" Takes a stringified header, and attaches the prefix and", "a solution in their preferred programming language to read most", "% ARRAY_ALIGN) try: header_prefix = magic(*version) + struct.pack(fmt, hlen +", "data or the mode is invalid. IOError If the file", "with fields with empty names will have the names replaced", "the dtype contains Python objects (i.e. ``dtype.hasobject is True``), then", "b'\\n' def _wrap_header_guess_version(header): \"\"\" Like `_wrap_header`, but chooses an appropriate", "and the file contains an object array. \"\"\" version =", "current. \"\"\" import numpy import io import warnings from numpy.lib.utils", "case this parameter is required. Otherwise, this parameter is ignored", "cannot be opened correctly. See Also -------- numpy.memmap \"\"\" if", "not None: # This is a record array. The .descr", "from e if not isinstance(d, dict): msg = \"Header is", "len(data) == size: break except io.BlockingIOError: pass if len(data) !=", "zip file containing multiple ``.npy`` files, one for each array.", "is for convenience only. A writer SHOULD implement this if", "from a numpy.ndarray. Parameters ---------- array : numpy.ndarray Returns -------", "version must be 0 <= minor < 256\") return MAGIC_PREFIX", "# always true on python 3 header = header.encode(encoding) hlen", "array with one field with '' as a name. The", "are only useful when pickling objects in object arrays on", "dtype : data-type, optional The data type of the array", "is not a real file object, this function will have", "0)) def _filter_header(s): \"\"\"Clean up 'L' in npz header ints.", "is encountered before size bytes are read. Non-blocking objects only", "to an NPY file, including a header. If the array", "2 when using Python 3. Returns ------- array : ndarray", "keyword arguments to pass to pickle.load. These are only useful", "object that can be passed to `numpy.dtype()` in order to", "= _read_bytes(fp, MAGIC_LEN, \"magic string\") if magic_str[:-2] != MAGIC_PREFIX: msg", "Format Version 1.0 ------------------ The first 6 bytes are a", "(2, 0): header = _filter_header(header) try: d = safe_eval(header) except", "new file in \"write\" mode. version : tuple of int", "written out. A regular numpy.ndarray object will be created upon", "ValueError if the format does not allow saving this data.", "dtype may be restored by using the ``loadedarray.view(correct_dtype)`` method. File", "= field dt = descr_to_dtype(descr_str) else: name, descr_str, shape =", "regular files can't be non-blocking try: r = fp.read(size -", "can return less data than requested. \"\"\" data = bytes()", "object instead of an actual file. - Stores object arrays,", "but can be read and written to disk. Limitations -----------", "short int which has the length of the # header.", "byte is an unsigned byte: the major version number of", "StringIO tokens = [] last_token_was_number = False for token in", "dtype('float32'), have a descr which looks like a record array", "-------- numpy.memmap \"\"\" if isfileobj(filename): raise ValueError(\"Filename must be a", "to write to disk. version : (int, int) or None,", "> 0: # If dtype.itemsize == 0 then there's nothing", "version. Parameters ---------- major : int in [0, 255] minor", "else: return False def dtype_to_descr(dtype): \"\"\" Get a serializable descriptor", "is not a dictionary: {!r}\" raise ValueError(msg.format(d)) if EXPECTED_KEYS !=", "the version used Parameters ---------- fp : filelike object d", "(3, 0)) warnings.warn(\"Stored array in format 3.0. It can only", "\"long int\" writes out an array with \"long ints\", a", "read in Python3. Parameters ---------- s : string Npy file", "filtering was implemented. if version <= (2, 0): header =", "file object located just after the header. .. versionadded:: 1.9.0", "file object, then this may take extra memory and time.", "# directly. Instead, we will pickle it out if not", "of columns. The version 2.0 format extends the header size", "import warnings from numpy.lib.utils import safe_eval from numpy.compat import (", "descr_str, shape = field dt = numpy.dtype((descr_to_dtype(descr_str), shape)) # Ignore", "ints. Cleans up the 'L' in strings representing integers. Needed", "size: break except io.BlockingIOError: pass if len(data) != size: msg", "version must be 0 <= major < 256\") if minor", "encoding= option \" \"to numpy.load\" % (err,)) from err else:", "If the data or the mode is invalid. IOError If", "titles = [] names = [] formats = [] offsets", "% (err,)) from err else: if isfileobj(fp): # We can", "the array data will be written out. A regular numpy.ndarray", "version): \"\"\" Takes a stringified header, and attaches the prefix", "given the contents \"\"\" try: return _wrap_header(header, (1, 0)) except", "tokenize.NAME and token_string == \"L\"): continue else: tokens.append(token) last_token_was_number =", "_check_version(version) # Ensure that the given dtype is an authentic", "dtypes; see # https://github.com/numpy/numpy/pull/6430 array = numpy.ndarray(count, dtype=dtype) if dtype.itemsize", "default) if we are creating a new file in \"write\"", "array : ndarray The array to write to disk. version", "bool, optional Whether to allow writing pickled data. Default: True", "a ValueError if the format does not allow saving this", "name. Instead, we construct descriptor that can be passed to", "use an extension specific to the application. In the absence", "existing file handles.\") if 'w' in mode: # We are", "\"L\"): continue else: tokens.append(token) last_token_was_number = (token_type == tokenize.NUMBER) return", "is not None fmt, encoding = _header_size_info[version] if not isinstance(header,", "and token_type == tokenize.NAME and token_string == \"L\"): continue else:", "created by, i.e. simple fields like dtype('float32'), and then convert", "False d['descr'] = dtype_to_descr(array.dtype) return d def _wrap_header(header, version): \"\"\"", "----------- - Arbitrary subclasses of numpy.ndarray are not completely preserved.", "(last_token_was_number and token_type == tokenize.NAME and token_string == \"L\"): continue", "``.npy`` files, one for each array. Capabilities ------------ - Can", "little-endian numbers will yield a little-endian array on any machine", "64 for alignment purposes. The dictionary contains three keys: \"descr\"", "Python 2 # implementation before header filtering was implemented. if", "Write an array to an NPY file, including a header.", "the data is invalid, or allow_pickle=False and the file contains", "thus optional. fortran_order : bool, optional Whether the array should", "next 4 bytes form a little-endian unsigned int: the length", "located just after the header. .. versionadded:: 1.9.0 Parameters ----------", "False in response to CVE-2019-6446. pickle_kwargs : dict Additional keyword", "a 1-D array is both C_CONTIGUOUS and F_CONTIGUOUS. d['fortran_order'] =", "tokens.append(token) last_token_was_number = (token_type == tokenize.NUMBER) return tokenize.untokenize(tokens) def _read_array_header(fp,", "tied to the version of the numpy package. The next", "to pass the encoding= option \" \"to numpy.load\" % (err,))", "It will remove the valueless padding fields created by, i.e.", "have a total size of 65535 bytes. This can be", "len(length) + HEADER_LEN`` be evenly divisible by 64 for alignment", "d : dict This has the appropriate entries for writing", "need to pass the encoding= option \" \"to numpy.load\" %", "can use the fast fromfile() function. array = numpy.fromfile(fp, dtype=dtype,", ".descr attribute of a dtype object cannot be round-tripped through", "array.T.tofile(fp) else: for chunk in numpy.nditer( array, flags=['external_loop', 'buffered', 'zerosize_ok'],", "live longer than the programs that created them. A competent", "minor : int in [0, 255] Returns ------- magic :", "format is not tied to the version of the numpy", "max_read_count, so # only one read is performed. # Use", "isfileobj(fp): # We can use the fast fromfile() function. array", "reads greater than 2 ** 32 bytes, # breaking large", "None: return _has_metadata(dt.base) else: return False def dtype_to_descr(dtype): \"\"\" Get", "ValueError(\"minor version must be 0 <= minor < 256\") return", "file object located just after the header. Parameters ---------- fp", "constructor interprets this as a request to give a default", "if isfileobj(fp): array.tofile(fp) else: for chunk in numpy.nditer( array, flags=['external_loop',", "header for an array using the 2.0 format. The 2.0", "unpickle the data. if not allow_pickle: raise ValueError(\"Object arrays cannot", "dtype descriptor: {!r}\" raise ValueError(msg.format(d['descr'])) from e return d['shape'], d['fortran_order'],", "dt = numpy.dtype((descr_to_dtype(descr_str), shape)) # Ignore padding bytes, which will", "pass to pickle.load. These are only useful when loading object", "it. # Check if we ought to create the file.", "files (default in python3) return None or raise on #", "read_magic(fp) _check_version(version) shape, fortran_order, dtype = _read_array_header(fp, version) if dtype.hasobject:", "int in [0, 255] Returns ------- magic : str Raises", "on disk. This may *not* be a file-like object. mode", "not None: return True elif dt.names is not None: return", "header of the file. \"\"\" _write_array_header(fp, d, (1, 0)) def", "designed to be as simple as possible while achieving its", "BUFFER_SIZE = 2**18 # size of buffer for reading npz", "= descr_to_dtype(descr[0]) return numpy.dtype((dt, descr[1])) titles = [] names =", "written directly to disk for efficiency. \"shape\" : tuple of", "# would-block, python2 file will truncate, probably nothing can be", "header. If the array is neither C-contiguous nor Fortran-contiguous AND", "---------- filename : str or path-like The name of the", "isfileobj(fp): array.T.tofile(fp) else: for chunk in numpy.nditer( array, flags=['external_loop', 'buffered',", "be read and written to disk. Limitations ----------- - Arbitrary", "The version 1.0 format only allowed the array header to", "+ b' '*padlen + b'\\n' def _wrap_header_guess_version(header): \"\"\" Like `_wrap_header`,", "0 <= major < 256\") if minor < 0 or", "byte (I) header length # instead of 2 bytes (H)", "if isinstance(descr, str): # No padding removal needed return numpy.dtype(descr)", "if not isinstance(header, bytes): # always true on python 3", "Required as e.g. ZipExtFile in python 2.6 can return less", "header of the file. \"\"\" d = {'shape': array.shape} if", "the data on disk. Raises ------ ValueError If the data", "[] offset = 0 for field in descr: if len(field)", "\"write\" mode, then this is the version of the file", "Non-blocking objects only supported if they derive from io objects.", "interpretation of structured dtypes, dtypes with fields with empty names", "err else: if isfileobj(fp): # We can use the fast", "1.0 and 2.0 is a 4 byte (I) header length", "overhead. buffersize = max(16 * 1024 ** 2 // array.itemsize,", "this. Following the header comes the array data. If the", "sorted(d.items()): # Need to use repr here, since we eval", "We are creating the file, not reading it. # Check", "a request to give a default name. Instead, we construct", "``len(magic string) + 2 + len(length) + HEADER_LEN`` be evenly", "or ignored, but will \" \"raise if saved when read.", "None: # This is a record array. The .descr is", "parse header: {!r}\" raise ValueError(msg.format(header)) from e if not isinstance(d,", "with 32-bit C \"long ints\" will yield an array with", "just something that can be interpreted as a dtype object.", "names. Notes ----- The ``.npy`` format, including motivation for creating", "# We need to change a write-only mode to a", "return numpy.dtype((dt, descr[1])) titles = [] names = [] formats", ": filelike object A file object or something with a", "is neither C-contiguous nor Fortran-contiguous AND the file_like object is", "blank names is removed, only \"if name == ''\" needed)", "0)) def read_array_header_1_0(fp): \"\"\" Read an array header from a", "and written to disk. Limitations ----------- - Arbitrary subclasses of", "= array.transpose() else: array.shape = shape return array def open_memmap(filename,", "= {'descr', 'fortran_order', 'shape'} MAGIC_PREFIX = b'\\x93NUMPY' MAGIC_LEN = len(MAGIC_PREFIX)", "{!r}\" raise ValueError(msg.format(d['shape'])) if not isinstance(d['fortran_order'], bool): msg = \"fortran_order", "the data. if not allow_pickle: raise ValueError(\"Object arrays cannot be", "else: count = numpy.multiply.reduce(shape, dtype=numpy.int64) # Now read the actual", "TypeError as e: msg = \"descr is not a valid", "the major version number of the file format, e.g. ``\\\\x01``.", "be read from a filelike stream object instead of an", "if pickle_kwargs is None: pickle_kwargs = {} try: array =", "= \"EOF: reading %s, expected %d bytes got %d\" raise", "keys: {!r}\" raise ValueError(msg.format(keys)) # Sanity-check the values. if (not", "non-chunked case count < max_read_count, so # only one read", "%r, got %r\" raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2])) major, minor", "new one. Parameters ---------- filename : str or path-like The", "reading the file. The types are described in terms of", "not isinstance(d, dict): msg = \"Header is not a dictionary:", "header: {!r}\" raise ValueError(msg.format(header)) from e if not isinstance(d, dict):", "even on another machine with a different architecture. The format", "can be passed to dtype(). Parameters ---------- dtype : dtype", "data on disk. Raises ------ ValueError If the data is", "Note that we need to test for C_CONTIGUOUS first #", "if a machine with a 64-bit C \"long int\" writes", "in tokenize.generate_tokens(StringIO(s).readline): token_type = token[0] token_string = token[1] if (last_token_was_number", "total of ``len(magic string) + 2 + len(length) + HEADER_LEN``", "time. allow_pickle : bool, optional Whether to allow writing pickled", "the length of the header data HEADER_LEN. The next HEADER_LEN", "If the file is not found or cannot be opened", "ARRAY_ALIGN byte # boundary. The keys are strings. # \"shape\"", "buffersize = 0 else: # Set buffer size to 16", "before writing it out. dtype : dtype The dtype of", "= 0 else: # Set buffer size to 16 MiB", "import struct hinfo = _header_size_info.get(version) if hinfo is None: raise", "the absence of an obvious alternative, however, we suggest using", "---------- fp : filelike object Returns ------- major : int", "Default: True pickle_kwargs : dict, optional Additional keyword arguments to", "memory-mapped: Python objects in dtype.\" raise ValueError(msg) d = dict(", "except io.BlockingIOError: pass if len(data) != size: msg = \"EOF:", "size: msg = \"EOF: reading %s, expected %d bytes got", "string which contains a Python literal expression of a dictionary.", "fails on reads greater than 2 ** 32 bytes, #", "the header comes the array data. If the dtype contains", "format entirely accurately. The data is intact; only the field", "read most ``.npy`` files that they have been given without", "most ``.npy`` files that they have been given without much", "this if possible. A reader MUST NOT depend on this.", "the header data HEADER_LEN.\" Format Version 3.0 ------------------ This version", "error message raise UnicodeError(\"Unpickling a python object failed: %r\\n\" \"You", "mode in which to open the file; the default is", "numpy.ndarray. Parameters ---------- array : numpy.ndarray Returns ------- d :", "the array if we are creating a new file in", "else: for chunk in numpy.nditer( array, flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize,", "requires it, else it will always use the more compatible", "is able to store the data. Default: None Returns -------", "the file). return header_prefix + header + b' '*padlen +", "The 2.0 format allows storing very large structured arrays. ..", "s : string Npy file header. Returns ------- header :", "use oldest that works explicit version will raise a ValueError", "not. Since Fortran-contiguous arrays are a common form of non-C-contiguity,", "reconstruct the array correctly even on another machine with a", "be void bytes with '' as name # Once support", "object using the 1.0 file format version. This will leave", "padded to a ARRAY_ALIGN byte # boundary. The keys are", "byte boundary. This supports memory mapping of dtypes # aligned", "dt.names is not None: return any(_has_metadata(dt[k]) for k in dt.names)", "their actual sizes. For example, if a machine with a", "and write Version 1.0 files. Format Version 1.0 ------------------ The", "a real file object, then this may take extra memory", "the header therefore has become: \"The next 4 bytes form", "name if isinstance(name, tuple) else (None, name) titles.append(title) names.append(name) formats.append(dt)", "\"\"\" return _read_array_header(fp, version=(1, 0)) def read_array_header_2_0(fp): \"\"\" Read an", "def _has_metadata(dt): if dt.metadata is not None: return True elif", "elif array.flags.f_contiguous and not array.flags.c_contiguous: if isfileobj(fp): array.T.tofile(fp) else: for", "to allow writing pickled data. Default: False .. versionchanged:: 1.16.3", "optional Additional keyword arguments to pass to pickle.dump, excluding 'protocol'.", "be made contiguous before writing it out. dtype : dtype", "one field with '' as a name. The dtype() constructor", "that the given dtype is an authentic dtype object rather", "documentation. - Allows memory-mapping of the data. See `open_memmap`. -", "Files with object arrays are not to be mmapable, but", "little-endian unsigned int: the length of the header data HEADER_LEN.\"", "minor]) def read_magic(fp): \"\"\" Read the magic string to get", "+ b'\\n' def _wrap_header_guess_version(header): \"\"\" Like `_wrap_header`, but chooses an", "0 then there's nothing more to read max_read_count = BUFFER_SIZE", "fortran_order=False, version=None): \"\"\" Open a .npy file as a memory-mapped", "(2, 0)) except UnicodeEncodeError: pass else: warnings.warn(\"Stored array in format", "available mode strings. dtype : data-type, optional The data type", "have to make it C-contiguous # before writing. Note that", "powers of 2 between 16 and 4096 BUFFER_SIZE = 2**18", "is None) if not is_pad: title, name = name if", "from io objects. Required as e.g. ZipExtFile in python 2.6", "major : int in [0, 255] minor : int in", "\"\"\" Get a serializable descriptor from the dtype. The .descr", "UserWarning, stacklevel=2) return header def _write_array_header(fp, d, version=None): \"\"\" Write", "_read_array_header(fp, version) if len(shape) == 0: count = 1 else:", "in the :doc:`\"npy-format\" NEP <neps:nep-0001-npy-format>`, however details have evolved with", "be page-aligned (i.e. the beginning of the file). return header_prefix", "numpy.lib.utils import safe_eval from numpy.compat import ( isfileobj, os_fspath, pickle", "mode, if not, `dtype` is ignored. The default value is", "titles.append(title) names.append(name) formats.append(dt) offsets.append(offset) offset += dt.itemsize return numpy.dtype({'names': names,", "we are creating a new file in \"write\" mode, if", "suggest using ``.npy`` and ``.npz``. Version numbering ----------------- The version", "which case this parameter is required. Otherwise, this parameter is", "of an actual file. - Stores object arrays, i.e. arrays", "an array header from a filelike object using the 1.0", "= \"shape is not valid: {!r}\" raise ValueError(msg.format(d['shape'])) if not", "_check_version(version) _write_array_header(fp, header_data_from_array_1_0(array), version) if array.itemsize == 0: buffersize =", "header data HEADER_LEN.\" Format Version 3.0 ------------------ This version replaces", "The .descr is fine. XXX: parts of the # record", "ARRAY_ALIGN byte boundary. This supports memory mapping of dtypes #", "not a real file. We have to read it the", "The default value is None, which results in a data-type", "We are working on a fix for this. This fix", "round-trip through the format entirely accurately. The data is intact;", "a dtype may be saved or ignored, but will \"", "out the data # directly. Instead, we will pickle it", "None: return True elif dt.names is not None: return any(_has_metadata(dt[k])", "the header. Parameters ---------- fp : filelike object A file", "format is the standard binary file format in NumPy for", "raise ValueError(\"major version must be 0 <= major < 256\")", "an array from an NPY file. Parameters ---------- fp :", "(1, 0): ('<H', 'latin1'), (2, 0): ('<I', 'latin1'), (3, 0):", "made contiguous before writing it out. dtype : dtype The", "in python3) return None or raise on # would-block, python2", "0)) except ValueError: pass try: ret = _wrap_header(header, (2, 0))", "int The shape of the array. fortran_order : bool The", "implemented. if version <= (2, 0): header = _filter_header(header) try:", "fp, protocol=3, **pickle_kwargs) elif array.flags.f_contiguous and not array.flags.c_contiguous: if isfileobj(fp):", "is ignored. The default value is None, which results in", "a new one. Parameters ---------- filename : str or path-like", "Returns ------- array : ndarray The array from the data", "columns. The version 2.0 format extends the header size to", "header = \"\".join(header) if version is None: header = _wrap_header_guess_version(header)", "the data is a Python pickle of the array. Otherwise", "of the file. \"\"\" _write_array_header(fp, d, (2, 0)) def read_array_header_1_0(fp):", "e.g. ``\\\\x01``. The next 1 byte is an unsigned byte:", "'C' # We need to change a write-only mode to", "to read max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize) for i", "alternatives, is described in the :doc:`\"npy-format\" NEP <neps:nep-0001-npy-format>`, however details", "fp : filelike object Returns ------- major : int minor", "actual file. - Stores object arrays, i.e. arrays containing elements", "something with a `.read()` method like a file. Returns -------", "with '' as name # Once support for blank names", "if the data requires it, else it will always use", "array. Consumers can figure out the number of bytes by", "not isinstance(d['fortran_order'], bool): msg = \"fortran_order is not a valid", "length {} too big for version={}\".format(hlen, version) raise ValueError(msg) from", "allow saving this data. Default: None \"\"\" header = [\"{\"]", "major < 0 or major > 255: raise ValueError(\"major version", "ValueError If the data or the mode is invalid. IOError", "return any(_has_metadata(dt[k]) for k in dt.names) elif dt.subdtype is not", "_read_array_header(fp, version=(2, 0)) def _filter_header(s): \"\"\"Clean up 'L' in npz", "If this is not a real file object, then this", "on # would-block, python2 file will truncate, probably nothing can", "filelike object A file object or something with a `.read()`", "1.0 format. Parameters ---------- fp : filelike object d :", "_write_array_header(fp, d, (1, 0)) def write_array_header_2_0(fp, d): \"\"\" Write the", "# plausible values are powers of 2 between 16 and", "file format. Parameters ---------- fp : filelike object Returns -------", "None fmt, encoding = _header_size_info[version] if not isinstance(header, bytes): #", "return marray def _read_bytes(fp, size, error_template=\"ran out of data\"): \"\"\"", "file format version. This will leave the file object located", "only the field names will differ. We are working on", "------- shape : tuple of int The shape of the", "array should be Fortran-contiguous (True) or C-contiguous (False, the default)", "order='F'): fp.write(chunk.tobytes('C')) else: if isfileobj(fp): array.tofile(fp) else: for chunk in", "expected %d bytes got %d\" raise ValueError(msg % (error_template, size,", "else: if isfileobj(fp): # We can use the fast fromfile()", "- Represents the data in its native binary form. -", "'L' in npz header ints. Cleans up the 'L' in", "the standard file modes, 'c' is also accepted to mean", "numpy.dtype(descr) elif isinstance(descr, tuple): # subtype, will always have a", "not a real file object, then this may take extra", "or len(data) == size: break except io.BlockingIOError: pass if len(data)", "the header data HEADER_LEN. The next HEADER_LEN bytes form the", "- len(data)) data += r if len(r) == 0 or", "the total of ``len(magic string) + 2 + len(length) +", "stream object instead of an actual file. - Stores object", "major, minor = magic_str[-2:] return major, minor def _has_metadata(dt): if", "version = read_magic(fp) _check_version(version) shape, fortran_order, dtype = _read_array_header(fp, version)", "formats = [] offsets = [] offset = 0 for", "def write_array_header_1_0(fp, d): \"\"\" Write the header for an array", "header is a pretty-printed string representation of a literal #", "version : (int, int) or None, optional The version number", "the file format is not tied to the version of", "compatible format. Raises ------ ValueError If the array cannot be", "The shape of the array. For repeatability and readability, the", "header = _read_bytes(fp, header_length, \"array header\") header = header.decode(encoding) #", "'w' in mode: # We are creating the file, not", "if len(field) == 2: name, descr_str = field dt =", "header of the file. version: tuple or None None means", "array. For repeatability and readability, the dictionary keys are sorted", "yield an array with 64-bit integers. - Is straightforward to", "a filelike object using the 2.0 file format version. This", "'itemsize': offset}) def header_data_from_array_1_0(array): \"\"\" Get the dictionary of header", "to replicate the input dtype. Returns ------- dtype : dtype", "competent developer should be able to create a solution in", "Various other errors If the array contains Python objects as", "the process of pickling them may raise various errors if", "size to 16 MiB to hide the Python loop overhead.", "of the header data HEADER_LEN.\" Format Version 3.0 ------------------ This", "# difference between version 1.0 and 2.0 is a 4", "derive from io objects. Required as e.g. ZipExtFile in python", "(``\\\\n``) and padded with spaces (``\\\\x20``) to make the total", "tuple of int The shape of the array. For repeatability", "short and the header are aligned on a # ARRAY_ALIGN", "since we eval these when reading header.append(\"'%s': %s, \" %", ".. warning:: Due to limitations in the interpretation of structured", "array.itemsize == 0: buffersize = 0 else: # Set buffer", "tokenize from io import StringIO tokens = [] last_token_was_number =", "probably nothing can be # done about that. note that", "leave the file object located just after the header. ..", "sorted in alphabetic order. This is for convenience only. A", "== 2: name, descr_str = field dt = descr_to_dtype(descr_str) else:", "more current. \"\"\" import numpy import io import warnings from", "dtype=dtype, shape=shape, order=order, mode=mode, offset=offset) return marray def _read_bytes(fp, size,", "flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize, order='C'): fp.write(chunk.tobytes('C')) def read_array(fp, allow_pickle=False, pickle_kwargs=None):", "Also -------- numpy.memmap \"\"\" if isfileobj(filename): raise ValueError(\"Filename must be", "Otherwise, it will be made contiguous before writing it out.", "pickle_kwargs is None: pickle_kwargs = {} pickle.dump(array, fp, protocol=3, **pickle_kwargs)", "try: return _wrap_header(header, (1, 0)) except ValueError: pass try: ret", "allow them to be written directly to disk for efficiency.", "None: pickle_kwargs = {} try: array = pickle.load(fp, **pickle_kwargs) except", "of buffer for reading npz files in bytes # difference", "pass try: ret = _wrap_header(header, (2, 0)) except UnicodeEncodeError: pass", "format, e.g. ``\\\\x01``. The next 1 byte is an unsigned", "The dtype of the array that will be written to", "return d['shape'], d['fortran_order'], dtype def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None):", "\"Header is not a dictionary: {!r}\" raise ValueError(msg.format(d)) if EXPECTED_KEYS", "HEADER_LEN`` be evenly divisible by 64 for alignment purposes. The", "3 to Python 2 compatible format. Raises ------ ValueError If", "NPY file, including a header. If the array is neither", "array data is Fortran-contiguous or not. Since Fortran-contiguous arrays are", "information about them. The ``.npy`` format is the standard binary", "= _wrap_header(header, (2, 0)) except UnicodeEncodeError: pass else: warnings.warn(\"Stored array", "only useful when loading object arrays saved on Python 2", "real file. We have to read it the # memory-intensive", "type of the array if we are creating a new", "file. if mode == 'w+': mode = 'r+' marray =", "ASCII string (which in practice was latin1) with a utf8-encoded", "if dt.metadata is not None: return True elif dt.names is", "will be written to disk. Returns ------- descr : object", "the array contains Python objects as part of its dtype,", "the version cannot be formatted. \"\"\" if major < 0", "msg = \"Cannot parse header: {!r}\" raise ValueError(msg.format(header)) from e", "the length of the # header. import struct hinfo =", "not valid: {!r}\" raise ValueError(msg.format(d['shape'])) if not isinstance(d['fortran_order'], bool): msg", "and a final newline such that the magic # string,", "the correct dtype may be restored by using the ``loadedarray.view(correct_dtype)``", "magic(major, minor): \"\"\" Return the magic string for the given", "newline (``\\\\n``) and padded with spaces (``\\\\x20``) to make the", "255: raise ValueError(\"major version must be 0 <= major <", "document is more current. \"\"\" import numpy import io import", "based off the given description. This is essentially the reverse", "representation of a literal # Python dictionary with trailing newlines", "in dtype.\" raise ValueError(msg) offset = fp.tell() if fortran_order: order", "read max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize) for i in", "a file with little-endian numbers will yield a little-endian array", "%d bytes got %d\" raise ValueError(msg % (error_template, size, len(data)))", "divisible by 64 for alignment purposes. The dictionary contains three", "simple as possible while achieving its limited goals. The ``.npz``", "version not in [(1, 0), (2, 0), (3, 0), None]:", "array that will be written to disk. Returns ------- descr", "see # https://github.com/numpy/numpy/pull/6430 array = numpy.ndarray(count, dtype=dtype) if dtype.itemsize >", "= \"descr is not a valid dtype descriptor: {!r}\" raise", "array in format 3.0. It can only be \" \"read", "the data or the mode is invalid. IOError If the", "padlen) except struct.error: msg = \"Header length {} too big", "io objects. Required as e.g. ZipExtFile in python 2.6 can", "Write the header for an array using the 1.0 format.", "need to unpickle the data. if not allow_pickle: raise ValueError(\"Object", "passed as an argument to the `numpy.dtype` constructor to create", "= ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize(fmt) + hlen) % ARRAY_ALIGN)", "version given the contents \"\"\" try: return _wrap_header(header, (1, 0))", "array data. If the dtype contains Python objects (i.e. ``dtype.hasobject", "= safe_eval(header) except SyntaxError as e: msg = \"Cannot parse", "arrays cannot be saved when \" \"allow_pickle=False\") if pickle_kwargs is", "read it the # memory-intensive way. # crc32 module fails", "C-contiguous # before writing. Note that we need to test", "to 4 GiB. `numpy.save` will automatically save in 2.0 format", "d, (1, 0)) def write_array_header_2_0(fp, d): \"\"\" Write the header", "The array from the data on disk. Raises ------ ValueError", "(True) or C-contiguous (False, the default) if we are creating", "in \"write\" mode. version : tuple of int (major, minor)", "= \"Header does not contain the correct keys: {!r}\" raise", "(``\\\\x20``) to make the total of ``len(magic string) + 2", "the magic string to get the version of the file", "void bytes with '' as name # Once support for", "numpy.nditer( array, flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize, order='F'): fp.write(chunk.tobytes('C')) else: if", "hlen + padlen) except struct.error: msg = \"Header length {}", "appropriate entries for writing its string representation to the header", "file. The types are described in terms of their actual", "HEADER_LEN bytes form the header data describing the array's format.", "------- d : dict This has the appropriate entries for", "array contains Python objects as part of its dtype, the", "objects. Files with object arrays are not to be mmapable,", "of the file). return header_prefix + header + b' '*padlen", "# instead of 2 bytes (H) allowing storage of large", "array on any machine reading the file. The types are", "the description to its corresponding dtype. Parameters ---------- descr :", "not None: return _has_metadata(dt.base) else: return False def dtype_to_descr(dtype): \"\"\"", "``shape=()`` means there is 1 element) by ``dtype.itemsize``. Format Version", "will be accepted for writing, but only the array data", "function will have to copy data in memory. Parameters ----------", "may be restored by using the ``loadedarray.view(correct_dtype)`` method. File extensions", "major version number of the file format, e.g. ``\\\\x01``. The", "a *single* arbitrary NumPy array on disk. The format stores", "ignored, but will \" \"raise if saved when read. Use", "raise ValueError(msg.format(keys)) # Sanity-check the values. if (not isinstance(d['shape'], tuple)", "dtype.descr. Can be passed to `numpy.dtype()` in order to replicate", "= numpy.frombuffer(data, dtype=dtype, count=read_count) if fortran_order: array.shape = shape[::-1] array", "another form of storage.\", UserWarning, stacklevel=2) if dtype.names is not", ": dtype.descr # Versions (2, 0) and (1, 0) could", "if dtype.hasobject: # The array contained Python objects. We need", "the 1.0 format. Parameters ---------- fp : filelike object d", "to copy data in memory. Parameters ---------- fp : file_like", "one. Parameters ---------- filename : str or path-like The name", "of pickling them may raise various errors if the objects", "intact; only the field names will differ. We are working", "format in NumPy for persisting a *single* arbitrary NumPy array", "number of bytes by multiplying the number of elements given", "page-aligned (i.e. the beginning of the file). return header_prefix +", "data to the file. if mode == 'w+': mode =", "from io import StringIO tokens = [] last_token_was_number = False", "(2, 0)) def read_array_header_1_0(fp): \"\"\" Read an array header from", "on Python 2 when using Python 3. Returns ------- array", "it, else it will always use the more compatible 1.0", "is not tied to the version of the numpy package.", "the input dtype. \"\"\" if _has_metadata(dtype): warnings.warn(\"metadata on a dtype", "mode since we've # already written data to the file.", "warnings from numpy.lib.utils import safe_eval from numpy.compat import ( isfileobj,", "raise on # would-block, python2 file will truncate, probably nothing", "{!r}\" raise ValueError(msg.format(keys)) # Sanity-check the values. if (not isinstance(d['shape'],", "file will truncate, probably nothing can be # done about", "but use an extension specific to the application. In the", "instead of 2 bytes (H) allowing storage of large structured", "\"copy on write.\" See `memmap` for the available mode strings.", "we got here, then it should be safe to create", "in memory. Parameters ---------- fp : file_like object An open,", "record array with one field with '' as a name.", "can't be memory-mapped: Python objects in dtype.\" raise ValueError(msg) d", "raise ValueError(\"minor version must be 0 <= minor < 256\")", "None allow_pickle : bool, optional Whether to allow writing pickled", "fortran_order : bool, optional Whether the array should be Fortran-contiguous", "not contain the correct keys: {!r}\" raise ValueError(msg.format(keys)) # Sanity-check", "non-C-contiguity, we allow them to be written directly to disk", "\"write\" mode, in which case this parameter is required. Otherwise,", "256\") if minor < 0 or minor > 255: raise", "these file formats but use an extension specific to the", "# Set buffer size to 16 MiB to hide the", "an existing file or create a new one. Parameters ----------", "is also accepted to mean \"copy on write.\" See `memmap`", "descr=dtype_to_descr(dtype), fortran_order=fortran_order, shape=shape, ) # If we got here, then", "2.0. It can only be\" \"read by NumPy >= 1.9\",", "binary form. - Supports Fortran-contiguous arrays directly. - Stores all", "by structured arrays with a large number of columns. The", "``.npy`` format, including motivation for creating it and a comparison", "reading it. # Check if we ought to create the", "types, like dtype('float32'), have a descr which looks like a", "header from a filelike object using the 2.0 file format", "implement this if possible. A reader MUST NOT depend on", "replaced by 'f0', 'f1', etc. Such arrays will not round-trip", "array. Various other errors If the array contains Python objects", "a \"write\" mode, then this is the version of the", "= False d['descr'] = dtype_to_descr(array.dtype) return d def _wrap_header(header, version):", "use the more compatible 1.0 format. The description of the", "be saved and restored, and the correct dtype may be", "using ``.npy`` and ``.npz``. Version numbering ----------------- The version numbering", "fp.tell() else: # Read the header of the file first.", "from e return d['shape'], d['fortran_order'], dtype def write_array(fp, array, version=None,", "shape)) # Ignore padding bytes, which will be void bytes", "Python objects so we cannot write out the data #", "to change a write-only mode to a read-write mode since", "headers produced in Python2 to be read in Python3. Parameters", "is ignored and is thus optional. fortran_order : bool, optional", "--------------- We recommend using the ``.npy`` and ``.npz`` extensions for", "d['fortran_order'], dtype def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None): \"\"\" Write", "= {} try: array = pickle.load(fp, **pickle_kwargs) except UnicodeError as", "saved when \" \"allow_pickle=False\") if pickle_kwargs is None: pickle_kwargs =", "+ 1 padlen = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize(fmt) +", "read_array(fp, allow_pickle=False, pickle_kwargs=None): \"\"\" Read an array from an NPY", "to the file. if mode == 'w+': mode = 'r+'", ": int in [0, 255] minor : int in [0,", "format. The arrays with such structures can still be saved", "default value is None, which results in a data-type of", "+ padlen) except struct.error: msg = \"Header length {} too", "header are aligned on a # ARRAY_ALIGN byte boundary. This", "2 bytes form a little-endian unsigned short int: the length", "out. A regular numpy.ndarray object will be created upon reading", "format version. Parameters ---------- major : int in [0, 255]", "it C-contiguous # before writing. Note that we need to", "string representation to the header of the file. \"\"\" _write_array_header(fp,", "dtype. \"\"\" if _has_metadata(dtype): warnings.warn(\"metadata on a dtype may be", "Raises ------ ValueError If the array cannot be persisted. This", "for an array and returns the version used Parameters ----------", "dict Additional keyword arguments to pass to pickle.load. These are", "dtype object. dtype = numpy.dtype(dtype) if dtype.hasobject: msg = \"Array", "header data HEADER_LEN. The next HEADER_LEN bytes form the header", "is more current. \"\"\" import numpy import io import warnings", "other errors If the array contains Python objects as part", "native binary form. - Supports Fortran-contiguous arrays directly. - Stores", "1.16.3 Made default False in response to CVE-2019-6446. pickle_kwargs :", "4 GiB. `numpy.save` will automatically save in 2.0 format if", "boundary. The keys are strings. # \"shape\" : tuple of", "Default: None allow_pickle : bool, optional Whether to allow writing", "0): header = _filter_header(header) try: d = safe_eval(header) except SyntaxError", "have to copy data in memory. Parameters ---------- fp :", "with little-endian numbers will yield a little-endian array on any", "readability, the dictionary keys are sorted in alphabetic order. This", "0), (2, 0), (3, 0), None]: msg = \"we only", "structured arrays. .. versionadded:: 1.9.0 Parameters ---------- fp : filelike", "import struct assert version is not None fmt, encoding =", "with open(os_fspath(filename), mode+'b') as fp: _write_array_header(fp, d, version) offset =", "would-block, python2 file will truncate, probably nothing can be #", ": str Raises ------ ValueError if the version cannot be", "return tokenize.untokenize(tokens) def _read_array_header(fp, version): \"\"\" see read_array_header_1_0 \"\"\" #", "errors if the objects are not picklable. \"\"\" _check_version(version) _write_array_header(fp,", "the full information about them. The ``.npy`` format is the", "if 'w' in mode: # We are creating the file,", ": tuple of int The shape of the array if", "as simple as possible while achieving its limited goals. The", "{ (1, 0): ('<H', 'latin1'), (2, 0): ('<I', 'latin1'), (3,", "format stores all of the shape and dtype information necessary", "values are powers of 2 between 16 and 4096 BUFFER_SIZE", "\"\"\" Write the header for an array using the 2.0", "data. if not allow_pickle: raise ValueError(\"Object arrays cannot be loaded", "of the necessary information to reconstruct the array including shape", "to the application. In the absence of an obvious alternative,", ": dtype The dtype of the file's data. Raises ------", "contains Python objects as part of its dtype, the process", "version: tuple or None None means use oldest that works", "The shape of the array. fortran_order : bool The array", "unsigned byte: the minor version number of the file format,", "directly. Instead, we will pickle it out if not allow_pickle:", "out. dtype : dtype The dtype of the file's data.", "---------- s : string Npy file header. Returns ------- header", "(i.e. ``dtype.hasobject is True``), then the data is a Python", "data. We will have to make it C-contiguous # before", "\"\"\" header = [\"{\"] for key, value in sorted(d.items()): #", "header = [\"{\"] for key, value in sorted(d.items()): # Need", "_read_array_header(fp, version) if dtype.hasobject: msg = \"Array can't be memory-mapped:", "Python2 to be read in Python3. Parameters ---------- s :", "= token[1] if (last_token_was_number and token_type == tokenize.NAME and token_string", "objects. Required as e.g. ZipExtFile in python 2.6 can return", "Stores object arrays, i.e. arrays containing elements that are arbitrary", "order = 'F' else: order = 'C' # We need", "ignored. The default value is None, which results in a", "file). return header_prefix + header + b' '*padlen + b'\\n'", "mapping of dtypes # aligned up to ARRAY_ALIGN on systems", ".. versionchanged:: 1.16.3 Made default False in response to CVE-2019-6446.", "between 16 and 4096 BUFFER_SIZE = 2**18 # size of", "difference between version 1.0 and 2.0 is a 4 byte", "major : int minor : int \"\"\" magic_str = _read_bytes(fp,", "Fortran-contiguous arrays are a common form of non-C-contiguity, we allow", "magic_str[-2:] return major, minor def _has_metadata(dt): if dt.metadata is not", "newlines padded to a ARRAY_ALIGN byte # boundary. The keys", "this is not a real file object, then this may", "writing it out. dtype : dtype The dtype of the", "count < max_read_count, so # only one read is performed.", "if (not isinstance(d['shape'], tuple) or not all(isinstance(x, int) for x", "We can use the fast fromfile() function. array = numpy.fromfile(fp,", "on write.\" See `memmap` for the available mode strings. dtype", "a pretty-printed string representation of a literal # Python dictionary", "This may be used to read an existing file or", "else: # Read the header of the file first. with", "offset = fp.tell() if fortran_order: order = 'F' else: order", "+ hlen) % ARRAY_ALIGN) try: header_prefix = magic(*version) + struct.pack(fmt,", "ValueError if the version cannot be formatted. \"\"\" if major", "differ. We are working on a fix for this. This", "dtype('float32'), and then convert the description to its corresponding dtype.", "and dt.type is numpy.void and dt.names is None) if not", "just after the header. Parameters ---------- fp : filelike object", "containing multiple ``.npy`` files, one for each array. Capabilities ------------", "pickle.dump, excluding 'protocol'. These are only useful when pickling objects", "are creating a new file in \"write\" mode, in which", "shape, fortran_order, dtype = _read_array_header(fp, version) if dtype.hasobject: msg =", "+ 2 ARRAY_ALIGN = 64 # plausible values are powers", "return _read_array_header(fp, version=(1, 0)) def read_array_header_2_0(fp): \"\"\" Read an array", "round-tripped through the dtype() constructor. Simple types, like dtype('float32'), have", "completely preserved. Subclasses will be accepted for writing, but only", "allow_pickle=False and array being an object array. Various other errors", "bytes # difference between version 1.0 and 2.0 is a", "in 2.0 format if the data requires it, else it", "of allow_pickle=False and array being an object array. Various other", "for convenience only. A writer SHOULD implement this if possible.", "version) raise ValueError(msg) from None # Pad the header with", "types are described in terms of their actual sizes. For", "arrays containing elements that are arbitrary Python objects. Files with", "reading npz files in bytes # difference between version 1.0", "key, value in sorted(d.items()): # Need to use repr here,", "raise ValueError(msg.format(d['shape'])) if not isinstance(d['fortran_order'], bool): msg = \"fortran_order is", "safe to create the file. with open(os_fspath(filename), mode+'b') as fp:", "header to have a total size of 65535 bytes. This", "of data\"): \"\"\" Read from file-like object until size bytes", "to create the array's dtype. \"fortran_order\" : bool Whether the", "done about that. note that regular files can't be non-blocking", "array contained Python objects. We need to unpickle the data.", "If the mode is a \"write\" mode, then this is", "by the description. \"\"\" if isinstance(descr, str): # No padding", "bytes are a magic string: exactly ``\\\\x93NUMPY``. The next 1", "object If this is not a real file object, then", "count = numpy.multiply.reduce(shape, dtype=numpy.int64) # Now read the actual data.", "'c' is also accepted to mean \"copy on write.\" See", "\" \"allow_pickle=False\") if pickle_kwargs is None: pickle_kwargs = {} try:", "supports memory mapping of dtypes # aligned up to ARRAY_ALIGN", "option \" \"to numpy.load\" % (err,)) from err else: if", "reading %s, expected %d bytes got %d\" raise ValueError(msg %", "form a little-endian unsigned short int: the length of the", "'' and dt.type is numpy.void and dt.names is None) if", "in mode: # We are creating the file, not reading", "raise various errors if the objects are not picklable. \"\"\"", "literal expression of a dictionary. It is terminated by a", "order='C'): fp.write(chunk.tobytes('C')) def read_array(fp, allow_pickle=False, pickle_kwargs=None): \"\"\" Read an array", "file handles.\") if 'w' in mode: # We are creating", "If dtype.itemsize == 0 then there's nothing more to read", "Default: None \"\"\" header = [\"{\"] for key, value in", "the file. _check_version(version) # Ensure that the given dtype is", "dtype.str def descr_to_dtype(descr): \"\"\" Returns a dtype based off the", "names, 'formats': formats, 'titles': titles, 'offsets': offsets, 'itemsize': offset}) def", "described in terms of their actual sizes. For example, if", "ValueError if not EOF is encountered before size bytes are", "file. .. warning:: Due to limitations in the interpretation of", "will truncate, probably nothing can be # done about that.", "`numpy.save` will automatically save in 2.0 format if the data", "and dtype information necessary to reconstruct the array correctly even", "0)) def write_array_header_2_0(fp, d): \"\"\" Write the header for an", "mmapable, but can be read and written to disk. Limitations", "a requirement; applications may wish to use these file formats", "header-length short and the header are aligned on a #", "def _wrap_header_guess_version(header): \"\"\" Like `_wrap_header`, but chooses an appropriate version", "programming language to read most ``.npy`` files that they have", "its string representation to the header of the file. version:", "the file's data. Raises ------ ValueError If the data is", ": tuple of int The shape of the array. fortran_order", "else: # Set buffer size to 16 MiB to hide", "token_type = token[0] token_string = token[1] if (last_token_was_number and token_type", "a different architecture. The format is designed to be as", "is Fortran-contiguous or not. Since Fortran-contiguous arrays are a common", "0 for field in descr: if len(field) == 2: name,", "`.read()` method like a file. Returns ------- shape : tuple", "The format stores all of the shape and dtype information", "This is not a real file. We have to read", "len(MAGIC_PREFIX) + 2 ARRAY_ALIGN = 64 # plausible values are", "dtype=None, shape=None, fortran_order=False, version=None): \"\"\" Open a .npy file as", "the array should be Fortran-contiguous (True) or C-contiguous (False, the", "the header size to 4 GiB. `numpy.save` will automatically save", "the header for an array using the 1.0 format. Parameters", "true on python 3 header = header.encode(encoding) hlen = len(header)", "by multiplying the number of elements given by the shape", "data in memory. Parameters ---------- fp : file_like object An", "Returns ------- major : int minor : int \"\"\" magic_str", "of a dictionary. It is terminated by a newline (``\\\\n``)", "or similar object with a ``.write()`` method. array : ndarray", ": dict, optional Additional keyword arguments to pass to pickle.dump,", "the ``.npy`` and ``.npz`` extensions for files saved in this", "major < 256\") if minor < 0 or minor >", "a write-only mode to a read-write mode since we've #", "int(read_count * dtype.itemsize) data = _read_bytes(fp, read_size, \"array data\") array[i:i+read_count]", "raise ValueError(\"Filename must be a string or a path-like object.\"", "given without much documentation. - Allows memory-mapping of the data.", "different architecture. The format is designed to be as simple", "F_CONTIGUOUS. d['fortran_order'] = False d['descr'] = dtype_to_descr(array.dtype) return d def", "architecture. The format is designed to be as simple as", "must be 0 <= major < 256\") if minor <", "+ header + b' '*padlen + b'\\n' def _wrap_header_guess_version(header): \"\"\"", "Python literal expression of a dictionary. It is terminated by", "been created by a Python 2 # implementation before header", "or allow_pickle=False and the file contains an object array. \"\"\"", "a real file. We have to read it the #", "in which to open the file; the default is 'r+'.", "of the file's data. Raises ------ ValueError If the data", "The next 1 byte is an unsigned byte: the minor", "object An object that can be passed to `numpy.dtype()` in", "The dtype of the file's data. Raises ------ ValueError If", "header = header.decode(encoding) # The header is a pretty-printed string", "the file contains an object array. \"\"\" version = read_magic(fp)", "if the objects are not picklable. \"\"\" _check_version(version) _write_array_header(fp, header_data_from_array_1_0(array),", "= numpy.fromfile(fp, dtype=dtype, count=count) else: # This is not a", "possible while achieving its limited goals. The ``.npz`` format is", "case of allow_pickle=False and array being an object array. Various", "first # because a 1-D array is both C_CONTIGUOUS and", "file's data. Raises ------ ValueError If the data is invalid.", "header. Returns ------- header : str Cleaned up header. \"\"\"", "``.npz`` file is a zip file containing multiple ``.npy`` files,", "1 byte is an unsigned byte: the minor version number", "msg = \"Header is not a dictionary: {!r}\" raise ValueError(msg.format(d))", "which looks like a record array with one field with", "# offset must be page-aligned (i.e. the beginning of the", "Sanity-check the values. if (not isinstance(d['shape'], tuple) or not all(isinstance(x,", "short int: the length of the header data HEADER_LEN. The", "and not array.flags.c_contiguous: if isfileobj(fp): array.T.tofile(fp) else: for chunk in", "255] minor : int in [0, 255] Returns ------- magic", "of header metadata from a numpy.ndarray. Parameters ---------- array :", "_filter_header(s): \"\"\"Clean up 'L' in npz header ints. Cleans up", "pickled data. Default: False .. versionchanged:: 1.16.3 Made default False", "mode. version : tuple of int (major, minor) or None", "not allow_pickle: raise ValueError(\"Object arrays cannot be loaded when \"", "supports structured types with any unicode field names. Notes -----", "for this. This fix will not require a change in", "safe_eval from numpy.compat import ( isfileobj, os_fspath, pickle ) __all__", "could have been created by a Python 2 # implementation", "crc32 module fails on reads greater than 2 ** 32", "Limitations ----------- - Arbitrary subclasses of numpy.ndarray are not completely", "oldest that works explicit version will raise a ValueError if", "The .descr attribute of a dtype object cannot be round-tripped", "of an obvious alternative, however, we suggest using ``.npy`` and", "writer SHOULD implement this if possible. A reader MUST NOT", "does not contain the correct keys: {!r}\" raise ValueError(msg.format(keys)) #", "will remove the valueless padding fields created by, i.e. simple", "when pickling objects in object arrays on Python 3 to", "be persisted. This includes the case of allow_pickle=False and array", "not None: return any(_has_metadata(dt[k]) for k in dt.names) elif dt.subdtype", "'offsets': offsets, 'itemsize': offset}) def header_data_from_array_1_0(array): \"\"\" Get the dictionary", "dtype : dtype The dtype of the file's data. Raises", "bytes got %d\" raise ValueError(msg % (error_template, size, len(data))) else:", "have the names replaced by 'f0', 'f1', etc. Such arrays", "and returns the version used Parameters ---------- fp : filelike", "will always have a shape descr[1] dt = descr_to_dtype(descr[0]) return", "ValueError: pass try: ret = _wrap_header(header, (2, 0)) except UnicodeEncodeError:", "header.append(\"'%s': %s, \" % (key, repr(value))) header.append(\"}\") header = \"\".join(header)", "# We contain Python objects so we cannot write out", "allow_pickle=True, pickle_kwargs=None): \"\"\" Write an array to an NPY file,", "buffer for reading npz files in bytes # difference between", "found or cannot be opened correctly. See Also -------- numpy.memmap", "a zip file containing multiple ``.npy`` files, one for each", "be a string or a path-like object.\" \" Memmap cannot", "dt.subdtype is not None: return _has_metadata(dt.base) else: return False def", "for an array using the 1.0 format. Parameters ---------- fp", "a machine of a different architecture. Both little-endian and big-endian", "Notes ----- The ``.npy`` format, including motivation for creating it", "format 2.0. It can only be\" \"read by NumPy >=", "correct keys: {!r}\" raise ValueError(msg.format(keys)) # Sanity-check the values. if", "to use repr here, since we eval these when reading", "None means use oldest that works explicit version will raise", "is not correct; expected %r, got %r\" raise ValueError(msg %", "require a change in the file format. The arrays with", "range(0, count, max_read_count): read_count = min(max_read_count, count - i) read_size", "arrays to disk with the full information about them. The", "needed) is_pad = (name == '' and dt.type is numpy.void", "support for blank names is removed, only \"if name ==", "in [0, 255] minor : int in [0, 255] Returns", ": tuple of int (major, minor) or None If the", "of a different architecture. Both little-endian and big-endian arrays are", "the array including shape and dtype on a machine of", "def _wrap_header(header, version): \"\"\" Takes a stringified header, and attaches", "'zerosize_ok'], buffersize=buffersize, order='F'): fp.write(chunk.tobytes('C')) else: if isfileobj(fp): array.tofile(fp) else: for", "structures can still be saved and restored, and the correct", "input dtype. \"\"\" if _has_metadata(dtype): warnings.warn(\"metadata on a dtype may", "default name. Instead, we construct descriptor that can be passed", "MAGIC_LEN, \"magic string\") if magic_str[:-2] != MAGIC_PREFIX: msg = \"the", "is not None: return _has_metadata(dt.base) else: return False def dtype_to_descr(dtype):", "is an unsigned byte: the major version number of the", "strings representing integers. Needed to allow npz headers produced in", "pickle.load(fp, **pickle_kwargs) except UnicodeError as err: # Friendlier error message", "may be saved or ignored, but will \" \"raise if", "# io files (default in python3) return None or raise", "dtype : dtype The dtype of the array that will", "\"Header length {} too big for version={}\".format(hlen, version) raise ValueError(msg)", "is 1 element) by ``dtype.itemsize``. Format Version 2.0 ------------------ The", "See `memmap` for the available mode strings. dtype : data-type,", "the :doc:`\"npy-format\" NEP <neps:nep-0001-npy-format>`, however details have evolved with time", "stringified header, and attaches the prefix and padding to it", ": bool The array data will be written out directly", "file format in NumPy for persisting a *single* arbitrary NumPy", "(1,0), (2,0), and (3,0), not %s\" raise ValueError(msg % (version,))", "such that the magic # string, the header-length short and", "version used Parameters ---------- fp : filelike object d :", "the format. None means use the oldest supported version that", "array from an NPY file. Parameters ---------- fp : file_like", "note that regular files can't be non-blocking try: r =", "('<I', 'latin1'), (3, 0): ('<I', 'utf8'), } def _check_version(version): if", "shape = field dt = numpy.dtype((descr_to_dtype(descr_str), shape)) # Ignore padding", "contain the correct keys: {!r}\" raise ValueError(msg.format(keys)) # Sanity-check the", "is 'r+'. In addition to the standard file modes, 'c'", "array.dtype.hasobject: # We contain Python objects so we cannot write", "to use these file formats but use an extension specific", "path-like The name of the file on disk. This may", "able to store the data. Default: None Returns ------- marray", "is a Python pickle of the array. Otherwise the data", "pickle.dump(array, fp, protocol=3, **pickle_kwargs) elif array.flags.f_contiguous and not array.flags.c_contiguous: if", "A writer SHOULD implement this if possible. A reader MUST", "spaces and a final newline such that the magic #", "format extends the header size to 4 GiB. `numpy.save` will", "file. \"\"\" _write_array_header(fp, d, (2, 0)) def read_array_header_1_0(fp): \"\"\" Read", "_has_metadata(dt): if dt.metadata is not None: return True elif dt.names", "through the format entirely accurately. The data is intact; only", "''\" needed) is_pad = (name == '' and dt.type is", "the Python loop overhead. buffersize = max(16 * 1024 **", "header_data_from_array_1_0(array), version) if array.itemsize == 0: buffersize = 0 else:", "allows storing very large structured arrays. .. versionadded:: 1.9.0 Parameters", "correctly. See Also -------- numpy.memmap \"\"\" if isfileobj(filename): raise ValueError(\"Filename", "like dtype('float32'), have a descr which looks like a record", "mode strings. dtype : data-type, optional The data type of", "65535 bytes. This can be exceeded by structured arrays with", "dtype() constructor. Simple types, like dtype('float32'), have a descr which", "remove the valueless padding fields created by, i.e. simple fields", "which to open the file; the default is 'r+'. In", "create the file. with open(os_fspath(filename), mode+'b') as fp: _write_array_header(fp, d,", "descr_to_dtype(descr[0]) return numpy.dtype((dt, descr[1])) titles = [] names = []", "for files saved in this format. This is by no", "It can only be\" \"read by NumPy >= 1.9\", UserWarning,", "ret header = _wrap_header(header, (3, 0)) warnings.warn(\"Stored array in format", "dtype.names is not None: # This is a record array.", "a stringified header, and attaches the prefix and padding to", "Open a .npy file as a memory-mapped array. This may", "= True else: # Totally non-contiguous data. We will have", "limited goals. The ``.npz`` format is the standard format for", "= _read_array_header(fp, version) if dtype.hasobject: msg = \"Array can't be", "\"\"\"Clean up 'L' in npz header ints. Cleans up the", "= 0 for field in descr: if len(field) == 2:", "= sorted(d.keys()) msg = \"Header does not contain the correct", "objects so we cannot write out the data # directly.", "a filelike stream object instead of an actual file. -", "64 # plausible values are powers of 2 between 16", "any(_has_metadata(dt[k]) for k in dt.names) elif dt.subdtype is not None:", "header = _wrap_header(header, version) fp.write(header) def write_array_header_1_0(fp, d): \"\"\" Write", "extensions --------------- We recommend using the ``.npy`` and ``.npz`` extensions", "Write the header for an array using the 2.0 format.", "on disk. A ``.npz`` file is a zip file containing", ">= 1.9\", UserWarning, stacklevel=2) return ret header = _wrap_header(header, (3,", "about them. The ``.npy`` format is the standard binary file", "will have to copy data in memory. Parameters ---------- fp", ": data-type, optional The data type of the array if", "not in [(1, 0), (2, 0), (3, 0), None]: msg", "array to an NPY file, including a header. If the", "for chunk in numpy.nditer( array, flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize, order='F'):", "than requested. \"\"\" data = bytes() while True: # io", "bytes are read. Raises ValueError if not EOF is encountered", "by no means a requirement; applications may wish to use", "# because a 1-D array is both C_CONTIGUOUS and F_CONTIGUOUS.", "pickle.load. These are only useful when loading object arrays saved", "including motivation for creating it and a comparison of alternatives,", "return dtype.str def descr_to_dtype(descr): \"\"\" Returns a dtype based off", "version=None): \"\"\" Write the header for an array and returns", "a little-endian unsigned int: the length of the header data", "is a 4 byte (I) header length # instead of", "Parameters ---------- descr : object The object retreived by dtype.descr.", "Additional keyword arguments to pass to pickle.load. These are only", "the header-length short and the header are aligned on a", "else it will always use the more compatible 1.0 format.", "\"Array can't be memory-mapped: Python objects in dtype.\" raise ValueError(msg)", "an unsigned byte: the major version number of the file", "be as simple as possible while achieving its limited goals.", "the ``loadedarray.view(correct_dtype)`` method. File extensions --------------- We recommend using the", "fp : file_like object An open, writable file object, or", "plausible values are powers of 2 between 16 and 4096", "out of data\"): \"\"\" Read from file-like object until size", "or not. Since Fortran-contiguous arrays are a common form of", "in order to replicate the input dtype. \"\"\" if _has_metadata(dtype):", "only \"if name == ''\" needed) is_pad = (name ==", "utf8-encoded string, so supports structured types with any unicode field", "if magic_str[:-2] != MAGIC_PREFIX: msg = \"the magic string is", "dtype of the array that will be written to disk.", "metadata from a numpy.ndarray. Parameters ---------- array : numpy.ndarray Returns", "to 16 MiB to hide the Python loop overhead. buffersize", "fine. XXX: parts of the # record array with an", "versionadded:: 1.9.0 Parameters ---------- fp : filelike object A file", "fortran_order=fortran_order, shape=shape, ) # If we got here, then it", "2 + len(length) + HEADER_LEN`` be evenly divisible by 64", "the valueless padding fields created by, i.e. simple fields like", "contains a Python literal expression of a dictionary. It is", "dt.itemsize return numpy.dtype({'names': names, 'formats': formats, 'titles': titles, 'offsets': offsets,", "strings. # \"shape\" : tuple of int # \"fortran_order\" :", "bool, optional Whether the array should be Fortran-contiguous (True) or", "'fortran_order', 'shape'} MAGIC_PREFIX = b'\\x93NUMPY' MAGIC_LEN = len(MAGIC_PREFIX) + 2", "Check if we ought to create the file. _check_version(version) #", "See `open_memmap`. - Can be read from a filelike stream", "can be # done about that. note that regular files", ": bool, optional Whether the array should be Fortran-contiguous (True)", "tuple) else (None, name) titles.append(title) names.append(name) formats.append(dt) offsets.append(offset) offset +=", "persisting *multiple* NumPy arrays on disk. A ``.npz`` file is", "valid bool: {!r}\" raise ValueError(msg.format(d['fortran_order'])) try: dtype = descr_to_dtype(d['descr']) except", "('<H', 'latin1'), (2, 0): ('<I', 'latin1'), (3, 0): ('<I', 'utf8'),", "the array's format. It is an ASCII string which contains", "Raises ------ ValueError if the version cannot be formatted. \"\"\"", "Binary serialization NPY format ========== A simple format for saving", "then convert the description to its corresponding dtype. Parameters ----------", "C- or Fortran-, depending on ``fortran_order``) bytes of the array.", "None) if not is_pad: title, name = name if isinstance(name,", "when \" \"allow_pickle=False\") if pickle_kwargs is None: pickle_kwargs = {}", "nested record arrays and object arrays. - Represents the data", "Whether to allow writing pickled data. Default: True pickle_kwargs :", "always have a shape descr[1] dt = descr_to_dtype(descr[0]) return numpy.dtype((dt,", "True: # io files (default in python3) return None or", "\"\"\" try: return _wrap_header(header, (1, 0)) except ValueError: pass try:", "dtype=dtype, count=count) else: # This is not a real file.", "data than requested. \"\"\" data = bytes() while True: #", "The version number of the format. None means use the", "magic string: exactly ``\\\\x93NUMPY``. The next 1 byte is an", "- Stores object arrays, i.e. arrays containing elements that are", "# \"descr\" : dtype.descr # Versions (2, 0) and (1,", "for x in d['shape'])): msg = \"shape is not valid:", "first 6 bytes are a magic string: exactly ``\\\\x93NUMPY``. The", "useful when pickling objects in object arrays on Python 3", "= [\"{\"] for key, value in sorted(d.items()): # Need to", "be memory-mapped: Python objects in dtype.\" raise ValueError(msg) d =", "with open(os_fspath(filename), 'rb') as fp: version = read_magic(fp) _check_version(version) shape,", "integers. - Is straightforward to reverse engineer. Datasets often live", "Python loop overhead. buffersize = max(16 * 1024 ** 2", "array from the data on disk. Raises ------ ValueError If", "the format does not allow saving this data. Default: None", "nor Fortran-contiguous AND the file_like object is not a real", "standard file modes, 'c' is also accepted to mean \"copy", "that created them. A competent developer should be able to", "be written out. A regular numpy.ndarray object will be created", "return header_prefix + header + b' '*padlen + b'\\n' def", "has become: \"The next 4 bytes form a little-endian unsigned", "= _read_bytes(fp, struct.calcsize(hlength_type), \"array header length\") header_length = struct.unpack(hlength_type, hlength_str)[0]", "header length # instead of 2 bytes (H) allowing storage", "**pickle_kwargs) except UnicodeError as err: # Friendlier error message raise", "``\\\\x93NUMPY``. The next 1 byte is an unsigned byte: the", "essentially the reverse of `dtype_to_descr()`. It will remove the valueless", "\" \"read by NumPy >= 1.17\", UserWarning, stacklevel=2) return header", "possible. A reader MUST NOT depend on this. Following the", "will always use the more compatible 1.0 format. The description", "when read. Use another form of storage.\", UserWarning, stacklevel=2) if", "the file is not found or cannot be opened correctly.", "warning:: Due to limitations in the interpretation of structured dtypes,", "%s\" raise ValueError(msg % (version,)) def magic(major, minor): \"\"\" Return", "disk. Returns ------- descr : object An object that can", "pass to pickle.dump, excluding 'protocol'. These are only useful when", "the array correctly even on another machine with a different", "the # memory-intensive way. # crc32 module fails on reads", "The types are described in terms of their actual sizes.", "- Is straightforward to reverse engineer. Datasets often live longer", "(version,)) def magic(major, minor): \"\"\" Return the magic string for", "---------- fp : filelike object A file object or something", "byte # boundary. The keys are strings. # \"shape\" :", "an array to an NPY file, including a header. If", "# This is not a real file. We have to", "ints\" will yield an array with 64-bit integers. - Is", "UnicodeEncodeError: pass else: warnings.warn(\"Stored array in format 2.0. It can", "must be a string or a path-like object.\" \" Memmap", "shape=None, fortran_order=False, version=None): \"\"\" Open a .npy file as a", "not reading it. # Check if we ought to create", "\" \"raise if saved when read. Use another form of", "offsets.append(offset) offset += dt.itemsize return numpy.dtype({'names': names, 'formats': formats, 'titles':", "in the C implementation of # dtype(). return dtype.descr else:", "no means a requirement; applications may wish to use these", "able to read and write Version 1.0 files. Format Version", "npz files in bytes # difference between version 1.0 and", "bytes): # always true on python 3 header = header.encode(encoding)", "'buffered', 'zerosize_ok'], buffersize=buffersize, order='F'): fp.write(chunk.tobytes('C')) else: if isfileobj(fp): array.tofile(fp) else:", "The arrays with such structures can still be saved and", "are sorted in alphabetic order. This is for convenience only.", "this is the version of the file format used to", "to make the total of ``len(magic string) + 2 +", "%r\" raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2])) major, minor = magic_str[-2:]", "size of 65535 bytes. This can be exceeded by structured", "if isfileobj(fp): # We can use the fast fromfile() function.", "it will be made contiguous before writing it out. dtype", "not a valid bool: {!r}\" raise ValueError(msg.format(d['fortran_order'])) try: dtype =", "padding bytes, which will be void bytes with '' as", "of int # \"fortran_order\" : bool # \"descr\" : dtype.descr", "numpy.multiply.reduce(shape, dtype=numpy.int64) # Now read the actual data. if dtype.hasobject:", "is not found or cannot be opened correctly. See Also", "# breaking large reads from gzip streams. Chunk reads to", "read_size = int(read_count * dtype.itemsize) data = _read_bytes(fp, read_size, \"array", "the minor version number of the file format, e.g. ``\\\\x00``.", "array.flags.f_contiguous: d['fortran_order'] = True else: # Totally non-contiguous data. We", "file object or something with a `.read()` method like a", "= struct.unpack(hlength_type, hlength_str)[0] header = _read_bytes(fp, header_length, \"array header\") header", "use the fast fromfile() function. array = numpy.fromfile(fp, dtype=dtype, count=count)", "in the file format. The arrays with such structures can", "interprets this as a request to give a default name.", "padding removal needed return numpy.dtype(descr) elif isinstance(descr, tuple): # subtype,", "mode is a \"write\" mode, then this is the version", "is a zip file containing multiple ``.npy`` files, one for", "numpy.ndarray Returns ------- d : dict This has the appropriate", "int (major, minor) or None If the mode is a", "newline such that the magic # string, the header-length short", "format. The description of the fourth element of the header", "encountered before size bytes are read. Non-blocking objects only supported", "through the dtype() constructor. Simple types, like dtype('float32'), have a", "unsigned short int: the length of the header data HEADER_LEN.", "that can be passed to `numpy.dtype()` in order to replicate", "is the standard binary file format in NumPy for persisting", ": int in [0, 255] Returns ------- magic : str", "= {} pickle.dump(array, fp, protocol=3, **pickle_kwargs) elif array.flags.f_contiguous and not", "= fp.tell() if fortran_order: order = 'F' else: order =", "a dictionary: {!r}\" raise ValueError(msg.format(d)) if EXPECTED_KEYS != d.keys(): keys", "fp : file_like object If this is not a real", "shape return array def open_memmap(filename, mode='r+', dtype=None, shape=None, fortran_order=False, version=None):", "the fast fromfile() function. array = numpy.fromfile(fp, dtype=dtype, count=count) else:", "given by the shape (noting that ``shape=()`` means there is", "structured dtypes, dtypes with fields with empty names will have", "Version numbering ----------------- The version numbering of these formats is", "EOF is encountered before size bytes are read. Non-blocking objects", "passed to `numpy.dtype()` in order to replicate the input dtype.", "format used to create the file. None means use the", "data requires it, else it will always use the more", "we've # already written data to the file. if mode", "a ``.write()`` method. array : ndarray The array to write", "import safe_eval from numpy.compat import ( isfileobj, os_fspath, pickle )", "format. Parameters ---------- fp : filelike object Returns ------- major", "disk. Raises ------ ValueError If the data is invalid, or", "of the array if we are creating a new file", "version. This will leave the file object located just after", ".npy file as a memory-mapped array. This may be used", "dt = descr_to_dtype(descr[0]) return numpy.dtype((dt, descr[1])) titles = [] names", "numbers will yield a little-endian array on any machine reading", "_wrap_header(header, (2, 0)) except UnicodeEncodeError: pass else: warnings.warn(\"Stored array in", "this function will have to copy data in memory. Parameters", "disk. A ``.npz`` file is a zip file containing multiple", "as part of its dtype, the process of pickling them", "Python objects. We need to unpickle the data. if not", "bytes with '' as name # Once support for blank", "this may take extra memory and time. allow_pickle : bool,", "necessary to reconstruct the array correctly even on another machine", "array : numpy.ndarray Returns ------- d : dict This has", "fp: _write_array_header(fp, d, version) offset = fp.tell() else: # Read", "always use the more compatible 1.0 format. The description of", "``.npy`` and ``.npz``. Version numbering ----------------- The version numbering of", "fromfile() function. array = numpy.fromfile(fp, dtype=dtype, count=count) else: # This", "only allowed the array header to have a total size", "a valid dtype descriptor: {!r}\" raise ValueError(msg.format(d['descr'])) from e return", "version=(1, 0)) def read_array_header_2_0(fp): \"\"\" Read an array header from", "header_length = struct.unpack(hlength_type, hlength_str)[0] header = _read_bytes(fp, header_length, \"array header\")", "mean \"copy on write.\" See `memmap` for the available mode", "Python 2 compatible format. Raises ------ ValueError If the array", "describing the array's format. It is an ASCII string which", "dtype def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None): \"\"\" Write an", "version is not None fmt, encoding = _header_size_info[version] if not", "their preferred programming language to read most ``.npy`` files that", "format if the data requires it, else it will always", "Returns ------- dtype : dtype The dtype constructed by the", "array header to have a total size of 65535 bytes.", "_filter_header(header) try: d = safe_eval(header) except SyntaxError as e: msg", "in [(1, 0), (2, 0), (3, 0), None]: msg =", "bool): msg = \"fortran_order is not a valid bool: {!r}\"", "version) if array.itemsize == 0: buffersize = 0 else: #", "format for saving numpy arrays to disk with the full", "memory-intensive way. # crc32 module fails on reads greater than", "be opened correctly. See Also -------- numpy.memmap \"\"\" if isfileobj(filename):", "with. This needs to be fixed in the C implementation", "int The shape of the array if we are creating", "the encoding= option \" \"to numpy.load\" % (err,)) from err", "offset must be page-aligned (i.e. the beginning of the file).", "_read_bytes(fp, MAGIC_LEN, \"magic string\") if magic_str[:-2] != MAGIC_PREFIX: msg =", "of the read. In non-chunked case count < max_read_count, so", "= fp.tell() else: # Read the header of the file", "saved when read. Use another form of storage.\", UserWarning, stacklevel=2)", ": str, optional The mode in which to open the", "Ignore padding bytes, which will be void bytes with ''", "are arbitrary Python objects. Files with object arrays are not", "comes the array data. If the dtype contains Python objects", "length\") header_length = struct.unpack(hlength_type, hlength_str)[0] header = _read_bytes(fp, header_length, \"array", "array using the 1.0 format. Parameters ---------- fp : filelike", "byte is an unsigned byte: the minor version number of", "depending on ``fortran_order``) bytes of the array. Consumers can figure", "mode to a read-write mode since we've # already written", "try: r = fp.read(size - len(data)) data += r if", "and (1, 0) could have been created by a Python", "use the oldest supported version that is able to store", "in descr: if len(field) == 2: name, descr_str = field", "the length of the header data HEADER_LEN.\" Format Version 3.0", "and restored, and the correct dtype may be restored by", "objects (i.e. ``dtype.hasobject is True``), then the data is a", "that works explicit version will raise a ValueError if the", "files that they have been given without much documentation. -", "[] last_token_was_number = False for token in tokenize.generate_tokens(StringIO(s).readline): token_type =", "contain Python objects so we cannot write out the data", "pass the encoding= option \" \"to numpy.load\" % (err,)) from", "\"shape\" : tuple of int # \"fortran_order\" : bool #", "bytes, which will be void bytes with '' as name", "be used to read an existing file or create a", "is upgraded, the code in `numpy.io` will still be able", "shape descr[1] dt = descr_to_dtype(descr[0]) return numpy.dtype((dt, descr[1])) titles =", "Write the header for an array and returns the version", "of int (major, minor) or None If the mode is", "and reduce memory overhead # of the read. In non-chunked", "Instead, we construct descriptor that can be passed to dtype().", "\"\"\" import struct assert version is not None fmt, encoding", "may take extra memory and time. allow_pickle : bool, optional", "like Linux where mmap() # offset must be page-aligned (i.e.", "need to test for C_CONTIGUOUS first # because a 1-D", "convenience only. A writer SHOULD implement this if possible. A", "is performed. # Use np.ndarray instead of np.empty since the", "similar object with a ``.write()`` method. array : ndarray The", "i) read_size = int(read_count * dtype.itemsize) data = _read_bytes(fp, read_size,", "the magic # string, the header-length short and the header", "file format. The arrays with such structures can still be", ": dtype The dtype constructed by the description. \"\"\" if", "not a dictionary: {!r}\" raise ValueError(msg.format(d)) if EXPECTED_KEYS != d.keys():", "the application. In the absence of an obvious alternative, however,", "= (name == '' and dt.type is numpy.void and dt.names", "invalid. \"\"\" return _read_array_header(fp, version=(2, 0)) def _filter_header(s): \"\"\"Clean up", "For repeatability and readability, the dictionary keys are sorted in", "1.17\", UserWarning, stacklevel=2) return header def _write_array_header(fp, d, version=None): \"\"\"", "bytes() while True: # io files (default in python3) return", ": dtype.descr An object that can be passed as an", "= name if isinstance(name, tuple) else (None, name) titles.append(title) names.append(name)", "array cannot be persisted. This includes the case of allow_pickle=False", "be loaded when \" \"allow_pickle=False\") if pickle_kwargs is None: pickle_kwargs", "replicate the input dtype. \"\"\" if _has_metadata(dtype): warnings.warn(\"metadata on a", "read. Use another form of storage.\", UserWarning, stacklevel=2) if dtype.names", "offsets = [] offset = 0 for field in descr:", "version={}\".format(hlen, version) raise ValueError(msg) from None # Pad the header", "contents \"\"\" try: return _wrap_header(header, (1, 0)) except ValueError: pass", "like a record array with one field with '' as", "is not a valid bool: {!r}\" raise ValueError(msg.format(d['fortran_order'])) try: dtype", "accepted for writing, but only the array data will be", "extends the header size to 4 GiB. `numpy.save` will automatically", "a .npy file as a memory-mapped array. This may be", "the available mode strings. dtype : data-type, optional The data", "of 2 bytes (H) allowing storage of large structured arrays", "be # done about that. note that regular files can't", "format allows storing very large structured arrays. .. versionadded:: 1.9.0", "we will pickle it out if not allow_pickle: raise ValueError(\"Object", "pretty-printed string representation of a literal # Python dictionary with", "`_wrap_header`, but chooses an appropriate version given the contents \"\"\"", "file. - Stores object arrays, i.e. arrays containing elements that", "Npy file header. Returns ------- header : str Cleaned up", "saved and restored, and the correct dtype may be restored", "# If we got here, then it should be safe", "%r\\n\" \"You may need to pass the encoding= option \"", "record array. The .descr is fine. XXX: parts of the", "fp.write(chunk.tobytes('C')) else: if isfileobj(fp): array.tofile(fp) else: for chunk in numpy.nditer(", "with a utf8-encoded string, so supports structured types with any", "\"\"\" magic_str = _read_bytes(fp, MAGIC_LEN, \"magic string\") if magic_str[:-2] !=", "order. This is for convenience only. A writer SHOULD implement", "given description. This is essentially the reverse of `dtype_to_descr()`. It", "name == ''\" needed) is_pad = (name == '' and", "not %s\" raise ValueError(msg % (version,)) def magic(major, minor): \"\"\"", "shape (noting that ``shape=()`` means there is 1 element) by", "an extension specific to the application. In the absence of", "(name == '' and dt.type is numpy.void and dt.names is", "ValueError(msg) offset = fp.tell() if fortran_order: order = 'F' else:", "path-like object.\" \" Memmap cannot use existing file handles.\") if", "= field dt = numpy.dtype((descr_to_dtype(descr_str), shape)) # Ignore padding bytes,", "\"\"\" import tokenize from io import StringIO tokens = []", "_header_size_info = { (1, 0): ('<H', 'latin1'), (2, 0): ('<I',", "*single* arbitrary NumPy array on disk. The format stores all", "order to replicate the input dtype. Returns ------- dtype :", "all(isinstance(x, int) for x in d['shape'])): msg = \"shape is", "1.0 format. The description of the fourth element of the", "representation to the header of the file. \"\"\" _write_array_header(fp, d,", "# If dtype.itemsize == 0 then there's nothing more to", "------- marray : memmap The memory-mapped array. Raises ------ ValueError", "are creating a new file in \"write\" mode, if not,", "import tokenize from io import StringIO tokens = [] last_token_was_number", "avoid issue and reduce memory overhead # of the read.", ": bool # \"descr\" : dtype.descr # Versions (2, 0)", "= magic_str[-2:] return major, minor def _has_metadata(dt): if dt.metadata is", "or the mode is invalid. IOError If the file is", "the given description. This is essentially the reverse of `dtype_to_descr()`.", "header length\") header_length = struct.unpack(hlength_type, hlength_str)[0] header = _read_bytes(fp, header_length,", "pickling them may raise various errors if the objects are", "size of buffer for reading npz files in bytes #", "a literal # Python dictionary with trailing newlines padded to", "int which has the length of the # header. import", "copy data in memory. Parameters ---------- fp : file_like object", "or not all(isinstance(x, int) for x in d['shape'])): msg =", "io.BlockingIOError: pass if len(data) != size: msg = \"EOF: reading", "is None, which results in a data-type of `float64`. shape", "{!r}\" raise ValueError(msg.format(d['descr'])) from e return d['shape'], d['fortran_order'], dtype def", "return numpy.dtype({'names': names, 'formats': formats, 'titles': titles, 'offsets': offsets, 'itemsize':", "to create a solution in their preferred programming language to", "field names. Notes ----- The ``.npy`` format, including motivation for", "on a dtype may be saved or ignored, but will", "If the dtype contains Python objects (i.e. ``dtype.hasobject is True``),", "'' as name # Once support for blank names is", "\"\"\" see read_array_header_1_0 \"\"\" # Read an unsigned, little-endian short", "``dtype.itemsize``. Format Version 2.0 ------------------ The version 1.0 format only", "this data. Default: None \"\"\" header = [\"{\"] for key,", "dictionary: {!r}\" raise ValueError(msg.format(d)) if EXPECTED_KEYS != d.keys(): keys =", "the given file format version. Parameters ---------- major : int", "descr[1] dt = descr_to_dtype(descr[0]) return numpy.dtype((dt, descr[1])) titles = []", "``dtype.hasobject is True``), then the data is a Python pickle", "data\"): \"\"\" Read from file-like object until size bytes are", "This is essentially the reverse of `dtype_to_descr()`. It will remove", "else: tokens.append(token) last_token_was_number = (token_type == tokenize.NUMBER) return tokenize.untokenize(tokens) def", "Fortran-contiguous (True) or C-contiguous (False, the default) if we are", "numbering of these formats is independent of NumPy version numbering.", "goals. The ``.npz`` format is the standard format for persisting", "# implementation before header filtering was implemented. if version <=", "the header of the file. version: tuple or None None", "names is removed, only \"if name == ''\" needed) is_pad", "stacklevel=2) return ret header = _wrap_header(header, (3, 0)) warnings.warn(\"Stored array", "version will raise a ValueError if the format does not", "of its dtype, the process of pickling them may raise", "file_like object If this is not a real file object,", "Parameters ---------- fp : file_like object An open, writable file", "be written directly to disk for efficiency. \"shape\" : tuple", "len(data)) data += r if len(r) == 0 or len(data)", "\"long ints\", a reading machine with 32-bit C \"long ints\"", "on any machine reading the file. The types are described", "NumPy >= 1.17\", UserWarning, stacklevel=2) return header def _write_array_header(fp, d,", "if isfileobj(fp): array.T.tofile(fp) else: for chunk in numpy.nditer( array, flags=['external_loop',", "else: if isfileobj(fp): array.tofile(fp) else: for chunk in numpy.nditer( array,", "ValueError(\"major version must be 0 <= major < 256\") if", ".descr is fine. XXX: parts of the # record array", "by dtype.descr. Can be passed to `numpy.dtype()` in order to", "not is_pad: title, name = name if isinstance(name, tuple) else", "dtype The dtype of the file's data. Raises ------ ValueError", "means use the oldest supported version that is able to", "data. Default: None allow_pickle : bool, optional Whether to allow", "useful when loading object arrays saved on Python 2 when", "does # not correctly instantiate zero-width string dtypes; see #", "we ought to create the file. _check_version(version) # Ensure that", "= bytes() while True: # io files (default in python3)", "developer should be able to create a solution in their", "e: msg = \"descr is not a valid dtype descriptor:", "format only allowed the array header to have a total", "be read in Python3. Parameters ---------- s : string Npy", "numpy.ndarray(count, dtype=dtype) if dtype.itemsize > 0: # If dtype.itemsize ==", "tuple or None None means use oldest that works explicit", "= _filter_header(header) try: d = safe_eval(header) except SyntaxError as e:", "dtype_to_descr(array.dtype) return d def _wrap_header(header, version): \"\"\" Takes a stringified", "write_array_header_1_0(fp, d): \"\"\" Write the header for an array using", "- Allows memory-mapping of the data. See `open_memmap`. - Can", "token_string = token[1] if (last_token_was_number and token_type == tokenize.NAME and", "the more compatible 1.0 format. The description of the fourth", "If the format is upgraded, the code in `numpy.io` will", "in the interpretation of structured dtypes, dtypes with fields with", "of ``len(magic string) + 2 + len(length) + HEADER_LEN`` be", "bytes. This can be exceeded by structured arrays with a", "support format version (1,0), (2,0), and (3,0), not %s\" raise", "string, the header-length short and the header are aligned on", "\"Cannot parse header: {!r}\" raise ValueError(msg.format(header)) from e if not", "are supported, and a file with little-endian numbers will yield", "str): # No padding removal needed return numpy.dtype(descr) elif isinstance(descr,", "version 1.0 and 2.0 is a 4 byte (I) header", "supported version that is able to store the data. Default:", "file. None means use the oldest supported version that is", "None: raise ValueError(\"Invalid version {!r}\".format(version)) hlength_type, encoding = hinfo hlength_str", "them. The ``.npy`` format is the standard binary file format", "dtype_to_descr(dtype): \"\"\" Get a serializable descriptor from the dtype. The", "Note: the version of the file format is not tied", "big for version={}\".format(hlen, version) raise ValueError(msg) from None # Pad", "restored by using the ``loadedarray.view(correct_dtype)`` method. File extensions --------------- We", "be a file-like object. mode : str, optional The mode", "# memory-intensive way. # crc32 module fails on reads greater", "exactly ``\\\\x93NUMPY``. The next 1 byte is an unsigned byte:", "try: array = pickle.load(fp, **pickle_kwargs) except UnicodeError as err: #", "allowing storage of large structured arrays _header_size_info = { (1,", "import numpy import io import warnings from numpy.lib.utils import safe_eval", "EXPECTED_KEYS = {'descr', 'fortran_order', 'shape'} MAGIC_PREFIX = b'\\x93NUMPY' MAGIC_LEN =", "# Now read the actual data. if dtype.hasobject: # The", "def read_array(fp, allow_pickle=False, pickle_kwargs=None): \"\"\" Read an array from an", "The object retreived by dtype.descr. Can be passed to `numpy.dtype()`", "hinfo hlength_str = _read_bytes(fp, struct.calcsize(hlength_type), \"array header length\") header_length =", "written to disk. Returns ------- descr : object An object", "if not allow_pickle: raise ValueError(\"Object arrays cannot be saved when", "format. Parameters ---------- fp : filelike object d : dict", "= magic(*version) + struct.pack(fmt, hlen + padlen) except struct.error: msg", "dictionary. It is terminated by a newline (``\\\\n``) and padded", "that can be passed to dtype(). Parameters ---------- dtype :", "not completely preserved. Subclasses will be accepted for writing, but", "header.encode(encoding) hlen = len(header) + 1 padlen = ARRAY_ALIGN -", "using the 1.0 file format version. This will leave the", "form of storage.\", UserWarning, stacklevel=2) if dtype.names is not None:", "as name # Once support for blank names is removed,", "return _read_array_header(fp, version=(2, 0)) def _filter_header(s): \"\"\"Clean up 'L' in", "token in tokenize.generate_tokens(StringIO(s).readline): token_type = token[0] token_string = token[1] if", "that is able to store the data. Default: None allow_pickle", "passed to dtype(). Parameters ---------- dtype : dtype The dtype", "and attaches the prefix and padding to it \"\"\" import", "after the header. Parameters ---------- fp : filelike object A", "0): ('<I', 'latin1'), (3, 0): ('<I', 'utf8'), } def _check_version(version):", "object An open, writable file object, or similar object with", "if not is_pad: title, name = name if isinstance(name, tuple)", "*multiple* NumPy arrays on disk. A ``.npz`` file is a", "and ``.npz`` extensions for files saved in this format. This", "correctly even on another machine with a different architecture. The", "1.0 ------------------ The first 6 bytes are a magic string:", "`numpy.dtype` constructor to create the array's dtype. \"fortran_order\" : bool", "elements given by the shape (noting that ``shape=()`` means there", "upgraded, the code in `numpy.io` will still be able to", "must be 0 <= minor < 256\") return MAGIC_PREFIX +", "dt.metadata is not None: return True elif dt.names is not", "not isinstance(header, bytes): # always true on python 3 header", "write out the data # directly. Instead, we will pickle", "== 0 then there's nothing more to read max_read_count =", "read-write mode since we've # already written data to the", "_wrap_header(header, version) fp.write(header) def write_array_header_1_0(fp, d): \"\"\" Write the header", "truncate, probably nothing can be # done about that. note", "the appropriate entries for writing its string representation to the", "<= major < 256\") if minor < 0 or minor", "int\" writes out an array with \"long ints\", a reading", "r = fp.read(size - len(data)) data += r if len(r)", "open, writable file object, or similar object with a ``.write()``", "Python 3 to Python 2 compatible format. Raises ------ ValueError", "0: # If dtype.itemsize == 0 then there's nothing more", "In addition to the standard file modes, 'c' is also", "versionchanged:: 1.16.3 Made default False in response to CVE-2019-6446. pickle_kwargs", "return d def _wrap_header(header, version): \"\"\" Takes a stringified header,", "Read an array from an NPY file. Parameters ---------- fp", "will be written out. A regular numpy.ndarray object will be", "2.0 is a 4 byte (I) header length # instead", "Pad the header with spaces and a final newline such", "array.itemsize, 1) if array.dtype.hasobject: # We contain Python objects so", "data is Fortran-contiguous or not. Since Fortran-contiguous arrays are a", "correctly instantiate zero-width string dtypes; see # https://github.com/numpy/numpy/pull/6430 array =", "string representation of a literal # Python dictionary with trailing", "array.shape = shape[::-1] array = array.transpose() else: array.shape = shape", "overhead # of the read. In non-chunked case count <", "Supports Fortran-contiguous arrays directly. - Stores all of the necessary", "on systems like Linux where mmap() # offset must be", "got %d\" raise ValueError(msg % (error_template, size, len(data))) else: return", "if array.itemsize == 0: buffersize = 0 else: # Set", "a filelike object using the 1.0 file format version. This", "descriptor: {!r}\" raise ValueError(msg.format(d['descr'])) from e return d['shape'], d['fortran_order'], dtype", "\"allow_pickle=False\") if pickle_kwargs is None: pickle_kwargs = {} try: array", "of the array. Otherwise the data is the contiguous (either", "using the 2.0 format. The 2.0 format allows storing very", "int) or None, optional The version number of the format.", "and is thus optional. fortran_order : bool, optional Whether the", "therefore has become: \"The next 4 bytes form a little-endian", "dtype.descr # Versions (2, 0) and (1, 0) could have", "the field names will differ. We are working on a", "C-contiguous or Fortran-contiguous. Otherwise, it will be made contiguous before", "pickle_kwargs : dict Additional keyword arguments to pass to pickle.load.", "write to disk. version : (int, int) or None, optional", "Datasets often live longer than the programs that created them.", "of the file format used to create the file. None", "data. Raises ------ ValueError If the data is invalid. \"\"\"", "= \"we only support format version (1,0), (2,0), and (3,0),", "Additional keyword arguments to pass to pickle.dump, excluding 'protocol'. These", "should be able to create a solution in their preferred", "disk. This may *not* be a file-like object. mode :", "standard binary file format in NumPy for persisting a *single*", "nothing can be # done about that. note that regular", "Fortran-contiguous AND the file_like object is not a real file", "fast fromfile() function. array = numpy.fromfile(fp, dtype=dtype, count=count) else: #", "== '' and dt.type is numpy.void and dt.names is None)", "if dtype.names is not None: # This is a record", "be \" \"read by NumPy >= 1.17\", UserWarning, stacklevel=2) return", "of the header data HEADER_LEN. The next HEADER_LEN bytes form", "https://github.com/numpy/numpy/pull/6430 array = numpy.ndarray(count, dtype=dtype) if dtype.itemsize > 0: #", "We need to change a write-only mode to a read-write", "raise ValueError(msg) from None # Pad the header with spaces", "dtypes, dtypes with fields with empty names will have the", "_read_array_header(fp, version=(1, 0)) def read_array_header_2_0(fp): \"\"\" Read an array header", "the shape (noting that ``shape=()`` means there is 1 element)", ": file_like object If this is not a real file", "dtype information necessary to reconstruct the array correctly even on", "the file format. The arrays with such structures can still", "absence of an obvious alternative, however, we suggest using ``.npy``", "upon reading the file. .. warning:: Due to limitations in", "will not require a change in the file format. The", "== tokenize.NAME and token_string == \"L\"): continue else: tokens.append(token) last_token_was_number", "the header of the file. \"\"\" d = {'shape': array.shape}", "contiguous before writing it out. dtype : dtype The dtype", "to the version of the numpy package. The next 2", "and a file with little-endian numbers will yield a little-endian", "header data describing the array's format. It is an ASCII", "the data is invalid. \"\"\" return _read_array_header(fp, version=(1, 0)) def", "object. mode : str, optional The mode in which to", "streams. Chunk reads to # BUFFER_SIZE bytes to avoid issue", "data-type, optional The data type of the array if we", "format is designed to be as simple as possible while", "string is not correct; expected %r, got %r\" raise ValueError(msg", "shape of the array. fortran_order : bool The array data", "them. A competent developer should be able to create a", "and token_string == \"L\"): continue else: tokens.append(token) last_token_was_number = (token_type", "if not, `dtype` is ignored. The default value is None,", "arrays. - Represents the data in its native binary form.", "+ HEADER_LEN`` be evenly divisible by 64 for alignment purposes.", "def _read_array_header(fp, version): \"\"\" see read_array_header_1_0 \"\"\" # Read an", "magic(*version) + struct.pack(fmt, hlen + padlen) except struct.error: msg =", "be passed to `numpy.dtype()` in order to replicate the input", "else (None, name) titles.append(title) names.append(name) formats.append(dt) offsets.append(offset) offset += dt.itemsize", "is_pad: title, name = name if isinstance(name, tuple) else (None,", "dtypes with fields with empty names will have the names", "// array.itemsize, 1) if array.dtype.hasobject: # We contain Python objects", "# Friendlier error message raise UnicodeError(\"Unpickling a python object failed:", "as a dtype object. dtype = numpy.dtype(dtype) if dtype.hasobject: msg", "files. Format Version 1.0 ------------------ The first 6 bytes are", "flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize, order='F'): fp.write(chunk.tobytes('C')) else: if isfileobj(fp): array.tofile(fp)", "offset = 0 for field in descr: if len(field) ==", "for the given file format version. Parameters ---------- major :", "------- array : ndarray The array from the data on", "This supports memory mapping of dtypes # aligned up to", "\"Header does not contain the correct keys: {!r}\" raise ValueError(msg.format(keys))", "will be made contiguous before writing it out. dtype :", "1-D array is both C_CONTIGUOUS and F_CONTIGUOUS. d['fortran_order'] = False", "take extra memory and time. allow_pickle : bool, optional Whether", "ValueError(msg) d = dict( descr=dtype_to_descr(dtype), fortran_order=fortran_order, shape=shape, ) # If", "pickle_kwargs=None): \"\"\" Write an array to an NPY file, including", "ValueError(msg.format(keys)) # Sanity-check the values. if (not isinstance(d['shape'], tuple) or", "if not allow_pickle: raise ValueError(\"Object arrays cannot be loaded when", "0 or minor > 255: raise ValueError(\"minor version must be", "cannot be formatted. \"\"\" if major < 0 or major", "array is both C_CONTIGUOUS and F_CONTIGUOUS. d['fortran_order'] = False d['descr']", "keyword arguments to pass to pickle.dump, excluding 'protocol'. These are", "latin1) with a utf8-encoded string, so supports structured types with", "C implementation of # dtype(). return dtype.descr else: return dtype.str", "ValueError(msg.format(d['fortran_order'])) try: dtype = descr_to_dtype(d['descr']) except TypeError as e: msg", "creating a new file in \"write\" mode. version : tuple", "this as a request to give a default name. Instead,", "and readability, the dictionary keys are sorted in alphabetic order.", "that are arbitrary Python objects. Files with object arrays are", "first. with open(os_fspath(filename), 'rb') as fp: version = read_magic(fp) _check_version(version)", "to ARRAY_ALIGN on systems like Linux where mmap() # offset", "are powers of 2 between 16 and 4096 BUFFER_SIZE =", "on disk. Raises ------ ValueError If the data is invalid,", "allow_pickle : bool, optional Whether to allow writing pickled data.", "< 256\") return MAGIC_PREFIX + bytes([major, minor]) def read_magic(fp): \"\"\"", "array = array.transpose() else: array.shape = shape return array def", "more to read max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize) for", "isinstance(d, dict): msg = \"Header is not a dictionary: {!r}\"", "the oldest supported version that is able to store the", "from gzip streams. Chunk reads to # BUFFER_SIZE bytes to", "mode is invalid. IOError If the file is not found", "given dtype is an authentic dtype object rather # than", "strings. dtype : data-type, optional The data type of the", "'formats': formats, 'titles': titles, 'offsets': offsets, 'itemsize': offset}) def header_data_from_array_1_0(array):", "required. Otherwise, this parameter is ignored and is thus optional.", "still be able to read and write Version 1.0 files.", "using Python 3. Returns ------- array : ndarray The array", "Otherwise, this parameter is ignored and is thus optional. fortran_order", "unsigned byte: the major version number of the file format,", "and padded with spaces (``\\\\x20``) to make the total of", "to read and write Version 1.0 files. Format Version 1.0", "to test for C_CONTIGUOUS first # because a 1-D array", "objects in dtype.\" raise ValueError(msg) d = dict( descr=dtype_to_descr(dtype), fortran_order=fortran_order,", "supported, and a file with little-endian numbers will yield a", "a new file in \"write\" mode. version : tuple of", "of numpy.ndarray are not completely preserved. Subclasses will be accepted", "'' as a name. The dtype() constructor interprets this as", "with spaces and a final newline such that the magic", "applications may wish to use these file formats but use", "version replaces the ASCII string (which in practice was latin1)", "# The header is a pretty-printed string representation of a", "\"\"\" Like `_wrap_header`, but chooses an appropriate version given the", "while True: # io files (default in python3) return None", "Read the header of the file first. with open(os_fspath(filename), 'rb')", "header.decode(encoding) # The header is a pretty-printed string representation of", "_wrap_header_guess_version(header) else: header = _wrap_header(header, version) fp.write(header) def write_array_header_1_0(fp, d):", "format. Raises ------ ValueError If the array cannot be persisted.", "a file. Returns ------- shape : tuple of int The", "as a name. The dtype() constructor interprets this as a", "so # only one read is performed. # Use np.ndarray", "to it \"\"\" import struct assert version is not None", "the data # directly. Instead, we will pickle it out", "header_prefix + header + b' '*padlen + b'\\n' def _wrap_header_guess_version(header):", "# not correctly instantiate zero-width string dtypes; see # https://github.com/numpy/numpy/pull/6430", "if we ought to create the file. _check_version(version) # Ensure", "array correctly even on another machine with a different architecture.", "to a read-write mode since we've # already written data", "become: \"The next 4 bytes form a little-endian unsigned int:", "version {!r}\".format(version)) hlength_type, encoding = hinfo hlength_str = _read_bytes(fp, struct.calcsize(hlength_type),", "MAGIC_PREFIX + bytes([major, minor]) def read_magic(fp): \"\"\" Read the magic", "bytes, # breaking large reads from gzip streams. Chunk reads", "in \"write\" mode, in which case this parameter is required.", "may wish to use these file formats but use an", "reverse of `dtype_to_descr()`. It will remove the valueless padding fields", "\"allow_pickle=False\") if pickle_kwargs is None: pickle_kwargs = {} pickle.dump(array, fp,", "2.0 format. The 2.0 format allows storing very large structured", "read is performed. # Use np.ndarray instead of np.empty since", "contains Python objects (i.e. ``dtype.hasobject is True``), then the data", "object arrays. - Represents the data in its native binary", "descriptor from the dtype. The .descr attribute of a dtype", "performed. # Use np.ndarray instead of np.empty since the latter", "See Also -------- numpy.memmap \"\"\" if isfileobj(filename): raise ValueError(\"Filename must", "it will always use the more compatible 1.0 format. The", "three keys: \"descr\" : dtype.descr An object that can be", "repr here, since we eval these when reading header.append(\"'%s': %s,", "to disk with the full information about them. The ``.npy``", "written out directly if it is either C-contiguous or Fortran-contiguous.", "object, then this may take extra memory and time. allow_pickle", "struct.pack(fmt, hlen + padlen) except struct.error: msg = \"Header length", "2 ** 32 bytes, # breaking large reads from gzip", "objects in dtype.\" raise ValueError(msg) offset = fp.tell() if fortran_order:", "it and a comparison of alternatives, is described in the", "d.keys(): keys = sorted(d.keys()) msg = \"Header does not contain", "this parameter is required. Otherwise, this parameter is ignored and", "fp: version = read_magic(fp) _check_version(version) shape, fortran_order, dtype = _read_array_header(fp,", "= numpy.ndarray(count, dtype=dtype) if dtype.itemsize > 0: # If dtype.itemsize", "NPY format ========== A simple format for saving numpy arrays", "Need to use repr here, since we eval these when", "disk. version : (int, int) or None, optional The version", "# Totally non-contiguous data. We will have to make it", "object using the 2.0 file format version. This will leave", "Parameters ---------- fp : filelike object d : dict This", "2.0 file format version. This will leave the file object", "parts of the # record array with an empty name,", "hlen) % ARRAY_ALIGN) try: header_prefix = magic(*version) + struct.pack(fmt, hlen", "able to store the data. Default: None allow_pickle : bool,", "bytes form the header data describing the array's format. It", "object or something with a `.read()` method like a file.", "are working on a fix for this. This fix will", "2 bytes (H) allowing storage of large structured arrays _header_size_info", "the version of the file format. Parameters ---------- fp :", "to disk for efficiency. \"shape\" : tuple of int The", "the number of bytes by multiplying the number of elements", "read_count = min(max_read_count, count - i) read_size = int(read_count *", "offset=offset) return marray def _read_bytes(fp, size, error_template=\"ran out of data\"):", "the 'L' in strings representing integers. Needed to allow npz", "big-endian arrays are supported, and a file with little-endian numbers", "the file format. Parameters ---------- fp : filelike object Returns", "Version 2.0 ------------------ The version 1.0 format only allowed the", "its string representation to the header of the file. \"\"\"", "little-endian unsigned short int: the length of the header data", "len(r) == 0 or len(data) == size: break except io.BlockingIOError:", "is invalid. \"\"\" return _read_array_header(fp, version=(1, 0)) def read_array_header_2_0(fp): \"\"\"", "contiguous (either C- or Fortran-, depending on ``fortran_order``) bytes of", "as a request to give a default name. Instead, we", "else: return dtype.str def descr_to_dtype(descr): \"\"\" Returns a dtype based", "keys are strings. # \"shape\" : tuple of int #", "# BUFFER_SIZE bytes to avoid issue and reduce memory overhead", "cannot be saved when \" \"allow_pickle=False\") if pickle_kwargs is None:", "file first. with open(os_fspath(filename), 'rb') as fp: version = read_magic(fp)", "== tokenize.NUMBER) return tokenize.untokenize(tokens) def _read_array_header(fp, version): \"\"\" see read_array_header_1_0", "> 255: raise ValueError(\"major version must be 0 <= major", "to have a total size of 65535 bytes. This can", "extensions for files saved in this format. This is by", "version numbering of these formats is independent of NumPy version", "but chooses an appropriate version given the contents \"\"\" try:", "mode : str, optional The mode in which to open", "d, version=None): \"\"\" Write the header for an array and", "example, if a machine with a 64-bit C \"long int\"", "version of the file format is not tied to the", "numpy.ndarray are not completely preserved. Subclasses will be accepted for", "version : tuple of int (major, minor) or None If", "numpy.frombuffer(data, dtype=dtype, count=read_count) if fortran_order: array.shape = shape[::-1] array =", "import StringIO tokens = [] last_token_was_number = False for token", "the file. \"\"\" d = {'shape': array.shape} if array.flags.c_contiguous: d['fortran_order']", "record array with an empty name, like padding bytes, still", "[] EXPECTED_KEYS = {'descr', 'fortran_order', 'shape'} MAGIC_PREFIX = b'\\x93NUMPY' MAGIC_LEN", "Python 2 when using Python 3. Returns ------- array :", "If we got here, then it should be safe to", "will raise a ValueError if the format does not allow", "__all__ = [] EXPECTED_KEYS = {'descr', 'fortran_order', 'shape'} MAGIC_PREFIX =", "data = bytes() while True: # io files (default in", "a `.read()` method like a file. Returns ------- shape :", "Whether the array data is Fortran-contiguous or not. Since Fortran-contiguous", "It is an ASCII string which contains a Python literal", "descr : object An object that can be passed to", "dt.type is numpy.void and dt.names is None) if not is_pad:", "new file in \"write\" mode, in which case this parameter", "magic_str[:-2] != MAGIC_PREFIX: msg = \"the magic string is not", "e.g. ``\\\\x00``. Note: the version of the file format is", "array header from a filelike object using the 2.0 file", "for alignment purposes. The dictionary contains three keys: \"descr\" :", "with empty names will have the names replaced by 'f0',", "serializable descriptor from the dtype. The .descr attribute of a", "name = name if isinstance(name, tuple) else (None, name) titles.append(title)", "The version numbering of these formats is independent of NumPy", "d, version) offset = fp.tell() else: # Read the header", ".. versionadded:: 1.9.0 Parameters ---------- fp : filelike object d", "= 2**18 # size of buffer for reading npz files", "works explicit version will raise a ValueError if the format", "(2, 0) and (1, 0) could have been created by", "keys: \"descr\" : dtype.descr An object that can be passed", "are creating the file, not reading it. # Check if", "version number of the file format, e.g. ``\\\\x01``. The next", "implementation before header filtering was implemented. if version <= (2,", "Takes a stringified header, and attaches the prefix and padding", "\"The next 4 bytes form a little-endian unsigned int: the", "msg = \"the magic string is not correct; expected %r,", "This has the appropriate entries for writing its string representation", "create a new one. Parameters ---------- filename : str or", "for version={}\".format(hlen, version) raise ValueError(msg) from None # Pad the", "for efficiency. \"shape\" : tuple of int The shape of", "be formatted. \"\"\" if major < 0 or major >", "if saved when read. Use another form of storage.\", UserWarning,", "header filtering was implemented. if version <= (2, 0): header", "are a common form of non-C-contiguity, we allow them to", "len(data) != size: msg = \"EOF: reading %s, expected %d", "minor < 0 or minor > 255: raise ValueError(\"minor version", "an ASCII string which contains a Python literal expression of", "including shape and dtype on a machine of a different", "with an empty name, like padding bytes, still get #", "255] Returns ------- magic : str Raises ------ ValueError if", "Can be passed to `numpy.dtype()` in order to replicate the", "dtype constructed by the description. \"\"\" if isinstance(descr, str): #", "including nested record arrays and object arrays. - Represents the", "version of the file format. Parameters ---------- fp : filelike", "EXPECTED_KEYS != d.keys(): keys = sorted(d.keys()) msg = \"Header does", "allow writing pickled data. Default: True pickle_kwargs : dict, optional", "and dt.names is None) if not is_pad: title, name =", "{'shape': array.shape} if array.flags.c_contiguous: d['fortran_order'] = False elif array.flags.f_contiguous: d['fortran_order']", "``.npy`` format is the standard binary file format in NumPy", "(1, 0)) except ValueError: pass try: ret = _wrap_header(header, (2,", "== 0: buffersize = 0 else: # Set buffer size", "entirely accurately. The data is intact; only the field names", "is removed, only \"if name == ''\" needed) is_pad =", "terms of their actual sizes. For example, if a machine", "format ========== A simple format for saving numpy arrays to", "and a comparison of alternatives, is described in the :doc:`\"npy-format\"", "= _read_bytes(fp, read_size, \"array data\") array[i:i+read_count] = numpy.frombuffer(data, dtype=dtype, count=read_count)", "to store the data. Default: None allow_pickle : bool, optional", "information necessary to reconstruct the array correctly even on another", "numpy.compat import ( isfileobj, os_fspath, pickle ) __all__ = []", "dtype(). Parameters ---------- dtype : dtype The dtype of the", "- Can represent all NumPy arrays including nested record arrays", "with trailing newlines padded to a ARRAY_ALIGN byte # boundary.", "non-blocking try: r = fp.read(size - len(data)) data += r", "{!r}\".format(version)) hlength_type, encoding = hinfo hlength_str = _read_bytes(fp, struct.calcsize(hlength_type), \"array", "= [] offsets = [] offset = 0 for field", "SyntaxError as e: msg = \"Cannot parse header: {!r}\" raise", "raise ValueError(msg) d = dict( descr=dtype_to_descr(dtype), fortran_order=fortran_order, shape=shape, ) #", "\"\"\" import numpy import io import warnings from numpy.lib.utils import", "fixed in the C implementation of # dtype(). return dtype.descr", "still be saved and restored, and the correct dtype may", "of `float64`. shape : tuple of int The shape of", "= False elif array.flags.f_contiguous: d['fortran_order'] = True else: # Totally", "= { (1, 0): ('<H', 'latin1'), (2, 0): ('<I', 'latin1'),", "for writing its string representation to the header of the", "of the file. \"\"\" _write_array_header(fp, d, (1, 0)) def write_array_header_2_0(fp,", "array data will be written out. A regular numpy.ndarray object", "def _write_array_header(fp, d, version=None): \"\"\" Write the header for an", "fp.write(header) def write_array_header_1_0(fp, d): \"\"\" Write the header for an", "preferred programming language to read most ``.npy`` files that they", "if EXPECTED_KEYS != d.keys(): keys = sorted(d.keys()) msg = \"Header", "the 2.0 format. The 2.0 format allows storing very large", "2 compatible format. Raises ------ ValueError If the array cannot", "!= MAGIC_PREFIX: msg = \"the magic string is not correct;", "- Can be read from a filelike stream object instead", "\"\"\" # Read an unsigned, little-endian short int which has", "python2 file will truncate, probably nothing can be # done", "header of the file. \"\"\" _write_array_header(fp, d, (2, 0)) def", "{!r}\" raise ValueError(msg.format(d)) if EXPECTED_KEYS != d.keys(): keys = sorted(d.keys())", "accepted to mean \"copy on write.\" See `memmap` for the", "field names will differ. We are working on a fix", "the header with spaces and a final newline such that", "looks like a record array with one field with ''", "ValueError If the data is invalid. \"\"\" return _read_array_header(fp, version=(2,", "(default in python3) return None or raise on # would-block,", "\"write\" mode. version : tuple of int (major, minor) or", "An object that can be passed as an argument to", "i.e. simple fields like dtype('float32'), and then convert the description", "expected %r, got %r\" raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2])) major,", "in npz header ints. Cleans up the 'L' in strings", "allow_pickle=False, pickle_kwargs=None): \"\"\" Read an array from an NPY file.", "header for an array using the 1.0 format. Parameters ----------", "2.0 format extends the header size to 4 GiB. `numpy.save`", "name, descr_str, shape = field dt = numpy.dtype((descr_to_dtype(descr_str), shape)) #", "k in dt.names) elif dt.subdtype is not None: return _has_metadata(dt.base)", "a dtype object cannot be round-tripped through the dtype() constructor.", "NOT depend on this. Following the header comes the array", "the file; the default is 'r+'. In addition to the", "evolved with time and this document is more current. \"\"\"", "mode, in which case this parameter is required. Otherwise, this", "is a \"write\" mode, then this is the version of", "numpy import io import warnings from numpy.lib.utils import safe_eval from", "tuple of int The shape of the array if we", "the prefix and padding to it \"\"\" import struct assert", "spaces (``\\\\x20``) to make the total of ``len(magic string) +", "from None # Pad the header with spaces and a", "2 between 16 and 4096 BUFFER_SIZE = 2**18 # size", "else: order = 'C' # We need to change a", "array data will be written out directly if it is", "is None: raise ValueError(\"Invalid version {!r}\".format(version)) hlength_type, encoding = hinfo", "solution in their preferred programming language to read most ``.npy``", "give a default name. Instead, we construct descriptor that can", "writing pickled data. Default: False .. versionchanged:: 1.16.3 Made default", "_write_array_header(fp, d, version=None): \"\"\" Write the header for an array", "``\\\\x00``. Note: the version of the file format is not", "the dtype. The .descr attribute of a dtype object cannot", "open_memmap(filename, mode='r+', dtype=None, shape=None, fortran_order=False, version=None): \"\"\" Open a .npy", "Use another form of storage.\", UserWarning, stacklevel=2) if dtype.names is", "fortran_order, dtype = _read_array_header(fp, version) if len(shape) == 0: count", "failed: %r\\n\" \"You may need to pass the encoding= option", "mode == 'w+': mode = 'r+' marray = numpy.memmap(filename, dtype=dtype,", "def read_array_header_1_0(fp): \"\"\" Read an array header from a filelike", "the header of the file first. with open(os_fspath(filename), 'rb') as", "continue else: tokens.append(token) last_token_was_number = (token_type == tokenize.NUMBER) return tokenize.untokenize(tokens)", "needs to be fixed in the C implementation of #", "struct.calcsize(hlength_type), \"array header length\") header_length = struct.unpack(hlength_type, hlength_str)[0] header =", "attaches the prefix and padding to it \"\"\" import struct", "version number of the format. None means use the oldest", "= numpy.memmap(filename, dtype=dtype, shape=shape, order=order, mode=mode, offset=offset) return marray def", "in range(0, count, max_read_count): read_count = min(max_read_count, count - i)", "2.0 ------------------ The version 1.0 format only allowed the array", "dictionary of header metadata from a numpy.ndarray. Parameters ---------- array", "the file. if mode == 'w+': mode = 'r+' marray", "shape of the array if we are creating a new", "`float64`. shape : tuple of int The shape of the", "error_template=\"ran out of data\"): \"\"\" Read from file-like object until", "the names replaced by 'f0', 'f1', etc. Such arrays will", "the read. In non-chunked case count < max_read_count, so #", "the format is upgraded, the code in `numpy.io` will still", "# record array with an empty name, like padding bytes,", "(3, 0): ('<I', 'utf8'), } def _check_version(version): if version not", "of the file format, e.g. ``\\\\x01``. The next 1 byte", "read an existing file or create a new one. Parameters", "minor def _has_metadata(dt): if dt.metadata is not None: return True", "write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None): \"\"\" Write an array to", "*not* be a file-like object. mode : str, optional The", "- Arbitrary subclasses of numpy.ndarray are not completely preserved. Subclasses", "isinstance(descr, tuple): # subtype, will always have a shape descr[1]", "else: # Totally non-contiguous data. We will have to make", "allowed the array header to have a total size of", "straightforward to reverse engineer. Datasets often live longer than the", "We recommend using the ``.npy`` and ``.npz`` extensions for files", "pickle it out if not allow_pickle: raise ValueError(\"Object arrays cannot", "dtype=numpy.int64) # Now read the actual data. if dtype.hasobject: #", "mode, then this is the version of the file format", "simple fields like dtype('float32'), and then convert the description to", "BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize) for i in range(0, count, max_read_count):", "as e.g. ZipExtFile in python 2.6 can return less data", "struct.calcsize(fmt) + hlen) % ARRAY_ALIGN) try: header_prefix = magic(*version) +", "The first 6 bytes are a magic string: exactly ``\\\\x93NUMPY``.", "# \"shape\" : tuple of int # \"fortran_order\" : bool", "Friendlier error message raise UnicodeError(\"Unpickling a python object failed: %r\\n\"", "a change in the file format. The arrays with such", "int minor : int \"\"\" magic_str = _read_bytes(fp, MAGIC_LEN, \"magic", "return array def open_memmap(filename, mode='r+', dtype=None, shape=None, fortran_order=False, version=None): \"\"\"", "names will differ. We are working on a fix for", "objects only supported if they derive from io objects. Required", "representing integers. Needed to allow npz headers produced in Python2", "ASCII string which contains a Python literal expression of a", "0 or major > 255: raise ValueError(\"major version must be", "1.0 files. Format Version 1.0 ------------------ The first 6 bytes", "the file format used to create the file. None means", "saving numpy arrays to disk with the full information about", "the array. fortran_order : bool The array data will be", "raise ValueError(msg.format(d)) if EXPECTED_KEYS != d.keys(): keys = sorted(d.keys()) msg", "raise ValueError(msg.format(d['fortran_order'])) try: dtype = descr_to_dtype(d['descr']) except TypeError as e:", "Read an array header from a filelike object using the", "array. This may be used to read an existing file", "will be created upon reading the file. .. warning:: Due", "return numpy.dtype(descr) elif isinstance(descr, tuple): # subtype, will always have", "filename : str or path-like The name of the file", "loop overhead. buffersize = max(16 * 1024 ** 2 //", "valueless padding fields created by, i.e. simple fields like dtype('float32'),", "_read_bytes(fp, read_size, \"array data\") array[i:i+read_count] = numpy.frombuffer(data, dtype=dtype, count=read_count) if", "opened correctly. See Also -------- numpy.memmap \"\"\" if isfileobj(filename): raise", "'latin1'), (3, 0): ('<I', 'utf8'), } def _check_version(version): if version", "or minor > 255: raise ValueError(\"minor version must be 0", "# We can use the fast fromfile() function. array =", "names = [] formats = [] offsets = [] offset", "False def dtype_to_descr(dtype): \"\"\" Get a serializable descriptor from the", "= len(header) + 1 padlen = ARRAY_ALIGN - ((MAGIC_LEN +", "minor) or None If the mode is a \"write\" mode,", "they have been given without much documentation. - Allows memory-mapping", "= \"\".join(header) if version is None: header = _wrap_header_guess_version(header) else:", "Like `_wrap_header`, but chooses an appropriate version given the contents", "an NPY file. Parameters ---------- fp : file_like object If", "str or path-like The name of the file on disk.", "a string or a path-like object.\" \" Memmap cannot use", "bytes to avoid issue and reduce memory overhead # of", "are not to be mmapable, but can be read and", "are a magic string: exactly ``\\\\x93NUMPY``. The next 1 byte", "be fixed in the C implementation of # dtype(). return", "data in its native binary form. - Supports Fortran-contiguous arrays", "arrays are a common form of non-C-contiguity, we allow them", "field dt = numpy.dtype((descr_to_dtype(descr_str), shape)) # Ignore padding bytes, which", "next 1 byte is an unsigned byte: the major version", "all of the necessary information to reconstruct the array including", "magic_str = _read_bytes(fp, MAGIC_LEN, \"magic string\") if magic_str[:-2] != MAGIC_PREFIX:", "sizes. For example, if a machine with a 64-bit C", "will leave the file object located just after the header.", "ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize(fmt) + hlen) % ARRAY_ALIGN) try:", "if the version cannot be formatted. \"\"\" if major <", "\" \"allow_pickle=False\") if pickle_kwargs is None: pickle_kwargs = {} pickle.dump(array,", "ValueError If the data is invalid. \"\"\" return _read_array_header(fp, version=(1,", "\"descr\" : dtype.descr # Versions (2, 0) and (1, 0)", "HEADER_LEN. The next HEADER_LEN bytes form the header data describing", "description of the fourth element of the header therefore has", ": dict Additional keyword arguments to pass to pickle.load. These", "value in sorted(d.items()): # Need to use repr here, since", "We will have to make it C-contiguous # before writing.", "when loading object arrays saved on Python 2 when using", "= dict( descr=dtype_to_descr(dtype), fortran_order=fortran_order, shape=shape, ) # If we got", "if isfileobj(filename): raise ValueError(\"Filename must be a string or a", "XXX: parts of the # record array with an empty", ": filelike object d : dict This has the appropriate", "very large structured arrays. .. versionadded:: 1.9.0 Parameters ---------- fp", "before size bytes are read. Non-blocking objects only supported if", "offset}) def header_data_from_array_1_0(array): \"\"\" Get the dictionary of header metadata", "replicate the input dtype. Returns ------- dtype : dtype The", "== size: break except io.BlockingIOError: pass if len(data) != size:", "dtype The dtype constructed by the description. \"\"\" if isinstance(descr,", "The array contained Python objects. We need to unpickle the", "for persisting *multiple* NumPy arrays on disk. A ``.npz`` file", "files, one for each array. Capabilities ------------ - Can represent", "shape[::-1] array = array.transpose() else: array.shape = shape return array", "more compatible 1.0 format. The description of the fourth element", "name, like padding bytes, still get # fiddled with. This", "used Parameters ---------- fp : filelike object d : dict", "fortran_order : bool The array data will be written out", "raise ValueError(msg.format(header)) from e if not isinstance(d, dict): msg =", "names will have the names replaced by 'f0', 'f1', etc.", "array on disk. The format stores all of the shape", "the ASCII string (which in practice was latin1) with a", "valid dtype descriptor: {!r}\" raise ValueError(msg.format(d['descr'])) from e return d['shape'],", "array[i:i+read_count] = numpy.frombuffer(data, dtype=dtype, count=read_count) if fortran_order: array.shape = shape[::-1]", "to its corresponding dtype. Parameters ---------- descr : object The", "1024 ** 2 // array.itemsize, 1) if array.dtype.hasobject: # We", "used to create the file. None means use the oldest", "shape : tuple of int The shape of the array.", "of the array. Consumers can figure out the number of", "to replicate the input dtype. \"\"\" if _has_metadata(dtype): warnings.warn(\"metadata on", "False for token in tokenize.generate_tokens(StringIO(s).readline): token_type = token[0] token_string =", "max(16 * 1024 ** 2 // array.itemsize, 1) if array.dtype.hasobject:", "file; the default is 'r+'. In addition to the standard", "_check_version(version) shape, fortran_order, dtype = _read_array_header(fp, version) if dtype.hasobject: msg", "depend on this. Following the header comes the array data.", "file. with open(os_fspath(filename), mode+'b') as fp: _write_array_header(fp, d, version) offset", "in numpy.nditer( array, flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize, order='F'): fp.write(chunk.tobytes('C')) else:", "by the shape (noting that ``shape=()`` means there is 1", "message raise UnicodeError(\"Unpickling a python object failed: %r\\n\" \"You may", "(False, the default) if we are creating a new file", "the header data describing the array's format. It is an", "filelike object using the 1.0 file format version. This will", "C \"long int\" writes out an array with \"long ints\",", "an obvious alternative, however, we suggest using ``.npy`` and ``.npz``.", "filelike stream object instead of an actual file. - Stores", "be saved when \" \"allow_pickle=False\") if pickle_kwargs is None: pickle_kwargs", "bool, optional Whether to allow writing pickled data. Default: False", "string Npy file header. Returns ------- header : str Cleaned", "hinfo is None: raise ValueError(\"Invalid version {!r}\".format(version)) hlength_type, encoding =", "not array.flags.c_contiguous: if isfileobj(fp): array.T.tofile(fp) else: for chunk in numpy.nditer(", "int in [0, 255] minor : int in [0, 255]", "The ``.npz`` format is the standard format for persisting *multiple*", "header from a filelike object using the 1.0 file format", "from a filelike object using the 1.0 file format version.", "'latin1'), (2, 0): ('<I', 'latin1'), (3, 0): ('<I', 'utf8'), }", "instead of np.empty since the latter does # not correctly", "a real file object, this function will have to copy", "the objects are not picklable. \"\"\" _check_version(version) _write_array_header(fp, header_data_from_array_1_0(array), version)", "to the standard file modes, 'c' is also accepted to", "to reconstruct the array correctly even on another machine with", "pickle ) __all__ = [] EXPECTED_KEYS = {'descr', 'fortran_order', 'shape'}", "isfileobj(fp): array.tofile(fp) else: for chunk in numpy.nditer( array, flags=['external_loop', 'buffered',", "store the data. Default: None Returns ------- marray : memmap", "it is either C-contiguous or Fortran-contiguous. Otherwise, it will be", "includes the case of allow_pickle=False and array being an object", "data will be written out directly if it is either", "the array data is Fortran-contiguous or not. Since Fortran-contiguous arrays", "``.npy`` files that they have been given without much documentation.", "a name. The dtype() constructor interprets this as a request", "to disk. Returns ------- descr : object An object that", "entries for writing its string representation to the header of", "except UnicodeError as err: # Friendlier error message raise UnicodeError(\"Unpickling", "the file. \"\"\" _write_array_header(fp, d, (1, 0)) def write_array_header_2_0(fp, d):", "a machine with a 64-bit C \"long int\" writes out", "the contents \"\"\" try: return _wrap_header(header, (1, 0)) except ValueError:", "created by a Python 2 # implementation before header filtering", "------ ValueError if the version cannot be formatted. \"\"\" if", "of np.empty since the latter does # not correctly instantiate", "arrays with a large number of columns. The version 2.0", "create a solution in their preferred programming language to read", "C-contiguous nor Fortran-contiguous AND the file_like object is not a", "Simple types, like dtype('float32'), have a descr which looks like", "the header. .. versionadded:: 1.9.0 Parameters ---------- fp : filelike", "can only be \" \"read by NumPy >= 1.17\", UserWarning,", "practice was latin1) with a utf8-encoded string, so supports structured", "for reading npz files in bytes # difference between version", "hlength_type, encoding = hinfo hlength_str = _read_bytes(fp, struct.calcsize(hlength_type), \"array header", "represent all NumPy arrays including nested record arrays and object", "the array cannot be persisted. This includes the case of", "of these formats is independent of NumPy version numbering. If", "major, minor def _has_metadata(dt): if dt.metadata is not None: return", "objects in object arrays on Python 3 to Python 2", "names replaced by 'f0', 'f1', etc. Such arrays will not", "fortran_order: array.shape = shape[::-1] array = array.transpose() else: array.shape =", "will differ. We are working on a fix for this.", "not to be mmapable, but can be read and written", "\"\"\" Write an array to an NPY file, including a", "format 3.0. It can only be \" \"read by NumPy", "to the `numpy.dtype` constructor to create the array's dtype. \"fortran_order\"", "warnings.warn(\"metadata on a dtype may be saved or ignored, but", "Totally non-contiguous data. We will have to make it C-contiguous", "Parameters ---------- fp : file_like object If this is not", "\"shape is not valid: {!r}\" raise ValueError(msg.format(d['shape'])) if not isinstance(d['fortran_order'],", "UnicodeError as err: # Friendlier error message raise UnicodeError(\"Unpickling a", "format. None means use the oldest supported version that is", "\"to numpy.load\" % (err,)) from err else: if isfileobj(fp): #", "NumPy version numbering. If the format is upgraded, the code", "for field in descr: if len(field) == 2: name, descr_str", "file. _check_version(version) # Ensure that the given dtype is an", "token_string == \"L\"): continue else: tokens.append(token) last_token_was_number = (token_type ==", "NPY file. Parameters ---------- fp : file_like object If this", "3.0 ------------------ This version replaces the ASCII string (which in", "{!r}\" raise ValueError(msg.format(header)) from e if not isinstance(d, dict): msg", "format for persisting *multiple* NumPy arrays on disk. A ``.npz``", "It can only be \" \"read by NumPy >= 1.17\",", "be created upon reading the file. .. warning:: Due to", "------ ValueError If the data is invalid, or allow_pickle=False and", "Arbitrary subclasses of numpy.ndarray are not completely preserved. Subclasses will", "memory-mapped array. Raises ------ ValueError If the data or the", "dict This has the appropriate entries for writing its string", "are not picklable. \"\"\" _check_version(version) _write_array_header(fp, header_data_from_array_1_0(array), version) if array.itemsize", "number of the file format, e.g. ``\\\\x00``. Note: the version", "{} try: array = pickle.load(fp, **pickle_kwargs) except UnicodeError as err:", "arbitrary Python objects. Files with object arrays are not to", "zero-width string dtypes; see # https://github.com/numpy/numpy/pull/6430 array = numpy.ndarray(count, dtype=dtype)", "_read_array_header(fp, version): \"\"\" see read_array_header_1_0 \"\"\" # Read an unsigned,", "until size bytes are read. Raises ValueError if not EOF", "2.6 can return less data than requested. \"\"\" data =", "isinstance(d['shape'], tuple) or not all(isinstance(x, int) for x in d['shape'])):", "name # Once support for blank names is removed, only", "(2,0), and (3,0), not %s\" raise ValueError(msg % (version,)) def", "the file. The types are described in terms of their", "\"read by NumPy >= 1.9\", UserWarning, stacklevel=2) return ret header", "------ ValueError If the data or the mode is invalid.", "mode = 'r+' marray = numpy.memmap(filename, dtype=dtype, shape=shape, order=order, mode=mode,", "arguments to pass to pickle.load. These are only useful when", "def dtype_to_descr(dtype): \"\"\" Get a serializable descriptor from the dtype.", "numpy.void and dt.names is None) if not is_pad: title, name", "valid: {!r}\" raise ValueError(msg.format(d['shape'])) if not isinstance(d['fortran_order'], bool): msg =", "next HEADER_LEN bytes form the header data describing the array's", ": (int, int) or None, optional The version number of", "all of the shape and dtype information necessary to reconstruct", "header\") header = header.decode(encoding) # The header is a pretty-printed", "return ret header = _wrap_header(header, (3, 0)) warnings.warn(\"Stored array in", "is not a valid dtype descriptor: {!r}\" raise ValueError(msg.format(d['descr'])) from", "request to give a default name. Instead, we construct descriptor", "to allow npz headers produced in Python2 to be read", "the data. Default: None Returns ------- marray : memmap The", "file modes, 'c' is also accepted to mean \"copy on", "``.npz`` extensions for files saved in this format. This is", "machine of a different architecture. Both little-endian and big-endian arrays", "= numpy.dtype(dtype) if dtype.hasobject: msg = \"Array can't be memory-mapped:", "ARRAY_ALIGN) try: header_prefix = magic(*version) + struct.pack(fmt, hlen + padlen)", "\"fortran_order\" : bool # \"descr\" : dtype.descr # Versions (2,", "arguments to pass to pickle.dump, excluding 'protocol'. These are only", "struct hinfo = _header_size_info.get(version) if hinfo is None: raise ValueError(\"Invalid", "or create a new one. Parameters ---------- filename : str", "an array and returns the version used Parameters ---------- fp", "shape=shape, ) # If we got here, then it should", "writing its string representation to the header of the file.", "wish to use these file formats but use an extension", "by 64 for alignment purposes. The dictionary contains three keys:", "2.0 format if the data requires it, else it will", "MAGIC_PREFIX = b'\\x93NUMPY' MAGIC_LEN = len(MAGIC_PREFIX) + 2 ARRAY_ALIGN =", "an appropriate version given the contents \"\"\" try: return _wrap_header(header,", "bool # \"descr\" : dtype.descr # Versions (2, 0) and", "3. Returns ------- array : ndarray The array from the", "The next 2 bytes form a little-endian unsigned short int:", "header_length, \"array header\") header = header.decode(encoding) # The header is", "on ``fortran_order``) bytes of the array. Consumers can figure out", "an actual file. - Stores object arrays, i.e. arrays containing", "# Read an unsigned, little-endian short int which has the", "reduce memory overhead # of the read. In non-chunked case", "d = dict( descr=dtype_to_descr(dtype), fortran_order=fortran_order, shape=shape, ) # If we", "disk. The format stores all of the shape and dtype", "object The object retreived by dtype.descr. Can be passed to", "0) could have been created by a Python 2 #", "which contains a Python literal expression of a dictionary. It", "is able to store the data. Default: None allow_pickle :", "may need to pass the encoding= option \" \"to numpy.load\"", "else: warnings.warn(\"Stored array in format 2.0. It can only be\"", "array. Raises ------ ValueError If the data or the mode", "stores all of the shape and dtype information necessary to", "language to read most ``.npy`` files that they have been", "object array. Various other errors If the array contains Python", "programs that created them. A competent developer should be able", "dtype() constructor interprets this as a request to give a", "dtype may be saved or ignored, but will \" \"raise", "return header def _write_array_header(fp, d, version=None): \"\"\" Write the header", "# Need to use repr here, since we eval these", "in object arrays on Python 3 to Python 2 compatible", "ValueError(msg) from None # Pad the header with spaces and", "on reads greater than 2 ** 32 bytes, # breaking", "open(os_fspath(filename), 'rb') as fp: version = read_magic(fp) _check_version(version) shape, fortran_order,", "without much documentation. - Allows memory-mapping of the data. See", "is not None: return any(_has_metadata(dt[k]) for k in dt.names) elif", "Parameters ---------- fp : filelike object A file object or", "dt = descr_to_dtype(descr_str) else: name, descr_str, shape = field dt", "the actual data. if dtype.hasobject: # The array contained Python", "= BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize) for i in range(0, count,", "count - i) read_size = int(read_count * dtype.itemsize) data =", "\"\"\" Write the header for an array using the 1.0", "its dtype, the process of pickling them may raise various", "= [] EXPECTED_KEYS = {'descr', 'fortran_order', 'shape'} MAGIC_PREFIX = b'\\x93NUMPY'", "description. \"\"\" if isinstance(descr, str): # No padding removal needed", "that can be interpreted as a dtype object. dtype =", "minor version number of the file format, e.g. ``\\\\x00``. Note:", "array is neither C-contiguous nor Fortran-contiguous AND the file_like object", "Otherwise the data is the contiguous (either C- or Fortran-,", "in [0, 255] Returns ------- magic : str Raises ------", "off the given description. This is essentially the reverse of", "return less data than requested. \"\"\" data = bytes() while", "numbering. If the format is upgraded, the code in `numpy.io`", "version cannot be formatted. \"\"\" if major < 0 or", "chooses an appropriate version given the contents \"\"\" try: return", "the file. with open(os_fspath(filename), mode+'b') as fp: _write_array_header(fp, d, version)", "header. Parameters ---------- fp : filelike object A file object", "= _header_size_info[version] if not isinstance(header, bytes): # always true on", "the version of the file format used to create the", "like padding bytes, still get # fiddled with. This needs", "the array that will be written to disk. Returns -------", "fortran_order, dtype = _read_array_header(fp, version) if dtype.hasobject: msg = \"Array", "0), (3, 0), None]: msg = \"we only support format", "Raises ValueError if not EOF is encountered before size bytes", "cannot be round-tripped through the dtype() constructor. Simple types, like", "except ValueError: pass try: ret = _wrap_header(header, (2, 0)) except", "that they have been given without much documentation. - Allows", "Python 3. Returns ------- array : ndarray The array from", "storage of large structured arrays _header_size_info = { (1, 0):", "file format, e.g. ``\\\\x01``. The next 1 byte is an", "fp.read(size - len(data)) data += r if len(r) == 0", "saved in this format. This is by no means a", "The keys are strings. # \"shape\" : tuple of int", "if len(data) != size: msg = \"EOF: reading %s, expected", "A ``.npz`` file is a zip file containing multiple ``.npy``", "dtype, the process of pickling them may raise various errors", "in their preferred programming language to read most ``.npy`` files", "0: buffersize = 0 else: # Set buffer size to", "Raises ------ ValueError If the data or the mode is", "reverse engineer. Datasets often live longer than the programs that", "a default name. Instead, we construct descriptor that can be", "reads from gzip streams. Chunk reads to # BUFFER_SIZE bytes", "as a memory-mapped array. This may be used to read", "shape=shape, order=order, mode=mode, offset=offset) return marray def _read_bytes(fp, size, error_template=\"ran", "than 2 ** 32 bytes, # breaking large reads from", "File extensions --------------- We recommend using the ``.npy`` and ``.npz``", "these when reading header.append(\"'%s': %s, \" % (key, repr(value))) header.append(\"}\")", "field in descr: if len(field) == 2: name, descr_str =", "if we are creating a new file in \"write\" mode.", "safe_eval(header) except SyntaxError as e: msg = \"Cannot parse header:", "the file first. with open(os_fspath(filename), 'rb') as fp: version =", "AND the file_like object is not a real file object,", "# done about that. note that regular files can't be", "of a dtype object cannot be round-tripped through the dtype()", "be round-tripped through the dtype() constructor. Simple types, like dtype('float32'),", "`numpy.dtype()` in order to replicate the input dtype. Returns -------", "actual data. if dtype.hasobject: # The array contained Python objects.", "may be used to read an existing file or create", "NumPy array on disk. The format stores all of the", "existing file or create a new one. Parameters ---------- filename", "change in the file format. The arrays with such structures", "than the programs that created them. A competent developer should", "is not None: # This is a record array. The", "directly if it is either C-contiguous or Fortran-contiguous. Otherwise, it", "(either C- or Fortran-, depending on ``fortran_order``) bytes of the", "method like a file. Returns ------- shape : tuple of", "should be safe to create the file. with open(os_fspath(filename), mode+'b')", "Capabilities ------------ - Can represent all NumPy arrays including nested", "using the ``.npy`` and ``.npz`` extensions for files saved in", "(3,0), not %s\" raise ValueError(msg % (version,)) def magic(major, minor):", ".. versionadded:: 1.9.0 Parameters ---------- fp : filelike object A", "to pickle.dump, excluding 'protocol'. These are only useful when pickling", "numpy.dtype((dt, descr[1])) titles = [] names = [] formats =", "representation to the header of the file. version: tuple or", "order=order, mode=mode, offset=offset) return marray def _read_bytes(fp, size, error_template=\"ran out", "marray def _read_bytes(fp, size, error_template=\"ran out of data\"): \"\"\" Read", "\"\"\" return _read_array_header(fp, version=(2, 0)) def _filter_header(s): \"\"\"Clean up 'L'", "the case of allow_pickle=False and array being an object array.", "The ``.npy`` format is the standard binary file format in", "UserWarning, stacklevel=2) if dtype.names is not None: # This is", "convert the description to its corresponding dtype. Parameters ---------- descr", "dtype.\" raise ValueError(msg) d = dict( descr=dtype_to_descr(dtype), fortran_order=fortran_order, shape=shape, )", "d['fortran_order'] = False d['descr'] = dtype_to_descr(array.dtype) return d def _wrap_header(header,", ": int minor : int \"\"\" magic_str = _read_bytes(fp, MAGIC_LEN,", "allow_pickle: raise ValueError(\"Object arrays cannot be saved when \" \"allow_pickle=False\")", "The array data will be written out directly if it", "invalid. IOError If the file is not found or cannot", "aligned up to ARRAY_ALIGN on systems like Linux where mmap()", "io import StringIO tokens = [] last_token_was_number = False for", "string, so supports structured types with any unicode field names.", "elif isinstance(descr, tuple): # subtype, will always have a shape", "tokenize.NUMBER) return tokenize.untokenize(tokens) def _read_array_header(fp, version): \"\"\" see read_array_header_1_0 \"\"\"", "If the array is neither C-contiguous nor Fortran-contiguous AND the", "we cannot write out the data # directly. Instead, we", "to hide the Python loop overhead. buffersize = max(16 *", "was latin1) with a utf8-encoded string, so supports structured types", "raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2])) major, minor = magic_str[-2:] return", "to the header of the file. \"\"\" d = {'shape':", "and 4096 BUFFER_SIZE = 2**18 # size of buffer for", "too big for version={}\".format(hlen, version) raise ValueError(msg) from None #", "from the dtype. The .descr attribute of a dtype object", "Fortran-, depending on ``fortran_order``) bytes of the array. Consumers can", "test for C_CONTIGUOUS first # because a 1-D array is", "array if we are creating a new file in \"write\"", "% (key, repr(value))) header.append(\"}\") header = \"\".join(header) if version is", "0): ('<H', 'latin1'), (2, 0): ('<I', 'latin1'), (3, 0): ('<I',", "file in \"write\" mode, in which case this parameter is", "chunk in numpy.nditer( array, flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize, order='F'): fp.write(chunk.tobytes('C'))", "Default: False .. versionchanged:: 1.16.3 Made default False in response", "version is None: header = _wrap_header_guess_version(header) else: header = _wrap_header(header,", "\"\"\" d = {'shape': array.shape} if array.flags.c_contiguous: d['fortran_order'] = False", "0), None]: msg = \"we only support format version (1,0),", "ValueError(\"Invalid version {!r}\".format(version)) hlength_type, encoding = hinfo hlength_str = _read_bytes(fp,", "created upon reading the file. .. warning:: Due to limitations", "optional Whether to allow writing pickled data. Default: True pickle_kwargs", "written data to the file. if mode == 'w+': mode", "implementation of # dtype(). return dtype.descr else: return dtype.str def", "Versions (2, 0) and (1, 0) could have been created", "Python objects in dtype.\" raise ValueError(msg) offset = fp.tell() if", "'r+' marray = numpy.memmap(filename, dtype=dtype, shape=shape, order=order, mode=mode, offset=offset) return", "= _wrap_header(header, version) fp.write(header) def write_array_header_1_0(fp, d): \"\"\" Write the", "Parameters ---------- major : int in [0, 255] minor :", "of elements given by the shape (noting that ``shape=()`` means", ":doc:`\"npy-format\" NEP <neps:nep-0001-npy-format>`, however details have evolved with time and", "``.write()`` method. array : ndarray The array to write to", "use these file formats but use an extension specific to", "ndarray The array from the data on disk. Raises ------", "formats is independent of NumPy version numbering. If the format", "struct assert version is not None fmt, encoding = _header_size_info[version]", "a python object failed: %r\\n\" \"You may need to pass", "file is not found or cannot be opened correctly. See", "able to create a solution in their preferred programming language", "keys are sorted in alphabetic order. This is for convenience", "open the file; the default is 'r+'. In addition to", "# than just something that can be interpreted as a", "array = numpy.fromfile(fp, dtype=dtype, count=count) else: # This is not", "element of the header therefore has become: \"The next 4", "== ''\" needed) is_pad = (name == '' and dt.type", "Return the magic string for the given file format version.", "msg = \"Header length {} too big for version={}\".format(hlen, version)", "working on a fix for this. This fix will not", "record arrays and object arrays. - Represents the data in", "not tied to the version of the numpy package. The", "not EOF is encountered before size bytes are read. Non-blocking", "raise ValueError(msg % (version,)) def magic(major, minor): \"\"\" Return the", "independent of NumPy version numbering. If the format is upgraded,", "breaking large reads from gzip streams. Chunk reads to #", "only one read is performed. # Use np.ndarray instead of", "has the appropriate entries for writing its string representation to", "or None, optional The version number of the format. None", "to the header of the file. \"\"\" _write_array_header(fp, d, (2,", "0): ('<I', 'utf8'), } def _check_version(version): if version not in", "or major > 255: raise ValueError(\"major version must be 0", "is numpy.void and dt.names is None) if not is_pad: title,", "will not round-trip through the format entirely accurately. The data", "to be written directly to disk for efficiency. \"shape\" :", "binary file format in NumPy for persisting a *single* arbitrary", "# aligned up to ARRAY_ALIGN on systems like Linux where", "formats.append(dt) offsets.append(offset) offset += dt.itemsize return numpy.dtype({'names': names, 'formats': formats,", "is fine. XXX: parts of the # record array with", "that. note that regular files can't be non-blocking try: r", "then the data is a Python pickle of the array.", "and ``.npz``. Version numbering ----------------- The version numbering of these", "# only one read is performed. # Use np.ndarray instead", "new file in \"write\" mode, if not, `dtype` is ignored.", "dtype.hasobject: msg = \"Array can't be memory-mapped: Python objects in", "that we need to test for C_CONTIGUOUS first # because", "header def _write_array_header(fp, d, version=None): \"\"\" Write the header for", "so supports structured types with any unicode field names. Notes", "that regular files can't be non-blocking try: r = fp.read(size", "application. In the absence of an obvious alternative, however, we", "err: # Friendlier error message raise UnicodeError(\"Unpickling a python object", "length of the header data HEADER_LEN.\" Format Version 3.0 ------------------", "[] offsets = [] offset = 0 for field in", "to avoid issue and reduce memory overhead # of the", "last_token_was_number = (token_type == tokenize.NUMBER) return tokenize.untokenize(tokens) def _read_array_header(fp, version):", "shape, fortran_order, dtype = _read_array_header(fp, version) if len(shape) == 0:", "3 header = header.encode(encoding) hlen = len(header) + 1 padlen", "The array to write to disk. version : (int, int)", "ValueError(\"Object arrays cannot be loaded when \" \"allow_pickle=False\") if pickle_kwargs", "case count < max_read_count, so # only one read is", "can't be memory-mapped: Python objects in dtype.\" raise ValueError(msg) offset", "before header filtering was implemented. if version <= (2, 0):", ": str or path-like The name of the file on", "it \"\"\" import struct assert version is not None fmt,", "- Supports Fortran-contiguous arrays directly. - Stores all of the", "final newline such that the magic # string, the header-length", "'f1', etc. Such arrays will not round-trip through the format", "number of the file format, e.g. ``\\\\x01``. The next 1", "---------- descr : object The object retreived by dtype.descr. Can", "d = {'shape': array.shape} if array.flags.c_contiguous: d['fortran_order'] = False elif", "rather # than just something that can be interpreted as", "x in d['shape'])): msg = \"shape is not valid: {!r}\"", "may *not* be a file-like object. mode : str, optional", "<= (2, 0): header = _filter_header(header) try: d = safe_eval(header)", "by using the ``loadedarray.view(correct_dtype)`` method. File extensions --------------- We recommend", "io import warnings from numpy.lib.utils import safe_eval from numpy.compat import", "out an array with \"long ints\", a reading machine with", "def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None): \"\"\" Write an array", "the array is neither C-contiguous nor Fortran-contiguous AND the file_like", "in its native binary form. - Supports Fortran-contiguous arrays directly.", "be passed as an argument to the `numpy.dtype` constructor to", "None: pickle_kwargs = {} pickle.dump(array, fp, protocol=3, **pickle_kwargs) elif array.flags.f_contiguous", "< max_read_count, so # only one read is performed. #", "on a machine of a different architecture. Both little-endian and", "to make it C-contiguous # before writing. Note that we", "array and returns the version used Parameters ---------- fp :", "token_type == tokenize.NAME and token_string == \"L\"): continue else: tokens.append(token)", "Since Fortran-contiguous arrays are a common form of non-C-contiguity, we", "if version <= (2, 0): header = _filter_header(header) try: d", "Fortran-contiguous arrays directly. - Stores all of the necessary information", "preserved. Subclasses will be accepted for writing, but only the", "this parameter is ignored and is thus optional. fortran_order :", "Needed to allow npz headers produced in Python2 to be", "construct descriptor that can be passed to dtype(). Parameters ----------", "object retreived by dtype.descr. Can be passed to `numpy.dtype()` in", "for key, value in sorted(d.items()): # Need to use repr", "+ len(length) + HEADER_LEN`` be evenly divisible by 64 for", "} def _check_version(version): if version not in [(1, 0), (2,", "be passed to dtype(). Parameters ---------- dtype : dtype The", "An object that can be passed to `numpy.dtype()` in order", "= _wrap_header(header, (3, 0)) warnings.warn(\"Stored array in format 3.0. It", "on another machine with a different architecture. The format is", "for an array using the 2.0 format. The 2.0 format", "= shape[::-1] array = array.transpose() else: array.shape = shape return", "= fp.read(size - len(data)) data += r if len(r) ==", "reader MUST NOT depend on this. Following the header comes", "\"\"\" Returns a dtype based off the given description. This", "an array header from a filelike object using the 2.0", "if version not in [(1, 0), (2, 0), (3, 0),", "If the array cannot be persisted. This includes the case", "extension specific to the application. In the absence of an", "= False for token in tokenize.generate_tokens(StringIO(s).readline): token_type = token[0] token_string", "shape of the array. For repeatability and readability, the dictionary", "code in `numpy.io` will still be able to read and", "a dtype based off the given description. This is essentially", "that the magic # string, the header-length short and the", "data HEADER_LEN. The next HEADER_LEN bytes form the header data", "common form of non-C-contiguity, we allow them to be written", "16 MiB to hide the Python loop overhead. buffersize =", "disk for efficiency. \"shape\" : tuple of int The shape", "= \"Header is not a dictionary: {!r}\" raise ValueError(msg.format(d)) if", "keys = sorted(d.keys()) msg = \"Header does not contain the", "version=None): \"\"\" Open a .npy file as a memory-mapped array.", "which will be void bytes with '' as name #", "elif dt.subdtype is not None: return _has_metadata(dt.base) else: return False", "dtype : dtype The dtype constructed by the description. \"\"\"", "pickle_kwargs is None: pickle_kwargs = {} try: array = pickle.load(fp,", "dtype=dtype, count=read_count) if fortran_order: array.shape = shape[::-1] array = array.transpose()", "by 'f0', 'f1', etc. Such arrays will not round-trip through", "the correct keys: {!r}\" raise ValueError(msg.format(keys)) # Sanity-check the values.", "MiB to hide the Python loop overhead. buffersize = max(16", "data. Default: None \"\"\" header = [\"{\"] for key, value", "to pickle.load. These are only useful when loading object arrays", "and dtype on a machine of a different architecture. Both", "handles.\") if 'w' in mode: # We are creating the", "Raises ------ ValueError If the data is invalid. \"\"\" return", "# size of buffer for reading npz files in bytes", "ValueError(msg % (version,)) def magic(major, minor): \"\"\" Return the magic", "# Python dictionary with trailing newlines padded to a ARRAY_ALIGN", "This can be exceeded by structured arrays with a large", "None means use the oldest supported version that is able", "NumPy arrays including nested record arrays and object arrays. -", "bool The array data will be written out directly if", "the numpy package. The next 2 bytes form a little-endian", "in alphabetic order. This is for convenience only. A writer", "These are only useful when loading object arrays saved on", "= pickle.load(fp, **pickle_kwargs) except UnicodeError as err: # Friendlier error", "= _read_bytes(fp, header_length, \"array header\") header = header.decode(encoding) # The", "be exceeded by structured arrays with a large number of", "formats but use an extension specific to the application. In", "\"\"\" Open a .npy file as a memory-mapped array. This", "array def open_memmap(filename, mode='r+', dtype=None, shape=None, fortran_order=False, version=None): \"\"\" Open", "disk. Limitations ----------- - Arbitrary subclasses of numpy.ndarray are not", "interpreted as a dtype object. dtype = numpy.dtype(dtype) if dtype.hasobject:", "the array's dtype. \"fortran_order\" : bool Whether the array data", "None \"\"\" header = [\"{\"] for key, value in sorted(d.items()):", "'buffered', 'zerosize_ok'], buffersize=buffersize, order='C'): fp.write(chunk.tobytes('C')) def read_array(fp, allow_pickle=False, pickle_kwargs=None): \"\"\"", "to be read in Python3. Parameters ---------- s : string", "2.0 format allows storing very large structured arrays. .. versionadded::", "a ARRAY_ALIGN byte # boundary. The keys are strings. #", "data. If the dtype contains Python objects (i.e. ``dtype.hasobject is", "the input dtype. Returns ------- dtype : dtype The dtype", "Parameters ---------- dtype : dtype The dtype of the array", "size bytes are read. Non-blocking objects only supported if they", "size bytes are read. Raises ValueError if not EOF is", "descr_to_dtype(descr): \"\"\" Returns a dtype based off the given description.", "This version replaces the ASCII string (which in practice was", "def read_magic(fp): \"\"\" Read the magic string to get the", "the latter does # not correctly instantiate zero-width string dtypes;", "_wrap_header(header, (1, 0)) except ValueError: pass try: ret = _wrap_header(header,", "hlen = len(header) + 1 padlen = ARRAY_ALIGN - ((MAGIC_LEN", "Parameters ---------- array : numpy.ndarray Returns ------- d : dict", "len(shape) == 0: count = 1 else: count = numpy.multiply.reduce(shape,", "eval these when reading header.append(\"'%s': %s, \" % (key, repr(value)))", "in NumPy for persisting a *single* arbitrary NumPy array on", "dtype.hasobject: # The array contained Python objects. We need to", "_wrap_header_guess_version(header): \"\"\" Like `_wrap_header`, but chooses an appropriate version given", "fix will not require a change in the file format.", "not a valid dtype descriptor: {!r}\" raise ValueError(msg.format(d['descr'])) from e", "e return d['shape'], d['fortran_order'], dtype def write_array(fp, array, version=None, allow_pickle=True,", "``.npz`` format is the standard format for persisting *multiple* NumPy", "file_like object An open, writable file object, or similar object", "file is a zip file containing multiple ``.npy`` files, one", "2: name, descr_str = field dt = descr_to_dtype(descr_str) else: name,", "Fortran-contiguous or not. Since Fortran-contiguous arrays are a common form", "optional. fortran_order : bool, optional Whether the array should be", "try: header_prefix = magic(*version) + struct.pack(fmt, hlen + padlen) except", "the number of elements given by the shape (noting that", "fp.tell() if fortran_order: order = 'F' else: order = 'C'", "multiplying the number of elements given by the shape (noting", "This needs to be fixed in the C implementation of", "a shape descr[1] dt = descr_to_dtype(descr[0]) return numpy.dtype((dt, descr[1])) titles", "is invalid. \"\"\" return _read_array_header(fp, version=(2, 0)) def _filter_header(s): \"\"\"Clean", "by NumPy >= 1.17\", UserWarning, stacklevel=2) return header def _write_array_header(fp,", "by, i.e. simple fields like dtype('float32'), and then convert the", "be safe to create the file. with open(os_fspath(filename), mode+'b') as", "total size of 65535 bytes. This can be exceeded by", "create the file. _check_version(version) # Ensure that the given dtype", "version) offset = fp.tell() else: # Read the header of", "length # instead of 2 bytes (H) allowing storage of", "1 else: count = numpy.multiply.reduce(shape, dtype=numpy.int64) # Now read the", "replaces the ASCII string (which in practice was latin1) with", "form. - Supports Fortran-contiguous arrays directly. - Stores all of", "bytes by multiplying the number of elements given by the", "order to replicate the input dtype. \"\"\" if _has_metadata(dtype): warnings.warn(\"metadata", "of `dtype_to_descr()`. It will remove the valueless padding fields created", "a little-endian array on any machine reading the file. The", "if array.dtype.hasobject: # We contain Python objects so we cannot", "memory. Parameters ---------- fp : file_like object An open, writable", "isinstance(descr, str): # No padding removal needed return numpy.dtype(descr) elif", "requested. \"\"\" data = bytes() while True: # io files", "``\\\\x01``. The next 1 byte is an unsigned byte: the", "simple format for saving numpy arrays to disk with the", "that can be passed as an argument to the `numpy.dtype`", "description to its corresponding dtype. Parameters ---------- descr : object", "NumPy arrays on disk. A ``.npz`` file is a zip", "Returns ------- descr : object An object that can be", "hlength_str = _read_bytes(fp, struct.calcsize(hlength_type), \"array header length\") header_length = struct.unpack(hlength_type,", "to the header of the file. version: tuple or None", "description. This is essentially the reverse of `dtype_to_descr()`. It will", "see read_array_header_1_0 \"\"\" # Read an unsigned, little-endian short int", "= \"Header length {} too big for version={}\".format(hlen, version) raise", "(token_type == tokenize.NUMBER) return tokenize.untokenize(tokens) def _read_array_header(fp, version): \"\"\" see", "neither C-contiguous nor Fortran-contiguous AND the file_like object is not", "= \"fortran_order is not a valid bool: {!r}\" raise ValueError(msg.format(d['fortran_order']))", "# We are creating the file, not reading it. #", "from the data on disk. Raises ------ ValueError If the", "Returns ------- magic : str Raises ------ ValueError if the", "\"array data\") array[i:i+read_count] = numpy.frombuffer(data, dtype=dtype, count=read_count) if fortran_order: array.shape", "dtype = numpy.dtype(dtype) if dtype.hasobject: msg = \"Array can't be", "a Python pickle of the array. Otherwise the data is", "is intact; only the field names will differ. We are", "- i) read_size = int(read_count * dtype.itemsize) data = _read_bytes(fp,", "only the array data will be written out. A regular", "format. The 2.0 format allows storing very large structured arrays.", "data = _read_bytes(fp, read_size, \"array data\") array[i:i+read_count] = numpy.frombuffer(data, dtype=dtype,", "object cannot be round-tripped through the dtype() constructor. Simple types,", "it out. dtype : dtype The dtype of the file's", "can be read and written to disk. Limitations ----------- -", ": bool Whether the array data is Fortran-contiguous or not.", "\" % (key, repr(value))) header.append(\"}\") header = \"\".join(header) if version", "array, flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize, order='C'): fp.write(chunk.tobytes('C')) def read_array(fp, allow_pickle=False,", "this document is more current. \"\"\" import numpy import io", "is True``), then the data is a Python pickle of", "# of the read. In non-chunked case count < max_read_count,", "is thus optional. fortran_order : bool, optional Whether the array", "the code in `numpy.io` will still be able to read", "# Once support for blank names is removed, only \"if", "like a file. Returns ------- shape : tuple of int", "to dtype(). Parameters ---------- dtype : dtype The dtype of", "1.0 format only allowed the array header to have a", "raise ValueError(msg.format(d['descr'])) from e return d['shape'], d['fortran_order'], dtype def write_array(fp,", "if pickle_kwargs is None: pickle_kwargs = {} pickle.dump(array, fp, protocol=3,", "saving this data. Default: None \"\"\" header = [\"{\"] for", "None, which results in a data-type of `float64`. shape :", "numpy.ndarray object will be created upon reading the file. ..", "read and written to disk. Limitations ----------- - Arbitrary subclasses", "version of the numpy package. The next 2 bytes form", "arbitrary NumPy array on disk. The format stores all of", "a total size of 65535 bytes. This can be exceeded", "count, max_read_count): read_count = min(max_read_count, count - i) read_size =", "achieving its limited goals. The ``.npz`` format is the standard", "to be mmapable, but can be read and written to", "as an argument to the `numpy.dtype` constructor to create the", "header_data_from_array_1_0(array): \"\"\" Get the dictionary of header metadata from a", "(I) header length # instead of 2 bytes (H) allowing", "name) titles.append(title) names.append(name) formats.append(dt) offsets.append(offset) offset += dt.itemsize return numpy.dtype({'names':", "32 bytes, # breaking large reads from gzip streams. Chunk", "header + b' '*padlen + b'\\n' def _wrap_header_guess_version(header): \"\"\" Like", "being an object array. Various other errors If the array", "from err else: if isfileobj(fp): # We can use the", "isfileobj(filename): raise ValueError(\"Filename must be a string or a path-like", "tuple) or not all(isinstance(x, int) for x in d['shape'])): msg", "using the ``loadedarray.view(correct_dtype)`` method. File extensions --------------- We recommend using", "# https://github.com/numpy/numpy/pull/6430 array = numpy.ndarray(count, dtype=dtype) if dtype.itemsize > 0:", "C \"long ints\" will yield an array with 64-bit integers.", "memory overhead # of the read. In non-chunked case count", "if dtype.hasobject: msg = \"Array can't be memory-mapped: Python objects", "descr: if len(field) == 2: name, descr_str = field dt", "arrays and object arrays. - Represents the data in its", "its limited goals. The ``.npz`` format is the standard format", "# ARRAY_ALIGN byte boundary. This supports memory mapping of dtypes", "prefix and padding to it \"\"\" import struct assert version", "array using the 2.0 format. The 2.0 format allows storing", "This is a record array. The .descr is fine. XXX:", "used to read an existing file or create a new", "d['descr'] = dtype_to_descr(array.dtype) return d def _wrap_header(header, version): \"\"\" Takes", "Parameters ---------- filename : str or path-like The name of", "for persisting a *single* arbitrary NumPy array on disk. The", "array with an empty name, like padding bytes, still get", ") # If we got here, then it should be", "False elif array.flags.f_contiguous: d['fortran_order'] = True else: # Totally non-contiguous", "bytes, still get # fiddled with. This needs to be", "format version. This will leave the file object located just", "file. Parameters ---------- fp : file_like object If this is", "0 or len(data) == size: break except io.BlockingIOError: pass if", "the magic string for the given file format version. Parameters", "means a requirement; applications may wish to use these file", "Linux where mmap() # offset must be page-aligned (i.e. the", "Whether to allow writing pickled data. Default: False .. versionchanged::", "_has_metadata(dt.base) else: return False def dtype_to_descr(dtype): \"\"\" Get a serializable", "machine with a 64-bit C \"long int\" writes out an", "an array using the 1.0 format. Parameters ---------- fp :", "correct dtype may be restored by using the ``loadedarray.view(correct_dtype)`` method.", "= \"the magic string is not correct; expected %r, got", "Python objects in dtype.\" raise ValueError(msg) d = dict( descr=dtype_to_descr(dtype),", "to CVE-2019-6446. pickle_kwargs : dict Additional keyword arguments to pass", "header.append(\"}\") header = \"\".join(header) if version is None: header =", "<neps:nep-0001-npy-format>`, however details have evolved with time and this document", "array with 64-bit integers. - Is straightforward to reverse engineer.", "filelike object Returns ------- major : int minor : int", "in Python3. Parameters ---------- s : string Npy file header.", "a 64-bit C \"long int\" writes out an array with", "if len(shape) == 0: count = 1 else: count =", "16 and 4096 BUFFER_SIZE = 2**18 # size of buffer", "In non-chunked case count < max_read_count, so # only one", "(int, int) or None, optional The version number of the", "\"fortran_order is not a valid bool: {!r}\" raise ValueError(msg.format(d['fortran_order'])) try:", "read_array_header_1_0 \"\"\" # Read an unsigned, little-endian short int which", "contains three keys: \"descr\" : dtype.descr An object that can", "dtype(). return dtype.descr else: return dtype.str def descr_to_dtype(descr): \"\"\" Returns", "as fp: _write_array_header(fp, d, version) offset = fp.tell() else: #", "actual sizes. For example, if a machine with a 64-bit", "_check_version(version) shape, fortran_order, dtype = _read_array_header(fp, version) if len(shape) ==", "= numpy.multiply.reduce(shape, dtype=numpy.int64) # Now read the actual data. if", "file format used to create the file. None means use", "This fix will not require a change in the file", "array, flags=['external_loop', 'buffered', 'zerosize_ok'], buffersize=buffersize, order='F'): fp.write(chunk.tobytes('C')) else: if isfileobj(fp):", "name of the file on disk. This may *not* be", "the array header to have a total size of 65535", "contained Python objects. We need to unpickle the data. if", "Made default False in response to CVE-2019-6446. pickle_kwargs : dict", "must be page-aligned (i.e. the beginning of the file). return", "dtype based off the given description. This is essentially the", "if version is None: header = _wrap_header_guess_version(header) else: header =", "= 64 # plausible values are powers of 2 between", "file, including a header. If the array is neither C-contiguous", "# Check if we ought to create the file. _check_version(version)", "cannot use existing file handles.\") if 'w' in mode: #", "or something with a `.read()` method like a file. Returns", "object until size bytes are read. Raises ValueError if not", "+= r if len(r) == 0 or len(data) == size:", "a Python 2 # implementation before header filtering was implemented.", "while achieving its limited goals. The ``.npz`` format is the", "a fix for this. This fix will not require a", "or Fortran-contiguous. Otherwise, it will be made contiguous before writing", "i in range(0, count, max_read_count): read_count = min(max_read_count, count -", "by a newline (``\\\\n``) and padded with spaces (``\\\\x20``) to", "can be passed as an argument to the `numpy.dtype` constructor", "in strings representing integers. Needed to allow npz headers produced", "( isfileobj, os_fspath, pickle ) __all__ = [] EXPECTED_KEYS =", "as possible while achieving its limited goals. The ``.npz`` format", "is a pretty-printed string representation of a literal # Python", "# \"fortran_order\" : bool # \"descr\" : dtype.descr # Versions", "version) if dtype.hasobject: msg = \"Array can't be memory-mapped: Python", "machine reading the file. The types are described in terms", "in response to CVE-2019-6446. pickle_kwargs : dict Additional keyword arguments", "is None: pickle_kwargs = {} pickle.dump(array, fp, protocol=3, **pickle_kwargs) elif", "A regular numpy.ndarray object will be created upon reading the", "return major, minor def _has_metadata(dt): if dt.metadata is not None:", "If the data is invalid. \"\"\" return _read_array_header(fp, version=(2, 0))", "The mode in which to open the file; the default", "= hinfo hlength_str = _read_bytes(fp, struct.calcsize(hlength_type), \"array header length\") header_length", "number of the format. None means use the oldest supported", "msg = \"shape is not valid: {!r}\" raise ValueError(msg.format(d['shape'])) if", "= [] formats = [] offsets = [] offset =", "numpy arrays to disk with the full information about them.", "this. This fix will not require a change in the", "in which case this parameter is required. Otherwise, this parameter", "and (3,0), not %s\" raise ValueError(msg % (version,)) def magic(major,", "except TypeError as e: msg = \"descr is not a", "in format 2.0. It can only be\" \"read by NumPy", "or None If the mode is a \"write\" mode, then", "64-bit C \"long int\" writes out an array with \"long", "to disk. version : (int, int) or None, optional The", "dictionary contains three keys: \"descr\" : dtype.descr An object that", "[0, 255] Returns ------- magic : str Raises ------ ValueError", "arrays. .. versionadded:: 1.9.0 Parameters ---------- fp : filelike object", "the programs that created them. A competent developer should be", ": str Cleaned up header. \"\"\" import tokenize from io", "a final newline such that the magic # string, the", "large structured arrays _header_size_info = { (1, 0): ('<H', 'latin1'),", "d): \"\"\" Write the header for an array using the", "return MAGIC_PREFIX + bytes([major, minor]) def read_magic(fp): \"\"\" Read the", "are only useful when loading object arrays saved on Python", "fp.write(chunk.tobytes('C')) def read_array(fp, allow_pickle=False, pickle_kwargs=None): \"\"\" Read an array from", "terminated by a newline (``\\\\n``) and padded with spaces (``\\\\x20``)", "buffer size to 16 MiB to hide the Python loop", "returns the version used Parameters ---------- fp : filelike object", "def _read_bytes(fp, size, error_template=\"ran out of data\"): \"\"\" Read from", "ARRAY_ALIGN = 64 # plausible values are powers of 2", "size to 4 GiB. `numpy.save` will automatically save in 2.0", "of the file on disk. This may *not* be a", "an authentic dtype object rather # than just something that", "0)) def read_array_header_2_0(fp): \"\"\" Read an array header from a", "header. .. versionadded:: 1.9.0 Parameters ---------- fp : filelike object", "dict( descr=dtype_to_descr(dtype), fortran_order=fortran_order, shape=shape, ) # If we got here,", "`numpy.io` will still be able to read and write Version", "raise ValueError(msg) offset = fp.tell() if fortran_order: order = 'F'", "1.9\", UserWarning, stacklevel=2) return ret header = _wrap_header(header, (3, 0))", "specific to the application. In the absence of an obvious", "machine with a different architecture. The format is designed to", "oldest supported version that is able to store the data.", "allow_pickle: raise ValueError(\"Object arrays cannot be loaded when \" \"allow_pickle=False\")", "length of the # header. import struct hinfo = _header_size_info.get(version)", "the file_like object is not a real file object, this", "= \"Cannot parse header: {!r}\" raise ValueError(msg.format(header)) from e if", "such structures can still be saved and restored, and the", "is not valid: {!r}\" raise ValueError(msg.format(d['shape'])) if not isinstance(d['fortran_order'], bool):", "various errors if the objects are not picklable. \"\"\" _check_version(version)", "fields with empty names will have the names replaced by", "are strings. # \"shape\" : tuple of int # \"fortran_order\"", "+ 2 + len(length) + HEADER_LEN`` be evenly divisible by", "descr which looks like a record array with one field", "be able to create a solution in their preferred programming", "ValueError(msg.format(header)) from e if not isinstance(d, dict): msg = \"Header", "boundary. This supports memory mapping of dtypes # aligned up", "_header_size_info.get(version) if hinfo is None: raise ValueError(\"Invalid version {!r}\".format(version)) hlength_type,", "out if not allow_pickle: raise ValueError(\"Object arrays cannot be saved", "------------------ The first 6 bytes are a magic string: exactly", "get the version of the file format. Parameters ---------- fp", "This may *not* be a file-like object. mode : str,", "does not allow saving this data. Default: None \"\"\" header", "with a `.read()` method like a file. Returns ------- shape", "isinstance(name, tuple) else (None, name) titles.append(title) names.append(name) formats.append(dt) offsets.append(offset) offset", "saved on Python 2 when using Python 3. Returns -------", "the header for an array using the 2.0 format. The", "has the length of the # header. import struct hinfo", "if not EOF is encountered before size bytes are read.", "only be \" \"read by NumPy >= 1.17\", UserWarning, stacklevel=2)", "No padding removal needed return numpy.dtype(descr) elif isinstance(descr, tuple): #", "`numpy.dtype()` in order to replicate the input dtype. \"\"\" if", "the # header. import struct hinfo = _header_size_info.get(version) if hinfo", "each array. Capabilities ------------ - Can represent all NumPy arrays", "\"fortran_order\" : bool Whether the array data is Fortran-contiguous or", "exceeded by structured arrays with a large number of columns.", "should be Fortran-contiguous (True) or C-contiguous (False, the default) if", "\"\"\" data = bytes() while True: # io files (default", "Fortran-contiguous. Otherwise, it will be made contiguous before writing it", "arrays _header_size_info = { (1, 0): ('<H', 'latin1'), (2, 0):", "An open, writable file object, or similar object with a", "only supported if they derive from io objects. Required as", "using the 1.0 format. Parameters ---------- fp : filelike object", "1 element) by ``dtype.itemsize``. Format Version 2.0 ------------------ The version", "This will leave the file object located just after the", "to pass to pickle.dump, excluding 'protocol'. These are only useful", "of NumPy version numbering. If the format is upgraded, the", "array in format 2.0. It can only be\" \"read by", "d['shape'], d['fortran_order'], dtype def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None): \"\"\"", "header metadata from a numpy.ndarray. Parameters ---------- array : numpy.ndarray", "memory-mapped array. This may be used to read an existing", "version=(2, 0)) def _filter_header(s): \"\"\"Clean up 'L' in npz header", "byte: the minor version number of the file format, e.g.", "In the absence of an obvious alternative, however, we suggest", "{} pickle.dump(array, fp, protocol=3, **pickle_kwargs) elif array.flags.f_contiguous and not array.flags.c_contiguous:", "\"write\" mode, if not, `dtype` is ignored. The default value", "all NumPy arrays including nested record arrays and object arrays.", "read. Non-blocking objects only supported if they derive from io", "the file, not reading it. # Check if we ought", "[0, 255] minor : int in [0, 255] Returns -------", "object with a ``.write()`` method. array : ndarray The array", "a read-write mode since we've # already written data to", "_read_bytes(fp, size, error_template=\"ran out of data\"): \"\"\" Read from file-like", "[\"{\"] for key, value in sorted(d.items()): # Need to use", "on a # ARRAY_ALIGN byte boundary. This supports memory mapping", "'F' else: order = 'C' # We need to change", "a Python literal expression of a dictionary. It is terminated", "with the full information about them. The ``.npy`` format is", "the array. Consumers can figure out the number of bytes", "object Returns ------- major : int minor : int \"\"\"", "make the total of ``len(magic string) + 2 + len(length)", "\"\"\" if isfileobj(filename): raise ValueError(\"Filename must be a string or", "since we've # already written data to the file. if", "another machine with a different architecture. The format is designed", "------------ - Can represent all NumPy arrays including nested record", "descr_to_dtype(d['descr']) except TypeError as e: msg = \"descr is not", "module fails on reads greater than 2 ** 32 bytes,", "of 2 between 16 and 4096 BUFFER_SIZE = 2**18 #", "name, descr_str = field dt = descr_to_dtype(descr_str) else: name, descr_str,", "on Python 3 to Python 2 compatible format. Raises ------", "expression of a dictionary. It is terminated by a newline", "the header of the file. \"\"\" _write_array_header(fp, d, (2, 0))", "have been given without much documentation. - Allows memory-mapping of", "the # record array with an empty name, like padding", "---------- dtype : dtype The dtype of the array that", "the beginning of the file). return header_prefix + header +", "form of non-C-contiguity, we allow them to be written directly", "= {'shape': array.shape} if array.flags.c_contiguous: d['fortran_order'] = False elif array.flags.f_contiguous:", "array.flags.c_contiguous: if isfileobj(fp): array.T.tofile(fp) else: for chunk in numpy.nditer( array,", "version=None, allow_pickle=True, pickle_kwargs=None): \"\"\" Write an array to an NPY", "with such structures can still be saved and restored, and", "reading machine with 32-bit C \"long ints\" will yield an", "in \"write\" mode, if not, `dtype` is ignored. The default", "of # dtype(). return dtype.descr else: return dtype.str def descr_to_dtype(descr):", "up 'L' in npz header ints. Cleans up the 'L'", "format, including motivation for creating it and a comparison of", "of int The shape of the array. For repeatability and", "the file. \"\"\" _write_array_header(fp, d, (2, 0)) def read_array_header_1_0(fp): \"\"\"", "to unpickle the data. if not allow_pickle: raise ValueError(\"Object arrays", "# crc32 module fails on reads greater than 2 **", "count=count) else: # This is not a real file. We", "object. dtype = numpy.dtype(dtype) if dtype.hasobject: msg = \"Array can't", "not a real file object, this function will have to", "as fp: version = read_magic(fp) _check_version(version) shape, fortran_order, dtype =", "by a Python 2 # implementation before header filtering was", "directly. - Stores all of the necessary information to reconstruct", "an array with \"long ints\", a reading machine with 32-bit", "can only be\" \"read by NumPy >= 1.9\", UserWarning, stacklevel=2)", "def read_array_header_2_0(fp): \"\"\" Read an array header from a filelike", "1.0 file format version. This will leave the file object", "token[0] token_string = token[1] if (last_token_was_number and token_type == tokenize.NAME", "a magic string: exactly ``\\\\x93NUMPY``. The next 1 byte is", "errors If the array contains Python objects as part of", "from numpy.compat import ( isfileobj, os_fspath, pickle ) __all__ =", "engineer. Datasets often live longer than the programs that created", "\"descr\" : dtype.descr An object that can be passed as", "1 padlen = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize(fmt) + hlen)", "ValueError(msg.format(d['shape'])) if not isinstance(d['fortran_order'], bool): msg = \"fortran_order is not", ": object An object that can be passed to `numpy.dtype()`", "or raise on # would-block, python2 file will truncate, probably", "get # fiddled with. This needs to be fixed in", "data-type of `float64`. shape : tuple of int The shape", "< 0 or minor > 255: raise ValueError(\"minor version must", "corresponding dtype. Parameters ---------- descr : object The object retreived", "ignored and is thus optional. fortran_order : bool, optional Whether", "numpy package. The next 2 bytes form a little-endian unsigned", "a little-endian unsigned short int: the length of the header", "if mode == 'w+': mode = 'r+' marray = numpy.memmap(filename,", "\"if name == ''\" needed) is_pad = (name == ''", "if they derive from io objects. Required as e.g. ZipExtFile", "are described in terms of their actual sizes. For example,", "dtype. Parameters ---------- descr : object The object retreived by", "elements that are arbitrary Python objects. Files with object arrays", "We have to read it the # memory-intensive way. #", "of a literal # Python dictionary with trailing newlines padded", "read_magic(fp): \"\"\" Read the magic string to get the version", "major > 255: raise ValueError(\"major version must be 0 <=", "unsigned, little-endian short int which has the length of the", "length of the header data HEADER_LEN. The next HEADER_LEN bytes", "magic string to get the version of the file format.", "trailing newlines padded to a ARRAY_ALIGN byte # boundary. The", "r if len(r) == 0 or len(data) == size: break", "data. if dtype.hasobject: # The array contained Python objects. We", "storing very large structured arrays. .. versionadded:: 1.9.0 Parameters ----------", "is by no means a requirement; applications may wish to", "of the array. For repeatability and readability, the dictionary keys", "is_pad = (name == '' and dt.type is numpy.void and", "often live longer than the programs that created them. A", "version (1,0), (2,0), and (3,0), not %s\" raise ValueError(msg %", "we need to test for C_CONTIGUOUS first # because a", "pass else: warnings.warn(\"Stored array in format 2.0. It can only", "any machine reading the file. The types are described in", "For example, if a machine with a 64-bit C \"long", "a path-like object.\" \" Memmap cannot use existing file handles.\")", "= shape return array def open_memmap(filename, mode='r+', dtype=None, shape=None, fortran_order=False,", "\"long ints\" will yield an array with 64-bit integers. -", "The ``.npy`` format, including motivation for creating it and a", "tuple of int # \"fortran_order\" : bool # \"descr\" :", "instead of an actual file. - Stores object arrays, i.e.", "32-bit C \"long ints\" will yield an array with 64-bit", "a memory-mapped array. This may be used to read an", "method. array : ndarray The array to write to disk.", "of the file format. Parameters ---------- fp : filelike object", "(2, 0), (3, 0), None]: msg = \"we only support", "if len(r) == 0 or len(data) == size: break except", "data. See `open_memmap`. - Can be read from a filelike", "------------------ This version replaces the ASCII string (which in practice", "'rb') as fp: version = read_magic(fp) _check_version(version) shape, fortran_order, dtype", "be accepted for writing, but only the array data will", "real file object, this function will have to copy data", "produced in Python2 to be read in Python3. Parameters ----------", "msg = \"we only support format version (1,0), (2,0), and", "descr : object The object retreived by dtype.descr. Can be", "offsets, 'itemsize': offset}) def header_data_from_array_1_0(array): \"\"\" Get the dictionary of", "A reader MUST NOT depend on this. Following the header", "array. \"\"\" version = read_magic(fp) _check_version(version) shape, fortran_order, dtype =", "from a filelike stream object instead of an actual file.", "str, optional The mode in which to open the file;", "header with spaces and a final newline such that the", "saved or ignored, but will \" \"raise if saved when", "\" Memmap cannot use existing file handles.\") if 'w' in", "with \"long ints\", a reading machine with 32-bit C \"long", "return True elif dt.names is not None: return any(_has_metadata(dt[k]) for", "an array with 64-bit integers. - Is straightforward to reverse", "using the 2.0 file format version. This will leave the", "Chunk reads to # BUFFER_SIZE bytes to avoid issue and", "if not isinstance(d['fortran_order'], bool): msg = \"fortran_order is not a", "%s, \" % (key, repr(value))) header.append(\"}\") header = \"\".join(header) if", "string: exactly ``\\\\x93NUMPY``. The next 1 byte is an unsigned", "string or a path-like object.\" \" Memmap cannot use existing", "they derive from io objects. Required as e.g. ZipExtFile in", "('<I', 'utf8'), } def _check_version(version): if version not in [(1,", "We contain Python objects so we cannot write out the", "allow npz headers produced in Python2 to be read in", "Parameters ---------- fp : filelike object Returns ------- major :", "GiB. `numpy.save` will automatically save in 2.0 format if the", "as e: msg = \"Cannot parse header: {!r}\" raise ValueError(msg.format(header))", "\"shape\" : tuple of int The shape of the array.", "(noting that ``shape=()`` means there is 1 element) by ``dtype.itemsize``.", "formats, 'titles': titles, 'offsets': offsets, 'itemsize': offset}) def header_data_from_array_1_0(array): \"\"\"", "of the # header. import struct hinfo = _header_size_info.get(version) if", "real file object, then this may take extra memory and", "unsigned int: the length of the header data HEADER_LEN.\" Format", "arrays are supported, and a file with little-endian numbers will", "will be void bytes with '' as name # Once", "structured types with any unicode field names. Notes ----- The", "Returns ------- d : dict This has the appropriate entries", "names.append(name) formats.append(dt) offsets.append(offset) offset += dt.itemsize return numpy.dtype({'names': names, 'formats':", "dtype. Returns ------- dtype : dtype The dtype constructed by", "fp : filelike object A file object or something with", "from file-like object until size bytes are read. Raises ValueError", "HEADER_LEN.\" Format Version 3.0 ------------------ This version replaces the ASCII", "minor > 255: raise ValueError(\"minor version must be 0 <=", "dtype. The .descr attribute of a dtype object cannot be", "be\" \"read by NumPy >= 1.9\", UserWarning, stacklevel=2) return ret", "True else: # Totally non-contiguous data. We will have to", "so we cannot write out the data # directly. Instead,", "data is invalid, or allow_pickle=False and the file contains an", "msg = \"descr is not a valid dtype descriptor: {!r}\"", "empty names will have the names replaced by 'f0', 'f1',", "= max(16 * 1024 ** 2 // array.itemsize, 1) if", "we suggest using ``.npy`` and ``.npz``. Version numbering ----------------- The", "\"\"\" Read an array header from a filelike object using", "MAGIC_PREFIX: msg = \"the magic string is not correct; expected", "The version 2.0 format extends the header size to 4", "3.0. It can only be \" \"read by NumPy >=", "is essentially the reverse of `dtype_to_descr()`. It will remove the", "of 65535 bytes. This can be exceeded by structured arrays", "%d\" raise ValueError(msg % (error_template, size, len(data))) else: return data", "the standard format for persisting *multiple* NumPy arrays on disk.", "It is terminated by a newline (``\\\\n``) and padded with", "located just after the header. Parameters ---------- fp : filelike", "is an authentic dtype object rather # than just something", "import io import warnings from numpy.lib.utils import safe_eval from numpy.compat", "The dtype constructed by the description. \"\"\" if isinstance(descr, str):", "not all(isinstance(x, int) for x in d['shape'])): msg = \"shape", "written to disk. Limitations ----------- - Arbitrary subclasses of numpy.ndarray", "descr_str = field dt = descr_to_dtype(descr_str) else: name, descr_str, shape", "[] formats = [] offsets = [] offset = 0", "minor < 256\") return MAGIC_PREFIX + bytes([major, minor]) def read_magic(fp):", "header = _wrap_header(header, (3, 0)) warnings.warn(\"Stored array in format 3.0.", "then this may take extra memory and time. allow_pickle :", "fields like dtype('float32'), and then convert the description to its", "like dtype('float32'), and then convert the description to its corresponding", "of alternatives, is described in the :doc:`\"npy-format\" NEP <neps:nep-0001-npy-format>`, however", "non-contiguous data. We will have to make it C-contiguous #", "empty name, like padding bytes, still get # fiddled with.", "much documentation. - Allows memory-mapping of the data. See `open_memmap`.", "can be exceeded by structured arrays with a large number", "0 <= minor < 256\") return MAGIC_PREFIX + bytes([major, minor])", "= descr_to_dtype(descr_str) else: name, descr_str, shape = field dt =", "numpy.memmap \"\"\" if isfileobj(filename): raise ValueError(\"Filename must be a string", "be able to read and write Version 1.0 files. Format", "None Returns ------- marray : memmap The memory-mapped array. Raises", "The header is a pretty-printed string representation of a literal", "by NumPy >= 1.9\", UserWarning, stacklevel=2) return ret header =", "shape : tuple of int The shape of the array", "format. This is by no means a requirement; applications may", "file header. Returns ------- header : str Cleaned up header.", "disk with the full information about them. The ``.npy`` format", "constructed by the description. \"\"\" if isinstance(descr, str): # No", "before writing. Note that we need to test for C_CONTIGUOUS", "str Cleaned up header. \"\"\" import tokenize from io import", "by ``dtype.itemsize``. Format Version 2.0 ------------------ The version 1.0 format", "creating it and a comparison of alternatives, is described in", "msg = \"EOF: reading %s, expected %d bytes got %d\"", "mode='r+', dtype=None, shape=None, fortran_order=False, version=None): \"\"\" Open a .npy file", "fourth element of the header therefore has become: \"The next", "to the header of the file. \"\"\" _write_array_header(fp, d, (1,", "number of columns. The version 2.0 format extends the header", "unicode field names. Notes ----- The ``.npy`` format, including motivation", "if major < 0 or major > 255: raise ValueError(\"major", "array.shape} if array.flags.c_contiguous: d['fortran_order'] = False elif array.flags.f_contiguous: d['fortran_order'] =", "hide the Python loop overhead. buffersize = max(16 * 1024", "be restored by using the ``loadedarray.view(correct_dtype)`` method. File extensions ---------------", "256\") return MAGIC_PREFIX + bytes([major, minor]) def read_magic(fp): \"\"\" Read", "title, name = name if isinstance(name, tuple) else (None, name)", "These are only useful when pickling objects in object arrays", "input dtype. Returns ------- dtype : dtype The dtype constructed", "arrays on disk. A ``.npz`` file is a zip file", "else: name, descr_str, shape = field dt = numpy.dtype((descr_to_dtype(descr_str), shape))", "if hinfo is None: raise ValueError(\"Invalid version {!r}\".format(version)) hlength_type, encoding", "the description. \"\"\" if isinstance(descr, str): # No padding removal", "to mean \"copy on write.\" See `memmap` for the available", "object.\" \" Memmap cannot use existing file handles.\") if 'w'", "the interpretation of structured dtypes, dtypes with fields with empty", "to pass to pickle.load. These are only useful when loading", "needed return numpy.dtype(descr) elif isinstance(descr, tuple): # subtype, will always", "Such arrays will not round-trip through the format entirely accurately.", "string to get the version of the file format. Parameters", "dtype.itemsize > 0: # If dtype.itemsize == 0 then there's", "dict): msg = \"Header is not a dictionary: {!r}\" raise", "use existing file handles.\") if 'w' in mode: # We", "= token[0] token_string = token[1] if (last_token_was_number and token_type ==", "a reading machine with 32-bit C \"long ints\" will yield", "need to change a write-only mode to a read-write mode", "data will be written out. A regular numpy.ndarray object will", "of the data. See `open_memmap`. - Can be read from", "padding bytes, still get # fiddled with. This needs to", "if isinstance(name, tuple) else (None, name) titles.append(title) names.append(name) formats.append(dt) offsets.append(offset)", "with '' as a name. The dtype() constructor interprets this", "fields created by, i.e. simple fields like dtype('float32'), and then", "and F_CONTIGUOUS. d['fortran_order'] = False d['descr'] = dtype_to_descr(array.dtype) return d", "Is straightforward to reverse engineer. Datasets often live longer than", "stacklevel=2) if dtype.names is not None: # This is a", "for C_CONTIGUOUS first # because a 1-D array is both", "the necessary information to reconstruct the array including shape and", "in Python2 to be read in Python3. Parameters ---------- s", "buffersize=buffersize, order='F'): fp.write(chunk.tobytes('C')) else: if isfileobj(fp): array.tofile(fp) else: for chunk", "ought to create the file. _check_version(version) # Ensure that the", "dictionary keys are sorted in alphabetic order. This is for", "a different architecture. Both little-endian and big-endian arrays are supported,", "Python3. Parameters ---------- s : string Npy file header. Returns", "object that can be passed as an argument to the", "------ ValueError If the array cannot be persisted. This includes", "objects. We need to unpickle the data. if not allow_pickle:", "size, error_template=\"ran out of data\"): \"\"\" Read from file-like object", "create the file. None means use the oldest supported version", "string\") if magic_str[:-2] != MAGIC_PREFIX: msg = \"the magic string", "ints\", a reading machine with 32-bit C \"long ints\" will", "purposes. The dictionary contains three keys: \"descr\" : dtype.descr An", "its corresponding dtype. Parameters ---------- descr : object The object", "for creating it and a comparison of alternatives, is described", "a file-like object. mode : str, optional The mode in", "python object failed: %r\\n\" \"You may need to pass the", "the dtype() constructor. Simple types, like dtype('float32'), have a descr", "of non-C-contiguity, we allow them to be written directly to", "of the numpy package. The next 2 bytes form a", "Following the header comes the array data. If the dtype", "of dtypes # aligned up to ARRAY_ALIGN on systems like", "None: header = _wrap_header_guess_version(header) else: header = _wrap_header(header, version) fp.write(header)", "version) if len(shape) == 0: count = 1 else: count", "data. Default: None Returns ------- marray : memmap The memory-mapped", "mode=mode, offset=offset) return marray def _read_bytes(fp, size, error_template=\"ran out of", "e.g. ZipExtFile in python 2.6 can return less data than", "an NPY file, including a header. If the array is", "be mmapable, but can be read and written to disk.", "NEP <neps:nep-0001-npy-format>`, however details have evolved with time and this", "'titles': titles, 'offsets': offsets, 'itemsize': offset}) def header_data_from_array_1_0(array): \"\"\" Get", "A file object or something with a `.read()` method like", "Version 1.0 ------------------ The first 6 bytes are a magic", "are aligned on a # ARRAY_ALIGN byte boundary. This supports", "is invalid, or allow_pickle=False and the file contains an object", "d['shape'])): msg = \"shape is not valid: {!r}\" raise ValueError(msg.format(d['shape']))", "to store the data. Default: None Returns ------- marray :", "are not completely preserved. Subclasses will be accepted for writing,", "on a fix for this. This fix will not require", "reading header.append(\"'%s': %s, \" % (key, repr(value))) header.append(\"}\") header =", ": ndarray The array to write to disk. version :", "'zerosize_ok'], buffersize=buffersize, order='C'): fp.write(chunk.tobytes('C')) def read_array(fp, allow_pickle=False, pickle_kwargs=None): \"\"\" Read", "`memmap` for the available mode strings. dtype : data-type, optional", "object arrays, i.e. arrays containing elements that are arbitrary Python", "persisted. This includes the case of allow_pickle=False and array being", "header = header.encode(encoding) hlen = len(header) + 1 padlen =", "data += r if len(r) == 0 or len(data) ==", "if (last_token_was_number and token_type == tokenize.NAME and token_string == \"L\"):", "Cleaned up header. \"\"\" import tokenize from io import StringIO", "versionadded:: 1.9.0 Parameters ---------- fp : filelike object d :", "the C implementation of # dtype(). return dtype.descr else: return", "reading the file. .. warning:: Due to limitations in the", "------- magic : str Raises ------ ValueError if the version", "object arrays saved on Python 2 when using Python 3.", "about that. note that regular files can't be non-blocking try:", "to be as simple as possible while achieving its limited", "the dictionary keys are sorted in alphabetic order. This is", "array's format. It is an ASCII string which contains a", "with a different architecture. The format is designed to be", "%s, expected %d bytes got %d\" raise ValueError(msg % (error_template,", "repr(value))) header.append(\"}\") header = \"\".join(header) if version is None: header", "if minor < 0 or minor > 255: raise ValueError(\"minor", "dict, optional Additional keyword arguments to pass to pickle.dump, excluding", "None, optional The version number of the format. None means", "to Python 2 compatible format. Raises ------ ValueError If the", "make it C-contiguous # before writing. Note that we need", "object, this function will have to copy data in memory.", "pickle_kwargs : dict, optional Additional keyword arguments to pass to", "version of the file format used to create the file.", "dtype The dtype of the array that will be written", "# subtype, will always have a shape descr[1] dt =", "None # Pad the header with spaces and a final", "\"\"\" Write the header for an array and returns the", "read_magic(fp) _check_version(version) shape, fortran_order, dtype = _read_array_header(fp, version) if len(shape)", "bytes form a little-endian unsigned short int: the length of", "format version (1,0), (2,0), and (3,0), not %s\" raise ValueError(msg", "ValueError(\"Filename must be a string or a path-like object.\" \"", "the data requires it, else it will always use the", "in `numpy.io` will still be able to read and write", "Now read the actual data. if dtype.hasobject: # The array", "# Use np.ndarray instead of np.empty since the latter does", "SHOULD implement this if possible. A reader MUST NOT depend", "---------- fp : filelike object d : dict This has", "string dtypes; see # https://github.com/numpy/numpy/pull/6430 array = numpy.ndarray(count, dtype=dtype) if", "Instead, we will pickle it out if not allow_pickle: raise", "next 2 bytes form a little-endian unsigned short int: the", "None]: msg = \"we only support format version (1,0), (2,0),", "little-endian and big-endian arrays are supported, and a file with", "is a record array. The .descr is fine. XXX: parts", "string representation to the header of the file. \"\"\" d", "header = _filter_header(header) try: d = safe_eval(header) except SyntaxError as", "have a shape descr[1] dt = descr_to_dtype(descr[0]) return numpy.dtype((dt, descr[1]))", "of the format. None means use the oldest supported version", "a utf8-encoded string, so supports structured types with any unicode", ": ndarray The array from the data on disk. Raises", "object located just after the header. .. versionadded:: 1.9.0 Parameters", "regular numpy.ndarray object will be created upon reading the file.", "up to ARRAY_ALIGN on systems like Linux where mmap() #", "fortran_order: order = 'F' else: order = 'C' # We", "shape and dtype on a machine of a different architecture.", "(1, 0)) def write_array_header_2_0(fp, d): \"\"\" Write the header for", "= [] names = [] formats = [] offsets =", "1.9.0 Parameters ---------- fp : filelike object A file object", "object array. \"\"\" version = read_magic(fp) _check_version(version) shape, fortran_order, dtype", "or C-contiguous (False, the default) if we are creating a", "bool: {!r}\" raise ValueError(msg.format(d['fortran_order'])) try: dtype = descr_to_dtype(d['descr']) except TypeError", "import ( isfileobj, os_fspath, pickle ) __all__ = [] EXPECTED_KEYS", "large structured arrays. .. versionadded:: 1.9.0 Parameters ---------- fp :", "A simple format for saving numpy arrays to disk with", "creating a new file in \"write\" mode, in which case" ]
[ "list of allowed values (case sensitive) \"\"\" self.symbols = kwargs.get('symbols',", "__slots__ = ('symbols') def __init__(self, **kwargs): \"\"\" -> \"type\": \"enum\",", "= ('symbols') def __init__(self, **kwargs): \"\"\" -> \"type\": \"enum\", \"symbols\":", "return value and value in self.symbols def __str__(self): return f'enum", "**kwargs): \"\"\" -> \"type\": \"enum\", \"symbols\": [\"up\", \"down\"] symbols: list", "\"enum\", \"symbols\": [\"up\", \"down\"] symbols: list of allowed values (case", "of allowed values (case sensitive) \"\"\" self.symbols = kwargs.get('symbols', ())", "def __init__(self, **kwargs): \"\"\" -> \"type\": \"enum\", \"symbols\": [\"up\", \"down\"]", "class is_valid_enum(): \"\"\" Test if a variable is on a", "variable is on a list of valid values \"\"\" __slots__", "-> \"type\": \"enum\", \"symbols\": [\"up\", \"down\"] symbols: list of allowed", "= kwargs.get('symbols', ()) def __call__(self, value: Any) -> bool: return", "kwargs.get('symbols', ()) def __call__(self, value: Any) -> bool: return value", "\"\"\" Enumerator Test \"\"\" from typing import Any class is_valid_enum():", "is_valid_enum(): \"\"\" Test if a variable is on a list", "[\"up\", \"down\"] symbols: list of allowed values (case sensitive) \"\"\"", "__call__(self, value: Any) -> bool: return value and value in", "value and value in self.symbols def __str__(self): return f'enum {self.symbols}'", "if a variable is on a list of valid values", "of valid values \"\"\" __slots__ = ('symbols') def __init__(self, **kwargs):", "a variable is on a list of valid values \"\"\"", "allowed values (case sensitive) \"\"\" self.symbols = kwargs.get('symbols', ()) def", "symbols: list of allowed values (case sensitive) \"\"\" self.symbols =", "sensitive) \"\"\" self.symbols = kwargs.get('symbols', ()) def __call__(self, value: Any)", "is on a list of valid values \"\"\" __slots__ =", "\"\"\" __slots__ = ('symbols') def __init__(self, **kwargs): \"\"\" -> \"type\":", "Any) -> bool: return value and value in self.symbols def", "values \"\"\" __slots__ = ('symbols') def __init__(self, **kwargs): \"\"\" ->", "\"type\": \"enum\", \"symbols\": [\"up\", \"down\"] symbols: list of allowed values", "self.symbols = kwargs.get('symbols', ()) def __call__(self, value: Any) -> bool:", "()) def __call__(self, value: Any) -> bool: return value and", "\"\"\" from typing import Any class is_valid_enum(): \"\"\" Test if", "\"\"\" Test if a variable is on a list of", "\"symbols\": [\"up\", \"down\"] symbols: list of allowed values (case sensitive)", "bool: return value and value in self.symbols def __str__(self): return", "values (case sensitive) \"\"\" self.symbols = kwargs.get('symbols', ()) def __call__(self,", "\"\"\" -> \"type\": \"enum\", \"symbols\": [\"up\", \"down\"] symbols: list of", "list of valid values \"\"\" __slots__ = ('symbols') def __init__(self,", "Test \"\"\" from typing import Any class is_valid_enum(): \"\"\" Test", "valid values \"\"\" __slots__ = ('symbols') def __init__(self, **kwargs): \"\"\"", "\"\"\" self.symbols = kwargs.get('symbols', ()) def __call__(self, value: Any) ->", "on a list of valid values \"\"\" __slots__ = ('symbols')", "import Any class is_valid_enum(): \"\"\" Test if a variable is", "def __call__(self, value: Any) -> bool: return value and value", "typing import Any class is_valid_enum(): \"\"\" Test if a variable", "\"down\"] symbols: list of allowed values (case sensitive) \"\"\" self.symbols", "from typing import Any class is_valid_enum(): \"\"\" Test if a", "Enumerator Test \"\"\" from typing import Any class is_valid_enum(): \"\"\"", "(case sensitive) \"\"\" self.symbols = kwargs.get('symbols', ()) def __call__(self, value:", "a list of valid values \"\"\" __slots__ = ('symbols') def", "<gh_stars>0 \"\"\" Enumerator Test \"\"\" from typing import Any class", "('symbols') def __init__(self, **kwargs): \"\"\" -> \"type\": \"enum\", \"symbols\": [\"up\",", "value: Any) -> bool: return value and value in self.symbols", "__init__(self, **kwargs): \"\"\" -> \"type\": \"enum\", \"symbols\": [\"up\", \"down\"] symbols:", "-> bool: return value and value in self.symbols def __str__(self):", "Test if a variable is on a list of valid", "Any class is_valid_enum(): \"\"\" Test if a variable is on" ]
[ "{ # define nested Bundle \"style\": Bundle( \"scss/*.scss\", filters=(libsass), output=\"style.css\",", "+ 2], 16) for i in (0, 2, 4)) #", "import flask from dateutil.parser import parse from flask_assets import Bundle,", "4)) # noqa except Exception as err: logger.exception(f\"unable to convert", "Environment instance bundles = { # define nested Bundle \"style\":", "hex2rgb(hex, alpha=None): \"\"\"Convert a string to all caps.\"\"\" if not", "return parse(datetime_str).replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter() def replace_tz(datetime_obj): return datetime_obj.replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter() def hex2rgb(hex,", "{rgb[1]}, {rgb[2]}, {alpha})\" def get_base_url(): if prefix := cfg.gcs_bucket_prefix: return", "define nested Bundle \"style\": Bundle( \"scss/*.scss\", filters=(libsass), output=\"style.css\", ) }", "a string to all caps.\"\"\" if not hex.startswith(\"#\"): return hex", "assets.register(bundles) @app.route(\"/\") def events(): return flask.render_template( \"index.html\", calendar=gcal.load_calendar( service=gcal.build_service(), calendar_id=cfg.calendar_id,", ": i + 2], 16) for i in (0, 2,", "gcal setup_logger(name=__name__) app = flask.Flask(__name__) libsass = get_filter( \"libsass\", as_output=True,", "as err: logger.exception(f\"unable to convert {hex=} to rgb: {err}\") return", "def get_base_url(): if prefix := cfg.gcs_bucket_prefix: return f\"https://{cfg.hostname}/{prefix}\" return f\"https://{cfg.hostname}\"", "get_filter from config import cfg from apis import calendar as", "), ) @app.template_filter() def parse_tz_datetime(datetime_str): return parse(datetime_str).replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter() def replace_tz(datetime_obj):", "datetime_obj.replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter() def hex2rgb(hex, alpha=None): \"\"\"Convert a string to all", ") @app.template_filter() def parse_tz_datetime(datetime_str): return parse(datetime_str).replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter() def replace_tz(datetime_obj): return", "as_output=True, style=\"compressed\", ) assets = Environment(app) # create an Environment", "from config import cfg from apis import calendar as gcal", "dateutil.parser import parse from flask_assets import Bundle, Environment from logzero", "= flask.Flask(__name__) libsass = get_filter( \"libsass\", as_output=True, style=\"compressed\", ) assets", "noqa except Exception as err: logger.exception(f\"unable to convert {hex=} to", "tuple(int(h[i : i + 2], 16) for i in (0,", ":= cfg.gcs_bucket_prefix: return f\"https://{cfg.hostname}/{prefix}\" return f\"https://{cfg.hostname}\" def create_app(): cfg.load() #", "h if alpha is None: return f\"rgb({rgb[0]}, {rgb[1]}, {rgb[2]})\" else:", "err: logger.exception(f\"unable to convert {hex=} to rgb: {err}\") return h", "import Bundle, Environment from logzero import logger, setup_logger from webassets.filter", "= { # define nested Bundle \"style\": Bundle( \"scss/*.scss\", filters=(libsass),", "events(): return flask.render_template( \"index.html\", calendar=gcal.load_calendar( service=gcal.build_service(), calendar_id=cfg.calendar_id, ), ) @app.template_filter()", "service=gcal.build_service(), calendar_id=cfg.calendar_id, ), ) @app.template_filter() def parse_tz_datetime(datetime_str): return parse(datetime_str).replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter()", "flask.render_template( \"index.html\", calendar=gcal.load_calendar( service=gcal.build_service(), calendar_id=cfg.calendar_id, ), ) @app.template_filter() def parse_tz_datetime(datetime_str):", "an Environment instance bundles = { # define nested Bundle", "import logger, setup_logger from webassets.filter import get_filter from config import", "# noqa except Exception as err: logger.exception(f\"unable to convert {hex=}", "FREEZER_STATIC_IGNORE=[\"*.scss\", \".webassets-cache/*\", \".DS_Store\"], FREEZER_RELATIVE_URLS=False, FREEZER_REMOVE_EXTRA_FILES=True, ) logger.info(f\"create_app() => {default_app_config=}\") app.config.update(default_app_config)", "nested Bundle \"style\": Bundle( \"scss/*.scss\", filters=(libsass), output=\"style.css\", ) } assets.register(bundles)", "import calendar as gcal setup_logger(name=__name__) app = flask.Flask(__name__) libsass =", "calendar=gcal.load_calendar( service=gcal.build_service(), calendar_id=cfg.calendar_id, ), ) @app.template_filter() def parse_tz_datetime(datetime_str): return parse(datetime_str).replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"]))", "FREEZER_RELATIVE_URLS=False, FREEZER_REMOVE_EXTRA_FILES=True, ) logger.info(f\"create_app() => {default_app_config=}\") app.config.update(default_app_config) return app if", "better? default_app_config = dict( display_timezone=cfg.display_timezone, FREEZER_BASE_URL=get_base_url(), FREEZER_STATIC_IGNORE=[\"*.scss\", \".webassets-cache/*\", \".DS_Store\"], FREEZER_RELATIVE_URLS=False,", "default_app_config = dict( display_timezone=cfg.display_timezone, FREEZER_BASE_URL=get_base_url(), FREEZER_STATIC_IGNORE=[\"*.scss\", \".webassets-cache/*\", \".DS_Store\"], FREEZER_RELATIVE_URLS=False, FREEZER_REMOVE_EXTRA_FILES=True,", "this default settings thing better? default_app_config = dict( display_timezone=cfg.display_timezone, FREEZER_BASE_URL=get_base_url(),", "\"\"\"Convert a string to all caps.\"\"\" if not hex.startswith(\"#\"): return", "except Exception as err: logger.exception(f\"unable to convert {hex=} to rgb:", "@app.template_filter() def parse_tz_datetime(datetime_str): return parse(datetime_str).replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter() def replace_tz(datetime_obj): return datetime_obj.replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"]))", "alpha=None): \"\"\"Convert a string to all caps.\"\"\" if not hex.startswith(\"#\"):", "\".DS_Store\"], FREEZER_RELATIVE_URLS=False, FREEZER_REMOVE_EXTRA_FILES=True, ) logger.info(f\"create_app() => {default_app_config=}\") app.config.update(default_app_config) return app", "libsass = get_filter( \"libsass\", as_output=True, style=\"compressed\", ) assets = Environment(app)", ") assets = Environment(app) # create an Environment instance bundles", "} assets.register(bundles) @app.route(\"/\") def events(): return flask.render_template( \"index.html\", calendar=gcal.load_calendar( service=gcal.build_service(),", "calendar as gcal setup_logger(name=__name__) app = flask.Flask(__name__) libsass = get_filter(", "\"scss/*.scss\", filters=(libsass), output=\"style.css\", ) } assets.register(bundles) @app.route(\"/\") def events(): return", "create an Environment instance bundles = { # define nested", "cfg from apis import calendar as gcal setup_logger(name=__name__) app =", "= tuple(int(h[i : i + 2], 16) for i in", "bundles = { # define nested Bundle \"style\": Bundle( \"scss/*.scss\",", "string to all caps.\"\"\" if not hex.startswith(\"#\"): return hex h", "get_filter( \"libsass\", as_output=True, style=\"compressed\", ) assets = Environment(app) # create", "# define nested Bundle \"style\": Bundle( \"scss/*.scss\", filters=(libsass), output=\"style.css\", )", "\"style\": Bundle( \"scss/*.scss\", filters=(libsass), output=\"style.css\", ) } assets.register(bundles) @app.route(\"/\") def", "from zoneinfo import ZoneInfo import flask from dateutil.parser import parse", "2], 16) for i in (0, 2, 4)) # noqa", "=> {default_app_config=}\") app.config.update(default_app_config) return app if __name__ == \"__main__\": app", "cfg.gcs_bucket_prefix: return f\"https://{cfg.hostname}/{prefix}\" return f\"https://{cfg.hostname}\" def create_app(): cfg.load() # TODO:", "not hex.startswith(\"#\"): return hex h = hex.lstrip(\"#\") try: rgb =", "default settings thing better? default_app_config = dict( display_timezone=cfg.display_timezone, FREEZER_BASE_URL=get_base_url(), FREEZER_STATIC_IGNORE=[\"*.scss\",", "python from zoneinfo import ZoneInfo import flask from dateutil.parser import", "{hex=} to rgb: {err}\") return h if alpha is None:", "FREEZER_REMOVE_EXTRA_FILES=True, ) logger.info(f\"create_app() => {default_app_config=}\") app.config.update(default_app_config) return app if __name__", "parse from flask_assets import Bundle, Environment from logzero import logger,", "settings thing better? default_app_config = dict( display_timezone=cfg.display_timezone, FREEZER_BASE_URL=get_base_url(), FREEZER_STATIC_IGNORE=[\"*.scss\", \".webassets-cache/*\",", "parse(datetime_str).replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter() def replace_tz(datetime_obj): return datetime_obj.replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter() def hex2rgb(hex, alpha=None):", "rgb = tuple(int(h[i : i + 2], 16) for i", "get_base_url(): if prefix := cfg.gcs_bucket_prefix: return f\"https://{cfg.hostname}/{prefix}\" return f\"https://{cfg.hostname}\" def", "caps.\"\"\" if not hex.startswith(\"#\"): return hex h = hex.lstrip(\"#\") try:", "logger, setup_logger from webassets.filter import get_filter from config import cfg", "return hex h = hex.lstrip(\"#\") try: rgb = tuple(int(h[i :", "(0, 2, 4)) # noqa except Exception as err: logger.exception(f\"unable", "from flask_assets import Bundle, Environment from logzero import logger, setup_logger", "@app.route(\"/\") def events(): return flask.render_template( \"index.html\", calendar=gcal.load_calendar( service=gcal.build_service(), calendar_id=cfg.calendar_id, ),", "{default_app_config=}\") app.config.update(default_app_config) return app if __name__ == \"__main__\": app =", "return flask.render_template( \"index.html\", calendar=gcal.load_calendar( service=gcal.build_service(), calendar_id=cfg.calendar_id, ), ) @app.template_filter() def", "@app.template_filter() def hex2rgb(hex, alpha=None): \"\"\"Convert a string to all caps.\"\"\"", "return f\"rgb({rgb[0]}, {rgb[1]}, {rgb[2]})\" else: return f\"rgba({rgb[0]}, {rgb[1]}, {rgb[2]}, {alpha})\"", "from dateutil.parser import parse from flask_assets import Bundle, Environment from", "2, 4)) # noqa except Exception as err: logger.exception(f\"unable to", "f\"https://{cfg.hostname}\" def create_app(): cfg.load() # TODO: do this default settings", "hex.startswith(\"#\"): return hex h = hex.lstrip(\"#\") try: rgb = tuple(int(h[i", "thing better? default_app_config = dict( display_timezone=cfg.display_timezone, FREEZER_BASE_URL=get_base_url(), FREEZER_STATIC_IGNORE=[\"*.scss\", \".webassets-cache/*\", \".DS_Store\"],", "= hex.lstrip(\"#\") try: rgb = tuple(int(h[i : i + 2],", "import parse from flask_assets import Bundle, Environment from logzero import", "style=\"compressed\", ) assets = Environment(app) # create an Environment instance", "return f\"rgba({rgb[0]}, {rgb[1]}, {rgb[2]}, {alpha})\" def get_base_url(): if prefix :=", "to rgb: {err}\") return h if alpha is None: return", "rgb: {err}\") return h if alpha is None: return f\"rgb({rgb[0]},", "# create an Environment instance bundles = { # define", "Exception as err: logger.exception(f\"unable to convert {hex=} to rgb: {err}\")", "\".webassets-cache/*\", \".DS_Store\"], FREEZER_RELATIVE_URLS=False, FREEZER_REMOVE_EXTRA_FILES=True, ) logger.info(f\"create_app() => {default_app_config=}\") app.config.update(default_app_config) return", "#!/usr/bin/env python from zoneinfo import ZoneInfo import flask from dateutil.parser", "to all caps.\"\"\" if not hex.startswith(\"#\"): return hex h =", "= dict( display_timezone=cfg.display_timezone, FREEZER_BASE_URL=get_base_url(), FREEZER_STATIC_IGNORE=[\"*.scss\", \".webassets-cache/*\", \".DS_Store\"], FREEZER_RELATIVE_URLS=False, FREEZER_REMOVE_EXTRA_FILES=True, )", "h = hex.lstrip(\"#\") try: rgb = tuple(int(h[i : i +", "convert {hex=} to rgb: {err}\") return h if alpha is", "dict( display_timezone=cfg.display_timezone, FREEZER_BASE_URL=get_base_url(), FREEZER_STATIC_IGNORE=[\"*.scss\", \".webassets-cache/*\", \".DS_Store\"], FREEZER_RELATIVE_URLS=False, FREEZER_REMOVE_EXTRA_FILES=True, ) logger.info(f\"create_app()", "@app.template_filter() def replace_tz(datetime_obj): return datetime_obj.replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter() def hex2rgb(hex, alpha=None): \"\"\"Convert", "create_app(): cfg.load() # TODO: do this default settings thing better?", "Environment(app) # create an Environment instance bundles = { #", "hex h = hex.lstrip(\"#\") try: rgb = tuple(int(h[i : i", "if not hex.startswith(\"#\"): return hex h = hex.lstrip(\"#\") try: rgb", "logger.exception(f\"unable to convert {hex=} to rgb: {err}\") return h if", ") } assets.register(bundles) @app.route(\"/\") def events(): return flask.render_template( \"index.html\", calendar=gcal.load_calendar(", "logger.info(f\"create_app() => {default_app_config=}\") app.config.update(default_app_config) return app if __name__ == \"__main__\":", "ZoneInfo import flask from dateutil.parser import parse from flask_assets import", "if alpha is None: return f\"rgb({rgb[0]}, {rgb[1]}, {rgb[2]})\" else: return", "None: return f\"rgb({rgb[0]}, {rgb[1]}, {rgb[2]})\" else: return f\"rgba({rgb[0]}, {rgb[1]}, {rgb[2]},", "hex.lstrip(\"#\") try: rgb = tuple(int(h[i : i + 2], 16)", "{alpha})\" def get_base_url(): if prefix := cfg.gcs_bucket_prefix: return f\"https://{cfg.hostname}/{prefix}\" return", "return f\"https://{cfg.hostname}\" def create_app(): cfg.load() # TODO: do this default", "try: rgb = tuple(int(h[i : i + 2], 16) for", "f\"rgba({rgb[0]}, {rgb[1]}, {rgb[2]}, {alpha})\" def get_base_url(): if prefix := cfg.gcs_bucket_prefix:", "def events(): return flask.render_template( \"index.html\", calendar=gcal.load_calendar( service=gcal.build_service(), calendar_id=cfg.calendar_id, ), )", "16) for i in (0, 2, 4)) # noqa except", "display_timezone=cfg.display_timezone, FREEZER_BASE_URL=get_base_url(), FREEZER_STATIC_IGNORE=[\"*.scss\", \".webassets-cache/*\", \".DS_Store\"], FREEZER_RELATIVE_URLS=False, FREEZER_REMOVE_EXTRA_FILES=True, ) logger.info(f\"create_app() =>", "flask.Flask(__name__) libsass = get_filter( \"libsass\", as_output=True, style=\"compressed\", ) assets =", "parse_tz_datetime(datetime_str): return parse(datetime_str).replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter() def replace_tz(datetime_obj): return datetime_obj.replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter() def", "from webassets.filter import get_filter from config import cfg from apis", "return datetime_obj.replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter() def hex2rgb(hex, alpha=None): \"\"\"Convert a string to", "app if __name__ == \"__main__\": app = create_app() app.run( host=\"0.0.0.0\",", "webassets.filter import get_filter from config import cfg from apis import", "else: return f\"rgba({rgb[0]}, {rgb[1]}, {rgb[2]}, {alpha})\" def get_base_url(): if prefix", "assets = Environment(app) # create an Environment instance bundles =", "from apis import calendar as gcal setup_logger(name=__name__) app = flask.Flask(__name__)", "for i in (0, 2, 4)) # noqa except Exception", "setup_logger from webassets.filter import get_filter from config import cfg from", "def parse_tz_datetime(datetime_str): return parse(datetime_str).replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter() def replace_tz(datetime_obj): return datetime_obj.replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter()", "config import cfg from apis import calendar as gcal setup_logger(name=__name__)", "flask_assets import Bundle, Environment from logzero import logger, setup_logger from", "Bundle \"style\": Bundle( \"scss/*.scss\", filters=(libsass), output=\"style.css\", ) } assets.register(bundles) @app.route(\"/\")", "Environment from logzero import logger, setup_logger from webassets.filter import get_filter", "import get_filter from config import cfg from apis import calendar", "setup_logger(name=__name__) app = flask.Flask(__name__) libsass = get_filter( \"libsass\", as_output=True, style=\"compressed\",", "return app if __name__ == \"__main__\": app = create_app() app.run(", "= Environment(app) # create an Environment instance bundles = {", "def create_app(): cfg.load() # TODO: do this default settings thing", "output=\"style.css\", ) } assets.register(bundles) @app.route(\"/\") def events(): return flask.render_template( \"index.html\",", "i in (0, 2, 4)) # noqa except Exception as", "= get_filter( \"libsass\", as_output=True, style=\"compressed\", ) assets = Environment(app) #", "if prefix := cfg.gcs_bucket_prefix: return f\"https://{cfg.hostname}/{prefix}\" return f\"https://{cfg.hostname}\" def create_app():", "i + 2], 16) for i in (0, 2, 4))", "__name__ == \"__main__\": app = create_app() app.run( host=\"0.0.0.0\", debug=True, )", "FREEZER_BASE_URL=get_base_url(), FREEZER_STATIC_IGNORE=[\"*.scss\", \".webassets-cache/*\", \".DS_Store\"], FREEZER_RELATIVE_URLS=False, FREEZER_REMOVE_EXTRA_FILES=True, ) logger.info(f\"create_app() => {default_app_config=}\")", "alpha is None: return f\"rgb({rgb[0]}, {rgb[1]}, {rgb[2]})\" else: return f\"rgba({rgb[0]},", "filters=(libsass), output=\"style.css\", ) } assets.register(bundles) @app.route(\"/\") def events(): return flask.render_template(", "Bundle( \"scss/*.scss\", filters=(libsass), output=\"style.css\", ) } assets.register(bundles) @app.route(\"/\") def events():", "return f\"https://{cfg.hostname}/{prefix}\" return f\"https://{cfg.hostname}\" def create_app(): cfg.load() # TODO: do", "instance bundles = { # define nested Bundle \"style\": Bundle(", "cfg.load() # TODO: do this default settings thing better? default_app_config", "all caps.\"\"\" if not hex.startswith(\"#\"): return hex h = hex.lstrip(\"#\")", "f\"https://{cfg.hostname}/{prefix}\" return f\"https://{cfg.hostname}\" def create_app(): cfg.load() # TODO: do this", "replace_tz(datetime_obj): return datetime_obj.replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter() def hex2rgb(hex, alpha=None): \"\"\"Convert a string", "{rgb[1]}, {rgb[2]})\" else: return f\"rgba({rgb[0]}, {rgb[1]}, {rgb[2]}, {alpha})\" def get_base_url():", "Bundle, Environment from logzero import logger, setup_logger from webassets.filter import", "def replace_tz(datetime_obj): return datetime_obj.replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter() def hex2rgb(hex, alpha=None): \"\"\"Convert a", "{rgb[2]})\" else: return f\"rgba({rgb[0]}, {rgb[1]}, {rgb[2]}, {alpha})\" def get_base_url(): if", "# TODO: do this default settings thing better? default_app_config =", "to convert {hex=} to rgb: {err}\") return h if alpha", "in (0, 2, 4)) # noqa except Exception as err:", "import ZoneInfo import flask from dateutil.parser import parse from flask_assets", ") logger.info(f\"create_app() => {default_app_config=}\") app.config.update(default_app_config) return app if __name__ ==", "app.config.update(default_app_config) return app if __name__ == \"__main__\": app = create_app()", "f\"rgb({rgb[0]}, {rgb[1]}, {rgb[2]})\" else: return f\"rgba({rgb[0]}, {rgb[1]}, {rgb[2]}, {alpha})\" def", "return h if alpha is None: return f\"rgb({rgb[0]}, {rgb[1]}, {rgb[2]})\"", "import cfg from apis import calendar as gcal setup_logger(name=__name__) app", "def hex2rgb(hex, alpha=None): \"\"\"Convert a string to all caps.\"\"\" if", "prefix := cfg.gcs_bucket_prefix: return f\"https://{cfg.hostname}/{prefix}\" return f\"https://{cfg.hostname}\" def create_app(): cfg.load()", "\"index.html\", calendar=gcal.load_calendar( service=gcal.build_service(), calendar_id=cfg.calendar_id, ), ) @app.template_filter() def parse_tz_datetime(datetime_str): return", "TODO: do this default settings thing better? default_app_config = dict(", "logzero import logger, setup_logger from webassets.filter import get_filter from config", "flask from dateutil.parser import parse from flask_assets import Bundle, Environment", "zoneinfo import ZoneInfo import flask from dateutil.parser import parse from", "{rgb[2]}, {alpha})\" def get_base_url(): if prefix := cfg.gcs_bucket_prefix: return f\"https://{cfg.hostname}/{prefix}\"", "app = flask.Flask(__name__) libsass = get_filter( \"libsass\", as_output=True, style=\"compressed\", )", "calendar_id=cfg.calendar_id, ), ) @app.template_filter() def parse_tz_datetime(datetime_str): return parse(datetime_str).replace(tzinfo=ZoneInfo(app.config[\"display_timezone\"])) @app.template_filter() def", "is None: return f\"rgb({rgb[0]}, {rgb[1]}, {rgb[2]})\" else: return f\"rgba({rgb[0]}, {rgb[1]},", "from logzero import logger, setup_logger from webassets.filter import get_filter from", "\"libsass\", as_output=True, style=\"compressed\", ) assets = Environment(app) # create an", "if __name__ == \"__main__\": app = create_app() app.run( host=\"0.0.0.0\", debug=True,", "do this default settings thing better? default_app_config = dict( display_timezone=cfg.display_timezone,", "apis import calendar as gcal setup_logger(name=__name__) app = flask.Flask(__name__) libsass", "as gcal setup_logger(name=__name__) app = flask.Flask(__name__) libsass = get_filter( \"libsass\",", "{err}\") return h if alpha is None: return f\"rgb({rgb[0]}, {rgb[1]}," ]
[ "scan if (i == 0) & (tab[0]['EXPTIME'] < 1.1): print('SKIPPING", "plt.subplot(6, len(expids), len(expids)*j + i + 1) plt.xticks([]) plt.yticks([]) im", "c='r') expid_min = int(np.min(expids)) print(focus_z) print(fwhm_pix) plt.savefig(os.path.join(outdir, 'stamps_focus_scan-' + str(expid_min).zfill(8)+'.png'),", "plt.text(focus_z[2], yrange[0] + 0.9*(yrange[1]-yrange[0]), 'best focus : ' + str(int(np.round(zmin))))", "i, expid in enumerate(expids): fname = _fname(expid, night, basedir=basedir, ccds=True)", "hdu in hdul] for j, extname in enumerate(extnames): if extname", "if (i == 0) & (tab[0]['EXPTIME'] < 1.1): print('SKIPPING DUMMY", "night, basedir=basedir) if len(expids) == 0: print('NO FOCUS SCAN EXPOSURES", "focus_z.append(float(ccds[0]['FOCUS'].split(',')[2])) hdul = fits.open(fname) extnames_present = [hdu.header['EXTNAME'] for hdu in", "plt.plot(xsamp, ysamp) zmin = -coeff[1]/(2*coeff[0]) min_fwhm_fit_asec = coeff[0]*(zmin**2) + coeff[1]*zmin", "0.205 focus_z = np.array(focus_z) fwhm_asec = np.array(fwhm_pix)*asec_per_pix plt.scatter(focus_z, fwhm_asec) plt.xlabel('focus", "+ str(expid_min).zfill(8) + '.png'), bbox_inches='tight') if not no_popups: plt.show() def", "plot windows') args = parser.parse_args() expids = args.first_expid + np.arange(16,", "extname=extname) plt.imshow(im, interpolation='nearest', origin='lower', cmap='gray_r', vmin=0.01) plt.text(5, 44, str(expid) +", "accidentally lists the 'setup focus scan' # 1 second exposure", "'setup focus scan' # 1 second exposure as the start", "exposure as the start of the focus scan if (i", "import matplotlib.pyplot as plt import argparse def _fname(expid, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus',", "= 45485 + np.arange(7) focus_plots(night, expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid') if __name__ ==", "= [] fwhm_pix = [] # PSF stamps plot plt.subplots_adjust(hspace=0.01,", "keep = [] for i, expid in enumerate(expids): fname =", "fits.getdata(fname_ccds) if np.sum(np.isfinite(ccds['PSF_FWHM_PIX'])) != 0: fwhm_pix.append(np.median(ccds['PSF_FWHM_PIX'][np.isfinite(ccds['PSF_FWHM_PIX'])])) focus_z.append(float(ccds[0]['FOCUS'].split(',')[2])) hdul = fits.open(fname)", "bbox_inches='tight') #plt.cla() plt.figure(200) asec_per_pix = 0.205 focus_z = np.array(focus_z) fwhm_asec", "with EXPID = ' + str(expid_min)) plt.plot(xsamp, ysamp) zmin =", "yrange[0] + 0.8*(yrange[1]-yrange[0]), 'best FWHM (meas) : ' + '{:.2f}'.format(np.min(fwhm_asec)))", "_fname(expid, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus', ccds=False): fname = basedir + '/' +", "== 0: print('NO FOCUS SCAN EXPOSURES TO ANALYZE ??') assert(False)", "basedir=basedir, ccds=True) if not os.path.exists(fname): continue tab = fits.getdata(fname) #", "+ str(int(np.round(zmin)))) plt.savefig(os.path.join(outdir, 'fit_focus_scan-' + str(expid_min).zfill(8) + '.png'), bbox_inches='tight') if", "FWHM (meas) : ' + '{:.2f}'.format(np.min(fwhm_asec))) plt.text(focus_z[2], yrange[0] + 0.7*(yrange[1]-yrange[0]),", "'GUIDE3', 'GUIDE5', 'GUIDE7', 'GUIDE8'] focus_z = [] fwhm_pix = []", "+ '; ' + extname, color='r', fontsize=9) plt.text(10, 3.5, 'z", "handle case where observer accidentally lists the 'setup focus scan'", "args = parser.parse_args() expids = args.first_expid + np.arange(16, dtype=int) print(expids)", "extnames_present = [hdu.header['EXTNAME'] for hdu in hdul] for j, extname", "tab[0]['PROGRAM'].strip() if program != 'focus scan': break keep.append(expid) return keep", "' + str(int(float(ccds[0]['FOCUS'].split(',')[2]))), color='r') if np.isfinite(ccds[j]['XCENTROID_PSF']) and np.isfinite(ccds[j]['YCENTROID_PSF']): plt.scatter([ccds[j]['XCENTROID_PSF']], [ccds[j]['YCENTROID_PSF']],", "fwhm_pix = [] # PSF stamps plot plt.subplots_adjust(hspace=0.01, wspace=0.01) for", "import astropy.io.fits as fits import numpy as np import os", "# try to handle case where observer accidentally lists the", "_test_missing_cam(): night = '20200131' expids = 45485 + np.arange(7) focus_plots(night,", "FOCUS SCAN EXPOSURES TO ANALYZE ??') assert(False) plt.figure(1, figsize=(12.0*(len(expids)/7.0), 9))", "for GFA reductions') parser.add_argument('--outdir', default='/n/home/desiobserver/focus_scan_pngs', type=str, help='output directory for plot", "night, basedir='/n/home/datasystems/users/ameisner/reduced/focus', ccds=False): fname = basedir + '/' + night", "night = '20200131' expids = 45485 + np.arange(7) focus_plots(night, expids,", "(meas) : ' + '{:.2f}'.format(np.min(fwhm_asec))) plt.text(focus_z[2], yrange[0] + 0.7*(yrange[1]-yrange[0]), 'best", "default='/n/home/desiobserver/focus_scan_pngs', type=str, help='output directory for plot PNGs') parser.add_argument('--no_popups', default=False, action='store_true',", "fits.getdata(fname) # try to handle case where observer accidentally lists", "' + '{:.2f}'.format(min_fwhm_fit_asec)) plt.text(focus_z[2], yrange[0] + 0.9*(yrange[1]-yrange[0]), 'best focus :", "np.isfinite(ccds[j]['YCENTROID_PSF']): plt.scatter([ccds[j]['XCENTROID_PSF']], [ccds[j]['YCENTROID_PSF']], marker='.', c='r') expid_min = int(np.min(expids)) print(focus_z) print(fwhm_pix)", "< 1.1): print('SKIPPING DUMMY SETUP EXPOSURE') continue program = tab[0]['PROGRAM'].strip()", "= tab[0]['PROGRAM'].strip() if program != 'focus scan': break keep.append(expid) return", "bbox_inches='tight') if not no_popups: plt.show() def _test(): night = '20200131'", "# 1 second exposure as the start of the focus", "help='base directory for GFA reductions') parser.add_argument('--outdir', default='/n/home/desiobserver/focus_scan_pngs', type=str, help='output directory", "plt.title('focus scan starting with EXPID = ' + str(expid_min)) plt.plot(xsamp,", "(i == 0) & (tab[0]['EXPTIME'] < 1.1): print('SKIPPING DUMMY SETUP", "0.7*(yrange[1]-yrange[0]), 'best FWHM (fit) : ' + '{:.2f}'.format(min_fwhm_fit_asec)) plt.text(focus_z[2], yrange[0]", "'best FWHM (fit) : ' + '{:.2f}'.format(min_fwhm_fit_asec)) plt.text(focus_z[2], yrange[0] +", "type=str, nargs=1) parser.add_argument('--basedir', default='/n/home/datasystems/users/ameisner/reduced/focus', type=str, help='base directory for GFA reductions')", "extnames_present: continue print(i, j) plt.subplot(6, len(expids), len(expids)*j + i +", "xsamp = np.arange(np.min(focus_z), np.max(focus_z)) ysamp = coeff[0]*(np.power(xsamp, 2)) + coeff[1]*xsamp", "' + str(int(np.round(zmin)))) plt.savefig(os.path.join(outdir, 'fit_focus_scan-' + str(expid_min).zfill(8) + '.png'), bbox_inches='tight')", "break keep.append(expid) return keep def focus_plots(night, expids, basedir='/n/home/datasystems/users/ameisner/reduced/focus', outdir='/n/home/desiobserver/focus_scan_pngs', no_popups=False):", "DUMMY SETUP EXPOSURE') continue program = tab[0]['PROGRAM'].strip() if program !=", "for i, expid in enumerate(expids): fname = _fname(expid, night, basedir=basedir,", "== 0) & (tab[0]['EXPTIME'] < 1.1): print('SKIPPING DUMMY SETUP EXPOSURE')", "print(focus_z) print(fwhm_pix) plt.savefig(os.path.join(outdir, 'stamps_focus_scan-' + str(expid_min).zfill(8)+'.png'), bbox_inches='tight') #plt.cla() plt.figure(200) asec_per_pix", "' + '{:.2f}'.format(np.min(fwhm_asec))) plt.text(focus_z[2], yrange[0] + 0.7*(yrange[1]-yrange[0]), 'best FWHM (fit)", "+ str(expid).zfill(8) + '/gfa-' + str(expid).zfill(8) + '_psfs.fits' if ccds:", "+ 0.9*(yrange[1]-yrange[0]), 'best focus : ' + str(int(np.round(zmin)))) plt.savefig(os.path.join(outdir, 'fit_focus_scan-'", "if np.isfinite(ccds[j]['XCENTROID_PSF']) and np.isfinite(ccds[j]['YCENTROID_PSF']): plt.scatter([ccds[j]['XCENTROID_PSF']], [ccds[j]['YCENTROID_PSF']], marker='.', c='r') expid_min =", "focus_plots(night, expids, basedir='/n/home/datasystems/users/ameisner/reduced/focus', outdir='/n/home/desiobserver/focus_scan_pngs', no_popups=False): expids = _actual_expid_list(expids, night, basedir=basedir)", "case where observer accidentally lists the 'setup focus scan' #", "hdul] for j, extname in enumerate(extnames): if extname not in", "np.arange(7) focus_plots(night, expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid') if __name__ == \"__main__\": descr =", "+ coeff[2] plt.title('focus scan starting with EXPID = ' +", "yrange[0] + 0.9*(yrange[1]-yrange[0]), 'best focus : ' + str(int(np.round(zmin)))) plt.savefig(os.path.join(outdir,", "as plt import argparse def _fname(expid, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus', ccds=False): fname", "plt.xlabel('focus z (micron)') plt.ylabel('FWHM (asec)') coeff = np.polyfit(focus_z, fwhm_asec, 2)", "'GFA focus sequence plots/analysis' parser = argparse.ArgumentParser(description=descr) parser.add_argument('first_expid', type=int, nargs=1)", "+ coeff[1]*xsamp + coeff[2] plt.title('focus scan starting with EXPID =", "'/gfa-' + str(expid).zfill(8) + '_psfs.fits' if ccds: fname = fname.replace('_psfs.fits',", "fits import numpy as np import os import matplotlib.pyplot as", "'best focus : ' + str(int(np.round(zmin)))) plt.savefig(os.path.join(outdir, 'fit_focus_scan-' + str(expid_min).zfill(8)", "in enumerate(expids): fname = _fname(expid, night, basedir=basedir) print(fname) fname_ccds =", "-coeff[1]/(2*coeff[0]) min_fwhm_fit_asec = coeff[0]*(zmin**2) + coeff[1]*zmin + coeff[2] yrange =", "'/' + str(expid).zfill(8) + '/gfa-' + str(expid).zfill(8) + '_psfs.fits' if", "+ 0.7*(yrange[1]-yrange[0]), 'best FWHM (fit) : ' + '{:.2f}'.format(min_fwhm_fit_asec)) plt.text(focus_z[2],", "_fname(expid, night, basedir=basedir) print(fname) fname_ccds = _fname(expid, night, basedir=basedir, ccds=True)", "plt.text(5, 44, str(expid) + '; ' + extname, color='r', fontsize=9)", "parser.add_argument('first_expid', type=int, nargs=1) parser.add_argument('night', type=str, nargs=1) parser.add_argument('--basedir', default='/n/home/datasystems/users/ameisner/reduced/focus', type=str, help='base", "+ coeff[2] yrange = [np.min(fwhm_asec), np.max(fwhm_asec)] plt.text(focus_z[2], yrange[0] + 0.8*(yrange[1]-yrange[0]),", "PNGs without popping up plot windows') args = parser.parse_args() expids", "ccds: fname = fname.replace('_psfs.fits', '_ccds.fits') return fname def _actual_expid_list(expids, night,", "0.9*(yrange[1]-yrange[0]), 'best focus : ' + str(int(np.round(zmin)))) plt.savefig(os.path.join(outdir, 'fit_focus_scan-' +", "[] # PSF stamps plot plt.subplots_adjust(hspace=0.01, wspace=0.01) for i, expid", "and np.isfinite(ccds[j]['YCENTROID_PSF']): plt.scatter([ccds[j]['XCENTROID_PSF']], [ccds[j]['YCENTROID_PSF']], marker='.', c='r') expid_min = int(np.min(expids)) print(focus_z)", "_actual_expid_list(expids, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus'): keep = [] for i, expid in", "fname def _actual_expid_list(expids, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus'): keep = [] for i,", "focus scan if (i == 0) & (tab[0]['EXPTIME'] < 1.1):", "no_popups: plt.show() def _test(): night = '20200131' expids = 45446", "stamps plot plt.subplots_adjust(hspace=0.01, wspace=0.01) for i, expid in enumerate(expids): fname", "basedir=basedir) if len(expids) == 0: print('NO FOCUS SCAN EXPOSURES TO", "fwhm_asec, 2) xsamp = np.arange(np.min(focus_z), np.max(focus_z)) ysamp = coeff[0]*(np.power(xsamp, 2))", "'GUIDE2', 'GUIDE3', 'GUIDE5', 'GUIDE7', 'GUIDE8'] focus_z = [] fwhm_pix =", "sequence plots/analysis' parser = argparse.ArgumentParser(description=descr) parser.add_argument('first_expid', type=int, nargs=1) parser.add_argument('night', type=str,", "in enumerate(expids): fname = _fname(expid, night, basedir=basedir, ccds=True) if not", "focus_plots(night, expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid', outdir='.') def _test_missing_cam(): night = '20200131' expids", "[hdu.header['EXTNAME'] for hdu in hdul] for j, extname in enumerate(extnames):", "' + extname, color='r', fontsize=9) plt.text(10, 3.5, 'z = '", "min_fwhm_fit_asec = coeff[0]*(zmin**2) + coeff[1]*zmin + coeff[2] yrange = [np.min(fwhm_asec),", "no_popups=False): expids = _actual_expid_list(expids, night, basedir=basedir) if len(expids) == 0:", "basedir='/n/home/datasystems/users/ameisner/reduced/focus'): keep = [] for i, expid in enumerate(expids): fname", "parser.add_argument('--no_popups', default=False, action='store_true', help='write PNGs without popping up plot windows')", "expid in enumerate(expids): fname = _fname(expid, night, basedir=basedir) print(fname) fname_ccds", "1 second exposure as the start of the focus scan", "0: fwhm_pix.append(np.median(ccds['PSF_FWHM_PIX'][np.isfinite(ccds['PSF_FWHM_PIX'])])) focus_z.append(float(ccds[0]['FOCUS'].split(',')[2])) hdul = fits.open(fname) extnames_present = [hdu.header['EXTNAME'] for", "not in extnames_present: continue print(i, j) plt.subplot(6, len(expids), len(expids)*j +", "fwhm_asec = np.array(fwhm_pix)*asec_per_pix plt.scatter(focus_z, fwhm_asec) plt.xlabel('focus z (micron)') plt.ylabel('FWHM (asec)')", "= args.first_expid + np.arange(16, dtype=int) print(expids) print(args.night[0]) print(args.basedir) outdir =", "'; ' + extname, color='r', fontsize=9) plt.text(10, 3.5, 'z =", "fits.getdata(fname, extname=extname) plt.imshow(im, interpolation='nearest', origin='lower', cmap='gray_r', vmin=0.01) plt.text(5, 44, str(expid)", "not os.path.exists(fname): continue tab = fits.getdata(fname) # try to handle", "+ '/' + str(expid).zfill(8) + '/gfa-' + str(expid).zfill(8) + '_psfs.fits'", "'GUIDE7', 'GUIDE8'] focus_z = [] fwhm_pix = [] # PSF", "fname.replace('_psfs.fits', '_ccds.fits') return fname def _actual_expid_list(expids, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus'): keep =", "44, str(expid) + '; ' + extname, color='r', fontsize=9) plt.text(10,", "'stamps_focus_scan-' + str(expid_min).zfill(8)+'.png'), bbox_inches='tight') #plt.cla() plt.figure(200) asec_per_pix = 0.205 focus_z", "_fname(expid, night, basedir=basedir, ccds=True) if not os.path.exists(fname): continue ccds =", "program = tab[0]['PROGRAM'].strip() if program != 'focus scan': break keep.append(expid)", "'fit_focus_scan-' + str(expid_min).zfill(8) + '.png'), bbox_inches='tight') if not no_popups: plt.show()", "+ 0.8*(yrange[1]-yrange[0]), 'best FWHM (meas) : ' + '{:.2f}'.format(np.min(fwhm_asec))) plt.text(focus_z[2],", "directory for plot PNGs') parser.add_argument('--no_popups', default=False, action='store_true', help='write PNGs without", "'GUIDE8'] focus_z = [] fwhm_pix = [] # PSF stamps", "plt.scatter([ccds[j]['XCENTROID_PSF']], [ccds[j]['YCENTROID_PSF']], marker='.', c='r') expid_min = int(np.min(expids)) print(focus_z) print(fwhm_pix) plt.savefig(os.path.join(outdir,", "= ['GUIDE0', 'GUIDE2', 'GUIDE3', 'GUIDE5', 'GUIDE7', 'GUIDE8'] focus_z = []", "'20200131' expids = 45485 + np.arange(7) focus_plots(night, expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid') if", "def _actual_expid_list(expids, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus'): keep = [] for i, expid", "continue ccds = fits.getdata(fname_ccds) if np.sum(np.isfinite(ccds['PSF_FWHM_PIX'])) != 0: fwhm_pix.append(np.median(ccds['PSF_FWHM_PIX'][np.isfinite(ccds['PSF_FWHM_PIX'])])) focus_z.append(float(ccds[0]['FOCUS'].split(',')[2]))", "fits.open(fname) extnames_present = [hdu.header['EXTNAME'] for hdu in hdul] for j,", "fname = basedir + '/' + night + '/' +", "1) plt.xticks([]) plt.yticks([]) im = fits.getdata(fname, extname=extname) plt.imshow(im, interpolation='nearest', origin='lower',", "outdir = args.outdir if os.path.exists(args.outdir) else '.' focus_plots(args.night[0], expids, basedir=args.basedir,", "cmap='gray_r', vmin=0.01) plt.text(5, 44, str(expid) + '; ' + extname,", "astropy.io.fits as fits import numpy as np import os import", "night, basedir=basedir, ccds=True) if not os.path.exists(fname): continue ccds = fits.getdata(fname_ccds)", "np.array(focus_z) fwhm_asec = np.array(fwhm_pix)*asec_per_pix plt.scatter(focus_z, fwhm_asec) plt.xlabel('focus z (micron)') plt.ylabel('FWHM", "continue print(i, j) plt.subplot(6, len(expids), len(expids)*j + i + 1)", "outdir='/n/home/desiobserver/focus_scan_pngs', no_popups=False): expids = _actual_expid_list(expids, night, basedir=basedir) if len(expids) ==", "if __name__ == \"__main__\": descr = 'GFA focus sequence plots/analysis'", "GFA reductions') parser.add_argument('--outdir', default='/n/home/desiobserver/focus_scan_pngs', type=str, help='output directory for plot PNGs')", "args.outdir if os.path.exists(args.outdir) else '.' focus_plots(args.night[0], expids, basedir=args.basedir, outdir=outdir, no_popups=args.no_popups)", "focus_z = np.array(focus_z) fwhm_asec = np.array(fwhm_pix)*asec_per_pix plt.scatter(focus_z, fwhm_asec) plt.xlabel('focus z", "windows') args = parser.parse_args() expids = args.first_expid + np.arange(16, dtype=int)", "def _fname(expid, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus', ccds=False): fname = basedir + '/'", "45446 + np.arange(7) focus_plots(night, expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid', outdir='.') def _test_missing_cam(): night", "plt.ylabel('FWHM (asec)') coeff = np.polyfit(focus_z, fwhm_asec, 2) xsamp = np.arange(np.min(focus_z),", "SETUP EXPOSURE') continue program = tab[0]['PROGRAM'].strip() if program != 'focus", "action='store_true', help='write PNGs without popping up plot windows') args =", "str(expid).zfill(8) + '_psfs.fits' if ccds: fname = fname.replace('_psfs.fits', '_ccds.fits') return", "the start of the focus scan if (i == 0)", "enumerate(expids): fname = _fname(expid, night, basedir=basedir, ccds=True) if not os.path.exists(fname):", "print(args.basedir) outdir = args.outdir if os.path.exists(args.outdir) else '.' focus_plots(args.night[0], expids,", "np.array(fwhm_pix)*asec_per_pix plt.scatter(focus_z, fwhm_asec) plt.xlabel('focus z (micron)') plt.ylabel('FWHM (asec)') coeff =", "np.arange(16, dtype=int) print(expids) print(args.night[0]) print(args.basedir) outdir = args.outdir if os.path.exists(args.outdir)", "expid_min = int(np.min(expids)) print(focus_z) print(fwhm_pix) plt.savefig(os.path.join(outdir, 'stamps_focus_scan-' + str(expid_min).zfill(8)+'.png'), bbox_inches='tight')", "vmin=0.01) plt.text(5, 44, str(expid) + '; ' + extname, color='r',", "keep def focus_plots(night, expids, basedir='/n/home/datasystems/users/ameisner/reduced/focus', outdir='/n/home/desiobserver/focus_scan_pngs', no_popups=False): expids = _actual_expid_list(expids,", "= _fname(expid, night, basedir=basedir, ccds=True) if not os.path.exists(fname): continue tab", "i, expid in enumerate(expids): fname = _fname(expid, night, basedir=basedir) print(fname)", "plt.yticks([]) im = fits.getdata(fname, extname=extname) plt.imshow(im, interpolation='nearest', origin='lower', cmap='gray_r', vmin=0.01)", "marker='.', c='r') expid_min = int(np.min(expids)) print(focus_z) print(fwhm_pix) plt.savefig(os.path.join(outdir, 'stamps_focus_scan-' +", "str(int(np.round(zmin)))) plt.savefig(os.path.join(outdir, 'fit_focus_scan-' + str(expid_min).zfill(8) + '.png'), bbox_inches='tight') if not", "starting with EXPID = ' + str(expid_min)) plt.plot(xsamp, ysamp) zmin", "as fits import numpy as np import os import matplotlib.pyplot", "= [hdu.header['EXTNAME'] for hdu in hdul] for j, extname in", "#plt.cla() plt.figure(200) asec_per_pix = 0.205 focus_z = np.array(focus_z) fwhm_asec =", "type=int, nargs=1) parser.add_argument('night', type=str, nargs=1) parser.add_argument('--basedir', default='/n/home/datasystems/users/ameisner/reduced/focus', type=str, help='base directory", "= fits.open(fname) extnames_present = [hdu.header['EXTNAME'] for hdu in hdul] for", "expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid', outdir='.') def _test_missing_cam(): night = '20200131' expids =", "in hdul] for j, extname in enumerate(extnames): if extname not", "coeff[0]*(zmin**2) + coeff[1]*zmin + coeff[2] yrange = [np.min(fwhm_asec), np.max(fwhm_asec)] plt.text(focus_z[2],", "as the start of the focus scan if (i ==", "im = fits.getdata(fname, extname=extname) plt.imshow(im, interpolation='nearest', origin='lower', cmap='gray_r', vmin=0.01) plt.text(5,", "basedir='/n/home/datasystems/users/ameisner/reduced/focus', ccds=False): fname = basedir + '/' + night +", "len(expids), len(expids)*j + i + 1) plt.xticks([]) plt.yticks([]) im =", "expids, basedir='/n/home/datasystems/users/ameisner/reduced/focus', outdir='/n/home/desiobserver/focus_scan_pngs', no_popups=False): expids = _actual_expid_list(expids, night, basedir=basedir) if", "numpy as np import os import matplotlib.pyplot as plt import", "+ '/' + night + '/' + str(expid).zfill(8) + '/gfa-'", "= fits.getdata(fname, extname=extname) plt.imshow(im, interpolation='nearest', origin='lower', cmap='gray_r', vmin=0.01) plt.text(5, 44,", "expids = 45446 + np.arange(7) focus_plots(night, expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid', outdir='.') def", "= _actual_expid_list(expids, night, basedir=basedir) if len(expids) == 0: print('NO FOCUS", "+ str(int(float(ccds[0]['FOCUS'].split(',')[2]))), color='r') if np.isfinite(ccds[j]['XCENTROID_PSF']) and np.isfinite(ccds[j]['YCENTROID_PSF']): plt.scatter([ccds[j]['XCENTROID_PSF']], [ccds[j]['YCENTROID_PSF']], marker='.',", "continue program = tab[0]['PROGRAM'].strip() if program != 'focus scan': break", "+ np.arange(16, dtype=int) print(expids) print(args.night[0]) print(args.basedir) outdir = args.outdir if", "+ str(expid_min)) plt.plot(xsamp, ysamp) zmin = -coeff[1]/(2*coeff[0]) min_fwhm_fit_asec = coeff[0]*(zmin**2)", "second exposure as the start of the focus scan if", "_actual_expid_list(expids, night, basedir=basedir) if len(expids) == 0: print('NO FOCUS SCAN", "nargs=1) parser.add_argument('night', type=str, nargs=1) parser.add_argument('--basedir', default='/n/home/datasystems/users/ameisner/reduced/focus', type=str, help='base directory for", "argparse.ArgumentParser(description=descr) parser.add_argument('first_expid', type=int, nargs=1) parser.add_argument('night', type=str, nargs=1) parser.add_argument('--basedir', default='/n/home/datasystems/users/ameisner/reduced/focus', type=str,", "if not os.path.exists(fname): continue tab = fits.getdata(fname) # try to", "default='/n/home/datasystems/users/ameisner/reduced/focus', type=str, help='base directory for GFA reductions') parser.add_argument('--outdir', default='/n/home/desiobserver/focus_scan_pngs', type=str,", "!= 0: fwhm_pix.append(np.median(ccds['PSF_FWHM_PIX'][np.isfinite(ccds['PSF_FWHM_PIX'])])) focus_z.append(float(ccds[0]['FOCUS'].split(',')[2])) hdul = fits.open(fname) extnames_present = [hdu.header['EXTNAME']", "return fname def _actual_expid_list(expids, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus'): keep = [] for", "plt.text(focus_z[2], yrange[0] + 0.7*(yrange[1]-yrange[0]), 'best FWHM (fit) : ' +", "np.sum(np.isfinite(ccds['PSF_FWHM_PIX'])) != 0: fwhm_pix.append(np.median(ccds['PSF_FWHM_PIX'][np.isfinite(ccds['PSF_FWHM_PIX'])])) focus_z.append(float(ccds[0]['FOCUS'].split(',')[2])) hdul = fits.open(fname) extnames_present =", "help='output directory for plot PNGs') parser.add_argument('--no_popups', default=False, action='store_true', help='write PNGs", "night = '20200131' expids = 45446 + np.arange(7) focus_plots(night, expids,", "not os.path.exists(fname): continue ccds = fits.getdata(fname_ccds) if np.sum(np.isfinite(ccds['PSF_FWHM_PIX'])) != 0:", "print(expids) print(args.night[0]) print(args.basedir) outdir = args.outdir if os.path.exists(args.outdir) else '.'", "default=False, action='store_true', help='write PNGs without popping up plot windows') args", "fname = fname.replace('_psfs.fits', '_ccds.fits') return fname def _actual_expid_list(expids, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus'):", "for i, expid in enumerate(expids): fname = _fname(expid, night, basedir=basedir)", "str(expid) + '; ' + extname, color='r', fontsize=9) plt.text(10, 3.5,", "for plot PNGs') parser.add_argument('--no_popups', default=False, action='store_true', help='write PNGs without popping", "= '20200131' expids = 45446 + np.arange(7) focus_plots(night, expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid',", "= [np.min(fwhm_asec), np.max(fwhm_asec)] plt.text(focus_z[2], yrange[0] + 0.8*(yrange[1]-yrange[0]), 'best FWHM (meas)", "plt.text(10, 3.5, 'z = ' + str(int(float(ccds[0]['FOCUS'].split(',')[2]))), color='r') if np.isfinite(ccds[j]['XCENTROID_PSF'])", "as np import os import matplotlib.pyplot as plt import argparse", "parser.add_argument('night', type=str, nargs=1) parser.add_argument('--basedir', default='/n/home/datasystems/users/ameisner/reduced/focus', type=str, help='base directory for GFA", "def _test_missing_cam(): night = '20200131' expids = 45485 + np.arange(7)", "scan': break keep.append(expid) return keep def focus_plots(night, expids, basedir='/n/home/datasystems/users/ameisner/reduced/focus', outdir='/n/home/desiobserver/focus_scan_pngs',", "!= 'focus scan': break keep.append(expid) return keep def focus_plots(night, expids,", "ysamp = coeff[0]*(np.power(xsamp, 2)) + coeff[1]*xsamp + coeff[2] plt.title('focus scan", "basedir=basedir) print(fname) fname_ccds = _fname(expid, night, basedir=basedir, ccds=True) if not", "plt.figure(200) asec_per_pix = 0.205 focus_z = np.array(focus_z) fwhm_asec = np.array(fwhm_pix)*asec_per_pix", "np.arange(np.min(focus_z), np.max(focus_z)) ysamp = coeff[0]*(np.power(xsamp, 2)) + coeff[1]*xsamp + coeff[2]", "args.first_expid + np.arange(16, dtype=int) print(expids) print(args.night[0]) print(args.basedir) outdir = args.outdir", "ccds=True) if not os.path.exists(fname): continue tab = fits.getdata(fname) # try", "basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid') if __name__ == \"__main__\": descr = 'GFA focus sequence", "np.arange(7) focus_plots(night, expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid', outdir='.') def _test_missing_cam(): night = '20200131'", "hdul = fits.open(fname) extnames_present = [hdu.header['EXTNAME'] for hdu in hdul]", "color='r') if np.isfinite(ccds[j]['XCENTROID_PSF']) and np.isfinite(ccds[j]['YCENTROID_PSF']): plt.scatter([ccds[j]['XCENTROID_PSF']], [ccds[j]['YCENTROID_PSF']], marker='.', c='r') expid_min", "not no_popups: plt.show() def _test(): night = '20200131' expids =", "_fname(expid, night, basedir=basedir, ccds=True) if not os.path.exists(fname): continue tab =", "TO ANALYZE ??') assert(False) plt.figure(1, figsize=(12.0*(len(expids)/7.0), 9)) extnames = ['GUIDE0',", "= int(np.min(expids)) print(focus_z) print(fwhm_pix) plt.savefig(os.path.join(outdir, 'stamps_focus_scan-' + str(expid_min).zfill(8)+'.png'), bbox_inches='tight') #plt.cla()", "coeff[1]*zmin + coeff[2] yrange = [np.min(fwhm_asec), np.max(fwhm_asec)] plt.text(focus_z[2], yrange[0] +", "plt.xticks([]) plt.yticks([]) im = fits.getdata(fname, extname=extname) plt.imshow(im, interpolation='nearest', origin='lower', cmap='gray_r',", "str(expid_min).zfill(8)+'.png'), bbox_inches='tight') #plt.cla() plt.figure(200) asec_per_pix = 0.205 focus_z = np.array(focus_z)", "for hdu in hdul] for j, extname in enumerate(extnames): if", "fname_ccds = _fname(expid, night, basedir=basedir, ccds=True) if not os.path.exists(fname): continue", "+ '.png'), bbox_inches='tight') if not no_popups: plt.show() def _test(): night", "type=str, help='output directory for plot PNGs') parser.add_argument('--no_popups', default=False, action='store_true', help='write", "night, basedir='/n/home/datasystems/users/ameisner/reduced/focus'): keep = [] for i, expid in enumerate(expids):", "fname = _fname(expid, night, basedir=basedir) print(fname) fname_ccds = _fname(expid, night,", "= 'GFA focus sequence plots/analysis' parser = argparse.ArgumentParser(description=descr) parser.add_argument('first_expid', type=int,", "np import os import matplotlib.pyplot as plt import argparse def", "program != 'focus scan': break keep.append(expid) return keep def focus_plots(night,", "& (tab[0]['EXPTIME'] < 1.1): print('SKIPPING DUMMY SETUP EXPOSURE') continue program", "plt.scatter(focus_z, fwhm_asec) plt.xlabel('focus z (micron)') plt.ylabel('FWHM (asec)') coeff = np.polyfit(focus_z,", "coeff[0]*(np.power(xsamp, 2)) + coeff[1]*xsamp + coeff[2] plt.title('focus scan starting with", "fname = _fname(expid, night, basedir=basedir, ccds=True) if not os.path.exists(fname): continue", "observer accidentally lists the 'setup focus scan' # 1 second", "focus scan' # 1 second exposure as the start of", "= _fname(expid, night, basedir=basedir, ccds=True) if not os.path.exists(fname): continue ccds", "keep.append(expid) return keep def focus_plots(night, expids, basedir='/n/home/datasystems/users/ameisner/reduced/focus', outdir='/n/home/desiobserver/focus_scan_pngs', no_popups=False): expids", "+ np.arange(7) focus_plots(night, expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid') if __name__ == \"__main__\": descr", "print(i, j) plt.subplot(6, len(expids), len(expids)*j + i + 1) plt.xticks([])", "= '20200131' expids = 45485 + np.arange(7) focus_plots(night, expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid')", "import os import matplotlib.pyplot as plt import argparse def _fname(expid,", "= basedir + '/' + night + '/' + str(expid).zfill(8)", "night, basedir=basedir, ccds=True) if not os.path.exists(fname): continue tab = fits.getdata(fname)", "plt.text(focus_z[2], yrange[0] + 0.8*(yrange[1]-yrange[0]), 'best FWHM (meas) : ' +", "assert(False) plt.figure(1, figsize=(12.0*(len(expids)/7.0), 9)) extnames = ['GUIDE0', 'GUIDE2', 'GUIDE3', 'GUIDE5',", "enumerate(extnames): if extname not in extnames_present: continue print(i, j) plt.subplot(6,", "expids = _actual_expid_list(expids, night, basedir=basedir) if len(expids) == 0: print('NO", "print(fwhm_pix) plt.savefig(os.path.join(outdir, 'stamps_focus_scan-' + str(expid_min).zfill(8)+'.png'), bbox_inches='tight') #plt.cla() plt.figure(200) asec_per_pix =", "+ '{:.2f}'.format(min_fwhm_fit_asec)) plt.text(focus_z[2], yrange[0] + 0.9*(yrange[1]-yrange[0]), 'best focus : '", "dtype=int) print(expids) print(args.night[0]) print(args.basedir) outdir = args.outdir if os.path.exists(args.outdir) else", "j, extname in enumerate(extnames): if extname not in extnames_present: continue", "interpolation='nearest', origin='lower', cmap='gray_r', vmin=0.01) plt.text(5, 44, str(expid) + '; '", "expid in enumerate(expids): fname = _fname(expid, night, basedir=basedir, ccds=True) if", "night + '/' + str(expid).zfill(8) + '/gfa-' + str(expid).zfill(8) +", "ANALYZE ??') assert(False) plt.figure(1, figsize=(12.0*(len(expids)/7.0), 9)) extnames = ['GUIDE0', 'GUIDE2',", "\"__main__\": descr = 'GFA focus sequence plots/analysis' parser = argparse.ArgumentParser(description=descr)", "#!/usr/bin/env python import astropy.io.fits as fits import numpy as np", "+ i + 1) plt.xticks([]) plt.yticks([]) im = fits.getdata(fname, extname=extname)", "plt import argparse def _fname(expid, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus', ccds=False): fname =", "= fits.getdata(fname_ccds) if np.sum(np.isfinite(ccds['PSF_FWHM_PIX'])) != 0: fwhm_pix.append(np.median(ccds['PSF_FWHM_PIX'][np.isfinite(ccds['PSF_FWHM_PIX'])])) focus_z.append(float(ccds[0]['FOCUS'].split(',')[2])) hdul =", "z (micron)') plt.ylabel('FWHM (asec)') coeff = np.polyfit(focus_z, fwhm_asec, 2) xsamp", "start of the focus scan if (i == 0) &", "fwhm_pix.append(np.median(ccds['PSF_FWHM_PIX'][np.isfinite(ccds['PSF_FWHM_PIX'])])) focus_z.append(float(ccds[0]['FOCUS'].split(',')[2])) hdul = fits.open(fname) extnames_present = [hdu.header['EXTNAME'] for hdu", "to handle case where observer accidentally lists the 'setup focus", "= _fname(expid, night, basedir=basedir) print(fname) fname_ccds = _fname(expid, night, basedir=basedir,", "print(fname) fname_ccds = _fname(expid, night, basedir=basedir, ccds=True) if not os.path.exists(fname):", "EXPID = ' + str(expid_min)) plt.plot(xsamp, ysamp) zmin = -coeff[1]/(2*coeff[0])", "extname not in extnames_present: continue print(i, j) plt.subplot(6, len(expids), len(expids)*j", "ccds=False): fname = basedir + '/' + night + '/'", "2)) + coeff[1]*xsamp + coeff[2] plt.title('focus scan starting with EXPID", "enumerate(expids): fname = _fname(expid, night, basedir=basedir) print(fname) fname_ccds = _fname(expid,", "'_psfs.fits' if ccds: fname = fname.replace('_psfs.fits', '_ccds.fits') return fname def", "asec_per_pix = 0.205 focus_z = np.array(focus_z) fwhm_asec = np.array(fwhm_pix)*asec_per_pix plt.scatter(focus_z,", "expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid') if __name__ == \"__main__\": descr = 'GFA focus", "focus sequence plots/analysis' parser = argparse.ArgumentParser(description=descr) parser.add_argument('first_expid', type=int, nargs=1) parser.add_argument('night',", "parser.add_argument('--outdir', default='/n/home/desiobserver/focus_scan_pngs', type=str, help='output directory for plot PNGs') parser.add_argument('--no_popups', default=False,", "'_ccds.fits') return fname def _actual_expid_list(expids, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus'): keep = []", "the 'setup focus scan' # 1 second exposure as the", "= fname.replace('_psfs.fits', '_ccds.fits') return fname def _actual_expid_list(expids, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus'): keep", "__name__ == \"__main__\": descr = 'GFA focus sequence plots/analysis' parser", "plt.savefig(os.path.join(outdir, 'fit_focus_scan-' + str(expid_min).zfill(8) + '.png'), bbox_inches='tight') if not no_popups:", "os import matplotlib.pyplot as plt import argparse def _fname(expid, night,", "plt.figure(1, figsize=(12.0*(len(expids)/7.0), 9)) extnames = ['GUIDE0', 'GUIDE2', 'GUIDE3', 'GUIDE5', 'GUIDE7',", "of the focus scan if (i == 0) & (tab[0]['EXPTIME']", "matplotlib.pyplot as plt import argparse def _fname(expid, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus', ccds=False):", "tab = fits.getdata(fname) # try to handle case where observer", "= 0.205 focus_z = np.array(focus_z) fwhm_asec = np.array(fwhm_pix)*asec_per_pix plt.scatter(focus_z, fwhm_asec)", "night, basedir=basedir) print(fname) fname_ccds = _fname(expid, night, basedir=basedir, ccds=True) if", "+ '/gfa-' + str(expid).zfill(8) + '_psfs.fits' if ccds: fname =", "origin='lower', cmap='gray_r', vmin=0.01) plt.text(5, 44, str(expid) + '; ' +", "parser.parse_args() expids = args.first_expid + np.arange(16, dtype=int) print(expids) print(args.night[0]) print(args.basedir)", "str(expid_min).zfill(8) + '.png'), bbox_inches='tight') if not no_popups: plt.show() def _test():", "focus : ' + str(int(np.round(zmin)))) plt.savefig(os.path.join(outdir, 'fit_focus_scan-' + str(expid_min).zfill(8) +", "zmin = -coeff[1]/(2*coeff[0]) min_fwhm_fit_asec = coeff[0]*(zmin**2) + coeff[1]*zmin + coeff[2]", "basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid', outdir='.') def _test_missing_cam(): night = '20200131' expids = 45485", "= ' + str(int(float(ccds[0]['FOCUS'].split(',')[2]))), color='r') if np.isfinite(ccds[j]['XCENTROID_PSF']) and np.isfinite(ccds[j]['YCENTROID_PSF']): plt.scatter([ccds[j]['XCENTROID_PSF']],", "basedir='/n/home/datasystems/users/ameisner/reduced/focus', outdir='/n/home/desiobserver/focus_scan_pngs', no_popups=False): expids = _actual_expid_list(expids, night, basedir=basedir) if len(expids)", "' + str(expid_min)) plt.plot(xsamp, ysamp) zmin = -coeff[1]/(2*coeff[0]) min_fwhm_fit_asec =", "PNGs') parser.add_argument('--no_popups', default=False, action='store_true', help='write PNGs without popping up plot", "directory for GFA reductions') parser.add_argument('--outdir', default='/n/home/desiobserver/focus_scan_pngs', type=str, help='output directory for", "extnames = ['GUIDE0', 'GUIDE2', 'GUIDE3', 'GUIDE5', 'GUIDE7', 'GUIDE8'] focus_z =", "= [] for i, expid in enumerate(expids): fname = _fname(expid,", "[] fwhm_pix = [] # PSF stamps plot plt.subplots_adjust(hspace=0.01, wspace=0.01)", "continue tab = fits.getdata(fname) # try to handle case where", "np.max(focus_z)) ysamp = coeff[0]*(np.power(xsamp, 2)) + coeff[1]*xsamp + coeff[2] plt.title('focus", "os.path.exists(fname): continue ccds = fits.getdata(fname_ccds) if np.sum(np.isfinite(ccds['PSF_FWHM_PIX'])) != 0: fwhm_pix.append(np.median(ccds['PSF_FWHM_PIX'][np.isfinite(ccds['PSF_FWHM_PIX'])]))", "= parser.parse_args() expids = args.first_expid + np.arange(16, dtype=int) print(expids) print(args.night[0])", "EXPOSURE') continue program = tab[0]['PROGRAM'].strip() if program != 'focus scan':", "def _test(): night = '20200131' expids = 45446 + np.arange(7)", "1.1): print('SKIPPING DUMMY SETUP EXPOSURE') continue program = tab[0]['PROGRAM'].strip() if", "plot PNGs') parser.add_argument('--no_popups', default=False, action='store_true', help='write PNGs without popping up", "np.isfinite(ccds[j]['XCENTROID_PSF']) and np.isfinite(ccds[j]['YCENTROID_PSF']): plt.scatter([ccds[j]['XCENTROID_PSF']], [ccds[j]['YCENTROID_PSF']], marker='.', c='r') expid_min = int(np.min(expids))", "PSF stamps plot plt.subplots_adjust(hspace=0.01, wspace=0.01) for i, expid in enumerate(expids):", "= ' + str(expid_min)) plt.plot(xsamp, ysamp) zmin = -coeff[1]/(2*coeff[0]) min_fwhm_fit_asec", "np.polyfit(focus_z, fwhm_asec, 2) xsamp = np.arange(np.min(focus_z), np.max(focus_z)) ysamp = coeff[0]*(np.power(xsamp,", "(tab[0]['EXPTIME'] < 1.1): print('SKIPPING DUMMY SETUP EXPOSURE') continue program =", "+ '{:.2f}'.format(np.min(fwhm_asec))) plt.text(focus_z[2], yrange[0] + 0.7*(yrange[1]-yrange[0]), 'best FWHM (fit) :", "argparse def _fname(expid, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus', ccds=False): fname = basedir +", "[] for i, expid in enumerate(expids): fname = _fname(expid, night,", "parser = argparse.ArgumentParser(description=descr) parser.add_argument('first_expid', type=int, nargs=1) parser.add_argument('night', type=str, nargs=1) parser.add_argument('--basedir',", "type=str, help='base directory for GFA reductions') parser.add_argument('--outdir', default='/n/home/desiobserver/focus_scan_pngs', type=str, help='output", "= coeff[0]*(np.power(xsamp, 2)) + coeff[1]*xsamp + coeff[2] plt.title('focus scan starting", "= coeff[0]*(zmin**2) + coeff[1]*zmin + coeff[2] yrange = [np.min(fwhm_asec), np.max(fwhm_asec)]", "os.path.exists(fname): continue tab = fits.getdata(fname) # try to handle case", "EXPOSURES TO ANALYZE ??') assert(False) plt.figure(1, figsize=(12.0*(len(expids)/7.0), 9)) extnames =", "[np.min(fwhm_asec), np.max(fwhm_asec)] plt.text(focus_z[2], yrange[0] + 0.8*(yrange[1]-yrange[0]), 'best FWHM (meas) :", "import numpy as np import os import matplotlib.pyplot as plt", "+ '_psfs.fits' if ccds: fname = fname.replace('_psfs.fits', '_ccds.fits') return fname", "<gh_stars>1-10 #!/usr/bin/env python import astropy.io.fits as fits import numpy as", "coeff[2] plt.title('focus scan starting with EXPID = ' + str(expid_min))", "2) xsamp = np.arange(np.min(focus_z), np.max(focus_z)) ysamp = coeff[0]*(np.power(xsamp, 2)) +", "print('NO FOCUS SCAN EXPOSURES TO ANALYZE ??') assert(False) plt.figure(1, figsize=(12.0*(len(expids)/7.0),", "if len(expids) == 0: print('NO FOCUS SCAN EXPOSURES TO ANALYZE", "focus_plots(night, expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid') if __name__ == \"__main__\": descr = 'GFA", "if extname not in extnames_present: continue print(i, j) plt.subplot(6, len(expids),", "descr = 'GFA focus sequence plots/analysis' parser = argparse.ArgumentParser(description=descr) parser.add_argument('first_expid',", "[ccds[j]['YCENTROID_PSF']], marker='.', c='r') expid_min = int(np.min(expids)) print(focus_z) print(fwhm_pix) plt.savefig(os.path.join(outdir, 'stamps_focus_scan-'", "def focus_plots(night, expids, basedir='/n/home/datasystems/users/ameisner/reduced/focus', outdir='/n/home/desiobserver/focus_scan_pngs', no_popups=False): expids = _actual_expid_list(expids, night,", "up plot windows') args = parser.parse_args() expids = args.first_expid +", "0.8*(yrange[1]-yrange[0]), 'best FWHM (meas) : ' + '{:.2f}'.format(np.min(fwhm_asec))) plt.text(focus_z[2], yrange[0]", "scan' # 1 second exposure as the start of the", "coeff[2] yrange = [np.min(fwhm_asec), np.max(fwhm_asec)] plt.text(focus_z[2], yrange[0] + 0.8*(yrange[1]-yrange[0]), 'best", "+ str(expid).zfill(8) + '_psfs.fits' if ccds: fname = fname.replace('_psfs.fits', '_ccds.fits')", "str(expid_min)) plt.plot(xsamp, ysamp) zmin = -coeff[1]/(2*coeff[0]) min_fwhm_fit_asec = coeff[0]*(zmin**2) +", "plots/analysis' parser = argparse.ArgumentParser(description=descr) parser.add_argument('first_expid', type=int, nargs=1) parser.add_argument('night', type=str, nargs=1)", "+ np.arange(7) focus_plots(night, expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid', outdir='.') def _test_missing_cam(): night =", "'z = ' + str(int(float(ccds[0]['FOCUS'].split(',')[2]))), color='r') if np.isfinite(ccds[j]['XCENTROID_PSF']) and np.isfinite(ccds[j]['YCENTROID_PSF']):", "ysamp) zmin = -coeff[1]/(2*coeff[0]) min_fwhm_fit_asec = coeff[0]*(zmin**2) + coeff[1]*zmin +", "coeff[1]*xsamp + coeff[2] plt.title('focus scan starting with EXPID = '", "'focus scan': break keep.append(expid) return keep def focus_plots(night, expids, basedir='/n/home/datasystems/users/ameisner/reduced/focus',", "'20200131' expids = 45446 + np.arange(7) focus_plots(night, expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid', outdir='.')", "expids = args.first_expid + np.arange(16, dtype=int) print(expids) print(args.night[0]) print(args.basedir) outdir", "??') assert(False) plt.figure(1, figsize=(12.0*(len(expids)/7.0), 9)) extnames = ['GUIDE0', 'GUIDE2', 'GUIDE3',", "= fits.getdata(fname) # try to handle case where observer accidentally", "plt.show() def _test(): night = '20200131' expids = 45446 +", "lists the 'setup focus scan' # 1 second exposure as", "basedir + '/' + night + '/' + str(expid).zfill(8) +", "0: print('NO FOCUS SCAN EXPOSURES TO ANALYZE ??') assert(False) plt.figure(1,", "print(args.night[0]) print(args.basedir) outdir = args.outdir if os.path.exists(args.outdir) else '.' focus_plots(args.night[0],", "= [] # PSF stamps plot plt.subplots_adjust(hspace=0.01, wspace=0.01) for i,", "basedir=basedir, ccds=True) if not os.path.exists(fname): continue ccds = fits.getdata(fname_ccds) if", "'best FWHM (meas) : ' + '{:.2f}'.format(np.min(fwhm_asec))) plt.text(focus_z[2], yrange[0] +", "where observer accidentally lists the 'setup focus scan' # 1", "'.png'), bbox_inches='tight') if not no_popups: plt.show() def _test(): night =", "'{:.2f}'.format(np.min(fwhm_asec))) plt.text(focus_z[2], yrange[0] + 0.7*(yrange[1]-yrange[0]), 'best FWHM (fit) : '", ": ' + '{:.2f}'.format(min_fwhm_fit_asec)) plt.text(focus_z[2], yrange[0] + 0.9*(yrange[1]-yrange[0]), 'best focus", "outdir='.') def _test_missing_cam(): night = '20200131' expids = 45485 +", "import argparse def _fname(expid, night, basedir='/n/home/datasystems/users/ameisner/reduced/focus', ccds=False): fname = basedir", "wspace=0.01) for i, expid in enumerate(expids): fname = _fname(expid, night,", "plot plt.subplots_adjust(hspace=0.01, wspace=0.01) for i, expid in enumerate(expids): fname =", "'GUIDE5', 'GUIDE7', 'GUIDE8'] focus_z = [] fwhm_pix = [] #", "9)) extnames = ['GUIDE0', 'GUIDE2', 'GUIDE3', 'GUIDE5', 'GUIDE7', 'GUIDE8'] focus_z", "'{:.2f}'.format(min_fwhm_fit_asec)) plt.text(focus_z[2], yrange[0] + 0.9*(yrange[1]-yrange[0]), 'best focus : ' +", "np.max(fwhm_asec)] plt.text(focus_z[2], yrange[0] + 0.8*(yrange[1]-yrange[0]), 'best FWHM (meas) : '", "_test(): night = '20200131' expids = 45446 + np.arange(7) focus_plots(night,", "in extnames_present: continue print(i, j) plt.subplot(6, len(expids), len(expids)*j + i", "yrange[0] + 0.7*(yrange[1]-yrange[0]), 'best FWHM (fit) : ' + '{:.2f}'.format(min_fwhm_fit_asec))", "coeff = np.polyfit(focus_z, fwhm_asec, 2) xsamp = np.arange(np.min(focus_z), np.max(focus_z)) ysamp", "yrange = [np.min(fwhm_asec), np.max(fwhm_asec)] plt.text(focus_z[2], yrange[0] + 0.8*(yrange[1]-yrange[0]), 'best FWHM", "len(expids) == 0: print('NO FOCUS SCAN EXPOSURES TO ANALYZE ??')", "= -coeff[1]/(2*coeff[0]) min_fwhm_fit_asec = coeff[0]*(zmin**2) + coeff[1]*zmin + coeff[2] yrange", "extname, color='r', fontsize=9) plt.text(10, 3.5, 'z = ' + str(int(float(ccds[0]['FOCUS'].split(',')[2]))),", "ccds=True) if not os.path.exists(fname): continue ccds = fits.getdata(fname_ccds) if np.sum(np.isfinite(ccds['PSF_FWHM_PIX']))", "extname in enumerate(extnames): if extname not in extnames_present: continue print(i,", "if program != 'focus scan': break keep.append(expid) return keep def", "SCAN EXPOSURES TO ANALYZE ??') assert(False) plt.figure(1, figsize=(12.0*(len(expids)/7.0), 9)) extnames", "color='r', fontsize=9) plt.text(10, 3.5, 'z = ' + str(int(float(ccds[0]['FOCUS'].split(',')[2]))), color='r')", "fwhm_asec) plt.xlabel('focus z (micron)') plt.ylabel('FWHM (asec)') coeff = np.polyfit(focus_z, fwhm_asec,", "int(np.min(expids)) print(focus_z) print(fwhm_pix) plt.savefig(os.path.join(outdir, 'stamps_focus_scan-' + str(expid_min).zfill(8)+'.png'), bbox_inches='tight') #plt.cla() plt.figure(200)", "== \"__main__\": descr = 'GFA focus sequence plots/analysis' parser =", "3.5, 'z = ' + str(int(float(ccds[0]['FOCUS'].split(',')[2]))), color='r') if np.isfinite(ccds[j]['XCENTROID_PSF']) and", "expids = 45485 + np.arange(7) focus_plots(night, expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid') if __name__", "= argparse.ArgumentParser(description=descr) parser.add_argument('first_expid', type=int, nargs=1) parser.add_argument('night', type=str, nargs=1) parser.add_argument('--basedir', default='/n/home/datasystems/users/ameisner/reduced/focus',", "fontsize=9) plt.text(10, 3.5, 'z = ' + str(int(float(ccds[0]['FOCUS'].split(',')[2]))), color='r') if", "= np.array(fwhm_pix)*asec_per_pix plt.scatter(focus_z, fwhm_asec) plt.xlabel('focus z (micron)') plt.ylabel('FWHM (asec)') coeff", "FWHM (fit) : ' + '{:.2f}'.format(min_fwhm_fit_asec)) plt.text(focus_z[2], yrange[0] + 0.9*(yrange[1]-yrange[0]),", "+ 1) plt.xticks([]) plt.yticks([]) im = fits.getdata(fname, extname=extname) plt.imshow(im, interpolation='nearest',", "plt.subplots_adjust(hspace=0.01, wspace=0.01) for i, expid in enumerate(expids): fname = _fname(expid,", "if ccds: fname = fname.replace('_psfs.fits', '_ccds.fits') return fname def _actual_expid_list(expids,", "return keep def focus_plots(night, expids, basedir='/n/home/datasystems/users/ameisner/reduced/focus', outdir='/n/home/desiobserver/focus_scan_pngs', no_popups=False): expids =", "in enumerate(extnames): if extname not in extnames_present: continue print(i, j)", ": ' + '{:.2f}'.format(np.min(fwhm_asec))) plt.text(focus_z[2], yrange[0] + 0.7*(yrange[1]-yrange[0]), 'best FWHM", "reductions') parser.add_argument('--outdir', default='/n/home/desiobserver/focus_scan_pngs', type=str, help='output directory for plot PNGs') parser.add_argument('--no_popups',", "for j, extname in enumerate(extnames): if extname not in extnames_present:", "figsize=(12.0*(len(expids)/7.0), 9)) extnames = ['GUIDE0', 'GUIDE2', 'GUIDE3', 'GUIDE5', 'GUIDE7', 'GUIDE8']", "+ extname, color='r', fontsize=9) plt.text(10, 3.5, 'z = ' +", "= np.array(focus_z) fwhm_asec = np.array(fwhm_pix)*asec_per_pix plt.scatter(focus_z, fwhm_asec) plt.xlabel('focus z (micron)')", "0) & (tab[0]['EXPTIME'] < 1.1): print('SKIPPING DUMMY SETUP EXPOSURE') continue", "plt.savefig(os.path.join(outdir, 'stamps_focus_scan-' + str(expid_min).zfill(8)+'.png'), bbox_inches='tight') #plt.cla() plt.figure(200) asec_per_pix = 0.205", "the focus scan if (i == 0) & (tab[0]['EXPTIME'] <", "scan starting with EXPID = ' + str(expid_min)) plt.plot(xsamp, ysamp)", "print('SKIPPING DUMMY SETUP EXPOSURE') continue program = tab[0]['PROGRAM'].strip() if program", "python import astropy.io.fits as fits import numpy as np import", "parser.add_argument('--basedir', default='/n/home/datasystems/users/ameisner/reduced/focus', type=str, help='base directory for GFA reductions') parser.add_argument('--outdir', default='/n/home/desiobserver/focus_scan_pngs',", "['GUIDE0', 'GUIDE2', 'GUIDE3', 'GUIDE5', 'GUIDE7', 'GUIDE8'] focus_z = [] fwhm_pix", "focus_z = [] fwhm_pix = [] # PSF stamps plot", "(asec)') coeff = np.polyfit(focus_z, fwhm_asec, 2) xsamp = np.arange(np.min(focus_z), np.max(focus_z))", "= np.polyfit(focus_z, fwhm_asec, 2) xsamp = np.arange(np.min(focus_z), np.max(focus_z)) ysamp =", "i + 1) plt.xticks([]) plt.yticks([]) im = fits.getdata(fname, extname=extname) plt.imshow(im,", "try to handle case where observer accidentally lists the 'setup", ": ' + str(int(np.round(zmin)))) plt.savefig(os.path.join(outdir, 'fit_focus_scan-' + str(expid_min).zfill(8) + '.png'),", "(micron)') plt.ylabel('FWHM (asec)') coeff = np.polyfit(focus_z, fwhm_asec, 2) xsamp =", "(fit) : ' + '{:.2f}'.format(min_fwhm_fit_asec)) plt.text(focus_z[2], yrange[0] + 0.9*(yrange[1]-yrange[0]), 'best", "+ str(expid_min).zfill(8)+'.png'), bbox_inches='tight') #plt.cla() plt.figure(200) asec_per_pix = 0.205 focus_z =", "if np.sum(np.isfinite(ccds['PSF_FWHM_PIX'])) != 0: fwhm_pix.append(np.median(ccds['PSF_FWHM_PIX'][np.isfinite(ccds['PSF_FWHM_PIX'])])) focus_z.append(float(ccds[0]['FOCUS'].split(',')[2])) hdul = fits.open(fname) extnames_present", "45485 + np.arange(7) focus_plots(night, expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid') if __name__ == \"__main__\":", "j) plt.subplot(6, len(expids), len(expids)*j + i + 1) plt.xticks([]) plt.yticks([])", "+ coeff[1]*zmin + coeff[2] yrange = [np.min(fwhm_asec), np.max(fwhm_asec)] plt.text(focus_z[2], yrange[0]", "+ night + '/' + str(expid).zfill(8) + '/gfa-' + str(expid).zfill(8)", "without popping up plot windows') args = parser.parse_args() expids =", "if not os.path.exists(fname): continue ccds = fits.getdata(fname_ccds) if np.sum(np.isfinite(ccds['PSF_FWHM_PIX'])) !=", "len(expids)*j + i + 1) plt.xticks([]) plt.yticks([]) im = fits.getdata(fname,", "= args.outdir if os.path.exists(args.outdir) else '.' focus_plots(args.night[0], expids, basedir=args.basedir, outdir=outdir,", "ccds = fits.getdata(fname_ccds) if np.sum(np.isfinite(ccds['PSF_FWHM_PIX'])) != 0: fwhm_pix.append(np.median(ccds['PSF_FWHM_PIX'][np.isfinite(ccds['PSF_FWHM_PIX'])])) focus_z.append(float(ccds[0]['FOCUS'].split(',')[2])) hdul", "'/' + night + '/' + str(expid).zfill(8) + '/gfa-' +", "str(expid).zfill(8) + '/gfa-' + str(expid).zfill(8) + '_psfs.fits' if ccds: fname", "plt.imshow(im, interpolation='nearest', origin='lower', cmap='gray_r', vmin=0.01) plt.text(5, 44, str(expid) + ';", "popping up plot windows') args = parser.parse_args() expids = args.first_expid", "help='write PNGs without popping up plot windows') args = parser.parse_args()", "str(int(float(ccds[0]['FOCUS'].split(',')[2]))), color='r') if np.isfinite(ccds[j]['XCENTROID_PSF']) and np.isfinite(ccds[j]['YCENTROID_PSF']): plt.scatter([ccds[j]['XCENTROID_PSF']], [ccds[j]['YCENTROID_PSF']], marker='.', c='r')", "if not no_popups: plt.show() def _test(): night = '20200131' expids", "# PSF stamps plot plt.subplots_adjust(hspace=0.01, wspace=0.01) for i, expid in", "= np.arange(np.min(focus_z), np.max(focus_z)) ysamp = coeff[0]*(np.power(xsamp, 2)) + coeff[1]*xsamp +", "= 45446 + np.arange(7) focus_plots(night, expids, basedir='/project/projectdirs/desi/users/ameisner/GFA/run/psf_flux_weighted_centroid', outdir='.') def _test_missing_cam():", "nargs=1) parser.add_argument('--basedir', default='/n/home/datasystems/users/ameisner/reduced/focus', type=str, help='base directory for GFA reductions') parser.add_argument('--outdir'," ]
[ "references(self) -> List[Reference]: return [ Reference(\"Classical and Nonclassical Logics\", [(\"Eric\",", "import Reference from ddq.topics.topic import Topic class Logic(Topic): def references(self)", "List from ddq.taxonomy.reference import Reference from ddq.topics.topic import Topic class", "ddq.topics.topic import Topic class Logic(Topic): def references(self) -> List[Reference]: return", "-> List[Reference]: return [ Reference(\"Classical and Nonclassical Logics\", [(\"Eric\", \"Schechter\")])", "import List from ddq.taxonomy.reference import Reference from ddq.topics.topic import Topic", "def references(self) -> List[Reference]: return [ Reference(\"Classical and Nonclassical Logics\",", "Logic(Topic): def references(self) -> List[Reference]: return [ Reference(\"Classical and Nonclassical", "List[Reference]: return [ Reference(\"Classical and Nonclassical Logics\", [(\"Eric\", \"Schechter\")]) ]", "Topic class Logic(Topic): def references(self) -> List[Reference]: return [ Reference(\"Classical", "import Topic class Logic(Topic): def references(self) -> List[Reference]: return [", "class Logic(Topic): def references(self) -> List[Reference]: return [ Reference(\"Classical and", "ddq.taxonomy.reference import Reference from ddq.topics.topic import Topic class Logic(Topic): def", "Reference from ddq.topics.topic import Topic class Logic(Topic): def references(self) ->", "typing import List from ddq.taxonomy.reference import Reference from ddq.topics.topic import", "from ddq.taxonomy.reference import Reference from ddq.topics.topic import Topic class Logic(Topic):", "from typing import List from ddq.taxonomy.reference import Reference from ddq.topics.topic", "from ddq.topics.topic import Topic class Logic(Topic): def references(self) -> List[Reference]:" ]
[ "self._single_log_map = set() def __del__(self): if getattr(self, \"summary_writer\", None) is", "Add handler to file channel = logging.FileHandler(filename=self.log_filename, mode=\"a\") channel.setFormatter(formatter) self.logger.addHandler(channel)", "= set() def __del__(self): if getattr(self, \"summary_writer\", None) is not", "None) if arg_log_dir: self.log_folder = arg_log_dir if not os.path.exists(self.log_folder): os.makedirs(self.log_folder)", "return for name, param in model.named_parameters(): np_param = param.clone().cpu().data.numpy() self.summary_writer.add_histogram(name,", "self.summary_writer = SummaryWriter(tensorboard_folder) self.log_filename = os.path.join(self.log_folder, self.log_filename) print(\"Logging to:\", self.log_filename)", "# Add handler to file channel = logging.FileHandler(filename=self.log_filename, mode=\"a\") channel.setFormatter(formatter)", "tensorboardX import SummaryWriter from pythia.utils.distributed_utils import is_main_process from pythia.utils.general import", "self.logger.addHandler(channel) warnings_logger.addHandler(channel) should_not_log = self.config[\"training_parameters\"][\"should_not_log\"] self.should_log = not should_not_log #", "channel.setFormatter(formatter) self.logger.addHandler(channel) self._file_only_logger.addHandler(channel) warnings_logger.addHandler(channel) # Add handler to stdout channel", "self.log_filename = ckpt_name_from_core_args(config) + \"_\" self.log_filename += self.timer.get_time_hhmmss(None, format=time_format) self.log_filename", "else: getattr(self.logger, level)(str(x)) else: self.logger.error(\"Unknown log level type: %s\" %", "affiliates. import base64 import logging import os import sys from", "= os.path.join(self.log_folder, self.log_filename) print(\"Logging to:\", self.log_filename) logging.captureWarnings(True) self.logger = logging.getLogger(__name__)", "self._file_only_logger.addHandler(channel) warnings_logger.addHandler(channel) # Add handler to stdout channel = logging.StreamHandler(sys.stdout)", "self.should_log = not should_not_log # Single log wrapper map self._single_log_map", "time_format = \"%Y-%m-%dT%H:%M:%S\" self.log_filename = ckpt_name_from_core_args(config) + \"_\" self.log_filename +=", "import sys from tensorboardX import SummaryWriter from pythia.utils.distributed_utils import is_main_process", "pythia.utils.timer import Timer class Logger: def __init__(self, config): self.logger =", "import base64 import logging import os import sys from tensorboardX", "level)(str(x)) else: self.logger.error(\"Unknown log level type: %s\" % level) else:", "self.write(x, level) def add_scalar(self, key, value, iteration): if self.summary_writer is", "None: return for name, param in model.named_parameters(): np_param = param.clone().cpu().data.numpy()", "import SummaryWriter from pythia.utils.distributed_utils import is_main_process from pythia.utils.general import (ckpt_name_from_core_args,", "logging.getLogger(__name__) warnings_logger = logging.getLogger(\"py.warnings\") # Set level level = config[\"training_parameters\"].get(\"logger_level\",", "for name, param in model.named_parameters(): np_param = param.clone().cpu().data.numpy() self.summary_writer.add_histogram(name, np_param,", "logging.getLogger(__name__) self._file_only_logger = logging.getLogger(__name__) warnings_logger = logging.getLogger(\"py.warnings\") # Set level", "if donot_print: getattr(self._file_only_logger, level)(str(x)) else: getattr(self.logger, level)(str(x)) else: self.logger.error(\"Unknown log", "warnings_logger = logging.getLogger(\"py.warnings\") # Set level level = config[\"training_parameters\"].get(\"logger_level\", \"info\")", "else: self.logger.error(\"Unknown log level type: %s\" % level) else: print(str(x)", "from pythia.utils.distributed_utils import is_main_process from pythia.utils.general import (ckpt_name_from_core_args, foldername_from_config_override) from", "+ \"\\n\") def single_write(self, x, level=\"info\"): if x + \"_\"", "None: self.summary_writer.close() def write(self, x, level=\"info\", donot_print=False): if self.logger is", "scalar_dict, iteration): if self.summary_writer is None: return for key, val", "Timer() self.config = config self.save_dir = config.training_parameters.save_dir self.log_folder = ckpt_name_from_core_args(config)", "if getattr(self, \"summary_writer\", None) is not None: self.summary_writer.close() def write(self,", "from pythia.utils.general import (ckpt_name_from_core_args, foldername_from_config_override) from pythia.utils.timer import Timer class", "config.training_parameters.save_dir self.log_folder = ckpt_name_from_core_args(config) self.log_folder += foldername_from_config_override(config) time_format = \"%Y-%m-%dT%H:%M:%S\"", "file channel = logging.FileHandler(filename=self.log_filename, mode=\"a\") channel.setFormatter(formatter) self.logger.addHandler(channel) self._file_only_logger.addHandler(channel) warnings_logger.addHandler(channel) #", "self._single_log_map: return else: self.write(x, level) def add_scalar(self, key, value, iteration):", "it should not log then just print it if self.should_log:", "log wrapper map self._single_log_map = set() def __del__(self): if getattr(self,", "map self._single_log_map = set() def __del__(self): if getattr(self, \"summary_writer\", None)", "logging import os import sys from tensorboardX import SummaryWriter from", "= config[\"training_parameters\"].get(\"logger_level\", \"info\") self.logger.setLevel(getattr(logging, level.upper())) self._file_only_logger.setLevel(getattr(logging, level.upper())) formatter = logging.Formatter(", "stdout channel = logging.StreamHandler(sys.stdout) channel.setFormatter(formatter) self.logger.addHandler(channel) warnings_logger.addHandler(channel) should_not_log = self.config[\"training_parameters\"][\"should_not_log\"]", "import is_main_process from pythia.utils.general import (ckpt_name_from_core_args, foldername_from_config_override) from pythia.utils.timer import", "self._file_only_logger = logging.getLogger(__name__) warnings_logger = logging.getLogger(\"py.warnings\") # Set level level", "(ckpt_name_from_core_args, foldername_from_config_override) from pythia.utils.timer import Timer class Logger: def __init__(self,", "to stdout channel = logging.StreamHandler(sys.stdout) channel.setFormatter(formatter) self.logger.addHandler(channel) warnings_logger.addHandler(channel) should_not_log =", "config self.save_dir = config.training_parameters.save_dir self.log_folder = ckpt_name_from_core_args(config) self.log_folder += foldername_from_config_override(config)", "to file channel = logging.FileHandler(filename=self.log_filename, mode=\"a\") channel.setFormatter(formatter) self.logger.addHandler(channel) self._file_only_logger.addHandler(channel) warnings_logger.addHandler(channel)", "is_main_process from pythia.utils.general import (ckpt_name_from_core_args, foldername_from_config_override) from pythia.utils.timer import Timer", "return self.timer = Timer() self.config = config self.save_dir = config.training_parameters.save_dir", "arg_log_dir if not os.path.exists(self.log_folder): os.makedirs(self.log_folder) tensorboard_folder = os.path.join(self.log_folder, \"tensorboard\") self.summary_writer", "# if it should not log then just print it", "scalar_dict.items(): self.summary_writer.add_scalar(key, val, iteration) def add_histogram_for_model(self, model, iteration): if self.summary_writer", "iteration) def add_scalars(self, scalar_dict, iteration): if self.summary_writer is None: return", "level = config[\"training_parameters\"].get(\"logger_level\", \"info\") self.logger.setLevel(getattr(logging, level.upper())) self._file_only_logger.setLevel(getattr(logging, level.upper())) formatter =", "= self.config.get(\"log_dir\", None) if arg_log_dir: self.log_folder = arg_log_dir if not", "formatter = logging.Formatter( \"%(asctime)s %(levelname)s: %(message)s\", datefmt=\"%Y-%m-%dT%H:%M:%S\" ) # Add", "%(levelname)s: %(message)s\", datefmt=\"%Y-%m-%dT%H:%M:%S\" ) # Add handler to file channel", "Facebook, Inc. and its affiliates. import base64 import logging import", "= config self.save_dir = config.training_parameters.save_dir self.log_folder = ckpt_name_from_core_args(config) self.log_folder +=", "x, level=\"info\"): if x + \"_\" + level in self._single_log_map:", "\"\\n\") def single_write(self, x, level=\"info\"): if x + \"_\" +", "pythia.utils.general import (ckpt_name_from_core_args, foldername_from_config_override) from pythia.utils.timer import Timer class Logger:", "if self.summary_writer is None: return self.summary_writer.add_scalar(key, value, iteration) def add_scalars(self,", "log then just print it if self.should_log: if hasattr(self.logger, level):", "self.log_filename += self.timer.get_time_hhmmss(None, format=time_format) self.log_filename += \".log\" self.log_folder = os.path.join(self.save_dir,", "if self.should_log: if hasattr(self.logger, level): if donot_print: getattr(self._file_only_logger, level)(str(x)) else:", "self.summary_writer.add_scalar(key, value, iteration) def add_scalars(self, scalar_dict, iteration): if self.summary_writer is", "\".log\" self.log_folder = os.path.join(self.save_dir, self.log_folder, \"logs\") arg_log_dir = self.config.get(\"log_dir\", None)", "iteration): if self.summary_writer is None: return for name, param in", "import Timer class Logger: def __init__(self, config): self.logger = None", "self.logger.addHandler(channel) self._file_only_logger.addHandler(channel) warnings_logger.addHandler(channel) # Add handler to stdout channel =", "warnings_logger.addHandler(channel) # Add handler to stdout channel = logging.StreamHandler(sys.stdout) channel.setFormatter(formatter)", "% level) else: print(str(x) + \"\\n\") def single_write(self, x, level=\"info\"):", "def write(self, x, level=\"info\", donot_print=False): if self.logger is None: return", "self.log_folder = ckpt_name_from_core_args(config) self.log_folder += foldername_from_config_override(config) time_format = \"%Y-%m-%dT%H:%M:%S\" self.log_filename", "self.summary_writer is None: return self.summary_writer.add_scalar(key, value, iteration) def add_scalars(self, scalar_dict,", ") # Add handler to file channel = logging.FileHandler(filename=self.log_filename, mode=\"a\")", "Add handler to stdout channel = logging.StreamHandler(sys.stdout) channel.setFormatter(formatter) self.logger.addHandler(channel) warnings_logger.addHandler(channel)", "config): self.logger = None self.summary_writer = None if not is_main_process():", "= None if not is_main_process(): return self.timer = Timer() self.config", "= SummaryWriter(tensorboard_folder) self.log_filename = os.path.join(self.log_folder, self.log_filename) print(\"Logging to:\", self.log_filename) logging.captureWarnings(True)", "os.makedirs(self.log_folder) tensorboard_folder = os.path.join(self.log_folder, \"tensorboard\") self.summary_writer = SummaryWriter(tensorboard_folder) self.log_filename =", "if self.summary_writer is None: return for name, param in model.named_parameters():", "__del__(self): if getattr(self, \"summary_writer\", None) is not None: self.summary_writer.close() def", "\"tensorboard\") self.summary_writer = SummaryWriter(tensorboard_folder) self.log_filename = os.path.join(self.log_folder, self.log_filename) print(\"Logging to:\",", "None: return for key, val in scalar_dict.items(): self.summary_writer.add_scalar(key, val, iteration)", "self.summary_writer is None: return for name, param in model.named_parameters(): np_param", "= config.training_parameters.save_dir self.log_folder = ckpt_name_from_core_args(config) self.log_folder += foldername_from_config_override(config) time_format =", "os.path.join(self.log_folder, \"tensorboard\") self.summary_writer = SummaryWriter(tensorboard_folder) self.log_filename = os.path.join(self.log_folder, self.log_filename) print(\"Logging", "donot_print: getattr(self._file_only_logger, level)(str(x)) else: getattr(self.logger, level)(str(x)) else: self.logger.error(\"Unknown log level", "value, iteration): if self.summary_writer is None: return self.summary_writer.add_scalar(key, value, iteration)", "if self.summary_writer is None: return for key, val in scalar_dict.items():", "self.log_filename = os.path.join(self.log_folder, self.log_filename) print(\"Logging to:\", self.log_filename) logging.captureWarnings(True) self.logger =", "for key, val in scalar_dict.items(): self.summary_writer.add_scalar(key, val, iteration) def add_histogram_for_model(self,", "key, val in scalar_dict.items(): self.summary_writer.add_scalar(key, val, iteration) def add_histogram_for_model(self, model,", "import os import sys from tensorboardX import SummaryWriter from pythia.utils.distributed_utils", "not os.path.exists(self.log_folder): os.makedirs(self.log_folder) tensorboard_folder = os.path.join(self.log_folder, \"tensorboard\") self.summary_writer = SummaryWriter(tensorboard_folder)", "logging.FileHandler(filename=self.log_filename, mode=\"a\") channel.setFormatter(formatter) self.logger.addHandler(channel) self._file_only_logger.addHandler(channel) warnings_logger.addHandler(channel) # Add handler to", "x, level=\"info\", donot_print=False): if self.logger is None: return # if", "+ \"_\" self.log_filename += self.timer.get_time_hhmmss(None, format=time_format) self.log_filename += \".log\" self.log_folder", "None: return # if it should not log then just", "def single_write(self, x, level=\"info\"): if x + \"_\" + level", "+ \"_\" + level in self._single_log_map: return else: self.write(x, level)", "level in self._single_log_map: return else: self.write(x, level) def add_scalar(self, key,", "add_scalars(self, scalar_dict, iteration): if self.summary_writer is None: return for key,", "not is_main_process(): return self.timer = Timer() self.config = config self.save_dir", "from tensorboardX import SummaryWriter from pythia.utils.distributed_utils import is_main_process from pythia.utils.general", "\"logs\") arg_log_dir = self.config.get(\"log_dir\", None) if arg_log_dir: self.log_folder = arg_log_dir", "logging.getLogger(\"py.warnings\") # Set level level = config[\"training_parameters\"].get(\"logger_level\", \"info\") self.logger.setLevel(getattr(logging, level.upper()))", "os import sys from tensorboardX import SummaryWriter from pythia.utils.distributed_utils import", "self.log_filename) print(\"Logging to:\", self.log_filename) logging.captureWarnings(True) self.logger = logging.getLogger(__name__) self._file_only_logger =", "single_write(self, x, level=\"info\"): if x + \"_\" + level in", "\"info\") self.logger.setLevel(getattr(logging, level.upper())) self._file_only_logger.setLevel(getattr(logging, level.upper())) formatter = logging.Formatter( \"%(asctime)s %(levelname)s:", "print(str(x) + \"\\n\") def single_write(self, x, level=\"info\"): if x +", "logging.Formatter( \"%(asctime)s %(levelname)s: %(message)s\", datefmt=\"%Y-%m-%dT%H:%M:%S\" ) # Add handler to", "set() def __del__(self): if getattr(self, \"summary_writer\", None) is not None:", "= ckpt_name_from_core_args(config) + \"_\" self.log_filename += self.timer.get_time_hhmmss(None, format=time_format) self.log_filename +=", "self._file_only_logger.setLevel(getattr(logging, level.upper())) formatter = logging.Formatter( \"%(asctime)s %(levelname)s: %(message)s\", datefmt=\"%Y-%m-%dT%H:%M:%S\" )", "None self.summary_writer = None if not is_main_process(): return self.timer =", "Single log wrapper map self._single_log_map = set() def __del__(self): if", "+= foldername_from_config_override(config) time_format = \"%Y-%m-%dT%H:%M:%S\" self.log_filename = ckpt_name_from_core_args(config) + \"_\"", "just print it if self.should_log: if hasattr(self.logger, level): if donot_print:", "getattr(self._file_only_logger, level)(str(x)) else: getattr(self.logger, level)(str(x)) else: self.logger.error(\"Unknown log level type:", "val in scalar_dict.items(): self.summary_writer.add_scalar(key, val, iteration) def add_histogram_for_model(self, model, iteration):", "import logging import os import sys from tensorboardX import SummaryWriter", "format=time_format) self.log_filename += \".log\" self.log_folder = os.path.join(self.save_dir, self.log_folder, \"logs\") arg_log_dir", "return # if it should not log then just print", "Inc. and its affiliates. import base64 import logging import os", "base64 import logging import os import sys from tensorboardX import", "should_not_log = self.config[\"training_parameters\"][\"should_not_log\"] self.should_log = not should_not_log # Single log", "None: return self.summary_writer.add_scalar(key, value, iteration) def add_scalars(self, scalar_dict, iteration): if", "def add_histogram_for_model(self, model, iteration): if self.summary_writer is None: return for", "= self.config[\"training_parameters\"][\"should_not_log\"] self.should_log = not should_not_log # Single log wrapper", "else: print(str(x) + \"\\n\") def single_write(self, x, level=\"info\"): if x", "value, iteration) def add_scalars(self, scalar_dict, iteration): if self.summary_writer is None:", "level level = config[\"training_parameters\"].get(\"logger_level\", \"info\") self.logger.setLevel(getattr(logging, level.upper())) self._file_only_logger.setLevel(getattr(logging, level.upper())) formatter", "\"summary_writer\", None) is not None: self.summary_writer.close() def write(self, x, level=\"info\",", "iteration): if self.summary_writer is None: return for key, val in", "channel.setFormatter(formatter) self.logger.addHandler(channel) warnings_logger.addHandler(channel) should_not_log = self.config[\"training_parameters\"][\"should_not_log\"] self.should_log = not should_not_log", "is None: return for name, param in model.named_parameters(): np_param =", "def __init__(self, config): self.logger = None self.summary_writer = None if", "key, value, iteration): if self.summary_writer is None: return self.summary_writer.add_scalar(key, value,", "class Logger: def __init__(self, config): self.logger = None self.summary_writer =", "= os.path.join(self.log_folder, \"tensorboard\") self.summary_writer = SummaryWriter(tensorboard_folder) self.log_filename = os.path.join(self.log_folder, self.log_filename)", "self.config[\"training_parameters\"][\"should_not_log\"] self.should_log = not should_not_log # Single log wrapper map", "print(\"Logging to:\", self.log_filename) logging.captureWarnings(True) self.logger = logging.getLogger(__name__) self._file_only_logger = logging.getLogger(__name__)", "self.summary_writer is None: return for key, val in scalar_dict.items(): self.summary_writer.add_scalar(key,", "= ckpt_name_from_core_args(config) self.log_folder += foldername_from_config_override(config) time_format = \"%Y-%m-%dT%H:%M:%S\" self.log_filename =", "self.log_folder += foldername_from_config_override(config) time_format = \"%Y-%m-%dT%H:%M:%S\" self.log_filename = ckpt_name_from_core_args(config) +", "hasattr(self.logger, level): if donot_print: getattr(self._file_only_logger, level)(str(x)) else: getattr(self.logger, level)(str(x)) else:", "arg_log_dir: self.log_folder = arg_log_dir if not os.path.exists(self.log_folder): os.makedirs(self.log_folder) tensorboard_folder =", "\"_\" self.log_filename += self.timer.get_time_hhmmss(None, format=time_format) self.log_filename += \".log\" self.log_folder =", "\"%(asctime)s %(levelname)s: %(message)s\", datefmt=\"%Y-%m-%dT%H:%M:%S\" ) # Add handler to file", "# Set level level = config[\"training_parameters\"].get(\"logger_level\", \"info\") self.logger.setLevel(getattr(logging, level.upper())) self._file_only_logger.setLevel(getattr(logging,", "self.should_log: if hasattr(self.logger, level): if donot_print: getattr(self._file_only_logger, level)(str(x)) else: getattr(self.logger,", "self.logger.error(\"Unknown log level type: %s\" % level) else: print(str(x) +", "and its affiliates. import base64 import logging import os import", "= os.path.join(self.save_dir, self.log_folder, \"logs\") arg_log_dir = self.config.get(\"log_dir\", None) if arg_log_dir:", "def __del__(self): if getattr(self, \"summary_writer\", None) is not None: self.summary_writer.close()", "= logging.StreamHandler(sys.stdout) channel.setFormatter(formatter) self.logger.addHandler(channel) warnings_logger.addHandler(channel) should_not_log = self.config[\"training_parameters\"][\"should_not_log\"] self.should_log =", "+= \".log\" self.log_folder = os.path.join(self.save_dir, self.log_folder, \"logs\") arg_log_dir = self.config.get(\"log_dir\",", "%(message)s\", datefmt=\"%Y-%m-%dT%H:%M:%S\" ) # Add handler to file channel =", "write(self, x, level=\"info\", donot_print=False): if self.logger is None: return #", "def add_scalar(self, key, value, iteration): if self.summary_writer is None: return", "is None: return for key, val in scalar_dict.items(): self.summary_writer.add_scalar(key, val,", "if arg_log_dir: self.log_folder = arg_log_dir if not os.path.exists(self.log_folder): os.makedirs(self.log_folder) tensorboard_folder", "to:\", self.log_filename) logging.captureWarnings(True) self.logger = logging.getLogger(__name__) self._file_only_logger = logging.getLogger(__name__) warnings_logger", "Copyright (c) Facebook, Inc. and its affiliates. import base64 import", "print it if self.should_log: if hasattr(self.logger, level): if donot_print: getattr(self._file_only_logger,", "self.log_folder, \"logs\") arg_log_dir = self.config.get(\"log_dir\", None) if arg_log_dir: self.log_folder =", "self.save_dir = config.training_parameters.save_dir self.log_folder = ckpt_name_from_core_args(config) self.log_folder += foldername_from_config_override(config) time_format", "warnings_logger.addHandler(channel) should_not_log = self.config[\"training_parameters\"][\"should_not_log\"] self.should_log = not should_not_log # Single", "None) is not None: self.summary_writer.close() def write(self, x, level=\"info\", donot_print=False):", "model, iteration): if self.summary_writer is None: return for name, param", "logging.StreamHandler(sys.stdout) channel.setFormatter(formatter) self.logger.addHandler(channel) warnings_logger.addHandler(channel) should_not_log = self.config[\"training_parameters\"][\"should_not_log\"] self.should_log = not", "is not None: self.summary_writer.close() def write(self, x, level=\"info\", donot_print=False): if", "return self.summary_writer.add_scalar(key, value, iteration) def add_scalars(self, scalar_dict, iteration): if self.summary_writer", "= logging.getLogger(__name__) warnings_logger = logging.getLogger(\"py.warnings\") # Set level level =", "ckpt_name_from_core_args(config) self.log_folder += foldername_from_config_override(config) time_format = \"%Y-%m-%dT%H:%M:%S\" self.log_filename = ckpt_name_from_core_args(config)", "self.log_folder = os.path.join(self.save_dir, self.log_folder, \"logs\") arg_log_dir = self.config.get(\"log_dir\", None) if", "level=\"info\", donot_print=False): if self.logger is None: return # if it", "level type: %s\" % level) else: print(str(x) + \"\\n\") def", "level=\"info\"): if x + \"_\" + level in self._single_log_map: return", "self.log_filename += \".log\" self.log_folder = os.path.join(self.save_dir, self.log_folder, \"logs\") arg_log_dir =", "it if self.should_log: if hasattr(self.logger, level): if donot_print: getattr(self._file_only_logger, level)(str(x))", "getattr(self.logger, level)(str(x)) else: self.logger.error(\"Unknown log level type: %s\" % level)", "Logger: def __init__(self, config): self.logger = None self.summary_writer = None", "is_main_process(): return self.timer = Timer() self.config = config self.save_dir =", "# Single log wrapper map self._single_log_map = set() def __del__(self):", "level) else: print(str(x) + \"\\n\") def single_write(self, x, level=\"info\"): if", "\"_\" + level in self._single_log_map: return else: self.write(x, level) def", "level.upper())) self._file_only_logger.setLevel(getattr(logging, level.upper())) formatter = logging.Formatter( \"%(asctime)s %(levelname)s: %(message)s\", datefmt=\"%Y-%m-%dT%H:%M:%S\"", "= logging.Formatter( \"%(asctime)s %(levelname)s: %(message)s\", datefmt=\"%Y-%m-%dT%H:%M:%S\" ) # Add handler", "arg_log_dir = self.config.get(\"log_dir\", None) if arg_log_dir: self.log_folder = arg_log_dir if", "if hasattr(self.logger, level): if donot_print: getattr(self._file_only_logger, level)(str(x)) else: getattr(self.logger, level)(str(x))", "datefmt=\"%Y-%m-%dT%H:%M:%S\" ) # Add handler to file channel = logging.FileHandler(filename=self.log_filename,", "%s\" % level) else: print(str(x) + \"\\n\") def single_write(self, x,", "+ level in self._single_log_map: return else: self.write(x, level) def add_scalar(self,", "handler to file channel = logging.FileHandler(filename=self.log_filename, mode=\"a\") channel.setFormatter(formatter) self.logger.addHandler(channel) self._file_only_logger.addHandler(channel)", "is None: return self.summary_writer.add_scalar(key, value, iteration) def add_scalars(self, scalar_dict, iteration):", "= not should_not_log # Single log wrapper map self._single_log_map =", "self.logger = None self.summary_writer = None if not is_main_process(): return", "return else: self.write(x, level) def add_scalar(self, key, value, iteration): if", "val, iteration) def add_histogram_for_model(self, model, iteration): if self.summary_writer is None:", "type: %s\" % level) else: print(str(x) + \"\\n\") def single_write(self,", "not None: self.summary_writer.close() def write(self, x, level=\"info\", donot_print=False): if self.logger", "self.summary_writer.close() def write(self, x, level=\"info\", donot_print=False): if self.logger is None:", "not log then just print it if self.should_log: if hasattr(self.logger,", "sys from tensorboardX import SummaryWriter from pythia.utils.distributed_utils import is_main_process from", "self.log_filename) logging.captureWarnings(True) self.logger = logging.getLogger(__name__) self._file_only_logger = logging.getLogger(__name__) warnings_logger =", "from pythia.utils.timer import Timer class Logger: def __init__(self, config): self.logger", "should_not_log # Single log wrapper map self._single_log_map = set() def", "channel = logging.StreamHandler(sys.stdout) channel.setFormatter(formatter) self.logger.addHandler(channel) warnings_logger.addHandler(channel) should_not_log = self.config[\"training_parameters\"][\"should_not_log\"] self.should_log", "if not is_main_process(): return self.timer = Timer() self.config = config", "if x + \"_\" + level in self._single_log_map: return else:", "if not os.path.exists(self.log_folder): os.makedirs(self.log_folder) tensorboard_folder = os.path.join(self.log_folder, \"tensorboard\") self.summary_writer =", "iteration): if self.summary_writer is None: return self.summary_writer.add_scalar(key, value, iteration) def", "os.path.join(self.log_folder, self.log_filename) print(\"Logging to:\", self.log_filename) logging.captureWarnings(True) self.logger = logging.getLogger(__name__) self._file_only_logger", "= logging.getLogger(__name__) self._file_only_logger = logging.getLogger(__name__) warnings_logger = logging.getLogger(\"py.warnings\") # Set", "import (ckpt_name_from_core_args, foldername_from_config_override) from pythia.utils.timer import Timer class Logger: def", "then just print it if self.should_log: if hasattr(self.logger, level): if", "else: self.write(x, level) def add_scalar(self, key, value, iteration): if self.summary_writer", "pythia.utils.distributed_utils import is_main_process from pythia.utils.general import (ckpt_name_from_core_args, foldername_from_config_override) from pythia.utils.timer", "add_scalar(self, key, value, iteration): if self.summary_writer is None: return self.summary_writer.add_scalar(key,", "if it should not log then just print it if", "= \"%Y-%m-%dT%H:%M:%S\" self.log_filename = ckpt_name_from_core_args(config) + \"_\" self.log_filename += self.timer.get_time_hhmmss(None,", "= logging.FileHandler(filename=self.log_filename, mode=\"a\") channel.setFormatter(formatter) self.logger.addHandler(channel) self._file_only_logger.addHandler(channel) warnings_logger.addHandler(channel) # Add handler", "in scalar_dict.items(): self.summary_writer.add_scalar(key, val, iteration) def add_histogram_for_model(self, model, iteration): if", "Timer class Logger: def __init__(self, config): self.logger = None self.summary_writer", "= arg_log_dir if not os.path.exists(self.log_folder): os.makedirs(self.log_folder) tensorboard_folder = os.path.join(self.log_folder, \"tensorboard\")", "# Add handler to stdout channel = logging.StreamHandler(sys.stdout) channel.setFormatter(formatter) self.logger.addHandler(channel)", "__init__(self, config): self.logger = None self.summary_writer = None if not", "donot_print=False): if self.logger is None: return # if it should", "self.timer = Timer() self.config = config self.save_dir = config.training_parameters.save_dir self.log_folder", "level.upper())) formatter = logging.Formatter( \"%(asctime)s %(levelname)s: %(message)s\", datefmt=\"%Y-%m-%dT%H:%M:%S\" ) #", "iteration) def add_histogram_for_model(self, model, iteration): if self.summary_writer is None: return", "x + \"_\" + level in self._single_log_map: return else: self.write(x,", "handler to stdout channel = logging.StreamHandler(sys.stdout) channel.setFormatter(formatter) self.logger.addHandler(channel) warnings_logger.addHandler(channel) should_not_log", "= logging.getLogger(\"py.warnings\") # Set level level = config[\"training_parameters\"].get(\"logger_level\", \"info\") self.logger.setLevel(getattr(logging,", "ckpt_name_from_core_args(config) + \"_\" self.log_filename += self.timer.get_time_hhmmss(None, format=time_format) self.log_filename += \".log\"", "if self.logger is None: return # if it should not", "self.summary_writer = None if not is_main_process(): return self.timer = Timer()", "mode=\"a\") channel.setFormatter(formatter) self.logger.addHandler(channel) self._file_only_logger.addHandler(channel) warnings_logger.addHandler(channel) # Add handler to stdout", "is None: return # if it should not log then", "level): if donot_print: getattr(self._file_only_logger, level)(str(x)) else: getattr(self.logger, level)(str(x)) else: self.logger.error(\"Unknown", "return for key, val in scalar_dict.items(): self.summary_writer.add_scalar(key, val, iteration) def", "= None self.summary_writer = None if not is_main_process(): return self.timer", "= Timer() self.config = config self.save_dir = config.training_parameters.save_dir self.log_folder =", "foldername_from_config_override(config) time_format = \"%Y-%m-%dT%H:%M:%S\" self.log_filename = ckpt_name_from_core_args(config) + \"_\" self.log_filename", "self.timer.get_time_hhmmss(None, format=time_format) self.log_filename += \".log\" self.log_folder = os.path.join(self.save_dir, self.log_folder, \"logs\")", "os.path.join(self.save_dir, self.log_folder, \"logs\") arg_log_dir = self.config.get(\"log_dir\", None) if arg_log_dir: self.log_folder", "self.summary_writer.add_scalar(key, val, iteration) def add_histogram_for_model(self, model, iteration): if self.summary_writer is", "name, param in model.named_parameters(): np_param = param.clone().cpu().data.numpy() self.summary_writer.add_histogram(name, np_param, iteration)", "+= self.timer.get_time_hhmmss(None, format=time_format) self.log_filename += \".log\" self.log_folder = os.path.join(self.save_dir, self.log_folder,", "self.log_folder = arg_log_dir if not os.path.exists(self.log_folder): os.makedirs(self.log_folder) tensorboard_folder = os.path.join(self.log_folder,", "wrapper map self._single_log_map = set() def __del__(self): if getattr(self, \"summary_writer\",", "SummaryWriter from pythia.utils.distributed_utils import is_main_process from pythia.utils.general import (ckpt_name_from_core_args, foldername_from_config_override)", "\"%Y-%m-%dT%H:%M:%S\" self.log_filename = ckpt_name_from_core_args(config) + \"_\" self.log_filename += self.timer.get_time_hhmmss(None, format=time_format)", "os.path.exists(self.log_folder): os.makedirs(self.log_folder) tensorboard_folder = os.path.join(self.log_folder, \"tensorboard\") self.summary_writer = SummaryWriter(tensorboard_folder) self.log_filename", "self.logger = logging.getLogger(__name__) self._file_only_logger = logging.getLogger(__name__) warnings_logger = logging.getLogger(\"py.warnings\") #", "foldername_from_config_override) from pythia.utils.timer import Timer class Logger: def __init__(self, config):", "not should_not_log # Single log wrapper map self._single_log_map = set()", "getattr(self, \"summary_writer\", None) is not None: self.summary_writer.close() def write(self, x,", "(c) Facebook, Inc. and its affiliates. import base64 import logging", "config[\"training_parameters\"].get(\"logger_level\", \"info\") self.logger.setLevel(getattr(logging, level.upper())) self._file_only_logger.setLevel(getattr(logging, level.upper())) formatter = logging.Formatter( \"%(asctime)s", "add_histogram_for_model(self, model, iteration): if self.summary_writer is None: return for name,", "self.config.get(\"log_dir\", None) if arg_log_dir: self.log_folder = arg_log_dir if not os.path.exists(self.log_folder):", "in self._single_log_map: return else: self.write(x, level) def add_scalar(self, key, value,", "SummaryWriter(tensorboard_folder) self.log_filename = os.path.join(self.log_folder, self.log_filename) print(\"Logging to:\", self.log_filename) logging.captureWarnings(True) self.logger", "# Copyright (c) Facebook, Inc. and its affiliates. import base64", "None if not is_main_process(): return self.timer = Timer() self.config =", "channel = logging.FileHandler(filename=self.log_filename, mode=\"a\") channel.setFormatter(formatter) self.logger.addHandler(channel) self._file_only_logger.addHandler(channel) warnings_logger.addHandler(channel) # Add", "self.logger.setLevel(getattr(logging, level.upper())) self._file_only_logger.setLevel(getattr(logging, level.upper())) formatter = logging.Formatter( \"%(asctime)s %(levelname)s: %(message)s\",", "self.config = config self.save_dir = config.training_parameters.save_dir self.log_folder = ckpt_name_from_core_args(config) self.log_folder", "Set level level = config[\"training_parameters\"].get(\"logger_level\", \"info\") self.logger.setLevel(getattr(logging, level.upper())) self._file_only_logger.setLevel(getattr(logging, level.upper()))", "level)(str(x)) else: getattr(self.logger, level)(str(x)) else: self.logger.error(\"Unknown log level type: %s\"", "logging.captureWarnings(True) self.logger = logging.getLogger(__name__) self._file_only_logger = logging.getLogger(__name__) warnings_logger = logging.getLogger(\"py.warnings\")", "log level type: %s\" % level) else: print(str(x) + \"\\n\")", "level) def add_scalar(self, key, value, iteration): if self.summary_writer is None:", "its affiliates. import base64 import logging import os import sys", "tensorboard_folder = os.path.join(self.log_folder, \"tensorboard\") self.summary_writer = SummaryWriter(tensorboard_folder) self.log_filename = os.path.join(self.log_folder,", "should not log then just print it if self.should_log: if", "self.logger is None: return # if it should not log", "def add_scalars(self, scalar_dict, iteration): if self.summary_writer is None: return for" ]
[ "None, project: Optional[pulumi.Input[str]] = None, resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]] = None): \"\"\"", "of the resource. :param pulumi.ResourceOptions opts: Options for the resource.", "= pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options", "__props__.__dict__[\"location\"] = location __props__.__dict__[\"name\"] = name __props__.__dict__[\"project\"] = project __props__.__dict__[\"resource_attributes\"]", "resource. \"\"\" return pulumi.get(self, \"data_id\") @property @pulumi.getter def name(self) ->", "parent consent store. :param str resource_name: The name of the", "str resource_name: The name of the resource. :param pulumi.ResourceOptions opts:", "identifier for the mapped resource. \"\"\" return pulumi.get(self, \"data_id\") @data_id.setter", "archived. \"\"\" return pulumi.get(self, \"archive_time\") @property @pulumi.getter def archived(self) ->", "location) if name is not None: pulumi.set(__self__, \"name\", name) if", "resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(UserDataMappingArgs, pulumi.ResourceOptions, *args,", "the User data mapping, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]", "pulumi.ResourceOptions opts: Options for the resource. \"\"\" opts = pulumi.ResourceOptions.merge(opts,", "pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = UserDataMappingArgs.__new__(UserDataMappingArgs) __props__.__dict__[\"archive_time\"] = None __props__.__dict__[\"archived\"] =", "__props__=None): if opts is None: opts = pulumi.ResourceOptions() if not", "return pulumi.get(self, \"resource_attributes\") @property @pulumi.getter(name=\"userId\") def user_id(self) -> pulumi.Output[str]: \"\"\"", "def user_id(self, value: pulumi.Input[str]): pulumi.set(self, \"user_id\", value) @property @pulumi.getter def", "pulumi.Input[str]: return pulumi.get(self, \"consent_store_id\") @consent_store_id.setter def consent_store_id(self, value: pulumi.Input[str]): pulumi.set(self,", "opts: Optional[pulumi.ResourceOptions] = None) -> 'UserDataMapping': \"\"\" Get an existing", "@pulumi.getter def archived(self) -> pulumi.Output[bool]: \"\"\" Indicates whether this mapping", "get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'UserDataMapping':", "opts.urn: raise TypeError(\"Missing required property 'consent_store_id'\") __props__.__dict__[\"consent_store_id\"] = consent_store_id if", "apply to these User data mappings. Attributes listed here must", "existing UserDataMapping resource's state with the given name, id, and", "ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if", "__props__.__dict__[\"archive_time\"] = None __props__.__dict__[\"archived\"] = None __props__.__dict__[\"data_id\"] = None __props__.__dict__[\"name\"]", "Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, project: Optional[pulumi.Input[str]] =", "'dataset_id'\") __props__.__dict__[\"dataset_id\"] = dataset_id __props__.__dict__[\"location\"] = location __props__.__dict__[\"name\"] = name", "*, consent_store_id: pulumi.Input[str], data_id: pulumi.Input[str], dataset_id: pulumi.Input[str], user_id: pulumi.Input[str], location:", "Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]]] = None, user_id: Optional[pulumi.Input[str]] = None, __props__=None): \"\"\" Creates", "consent store. :param str resource_name: The name of the resource.", "to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for", "when passed in combination with a valid opts.id to get", "__init__(__self__, *, consent_store_id: pulumi.Input[str], data_id: pulumi.Input[str], dataset_id: pulumi.Input[str], user_id: pulumi.Input[str],", "is not None: pulumi.set(__self__, \"location\", location) if name is not", "Union, overload from ... import _utilities from . import outputs", "value) @property @pulumi.getter(name=\"datasetId\") def dataset_id(self) -> pulumi.Input[str]: return pulumi.get(self, \"dataset_id\")", "@property @pulumi.getter def project(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"project\") @project.setter", "single valued, that is, exactly one value is specified for", "this file was generated by the Pulumi SDK Generator. ***", "Optional[pulumi.ResourceOptions] = None) -> 'UserDataMapping': \"\"\" Get an existing UserDataMapping", "options to be a ResourceOptions instance') if opts.version is None:", "location __props__.__dict__[\"name\"] = name __props__.__dict__[\"project\"] = project __props__.__dict__[\"resource_attributes\"] = resource_attributes", "_utilities.get_resource_args_opts(UserDataMappingArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name,", "form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]] resource_attributes: Attributes of the resource. Only", "Optional[pulumi.Input[str]] = None, data_id: Optional[pulumi.Input[str]] = None, dataset_id: Optional[pulumi.Input[str]] =", "raise TypeError('Expected resource options to be a ResourceOptions instance') if", "opts: Optional[pulumi.ResourceOptions] = None, consent_store_id: Optional[pulumi.Input[str]] = None, data_id: Optional[pulumi.Input[str]]", "project is not None: pulumi.set(__self__, \"project\", project) if resource_attributes is", "overload from ... import _utilities from . import outputs from", "pulumi.Output[str]: \"\"\" Indicates the time when this mapping was archived.", "\"resource_attributes\") @property @pulumi.getter(name=\"userId\") def user_id(self) -> pulumi.Output[str]: \"\"\" User's UUID", "def resource_attributes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]: \"\"\" Attributes of the resource. Only", "the mapped resource. \"\"\" return pulumi.get(self, \"data_id\") @data_id.setter def data_id(self,", "Options for the resource. :param pulumi.Input[str] data_id: A unique identifier", "__props__.__dict__[\"archive_time\"] = None __props__.__dict__[\"archived\"] = None super(UserDataMapping, __self__).__init__( 'google-native:healthcare/v1beta1:UserDataMapping', resource_name,", "pulumi.Input[str], user_id: pulumi.Input[str], location: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] =", "data_id(self, value: pulumi.Input[str]): pulumi.set(self, \"data_id\", value) @property @pulumi.getter(name=\"datasetId\") def dataset_id(self)", "-> pulumi.Output[bool]: \"\"\" Indicates whether this mapping is archived. \"\"\"", "import _utilities from . import outputs from ._inputs import *", "pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence,", "class UserDataMappingArgs: def __init__(__self__, *, consent_store_id: pulumi.Input[str], data_id: pulumi.Input[str], dataset_id:", "that is, exactly one value is specified for the field", "is not None: pulumi.set(__self__, \"name\", name) if project is not", "pulumi.set(__self__, \"resource_attributes\", resource_attributes) @property @pulumi.getter(name=\"consentStoreId\") def consent_store_id(self) -> pulumi.Input[str]: return", "raise TypeError(\"Missing required property 'user_id'\") __props__.__dict__[\"user_id\"] = user_id __props__.__dict__[\"archive_time\"] =", "@property @pulumi.getter def name(self) -> pulumi.Output[str]: \"\"\" Resource name of", "= None __props__.__dict__[\"archived\"] = None super(UserDataMapping, __self__).__init__( 'google-native:healthcare/v1beta1:UserDataMapping', resource_name, __props__,", "str resource_name: The name of the resource. :param UserDataMappingArgs args:", "implicitly apply to these User data mappings. Attributes listed here", "dataset_id is None and not opts.urn: raise TypeError(\"Missing required property", "\"\"\" Creates a new User data mapping in the parent", "None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if", "pulumi.get(self, \"name\") @property @pulumi.getter(name=\"resourceAttributes\") def resource_attributes(self) -> pulumi.Output[Sequence['outputs.AttributeResponse']]: \"\"\" Attributes", "unique identifier for the mapped resource. :param pulumi.Input[str] name: Resource", "mapped resource. \"\"\" return pulumi.get(self, \"data_id\") @data_id.setter def data_id(self, value:", "None __props__.__dict__[\"name\"] = None __props__.__dict__[\"resource_attributes\"] = None __props__.__dict__[\"user_id\"] = None", "\"\"\" ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts", "resource's state with the given name, id, and optional extra", "-> Optional[pulumi.Input[str]]: \"\"\" Resource name of the User data mapping,", "data_id: pulumi.Input[str], dataset_id: pulumi.Input[str], user_id: pulumi.Input[str], location: Optional[pulumi.Input[str]] = None,", "None: pulumi.set(__self__, \"project\", project) if resource_attributes is not None: pulumi.set(__self__,", "resource_attributes: Attributes of the resource. Only explicitly set attributes are", "by the client. :param pulumi.Input[str] name: Resource name of the", "The unique provider ID of the resource to lookup. :param", "Optional[pulumi.Input[str]]): pulumi.set(self, \"project\", value) @property @pulumi.getter(name=\"resourceAttributes\") def resource_attributes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]:", ":param pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]] resource_attributes: Attributes of the resource. Only explicitly set", "\"archived\") @property @pulumi.getter(name=\"dataId\") def data_id(self) -> pulumi.Output[str]: \"\"\" A unique", "value) @property @pulumi.getter(name=\"dataId\") def data_id(self) -> pulumi.Input[str]: \"\"\" A unique", "@pulumi.getter def location(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"location\") @location.setter def", "* __all__ = ['UserDataMappingArgs', 'UserDataMapping'] @pulumi.input_type class UserDataMappingArgs: def __init__(__self__,", "the resource. :param UserDataMappingArgs args: The arguments to use to", "= None, resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]]] = None, user_id: Optional[pulumi.Input[str]] = None,", "**kwargs): resource_args, opts = _utilities.get_resource_args_opts(UserDataMappingArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args", "import * __all__ = ['UserDataMappingArgs', 'UserDataMapping'] @pulumi.input_type class UserDataMappingArgs: def", "opts: Options for the resource. :param pulumi.Input[str] data_id: A unique", "None return UserDataMapping(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name=\"archiveTime\") def archive_time(self) ->", "and not opts.urn: raise TypeError(\"Missing required property 'data_id'\") __props__.__dict__[\"data_id\"] =", "mapping, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]] resource_attributes: Attributes of", "if __props__ is not None: raise TypeError('__props__ is only valid", "name __props__.__dict__[\"project\"] = project __props__.__dict__[\"resource_attributes\"] = resource_attributes if user_id is", "def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) ->", "'user_id'\") __props__.__dict__[\"user_id\"] = user_id __props__.__dict__[\"archive_time\"] = None __props__.__dict__[\"archived\"] = None", "resource options to be a ResourceOptions instance') if opts.version is", "UserDataMappingArgs: def __init__(__self__, *, consent_store_id: pulumi.Input[str], data_id: pulumi.Input[str], dataset_id: pulumi.Input[str],", "None) -> 'UserDataMapping': \"\"\" Get an existing UserDataMapping resource's state", "opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions):", "def consent_store_id(self) -> pulumi.Input[str]: return pulumi.get(self, \"consent_store_id\") @consent_store_id.setter def consent_store_id(self,", "def archive_time(self) -> pulumi.Output[str]: \"\"\" Indicates the time when this", "the resulting resource. :param pulumi.Input[str] id: The unique provider ID", "TypeError(\"Missing required property 'dataset_id'\") __props__.__dict__[\"dataset_id\"] = dataset_id __props__.__dict__[\"location\"] = location", "field \"values\" in each Attribute. \"\"\" return pulumi.get(self, \"resource_attributes\") @property", "name: Resource name of the User data mapping, of the", "@resource_attributes.setter def resource_attributes(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]): pulumi.set(self, \"resource_attributes\", value) class UserDataMapping(pulumi.CustomResource):", "\"\"\" pulumi.set(__self__, \"consent_store_id\", consent_store_id) pulumi.set(__self__, \"data_id\", data_id) pulumi.set(__self__, \"dataset_id\", dataset_id)", "the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]] resource_attributes: Attributes of the resource.", "property 'user_id'\") __props__.__dict__[\"user_id\"] = user_id __props__.__dict__[\"archive_time\"] = None __props__.__dict__[\"archived\"] =", "Optional[pulumi.ResourceOptions] = None): \"\"\" Creates a new User data mapping", ":param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] data_id:", "identifier for the mapped resource. \"\"\" return pulumi.get(self, \"data_id\") @property", "\"project\") @project.setter def project(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"project\", value) @property", "for the field \"values\" in each Attribute. \"\"\" return pulumi.get(self,", "value) class UserDataMapping(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]", "None, project: Optional[pulumi.Input[str]] = None, resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]]] = None, user_id:", "pulumi.set(__self__, \"project\", project) if resource_attributes is not None: pulumi.set(__self__, \"resource_attributes\",", "data_id(self) -> pulumi.Output[str]: \"\"\" A unique identifier for the mapped", "data mapping, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. \"\"\" return pulumi.get(self, \"name\")", "consent_store_id is None and not opts.urn: raise TypeError(\"Missing required property", "opts.version is None: opts.version = _utilities.get_version() if opts.id is None:", "\"archive_time\") @property @pulumi.getter def archived(self) -> pulumi.Output[bool]: \"\"\" Indicates whether", "hand unless you're certain you know what you are doing!", "return pulumi.get(self, \"data_id\") @property @pulumi.getter def name(self) -> pulumi.Output[str]: \"\"\"", "raise TypeError(\"Missing required property 'data_id'\") __props__.__dict__[\"data_id\"] = data_id if dataset_id", "id, and optional extra properties used to qualify the lookup.", "resource_attributes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]: \"\"\" Attributes of the resource. Only explicitly", "import outputs from ._inputs import * __all__ = ['UserDataMappingArgs', 'UserDataMapping']", "_utilities from . import outputs from ._inputs import * __all__", "The name of the resource. :param UserDataMappingArgs args: The arguments", "form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. \"\"\" return pulumi.get(self, \"name\") @name.setter def name(self, value:", "-> pulumi.Output[str]: \"\"\" Indicates the time when this mapping was", "archived. \"\"\" return pulumi.get(self, \"archived\") @property @pulumi.getter(name=\"dataId\") def data_id(self) ->", ":param str resource_name: The unique name of the resulting resource.", "data_id: Optional[pulumi.Input[str]] = None, dataset_id: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]]", "each Attribute. \"\"\" return pulumi.get(self, \"resource_attributes\") @property @pulumi.getter(name=\"userId\") def user_id(self)", "by the client. \"\"\" return pulumi.get(self, \"user_id\") @user_id.setter def user_id(self,", "value: pulumi.Input[str]): pulumi.set(self, \"dataset_id\", value) @property @pulumi.getter(name=\"userId\") def user_id(self) ->", "**resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts:", "def data_id(self) -> pulumi.Output[str]: \"\"\" A unique identifier for the", "unless you're certain you know what you are doing! ***", "pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to", "UserDataMapping(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None,", "property 'data_id'\") __props__.__dict__[\"data_id\"] = data_id if dataset_id is None and", "= None __props__.__dict__[\"name\"] = None __props__.__dict__[\"resource_attributes\"] = None __props__.__dict__[\"user_id\"] =", "the client. \"\"\" ... @overload def __init__(__self__, resource_name: str, args:", "__init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, consent_store_id: Optional[pulumi.Input[str]] =", "not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a", "a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version()", "pulumi.Output[str]: \"\"\" User's UUID provided by the client. \"\"\" return", "None __props__.__dict__[\"resource_attributes\"] = None __props__.__dict__[\"user_id\"] = None return UserDataMapping(resource_name, opts=opts,", "mapped resource. :param pulumi.Input[str] user_id: User's UUID provided by the", "required property 'dataset_id'\") __props__.__dict__[\"dataset_id\"] = dataset_id __props__.__dict__[\"location\"] = location __props__.__dict__[\"name\"]", "@location.setter def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"location\", value) @property @pulumi.getter", "pulumi.get(self, \"user_id\") @user_id.setter def user_id(self, value: pulumi.Input[str]): pulumi.set(self, \"user_id\", value)", "User's UUID provided by the client. \"\"\" return pulumi.get(self, \"user_id\")", "Attribute. \"\"\" return pulumi.get(self, \"resource_attributes\") @resource_attributes.setter def resource_attributes(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]):", "to use to populate this resource's properties. :param pulumi.ResourceOptions opts:", "opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str,", "pulumi.set(self, \"resource_attributes\", value) class UserDataMapping(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str,", "None, name: Optional[pulumi.Input[str]] = None, project: Optional[pulumi.Input[str]] = None, resource_attributes:", "\"data_id\", value) @property @pulumi.getter(name=\"datasetId\") def dataset_id(self) -> pulumi.Input[str]: return pulumi.get(self,", "= None, consent_store_id: Optional[pulumi.Input[str]] = None, data_id: Optional[pulumi.Input[str]] = None,", "Indicates the time when this mapping was archived. \"\"\" return", "`projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]] resource_attributes: Attributes of the resource. Only explicitly", "User data mapping, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]] resource_attributes:", "Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities", "the User data mapping, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]]", "resource_attributes(self) -> pulumi.Output[Sequence['outputs.AttributeResponse']]: \"\"\" Attributes of the resource. Only explicitly", "pulumi.Input[str] name: Resource name of the User data mapping, of", "opts: Options for the resource. \"\"\" ... def __init__(__self__, resource_name:", "not opts.urn: raise TypeError(\"Missing required property 'user_id'\") __props__.__dict__[\"user_id\"] = user_id", "the parent consent store. :param str resource_name: The name of", "if opts.id is None: if __props__ is not None: raise", "value: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]): pulumi.set(self, \"resource_attributes\", value) class UserDataMapping(pulumi.CustomResource): @overload def __init__(__self__,", "= UserDataMappingArgs.__new__(UserDataMappingArgs) __props__.__dict__[\"archive_time\"] = None __props__.__dict__[\"archived\"] = None __props__.__dict__[\"data_id\"] =", "= None, __props__=None): if opts is None: opts = pulumi.ResourceOptions()", "provided by the client. :param pulumi.Input[str] name: Resource name of", "\"name\") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property", "\"dataset_id\", value) @property @pulumi.getter(name=\"userId\") def user_id(self) -> pulumi.Input[str]: \"\"\" User's", "\"consent_store_id\") @consent_store_id.setter def consent_store_id(self, value: pulumi.Input[str]): pulumi.set(self, \"consent_store_id\", value) @property", "import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union,", "pulumi.Output[bool]: \"\"\" Indicates whether this mapping is archived. \"\"\" return", "what you are doing! *** import warnings import pulumi import", "Pulumi SDK Generator. *** # *** Do not edit by", "field \"values\" in each Attribute. \"\"\" pulumi.set(__self__, \"consent_store_id\", consent_store_id) pulumi.set(__self__,", "None, location: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, project:", "the given name, id, and optional extra properties used to", "= None, user_id: Optional[pulumi.Input[str]] = None, __props__=None): if opts is", "args: The arguments to use to populate this resource's properties.", "resource_attributes if user_id is None and not opts.urn: raise TypeError(\"Missing", "extra properties used to qualify the lookup. :param str resource_name:", "in each Attribute. \"\"\" pulumi.set(__self__, \"consent_store_id\", consent_store_id) pulumi.set(__self__, \"data_id\", data_id)", "def dataset_id(self) -> pulumi.Input[str]: return pulumi.get(self, \"dataset_id\") @dataset_id.setter def dataset_id(self,", "@property @pulumi.getter(name=\"resourceAttributes\") def resource_attributes(self) -> pulumi.Output[Sequence['outputs.AttributeResponse']]: \"\"\" Attributes of the", "data mapping, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]] resource_attributes: Attributes", "set attributes are displayed here. Attribute definitions with defaults set", "to lookup. :param pulumi.ResourceOptions opts: Options for the resource. \"\"\"", "dataset_id: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]]", "def __init__(__self__, *, consent_store_id: pulumi.Input[str], data_id: pulumi.Input[str], dataset_id: pulumi.Input[str], user_id:", "None __props__.__dict__[\"user_id\"] = None return UserDataMapping(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name=\"archiveTime\")", "_utilities.get_version() if opts.id is None: if __props__ is not None:", "\"values\" in each Attribute. \"\"\" return pulumi.get(self, \"resource_attributes\") @resource_attributes.setter def", "opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = UserDataMappingArgs.__new__(UserDataMappingArgs) __props__.__dict__[\"archive_time\"] = None", "= None): \"\"\" The set of arguments for constructing a", "@pulumi.getter(name=\"resourceAttributes\") def resource_attributes(self) -> pulumi.Output[Sequence['outputs.AttributeResponse']]: \"\"\" Attributes of the resource.", "are displayed here. Attribute definitions with defaults set implicitly apply", "\"data_id\") @property @pulumi.getter def name(self) -> pulumi.Output[str]: \"\"\" Resource name", "@dataset_id.setter def dataset_id(self, value: pulumi.Input[str]): pulumi.set(self, \"dataset_id\", value) @property @pulumi.getter(name=\"userId\")", "= user_id __props__.__dict__[\"archive_time\"] = None __props__.__dict__[\"archived\"] = None super(UserDataMapping, __self__).__init__(", "= None, resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]] = None): \"\"\" The set of", "these User data mappings. Attributes listed here must be single", "`projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. \"\"\" return pulumi.get(self, \"name\") @name.setter def name(self, value: Optional[pulumi.Input[str]]):", "resource_attributes is not None: pulumi.set(__self__, \"resource_attributes\", resource_attributes) @property @pulumi.getter(name=\"consentStoreId\") def", "opts = _utilities.get_resource_args_opts(UserDataMappingArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not", "consent_store_id(self) -> pulumi.Input[str]: return pulumi.get(self, \"consent_store_id\") @consent_store_id.setter def consent_store_id(self, value:", "dataset_id(self, value: pulumi.Input[str]): pulumi.set(self, \"dataset_id\", value) @property @pulumi.getter(name=\"userId\") def user_id(self)", "Optional[pulumi.Input[str]] = None, resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]]] = None, user_id: Optional[pulumi.Input[str]] =", "User data mapping, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]] resource_attributes:", "Attributes of the resource. Only explicitly set attributes are displayed", "\"location\") @location.setter def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"location\", value) @property", "is None and not opts.urn: raise TypeError(\"Missing required property 'consent_store_id'\")", "form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. \"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"resourceAttributes\") def resource_attributes(self)", "def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"location\", value) @property @pulumi.getter def", "to get an existing resource') __props__ = UserDataMappingArgs.__new__(UserDataMappingArgs) if consent_store_id", "resource_name: The unique name of the resulting resource. :param pulumi.Input[str]", "only valid when passed in combination with a valid opts.id", "pulumi.get(self, \"resource_attributes\") @property @pulumi.getter(name=\"userId\") def user_id(self) -> pulumi.Output[str]: \"\"\" User's", "definitions with defaults set implicitly apply to these User data", "-> pulumi.Input[str]: return pulumi.get(self, \"consent_store_id\") @consent_store_id.setter def consent_store_id(self, value: pulumi.Input[str]):", "@pulumi.getter(name=\"userId\") def user_id(self) -> pulumi.Input[str]: \"\"\" User's UUID provided by", "The set of arguments for constructing a UserDataMapping resource. :param", "not None: pulumi.set(__self__, \"project\", project) if resource_attributes is not None:", "= None super(UserDataMapping, __self__).__init__( 'google-native:healthcare/v1beta1:UserDataMapping', resource_name, __props__, opts) @staticmethod def", "warnings import pulumi import pulumi.runtime from typing import Any, Mapping,", "project(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"project\", value) @property @pulumi.getter(name=\"resourceAttributes\") def resource_attributes(self)", "of the resource. Only explicitly set attributes are displayed here.", "= location __props__.__dict__[\"name\"] = name __props__.__dict__[\"project\"] = project __props__.__dict__[\"resource_attributes\"] =", "project: Optional[pulumi.Input[str]] = None, resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]] = None): \"\"\" The", "value: Optional[pulumi.Input[str]]): pulumi.set(self, \"project\", value) @property @pulumi.getter(name=\"resourceAttributes\") def resource_attributes(self) ->", "Optional[pulumi.Input[str]] = None, __props__=None): \"\"\" Creates a new User data", "specified for the field \"values\" in each Attribute. :param pulumi.Input[str]", "None: pulumi.set(__self__, \"resource_attributes\", resource_attributes) @property @pulumi.getter(name=\"consentStoreId\") def consent_store_id(self) -> pulumi.Input[str]:", "= None): \"\"\" Creates a new User data mapping in", "the time when this mapping was archived. \"\"\" return pulumi.get(self,", "opts.id to get an existing resource') __props__ = UserDataMappingArgs.__new__(UserDataMappingArgs) if", "new User data mapping in the parent consent store. :param", "# coding=utf-8 # *** WARNING: this file was generated by", "set of arguments for constructing a UserDataMapping resource. :param pulumi.Input[str]", ":param pulumi.ResourceOptions opts: Options for the resource. \"\"\" ... def", "name: Optional[pulumi.Input[str]] = None, project: Optional[pulumi.Input[str]] = None, resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]", "import warnings import pulumi import pulumi.runtime from typing import Any,", "def data_id(self, value: pulumi.Input[str]): pulumi.set(self, \"data_id\", value) @property @pulumi.getter(name=\"datasetId\") def", "\"\"\" return pulumi.get(self, \"user_id\") @user_id.setter def user_id(self, value: pulumi.Input[str]): pulumi.set(self,", "\"data_id\", data_id) pulumi.set(__self__, \"dataset_id\", dataset_id) pulumi.set(__self__, \"user_id\", user_id) if location", "\"\"\" Indicates the time when this mapping was archived. \"\"\"", "dataset_id) pulumi.set(__self__, \"user_id\", user_id) if location is not None: pulumi.set(__self__,", "*** import warnings import pulumi import pulumi.runtime from typing import", "raise TypeError(\"Missing required property 'dataset_id'\") __props__.__dict__[\"dataset_id\"] = dataset_id __props__.__dict__[\"location\"] =", "\"project\", project) if resource_attributes is not None: pulumi.set(__self__, \"resource_attributes\", resource_attributes)", "\"consent_store_id\", consent_store_id) pulumi.set(__self__, \"data_id\", data_id) pulumi.set(__self__, \"dataset_id\", dataset_id) pulumi.set(__self__, \"user_id\",", "pulumi.Input[str], data_id: pulumi.Input[str], dataset_id: pulumi.Input[str], user_id: pulumi.Input[str], location: Optional[pulumi.Input[str]] =", "TypeError(\"Missing required property 'consent_store_id'\") __props__.__dict__[\"consent_store_id\"] = consent_store_id if data_id is", "you know what you are doing! *** import warnings import", "\"\"\" The set of arguments for constructing a UserDataMapping resource.", "def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(UserDataMappingArgs,", "user_id(self) -> pulumi.Input[str]: \"\"\" User's UUID provided by the client.", "dataset_id(self) -> pulumi.Input[str]: return pulumi.get(self, \"dataset_id\") @dataset_id.setter def dataset_id(self, value:", "@pulumi.input_type class UserDataMappingArgs: def __init__(__self__, *, consent_store_id: pulumi.Input[str], data_id: pulumi.Input[str],", "def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter def", "\"\"\" Attributes of the resource. Only explicitly set attributes are", "the client. :param pulumi.Input[str] name: Resource name of the User", "UserDataMapping resource. :param pulumi.Input[str] data_id: A unique identifier for the", "None, user_id: Optional[pulumi.Input[str]] = None, __props__=None): if opts is None:", "Resource name of the User data mapping, of the form", "set implicitly apply to these User data mappings. Attributes listed", "def user_id(self) -> pulumi.Output[str]: \"\"\" User's UUID provided by the", "def user_id(self) -> pulumi.Input[str]: \"\"\" User's UUID provided by the", "None, __props__=None): \"\"\" Creates a new User data mapping in", "-> Optional[pulumi.Input[str]]: return pulumi.get(self, \"project\") @project.setter def project(self, value: Optional[pulumi.Input[str]]):", "pulumi.Input[str], location: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, project:", "was archived. \"\"\" return pulumi.get(self, \"archive_time\") @property @pulumi.getter def archived(self)", "provider ID of the resource to lookup. :param pulumi.ResourceOptions opts:", "a UserDataMapping resource. :param pulumi.Input[str] data_id: A unique identifier for", "is None: if __props__ is not None: raise TypeError('__props__ is", "-> Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]: \"\"\" Attributes of the resource. Only explicitly set", "user_id: User's UUID provided by the client. \"\"\" ... @overload", "None, resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]] = None): \"\"\" The set of arguments", "= None) -> 'UserDataMapping': \"\"\" Get an existing UserDataMapping resource's", "resulting resource. :param pulumi.Input[str] id: The unique provider ID of", "the resource to lookup. :param pulumi.ResourceOptions opts: Options for the", "args: UserDataMappingArgs, opts: Optional[pulumi.ResourceOptions] = None): \"\"\" Creates a new", "str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'UserDataMapping': \"\"\"", "mapped resource. \"\"\" return pulumi.get(self, \"data_id\") @property @pulumi.getter def name(self)", "__self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name:", "by the client. \"\"\" ... @overload def __init__(__self__, resource_name: str,", "valid opts.id to get an existing resource') __props__ = UserDataMappingArgs.__new__(UserDataMappingArgs)", "`projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]] resource_attributes: Attributes of the resource. Only explicitly", "UserDataMapping(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name=\"archiveTime\") def archive_time(self) -> pulumi.Output[str]: \"\"\"", "pulumi.set(__self__, \"data_id\", data_id) pulumi.set(__self__, \"dataset_id\", dataset_id) pulumi.set(__self__, \"user_id\", user_id) if", "the resource. \"\"\" opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = UserDataMappingArgs.__new__(UserDataMappingArgs)", "name of the User data mapping, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`.", "= resource_attributes if user_id is None and not opts.urn: raise", "constructing a UserDataMapping resource. :param pulumi.Input[str] data_id: A unique identifier", "\"values\" in each Attribute. \"\"\" pulumi.set(__self__, \"consent_store_id\", consent_store_id) pulumi.set(__self__, \"data_id\",", "['UserDataMappingArgs', 'UserDataMapping'] @pulumi.input_type class UserDataMappingArgs: def __init__(__self__, *, consent_store_id: pulumi.Input[str],", "@user_id.setter def user_id(self, value: pulumi.Input[str]): pulumi.set(self, \"user_id\", value) @property @pulumi.getter", "= None, project: Optional[pulumi.Input[str]] = None, resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]]] = None,", "pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance')", "consent_store_id: Optional[pulumi.Input[str]] = None, data_id: Optional[pulumi.Input[str]] = None, dataset_id: Optional[pulumi.Input[str]]", "is not None: raise TypeError('__props__ is only valid when passed", "user_id: User's UUID provided by the client. :param pulumi.Input[str] name:", "user_id: Optional[pulumi.Input[str]] = None, __props__=None): if opts is None: opts", "\"\"\" return pulumi.get(self, \"data_id\") @data_id.setter def data_id(self, value: pulumi.Input[str]): pulumi.set(self,", "None __props__.__dict__[\"archived\"] = None __props__.__dict__[\"data_id\"] = None __props__.__dict__[\"name\"] = None", "each Attribute. :param pulumi.Input[str] user_id: User's UUID provided by the", "resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args,", "'UserDataMapping'] @pulumi.input_type class UserDataMappingArgs: def __init__(__self__, *, consent_store_id: pulumi.Input[str], data_id:", "@pulumi.getter def project(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"project\") @project.setter def", "name of the resource. :param pulumi.ResourceOptions opts: Options for the", "user_id: pulumi.Input[str], location: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None,", "__props__ = UserDataMappingArgs.__new__(UserDataMappingArgs) if consent_store_id is None and not opts.urn:", "mapping, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. \"\"\" return pulumi.get(self, \"name\") @name.setter", "= data_id if dataset_id is None and not opts.urn: raise", "__props__.__dict__[\"consent_store_id\"] = consent_store_id if data_id is None and not opts.urn:", "unique provider ID of the resource to lookup. :param pulumi.ResourceOptions", "name(self) -> Optional[pulumi.Input[str]]: \"\"\" Resource name of the User data", "-> pulumi.Input[str]: \"\"\" User's UUID provided by the client. \"\"\"", "project(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"project\") @project.setter def project(self, value:", "store. :param str resource_name: The name of the resource. :param", "valid when passed in combination with a valid opts.id to", "for the mapped resource. \"\"\" return pulumi.get(self, \"data_id\") @property @pulumi.getter", "= None, location: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None,", "data mappings. Attributes listed here must be single valued, that", "pulumi.ResourceOptions opts: Options for the resource. \"\"\" ... def __init__(__self__,", "for the mapped resource. \"\"\" return pulumi.get(self, \"data_id\") @data_id.setter def", "Optional[pulumi.Input[str]] = None, project: Optional[pulumi.Input[str]] = None, resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]] =", "pulumi.Input[str]: \"\"\" A unique identifier for the mapped resource. \"\"\"", "*** # *** Do not edit by hand unless you're", "@consent_store_id.setter def consent_store_id(self, value: pulumi.Input[str]): pulumi.set(self, \"consent_store_id\", value) @property @pulumi.getter(name=\"dataId\")", "for the resource. :param pulumi.Input[str] data_id: A unique identifier for", "pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'UserDataMapping': \"\"\" Get an", "for the resource. \"\"\" opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ =", "*** Do not edit by hand unless you're certain you", "super(UserDataMapping, __self__).__init__( 'google-native:healthcare/v1beta1:UserDataMapping', resource_name, __props__, opts) @staticmethod def get(resource_name: str,", "__props__.__dict__[\"project\"] = project __props__.__dict__[\"resource_attributes\"] = resource_attributes if user_id is None", "if name is not None: pulumi.set(__self__, \"name\", name) if project", "@pulumi.getter(name=\"userId\") def user_id(self) -> pulumi.Output[str]: \"\"\" User's UUID provided by", "`projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. \"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"resourceAttributes\") def resource_attributes(self) ->", "*args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__)", "def project(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"project\", value) @property @pulumi.getter(name=\"resourceAttributes\") def", "this mapping is archived. \"\"\" return pulumi.get(self, \"archived\") @property @pulumi.getter(name=\"dataId\")", "consent_store_id) pulumi.set(__self__, \"data_id\", data_id) pulumi.set(__self__, \"dataset_id\", dataset_id) pulumi.set(__self__, \"user_id\", user_id)", "pulumi.Input[str] user_id: User's UUID provided by the client. \"\"\" ...", "name of the resource. :param UserDataMappingArgs args: The arguments to", "__props__.__dict__[\"resource_attributes\"] = resource_attributes if user_id is None and not opts.urn:", "-> pulumi.Output[str]: \"\"\" User's UUID provided by the client. \"\"\"", "\"location\", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: \"\"\" Resource", "= consent_store_id if data_id is None and not opts.urn: raise", "@property @pulumi.getter(name=\"resourceAttributes\") def resource_attributes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]: \"\"\" Attributes of the", "-> Optional[pulumi.Input[str]]: return pulumi.get(self, \"location\") @location.setter def location(self, value: Optional[pulumi.Input[str]]):", "def name(self) -> Optional[pulumi.Input[str]]: \"\"\" Resource name of the User", "populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the", "value) @property @pulumi.getter(name=\"resourceAttributes\") def resource_attributes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]: \"\"\" Attributes of", "be a ResourceOptions instance') if opts.version is None: opts.version =", "field \"values\" in each Attribute. \"\"\" return pulumi.get(self, \"resource_attributes\") @resource_attributes.setter", "with a valid opts.id to get an existing resource') __props__", "*** WARNING: this file was generated by the Pulumi SDK", "resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource.", "@pulumi.getter(name=\"archiveTime\") def archive_time(self) -> pulumi.Output[str]: \"\"\" Indicates the time when", "\"\"\" Indicates whether this mapping is archived. \"\"\" return pulumi.get(self,", "__props__.__dict__[\"name\"] = None __props__.__dict__[\"resource_attributes\"] = None __props__.__dict__[\"user_id\"] = None return", "name(self) -> pulumi.Output[str]: \"\"\" Resource name of the User data", "property 'consent_store_id'\") __props__.__dict__[\"consent_store_id\"] = consent_store_id if data_id is None and", "def name(self) -> pulumi.Output[str]: \"\"\" Resource name of the User", "-> pulumi.Output[str]: \"\"\" Resource name of the User data mapping,", "\"\"\" return pulumi.get(self, \"resource_attributes\") @resource_attributes.setter def resource_attributes(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]): pulumi.set(self,", "\"resource_attributes\", value) class UserDataMapping(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts:", "else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]", "each Attribute. \"\"\" return pulumi.get(self, \"resource_attributes\") @resource_attributes.setter def resource_attributes(self, value:", "doing! *** import warnings import pulumi import pulumi.runtime from typing", "resource. :param pulumi.Input[str] user_id: User's UUID provided by the client.", "value) @property @pulumi.getter(name=\"userId\") def user_id(self) -> pulumi.Input[str]: \"\"\" User's UUID", "def project(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"project\") @project.setter def project(self,", "explicitly set attributes are displayed here. Attribute definitions with defaults", "location is not None: pulumi.set(__self__, \"location\", location) if name is", "'UserDataMapping': \"\"\" Get an existing UserDataMapping resource's state with the", "in each Attribute. \"\"\" return pulumi.get(self, \"resource_attributes\") @property @pulumi.getter(name=\"userId\") def", "pulumi.get(self, \"location\") @location.setter def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"location\", value)", "@overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, consent_store_id:", "mapped resource. :param pulumi.Input[str] name: Resource name of the User", "__props__.__dict__[\"archived\"] = None __props__.__dict__[\"data_id\"] = None __props__.__dict__[\"name\"] = None __props__.__dict__[\"resource_attributes\"]", "pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]] resource_attributes: Attributes of the resource. Only explicitly set attributes", "is, exactly one value is specified for the field \"values\"", "resource. :param pulumi.Input[str] data_id: A unique identifier for the mapped", "resource_attributes) @property @pulumi.getter(name=\"consentStoreId\") def consent_store_id(self) -> pulumi.Input[str]: return pulumi.get(self, \"consent_store_id\")", "def location(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"location\") @location.setter def location(self,", "\"resource_attributes\") @resource_attributes.setter def resource_attributes(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]): pulumi.set(self, \"resource_attributes\", value) class", "is specified for the field \"values\" in each Attribute. :param", "def resource_attributes(self) -> pulumi.Output[Sequence['outputs.AttributeResponse']]: \"\"\" Attributes of the resource. Only", "@pulumi.getter(name=\"resourceAttributes\") def resource_attributes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]: \"\"\" Attributes of the resource.", "def resource_attributes(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]): pulumi.set(self, \"resource_attributes\", value) class UserDataMapping(pulumi.CustomResource): @overload", "data_id is None and not opts.urn: raise TypeError(\"Missing required property", "mapping in the parent consent store. :param str resource_name: The", "UserDataMappingArgs args: The arguments to use to populate this resource's", "the resource. Only explicitly set attributes are displayed here. Attribute", "must be single valued, that is, exactly one value is", "name, id, and optional extra properties used to qualify the", "is None and not opts.urn: raise TypeError(\"Missing required property 'dataset_id'\")", "__props__.__dict__[\"name\"] = name __props__.__dict__[\"project\"] = project __props__.__dict__[\"resource_attributes\"] = resource_attributes if", "project: Optional[pulumi.Input[str]] = None, resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]]] = None, user_id: Optional[pulumi.Input[str]]", "the Pulumi SDK Generator. *** # *** Do not edit", "instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id", "__props__.__dict__[\"data_id\"] = None __props__.__dict__[\"name\"] = None __props__.__dict__[\"resource_attributes\"] = None __props__.__dict__[\"user_id\"]", "opts.urn: raise TypeError(\"Missing required property 'data_id'\") __props__.__dict__[\"data_id\"] = data_id if", "the field \"values\" in each Attribute. :param pulumi.Input[str] user_id: User's", "exactly one value is specified for the field \"values\" in", "is not None: pulumi.set(__self__, \"resource_attributes\", resource_attributes) @property @pulumi.getter(name=\"consentStoreId\") def consent_store_id(self)", "\"dataset_id\", dataset_id) pulumi.set(__self__, \"user_id\", user_id) if location is not None:", "Optional, Sequence, Union, overload from ... import _utilities from .", "__init__(__self__, resource_name: str, args: UserDataMappingArgs, opts: Optional[pulumi.ResourceOptions] = None): \"\"\"", "pulumi.set(__self__, \"location\", location) if name is not None: pulumi.set(__self__, \"name\",", "this mapping was archived. \"\"\" return pulumi.get(self, \"archive_time\") @property @pulumi.getter", "in each Attribute. :param pulumi.Input[str] user_id: User's UUID provided by", "data_id(self) -> pulumi.Input[str]: \"\"\" A unique identifier for the mapped", "pulumi.get(self, \"dataset_id\") @dataset_id.setter def dataset_id(self, value: pulumi.Input[str]): pulumi.set(self, \"dataset_id\", value)", "arguments to use to populate this resource's properties. :param pulumi.ResourceOptions", "field \"values\" in each Attribute. :param pulumi.Input[str] user_id: User's UUID", "Options for the resource. \"\"\" ... def __init__(__self__, resource_name: str,", "client. \"\"\" return pulumi.get(self, \"user_id\") @user_id.setter def user_id(self, value: pulumi.Input[str]):", "None): \"\"\" Creates a new User data mapping in the", "*args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None,", "value) @property @pulumi.getter def project(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"project\")", "of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]] resource_attributes: Attributes of the", "'google-native:healthcare/v1beta1:UserDataMapping', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str],", "of the User data mapping, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param", "__all__ = ['UserDataMappingArgs', 'UserDataMapping'] @pulumi.input_type class UserDataMappingArgs: def __init__(__self__, *,", "this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource.", "._inputs import * __all__ = ['UserDataMappingArgs', 'UserDataMapping'] @pulumi.input_type class UserDataMappingArgs:", "User data mappings. Attributes listed here must be single valued,", "@property @pulumi.getter(name=\"dataId\") def data_id(self) -> pulumi.Output[str]: \"\"\" A unique identifier", "pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload", "= None, __props__=None): \"\"\" Creates a new User data mapping", "None, consent_store_id: Optional[pulumi.Input[str]] = None, data_id: Optional[pulumi.Input[str]] = None, dataset_id:", "from ._inputs import * __all__ = ['UserDataMappingArgs', 'UserDataMapping'] @pulumi.input_type class", "properties. :param pulumi.ResourceOptions opts: Options for the resource. \"\"\" ...", "opts.version = _utilities.get_version() if opts.id is None: if __props__ is", "opts: Options for the resource. \"\"\" opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))", "pulumi.ResourceOptions(id=id)) __props__ = UserDataMappingArgs.__new__(UserDataMappingArgs) __props__.__dict__[\"archive_time\"] = None __props__.__dict__[\"archived\"] = None", "required property 'consent_store_id'\") __props__.__dict__[\"consent_store_id\"] = consent_store_id if data_id is None", "pulumi.get(self, \"archive_time\") @property @pulumi.getter def archived(self) -> pulumi.Output[bool]: \"\"\" Indicates", "... @overload def __init__(__self__, resource_name: str, args: UserDataMappingArgs, opts: Optional[pulumi.ResourceOptions]", "client. \"\"\" ... @overload def __init__(__self__, resource_name: str, args: UserDataMappingArgs,", "None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__,", "lookup. :param str resource_name: The unique name of the resulting", "pulumi.Input[str] user_id: User's UUID provided by the client. :param pulumi.Input[str]", "mapping, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]] resource_attributes: Attributes of", "\"\"\" ... @overload def __init__(__self__, resource_name: str, args: UserDataMappingArgs, opts:", "return pulumi.get(self, \"name\") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\",", "opts.id is None: if __props__ is not None: raise TypeError('__props__", "here must be single valued, that is, exactly one value", "__props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]", "of arguments for constructing a UserDataMapping resource. :param pulumi.Input[str] data_id:", "The unique name of the resulting resource. :param pulumi.Input[str] id:", "consent_store_id: pulumi.Input[str], data_id: pulumi.Input[str], dataset_id: pulumi.Input[str], user_id: pulumi.Input[str], location: Optional[pulumi.Input[str]]", "__props__=None): \"\"\" Creates a new User data mapping in the", "existing resource') __props__ = UserDataMappingArgs.__new__(UserDataMappingArgs) if consent_store_id is None and", "opts.urn: raise TypeError(\"Missing required property 'dataset_id'\") __props__.__dict__[\"dataset_id\"] = dataset_id __props__.__dict__[\"location\"]", "resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]]] = None, user_id: Optional[pulumi.Input[str]] = None, __props__=None): \"\"\"", "@property @pulumi.getter def archived(self) -> pulumi.Output[bool]: \"\"\" Indicates whether this", "A unique identifier for the mapped resource. :param pulumi.Input[str] name:", "pulumi.set(__self__, \"user_id\", user_id) if location is not None: pulumi.set(__self__, \"location\",", "User data mapping, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. \"\"\" return pulumi.get(self,", "unique identifier for the mapped resource. :param pulumi.Input[str] user_id: User's", "for the field \"values\" in each Attribute. \"\"\" pulumi.set(__self__, \"consent_store_id\",", "attributes are displayed here. Attribute definitions with defaults set implicitly", "... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts =", "def data_id(self) -> pulumi.Input[str]: \"\"\" A unique identifier for the", "in the parent consent store. :param str resource_name: The name", "Mapping, Optional, Sequence, Union, overload from ... import _utilities from", "\"\"\" return pulumi.get(self, \"data_id\") @property @pulumi.getter def name(self) -> pulumi.Output[str]:", "is specified for the field \"values\" in each Attribute. \"\"\"", "opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] =", "= None return UserDataMapping(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name=\"archiveTime\") def archive_time(self)", "from typing import Any, Mapping, Optional, Sequence, Union, overload from", ":param pulumi.Input[str] user_id: User's UUID provided by the client. :param", ":param pulumi.Input[str] data_id: A unique identifier for the mapped resource.", "resource') __props__ = UserDataMappingArgs.__new__(UserDataMappingArgs) if consent_store_id is None and not", "return pulumi.get(self, \"resource_attributes\") @resource_attributes.setter def resource_attributes(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]): pulumi.set(self, \"resource_attributes\",", "WARNING: this file was generated by the Pulumi SDK Generator.", "\"\"\" return pulumi.get(self, \"resource_attributes\") @property @pulumi.getter(name=\"userId\") def user_id(self) -> pulumi.Output[str]:", "opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource", "import Any, Mapping, Optional, Sequence, Union, overload from ... import", "know what you are doing! *** import warnings import pulumi", "pulumi.set(__self__, \"name\", name) if project is not None: pulumi.set(__self__, \"project\",", "= ['UserDataMappingArgs', 'UserDataMapping'] @pulumi.input_type class UserDataMappingArgs: def __init__(__self__, *, consent_store_id:", "opts.urn: raise TypeError(\"Missing required property 'user_id'\") __props__.__dict__[\"user_id\"] = user_id __props__.__dict__[\"archive_time\"]", "@pulumi.getter(name=\"dataId\") def data_id(self) -> pulumi.Output[str]: \"\"\" A unique identifier for", "certain you know what you are doing! *** import warnings", "pulumi.Input[str]): pulumi.set(self, \"consent_store_id\", value) @property @pulumi.getter(name=\"dataId\") def data_id(self) -> pulumi.Input[str]:", "Attribute. :param pulumi.Input[str] user_id: User's UUID provided by the client.", "and not opts.urn: raise TypeError(\"Missing required property 'consent_store_id'\") __props__.__dict__[\"consent_store_id\"] =", "resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, consent_store_id: Optional[pulumi.Input[str]] = None,", "pulumi.set(self, \"dataset_id\", value) @property @pulumi.getter(name=\"userId\") def user_id(self) -> pulumi.Input[str]: \"\"\"", "qualify the lookup. :param str resource_name: The unique name of", "specified for the field \"values\" in each Attribute. \"\"\" return", "you're certain you know what you are doing! *** import", "@property @pulumi.getter(name=\"userId\") def user_id(self) -> pulumi.Output[str]: \"\"\" User's UUID provided", "coding=utf-8 # *** WARNING: this file was generated by the", "not None: pulumi.set(__self__, \"name\", name) if project is not None:", "pulumi.Output[str]: \"\"\" Resource name of the User data mapping, of", "the field \"values\" in each Attribute. \"\"\" pulumi.set(__self__, \"consent_store_id\", consent_store_id)", "if user_id is None and not opts.urn: raise TypeError(\"Missing required", "pulumi.Input[str] data_id: A unique identifier for the mapped resource. :param", "from ... import _utilities from . import outputs from ._inputs", ". import outputs from ._inputs import * __all__ = ['UserDataMappingArgs',", "UserDataMappingArgs.__new__(UserDataMappingArgs) if consent_store_id is None and not opts.urn: raise TypeError(\"Missing", "when this mapping was archived. \"\"\" return pulumi.get(self, \"archive_time\") @property", "pulumi.get(self, \"project\") @project.setter def project(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"project\", value)", "UUID provided by the client. \"\"\" ... @overload def __init__(__self__,", "an existing UserDataMapping resource's state with the given name, id,", "resource_name: str, args: UserDataMappingArgs, opts: Optional[pulumi.ResourceOptions] = None): \"\"\" Creates", "resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]]] = None, user_id: Optional[pulumi.Input[str]] = None, __props__=None): if", "file was generated by the Pulumi SDK Generator. *** #", "= UserDataMappingArgs.__new__(UserDataMappingArgs) if consent_store_id is None and not opts.urn: raise", "return pulumi.get(self, \"user_id\") @user_id.setter def user_id(self, value: pulumi.Input[str]): pulumi.set(self, \"user_id\",", "the resource. \"\"\" ... def __init__(__self__, resource_name: str, *args, **kwargs):", "value: pulumi.Input[str]): pulumi.set(self, \"user_id\", value) @property @pulumi.getter def location(self) ->", "*args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(UserDataMappingArgs, pulumi.ResourceOptions, *args, **kwargs) if", "not edit by hand unless you're certain you know what", "-> pulumi.Output[str]: \"\"\" A unique identifier for the mapped resource.", "is archived. \"\"\" return pulumi.get(self, \"archived\") @property @pulumi.getter(name=\"dataId\") def data_id(self)", "-> pulumi.Input[str]: \"\"\" A unique identifier for the mapped resource.", "\"name\") @property @pulumi.getter(name=\"resourceAttributes\") def resource_attributes(self) -> pulumi.Output[Sequence['outputs.AttributeResponse']]: \"\"\" Attributes of", "given name, id, and optional extra properties used to qualify", "from . import outputs from ._inputs import * __all__ =", "opts: Optional[pulumi.ResourceOptions] = None): \"\"\" Creates a new User data", "combination with a valid opts.id to get an existing resource')", "required property 'user_id'\") __props__.__dict__[\"user_id\"] = user_id __props__.__dict__[\"archive_time\"] = None __props__.__dict__[\"archived\"]", "pulumi.Output[Sequence['outputs.AttributeResponse']]: \"\"\" Attributes of the resource. Only explicitly set attributes", "... import _utilities from . import outputs from ._inputs import", "__props__.__dict__[\"archived\"] = None super(UserDataMapping, __self__).__init__( 'google-native:healthcare/v1beta1:UserDataMapping', resource_name, __props__, opts) @staticmethod", "consent_store_id if data_id is None and not opts.urn: raise TypeError(\"Missing", "\"consent_store_id\", value) @property @pulumi.getter(name=\"dataId\") def data_id(self) -> pulumi.Input[str]: \"\"\" A", "not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def", "# *** WARNING: this file was generated by the Pulumi", "TypeError('__props__ is only valid when passed in combination with a", ":param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]] resource_attributes: Attributes of the resource. Only explicitly set", "pulumi.Input[str]): pulumi.set(self, \"user_id\", value) @property @pulumi.getter def location(self) -> Optional[pulumi.Input[str]]:", "was generated by the Pulumi SDK Generator. *** # ***", "data_id if dataset_id is None and not opts.urn: raise TypeError(\"Missing", "Optional[pulumi.Input[str]] = None, dataset_id: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] =", "= None, data_id: Optional[pulumi.Input[str]] = None, dataset_id: Optional[pulumi.Input[str]] = None,", "listed here must be single valued, that is, exactly one", "for the resource. \"\"\" ... def __init__(__self__, resource_name: str, *args,", "if opts.version is None: opts.version = _utilities.get_version() if opts.id is", "return pulumi.get(self, \"archived\") @property @pulumi.getter(name=\"dataId\") def data_id(self) -> pulumi.Output[str]: \"\"\"", "client. :param pulumi.Input[str] name: Resource name of the User data", "Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] =", "\"dataset_id\") @dataset_id.setter def dataset_id(self, value: pulumi.Input[str]): pulumi.set(self, \"dataset_id\", value) @property", "\"\"\" User's UUID provided by the client. \"\"\" return pulumi.get(self,", "not None: pulumi.set(__self__, \"resource_attributes\", resource_attributes) @property @pulumi.getter(name=\"consentStoreId\") def consent_store_id(self) ->", "specified for the field \"values\" in each Attribute. \"\"\" pulumi.set(__self__,", "by hand unless you're certain you know what you are", "\"name\", name) if project is not None: pulumi.set(__self__, \"project\", project)", "\"\"\" A unique identifier for the mapped resource. \"\"\" return", "None, user_id: Optional[pulumi.Input[str]] = None, __props__=None): \"\"\" Creates a new", "data mapping, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]] resource_attributes: Attributes", "not None: raise TypeError('__props__ is only valid when passed in", "resource. :param pulumi.Input[str] id: The unique provider ID of the", "value is specified for the field \"values\" in each Attribute.", "mapping, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. \"\"\" return pulumi.get(self, \"name\") @property", "None, dataset_id: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, name:", "of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]] resource_attributes: Attributes of the", "opts=opts, __props__=__props__) @property @pulumi.getter(name=\"archiveTime\") def archive_time(self) -> pulumi.Output[str]: \"\"\" Indicates", "not opts.urn: raise TypeError(\"Missing required property 'consent_store_id'\") __props__.__dict__[\"consent_store_id\"] = consent_store_id", "for the mapped resource. :param pulumi.Input[str] user_id: User's UUID provided", "location(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"location\") @location.setter def location(self, value:", "None super(UserDataMapping, __self__).__init__( 'google-native:healthcare/v1beta1:UserDataMapping', resource_name, __props__, opts) @staticmethod def get(resource_name:", "used to qualify the lookup. :param str resource_name: The unique", "User's UUID provided by the client. :param pulumi.Input[str] name: Resource", "The arguments to use to populate this resource's properties. :param", "archived(self) -> pulumi.Output[bool]: \"\"\" Indicates whether this mapping is archived.", "__props__ = UserDataMappingArgs.__new__(UserDataMappingArgs) __props__.__dict__[\"archive_time\"] = None __props__.__dict__[\"archived\"] = None __props__.__dict__[\"data_id\"]", "= None, user_id: Optional[pulumi.Input[str]] = None, __props__=None): \"\"\" Creates a", "@name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter", "identifier for the mapped resource. :param pulumi.Input[str] name: Resource name", "<reponame>AaronFriel/pulumi-google-native # coding=utf-8 # *** WARNING: this file was generated", "you are doing! *** import warnings import pulumi import pulumi.runtime", "data_id: A unique identifier for the mapped resource. :param pulumi.Input[str]", "form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]] resource_attributes: Attributes of the resource. Only", "@pulumi.getter(name=\"dataId\") def data_id(self) -> pulumi.Input[str]: \"\"\" A unique identifier for", "raise TypeError(\"Missing required property 'consent_store_id'\") __props__.__dict__[\"consent_store_id\"] = consent_store_id if data_id", "return pulumi.get(self, \"data_id\") @data_id.setter def data_id(self, value: pulumi.Input[str]): pulumi.set(self, \"data_id\",", "= None __props__.__dict__[\"archived\"] = None __props__.__dict__[\"data_id\"] = None __props__.__dict__[\"name\"] =", "pulumi.Input[str] id: The unique provider ID of the resource to", "a new User data mapping in the parent consent store.", "mappings. Attributes listed here must be single valued, that is,", "in combination with a valid opts.id to get an existing", "resource_args, opts = _utilities.get_resource_args_opts(UserDataMappingArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is", "str, args: UserDataMappingArgs, opts: Optional[pulumi.ResourceOptions] = None): \"\"\" Creates a", "= project __props__.__dict__[\"resource_attributes\"] = resource_attributes if user_id is None and", "passed in combination with a valid opts.id to get an", "@property @pulumi.getter(name=\"userId\") def user_id(self) -> pulumi.Input[str]: \"\"\" User's UUID provided", "pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] data_id: A", "= name __props__.__dict__[\"project\"] = project __props__.__dict__[\"resource_attributes\"] = resource_attributes if user_id", "__props__.__dict__[\"dataset_id\"] = dataset_id __props__.__dict__[\"location\"] = location __props__.__dict__[\"name\"] = name __props__.__dict__[\"project\"]", "each Attribute. \"\"\" pulumi.set(__self__, \"consent_store_id\", consent_store_id) pulumi.set(__self__, \"data_id\", data_id) pulumi.set(__self__,", "__props__.__dict__[\"data_id\"] = data_id if dataset_id is None and not opts.urn:", "Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]): pulumi.set(self, \"resource_attributes\", value) class UserDataMapping(pulumi.CustomResource): @overload def __init__(__self__, resource_name:", "the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param", "pulumi.get(self, \"data_id\") @property @pulumi.getter def name(self) -> pulumi.Output[str]: \"\"\" Resource", "Optional[pulumi.Input[str]] = None, __props__=None): if opts is None: opts =", "not None: pulumi.set(__self__, \"location\", location) if name is not None:", "Optional[pulumi.ResourceOptions] = None, consent_store_id: Optional[pulumi.Input[str]] = None, data_id: Optional[pulumi.Input[str]] =", "archive_time(self) -> pulumi.Output[str]: \"\"\" Indicates the time when this mapping", "name) if project is not None: pulumi.set(__self__, \"project\", project) if", ":param UserDataMappingArgs args: The arguments to use to populate this", "consent_store_id(self, value: pulumi.Input[str]): pulumi.set(self, \"consent_store_id\", value) @property @pulumi.getter(name=\"dataId\") def data_id(self)", "\"\"\" opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = UserDataMappingArgs.__new__(UserDataMappingArgs) __props__.__dict__[\"archive_time\"] =", "optional extra properties used to qualify the lookup. :param str", "\"user_id\", user_id) if location is not None: pulumi.set(__self__, \"location\", location)", "is None and not opts.urn: raise TypeError(\"Missing required property 'data_id'\")", "for the mapped resource. :param pulumi.Input[str] name: Resource name of", "pulumi.set(self, \"name\", value) @property @pulumi.getter def project(self) -> Optional[pulumi.Input[str]]: return", "in each Attribute. \"\"\" return pulumi.get(self, \"resource_attributes\") @resource_attributes.setter def resource_attributes(self,", "-> pulumi.Input[str]: return pulumi.get(self, \"dataset_id\") @dataset_id.setter def dataset_id(self, value: pulumi.Input[str]):", "user_id) if location is not None: pulumi.set(__self__, \"location\", location) if", "Optional[pulumi.Input[str]] = None, project: Optional[pulumi.Input[str]] = None, resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]]] =", "if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts,", "@overload def __init__(__self__, resource_name: str, args: UserDataMappingArgs, opts: Optional[pulumi.ResourceOptions] =", "None and not opts.urn: raise TypeError(\"Missing required property 'data_id'\") __props__.__dict__[\"data_id\"]", "of the resource to lookup. :param pulumi.ResourceOptions opts: Options for", "\"\"\" return pulumi.get(self, \"archive_time\") @property @pulumi.getter def archived(self) -> pulumi.Output[bool]:", "UserDataMappingArgs.__new__(UserDataMappingArgs) __props__.__dict__[\"archive_time\"] = None __props__.__dict__[\"archived\"] = None __props__.__dict__[\"data_id\"] = None", "None: pulumi.set(__self__, \"location\", location) if name is not None: pulumi.set(__self__,", "Attribute. \"\"\" return pulumi.get(self, \"resource_attributes\") @property @pulumi.getter(name=\"userId\") def user_id(self) ->", "if data_id is None and not opts.urn: raise TypeError(\"Missing required", "\"\"\" return pulumi.get(self, \"archived\") @property @pulumi.getter(name=\"dataId\") def data_id(self) -> pulumi.Output[str]:", "name is not None: pulumi.set(__self__, \"name\", name) if project is", "Only explicitly set attributes are displayed here. Attribute definitions with", "data mapping in the parent consent store. :param str resource_name:", "resource_name: The name of the resource. :param UserDataMappingArgs args: The", "arguments for constructing a UserDataMapping resource. :param pulumi.Input[str] data_id: A", "@data_id.setter def data_id(self, value: pulumi.Input[str]): pulumi.set(self, \"data_id\", value) @property @pulumi.getter(name=\"datasetId\")", "resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str]", "def consent_store_id(self, value: pulumi.Input[str]): pulumi.set(self, \"consent_store_id\", value) @property @pulumi.getter(name=\"dataId\") def", "-> 'UserDataMapping': \"\"\" Get an existing UserDataMapping resource's state with", "Attributes listed here must be single valued, that is, exactly", "pulumi.set(self, \"consent_store_id\", value) @property @pulumi.getter(name=\"dataId\") def data_id(self) -> pulumi.Input[str]: \"\"\"", "properties used to qualify the lookup. :param str resource_name: The", "provided by the client. \"\"\" ... @overload def __init__(__self__, resource_name:", "@property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: \"\"\" Resource name of", "required property 'data_id'\") __props__.__dict__[\"data_id\"] = data_id if dataset_id is None", "property 'dataset_id'\") __props__.__dict__[\"dataset_id\"] = dataset_id __props__.__dict__[\"location\"] = location __props__.__dict__[\"name\"] =", "\"values\" in each Attribute. \"\"\" return pulumi.get(self, \"resource_attributes\") @property @pulumi.getter(name=\"userId\")", "@property @pulumi.getter(name=\"consentStoreId\") def consent_store_id(self) -> pulumi.Input[str]: return pulumi.get(self, \"consent_store_id\") @consent_store_id.setter", "unique identifier for the mapped resource. \"\"\" return pulumi.get(self, \"data_id\")", "with the given name, id, and optional extra properties used", "an existing resource') __props__ = UserDataMappingArgs.__new__(UserDataMappingArgs) if consent_store_id is None", "unique name of the resulting resource. :param pulumi.Input[str] id: The", "import pulumi import pulumi.runtime from typing import Any, Mapping, Optional,", "resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]] = None): \"\"\" The set of arguments for", "value: Optional[pulumi.Input[str]]): pulumi.set(self, \"location\", value) @property @pulumi.getter def name(self) ->", "Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]]] = None, user_id: Optional[pulumi.Input[str]] = None, __props__=None): if opts", "= None __props__.__dict__[\"data_id\"] = None __props__.__dict__[\"name\"] = None __props__.__dict__[\"resource_attributes\"] =", "pulumi.set(self, \"project\", value) @property @pulumi.getter(name=\"resourceAttributes\") def resource_attributes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]: \"\"\"", "Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]] = None): \"\"\" The set of arguments for constructing", "\"\"\" return pulumi.get(self, \"name\") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self,", "@property @pulumi.getter(name=\"dataId\") def data_id(self) -> pulumi.Input[str]: \"\"\" A unique identifier", "return pulumi.get(self, \"dataset_id\") @dataset_id.setter def dataset_id(self, value: pulumi.Input[str]): pulumi.set(self, \"dataset_id\",", "resource. :param pulumi.Input[str] name: Resource name of the User data", "= _utilities.get_resource_args_opts(UserDataMappingArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None:", "str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(UserDataMappingArgs, pulumi.ResourceOptions, *args, **kwargs)", "generated by the Pulumi SDK Generator. *** # *** Do", "if dataset_id is None and not opts.urn: raise TypeError(\"Missing required", "TypeError('Expected resource options to be a ResourceOptions instance') if opts.version", "@property @pulumi.getter(name=\"datasetId\") def dataset_id(self) -> pulumi.Input[str]: return pulumi.get(self, \"dataset_id\") @dataset_id.setter", "@pulumi.getter(name=\"datasetId\") def dataset_id(self) -> pulumi.Input[str]: return pulumi.get(self, \"dataset_id\") @dataset_id.setter def", "pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]] resource_attributes: Attributes of the resource. Only explicitly set attributes", "to be a ResourceOptions instance') if opts.version is None: opts.version", "\"location\", location) if name is not None: pulumi.set(__self__, \"name\", name)", "None and not opts.urn: raise TypeError(\"Missing required property 'user_id'\") __props__.__dict__[\"user_id\"]", "here. Attribute definitions with defaults set implicitly apply to these", "__self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] =", "Attribute definitions with defaults set implicitly apply to these User", "\"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"resourceAttributes\") def resource_attributes(self) -> pulumi.Output[Sequence['outputs.AttributeResponse']]:", "state with the given name, id, and optional extra properties", "\"values\" in each Attribute. :param pulumi.Input[str] user_id: User's UUID provided", "of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. \"\"\" return pulumi.get(self, \"name\") @name.setter def", ":param pulumi.Input[str] user_id: User's UUID provided by the client. \"\"\"", "name of the resulting resource. :param pulumi.Input[str] id: The unique", "= pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = UserDataMappingArgs.__new__(UserDataMappingArgs) __props__.__dict__[\"archive_time\"] = None __props__.__dict__[\"archived\"]", "one value is specified for the field \"values\" in each", "and optional extra properties used to qualify the lookup. :param", "None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected", ":param pulumi.Input[str] id: The unique provider ID of the resource", "Indicates whether this mapping is archived. \"\"\" return pulumi.get(self, \"archived\")", "str resource_name: The unique name of the resulting resource. :param", "dataset_id __props__.__dict__[\"location\"] = location __props__.__dict__[\"name\"] = name __props__.__dict__[\"project\"] = project", "Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]: \"\"\" Attributes of the resource. Only explicitly set attributes", "lookup. :param pulumi.ResourceOptions opts: Options for the resource. \"\"\" opts", "__props__.__dict__[\"resource_attributes\"] = None __props__.__dict__[\"user_id\"] = None return UserDataMapping(resource_name, opts=opts, __props__=__props__)", "'consent_store_id'\") __props__.__dict__[\"consent_store_id\"] = consent_store_id if data_id is None and not", "def __init__(__self__, resource_name: str, args: UserDataMappingArgs, opts: Optional[pulumi.ResourceOptions] = None):", "UserDataMappingArgs, opts: Optional[pulumi.ResourceOptions] = None): \"\"\" Creates a new User", "@pulumi.getter(name=\"consentStoreId\") def consent_store_id(self) -> pulumi.Input[str]: return pulumi.get(self, \"consent_store_id\") @consent_store_id.setter def", "Generator. *** # *** Do not edit by hand unless", "name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter def project(self)", "name: Optional[pulumi.Input[str]] = None, project: Optional[pulumi.Input[str]] = None, resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]]]", "None, resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AttributeArgs']]]]] = None, user_id: Optional[pulumi.Input[str]] = None, __props__=None):", "def dataset_id(self, value: pulumi.Input[str]): pulumi.set(self, \"dataset_id\", value) @property @pulumi.getter(name=\"userId\") def", "\"user_id\", value) @property @pulumi.getter def location(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self,", "value) @property @pulumi.getter def location(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"location\")", "return UserDataMapping(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name=\"archiveTime\") def archive_time(self) -> pulumi.Output[str]:", "@pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: \"\"\" Resource name of the", "Sequence, Union, overload from ... import _utilities from . import", "be single valued, that is, exactly one value is specified", "the User data mapping, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. \"\"\" return", "= None __props__.__dict__[\"resource_attributes\"] = None __props__.__dict__[\"user_id\"] = None return UserDataMapping(resource_name,", "if consent_store_id is None and not opts.urn: raise TypeError(\"Missing required", "value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: \"\"\" Resource name", "resource. \"\"\" opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = UserDataMappingArgs.__new__(UserDataMappingArgs) __props__.__dict__[\"archive_time\"]", "is None and not opts.urn: raise TypeError(\"Missing required property 'user_id'\")", "the mapped resource. :param pulumi.Input[str] name: Resource name of the", "UUID provided by the client. :param pulumi.Input[str] name: Resource name", "mapping was archived. \"\"\" return pulumi.get(self, \"archive_time\") @property @pulumi.getter def", "@property @pulumi.getter def location(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, \"location\") @location.setter", "are doing! *** import warnings import pulumi import pulumi.runtime from", "value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter def project(self) ->", "if resource_attributes is not None: pulumi.set(__self__, \"resource_attributes\", resource_attributes) @property @pulumi.getter(name=\"consentStoreId\")", "\"resource_attributes\", resource_attributes) @property @pulumi.getter(name=\"consentStoreId\") def consent_store_id(self) -> pulumi.Input[str]: return pulumi.get(self,", "= None, name: Optional[pulumi.Input[str]] = None, project: Optional[pulumi.Input[str]] = None,", ":param str resource_name: The name of the resource. :param UserDataMappingArgs", "pulumi.Output[str]: \"\"\" A unique identifier for the mapped resource. \"\"\"", "user_id __props__.__dict__[\"archive_time\"] = None __props__.__dict__[\"archived\"] = None super(UserDataMapping, __self__).__init__( 'google-native:healthcare/v1beta1:UserDataMapping',", "ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options", "@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None)", "resource_attributes(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]): pulumi.set(self, \"resource_attributes\", value) class UserDataMapping(pulumi.CustomResource): @overload def", "the client. \"\"\" return pulumi.get(self, \"user_id\") @user_id.setter def user_id(self, value:", "= None, project: Optional[pulumi.Input[str]] = None, resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]] = None):", "None and not opts.urn: raise TypeError(\"Missing required property 'consent_store_id'\") __props__.__dict__[\"consent_store_id\"]", "id: The unique provider ID of the resource to lookup.", "if project is not None: pulumi.set(__self__, \"project\", project) if resource_attributes", "Optional[pulumi.Input[str]]: \"\"\" Resource name of the User data mapping, of", "is None: opts.version = _utilities.get_version() if opts.id is None: if", "and not opts.urn: raise TypeError(\"Missing required property 'user_id'\") __props__.__dict__[\"user_id\"] =", "edit by hand unless you're certain you know what you", "pulumi.get(self, \"name\") @name.setter def name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value)", "user_id: Optional[pulumi.Input[str]] = None, __props__=None): \"\"\" Creates a new User", "if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be", "Options for the resource. \"\"\" opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__", "the mapped resource. \"\"\" return pulumi.get(self, \"data_id\") @property @pulumi.getter def", "The name of the resource. :param pulumi.ResourceOptions opts: Options for", "__props__ is not None: raise TypeError('__props__ is only valid when", "dataset_id: pulumi.Input[str], user_id: pulumi.Input[str], location: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]]", "for constructing a UserDataMapping resource. :param pulumi.Input[str] data_id: A unique", "class UserDataMapping(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] =", "defaults set implicitly apply to these User data mappings. Attributes", "pulumi.set(__self__, \"dataset_id\", dataset_id) pulumi.set(__self__, \"user_id\", user_id) if location is not", "return pulumi.get(self, \"project\") @project.setter def project(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"project\",", "\"project\", value) @property @pulumi.getter(name=\"resourceAttributes\") def resource_attributes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]: \"\"\" Attributes", "TypeError(\"Missing required property 'data_id'\") __props__.__dict__[\"data_id\"] = data_id if dataset_id is", "if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name,", "to these User data mappings. Attributes listed here must be", "Do not edit by hand unless you're certain you know", "pulumi.set(__self__, \"consent_store_id\", consent_store_id) pulumi.set(__self__, \"data_id\", data_id) pulumi.set(__self__, \"dataset_id\", dataset_id) pulumi.set(__self__,", "Optional[pulumi.Input[str]]: return pulumi.get(self, \"project\") @project.setter def project(self, value: Optional[pulumi.Input[str]]): pulumi.set(self,", "return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"resourceAttributes\") def resource_attributes(self) -> pulumi.Output[Sequence['outputs.AttributeResponse']]: \"\"\"", "displayed here. Attribute definitions with defaults set implicitly apply to", "None): \"\"\" The set of arguments for constructing a UserDataMapping", "pulumi.set(self, \"location\", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]: \"\"\"", "time when this mapping was archived. \"\"\" return pulumi.get(self, \"archive_time\")", "the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. \"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"resourceAttributes\") def", "pulumi.Input[str]: return pulumi.get(self, \"dataset_id\") @dataset_id.setter def dataset_id(self, value: pulumi.Input[str]): pulumi.set(self,", "valued, that is, exactly one value is specified for the", "-> pulumi.Output[Sequence['outputs.AttributeResponse']]: \"\"\" Attributes of the resource. Only explicitly set", "the field \"values\" in each Attribute. \"\"\" return pulumi.get(self, \"resource_attributes\")", "data_id) pulumi.set(__self__, \"dataset_id\", dataset_id) pulumi.set(__self__, \"user_id\", user_id) if location is", "\"\"\" Resource name of the User data mapping, of the", "project __props__.__dict__[\"resource_attributes\"] = resource_attributes if user_id is None and not", "Optional[pulumi.Input[str]]): pulumi.set(self, \"name\", value) @property @pulumi.getter def project(self) -> Optional[pulumi.Input[str]]:", "User data mapping in the parent consent store. :param str", "location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"location\", value) @property @pulumi.getter def name(self)", "None __props__.__dict__[\"archived\"] = None super(UserDataMapping, __self__).__init__( 'google-native:healthcare/v1beta1:UserDataMapping', resource_name, __props__, opts)", "@project.setter def project(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"project\", value) @property @pulumi.getter(name=\"resourceAttributes\")", "use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options", "def archived(self) -> pulumi.Output[bool]: \"\"\" Indicates whether this mapping is", "\"user_id\") @user_id.setter def user_id(self, value: pulumi.Input[str]): pulumi.set(self, \"user_id\", value) @property", "user_id is None and not opts.urn: raise TypeError(\"Missing required property", "is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise", "and not opts.urn: raise TypeError(\"Missing required property 'dataset_id'\") __props__.__dict__[\"dataset_id\"] =", "# *** Do not edit by hand unless you're certain", "None and not opts.urn: raise TypeError(\"Missing required property 'dataset_id'\") __props__.__dict__[\"dataset_id\"]", "typing import Any, Mapping, Optional, Sequence, Union, overload from ...", "A unique identifier for the mapped resource. \"\"\" return pulumi.get(self,", "Creates a new User data mapping in the parent consent", "**kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else:", "the resource. :param pulumi.Input[str] data_id: A unique identifier for the", "UserDataMapping resource's state with the given name, id, and optional", "the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. \"\"\" return pulumi.get(self, \"name\") @name.setter def name(self,", "__init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(UserDataMappingArgs, pulumi.ResourceOptions,", "__props__.__dict__[\"user_id\"] = None return UserDataMapping(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name=\"archiveTime\") def", "pulumi.get(self, \"resource_attributes\") @resource_attributes.setter def resource_attributes(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]]): pulumi.set(self, \"resource_attributes\", value)", "value: pulumi.Input[str]): pulumi.set(self, \"data_id\", value) @property @pulumi.getter(name=\"datasetId\") def dataset_id(self) ->", "def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, consent_store_id: Optional[pulumi.Input[str]]", "to qualify the lookup. :param str resource_name: The unique name", "the lookup. :param str resource_name: The unique name of the", "resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts:", "of the resulting resource. :param pulumi.Input[str] id: The unique provider", "@pulumi.getter def name(self) -> pulumi.Output[str]: \"\"\" Resource name of the", "user_id(self, value: pulumi.Input[str]): pulumi.set(self, \"user_id\", value) @property @pulumi.getter def location(self)", "isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions", "resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options", "\"data_id\") @data_id.setter def data_id(self, value: pulumi.Input[str]): pulumi.set(self, \"data_id\", value) @property", "User's UUID provided by the client. \"\"\" ... @overload def", "Optional[pulumi.Input[str]]: return pulumi.get(self, \"location\") @location.setter def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self,", "value: pulumi.Input[str]): pulumi.set(self, \"consent_store_id\", value) @property @pulumi.getter(name=\"dataId\") def data_id(self) ->", "the mapped resource. :param pulumi.Input[str] user_id: User's UUID provided by", "__props__.__dict__[\"user_id\"] = user_id __props__.__dict__[\"archive_time\"] = None __props__.__dict__[\"archived\"] = None super(UserDataMapping,", "not opts.urn: raise TypeError(\"Missing required property 'data_id'\") __props__.__dict__[\"data_id\"] = data_id", "SDK Generator. *** # *** Do not edit by hand", "mapping is archived. \"\"\" return pulumi.get(self, \"archived\") @property @pulumi.getter(name=\"dataId\") def", "resource. Only explicitly set attributes are displayed here. Attribute definitions", "UUID provided by the client. \"\"\" return pulumi.get(self, \"user_id\") @user_id.setter", "not opts.urn: raise TypeError(\"Missing required property 'dataset_id'\") __props__.__dict__[\"dataset_id\"] = dataset_id", "get an existing resource') __props__ = UserDataMappingArgs.__new__(UserDataMappingArgs) if consent_store_id is", ":param pulumi.ResourceOptions opts: Options for the resource. \"\"\" opts =", "if location is not None: pulumi.set(__self__, \"location\", location) if name", "return pulumi.get(self, \"location\") @location.setter def location(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, \"location\",", "\"\"\" Get an existing UserDataMapping resource's state with the given", "None: pulumi.set(__self__, \"name\", name) if project is not None: pulumi.set(__self__,", "pulumi.get(self, \"data_id\") @data_id.setter def data_id(self, value: pulumi.Input[str]): pulumi.set(self, \"data_id\", value)", "pulumi.get(self, \"consent_store_id\") @consent_store_id.setter def consent_store_id(self, value: pulumi.Input[str]): pulumi.set(self, \"consent_store_id\", value)", "project) if resource_attributes is not None: pulumi.set(__self__, \"resource_attributes\", resource_attributes) @property", "return pulumi.get(self, \"consent_store_id\") @consent_store_id.setter def consent_store_id(self, value: pulumi.Input[str]): pulumi.set(self, \"consent_store_id\",", "= _utilities.get_version() if opts.id is None: if __props__ is not", "with defaults set implicitly apply to these User data mappings.", "pulumi.Input[str]): pulumi.set(self, \"data_id\", value) @property @pulumi.getter(name=\"datasetId\") def dataset_id(self) -> pulumi.Input[str]:", "for the field \"values\" in each Attribute. :param pulumi.Input[str] user_id:", "None: if __props__ is not None: raise TypeError('__props__ is only", "is only valid when passed in combination with a valid", "of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. \"\"\" return pulumi.get(self, \"name\") @property @pulumi.getter(name=\"resourceAttributes\")", "the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. :param pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]] resource_attributes: Attributes of the resource.", "'data_id'\") __props__.__dict__[\"data_id\"] = data_id if dataset_id is None and not", "pulumi.set(self, \"data_id\", value) @property @pulumi.getter(name=\"datasetId\") def dataset_id(self) -> pulumi.Input[str]: return", "identifier for the mapped resource. :param pulumi.Input[str] user_id: User's UUID", "resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. \"\"\"", "Optional[pulumi.Input[str]] = None, resource_attributes: Optional[pulumi.Input[Sequence[pulumi.Input['AttributeArgs']]]] = None): \"\"\" The set", "user_id(self) -> pulumi.Output[str]: \"\"\" User's UUID provided by the client.", "str, opts: Optional[pulumi.ResourceOptions] = None, consent_store_id: Optional[pulumi.Input[str]] = None, data_id:", "pulumi.Input[str], dataset_id: pulumi.Input[str], user_id: pulumi.Input[str], location: Optional[pulumi.Input[str]] = None, name:", "by the Pulumi SDK Generator. *** # *** Do not", "= dataset_id __props__.__dict__[\"location\"] = location __props__.__dict__[\"name\"] = name __props__.__dict__[\"project\"] =", "= None, dataset_id: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None,", "is not None: pulumi.set(__self__, \"project\", project) if resource_attributes is not", "resource. :param UserDataMappingArgs args: The arguments to use to populate", "pulumi.set(self, \"user_id\", value) @property @pulumi.getter def location(self) -> Optional[pulumi.Input[str]]: return", "\"name\", value) @property @pulumi.getter def project(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self,", "raise TypeError('__props__ is only valid when passed in combination with", "None, data_id: Optional[pulumi.Input[str]] = None, dataset_id: Optional[pulumi.Input[str]] = None, location:", "return pulumi.get(self, \"archive_time\") @property @pulumi.getter def archived(self) -> pulumi.Output[bool]: \"\"\"", "_internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, consent_store_id: Optional[pulumi.Input[str]] =", "A unique identifier for the mapped resource. :param pulumi.Input[str] user_id:", "Attribute. \"\"\" pulumi.set(__self__, \"consent_store_id\", consent_store_id) pulumi.set(__self__, \"data_id\", data_id) pulumi.set(__self__, \"dataset_id\",", "pulumi.Input[str]: \"\"\" User's UUID provided by the client. \"\"\" return", "resource. \"\"\" return pulumi.get(self, \"data_id\") @data_id.setter def data_id(self, value: pulumi.Input[str]):", "Optional[pulumi.Input[str]]): pulumi.set(self, \"location\", value) @property @pulumi.getter def name(self) -> Optional[pulumi.Input[str]]:", "pulumi.Input[str]): pulumi.set(self, \"dataset_id\", value) @property @pulumi.getter(name=\"userId\") def user_id(self) -> pulumi.Input[str]:", "outputs from ._inputs import * __all__ = ['UserDataMappingArgs', 'UserDataMapping'] @pulumi.input_type", "a valid opts.id to get an existing resource') __props__ =", "= None __props__.__dict__[\"user_id\"] = None return UserDataMapping(resource_name, opts=opts, __props__=__props__) @property", "of the User data mapping, of the form `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/consentStores/{consent_store_id}/userDataMappings/{user_data_mapping_id}`. \"\"\"", "TypeError(\"Missing required property 'user_id'\") __props__.__dict__[\"user_id\"] = user_id __props__.__dict__[\"archive_time\"] = None", "None: raise TypeError('__props__ is only valid when passed in combination", "is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs)", "resource. \"\"\" ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args,", "Get an existing UserDataMapping resource's state with the given name,", "def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, consent_store_id: Optional[pulumi.Input[str]]", "location: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, project: Optional[pulumi.Input[str]]", "None __props__.__dict__[\"data_id\"] = None __props__.__dict__[\"name\"] = None __props__.__dict__[\"resource_attributes\"] = None", "pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts,", ":param pulumi.Input[str] name: Resource name of the User data mapping,", "__self__).__init__( 'google-native:healthcare/v1beta1:UserDataMapping', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id:", "__props__=__props__) @property @pulumi.getter(name=\"archiveTime\") def archive_time(self) -> pulumi.Output[str]: \"\"\" Indicates the", "id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'UserDataMapping': \"\"\" Get", "@property @pulumi.getter(name=\"archiveTime\") def archive_time(self) -> pulumi.Output[str]: \"\"\" Indicates the time", "None: opts.version = _utilities.get_version() if opts.id is None: if __props__", ":param str resource_name: The name of the resource. :param pulumi.ResourceOptions", "whether this mapping is archived. \"\"\" return pulumi.get(self, \"archived\") @property", "provided by the client. \"\"\" return pulumi.get(self, \"user_id\") @user_id.setter def", "of the resource. :param UserDataMappingArgs args: The arguments to use", "pulumi.get(self, \"archived\") @property @pulumi.getter(name=\"dataId\") def data_id(self) -> pulumi.Output[str]: \"\"\" A", "**kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, consent_store_id:" ]
[ "import sphinx_rtd_theme source_path = os.path.normpath( os.path.join( os.path.abspath( os.path.split(__file__)[0]))) try: from", "'phdoc_static')] html_static_path = [os.path.join(source_path, 'phdoc_static')] if not os.path.exists(templates_path[0]): raise FileNotFoundError(templates_path[0])", "= [os.path.join(source_path, 'phdoc_static')] html_static_path = [os.path.join(source_path, 'phdoc_static')] if not os.path.exists(templates_path[0]):", "conf_base import * html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] templates_path", "= os.path.normpath( os.path.join( os.path.abspath( os.path.split(__file__)[0]))) try: from conf_base import *", "ImportError: sys.path.append(source_path) from conf_base import * html_theme = 'sphinx_rtd_theme' html_theme_path", "[os.path.join(source_path, 'phdoc_static')] if not os.path.exists(templates_path[0]): raise FileNotFoundError(templates_path[0]) blog_root = \"http://www.xavierdupre.fr/app/ensae_teaching_cs/helpsphinx3/\"", "html_static_path = [os.path.join(source_path, 'phdoc_static')] if not os.path.exists(templates_path[0]): raise FileNotFoundError(templates_path[0]) blog_root", "sphinx_rtd_theme source_path = os.path.normpath( os.path.join( os.path.abspath( os.path.split(__file__)[0]))) try: from conf_base", "except ImportError: sys.path.append(source_path) from conf_base import * html_theme = 'sphinx_rtd_theme'", "import * except ImportError: sys.path.append(source_path) from conf_base import * html_theme", "html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] templates_path = [os.path.join(source_path, 'phdoc_static')] html_static_path = [os.path.join(source_path,", "import sys import os import sphinx_rtd_theme source_path = os.path.normpath( os.path.join(", "source_path = os.path.normpath( os.path.join( os.path.abspath( os.path.split(__file__)[0]))) try: from conf_base import", "os.path.normpath( os.path.join( os.path.abspath( os.path.split(__file__)[0]))) try: from conf_base import * except", "sys.path.append(source_path) from conf_base import * html_theme = 'sphinx_rtd_theme' html_theme_path =", "= [os.path.join(source_path, 'phdoc_static')] if not os.path.exists(templates_path[0]): raise FileNotFoundError(templates_path[0]) blog_root =", "[os.path.join(source_path, 'phdoc_static')] html_static_path = [os.path.join(source_path, 'phdoc_static')] if not os.path.exists(templates_path[0]): raise", "* html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] templates_path = [os.path.join(source_path,", "os.path.abspath( os.path.split(__file__)[0]))) try: from conf_base import * except ImportError: sys.path.append(source_path)", "[sphinx_rtd_theme.get_html_theme_path()] templates_path = [os.path.join(source_path, 'phdoc_static')] html_static_path = [os.path.join(source_path, 'phdoc_static')] if", "import * html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] templates_path =", "= [sphinx_rtd_theme.get_html_theme_path()] templates_path = [os.path.join(source_path, 'phdoc_static')] html_static_path = [os.path.join(source_path, 'phdoc_static')]", "= 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] templates_path = [os.path.join(source_path, 'phdoc_static')] html_static_path", "os import sphinx_rtd_theme source_path = os.path.normpath( os.path.join( os.path.abspath( os.path.split(__file__)[0]))) try:", "'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] templates_path = [os.path.join(source_path, 'phdoc_static')] html_static_path =", "from conf_base import * html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]", "sys import os import sphinx_rtd_theme source_path = os.path.normpath( os.path.join( os.path.abspath(", "templates_path = [os.path.join(source_path, 'phdoc_static')] html_static_path = [os.path.join(source_path, 'phdoc_static')] if not", "html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] templates_path = [os.path.join(source_path, 'phdoc_static')]", "try: from conf_base import * except ImportError: sys.path.append(source_path) from conf_base", "* except ImportError: sys.path.append(source_path) from conf_base import * html_theme =", "conf_base import * except ImportError: sys.path.append(source_path) from conf_base import *", "os.path.split(__file__)[0]))) try: from conf_base import * except ImportError: sys.path.append(source_path) from", "from conf_base import * except ImportError: sys.path.append(source_path) from conf_base import", "os.path.join( os.path.abspath( os.path.split(__file__)[0]))) try: from conf_base import * except ImportError:", "import os import sphinx_rtd_theme source_path = os.path.normpath( os.path.join( os.path.abspath( os.path.split(__file__)[0])))" ]
[ "systems | +-----------------------------------+-----------------------------------------+ | :mod:`motion <dolfyn.adv.rotate>` | A module containing", "format. | +-----------------------------------+-----------------------------------------+ | :func:`~dolfyn.adv.base.mmload` | A function for loading", "| | | different coordinate systems | +-----------------------------------+-----------------------------------------+ | :mod:`motion", "from . import clean from ..io.nortek import read_nortek from .", "+-----------------------------------+-----------------------------------------+ Examples -------- .. literalinclude:: ../examples/adv_example01.py \"\"\" from .base import", "functions for performing motion | | | correction. | +-----------------------------------+-----------------------------------------+", "Vector | | read_nortek` | files. | +-----------------------------------+-----------------------------------------+ | :mod:`rotate", "statistics. | +-----------------------------------+-----------------------------------------+ Examples -------- .. literalinclude:: ../examples/adv_example01.py \"\"\" from", "in | | | DOLfYN format. | +-----------------------------------+-----------------------------------------+ | :func:`~dolfyn.adv.base.mmload`", "with adv data. It contains: +-----------------------------------+-----------------------------------------+ | Name | Description", "| :func:`~dolfyn.adv.base.mmload` | A function for loading ADV data in", "| | | various turbulence statistics. | +-----------------------------------+-----------------------------------------+ Examples --------", "module contains routines for reading and working with adv data.", "adv data between | | | different coordinate systems |", "arrays).| +-----------------------------------+-----------------------------------------+ | :func:`~dolfyn.io.nortek.\\ | A function for reading Nortek", "| A function for loading ADV data in | |", "<filename>dolfyn/adv/api.py \"\"\" This module contains routines for reading and working", "into | | adv.turbulence.TurbBinner` | 'bins', averaging it and estimating", "data. It contains: +-----------------------------------+-----------------------------------------+ | Name | Description | +===================================+=========================================+", "for performing motion | | | correction. | +-----------------------------------+-----------------------------------------+ |", "| correction. | +-----------------------------------+-----------------------------------------+ | :class:`~dolfyn.\\ | A class for", "..io.nortek import read_nortek from . import rotate from . import", ". import clean from ..io.nortek import read_nortek from . import", "\"\"\" This module contains routines for reading and working with", "module containing classes and | | | functions for rotating", "| | functions for rotating adv data between | |", "A function for loading ADV data in | | |", "| 'bins', averaging it and estimating | | | various", "+-----------------------------------+-----------------------------------------+ | Name | Description | +===================================+=========================================+ | :func:`~dolfyn.adv.base.load` |", "TurbBinner from . import clean from ..io.nortek import read_nortek from", "classes and | | | functions for performing motion |", "| A function for reading Nortek Vector | | read_nortek`", "| | read_nortek` | files. | +-----------------------------------+-----------------------------------------+ | :mod:`rotate <dolfyn.adv.rotate>`", "(as memory mapped arrays).| +-----------------------------------+-----------------------------------------+ | :func:`~dolfyn.io.nortek.\\ | A function", "in | | | DOLfYN format (as memory mapped arrays).|", "| adv.turbulence.TurbBinner` | 'bins', averaging it and estimating | |", "mmload from .turbulence import TurbBinner from . import clean from", "\"\"\" from .base import load, mmload from .turbulence import TurbBinner", "contains: +-----------------------------------+-----------------------------------------+ | Name | Description | +===================================+=========================================+ | :func:`~dolfyn.adv.base.load`", "| | DOLfYN format. | +-----------------------------------+-----------------------------------------+ | :func:`~dolfyn.adv.base.mmload` | A", "breaking ADV data into | | adv.turbulence.TurbBinner` | 'bins', averaging", "adv.turbulence.TurbBinner` | 'bins', averaging it and estimating | | |", "| +-----------------------------------+-----------------------------------------+ | :mod:`rotate <dolfyn.adv.rotate>` | A module containing classes", "| DOLfYN format. | +-----------------------------------+-----------------------------------------+ | :func:`~dolfyn.adv.base.mmload` | A function", ":mod:`motion <dolfyn.adv.rotate>` | A module containing classes and | |", "| | | DOLfYN format (as memory mapped arrays).| +-----------------------------------+-----------------------------------------+", "| DOLfYN format (as memory mapped arrays).| +-----------------------------------+-----------------------------------------+ | :func:`~dolfyn.io.nortek.\\", "class for breaking ADV data into | | adv.turbulence.TurbBinner` |", "| | adv.turbulence.TurbBinner` | 'bins', averaging it and estimating |", "../examples/adv_example01.py \"\"\" from .base import load, mmload from .turbulence import", "| | various turbulence statistics. | +-----------------------------------+-----------------------------------------+ Examples -------- ..", "loading ADV data in | | | DOLfYN format (as", "load, mmload from .turbulence import TurbBinner from . import clean", "from .base import load, mmload from .turbulence import TurbBinner from", "coordinate systems | +-----------------------------------+-----------------------------------------+ | :mod:`motion <dolfyn.adv.rotate>` | A module", ":func:`~dolfyn.adv.base.load` | A function for loading ADV data in |", "| :mod:`rotate <dolfyn.adv.rotate>` | A module containing classes and |", "routines for reading and working with adv data. It contains:", "| | | correction. | +-----------------------------------+-----------------------------------------+ | :class:`~dolfyn.\\ | A", "| | DOLfYN format (as memory mapped arrays).| +-----------------------------------+-----------------------------------------+ |", "it and estimating | | | various turbulence statistics. |", "format (as memory mapped arrays).| +-----------------------------------+-----------------------------------------+ | :func:`~dolfyn.io.nortek.\\ | A", "reading and working with adv data. It contains: +-----------------------------------+-----------------------------------------+ |", "| +-----------------------------------+-----------------------------------------+ Examples -------- .. literalinclude:: ../examples/adv_example01.py \"\"\" from .base", "| functions for performing motion | | | correction. |", "A function for reading Nortek Vector | | read_nortek` |", "motion | | | correction. | +-----------------------------------+-----------------------------------------+ | :class:`~dolfyn.\\ |", "for loading ADV data in | | | DOLfYN format", "+-----------------------------------+-----------------------------------------+ | :mod:`motion <dolfyn.adv.rotate>` | A module containing classes and", "clean from ..io.nortek import read_nortek from . import rotate from", ":mod:`rotate <dolfyn.adv.rotate>` | A module containing classes and | |", "function for reading Nortek Vector | | read_nortek` | files.", "It contains: +-----------------------------------+-----------------------------------------+ | Name | Description | +===================================+=========================================+ |", "classes and | | | functions for rotating adv data", "read_nortek` | files. | +-----------------------------------+-----------------------------------------+ | :mod:`rotate <dolfyn.adv.rotate>` | A", ":class:`~dolfyn.\\ | A class for breaking ADV data into |", "adv data. It contains: +-----------------------------------+-----------------------------------------+ | Name | Description |", "and | | | functions for performing motion | |", "between | | | different coordinate systems | +-----------------------------------+-----------------------------------------+ |", ".turbulence import TurbBinner from . import clean from ..io.nortek import", "ADV data into | | adv.turbulence.TurbBinner` | 'bins', averaging it", "| +-----------------------------------+-----------------------------------------+ | :func:`~dolfyn.adv.base.mmload` | A function for loading ADV", "A module containing classes and | | | functions for", "DOLfYN format (as memory mapped arrays).| +-----------------------------------+-----------------------------------------+ | :func:`~dolfyn.io.nortek.\\ |", "-------- .. literalinclude:: ../examples/adv_example01.py \"\"\" from .base import load, mmload", "| | different coordinate systems | +-----------------------------------+-----------------------------------------+ | :mod:`motion <dolfyn.adv.rotate>`", "loading ADV data in | | | DOLfYN format. |", "| :func:`~dolfyn.io.nortek.\\ | A function for reading Nortek Vector |", "| | | functions for rotating adv data between |", "A class for breaking ADV data into | | adv.turbulence.TurbBinner`", "function for loading ADV data in | | | DOLfYN", ".. literalinclude:: ../examples/adv_example01.py \"\"\" from .base import load, mmload from", "data into | | adv.turbulence.TurbBinner` | 'bins', averaging it and", "for rotating adv data between | | | different coordinate", "different coordinate systems | +-----------------------------------+-----------------------------------------+ | :mod:`motion <dolfyn.adv.rotate>` | A", "import read_nortek from . import rotate from . import motion", "and estimating | | | various turbulence statistics. | +-----------------------------------+-----------------------------------------+", "| functions for rotating adv data between | | |", "performing motion | | | correction. | +-----------------------------------+-----------------------------------------+ | :class:`~dolfyn.\\", "for reading and working with adv data. It contains: +-----------------------------------+-----------------------------------------+", "and | | | functions for rotating adv data between", "correction. | +-----------------------------------+-----------------------------------------+ | :class:`~dolfyn.\\ | A class for breaking", "| +-----------------------------------+-----------------------------------------+ | :class:`~dolfyn.\\ | A class for breaking ADV", "| +===================================+=========================================+ | :func:`~dolfyn.adv.base.load` | A function for loading ADV", "| | correction. | +-----------------------------------+-----------------------------------------+ | :class:`~dolfyn.\\ | A class", "Description | +===================================+=========================================+ | :func:`~dolfyn.adv.base.load` | A function for loading", "<dolfyn.adv.rotate>` | A module containing classes and | | |", "from ..io.nortek import read_nortek from . import rotate from .", "Examples -------- .. literalinclude:: ../examples/adv_example01.py \"\"\" from .base import load,", "import clean from ..io.nortek import read_nortek from . import rotate", "memory mapped arrays).| +-----------------------------------+-----------------------------------------+ | :func:`~dolfyn.io.nortek.\\ | A function for", "| read_nortek` | files. | +-----------------------------------+-----------------------------------------+ | :mod:`rotate <dolfyn.adv.rotate>` |", "| files. | +-----------------------------------+-----------------------------------------+ | :mod:`rotate <dolfyn.adv.rotate>` | A module", "This module contains routines for reading and working with adv", "from .turbulence import TurbBinner from . import clean from ..io.nortek", "for loading ADV data in | | | DOLfYN format.", "+-----------------------------------+-----------------------------------------+ | :func:`~dolfyn.io.nortek.\\ | A function for reading Nortek Vector", ":func:`~dolfyn.io.nortek.\\ | A function for reading Nortek Vector | |", "| | | functions for performing motion | | |", "| | functions for performing motion | | | correction.", "containing classes and | | | functions for performing motion", "averaging it and estimating | | | various turbulence statistics.", "'bins', averaging it and estimating | | | various turbulence", "literalinclude:: ../examples/adv_example01.py \"\"\" from .base import load, mmload from .turbulence", "| +-----------------------------------+-----------------------------------------+ | :mod:`motion <dolfyn.adv.rotate>` | A module containing classes", "estimating | | | various turbulence statistics. | +-----------------------------------+-----------------------------------------+ Examples", "turbulence statistics. | +-----------------------------------+-----------------------------------------+ Examples -------- .. literalinclude:: ../examples/adv_example01.py \"\"\"", "+===================================+=========================================+ | :func:`~dolfyn.adv.base.load` | A function for loading ADV data", "functions for rotating adv data between | | | different", "for reading Nortek Vector | | read_nortek` | files. |", "module containing classes and | | | functions for performing", "import load, mmload from .turbulence import TurbBinner from . import", "+-----------------------------------+-----------------------------------------+ | :func:`~dolfyn.adv.base.mmload` | A function for loading ADV data", "import TurbBinner from . import clean from ..io.nortek import read_nortek", "mapped arrays).| +-----------------------------------+-----------------------------------------+ | :func:`~dolfyn.io.nortek.\\ | A function for reading", "+-----------------------------------+-----------------------------------------+ | :mod:`rotate <dolfyn.adv.rotate>` | A module containing classes and", "| :mod:`motion <dolfyn.adv.rotate>` | A module containing classes and |", "contains routines for reading and working with adv data. It", "| Description | +===================================+=========================================+ | :func:`~dolfyn.adv.base.load` | A function for", "| A module containing classes and | | | functions", "and working with adv data. It contains: +-----------------------------------+-----------------------------------------+ | Name", "Name | Description | +===================================+=========================================+ | :func:`~dolfyn.adv.base.load` | A function", "ADV data in | | | DOLfYN format (as memory", "containing classes and | | | functions for rotating adv", "| :func:`~dolfyn.adv.base.load` | A function for loading ADV data in", "reading Nortek Vector | | read_nortek` | files. | +-----------------------------------+-----------------------------------------+", "data between | | | different coordinate systems | +-----------------------------------+-----------------------------------------+", "for breaking ADV data into | | adv.turbulence.TurbBinner` | 'bins',", ":func:`~dolfyn.adv.base.mmload` | A function for loading ADV data in |", "| different coordinate systems | +-----------------------------------+-----------------------------------------+ | :mod:`motion <dolfyn.adv.rotate>` |", "Nortek Vector | | read_nortek` | files. | +-----------------------------------+-----------------------------------------+ |", "DOLfYN format. | +-----------------------------------+-----------------------------------------+ | :func:`~dolfyn.adv.base.mmload` | A function for", "data in | | | DOLfYN format (as memory mapped", "ADV data in | | | DOLfYN format. | +-----------------------------------+-----------------------------------------+", "| | | DOLfYN format. | +-----------------------------------+-----------------------------------------+ | :func:`~dolfyn.adv.base.mmload` |", ".base import load, mmload from .turbulence import TurbBinner from .", "| A class for breaking ADV data into | |", "files. | +-----------------------------------+-----------------------------------------+ | :mod:`rotate <dolfyn.adv.rotate>` | A module containing", "various turbulence statistics. | +-----------------------------------+-----------------------------------------+ Examples -------- .. literalinclude:: ../examples/adv_example01.py", "+-----------------------------------+-----------------------------------------+ | :class:`~dolfyn.\\ | A class for breaking ADV data", "data in | | | DOLfYN format. | +-----------------------------------+-----------------------------------------+ |", "| Name | Description | +===================================+=========================================+ | :func:`~dolfyn.adv.base.load` | A", "| :class:`~dolfyn.\\ | A class for breaking ADV data into", "rotating adv data between | | | different coordinate systems", "working with adv data. It contains: +-----------------------------------+-----------------------------------------+ | Name |", "| various turbulence statistics. | +-----------------------------------+-----------------------------------------+ Examples -------- .. literalinclude::" ]
[ "operations = [ migrations.AlterField( model_name='task', name='author', field=models.CharField(default='Anonymous', max_length=100), ), migrations.AlterField(", "[ migrations.AlterField( model_name='task', name='author', field=models.CharField(default='Anonymous', max_length=100), ), migrations.AlterField( model_name='task', name='deadline',", "model_name='task', name='author', field=models.CharField(default='Anonymous', max_length=100), ), migrations.AlterField( model_name='task', name='deadline', field=models.DateTimeField(default='2020-10-11 10:53'),", "class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations =", "by Django 3.1.2 on 2020-10-11 10:53 from django.db import migrations,", "Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations = [", "name='author', field=models.CharField(default='Anonymous', max_length=100), ), migrations.AlterField( model_name='task', name='deadline', field=models.DateTimeField(default='2020-10-11 10:53'), ),", "dependencies = [ ('api', '0001_initial'), ] operations = [ migrations.AlterField(", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'),", "[ ('api', '0001_initial'), ] operations = [ migrations.AlterField( model_name='task', name='author',", "migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ]", "10:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "models class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "('api', '0001_initial'), ] operations = [ migrations.AlterField( model_name='task', name='author', field=models.CharField(default='Anonymous',", "3.1.2 on 2020-10-11 10:53 from django.db import migrations, models class", "= [ migrations.AlterField( model_name='task', name='author', field=models.CharField(default='Anonymous', max_length=100), ), migrations.AlterField( model_name='task',", "Generated by Django 3.1.2 on 2020-10-11 10:53 from django.db import", "# Generated by Django 3.1.2 on 2020-10-11 10:53 from django.db", "] operations = [ migrations.AlterField( model_name='task', name='author', field=models.CharField(default='Anonymous', max_length=100), ),", "migrations.AlterField( model_name='task', name='author', field=models.CharField(default='Anonymous', max_length=100), ), migrations.AlterField( model_name='task', name='deadline', field=models.DateTimeField(default='2020-10-11", "= [ ('api', '0001_initial'), ] operations = [ migrations.AlterField( model_name='task',", "'0001_initial'), ] operations = [ migrations.AlterField( model_name='task', name='author', field=models.CharField(default='Anonymous', max_length=100),", "on 2020-10-11 10:53 from django.db import migrations, models class Migration(migrations.Migration):", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api',", "2020-10-11 10:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "field=models.CharField(default='Anonymous', max_length=100), ), migrations.AlterField( model_name='task', name='deadline', field=models.DateTimeField(default='2020-10-11 10:53'), ), ]", "Django 3.1.2 on 2020-10-11 10:53 from django.db import migrations, models" ]
[ "OF ANY # KIND, either express or implied. See the", "str = None, sender: str = None): key = None", "\"\" else namespace sender = None if sender == \"\"", "more contributor license agreements. See the NOTICE file # distributed", "= MongoEvent.get_base_events_by_time(start_time) return res def list_all_events_from_version(self, start_version: int, end_version: int", "0 return mongo_events[0].version def add_event(self, event: BaseEvent, uuid: str): kwargs", "Apache Software Foundation (ASF) under one # or more contributor", "WARRANTIES OR CONDITIONS OF ANY # KIND, either express or", "else version event_type = None if event_type == \"\" else", "2.0 (the # \"License\"); you may not use this file", "= kwargs.get(\"authentication_source\", \"admin\") if (username or password) and not (username", "raise Exception(\"Please provide valid username and password\") if username and", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "provide valid username and password\") if username and password: db_conf.update({", "specific language governing permissions and limitations # under the License.", "under the License is distributed on an # \"AS IS\"", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either", "event.create_time = mongo_event.create_time event.version = mongo_event.version return event def list_events(self,", "None, namespace: str = None, sender: str = None): key", "**kwargs): db_conf = { \"host\": kwargs.get(\"host\"), \"port\": kwargs.get(\"port\"), \"db\": kwargs.get(\"db\"),", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #", "import Union, Tuple from mongoengine import connect from notification_service.event_storage import", "distributed with this work for additional information # regarding copyright", "(username or password) and not (username and password): raise Exception(\"Please", "for the # specific language governing permissions and limitations #", "= None, sender: str = None): key = None if", "int(time.time() * 1000), \"event_type\": event.event_type, \"key\": event.key, \"value\": event.value, \"context\":", "notification_service.mongo_notification import MongoEvent class MongoEventStorage(BaseEventStorage): def __init__(self, *args, **kwargs): self.db_conn", "See the License for the # specific language governing permissions", "to in writing, # software distributed under the License is", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "username and password: db_conf.update({ \"username\": username, \"password\": password, \"authentication_source\": authentication_source", "collections import Iterable from typing import Union, Tuple from mongoengine", "kwargs = { \"server_ip\": self.server_ip, \"create_time\": int(time.time() * 1000), \"event_type\":", "socket.gethostbyname(socket.gethostname()) def setup_connection(self, **kwargs): db_conf = { \"host\": kwargs.get(\"host\"), \"port\":", "password, \"authentication_source\": authentication_source }) return connect(**db_conf) def get_latest_version(self, key: str,", "event_type namespace = None if namespace == \"\" else namespace", "file # distributed with this work for additional information #", "not (username and password): raise Exception(\"Please provide valid username and", "if sender == \"\" else sender if isinstance(key, str): key", "implied. See the License for the # specific language governing", "to you under the Apache License, Version 2.0 (the #", "start_version: int, end_version: int = None): res = MongoEvent.get_base_events_by_version(start_version, end_version)", "\"\" else event_type namespace = None if namespace == \"\"", "str): kwargs = { \"server_ip\": self.server_ip, \"create_time\": int(time.time() * 1000),", "event.sender, \"uuid\": uuid } mongo_event = MongoEvent(**kwargs) mongo_event.save() mongo_event.reload() event.create_time", "may not use this file except in compliance # with", "None) authentication_source = kwargs.get(\"authentication_source\", \"admin\") if (username or password) and", "list_events(self, key: Union[str, Tuple[str]], version: int = None, event_type: str", "int = None, event_type: str = None, start_time: int =", "connect(**db_conf) def get_latest_version(self, key: str, namespace: str = None): mongo_events", "kwargs.get(\"password\", None) authentication_source = kwargs.get(\"authentication_source\", \"admin\") if (username or password)", "return event def list_events(self, key: Union[str, Tuple[str]], version: int =", "kwargs.get(\"authentication_source\", \"admin\") if (username or password) and not (username and", "connect from notification_service.event_storage import BaseEventStorage from notification_service.base_notification import BaseEvent from", "License, Version 2.0 (the # \"License\"); you may not use", "either express or implied. See the License for the #", "sender if isinstance(key, str): key = (key,) elif isinstance(key, Iterable):", "socket from collections import Iterable from typing import Union, Tuple", "\"\" else key version = None if version == 0", "additional information # regarding copyright ownership. The ASF licenses this", "See the NOTICE file # distributed with this work for", "mongo_events[0].version def add_event(self, event: BaseEvent, uuid: str): kwargs = {", "self.server_ip = socket.gethostbyname(socket.gethostname()) def setup_connection(self, **kwargs): db_conf = { \"host\":", "\"key\": event.key, \"value\": event.value, \"context\": event.context, \"namespace\": event.namespace, \"sender\": event.sender,", "notification_service.event_storage import BaseEventStorage from notification_service.base_notification import BaseEvent from notification_service.mongo_notification import", "Apache License, Version 2.0 (the # \"License\"); you may not", "typing import Union, Tuple from mongoengine import connect from notification_service.event_storage", "None, sender: str = None): key = None if key", "= None, namespace: str = None, sender: str = None):", "authentication_source = kwargs.get(\"authentication_source\", \"admin\") if (username or password) and not", "= (key,) elif isinstance(key, Iterable): key = tuple(key) res =", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "file except in compliance # with the License. You may", "# specific language governing permissions and limitations # under the", "0, 1, \"-version\") if not mongo_events: return 0 return mongo_events[0].version", "= { \"server_ip\": self.server_ip, \"create_time\": int(time.time() * 1000), \"event_type\": event.event_type,", "event def list_events(self, key: Union[str, Tuple[str]], version: int = None,", "you may not use this file except in compliance #", "mongo_event.version return event def list_events(self, key: Union[str, Tuple[str]], version: int", "use this file except in compliance # with the License.", "contributor license agreements. See the NOTICE file # distributed with", "(username and password): raise Exception(\"Please provide valid username and password\")", "str = None, start_time: int = None, namespace: str =", "{ \"server_ip\": self.server_ip, \"create_time\": int(time.time() * 1000), \"event_type\": event.event_type, \"key\":", "an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "setup_connection(self, **kwargs): db_conf = { \"host\": kwargs.get(\"host\"), \"port\": kwargs.get(\"port\"), \"db\":", "= kwargs.get(\"password\", None) authentication_source = kwargs.get(\"authentication_source\", \"admin\") if (username or", "def list_events(self, key: Union[str, Tuple[str]], version: int = None, event_type:", "uuid: str): kwargs = { \"server_ip\": self.server_ip, \"create_time\": int(time.time() *", "WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express", "return 0 return mongo_events[0].version def add_event(self, event: BaseEvent, uuid: str):", "from notification_service.event_storage import BaseEventStorage from notification_service.base_notification import BaseEvent from notification_service.mongo_notification", "with this work for additional information # regarding copyright ownership.", "None) password = kwargs.get(\"password\", None) authentication_source = kwargs.get(\"authentication_source\", \"admin\") if", "= socket.gethostbyname(socket.gethostname()) def setup_connection(self, **kwargs): db_conf = { \"host\": kwargs.get(\"host\"),", "password) and not (username and password): raise Exception(\"Please provide valid", "mongo_event = MongoEvent(**kwargs) mongo_event.save() mongo_event.reload() event.create_time = mongo_event.create_time event.version =", "work for additional information # regarding copyright ownership. The ASF", "\"server_ip\": self.server_ip, \"create_time\": int(time.time() * 1000), \"event_type\": event.event_type, \"key\": event.key,", "# under the License. # import time import socket from", "event.key, \"value\": event.value, \"context\": event.context, \"namespace\": event.namespace, \"sender\": event.sender, \"uuid\":", "end_version: int = None): res = MongoEvent.get_base_events_by_version(start_version, end_version) return res", "distributed under the License is distributed on an # \"AS", "# software distributed under the License is distributed on an", "* 1000), \"event_type\": event.event_type, \"key\": event.key, \"value\": event.value, \"context\": event.context,", "and limitations # under the License. # import time import", "= None if sender == \"\" else sender if isinstance(key,", "the License. You may obtain a copy of the License", "\"namespace\": event.namespace, \"sender\": event.sender, \"uuid\": uuid } mongo_event = MongoEvent(**kwargs)", "== \"\" else namespace sender = None if sender ==", "(key,) elif isinstance(key, Iterable): key = tuple(key) res = MongoEvent.get_base_events(key,", "= MongoEvent(**kwargs) mongo_event.save() mongo_event.reload() event.create_time = mongo_event.create_time event.version = mongo_event.version", "under the Apache License, Version 2.0 (the # \"License\"); you", "distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "regarding copyright ownership. The ASF licenses this file # to", "or agreed to in writing, # software distributed under the", "str = None): mongo_events = MongoEvent.get_by_key(key, 0, 1, \"-version\") if", "Iterable): key = tuple(key) res = MongoEvent.get_base_events(key, version, event_type, start_time,", "str = None): key = None if key == \"\"", "sender: str = None): key = None if key ==", "None if event_type == \"\" else event_type namespace = None", "version: int = None, event_type: str = None, start_time: int", "from collections import Iterable from typing import Union, Tuple from", "or more contributor license agreements. See the NOTICE file #", "Exception(\"Please provide valid username and password\") if username and password:", "limitations # under the License. # import time import socket", "import connect from notification_service.event_storage import BaseEventStorage from notification_service.base_notification import BaseEvent", "namespace, sender) return res def list_all_events(self, start_time: int): res =", "this work for additional information # regarding copyright ownership. The", "namespace sender = None if sender == \"\" else sender", "elif isinstance(key, Iterable): key = tuple(key) res = MongoEvent.get_base_events(key, version,", "the NOTICE file # distributed with this work for additional", "= mongo_event.version return event def list_events(self, key: Union[str, Tuple[str]], version:", "\"password\": password, \"authentication_source\": authentication_source }) return connect(**db_conf) def get_latest_version(self, key:", "import BaseEventStorage from notification_service.base_notification import BaseEvent from notification_service.mongo_notification import MongoEvent", "\"uuid\": uuid } mongo_event = MongoEvent(**kwargs) mongo_event.save() mongo_event.reload() event.create_time =", "mongo_event.create_time event.version = mongo_event.version return event def list_events(self, key: Union[str,", "import Iterable from typing import Union, Tuple from mongoengine import", "None): mongo_events = MongoEvent.get_by_key(key, 0, 1, \"-version\") if not mongo_events:", "KIND, either express or implied. See the License for the", "from notification_service.base_notification import BaseEvent from notification_service.mongo_notification import MongoEvent class MongoEventStorage(BaseEventStorage):", "event: BaseEvent, uuid: str): kwargs = { \"server_ip\": self.server_ip, \"create_time\":", "None): key = None if key == \"\" else key", "version event_type = None if event_type == \"\" else event_type", "Iterable from typing import Union, Tuple from mongoengine import connect", "isinstance(key, str): key = (key,) elif isinstance(key, Iterable): key =", "= None if namespace == \"\" else namespace sender =", "from typing import Union, Tuple from mongoengine import connect from", "or implied. See the License for the # specific language", "express or implied. See the License for the # specific", "= self.setup_connection(**kwargs) self.server_ip = socket.gethostbyname(socket.gethostname()) def setup_connection(self, **kwargs): db_conf =", "\"create_time\": int(time.time() * 1000), \"event_type\": event.event_type, \"key\": event.key, \"value\": event.value,", "list_all_events_from_version(self, start_version: int, end_version: int = None): res = MongoEvent.get_base_events_by_version(start_version,", "the # specific language governing permissions and limitations # under", "password = kwargs.get(\"password\", None) authentication_source = kwargs.get(\"authentication_source\", \"admin\") if (username", "db_conf.update({ \"username\": username, \"password\": password, \"authentication_source\": authentication_source }) return connect(**db_conf)", "may obtain a copy of the License at # #", "mongo_events = MongoEvent.get_by_key(key, 0, 1, \"-version\") if not mongo_events: return", "== \"\" else key version = None if version ==", "The ASF licenses this file # to you under the", "key = tuple(key) res = MongoEvent.get_base_events(key, version, event_type, start_time, namespace,", "db_conf = { \"host\": kwargs.get(\"host\"), \"port\": kwargs.get(\"port\"), \"db\": kwargs.get(\"db\"), }", "\"port\": kwargs.get(\"port\"), \"db\": kwargs.get(\"db\"), } username = kwargs.get(\"username\", None) password", "# Licensed to the Apache Software Foundation (ASF) under one", "} mongo_event = MongoEvent(**kwargs) mongo_event.save() mongo_event.reload() event.create_time = mongo_event.create_time event.version", "import MongoEvent class MongoEventStorage(BaseEventStorage): def __init__(self, *args, **kwargs): self.db_conn =", "= kwargs.get(\"username\", None) password = kwargs.get(\"password\", None) authentication_source = kwargs.get(\"authentication_source\",", "law or agreed to in writing, # software distributed under", "version, event_type, start_time, namespace, sender) return res def list_all_events(self, start_time:", "from mongoengine import connect from notification_service.event_storage import BaseEventStorage from notification_service.base_notification", "Foundation (ASF) under one # or more contributor license agreements.", "self.setup_connection(**kwargs) self.server_ip = socket.gethostbyname(socket.gethostname()) def setup_connection(self, **kwargs): db_conf = {", "kwargs.get(\"username\", None) password = kwargs.get(\"password\", None) authentication_source = kwargs.get(\"authentication_source\", \"admin\")", "= MongoEvent.get_base_events(key, version, event_type, start_time, namespace, sender) return res def", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "and password: db_conf.update({ \"username\": username, \"password\": password, \"authentication_source\": authentication_source })", "mongo_events: return 0 return mongo_events[0].version def add_event(self, event: BaseEvent, uuid:", "password): raise Exception(\"Please provide valid username and password\") if username", "Software Foundation (ASF) under one # or more contributor license", "\"\" else sender if isinstance(key, str): key = (key,) elif", "res = MongoEvent.get_base_events_by_time(start_time) return res def list_all_events_from_version(self, start_version: int, end_version:", "mongoengine import connect from notification_service.event_storage import BaseEventStorage from notification_service.base_notification import", "notification_service.base_notification import BaseEvent from notification_service.mongo_notification import MongoEvent class MongoEventStorage(BaseEventStorage): def", "# regarding copyright ownership. The ASF licenses this file #", "event.context, \"namespace\": event.namespace, \"sender\": event.sender, \"uuid\": uuid } mongo_event =", "res = MongoEvent.get_base_events(key, version, event_type, start_time, namespace, sender) return res", "not mongo_events: return 0 return mongo_events[0].version def add_event(self, event: BaseEvent,", "in compliance # with the License. You may obtain a", "# to you under the Apache License, Version 2.0 (the", "License for the # specific language governing permissions and limitations", "\"context\": event.context, \"namespace\": event.namespace, \"sender\": event.sender, \"uuid\": uuid } mongo_event", "OR CONDITIONS OF ANY # KIND, either express or implied.", "namespace = None if namespace == \"\" else namespace sender", "this file # to you under the Apache License, Version", "namespace: str = None): mongo_events = MongoEvent.get_by_key(key, 0, 1, \"-version\")", "\"db\": kwargs.get(\"db\"), } username = kwargs.get(\"username\", None) password = kwargs.get(\"password\",", "copyright ownership. The ASF licenses this file # to you", "the License. # import time import socket from collections import", "self.server_ip, \"create_time\": int(time.time() * 1000), \"event_type\": event.event_type, \"key\": event.key, \"value\":", "= None): res = MongoEvent.get_base_events_by_version(start_version, end_version) return res def clean_up(self):", "def list_all_events(self, start_time: int): res = MongoEvent.get_base_events_by_time(start_time) return res def", "in writing, # software distributed under the License is distributed", "License. # import time import socket from collections import Iterable", "= mongo_event.create_time event.version = mongo_event.version return event def list_events(self, key:", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "License is distributed on an # \"AS IS\" BASIS, WITHOUT", "return res def list_all_events(self, start_time: int): res = MongoEvent.get_base_events_by_time(start_time) return", "\"sender\": event.sender, \"uuid\": uuid } mongo_event = MongoEvent(**kwargs) mongo_event.save() mongo_event.reload()", "1, \"-version\") if not mongo_events: return 0 return mongo_events[0].version def", "= None): mongo_events = MongoEvent.get_by_key(key, 0, 1, \"-version\") if not", "or password) and not (username and password): raise Exception(\"Please provide", "time import socket from collections import Iterable from typing import", "{ \"host\": kwargs.get(\"host\"), \"port\": kwargs.get(\"port\"), \"db\": kwargs.get(\"db\"), } username =", "def setup_connection(self, **kwargs): db_conf = { \"host\": kwargs.get(\"host\"), \"port\": kwargs.get(\"port\"),", "key: str, namespace: str = None): mongo_events = MongoEvent.get_by_key(key, 0,", "start_time, namespace, sender) return res def list_all_events(self, start_time: int): res", "# \"License\"); you may not use this file except in", "\"authentication_source\": authentication_source }) return connect(**db_conf) def get_latest_version(self, key: str, namespace:", "# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "to the Apache Software Foundation (ASF) under one # or", "\"License\"); you may not use this file except in compliance", "kwargs.get(\"host\"), \"port\": kwargs.get(\"port\"), \"db\": kwargs.get(\"db\"), } username = kwargs.get(\"username\", None)", "kwargs.get(\"db\"), } username = kwargs.get(\"username\", None) password = kwargs.get(\"password\", None)", "return connect(**db_conf) def get_latest_version(self, key: str, namespace: str = None):", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "start_time: int = None, namespace: str = None, sender: str", "}) return connect(**db_conf) def get_latest_version(self, key: str, namespace: str =", "= MongoEvent.get_by_key(key, 0, 1, \"-version\") if not mongo_events: return 0", "sender) return res def list_all_events(self, start_time: int): res = MongoEvent.get_base_events_by_time(start_time)", "str, namespace: str = None): mongo_events = MongoEvent.get_by_key(key, 0, 1,", "# distributed with this work for additional information # regarding", "writing, # software distributed under the License is distributed on", "from notification_service.mongo_notification import MongoEvent class MongoEventStorage(BaseEventStorage): def __init__(self, *args, **kwargs):", "kwargs.get(\"port\"), \"db\": kwargs.get(\"db\"), } username = kwargs.get(\"username\", None) password =", "tuple(key) res = MongoEvent.get_base_events(key, version, event_type, start_time, namespace, sender) return", "Union[str, Tuple[str]], version: int = None, event_type: str = None,", "sender == \"\" else sender if isinstance(key, str): key =", "password: db_conf.update({ \"username\": username, \"password\": password, \"authentication_source\": authentication_source }) return", "CONDITIONS OF ANY # KIND, either express or implied. See", "def list_all_events_from_version(self, start_version: int, end_version: int = None): res =", "**kwargs): self.db_conn = self.setup_connection(**kwargs) self.server_ip = socket.gethostbyname(socket.gethostname()) def setup_connection(self, **kwargs):", "key == \"\" else key version = None if version", "None if namespace == \"\" else namespace sender = None", "if isinstance(key, str): key = (key,) elif isinstance(key, Iterable): key", "= tuple(key) res = MongoEvent.get_base_events(key, version, event_type, start_time, namespace, sender)", "= None if version == 0 else version event_type =", "for additional information # regarding copyright ownership. The ASF licenses", "the Apache Software Foundation (ASF) under one # or more", "# # Unless required by applicable law or agreed to", "Tuple[str]], version: int = None, event_type: str = None, start_time:", "Version 2.0 (the # \"License\"); you may not use this", "MongoEvent.get_base_events_by_time(start_time) return res def list_all_events_from_version(self, start_version: int, end_version: int =", "== \"\" else event_type namespace = None if namespace ==", "int = None): res = MongoEvent.get_base_events_by_version(start_version, end_version) return res def", "one # or more contributor license agreements. See the NOTICE", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "if version == 0 else version event_type = None if", "return res def list_all_events_from_version(self, start_version: int, end_version: int = None):", "import BaseEvent from notification_service.mongo_notification import MongoEvent class MongoEventStorage(BaseEventStorage): def __init__(self,", "username = kwargs.get(\"username\", None) password = kwargs.get(\"password\", None) authentication_source =", "None if key == \"\" else key version = None", "Tuple from mongoengine import connect from notification_service.event_storage import BaseEventStorage from", "except in compliance # with the License. You may obtain", "import time import socket from collections import Iterable from typing", "NOTICE file # distributed with this work for additional information", "__init__(self, *args, **kwargs): self.db_conn = self.setup_connection(**kwargs) self.server_ip = socket.gethostbyname(socket.gethostname()) def", "this file except in compliance # with the License. You", "if namespace == \"\" else namespace sender = None if", "key: Union[str, Tuple[str]], version: int = None, event_type: str =", "license agreements. See the NOTICE file # distributed with this", "namespace: str = None, sender: str = None): key =", "None if sender == \"\" else sender if isinstance(key, str):", "required by applicable law or agreed to in writing, #", "None, start_time: int = None, namespace: str = None, sender:", "\"admin\") if (username or password) and not (username and password):", "\"host\": kwargs.get(\"host\"), \"port\": kwargs.get(\"port\"), \"db\": kwargs.get(\"db\"), } username = kwargs.get(\"username\",", "= None if key == \"\" else key version =", "the License for the # specific language governing permissions and", "mongo_event.save() mongo_event.reload() event.create_time = mongo_event.create_time event.version = mongo_event.version return event", "key = (key,) elif isinstance(key, Iterable): key = tuple(key) res", "ANY # KIND, either express or implied. See the License", "the License is distributed on an # \"AS IS\" BASIS,", "0 else version event_type = None if event_type == \"\"", "and password): raise Exception(\"Please provide valid username and password\") if", "= None, event_type: str = None, start_time: int = None,", "= None, start_time: int = None, namespace: str = None,", "# # Licensed to the Apache Software Foundation (ASF) under", "event.namespace, \"sender\": event.sender, \"uuid\": uuid } mongo_event = MongoEvent(**kwargs) mongo_event.save()", "not use this file except in compliance # with the", "None if version == 0 else version event_type = None", "if (username or password) and not (username and password): raise", "\"-version\") if not mongo_events: return 0 return mongo_events[0].version def add_event(self,", "event_type == \"\" else event_type namespace = None if namespace", "# import time import socket from collections import Iterable from", "Unless required by applicable law or agreed to in writing,", "None): res = MongoEvent.get_base_events_by_version(start_version, end_version) return res def clean_up(self): MongoEvent.delete_by_client(self.server_ip)", "def get_latest_version(self, key: str, namespace: str = None): mongo_events =", "res def list_all_events(self, start_time: int): res = MongoEvent.get_base_events_by_time(start_time) return res", "else sender if isinstance(key, str): key = (key,) elif isinstance(key,", "int, end_version: int = None): res = MongoEvent.get_base_events_by_version(start_version, end_version) return", "def add_event(self, event: BaseEvent, uuid: str): kwargs = { \"server_ip\":", "(ASF) under one # or more contributor license agreements. See", "else namespace sender = None if sender == \"\" else", "authentication_source }) return connect(**db_conf) def get_latest_version(self, key: str, namespace: str", "# or more contributor license agreements. See the NOTICE file", "agreed to in writing, # software distributed under the License", "mongo_event.reload() event.create_time = mongo_event.create_time event.version = mongo_event.version return event def", "event.version = mongo_event.version return event def list_events(self, key: Union[str, Tuple[str]],", "return mongo_events[0].version def add_event(self, event: BaseEvent, uuid: str): kwargs =", "int = None, namespace: str = None, sender: str =", "MongoEvent.get_by_key(key, 0, 1, \"-version\") if not mongo_events: return 0 return", "(the # \"License\"); you may not use this file except", "event_type = None if event_type == \"\" else event_type namespace", "\"value\": event.value, \"context\": event.context, \"namespace\": event.namespace, \"sender\": event.sender, \"uuid\": uuid", "get_latest_version(self, key: str, namespace: str = None): mongo_events = MongoEvent.get_by_key(key,", "username, \"password\": password, \"authentication_source\": authentication_source }) return connect(**db_conf) def get_latest_version(self,", "ASF licenses this file # to you under the Apache", "sender = None if sender == \"\" else sender if", "on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "if username and password: db_conf.update({ \"username\": username, \"password\": password, \"authentication_source\":", "1000), \"event_type\": event.event_type, \"key\": event.key, \"value\": event.value, \"context\": event.context, \"namespace\":", "ownership. The ASF licenses this file # to you under", "class MongoEventStorage(BaseEventStorage): def __init__(self, *args, **kwargs): self.db_conn = self.setup_connection(**kwargs) self.server_ip", "= { \"host\": kwargs.get(\"host\"), \"port\": kwargs.get(\"port\"), \"db\": kwargs.get(\"db\"), } username", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "list_all_events(self, start_time: int): res = MongoEvent.get_base_events_by_time(start_time) return res def list_all_events_from_version(self,", "self.db_conn = self.setup_connection(**kwargs) self.server_ip = socket.gethostbyname(socket.gethostname()) def setup_connection(self, **kwargs): db_conf", "with the License. You may obtain a copy of the", "res def list_all_events_from_version(self, start_version: int, end_version: int = None): res", "namespace == \"\" else namespace sender = None if sender", "applicable law or agreed to in writing, # software distributed", "permissions and limitations # under the License. # import time", "governing permissions and limitations # under the License. # import", "event_type: str = None, start_time: int = None, namespace: str", "} username = kwargs.get(\"username\", None) password = kwargs.get(\"password\", None) authentication_source", "and password\") if username and password: db_conf.update({ \"username\": username, \"password\":", "Union, Tuple from mongoengine import connect from notification_service.event_storage import BaseEventStorage", "password\") if username and password: db_conf.update({ \"username\": username, \"password\": password,", "MongoEvent class MongoEventStorage(BaseEventStorage): def __init__(self, *args, **kwargs): self.db_conn = self.setup_connection(**kwargs)", "import socket from collections import Iterable from typing import Union,", "is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES", "MongoEventStorage(BaseEventStorage): def __init__(self, *args, **kwargs): self.db_conn = self.setup_connection(**kwargs) self.server_ip =", "file # to you under the Apache License, Version 2.0", "if key == \"\" else key version = None if", "else event_type namespace = None if namespace == \"\" else", "= None): key = None if key == \"\" else", "# with the License. You may obtain a copy of", "under the License. # import time import socket from collections", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "language governing permissions and limitations # under the License. #", "int): res = MongoEvent.get_base_events_by_time(start_time) return res def list_all_events_from_version(self, start_version: int,", "uuid } mongo_event = MongoEvent(**kwargs) mongo_event.save() mongo_event.reload() event.create_time = mongo_event.create_time", "BaseEvent from notification_service.mongo_notification import MongoEvent class MongoEventStorage(BaseEventStorage): def __init__(self, *args,", "software distributed under the License is distributed on an #", "Licensed to the Apache Software Foundation (ASF) under one #", "None, event_type: str = None, start_time: int = None, namespace:", "str): key = (key,) elif isinstance(key, Iterable): key = tuple(key)", "under one # or more contributor license agreements. See the", "else key version = None if version == 0 else", "event.value, \"context\": event.context, \"namespace\": event.namespace, \"sender\": event.sender, \"uuid\": uuid }", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "key version = None if version == 0 else version", "if event_type == \"\" else event_type namespace = None if", "information # regarding copyright ownership. The ASF licenses this file", "BaseEventStorage from notification_service.base_notification import BaseEvent from notification_service.mongo_notification import MongoEvent class", "\"username\": username, \"password\": password, \"authentication_source\": authentication_source }) return connect(**db_conf) def", "the Apache License, Version 2.0 (the # \"License\"); you may", "def __init__(self, *args, **kwargs): self.db_conn = self.setup_connection(**kwargs) self.server_ip = socket.gethostbyname(socket.gethostname())", "MongoEvent.get_base_events(key, version, event_type, start_time, namespace, sender) return res def list_all_events(self,", "add_event(self, event: BaseEvent, uuid: str): kwargs = { \"server_ip\": self.server_ip,", "username and password\") if username and password: db_conf.update({ \"username\": username,", "== \"\" else sender if isinstance(key, str): key = (key,)", "you under the Apache License, Version 2.0 (the # \"License\");", "if not mongo_events: return 0 return mongo_events[0].version def add_event(self, event:", "# KIND, either express or implied. See the License for", "event.event_type, \"key\": event.key, \"value\": event.value, \"context\": event.context, \"namespace\": event.namespace, \"sender\":", "agreements. See the NOTICE file # distributed with this work", "licenses this file # to you under the Apache License,", "event_type, start_time, namespace, sender) return res def list_all_events(self, start_time: int):", "*args, **kwargs): self.db_conn = self.setup_connection(**kwargs) self.server_ip = socket.gethostbyname(socket.gethostname()) def setup_connection(self,", "key = None if key == \"\" else key version", "by applicable law or agreed to in writing, # software", "and not (username and password): raise Exception(\"Please provide valid username", "# Unless required by applicable law or agreed to in", "BaseEvent, uuid: str): kwargs = { \"server_ip\": self.server_ip, \"create_time\": int(time.time()", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,", "License. You may obtain a copy of the License at", "isinstance(key, Iterable): key = tuple(key) res = MongoEvent.get_base_events(key, version, event_type,", "start_time: int): res = MongoEvent.get_base_events_by_time(start_time) return res def list_all_events_from_version(self, start_version:", "== 0 else version event_type = None if event_type ==", "You may obtain a copy of the License at #", "MongoEvent(**kwargs) mongo_event.save() mongo_event.reload() event.create_time = mongo_event.create_time event.version = mongo_event.version return", "valid username and password\") if username and password: db_conf.update({ \"username\":", "compliance # with the License. You may obtain a copy", "\"event_type\": event.event_type, \"key\": event.key, \"value\": event.value, \"context\": event.context, \"namespace\": event.namespace,", "= None if event_type == \"\" else event_type namespace =", "version == 0 else version event_type = None if event_type", "version = None if version == 0 else version event_type" ]
[ "import ConfdServiceList, ConfdConnection, ConfdConnectionProvider from .statemachine import CspStateMachine from .settings", "'single_rp' state_machine_class = CspStateMachine connection_provider_class = ConfdConnectionProvider subcommand_list = CspServiceList", "from .statemachine import CspStateMachine from .settings import CspSettings from .", "CspStateMachine connection_provider_class = ConfdConnectionProvider subcommand_list = CspServiceList settings = CspSettings()", "unicon.plugins.confd import ConfdServiceList, ConfdConnection, ConfdConnectionProvider from .statemachine import CspStateMachine from", "import CspStateMachine from .settings import CspSettings from . import service_implementation", "= CspStateMachine connection_provider_class = ConfdConnectionProvider subcommand_list = CspServiceList settings =", "\"<NAME> <<EMAIL>>\" from unicon.plugins.confd import ConfdServiceList, ConfdConnection, ConfdConnectionProvider from .statemachine", "ConfdConnection, ConfdConnectionProvider from .statemachine import CspStateMachine from .settings import CspSettings", ".statemachine import CspStateMachine from .settings import CspSettings from . import", "as csp_svc class CspServiceList(ConfdServiceList): def __init__(self): super().__init__() delattr(self, 'cli_style') self.reload", "import service_implementation as csp_svc class CspServiceList(ConfdServiceList): def __init__(self): super().__init__() delattr(self,", "from .settings import CspSettings from . import service_implementation as csp_svc", "self.reload = csp_svc.Reload class CspSingleRPConnection(ConfdConnection): os = 'confd' series =", "= 'single_rp' state_machine_class = CspStateMachine connection_provider_class = ConfdConnectionProvider subcommand_list =", "CspServiceList(ConfdServiceList): def __init__(self): super().__init__() delattr(self, 'cli_style') self.reload = csp_svc.Reload class", "csp_svc.Reload class CspSingleRPConnection(ConfdConnection): os = 'confd' series = 'csp' chassis_type", "CspSettings from . import service_implementation as csp_svc class CspServiceList(ConfdServiceList): def", "import CspSettings from . import service_implementation as csp_svc class CspServiceList(ConfdServiceList):", "__init__(self): super().__init__() delattr(self, 'cli_style') self.reload = csp_svc.Reload class CspSingleRPConnection(ConfdConnection): os", "csp_svc class CspServiceList(ConfdServiceList): def __init__(self): super().__init__() delattr(self, 'cli_style') self.reload =", "state_machine_class = CspStateMachine connection_provider_class = ConfdConnectionProvider subcommand_list = CspServiceList settings", "delattr(self, 'cli_style') self.reload = csp_svc.Reload class CspSingleRPConnection(ConfdConnection): os = 'confd'", "CspSingleRPConnection(ConfdConnection): os = 'confd' series = 'csp' chassis_type = 'single_rp'", "= 'csp' chassis_type = 'single_rp' state_machine_class = CspStateMachine connection_provider_class =", "= csp_svc.Reload class CspSingleRPConnection(ConfdConnection): os = 'confd' series = 'csp'", "ConfdServiceList, ConfdConnection, ConfdConnectionProvider from .statemachine import CspStateMachine from .settings import", "series = 'csp' chassis_type = 'single_rp' state_machine_class = CspStateMachine connection_provider_class", "__author__ = \"<NAME> <<EMAIL>>\" from unicon.plugins.confd import ConfdServiceList, ConfdConnection, ConfdConnectionProvider", "from . import service_implementation as csp_svc class CspServiceList(ConfdServiceList): def __init__(self):", ". import service_implementation as csp_svc class CspServiceList(ConfdServiceList): def __init__(self): super().__init__()", "service_implementation as csp_svc class CspServiceList(ConfdServiceList): def __init__(self): super().__init__() delattr(self, 'cli_style')", "= 'confd' series = 'csp' chassis_type = 'single_rp' state_machine_class =", "'csp' chassis_type = 'single_rp' state_machine_class = CspStateMachine connection_provider_class = ConfdConnectionProvider", "= \"<NAME> <<EMAIL>>\" from unicon.plugins.confd import ConfdServiceList, ConfdConnection, ConfdConnectionProvider from", "<<EMAIL>>\" from unicon.plugins.confd import ConfdServiceList, ConfdConnection, ConfdConnectionProvider from .statemachine import", "def __init__(self): super().__init__() delattr(self, 'cli_style') self.reload = csp_svc.Reload class CspSingleRPConnection(ConfdConnection):", "super().__init__() delattr(self, 'cli_style') self.reload = csp_svc.Reload class CspSingleRPConnection(ConfdConnection): os =", "os = 'confd' series = 'csp' chassis_type = 'single_rp' state_machine_class", "chassis_type = 'single_rp' state_machine_class = CspStateMachine connection_provider_class = ConfdConnectionProvider subcommand_list", "CspStateMachine from .settings import CspSettings from . import service_implementation as", "class CspServiceList(ConfdServiceList): def __init__(self): super().__init__() delattr(self, 'cli_style') self.reload = csp_svc.Reload", "'cli_style') self.reload = csp_svc.Reload class CspSingleRPConnection(ConfdConnection): os = 'confd' series", "from unicon.plugins.confd import ConfdServiceList, ConfdConnection, ConfdConnectionProvider from .statemachine import CspStateMachine", "class CspSingleRPConnection(ConfdConnection): os = 'confd' series = 'csp' chassis_type =", "'confd' series = 'csp' chassis_type = 'single_rp' state_machine_class = CspStateMachine", "ConfdConnectionProvider from .statemachine import CspStateMachine from .settings import CspSettings from", ".settings import CspSettings from . import service_implementation as csp_svc class" ]
[ "name=package.__name__, version=package.__version__, description=package.__description__, long_description=readme(), author=package.__author__, author_email=package.__email__, license=package.__license__, url=package.__url__, download_url=package.__download_url__, keywords", "readme(): with open('README.rst') as f: return ''.join(f.readlines()[11:]) setup( name=package.__name__, version=package.__version__,", "long_description=readme(), author=package.__author__, author_email=package.__email__, license=package.__license__, url=package.__url__, download_url=package.__download_url__, keywords =package. __keywords__, entry_points=package.__entry_points__,", "-*- coding: utf-8 -*- from setuptools import setup import search_google", "setup( name=package.__name__, version=package.__version__, description=package.__description__, long_description=readme(), author=package.__author__, author_email=package.__email__, license=package.__license__, url=package.__url__, download_url=package.__download_url__,", "with open('README.rst') as f: return ''.join(f.readlines()[11:]) setup( name=package.__name__, version=package.__version__, description=package.__description__,", "url=package.__url__, download_url=package.__download_url__, keywords =package. __keywords__, entry_points=package.__entry_points__, packages=package.__packages__, package_data=package.__package_data__, install_requires=package.__install_requires__ )", "description=package.__description__, long_description=readme(), author=package.__author__, author_email=package.__email__, license=package.__license__, url=package.__url__, download_url=package.__download_url__, keywords =package. __keywords__,", "version=package.__version__, description=package.__description__, long_description=readme(), author=package.__author__, author_email=package.__email__, license=package.__license__, url=package.__url__, download_url=package.__download_url__, keywords =package.", "import search_google as package def readme(): with open('README.rst') as f:", "def readme(): with open('README.rst') as f: return ''.join(f.readlines()[11:]) setup( name=package.__name__,", "coding: utf-8 -*- from setuptools import setup import search_google as", "-*- from setuptools import setup import search_google as package def", "license=package.__license__, url=package.__url__, download_url=package.__download_url__, keywords =package. __keywords__, entry_points=package.__entry_points__, packages=package.__packages__, package_data=package.__package_data__, install_requires=package.__install_requires__", "f: return ''.join(f.readlines()[11:]) setup( name=package.__name__, version=package.__version__, description=package.__description__, long_description=readme(), author=package.__author__, author_email=package.__email__,", "# -*- coding: utf-8 -*- from setuptools import setup import", "search_google as package def readme(): with open('README.rst') as f: return", "import setup import search_google as package def readme(): with open('README.rst')", "from setuptools import setup import search_google as package def readme():", "as f: return ''.join(f.readlines()[11:]) setup( name=package.__name__, version=package.__version__, description=package.__description__, long_description=readme(), author=package.__author__,", "setup import search_google as package def readme(): with open('README.rst') as", "author=package.__author__, author_email=package.__email__, license=package.__license__, url=package.__url__, download_url=package.__download_url__, keywords =package. __keywords__, entry_points=package.__entry_points__, packages=package.__packages__,", "utf-8 -*- from setuptools import setup import search_google as package", "open('README.rst') as f: return ''.join(f.readlines()[11:]) setup( name=package.__name__, version=package.__version__, description=package.__description__, long_description=readme(),", "setuptools import setup import search_google as package def readme(): with", "author_email=package.__email__, license=package.__license__, url=package.__url__, download_url=package.__download_url__, keywords =package. __keywords__, entry_points=package.__entry_points__, packages=package.__packages__, package_data=package.__package_data__,", "return ''.join(f.readlines()[11:]) setup( name=package.__name__, version=package.__version__, description=package.__description__, long_description=readme(), author=package.__author__, author_email=package.__email__, license=package.__license__,", "as package def readme(): with open('README.rst') as f: return ''.join(f.readlines()[11:])", "package def readme(): with open('README.rst') as f: return ''.join(f.readlines()[11:]) setup(", "''.join(f.readlines()[11:]) setup( name=package.__name__, version=package.__version__, description=package.__description__, long_description=readme(), author=package.__author__, author_email=package.__email__, license=package.__license__, url=package.__url__," ]
[ "= ['macos', 'bundle', 'package', 'redistribute', 'redistributable', 'install_name_tool', 'otool', 'mach'], classifiers", "'rst') if os.path.exists('README.md') else '' except ImportError: description = ''", "'https://github.com/chearon/macpack', download_url = 'https://github.com/chearon/macpack/tarball/v1.0.3', keywords = ['macos', 'bundle', 'package', 'redistribute',", "'redistribute', 'redistributable', 'install_name_tool', 'otool', 'mach'], classifiers = [], entry_points =", "os try: import pypandoc description = pypandoc.convert('README.md', 'rst') if os.path.exists('README.md')", "else '' except ImportError: description = '' setuptools.setup( name =", "author = '<NAME>', author_email = '<EMAIL>', url = 'https://github.com/chearon/macpack', download_url", "'bundle', 'package', 'redistribute', 'redistributable', 'install_name_tool', 'otool', 'mach'], classifiers = [],", "import pypandoc description = pypandoc.convert('README.md', 'rst') if os.path.exists('README.md') else ''", "os.path.exists('README.md') else '' except ImportError: description = '' setuptools.setup( name", "except ImportError: description = '' setuptools.setup( name = 'macpack', packages", "'' setuptools.setup( name = 'macpack', packages = setuptools.find_packages(), version =", "'macpack', packages = setuptools.find_packages(), version = '1.0.3', description = 'Makes", "a macOS binary redistributable by searching the dependency tree and", "setuptools.find_packages(), version = '1.0.3', description = 'Makes a macOS binary", "classifiers = [], entry_points = { 'console_scripts': ['macpack=macpack.patcher:main'], } )", "by searching the dependency tree and copying/patching non-system libraries.', long_description", "'' except ImportError: description = '' setuptools.setup( name = 'macpack',", "'mach'], classifiers = [], entry_points = { 'console_scripts': ['macpack=macpack.patcher:main'], }", "= '' setuptools.setup( name = 'macpack', packages = setuptools.find_packages(), version", "version = '1.0.3', description = 'Makes a macOS binary redistributable", "url = 'https://github.com/chearon/macpack', download_url = 'https://github.com/chearon/macpack/tarball/v1.0.3', keywords = ['macos', 'bundle',", "setuptools.setup( name = 'macpack', packages = setuptools.find_packages(), version = '1.0.3',", "ImportError: description = '' setuptools.setup( name = 'macpack', packages =", "keywords = ['macos', 'bundle', 'package', 'redistribute', 'redistributable', 'install_name_tool', 'otool', 'mach'],", "packages = setuptools.find_packages(), version = '1.0.3', description = 'Makes a", "tree and copying/patching non-system libraries.', long_description = description, author =", "pypandoc description = pypandoc.convert('README.md', 'rst') if os.path.exists('README.md') else '' except", "'1.0.3', description = 'Makes a macOS binary redistributable by searching", "libraries.', long_description = description, author = '<NAME>', author_email = '<EMAIL>',", "= '<EMAIL>', url = 'https://github.com/chearon/macpack', download_url = 'https://github.com/chearon/macpack/tarball/v1.0.3', keywords =", "= description, author = '<NAME>', author_email = '<EMAIL>', url =", "= '<NAME>', author_email = '<EMAIL>', url = 'https://github.com/chearon/macpack', download_url =", "= 'macpack', packages = setuptools.find_packages(), version = '1.0.3', description =", "non-system libraries.', long_description = description, author = '<NAME>', author_email =", "author_email = '<EMAIL>', url = 'https://github.com/chearon/macpack', download_url = 'https://github.com/chearon/macpack/tarball/v1.0.3', keywords", "'https://github.com/chearon/macpack/tarball/v1.0.3', keywords = ['macos', 'bundle', 'package', 'redistribute', 'redistributable', 'install_name_tool', 'otool',", "<filename>setup.py import setuptools import os try: import pypandoc description =", "'install_name_tool', 'otool', 'mach'], classifiers = [], entry_points = { 'console_scripts':", "setuptools import os try: import pypandoc description = pypandoc.convert('README.md', 'rst')", "pypandoc.convert('README.md', 'rst') if os.path.exists('README.md') else '' except ImportError: description =", "download_url = 'https://github.com/chearon/macpack/tarball/v1.0.3', keywords = ['macos', 'bundle', 'package', 'redistribute', 'redistributable',", "'<EMAIL>', url = 'https://github.com/chearon/macpack', download_url = 'https://github.com/chearon/macpack/tarball/v1.0.3', keywords = ['macos',", "= 'https://github.com/chearon/macpack', download_url = 'https://github.com/chearon/macpack/tarball/v1.0.3', keywords = ['macos', 'bundle', 'package',", "description, author = '<NAME>', author_email = '<EMAIL>', url = 'https://github.com/chearon/macpack',", "description = '' setuptools.setup( name = 'macpack', packages = setuptools.find_packages(),", "macOS binary redistributable by searching the dependency tree and copying/patching", "= 'Makes a macOS binary redistributable by searching the dependency", "import os try: import pypandoc description = pypandoc.convert('README.md', 'rst') if", "searching the dependency tree and copying/patching non-system libraries.', long_description =", "= setuptools.find_packages(), version = '1.0.3', description = 'Makes a macOS", "= 'https://github.com/chearon/macpack/tarball/v1.0.3', keywords = ['macos', 'bundle', 'package', 'redistribute', 'redistributable', 'install_name_tool',", "try: import pypandoc description = pypandoc.convert('README.md', 'rst') if os.path.exists('README.md') else", "'package', 'redistribute', 'redistributable', 'install_name_tool', 'otool', 'mach'], classifiers = [], entry_points", "redistributable by searching the dependency tree and copying/patching non-system libraries.',", "the dependency tree and copying/patching non-system libraries.', long_description = description,", "'redistributable', 'install_name_tool', 'otool', 'mach'], classifiers = [], entry_points = {", "copying/patching non-system libraries.', long_description = description, author = '<NAME>', author_email", "import setuptools import os try: import pypandoc description = pypandoc.convert('README.md',", "if os.path.exists('README.md') else '' except ImportError: description = '' setuptools.setup(", "= '1.0.3', description = 'Makes a macOS binary redistributable by", "= pypandoc.convert('README.md', 'rst') if os.path.exists('README.md') else '' except ImportError: description", "binary redistributable by searching the dependency tree and copying/patching non-system", "'<NAME>', author_email = '<EMAIL>', url = 'https://github.com/chearon/macpack', download_url = 'https://github.com/chearon/macpack/tarball/v1.0.3',", "['macos', 'bundle', 'package', 'redistribute', 'redistributable', 'install_name_tool', 'otool', 'mach'], classifiers =", "'Makes a macOS binary redistributable by searching the dependency tree", "long_description = description, author = '<NAME>', author_email = '<EMAIL>', url", "dependency tree and copying/patching non-system libraries.', long_description = description, author", "description = 'Makes a macOS binary redistributable by searching the", "'otool', 'mach'], classifiers = [], entry_points = { 'console_scripts': ['macpack=macpack.patcher:main'],", "name = 'macpack', packages = setuptools.find_packages(), version = '1.0.3', description", "and copying/patching non-system libraries.', long_description = description, author = '<NAME>',", "description = pypandoc.convert('README.md', 'rst') if os.path.exists('README.md') else '' except ImportError:" ]
[ "contoursMapper.ScalarVisibilityOn() contoursMapper.SelectColorArray(\"JPEGImage\") contoursMapper.SetScalarRange(scalarRange) contoursActor = vtk.vtkActor() contoursActor.SetMapper(contoursMapper) actor = vtk.vtkActor()", "vtk.vtkContourFilter() contoursFilter.SetInputConnection(imageDataGeometryFilter.GetOutputPort()) contoursFilter.GenerateValues(60, scalarRange) contoursMapper = vtk.vtkPolyDataMapper() contoursMapper.SetInputConnection(contoursFilter.GetOutputPort()) contoursMapper.SetColorModeToMapScalars() contoursMapper.ScalarVisibilityOn()", "file (to test that it was written correctly) reader =", "= vtk.vtkPolyDataMapper() contoursMapper.SetInputConnection(contoursFilter.GetOutputPort()) contoursMapper.SetColorModeToMapScalars() contoursMapper.ScalarVisibilityOn() contoursMapper.SelectColorArray(\"JPEGImage\") contoursMapper.SetScalarRange(scalarRange) contoursActor = vtk.vtkActor()", "vtk.vtkXMLImageDataReader() reader.SetFileName(\"../data/wind_image.vti\") reader.Update() print(reader.GetOutput()) # Convert the image to a", "Convert the image to a polydata imageDataGeometryFilter = vtk.vtkImageDataGeometryFilter() imageDataGeometryFilter.SetInputConnection(reader.GetOutputPort())", "was written correctly) reader = vtk.vtkXMLImageDataReader() reader.SetFileName(\"../data/wind_image.vti\") reader.Update() print(reader.GetOutput()) #", "test that it was written correctly) reader = vtk.vtkXMLImageDataReader() reader.SetFileName(\"../data/wind_image.vti\")", "contoursFilter = vtk.vtkContourFilter() contoursFilter.SetInputConnection(imageDataGeometryFilter.GetOutputPort()) contoursFilter.GenerateValues(60, scalarRange) contoursMapper = vtk.vtkPolyDataMapper() contoursMapper.SetInputConnection(contoursFilter.GetOutputPort())", "vtk.vtkActor() contoursActor.SetMapper(contoursMapper) actor = vtk.vtkActor() actor.SetMapper(contoursMapper) # Setup rendering renderer", "scalarRange) contoursMapper = vtk.vtkPolyDataMapper() contoursMapper.SetInputConnection(contoursFilter.GetOutputPort()) contoursMapper.SetColorModeToMapScalars() contoursMapper.ScalarVisibilityOn() contoursMapper.SelectColorArray(\"JPEGImage\") contoursMapper.SetScalarRange(scalarRange) contoursActor", "that it was written correctly) reader = vtk.vtkXMLImageDataReader() reader.SetFileName(\"../data/wind_image.vti\") reader.Update()", "renderer = vtk.vtkRenderer() renderer.AddActor(actor) renderer.SetBackground(1,1,1) renderer.ResetCamera() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer)", "it was written correctly) reader = vtk.vtkXMLImageDataReader() reader.SetFileName(\"../data/wind_image.vti\") reader.Update() print(reader.GetOutput())", "= reader.GetOutput().GetPointData().GetScalars().GetRange(-1) contoursFilter = vtk.vtkContourFilter() contoursFilter.SetInputConnection(imageDataGeometryFilter.GetOutputPort()) contoursFilter.GenerateValues(60, scalarRange) contoursMapper =", "vtk.vtkPolyDataMapper() contoursMapper.SetInputConnection(contoursFilter.GetOutputPort()) contoursMapper.SetColorModeToMapScalars() contoursMapper.ScalarVisibilityOn() contoursMapper.SelectColorArray(\"JPEGImage\") contoursMapper.SetScalarRange(scalarRange) contoursActor = vtk.vtkActor() contoursActor.SetMapper(contoursMapper)", "contoursMapper.SetInputConnection(contoursFilter.GetOutputPort()) contoursMapper.SetColorModeToMapScalars() contoursMapper.ScalarVisibilityOn() contoursMapper.SelectColorArray(\"JPEGImage\") contoursMapper.SetScalarRange(scalarRange) contoursActor = vtk.vtkActor() contoursActor.SetMapper(contoursMapper) actor", "correctly) reader = vtk.vtkXMLImageDataReader() reader.SetFileName(\"../data/wind_image.vti\") reader.Update() print(reader.GetOutput()) # Convert the", "actor = vtk.vtkActor() actor.SetMapper(contoursMapper) # Setup rendering renderer = vtk.vtkRenderer()", "the image to a polydata imageDataGeometryFilter = vtk.vtkImageDataGeometryFilter() imageDataGeometryFilter.SetInputConnection(reader.GetOutputPort()) imageDataGeometryFilter.Update()", "vtk.vtkImageDataGeometryFilter() imageDataGeometryFilter.SetInputConnection(reader.GetOutputPort()) imageDataGeometryFilter.Update() scalarRange = reader.GetOutput().GetPointData().GetScalars().GetRange(-1) contoursFilter = vtk.vtkContourFilter() contoursFilter.SetInputConnection(imageDataGeometryFilter.GetOutputPort())", "print(reader.GetOutput()) # Convert the image to a polydata imageDataGeometryFilter =", "rendering renderer = vtk.vtkRenderer() renderer.AddActor(actor) renderer.SetBackground(1,1,1) renderer.ResetCamera() renderWindow = vtk.vtkRenderWindow()", "Read the file (to test that it was written correctly)", "to a polydata imageDataGeometryFilter = vtk.vtkImageDataGeometryFilter() imageDataGeometryFilter.SetInputConnection(reader.GetOutputPort()) imageDataGeometryFilter.Update() scalarRange =", "the file (to test that it was written correctly) reader", "a polydata imageDataGeometryFilter = vtk.vtkImageDataGeometryFilter() imageDataGeometryFilter.SetInputConnection(reader.GetOutputPort()) imageDataGeometryFilter.Update() scalarRange = reader.GetOutput().GetPointData().GetScalars().GetRange(-1)", "vtk # Read the file (to test that it was", "image to a polydata imageDataGeometryFilter = vtk.vtkImageDataGeometryFilter() imageDataGeometryFilter.SetInputConnection(reader.GetOutputPort()) imageDataGeometryFilter.Update() scalarRange", "# Setup rendering renderer = vtk.vtkRenderer() renderer.AddActor(actor) renderer.SetBackground(1,1,1) renderer.ResetCamera() renderWindow", "contoursMapper.SelectColorArray(\"JPEGImage\") contoursMapper.SetScalarRange(scalarRange) contoursActor = vtk.vtkActor() contoursActor.SetMapper(contoursMapper) actor = vtk.vtkActor() actor.SetMapper(contoursMapper)", "imageDataGeometryFilter.SetInputConnection(reader.GetOutputPort()) imageDataGeometryFilter.Update() scalarRange = reader.GetOutput().GetPointData().GetScalars().GetRange(-1) contoursFilter = vtk.vtkContourFilter() contoursFilter.SetInputConnection(imageDataGeometryFilter.GetOutputPort()) contoursFilter.GenerateValues(60,", "scalarRange = reader.GetOutput().GetPointData().GetScalars().GetRange(-1) contoursFilter = vtk.vtkContourFilter() contoursFilter.SetInputConnection(imageDataGeometryFilter.GetOutputPort()) contoursFilter.GenerateValues(60, scalarRange) contoursMapper", "reader.SetFileName(\"../data/wind_image.vti\") reader.Update() print(reader.GetOutput()) # Convert the image to a polydata", "contoursMapper.SetColorModeToMapScalars() contoursMapper.ScalarVisibilityOn() contoursMapper.SelectColorArray(\"JPEGImage\") contoursMapper.SetScalarRange(scalarRange) contoursActor = vtk.vtkActor() contoursActor.SetMapper(contoursMapper) actor =", "= vtk.vtkActor() contoursActor.SetMapper(contoursMapper) actor = vtk.vtkActor() actor.SetMapper(contoursMapper) # Setup rendering", "contoursActor.SetMapper(contoursMapper) actor = vtk.vtkActor() actor.SetMapper(contoursMapper) # Setup rendering renderer =", "= vtk.vtkActor() actor.SetMapper(contoursMapper) # Setup rendering renderer = vtk.vtkRenderer() renderer.AddActor(actor)", "renderer.AddActor(actor) renderer.SetBackground(1,1,1) renderer.ResetCamera() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor()", "polydata imageDataGeometryFilter = vtk.vtkImageDataGeometryFilter() imageDataGeometryFilter.SetInputConnection(reader.GetOutputPort()) imageDataGeometryFilter.Update() scalarRange = reader.GetOutput().GetPointData().GetScalars().GetRange(-1) contoursFilter", "actor.SetMapper(contoursMapper) # Setup rendering renderer = vtk.vtkRenderer() renderer.AddActor(actor) renderer.SetBackground(1,1,1) renderer.ResetCamera()", "reader.Update() print(reader.GetOutput()) # Convert the image to a polydata imageDataGeometryFilter", "= vtk.vtkContourFilter() contoursFilter.SetInputConnection(imageDataGeometryFilter.GetOutputPort()) contoursFilter.GenerateValues(60, scalarRange) contoursMapper = vtk.vtkPolyDataMapper() contoursMapper.SetInputConnection(contoursFilter.GetOutputPort()) contoursMapper.SetColorModeToMapScalars()", "contoursFilter.GenerateValues(60, scalarRange) contoursMapper = vtk.vtkPolyDataMapper() contoursMapper.SetInputConnection(contoursFilter.GetOutputPort()) contoursMapper.SetColorModeToMapScalars() contoursMapper.ScalarVisibilityOn() contoursMapper.SelectColorArray(\"JPEGImage\") contoursMapper.SetScalarRange(scalarRange)", "Setup rendering renderer = vtk.vtkRenderer() renderer.AddActor(actor) renderer.SetBackground(1,1,1) renderer.ResetCamera() renderWindow =", "renderer.SetBackground(1,1,1) renderer.ResetCamera() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow)", "contoursMapper = vtk.vtkPolyDataMapper() contoursMapper.SetInputConnection(contoursFilter.GetOutputPort()) contoursMapper.SetColorModeToMapScalars() contoursMapper.ScalarVisibilityOn() contoursMapper.SelectColorArray(\"JPEGImage\") contoursMapper.SetScalarRange(scalarRange) contoursActor =", "# Convert the image to a polydata imageDataGeometryFilter = vtk.vtkImageDataGeometryFilter()", "contoursMapper.SetScalarRange(scalarRange) contoursActor = vtk.vtkActor() contoursActor.SetMapper(contoursMapper) actor = vtk.vtkActor() actor.SetMapper(contoursMapper) #", "contoursActor = vtk.vtkActor() contoursActor.SetMapper(contoursMapper) actor = vtk.vtkActor() actor.SetMapper(contoursMapper) # Setup", "# Read the file (to test that it was written", "imageDataGeometryFilter = vtk.vtkImageDataGeometryFilter() imageDataGeometryFilter.SetInputConnection(reader.GetOutputPort()) imageDataGeometryFilter.Update() scalarRange = reader.GetOutput().GetPointData().GetScalars().GetRange(-1) contoursFilter =", "= vtk.vtkImageDataGeometryFilter() imageDataGeometryFilter.SetInputConnection(reader.GetOutputPort()) imageDataGeometryFilter.Update() scalarRange = reader.GetOutput().GetPointData().GetScalars().GetRange(-1) contoursFilter = vtk.vtkContourFilter()", "vtk.vtkRenderer() renderer.AddActor(actor) renderer.SetBackground(1,1,1) renderer.ResetCamera() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor =", "vtk.vtkActor() actor.SetMapper(contoursMapper) # Setup rendering renderer = vtk.vtkRenderer() renderer.AddActor(actor) renderer.SetBackground(1,1,1)", "renderer.ResetCamera() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderWindowInteractor.Start()", "(to test that it was written correctly) reader = vtk.vtkXMLImageDataReader()", "imageDataGeometryFilter.Update() scalarRange = reader.GetOutput().GetPointData().GetScalars().GetRange(-1) contoursFilter = vtk.vtkContourFilter() contoursFilter.SetInputConnection(imageDataGeometryFilter.GetOutputPort()) contoursFilter.GenerateValues(60, scalarRange)", "= vtk.vtkRenderer() renderer.AddActor(actor) renderer.SetBackground(1,1,1) renderer.ResetCamera() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor", "contoursFilter.SetInputConnection(imageDataGeometryFilter.GetOutputPort()) contoursFilter.GenerateValues(60, scalarRange) contoursMapper = vtk.vtkPolyDataMapper() contoursMapper.SetInputConnection(contoursFilter.GetOutputPort()) contoursMapper.SetColorModeToMapScalars() contoursMapper.ScalarVisibilityOn() contoursMapper.SelectColorArray(\"JPEGImage\")", "reader = vtk.vtkXMLImageDataReader() reader.SetFileName(\"../data/wind_image.vti\") reader.Update() print(reader.GetOutput()) # Convert the image", "reader.GetOutput().GetPointData().GetScalars().GetRange(-1) contoursFilter = vtk.vtkContourFilter() contoursFilter.SetInputConnection(imageDataGeometryFilter.GetOutputPort()) contoursFilter.GenerateValues(60, scalarRange) contoursMapper = vtk.vtkPolyDataMapper()", "import vtk # Read the file (to test that it", "= vtk.vtkXMLImageDataReader() reader.SetFileName(\"../data/wind_image.vti\") reader.Update() print(reader.GetOutput()) # Convert the image to", "written correctly) reader = vtk.vtkXMLImageDataReader() reader.SetFileName(\"../data/wind_image.vti\") reader.Update() print(reader.GetOutput()) # Convert" ]
[ "ob, 'action': action}) ob_error = np.sum(np.abs(newob_from_api - new_ob)) ob =", "self._env.env.sim.data.qpos qvel = self._env.env.sim.data.qvel \"\"\" if self._env_name == 'gym_doublePendulum': if", "----------------------------------------------------------------------------- # @brief: # Tingwu: reset the reward function so", "if 'reset_type' in misc_info and misc_info['reset_type'] == 'gym': self._reset_return_obs_only =", "** 2 v1, v2 = self.model.data.qvel[1:3] vel_penalty = 1e-3 *", "self._current_version in ['0.7.4', '0.9.4']: _env_name = { 'gym_invertedPendulum': 'InvertedPendulum-v1', }", "def step(self, action): _, _, _, info = self._env.step(action) ob", "'action': action} ) # from mbbl.util.common.fpdb import fpdb; fpdb().set_trace() #", "new environments, if we don't set their ground-truth apis, then", "qvel[:] = data_dict['start_state'][ self._len_qpos: self._len_qpos + self._len_qvel ] # reset", "r = (alive_bonus - dist_penalty - vel_penalty)[0] done = bool(y", "= bool(y <= 1) return ob, r, done, {} reward:", "self._env.env.sim.data.qpos = qpos.reshape([-1]) self._env.env.sim.data.qvel = qpos.reshape([-1]) self._env.env.model._compute_subtree() # pylint: disable=W0212", "function assert self._env_name in self.PENDULUM \"\"\" xpos_ob_pos = \\ {'gym_pendulum':", "# reset the state if self._current_version in ['0.7.4', '0.9.4']: self._env.env.data.qpos", "raise ValueError(\"Invalid gym-{}\".format(self._current_version)) # make the environments self._env_info = env_register.get_env_info(self._env_name)", "gym self._current_version = gym.__version__ if self._current_version in ['0.7.4', '0.9.4']: _env_name", "self._old_ob.copy(), 0.0, False, {} def _get_observation(self): if self._current_version in ['0.7.4',", "= np.zeros( [num_data, self._env_info['ob_size'], self._env_info['ob_size']], dtype=np.float ) # the xpos", "self._env.reset() self.set_state({'start_state': self._old_ob.copy()}) self._old_ob = self._get_observation() if self._reset_return_obs_only: return self._old_ob.copy()", "flag to ignore self._old_ob = np.array(ob) return ob, reward, done,", "reward: @xpos_penalty: x ** 2 @ypos_penalty: (y - 2) **", "from mbbl.env import env_util from mbbl.util.common import logger class env(bew.base_env):", "reward = 1.0 self.do_simulation(a, self.frame_skip) ob = self._get_obs() notdone =", "= env(env_name, 1234, {}) api_env = env(env_name, 1234, {}) api_env.reset()", "\\ - 2.0 elif target == 'action-state': derivative_data = np.zeros(", "part derivative_data[:, xpos_ob_pos] += - 2.0 * xpos_coeff * \\", "mbbl.env import base_env_wrapper as bew from mbbl.env import env_register from", "= np.random.uniform(-1, 1, test_env._env.action_space.shape) new_ob, reward, _, _ = test_env.step(action)", "is a hack, there is some precision issue in mujoco_py", "following is a hack, there is some precision issue in", "1) qvel: 2 (2, 3) double_pendulum: (slide, hinge, hinge) qpos:", "= \\ self._env.observation_space, self._env.action_space # it's possible some environments have", "-> set logger flag to ignore self._old_ob = np.array(ob) return", "- 2) ** 2 pendulum: (slide, hinge) qpos: 2 (0,", "reward)) # test the dynamics api newob_from_api = \\ api_env.fdynamics({'start_state':", "= 10 r = (alive_bonus - dist_penalty - vel_penalty)[0] done", "0, 'gym_doublePendulum': 6}[self._env_name] ypos_ob_pos = \\ {'gym_pendulum': 1, 'gym_doublePendulum': 7}[self._env_name]", "bool(y <= 1) return ob, r, done, {} reward: @xpos_penalty:", "is some precision issue in mujoco_py self._old_ob = self._get_observation() self._env.reset()", "in misc_info and misc_info['reset_type'] == 'gym': self._reset_return_obs_only = True self.observation_space,", "import fpdb; fpdb().set_trace() # get the end signal self._current_step +=", "np.zeros([self._len_qvel]) qpos[:] = data_dict['start_state'][:self._len_qpos] qvel[:] = data_dict['start_state'][ self._len_qpos: self._len_qpos +", "(y - 2) ** 2 v1, v2 = self.model.data.qvel[1:3] vel_penalty", "in ['0.7.4', '0.9.4']: qpos = self._env.env.data.qpos qvel = self._env.env.data.qvel else:", "['0.7.4', '0.9.4']: qpos = self._env.env.data.qpos qvel = self._env.env.data.qvel else: qpos", "different obs self.observation_space = \\ env_util.box(self._env_info['ob_size'], -1, 1) else: self._reset_return_obs_only", "- vel_penalty)[0] done = bool(y <= 1) return ob, r,", "0.0, False, {} def _get_observation(self): if self._current_version in ['0.7.4', '0.9.4']:", "return self._old_ob.copy(), 0.0, False, {} def _get_observation(self): if self._current_version in", "derivative_data = np.zeros( [num_data, self._env_info['ob_size'], self._env_info['ob_size']], dtype=np.float ) # the", "self._env_info['action_size']], dtype=np.float ) else: assert False, logger.error('Invalid target {}'.format(target)) return", "ypos_target) ** 2 return xpos_reward + ypos_reward self.reward = reward", "= True else: done = False # will raise warnings", "self.model.data.site_xpos[0] dist_penalty = 0.01 * x ** 2 + (y", "xpos_ob_pos = 0 ypos_ob_pos = 1 ypos_target = 0.0 xpos_coeff", "ypos reward part derivative_data[:, ypos_ob_pos] += - 2.0 * \\", "\\ api_env.fdynamics({'start_state': ob, 'action': action}) ob_error = np.sum(np.abs(newob_from_api - new_ob))", "def _set_groundtruth_api(self): \"\"\" @brief: In this function, we could provide", "\\ {'gym_pendulum': 1, 'gym_doublePendulum': 7}[self._env_name] ypos_target = \\ {'gym_pendulum': 0.0,", "reward, _, _ = test_env.step(action) # test the reward api", "== 'action-state': derivative_data = np.zeros( [num_data, self._env_info['action_size'], self._env_info['ob_size']], dtype=np.float )", "gym versions here _env_name = { 'gym_invertedPendulum': 'InvertedPendulum-v2', } else:", "if self._current_version in ['0.7.4', '0.9.4']: self._env.env.data.qpos = qpos.reshape([-1, 1]) self._env.env.data.qvel", "1) else: self._reset_return_obs_only = False def step(self, action): _, _,", "test_env.reset() for _ in range(100): action = np.random.uniform(-1, 1, test_env._env.action_space.shape)", "hinge) qpos: 3 (0, 1, 2) qvel: 3 (3, 4,", "['gym_doublePendulum'] test_env_name = ['gym_invertedPendulum'] for env_name in test_env_name: test_env =", "_ in range(100): action = np.random.uniform(-1, 1, test_env._env.action_space.shape) new_ob, reward,", "{} def _get_observation(self): if self._current_version in ['0.7.4', '0.9.4']: qpos =", "xpos_reward = -(xpos ** 2) * xpos_coeff # ypos penalty", "info def reset(self, control_info={}): self._current_step = 0 self._env.reset() # the", "self._env_info['action_size']], dtype=np.float ) elif target == 'state-state': derivative_data = np.zeros(", "env_name in test_env_name: test_env = env(env_name, 1234, {}) api_env =", "set the zero-order reward function assert self._env_name in self.PENDULUM \"\"\"", "['0.7.4', '0.9.4']: self._env.env.data.qpos = qpos.reshape([-1, 1]) self._env.env.data.qvel = qvel.reshape([-1, 1])", "self._current_version in ['0.7.4', '0.9.4']: qpos = self._env.env.data.qpos qvel = self._env.env.data.qvel", "target == 'state-action': derivative_data = np.zeros( [num_data, self._env_info['ob_size'], self._env_info['action_size']], dtype=np.float", "gym-{}\".format(self._current_version)) # make the environments self._env_info = env_register.get_env_info(self._env_name) self._env_name =", "ypos_reward self.reward = reward def reward_derivative(data_dict, target): num_data = len(data_dict['start_state'])", "ypos_reward = -(ypos - ypos_target) ** 2 return xpos_reward +", "self._env.env.model.forward() self._old_ob = self._get_observation() self.set_state = set_state def fdynamics(data_dict): #", "\\ (data_dict['start_state'][:, ypos_ob_pos] - ypos_target) elif target == 'action': derivative_data", "reward_from_api = \\ api_env.reward({'start_state': ob, 'action': action}) reward_error = np.sum(np.abs(reward_from_api", "- new_ob)) ob = new_ob print('reward error: {}, dynamics error:", "= { 'gym_invertedPendulum': 'InvertedPendulum-v1', } elif self._current_version == NotImplementedError: #", "= self._env_name.split('-')[0] self._env = gym.make(_env_name[self._env_name]) def _set_groundtruth_api(self): \"\"\" @brief: In", "'0.9.4']: _env_name = { 'gym_invertedPendulum': 'InvertedPendulum-v1', } elif self._current_version ==", "1]) self._env.env.data.qvel = qvel.reshape([-1, 1]) else: self._env.env.sim.data.qpos = qpos.reshape([-1]) self._env.env.sim.data.qvel", "ypos_ob_pos = 1 ypos_target = 0.0 xpos_coeff = 0.0 def", "'gym_doublePendulum': 7}[self._env_name] ypos_target = \\ {'gym_pendulum': 0.0, 'gym_doublePendulum': 2}[self._env_name] xpos_coeff", "== 'gym': self._reset_return_obs_only = True self.observation_space, self.action_space = \\ self._env.observation_space,", "return xpos_reward + ypos_reward self.reward = reward def reward_derivative(data_dict, target):", "call. For the new environments, if we don't set their", "reward, _, _ = test_env.reset() for _ in range(100): action", "self.fynamics() self.set_state(data_dict) return self.step(data_dict['action'])[0] self.fdynamics = fdynamics def _set_reward_api(self): \"\"\"", "qpos[:] = data_dict['start_state'][:self._len_qpos] qvel[:] = data_dict['start_state'][ self._len_qpos: self._len_qpos + self._len_qvel", "* v1**2 + 5e-3 * v2**2 alive_bonus = 10 r", "= self.model.data.site_xpos[0] dist_penalty = 0.01 * x ** 2 +", "import numpy as np from mbbl.config import init_path from mbbl.env", "= 0 ypos_ob_pos = 1 ypos_target = 0.0 xpos_coeff =", "_, _, info = self._env.step(action) ob = self._get_observation() # get", "- 2.0 * \\ (data_dict['start_state'][:, ypos_ob_pos] - ypos_target) elif target", "test the reward api reward_from_api = \\ api_env.reward({'start_state': ob, 'action':", "self.frame_skip) ob = self._get_obs() notdone = np.isfinite(ob).all() and (np.abs(ob[1]) <=", "qvel = np.zeros([self._len_qvel]) qpos[:] = data_dict['start_state'][:self._len_qpos] qvel[:] = data_dict['start_state'][ self._len_qpos:", "= self._env.step(action) ob = self._get_observation() # get the reward reward", "misc_info) self._base_path = init_path.get_abs_base_dir() self._len_qpos, self._len_qvel = \\ env_util.get_gym_q_info(self._env, self._current_version)", "= 1.0 self.do_simulation(a, self.frame_skip) ob = self._get_obs() notdone = np.isfinite(ob).all()", "for env_name in test_env_name: test_env = env(env_name, 1234, {}) api_env", "misc_info['reset_type'] == 'gym': self._reset_return_obs_only = True self.observation_space, self.action_space = \\", "done, info def reset(self, control_info={}): self._current_step = 0 self._env.reset() #", "derivative_data[:, xpos_ob_pos, xpos_ob_pos] += \\ - 2.0 * xpos_coeff #", "derivative_data[:, ypos_ob_pos] += - 2.0 * \\ (data_dict['start_state'][:, ypos_ob_pos] -", "1, test_env._env.action_space.shape) new_ob, reward, _, _ = test_env.step(action) # test", "range(100): action = np.random.uniform(-1, 1, test_env._env.action_space.shape) new_ob, reward, _, _", "elif target == 'state-state': derivative_data = np.zeros( [num_data, self._env_info['ob_size'], self._env_info['ob_size']],", ") # from mbbl.util.common.fpdb import fpdb; fpdb().set_trace() # get the", "self._old_ob = self._get_observation() if self._reset_return_obs_only: return self._old_ob.copy() else: return self._old_ob.copy(),", "mbbl.util.common import logger class env(bew.base_env): # acrobot has applied sin/cos", "mbbl.env import env_util from mbbl.util.common import logger class env(bew.base_env): #", "2.0 * xpos_coeff * \\ (data_dict['start_state'][:, xpos_ob_pos]) # the ypos", "env(bew.base_env): # acrobot has applied sin/cos obs PENDULUM = ['gym_invertedPendulum']", "vel_penalty = 1e-3 * v1**2 + 5e-3 * v2**2 alive_bonus", "import env_util from mbbl.util.common import logger class env(bew.base_env): # acrobot", "== 'state-action': derivative_data = np.zeros( [num_data, self._env_info['ob_size'], self._env_info['action_size']], dtype=np.float )", "- dist_penalty - vel_penalty)[0] done = bool(y <= 1) return", "7}[self._env_name] ypos_target = \\ {'gym_pendulum': 0.0, 'gym_doublePendulum': 2}[self._env_name] xpos_coeff =", "np.zeros( [num_data, self._env_info['ob_size'], self._env_info['ob_size']], dtype=np.float ) # the xpos reward", "1 info['current_step'] = self._current_step if self._current_step > self._env_info['max_length']: done =", "the end signal self._current_step += 1 info['current_step'] = self._current_step if", "target == 'state': derivative_data = np.zeros( [num_data, self._env_info['ob_size']], dtype=np.float )", "self.do_simulation(a, self.frame_skip) ob = self._get_obs() notdone = np.isfinite(ob).all() and (np.abs(ob[1])", "self._len_qpos, self._len_qvel = \\ env_util.get_gym_q_info(self._env, self._current_version) # return the reset", "self._env.action_space # it's possible some environments have different obs self.observation_space", "ypos penalty ypos = data_dict['start_state'][ypos_ob_pos] ypos_reward = -(ypos - ypos_target)", "action}) reward_error = np.sum(np.abs(reward_from_api - reward)) # test the dynamics", "2]] else: site_xpos = self._env.env.sim.data.site_xpos[:, [0, 2]] site_xpos = np.transpose(site_xpos)", "** 2 return xpos_reward + ypos_reward self.reward = reward def", "init_path.get_abs_base_dir() self._len_qpos, self._len_qvel = \\ env_util.get_gym_q_info(self._env, self._current_version) # return the", "# ypos penalty ypos = data_dict['start_state'][ypos_ob_pos] ypos_reward = -(ypos -", "4, 5) site_pose: 2 (6, 7) \"\"\" # step 1,", "target): num_data = len(data_dict['start_state']) if target == 'state': derivative_data =", "----------------------------------------------------------------------------- \"\"\" import numpy as np from mbbl.config import init_path", "_build_env(self): import gym self._current_version = gym.__version__ if self._current_version in ['0.7.4',", "False, logger.error('Invalid target {}'.format(target)) return derivative_data self.reward_derivative = reward_derivative def", "{} reward: @xpos_penalty: x ** 2 @ypos_penalty: (y - 2)", "= init_path.get_abs_base_dir() self._len_qpos, self._len_qvel = \\ env_util.get_gym_q_info(self._env, self._current_version) # return", "{}) api_env.reset() ob, reward, _, _ = test_env.reset() for _", "# @brief: # Tingwu: reset the reward function so that", "other gym versions here _env_name = { 'gym_invertedPendulum': 'InvertedPendulum-v2', }", "In this function, we could provide the ground-truth dynamics and", "reward api reward_from_api = \\ api_env.reward({'start_state': ob, 'action': action}) reward_error", "= np.zeros( [num_data, self._env_info['action_size']], dtype=np.float ) elif target == 'state-state':", "# the following is a hack, there is some precision", "self._len_qpos + self._len_qvel ] # reset the state if self._current_version", "{}'.format(target)) return derivative_data self.reward_derivative = reward_derivative def render(self, *args, **kwargs):", "= np.zeros( [num_data, self._env_info['action_size'], self._env_info['ob_size']], dtype=np.float ) elif target ==", "self._env_info = env_register.get_env_info(self._env_name) self._env_name = self._env_name.split('-')[0] self._env = gym.make(_env_name[self._env_name]) def", "['gym_invertedPendulum'] for env_name in test_env_name: test_env = env(env_name, 1234, {})", "else: self._env.env.sim.data.qpos = qpos.reshape([-1]) self._env.env.sim.data.qvel = qpos.reshape([-1]) self._env.env.model._compute_subtree() # pylint:", "derivative_data[:, ypos_ob_pos, ypos_ob_pos] += \\ - 2.0 elif target ==", "agent to call. For the new environments, if we don't", "For the new environments, if we don't set their ground-truth", "for the agent to call. For the new environments, if", "self._env_info['ob_size'], self._env_info['ob_size']], dtype=np.float ) # the xpos reward derivative_data[:, xpos_ob_pos,", "warnings -> set logger flag to ignore self._old_ob = np.array(ob)", "= self._env.env.data.qpos qvel = self._env.env.data.qvel else: qpos = self._env.env.sim.data.qpos qvel", "init_path from mbbl.env import base_env_wrapper as bew from mbbl.env import", "self._env.step(action) ob = self._get_observation() # get the reward reward =", ") elif target == 'action-action': derivative_data = np.zeros( [num_data, self._env_info['action_size'],", "self._env_name = self._env_name.split('-')[0] self._env = gym.make(_env_name[self._env_name]) def _set_groundtruth_api(self): \"\"\" @brief:", "= gym.make(_env_name[self._env_name]) def _set_groundtruth_api(self): \"\"\" @brief: In this function, we", "def __init__(self, env_name, rand_seed, misc_info): super(env, self).__init__(env_name, rand_seed, misc_info) self._base_path", "** 2 pendulum: (slide, hinge) qpos: 2 (0, 1) qvel:", "-(ypos - ypos_target) ** 2 return xpos_reward + ypos_reward self.reward", "_set_reward_api(self): \"\"\" def _step(self, a): reward = 1.0 self.do_simulation(a, self.frame_skip)", "import base_env_wrapper as bew from mbbl.env import env_register from mbbl.env", "3 (0, 1, 2) qvel: 3 (3, 4, 5) site_pose:", "# the ypos reward derivative_data[:, ypos_ob_pos, ypos_ob_pos] += \\ -", "the reward api reward_from_api = \\ api_env.reward({'start_state': ob, 'action': action})", "penalty xpos = data_dict['start_state'][xpos_ob_pos] xpos_reward = -(xpos ** 2) *", "= data_dict['start_state'][xpos_ob_pos] xpos_reward = -(xpos ** 2) * xpos_coeff #", "- 2.0 * xpos_coeff * \\ (data_dict['start_state'][:, xpos_ob_pos]) # the", "self._get_observation() if self._reset_return_obs_only: return self._old_ob.copy() else: return self._old_ob.copy(), 0.0, False,", "self.do_simulation(action, self.frame_skip) ob = self._get_obs() x, _, y = self.model.data.site_xpos[0]", "control_info={}): self._current_step = 0 self._env.reset() # the following is a", "issue in mujoco_py self._old_ob = self._get_observation() self._env.reset() self.set_state({'start_state': self._old_ob.copy()}) self._old_ob", "\"\"\" assert self._env_name == 'gym_invertedPendulum' return np.concatenate([qpos, qvel]).ravel() def _build_env(self):", "some precision issue in mujoco_py self._old_ob = self._get_observation() self._env.reset() self.set_state({'start_state':", "} elif self._current_version == NotImplementedError: # TODO: other gym versions", "5e-3 * v2**2 alive_bonus = 10 r = (alive_bonus -", "# get the reward reward = self.reward( {'end_state': ob, 'start_state':", "= { 'gym_invertedPendulum': 'InvertedPendulum-v2', } else: raise ValueError(\"Invalid gym-{}\".format(self._current_version)) #", "return if __name__ == '__main__': # test_env_name = ['gym_doublePendulum'] test_env_name", "(2, 3) double_pendulum: (slide, hinge, hinge) qpos: 3 (0, 1,", "= \\ {'gym_pendulum': 0.0, 'gym_doublePendulum': 2}[self._env_name] xpos_coeff = \\ {'gym_pendulum':", "= \\ {'gym_pendulum': 0.0, 'gym_doublePendulum': 0.01}[self._env_name] \"\"\" xpos_ob_pos = 0", "_env_name = { 'gym_invertedPendulum': 'InvertedPendulum-v1', } elif self._current_version == NotImplementedError:", "0.0 def reward(data_dict): # xpos penalty xpos = data_dict['start_state'][xpos_ob_pos] xpos_reward", "fdynamics def _set_reward_api(self): \"\"\" def _step(self, a): reward = 1.0", "the one # defined in GYM # ----------------------------------------------------------------------------- \"\"\" import", "= np.zeros([self._len_qpos]) qvel = np.zeros([self._len_qvel]) qpos[:] = data_dict['start_state'][:self._len_qpos] qvel[:] =", "as np from mbbl.config import init_path from mbbl.env import base_env_wrapper", "numpy as np from mbbl.config import init_path from mbbl.env import", "_, _ = test_env.reset() for _ in range(100): action =", "_step(self, a): reward = 1.0 self.do_simulation(a, self.frame_skip) ob = self._get_obs()", "qpos: 3 (0, 1, 2) qvel: 3 (3, 4, 5)", "newob_from_api = \\ api_env.fdynamics({'start_state': ob, 'action': action}) ob_error = np.sum(np.abs(newob_from_api", "\\ env_util.box(self._env_info['ob_size'], -1, 1) else: self._reset_return_obs_only = False def step(self,", "reward derivative_data[:, ypos_ob_pos, ypos_ob_pos] += \\ - 2.0 elif target", "env_register.get_env_info(self._env_name) self._env_name = self._env_name.split('-')[0] self._env = gym.make(_env_name[self._env_name]) def _set_groundtruth_api(self): \"\"\"", "2 (0, 1) qvel: 2 (2, 3) double_pendulum: (slide, hinge,", "_env_name = { 'gym_invertedPendulum': 'InvertedPendulum-v2', } else: raise ValueError(\"Invalid gym-{}\".format(self._current_version))", "# test the dynamics api newob_from_api = \\ api_env.fdynamics({'start_state': ob,", "2 @ypos_penalty: (y - 2) ** 2 pendulum: (slide, hinge)", "in mujoco_py self._old_ob = self._get_observation() self._env.reset() self.set_state({'start_state': self._old_ob.copy()}) self._old_ob =", "'action': action}) ob_error = np.sum(np.abs(newob_from_api - new_ob)) ob = new_ob", "= False # will raise warnings -> set logger flag", "'0.9.4']: site_xpos = self._env.env.data.site_xpos[:, [0, 2]] else: site_xpos = self._env.env.sim.data.site_xpos[:,", "xpos = data_dict['start_state'][xpos_ob_pos] xpos_reward = -(xpos ** 2) * xpos_coeff", "self.observation_space = \\ env_util.box(self._env_info['ob_size'], -1, 1) else: self._reset_return_obs_only = False", "- 2) ** 2 v1, v2 = self.model.data.qvel[1:3] vel_penalty =", "api_env.fdynamics({'start_state': ob, 'action': action}) ob_error = np.sum(np.abs(newob_from_api - new_ob)) ob", "= (alive_bonus - dist_penalty - vel_penalty)[0] done = bool(y <=", "= 1 ypos_target = 0.0 xpos_coeff = 0.0 def reward(data_dict):", "obs PENDULUM = ['gym_invertedPendulum'] def __init__(self, env_name, rand_seed, misc_info): super(env,", "xpos_coeff * \\ (data_dict['start_state'][:, xpos_ob_pos]) # the ypos reward part", "5) site_pose: 2 (6, 7) \"\"\" # step 1, set", "test_env = env(env_name, 1234, {}) api_env = env(env_name, 1234, {})", "= self._get_observation() self._env.reset() self.set_state({'start_state': self._old_ob.copy()}) self._old_ob = self._get_observation() if self._reset_return_obs_only:", "the new environments, if we don't set their ground-truth apis,", "self._current_step = 0 self._env.reset() # the following is a hack,", "fdynamics(data_dict): # make sure reset is called before using self.fynamics()", "{'gym_pendulum': 0.0, 'gym_doublePendulum': 2}[self._env_name] xpos_coeff = \\ {'gym_pendulum': 0.0, 'gym_doublePendulum':", "def reward(data_dict): # xpos penalty xpos = data_dict['start_state'][xpos_ob_pos] xpos_reward =", "reward def reward_derivative(data_dict, target): num_data = len(data_dict['start_state']) if target ==", "then we cannot test the algorithm using ground-truth dynamics or", "0.0, 'gym_doublePendulum': 0.01}[self._env_name] \"\"\" xpos_ob_pos = 0 ypos_ob_pos = 1", "mbbl.config import init_path from mbbl.env import base_env_wrapper as bew from", "self._env_info['ob_size'], self._env_info['action_size']], dtype=np.float ) elif target == 'action-action': derivative_data =", "api reward_from_api = \\ api_env.reward({'start_state': ob, 'action': action}) reward_error =", "ground-truth dynamics or reward \"\"\" self._set_reward_api() self._set_dynamics_api() def _set_dynamics_api(self): def", "\\ {'gym_pendulum': 0, 'gym_doublePendulum': 6}[self._env_name] ypos_ob_pos = \\ {'gym_pendulum': 1,", "- reward)) # test the dynamics api newob_from_api = \\", "# pylint: disable=W0212 self._env.env.model.forward() self._old_ob = self._get_observation() self.set_state = set_state", "\"\"\" # step 1, set the zero-order reward function assert", "from mbbl.config import init_path from mbbl.env import base_env_wrapper as bew", "= ['gym_doublePendulum'] test_env_name = ['gym_invertedPendulum'] for env_name in test_env_name: test_env", "in ['0.7.4', '0.9.4']: self._env.env.data.qpos = qpos.reshape([-1, 1]) self._env.env.data.qvel = qvel.reshape([-1,", "= data_dict['start_state'][ self._len_qpos: self._len_qpos + self._len_qvel ] # reset the", "self._get_observation() self._env.reset() self.set_state({'start_state': self._old_ob.copy()}) self._old_ob = self._get_observation() if self._reset_return_obs_only: return", "_ = test_env.reset() for _ in range(100): action = np.random.uniform(-1,", "= \\ env_util.box(self._env_info['ob_size'], -1, 1) else: self._reset_return_obs_only = False def", "reset the reward function so that it's more similar to", "= fdynamics def _set_reward_api(self): \"\"\" def _step(self, a): reward =", "reward part derivative_data[:, xpos_ob_pos] += - 2.0 * xpos_coeff *", "1234, {}) api_env = env(env_name, 1234, {}) api_env.reset() ob, reward,", "{'gym_pendulum': 1, 'gym_doublePendulum': 7}[self._env_name] ypos_target = \\ {'gym_pendulum': 0.0, 'gym_doublePendulum':", "so that it's more similar to the one # defined", "return ob, r, done, {} reward: @xpos_penalty: x ** 2", "elif target == 'action-state': derivative_data = np.zeros( [num_data, self._env_info['action_size'], self._env_info['ob_size']],", "\"\"\" def _step(self, a): reward = 1.0 self.do_simulation(a, self.frame_skip) ob", "xpos_ob_pos, xpos_ob_pos] += \\ - 2.0 * xpos_coeff # the", "else: return self._old_ob.copy(), 0.0, False, {} def _get_observation(self): if self._current_version", "self._env_name.split('-')[0] self._env = gym.make(_env_name[self._env_name]) def _set_groundtruth_api(self): \"\"\" @brief: In this", "the ypos reward derivative_data[:, ypos_ob_pos, ypos_ob_pos] += \\ - 2.0", "['0.7.4', '0.9.4']: _env_name = { 'gym_invertedPendulum': 'InvertedPendulum-v1', } elif self._current_version", "self._env.env.sim.data.site_xpos[:, [0, 2]] site_xpos = np.transpose(site_xpos) return np.concatenate([qpos, qvel, site_xpos]).ravel()", "that it's more similar to the one # defined in", "hack, there is some precision issue in mujoco_py self._old_ob =", "the ypos reward part derivative_data[:, ypos_ob_pos] += - 2.0 *", "self._base_path = init_path.get_abs_base_dir() self._len_qpos, self._len_qvel = \\ env_util.get_gym_q_info(self._env, self._current_version) #", "x ** 2 + (y - 2) ** 2 v1,", "\\ self._env.observation_space, self._env.action_space # it's possible some environments have different", "True else: done = False # will raise warnings ->", "= gym.__version__ if self._current_version in ['0.7.4', '0.9.4']: _env_name = {", "self._get_observation() self.set_state = set_state def fdynamics(data_dict): # make sure reset", "info['current_step'] = self._current_step if self._current_step > self._env_info['max_length']: done = True", "2 + (y - 2) ** 2 v1, v2 =", "np.zeros( [num_data, self._env_info['action_size']], dtype=np.float ) elif target == 'state-state': derivative_data", "['gym_invertedPendulum'] def __init__(self, env_name, rand_seed, misc_info): super(env, self).__init__(env_name, rand_seed, misc_info)", "misc_info and misc_info['reset_type'] == 'gym': self._reset_return_obs_only = True self.observation_space, self.action_space", "_, info = self._env.step(action) ob = self._get_observation() # get the", "} else: raise ValueError(\"Invalid gym-{}\".format(self._current_version)) # make the environments self._env_info", "+= 1 info['current_step'] = self._current_step if self._current_step > self._env_info['max_length']: done", "def fdynamics(data_dict): # make sure reset is called before using", "'gym_doublePendulum': 6}[self._env_name] ypos_ob_pos = \\ {'gym_pendulum': 1, 'gym_doublePendulum': 7}[self._env_name] ypos_target", "[num_data, self._env_info['ob_size']], dtype=np.float ) # the xpos reward part derivative_data[:,", "if self._current_version in ['0.7.4', '0.9.4']: site_xpos = self._env.env.data.site_xpos[:, [0, 2]]", "get the reward reward = self.reward( {'end_state': ob, 'start_state': self._old_ob,", "assert self._env_name == 'gym_invertedPendulum' return np.concatenate([qpos, qvel]).ravel() def _build_env(self): import", "\\ api_env.reward({'start_state': ob, 'action': action}) reward_error = np.sum(np.abs(reward_from_api - reward))", "ob = new_ob print('reward error: {}, dynamics error: {}'.format( reward_error,", "in range(100): action = np.random.uniform(-1, 1, test_env._env.action_space.shape) new_ob, reward, _,", "ignore self._old_ob = np.array(ob) return ob, reward, done, info def", "self._env_info['action_size'], self._env_info['ob_size']], dtype=np.float ) elif target == 'state-action': derivative_data =", "> self._env_info['max_length']: done = True else: done = False #", "data_dict['start_state'][ self._len_qpos: self._len_qpos + self._len_qvel ] # reset the state", "2.0 elif target == 'action-state': derivative_data = np.zeros( [num_data, self._env_info['action_size'],", "assert False, logger.error('Invalid target {}'.format(target)) return derivative_data self.reward_derivative = reward_derivative", "qvel.reshape([-1, 1]) else: self._env.env.sim.data.qpos = qpos.reshape([-1]) self._env.env.sim.data.qvel = qpos.reshape([-1]) self._env.env.model._compute_subtree()", "def render(self, *args, **kwargs): return if __name__ == '__main__': #", "self._env_info['ob_size']], dtype=np.float ) # the xpos reward derivative_data[:, xpos_ob_pos, xpos_ob_pos]", "self._reset_return_obs_only: return self._old_ob.copy() else: return self._old_ob.copy(), 0.0, False, {} def", "applied sin/cos obs PENDULUM = ['gym_invertedPendulum'] def __init__(self, env_name, rand_seed,", "True self.observation_space, self.action_space = \\ self._env.observation_space, self._env.action_space # it's possible", "and misc_info['reset_type'] == 'gym': self._reset_return_obs_only = True self.observation_space, self.action_space =", "qvel]).ravel() def _build_env(self): import gym self._current_version = gym.__version__ if self._current_version", "[num_data, self._env_info['action_size'], self._env_info['action_size']], dtype=np.float ) else: assert False, logger.error('Invalid target", "defined in GYM # ----------------------------------------------------------------------------- \"\"\" import numpy as np", "ob = self._get_obs() x, _, y = self.model.data.site_xpos[0] dist_penalty =", "xpos reward derivative_data[:, xpos_ob_pos, xpos_ob_pos] += \\ - 2.0 *", "2 (6, 7) \"\"\" # step 1, set the zero-order", "import env_register from mbbl.env import env_util from mbbl.util.common import logger", "penalty ypos = data_dict['start_state'][ypos_ob_pos] ypos_reward = -(ypos - ypos_target) **", "or reward \"\"\" self._set_reward_api() self._set_dynamics_api() def _set_dynamics_api(self): def set_state(data_dict): qpos", "= self._get_observation() self.set_state = set_state def fdynamics(data_dict): # make sure", "1, 'gym_doublePendulum': 7}[self._env_name] ypos_target = \\ {'gym_pendulum': 0.0, 'gym_doublePendulum': 2}[self._env_name]", "logger.error('Invalid target {}'.format(target)) return derivative_data self.reward_derivative = reward_derivative def render(self,", "v2 = self.model.data.qvel[1:3] vel_penalty = 1e-3 * v1**2 + 5e-3", "to the one # defined in GYM # ----------------------------------------------------------------------------- \"\"\"", "** 2 + (y - 2) ** 2 v1, v2", "_set_dynamics_api(self): def set_state(data_dict): qpos = np.zeros([self._len_qpos]) qvel = np.zeros([self._len_qvel]) qpos[:]", "reward_derivative(data_dict, target): num_data = len(data_dict['start_state']) if target == 'state': derivative_data", "xpos_reward + ypos_reward self.reward = reward def reward_derivative(data_dict, target): num_data", "as the gym? if 'reset_type' in misc_info and misc_info['reset_type'] ==", "ob = self._get_obs() notdone = np.isfinite(ob).all() and (np.abs(ob[1]) <= .2)", "api newob_from_api = \\ api_env.fdynamics({'start_state': ob, 'action': action}) ob_error =", "from mbbl.env import env_register from mbbl.env import env_util from mbbl.util.common", "ValueError(\"Invalid gym-{}\".format(self._current_version)) # make the environments self._env_info = env_register.get_env_info(self._env_name) self._env_name", "double_pendulum: (slide, hinge, hinge) qpos: 3 (0, 1, 2) qvel:", "ypos_target = 0.0 xpos_coeff = 0.0 def reward(data_dict): # xpos", "self._env.env.sim.data.qvel = qpos.reshape([-1]) self._env.env.model._compute_subtree() # pylint: disable=W0212 self._env.env.model.forward() self._old_ob =", "_, _ = test_env.step(action) # test the reward api reward_from_api", "will raise warnings -> set logger flag to ignore self._old_ob", "= env_register.get_env_info(self._env_name) self._env_name = self._env_name.split('-')[0] self._env = gym.make(_env_name[self._env_name]) def _set_groundtruth_api(self):", "APIs for the agent to call. For the new environments,", "2 (2, 3) double_pendulum: (slide, hinge, hinge) qpos: 3 (0,", "def set_state(data_dict): qpos = np.zeros([self._len_qpos]) qvel = np.zeros([self._len_qvel]) qpos[:] =", "done = bool(y <= 1) return ob, r, done, {}", "self._current_version) # return the reset as the gym? if 'reset_type'", "in self.PENDULUM \"\"\" xpos_ob_pos = \\ {'gym_pendulum': 0, 'gym_doublePendulum': 6}[self._env_name]", "\\ {'gym_pendulum': 0.0, 'gym_doublePendulum': 0.01}[self._env_name] \"\"\" xpos_ob_pos = 0 ypos_ob_pos", "# test_env_name = ['gym_doublePendulum'] test_env_name = ['gym_invertedPendulum'] for env_name in", "x ** 2 @ypos_penalty: (y - 2) ** 2 pendulum:", "# TODO: other gym versions here _env_name = { 'gym_invertedPendulum':", "1, set the zero-order reward function assert self._env_name in self.PENDULUM", "__name__ == '__main__': # test_env_name = ['gym_doublePendulum'] test_env_name = ['gym_invertedPendulum']", "_get_observation(self): if self._current_version in ['0.7.4', '0.9.4']: qpos = self._env.env.data.qpos qvel", "ypos_target = \\ {'gym_pendulum': 0.0, 'gym_doublePendulum': 2}[self._env_name] xpos_coeff = \\", "dynamics and rewards APIs for the agent to call. For", "mbbl.env import env_register from mbbl.env import env_util from mbbl.util.common import", "reward = self.reward( {'end_state': ob, 'start_state': self._old_ob, 'action': action} )", "reset the state if self._current_version in ['0.7.4', '0.9.4']: self._env.env.data.qpos =", "'action-action': derivative_data = np.zeros( [num_data, self._env_info['action_size'], self._env_info['action_size']], dtype=np.float ) else:", "reward part derivative_data[:, ypos_ob_pos] += - 2.0 * \\ (data_dict['start_state'][:,", "# get the end signal self._current_step += 1 info['current_step'] =", "= self._get_observation() if self._reset_return_obs_only: return self._old_ob.copy() else: return self._old_ob.copy(), 0.0,", "self._set_reward_api() self._set_dynamics_api() def _set_dynamics_api(self): def set_state(data_dict): qpos = np.zeros([self._len_qpos]) qvel", "-(xpos ** 2) * xpos_coeff # ypos penalty ypos =", "= \\ api_env.fdynamics({'start_state': ob, 'action': action}) ob_error = np.sum(np.abs(newob_from_api -", "the dynamics api newob_from_api = \\ api_env.fdynamics({'start_state': ob, 'action': action})", "== 'gym_doublePendulum': if self._current_version in ['0.7.4', '0.9.4']: site_xpos = self._env.env.data.site_xpos[:,", "PENDULUM = ['gym_invertedPendulum'] def __init__(self, env_name, rand_seed, misc_info): super(env, self).__init__(env_name,", "] # reset the state if self._current_version in ['0.7.4', '0.9.4']:", "\\ env_util.get_gym_q_info(self._env, self._current_version) # return the reset as the gym?", "some environments have different obs self.observation_space = \\ env_util.box(self._env_info['ob_size'], -1,", "elif target == 'action': derivative_data = np.zeros( [num_data, self._env_info['action_size']], dtype=np.float", "reward_error = np.sum(np.abs(reward_from_api - reward)) # test the dynamics api", "self.PENDULUM \"\"\" xpos_ob_pos = \\ {'gym_pendulum': 0, 'gym_doublePendulum': 6}[self._env_name] ypos_ob_pos", "xpos reward part derivative_data[:, xpos_ob_pos] += - 2.0 * xpos_coeff", "return the reset as the gym? if 'reset_type' in misc_info", "= np.zeros( [num_data, self._env_info['ob_size']], dtype=np.float ) # the xpos reward", "# make the environments self._env_info = env_register.get_env_info(self._env_name) self._env_name = self._env_name.split('-')[0]", "np.transpose(site_xpos) return np.concatenate([qpos, qvel, site_xpos]).ravel() else: \"\"\" assert self._env_name ==", "{ 'gym_invertedPendulum': 'InvertedPendulum-v2', } else: raise ValueError(\"Invalid gym-{}\".format(self._current_version)) # make", "derivative_data = np.zeros( [num_data, self._env_info['action_size']], dtype=np.float ) elif target ==", "{'end_state': ob, 'start_state': self._old_ob, 'action': action} ) # from mbbl.util.common.fpdb", "if target == 'state': derivative_data = np.zeros( [num_data, self._env_info['ob_size']], dtype=np.float", "+ (y - 2) ** 2 v1, v2 = self.model.data.qvel[1:3]", "dtype=np.float ) elif target == 'state-state': derivative_data = np.zeros( [num_data,", "2]] site_xpos = np.transpose(site_xpos) return np.concatenate([qpos, qvel, site_xpos]).ravel() else: \"\"\"", "= -(ypos - ypos_target) ** 2 return xpos_reward + ypos_reward", "@brief: # Tingwu: reset the reward function so that it's", "self.set_state({'start_state': self._old_ob.copy()}) self._old_ob = self._get_observation() if self._reset_return_obs_only: return self._old_ob.copy() else:", "dtype=np.float ) elif target == 'state-action': derivative_data = np.zeros( [num_data,", "'start_state': self._old_ob, 'action': action} ) # from mbbl.util.common.fpdb import fpdb;", "self._env.env.data.qpos = qpos.reshape([-1, 1]) self._env.env.data.qvel = qvel.reshape([-1, 1]) else: self._env.env.sim.data.qpos", ") else: assert False, logger.error('Invalid target {}'.format(target)) return derivative_data self.reward_derivative", "gym.make(_env_name[self._env_name]) def _set_groundtruth_api(self): \"\"\" @brief: In this function, we could", "using self.fynamics() self.set_state(data_dict) return self.step(data_dict['action'])[0] self.fdynamics = fdynamics def _set_reward_api(self):", "self._reset_return_obs_only = True self.observation_space, self.action_space = \\ self._env.observation_space, self._env.action_space #", "xpos_coeff = 0.0 def reward(data_dict): # xpos penalty xpos =", "dist_penalty = 0.01 * x ** 2 + (y -", "(np.abs(ob[1]) <= .2) done = not notdone self.do_simulation(action, self.frame_skip) ob", "'action-state': derivative_data = np.zeros( [num_data, self._env_info['action_size'], self._env_info['ob_size']], dtype=np.float ) elif", "target == 'action-action': derivative_data = np.zeros( [num_data, self._env_info['action_size'], self._env_info['action_size']], dtype=np.float", "self._set_dynamics_api() def _set_dynamics_api(self): def set_state(data_dict): qpos = np.zeros([self._len_qpos]) qvel =", "self._old_ob = np.array(ob) return ob, reward, done, info def reset(self,", "\"\"\" xpos_ob_pos = 0 ypos_ob_pos = 1 ypos_target = 0.0", "self._env_name == 'gym_invertedPendulum' return np.concatenate([qpos, qvel]).ravel() def _build_env(self): import gym", "as bew from mbbl.env import env_register from mbbl.env import env_util", "np from mbbl.config import init_path from mbbl.env import base_env_wrapper as", ") # the xpos reward part derivative_data[:, xpos_ob_pos] += -", "this function, we could provide the ground-truth dynamics and rewards", "(data_dict['start_state'][:, xpos_ob_pos]) # the ypos reward part derivative_data[:, ypos_ob_pos] +=", "env_util from mbbl.util.common import logger class env(bew.base_env): # acrobot has", "7) \"\"\" # step 1, set the zero-order reward function", "= qpos.reshape([-1, 1]) self._env.env.data.qvel = qvel.reshape([-1, 1]) else: self._env.env.sim.data.qpos =", "self.frame_skip) ob = self._get_obs() x, _, y = self.model.data.site_xpos[0] dist_penalty", "return ob, reward, done, info def reset(self, control_info={}): self._current_step =", "(data_dict['start_state'][:, ypos_ob_pos] - ypos_target) elif target == 'action': derivative_data =", "= self.reward( {'end_state': ob, 'start_state': self._old_ob, 'action': action} ) #", "test_env._env.action_space.shape) new_ob, reward, _, _ = test_env.step(action) # test the", "make the environments self._env_info = env_register.get_env_info(self._env_name) self._env_name = self._env_name.split('-')[0] self._env", "= set_state def fdynamics(data_dict): # make sure reset is called", "2 v1, v2 = self.model.data.qvel[1:3] vel_penalty = 1e-3 * v1**2", "# from mbbl.util.common.fpdb import fpdb; fpdb().set_trace() # get the end", "test the algorithm using ground-truth dynamics or reward \"\"\" self._set_reward_api()", "part derivative_data[:, ypos_ob_pos] += - 2.0 * \\ (data_dict['start_state'][:, ypos_ob_pos]", "*args, **kwargs): return if __name__ == '__main__': # test_env_name =", "the reward function so that it's more similar to the", "a hack, there is some precision issue in mujoco_py self._old_ob", "'gym_doublePendulum': 0.01}[self._env_name] \"\"\" xpos_ob_pos = 0 ypos_ob_pos = 1 ypos_target", "= self._env.env.sim.data.qvel \"\"\" if self._env_name == 'gym_doublePendulum': if self._current_version in", "- ypos_target) elif target == 'action': derivative_data = np.zeros( [num_data,", "self).__init__(env_name, rand_seed, misc_info) self._base_path = init_path.get_abs_base_dir() self._len_qpos, self._len_qvel = \\", "set_state(data_dict): qpos = np.zeros([self._len_qpos]) qvel = np.zeros([self._len_qvel]) qpos[:] = data_dict['start_state'][:self._len_qpos]", "self._current_version in ['0.7.4', '0.9.4']: self._env.env.data.qpos = qpos.reshape([-1, 1]) self._env.env.data.qvel =", "xpos_coeff # the ypos reward derivative_data[:, ypos_ob_pos, ypos_ob_pos] += \\", "[num_data, self._env_info['ob_size'], self._env_info['action_size']], dtype=np.float ) elif target == 'action-action': derivative_data", "\"\"\" # ----------------------------------------------------------------------------- # @brief: # Tingwu: reset the reward", "= \\ api_env.reward({'start_state': ob, 'action': action}) reward_error = np.sum(np.abs(reward_from_api -", "# return the reset as the gym? if 'reset_type' in", "2.0 * \\ (data_dict['start_state'][:, ypos_ob_pos] - ypos_target) elif target ==", "data_dict['start_state'][ypos_ob_pos] ypos_reward = -(ypos - ypos_target) ** 2 return xpos_reward", "# test the reward api reward_from_api = \\ api_env.reward({'start_state': ob,", "<reponame>hbutsuak95/iv_rl \"\"\" # ----------------------------------------------------------------------------- # @brief: # Tingwu: reset the", "NotImplementedError: # TODO: other gym versions here _env_name = {", "self._env_info['action_size']], dtype=np.float ) elif target == 'action-action': derivative_data = np.zeros(", "reward_derivative def render(self, *args, **kwargs): return if __name__ == '__main__':", "test the dynamics api newob_from_api = \\ api_env.fdynamics({'start_state': ob, 'action':", "the reset as the gym? if 'reset_type' in misc_info and", "np.zeros([self._len_qpos]) qvel = np.zeros([self._len_qvel]) qpos[:] = data_dict['start_state'][:self._len_qpos] qvel[:] = data_dict['start_state'][", "import logger class env(bew.base_env): # acrobot has applied sin/cos obs", "raise warnings -> set logger flag to ignore self._old_ob =", "GYM # ----------------------------------------------------------------------------- \"\"\" import numpy as np from mbbl.config", "self._env_info['ob_size']], dtype=np.float ) elif target == 'state-action': derivative_data = np.zeros(", "hinge, hinge) qpos: 3 (0, 1, 2) qvel: 3 (3,", "= self._get_obs() notdone = np.isfinite(ob).all() and (np.abs(ob[1]) <= .2) done", "0.01}[self._env_name] \"\"\" xpos_ob_pos = 0 ypos_ob_pos = 1 ypos_target =", "def _set_reward_api(self): \"\"\" def _step(self, a): reward = 1.0 self.do_simulation(a,", "ob, r, done, {} reward: @xpos_penalty: x ** 2 @ypos_penalty:", "-1, 1) else: self._reset_return_obs_only = False def step(self, action): _,", "else: qpos = self._env.env.sim.data.qpos qvel = self._env.env.sim.data.qvel \"\"\" if self._env_name", "np.zeros( [num_data, self._env_info['ob_size'], self._env_info['action_size']], dtype=np.float ) elif target == 'action-action':", "pendulum: (slide, hinge) qpos: 2 (0, 1) qvel: 2 (2,", "self._len_qvel = \\ env_util.get_gym_q_info(self._env, self._current_version) # return the reset as", "and (np.abs(ob[1]) <= .2) done = not notdone self.do_simulation(action, self.frame_skip)", "xpos penalty xpos = data_dict['start_state'][xpos_ob_pos] xpos_reward = -(xpos ** 2)", "{'gym_pendulum': 0, 'gym_doublePendulum': 6}[self._env_name] ypos_ob_pos = \\ {'gym_pendulum': 1, 'gym_doublePendulum':", "= 0.0 xpos_coeff = 0.0 def reward(data_dict): # xpos penalty", "ob = self._get_observation() # get the reward reward = self.reward(", "rewards APIs for the agent to call. For the new", "= 1e-3 * v1**2 + 5e-3 * v2**2 alive_bonus =", "target == 'action': derivative_data = np.zeros( [num_data, self._env_info['action_size']], dtype=np.float )", "<= 1) return ob, r, done, {} reward: @xpos_penalty: x", "action = np.random.uniform(-1, 1, test_env._env.action_space.shape) new_ob, reward, _, _ =", "2) qvel: 3 (3, 4, 5) site_pose: 2 (6, 7)", "dtype=np.float ) elif target == 'action-action': derivative_data = np.zeros( [num_data,", "else: assert False, logger.error('Invalid target {}'.format(target)) return derivative_data self.reward_derivative =", "= 0.0 def reward(data_dict): # xpos penalty xpos = data_dict['start_state'][xpos_ob_pos]", "is called before using self.fynamics() self.set_state(data_dict) return self.step(data_dict['action'])[0] self.fdynamics =", "= new_ob print('reward error: {}, dynamics error: {}'.format( reward_error, ob_error)", "self._env_info['max_length']: done = True else: done = False # will", "we could provide the ground-truth dynamics and rewards APIs for", "= False def step(self, action): _, _, _, info =", "= self._current_step if self._current_step > self._env_info['max_length']: done = True else:", "versions here _env_name = { 'gym_invertedPendulum': 'InvertedPendulum-v2', } else: raise", "0 self._env.reset() # the following is a hack, there is", "(0, 1, 2) qvel: 3 (3, 4, 5) site_pose: 2", "notdone = np.isfinite(ob).all() and (np.abs(ob[1]) <= .2) done = not", "= reward_derivative def render(self, *args, **kwargs): return if __name__ ==", "if self._env_name == 'gym_doublePendulum': if self._current_version in ['0.7.4', '0.9.4']: site_xpos", "TODO: other gym versions here _env_name = { 'gym_invertedPendulum': 'InvertedPendulum-v2',", "= np.sum(np.abs(newob_from_api - new_ob)) ob = new_ob print('reward error: {},", "qpos.reshape([-1, 1]) self._env.env.data.qvel = qvel.reshape([-1, 1]) else: self._env.env.sim.data.qpos = qpos.reshape([-1])", "= data_dict['start_state'][:self._len_qpos] qvel[:] = data_dict['start_state'][ self._len_qpos: self._len_qpos + self._len_qvel ]", "2) * xpos_coeff # ypos penalty ypos = data_dict['start_state'][ypos_ob_pos] ypos_reward", "render(self, *args, **kwargs): return if __name__ == '__main__': # test_env_name", "there is some precision issue in mujoco_py self._old_ob = self._get_observation()", "y = self.model.data.site_xpos[0] dist_penalty = 0.01 * x ** 2", "2) ** 2 v1, v2 = self.model.data.qvel[1:3] vel_penalty = 1e-3", "to call. For the new environments, if we don't set", "xpos_ob_pos]) # the ypos reward part derivative_data[:, ypos_ob_pos] += -", "ob, 'start_state': self._old_ob, 'action': action} ) # from mbbl.util.common.fpdb import", "action}) ob_error = np.sum(np.abs(newob_from_api - new_ob)) ob = new_ob print('reward", "state if self._current_version in ['0.7.4', '0.9.4']: self._env.env.data.qpos = qpos.reshape([-1, 1])", ") elif target == 'state-state': derivative_data = np.zeros( [num_data, self._env_info['ob_size'],", "num_data = len(data_dict['start_state']) if target == 'state': derivative_data = np.zeros(", "'state-action': derivative_data = np.zeros( [num_data, self._env_info['ob_size'], self._env_info['action_size']], dtype=np.float ) elif", "api_env.reward({'start_state': ob, 'action': action}) reward_error = np.sum(np.abs(reward_from_api - reward)) #", "= self._env.env.data.qvel else: qpos = self._env.env.sim.data.qpos qvel = self._env.env.sim.data.qvel \"\"\"", "\"\"\" self._set_reward_api() self._set_dynamics_api() def _set_dynamics_api(self): def set_state(data_dict): qpos = np.zeros([self._len_qpos])", "if __name__ == '__main__': # test_env_name = ['gym_doublePendulum'] test_env_name =", "= env(env_name, 1234, {}) api_env.reset() ob, reward, _, _ =", "elif self._current_version == NotImplementedError: # TODO: other gym versions here", "xpos_coeff # ypos penalty ypos = data_dict['start_state'][ypos_ob_pos] ypos_reward = -(ypos", "test_env_name = ['gym_invertedPendulum'] for env_name in test_env_name: test_env = env(env_name,", "# defined in GYM # ----------------------------------------------------------------------------- \"\"\" import numpy as", "dynamics api newob_from_api = \\ api_env.fdynamics({'start_state': ob, 'action': action}) ob_error", "'__main__': # test_env_name = ['gym_doublePendulum'] test_env_name = ['gym_invertedPendulum'] for env_name", "environments self._env_info = env_register.get_env_info(self._env_name) self._env_name = self._env_name.split('-')[0] self._env = gym.make(_env_name[self._env_name])", "1]) else: self._env.env.sim.data.qpos = qpos.reshape([-1]) self._env.env.sim.data.qvel = qpos.reshape([-1]) self._env.env.model._compute_subtree() #", "* x ** 2 + (y - 2) ** 2", "Tingwu: reset the reward function so that it's more similar", "in ['0.7.4', '0.9.4']: _env_name = { 'gym_invertedPendulum': 'InvertedPendulum-v1', } elif", "self._env = gym.make(_env_name[self._env_name]) def _set_groundtruth_api(self): \"\"\" @brief: In this function,", "self.step(data_dict['action'])[0] self.fdynamics = fdynamics def _set_reward_api(self): \"\"\" def _step(self, a):", "3) double_pendulum: (slide, hinge, hinge) qpos: 3 (0, 1, 2)", "new_ob)) ob = new_ob print('reward error: {}, dynamics error: {}'.format(", "in test_env_name: test_env = env(env_name, 1234, {}) api_env = env(env_name,", "(3, 4, 5) site_pose: 2 (6, 7) \"\"\" # step", "xpos_ob_pos] += \\ - 2.0 * xpos_coeff # the ypos", "= self._env.env.sim.data.site_xpos[:, [0, 2]] site_xpos = np.transpose(site_xpos) return np.concatenate([qpos, qvel,", "False def step(self, action): _, _, _, info = self._env.step(action)", "before using self.fynamics() self.set_state(data_dict) return self.step(data_dict['action'])[0] self.fdynamics = fdynamics def", "self.set_state(data_dict) return self.step(data_dict['action'])[0] self.fdynamics = fdynamics def _set_reward_api(self): \"\"\" def", "xpos_coeff = \\ {'gym_pendulum': 0.0, 'gym_doublePendulum': 0.01}[self._env_name] \"\"\" xpos_ob_pos =", "data_dict['start_state'][:self._len_qpos] qvel[:] = data_dict['start_state'][ self._len_qpos: self._len_qpos + self._len_qvel ] #", "= data_dict['start_state'][ypos_ob_pos] ypos_reward = -(ypos - ypos_target) ** 2 return", "ypos_target) elif target == 'action': derivative_data = np.zeros( [num_data, self._env_info['action_size']],", "end signal self._current_step += 1 info['current_step'] = self._current_step if self._current_step", "site_xpos = self._env.env.data.site_xpos[:, [0, 2]] else: site_xpos = self._env.env.sim.data.site_xpos[:, [0,", "gym.__version__ if self._current_version in ['0.7.4', '0.9.4']: _env_name = { 'gym_invertedPendulum':", "self._len_qvel ] # reset the state if self._current_version in ['0.7.4',", "self._env.env.data.site_xpos[:, [0, 2]] else: site_xpos = self._env.env.sim.data.site_xpos[:, [0, 2]] site_xpos", "mbbl.util.common.fpdb import fpdb; fpdb().set_trace() # get the end signal self._current_step", "mujoco_py self._old_ob = self._get_observation() self._env.reset() self.set_state({'start_state': self._old_ob.copy()}) self._old_ob = self._get_observation()", "= qpos.reshape([-1]) self._env.env.sim.data.qvel = qpos.reshape([-1]) self._env.env.model._compute_subtree() # pylint: disable=W0212 self._env.env.model.forward()", "set logger flag to ignore self._old_ob = np.array(ob) return ob,", "2.0 * xpos_coeff # the ypos reward derivative_data[:, ypos_ob_pos, ypos_ob_pos]", "= test_env.step(action) # test the reward api reward_from_api = \\", "the reward reward = self.reward( {'end_state': ob, 'start_state': self._old_ob, 'action':", "v1, v2 = self.model.data.qvel[1:3] vel_penalty = 1e-3 * v1**2 +", "# it's possible some environments have different obs self.observation_space =", "if self._current_version in ['0.7.4', '0.9.4']: _env_name = { 'gym_invertedPendulum': 'InvertedPendulum-v1',", "target == 'state-state': derivative_data = np.zeros( [num_data, self._env_info['ob_size'], self._env_info['ob_size']], dtype=np.float", "1.0 self.do_simulation(a, self.frame_skip) ob = self._get_obs() notdone = np.isfinite(ob).all() and", "zero-order reward function assert self._env_name in self.PENDULUM \"\"\" xpos_ob_pos =", "'action': derivative_data = np.zeros( [num_data, self._env_info['action_size']], dtype=np.float ) elif target", "np.sum(np.abs(reward_from_api - reward)) # test the dynamics api newob_from_api =", "self._old_ob.copy() else: return self._old_ob.copy(), 0.0, False, {} def _get_observation(self): if", "\"\"\" xpos_ob_pos = \\ {'gym_pendulum': 0, 'gym_doublePendulum': 6}[self._env_name] ypos_ob_pos =", "\\ {'gym_pendulum': 0.0, 'gym_doublePendulum': 2}[self._env_name] xpos_coeff = \\ {'gym_pendulum': 0.0,", "v1**2 + 5e-3 * v2**2 alive_bonus = 10 r =", "ob, 'action': action}) reward_error = np.sum(np.abs(reward_from_api - reward)) # test", "_set_groundtruth_api(self): \"\"\" @brief: In this function, we could provide the", "step(self, action): _, _, _, info = self._env.step(action) ob =", "qvel: 2 (2, 3) double_pendulum: (slide, hinge, hinge) qpos: 3", "if self._current_version in ['0.7.4', '0.9.4']: qpos = self._env.env.data.qpos qvel =", "# the ypos reward part derivative_data[:, ypos_ob_pos] += - 2.0", "bew from mbbl.env import env_register from mbbl.env import env_util from", "'gym_doublePendulum': if self._current_version in ['0.7.4', '0.9.4']: site_xpos = self._env.env.data.site_xpos[:, [0,", "else: \"\"\" assert self._env_name == 'gym_invertedPendulum' return np.concatenate([qpos, qvel]).ravel() def", "misc_info): super(env, self).__init__(env_name, rand_seed, misc_info) self._base_path = init_path.get_abs_base_dir() self._len_qpos, self._len_qvel", "reset(self, control_info={}): self._current_step = 0 self._env.reset() # the following is", "site_xpos = self._env.env.sim.data.site_xpos[:, [0, 2]] site_xpos = np.transpose(site_xpos) return np.concatenate([qpos,", "= 0 self._env.reset() # the following is a hack, there", "self._current_version = gym.__version__ if self._current_version in ['0.7.4', '0.9.4']: _env_name =", "cannot test the algorithm using ground-truth dynamics or reward \"\"\"", "self._get_observation() # get the reward reward = self.reward( {'end_state': ob,", "'gym_invertedPendulum': 'InvertedPendulum-v1', } elif self._current_version == NotImplementedError: # TODO: other", "the environments self._env_info = env_register.get_env_info(self._env_name) self._env_name = self._env_name.split('-')[0] self._env =", "= qpos.reshape([-1]) self._env.env.model._compute_subtree() # pylint: disable=W0212 self._env.env.model.forward() self._old_ob = self._get_observation()", "= 0.01 * x ** 2 + (y - 2)", "self.model.data.qvel[1:3] vel_penalty = 1e-3 * v1**2 + 5e-3 * v2**2", "self._current_version == NotImplementedError: # TODO: other gym versions here _env_name", "<= .2) done = not notdone self.do_simulation(action, self.frame_skip) ob =", "not notdone self.do_simulation(action, self.frame_skip) ob = self._get_obs() x, _, y", "x, _, y = self.model.data.site_xpos[0] dist_penalty = 0.01 * x", "(slide, hinge, hinge) qpos: 3 (0, 1, 2) qvel: 3", "False, {} def _get_observation(self): if self._current_version in ['0.7.4', '0.9.4']: qpos", "site_xpos]).ravel() else: \"\"\" assert self._env_name == 'gym_invertedPendulum' return np.concatenate([qpos, qvel]).ravel()", "# Tingwu: reset the reward function so that it's more", "self._old_ob = self._get_observation() self._env.reset() self.set_state({'start_state': self._old_ob.copy()}) self._old_ob = self._get_observation() if", "self._get_obs() x, _, y = self.model.data.site_xpos[0] dist_penalty = 0.01 *", "2 pendulum: (slide, hinge) qpos: 2 (0, 1) qvel: 2", "ob, reward, _, _ = test_env.reset() for _ in range(100):", "* xpos_coeff # the ypos reward derivative_data[:, ypos_ob_pos, ypos_ob_pos] +=", "set their ground-truth apis, then we cannot test the algorithm", "reward function so that it's more similar to the one", "acrobot has applied sin/cos obs PENDULUM = ['gym_invertedPendulum'] def __init__(self,", "site_pose: 2 (6, 7) \"\"\" # step 1, set the", "'state': derivative_data = np.zeros( [num_data, self._env_info['ob_size']], dtype=np.float ) # the", "(y - 2) ** 2 pendulum: (slide, hinge) qpos: 2", "we cannot test the algorithm using ground-truth dynamics or reward", "done, {} reward: @xpos_penalty: x ** 2 @ypos_penalty: (y -", "self._env.env.sim.data.qvel \"\"\" if self._env_name == 'gym_doublePendulum': if self._current_version in ['0.7.4',", "1234, {}) api_env.reset() ob, reward, _, _ = test_env.reset() for", "ypos reward derivative_data[:, ypos_ob_pos, ypos_ob_pos] += \\ - 2.0 elif", "= np.sum(np.abs(reward_from_api - reward)) # test the dynamics api newob_from_api", "def _build_env(self): import gym self._current_version = gym.__version__ if self._current_version in", "# step 1, set the zero-order reward function assert self._env_name", "= -(xpos ** 2) * xpos_coeff # ypos penalty ypos", "could provide the ground-truth dynamics and rewards APIs for the", "import gym self._current_version = gym.__version__ if self._current_version in ['0.7.4', '0.9.4']:", "ypos_ob_pos] - ypos_target) elif target == 'action': derivative_data = np.zeros(", "environments, if we don't set their ground-truth apis, then we", "# make sure reset is called before using self.fynamics() self.set_state(data_dict)", "* xpos_coeff # ypos penalty ypos = data_dict['start_state'][ypos_ob_pos] ypos_reward =", "def _step(self, a): reward = 1.0 self.do_simulation(a, self.frame_skip) ob =", "reset is called before using self.fynamics() self.set_state(data_dict) return self.step(data_dict['action'])[0] self.fdynamics", "reward derivative_data[:, xpos_ob_pos, xpos_ob_pos] += \\ - 2.0 * xpos_coeff", "'0.9.4']: self._env.env.data.qpos = qpos.reshape([-1, 1]) self._env.env.data.qvel = qvel.reshape([-1, 1]) else:", "\\ - 2.0 * xpos_coeff # the ypos reward derivative_data[:,", "the ground-truth dynamics and rewards APIs for the agent to", "apis, then we cannot test the algorithm using ground-truth dynamics", "+ ypos_reward self.reward = reward def reward_derivative(data_dict, target): num_data =", "1 ypos_target = 0.0 xpos_coeff = 0.0 def reward(data_dict): #", "qvel = self._env.env.data.qvel else: qpos = self._env.env.sim.data.qpos qvel = self._env.env.sim.data.qvel", "* v2**2 alive_bonus = 10 r = (alive_bonus - dist_penalty", "has applied sin/cos obs PENDULUM = ['gym_invertedPendulum'] def __init__(self, env_name,", "1, 2) qvel: 3 (3, 4, 5) site_pose: 2 (6,", ".2) done = not notdone self.do_simulation(action, self.frame_skip) ob = self._get_obs()", "dist_penalty - vel_penalty)[0] done = bool(y <= 1) return ob,", "def reward_derivative(data_dict, target): num_data = len(data_dict['start_state']) if target == 'state':", "== 'action': derivative_data = np.zeros( [num_data, self._env_info['action_size']], dtype=np.float ) elif", "the agent to call. For the new environments, if we", "# xpos penalty xpos = data_dict['start_state'][xpos_ob_pos] xpos_reward = -(xpos **", "site_xpos = np.transpose(site_xpos) return np.concatenate([qpos, qvel, site_xpos]).ravel() else: \"\"\" assert", "1) return ob, r, done, {} reward: @xpos_penalty: x **", "np.sum(np.abs(newob_from_api - new_ob)) ob = new_ob print('reward error: {}, dynamics", "'gym_invertedPendulum': 'InvertedPendulum-v2', } else: raise ValueError(\"Invalid gym-{}\".format(self._current_version)) # make the", "rand_seed, misc_info) self._base_path = init_path.get_abs_base_dir() self._len_qpos, self._len_qvel = \\ env_util.get_gym_q_info(self._env,", "env_name, rand_seed, misc_info): super(env, self).__init__(env_name, rand_seed, misc_info) self._base_path = init_path.get_abs_base_dir()", "# the xpos reward part derivative_data[:, xpos_ob_pos] += - 2.0", "done = not notdone self.do_simulation(action, self.frame_skip) ob = self._get_obs() x,", "np.zeros( [num_data, self._env_info['ob_size']], dtype=np.float ) # the xpos reward part", "self._current_step if self._current_step > self._env_info['max_length']: done = True else: done", "= len(data_dict['start_state']) if target == 'state': derivative_data = np.zeros( [num_data,", "test_env.step(action) # test the reward api reward_from_api = \\ api_env.reward({'start_state':", "target == 'action-state': derivative_data = np.zeros( [num_data, self._env_info['action_size'], self._env_info['ob_size']], dtype=np.float", "np.zeros( [num_data, self._env_info['action_size'], self._env_info['action_size']], dtype=np.float ) else: assert False, logger.error('Invalid", "else: done = False # will raise warnings -> set", "get the end signal self._current_step += 1 info['current_step'] = self._current_step", "# ----------------------------------------------------------------------------- # @brief: # Tingwu: reset the reward function", "the following is a hack, there is some precision issue", "_ = test_env.step(action) # test the reward api reward_from_api =", "'gym': self._reset_return_obs_only = True self.observation_space, self.action_space = \\ self._env.observation_space, self._env.action_space", "make sure reset is called before using self.fynamics() self.set_state(data_dict) return", "= self._env.env.data.site_xpos[:, [0, 2]] else: site_xpos = self._env.env.sim.data.site_xpos[:, [0, 2]]", "called before using self.fynamics() self.set_state(data_dict) return self.step(data_dict['action'])[0] self.fdynamics = fdynamics", "self._env_info['action_size'], self._env_info['action_size']], dtype=np.float ) else: assert False, logger.error('Invalid target {}'.format(target))", "reward reward = self.reward( {'end_state': ob, 'start_state': self._old_ob, 'action': action}", "'gym_invertedPendulum' return np.concatenate([qpos, qvel]).ravel() def _build_env(self): import gym self._current_version =", "= np.transpose(site_xpos) return np.concatenate([qpos, qvel, site_xpos]).ravel() else: \"\"\" assert self._env_name", "self.action_space = \\ self._env.observation_space, self._env.action_space # it's possible some environments", "**kwargs): return if __name__ == '__main__': # test_env_name = ['gym_doublePendulum']", "dtype=np.float ) # the xpos reward derivative_data[:, xpos_ob_pos, xpos_ob_pos] +=", "_, _, _, info = self._env.step(action) ob = self._get_observation() #", "done = True else: done = False # will raise", "self._get_obs() notdone = np.isfinite(ob).all() and (np.abs(ob[1]) <= .2) done =", "[num_data, self._env_info['ob_size'], self._env_info['ob_size']], dtype=np.float ) # the xpos reward derivative_data[:,", "super(env, self).__init__(env_name, rand_seed, misc_info) self._base_path = init_path.get_abs_base_dir() self._len_qpos, self._len_qvel =", "# ----------------------------------------------------------------------------- \"\"\" import numpy as np from mbbl.config import", "qpos.reshape([-1]) self._env.env.model._compute_subtree() # pylint: disable=W0212 self._env.env.model.forward() self._old_ob = self._get_observation() self.set_state", "self._env.env.data.qpos qvel = self._env.env.data.qvel else: qpos = self._env.env.sim.data.qpos qvel =", "the zero-order reward function assert self._env_name in self.PENDULUM \"\"\" xpos_ob_pos", "+= \\ - 2.0 elif target == 'action-state': derivative_data =", "'InvertedPendulum-v2', } else: raise ValueError(\"Invalid gym-{}\".format(self._current_version)) # make the environments", "= reward def reward_derivative(data_dict, target): num_data = len(data_dict['start_state']) if target", "0.0 xpos_coeff = 0.0 def reward(data_dict): # xpos penalty xpos", "== 'state-state': derivative_data = np.zeros( [num_data, self._env_info['ob_size'], self._env_info['ob_size']], dtype=np.float )", "pylint: disable=W0212 self._env.env.model.forward() self._old_ob = self._get_observation() self.set_state = set_state def", "to ignore self._old_ob = np.array(ob) return ob, reward, done, info", "precision issue in mujoco_py self._old_ob = self._get_observation() self._env.reset() self.set_state({'start_state': self._old_ob.copy()})", "return self.step(data_dict['action'])[0] self.fdynamics = fdynamics def _set_reward_api(self): \"\"\" def _step(self,", "else: raise ValueError(\"Invalid gym-{}\".format(self._current_version)) # make the environments self._env_info =", "\"\"\" @brief: In this function, we could provide the ground-truth", "env_util.box(self._env_info['ob_size'], -1, 1) else: self._reset_return_obs_only = False def step(self, action):", "if we don't set their ground-truth apis, then we cannot", "self._len_qpos: self._len_qpos + self._len_qvel ] # reset the state if", "ground-truth dynamics and rewards APIs for the agent to call.", "+ self._len_qvel ] # reset the state if self._current_version in", "'reset_type' in misc_info and misc_info['reset_type'] == 'gym': self._reset_return_obs_only = True", "we don't set their ground-truth apis, then we cannot test", "ground-truth apis, then we cannot test the algorithm using ground-truth", "derivative_data = np.zeros( [num_data, self._env_info['ob_size'], self._env_info['action_size']], dtype=np.float ) elif target", "(0, 1) qvel: 2 (2, 3) double_pendulum: (slide, hinge, hinge)", "== NotImplementedError: # TODO: other gym versions here _env_name =", "vel_penalty)[0] done = bool(y <= 1) return ob, r, done,", "+= - 2.0 * \\ (data_dict['start_state'][:, ypos_ob_pos] - ypos_target) elif", "possible some environments have different obs self.observation_space = \\ env_util.box(self._env_info['ob_size'],", "return np.concatenate([qpos, qvel]).ravel() def _build_env(self): import gym self._current_version = gym.__version__", "r, done, {} reward: @xpos_penalty: x ** 2 @ypos_penalty: (y", "def reset(self, control_info={}): self._current_step = 0 self._env.reset() # the following", "return derivative_data self.reward_derivative = reward_derivative def render(self, *args, **kwargs): return", "self._current_step > self._env_info['max_length']: done = True else: done = False", "self.reward( {'end_state': ob, 'start_state': self._old_ob, 'action': action} ) # from", "if self._reset_return_obs_only: return self._old_ob.copy() else: return self._old_ob.copy(), 0.0, False, {}", "provide the ground-truth dynamics and rewards APIs for the agent", "= np.zeros( [num_data, self._env_info['action_size'], self._env_info['action_size']], dtype=np.float ) else: assert False,", "10 r = (alive_bonus - dist_penalty - vel_penalty)[0] done =", "'gym_doublePendulum': 2}[self._env_name] xpos_coeff = \\ {'gym_pendulum': 0.0, 'gym_doublePendulum': 0.01}[self._env_name] \"\"\"", "fpdb; fpdb().set_trace() # get the end signal self._current_step += 1", "2}[self._env_name] xpos_coeff = \\ {'gym_pendulum': 0.0, 'gym_doublePendulum': 0.01}[self._env_name] \"\"\" xpos_ob_pos", "xpos_ob_pos = \\ {'gym_pendulum': 0, 'gym_doublePendulum': 6}[self._env_name] ypos_ob_pos = \\", "def _set_dynamics_api(self): def set_state(data_dict): qpos = np.zeros([self._len_qpos]) qvel = np.zeros([self._len_qvel])", "set_state def fdynamics(data_dict): # make sure reset is called before", "derivative_data self.reward_derivative = reward_derivative def render(self, *args, **kwargs): return if", "derivative_data = np.zeros( [num_data, self._env_info['action_size'], self._env_info['action_size']], dtype=np.float ) else: assert", "= self.model.data.qvel[1:3] vel_penalty = 1e-3 * v1**2 + 5e-3 *", "'0.9.4']: qpos = self._env.env.data.qpos qvel = self._env.env.data.qvel else: qpos =", "from mbbl.util.common.fpdb import fpdb; fpdb().set_trace() # get the end signal", "self._old_ob.copy()}) self._old_ob = self._get_observation() if self._reset_return_obs_only: return self._old_ob.copy() else: return", "notdone self.do_simulation(action, self.frame_skip) ob = self._get_obs() x, _, y =", "= self._get_observation() # get the reward reward = self.reward( {'end_state':", "self.reward_derivative = reward_derivative def render(self, *args, **kwargs): return if __name__", "ob_error = np.sum(np.abs(newob_from_api - new_ob)) ob = new_ob print('reward error:", "self._env.reset() # the following is a hack, there is some", "{ 'gym_invertedPendulum': 'InvertedPendulum-v1', } elif self._current_version == NotImplementedError: # TODO:", "self.set_state = set_state def fdynamics(data_dict): # make sure reset is", "self._env.env.model._compute_subtree() # pylint: disable=W0212 self._env.env.model.forward() self._old_ob = self._get_observation() self.set_state =", "{'gym_pendulum': 0.0, 'gym_doublePendulum': 0.01}[self._env_name] \"\"\" xpos_ob_pos = 0 ypos_ob_pos =", "logger class env(bew.base_env): # acrobot has applied sin/cos obs PENDULUM", "target {}'.format(target)) return derivative_data self.reward_derivative = reward_derivative def render(self, *args,", "derivative_data[:, xpos_ob_pos] += - 2.0 * xpos_coeff * \\ (data_dict['start_state'][:,", "\"\"\" if self._env_name == 'gym_doublePendulum': if self._current_version in ['0.7.4', '0.9.4']:", "= test_env.reset() for _ in range(100): action = np.random.uniform(-1, 1,", "* \\ (data_dict['start_state'][:, ypos_ob_pos] - ypos_target) elif target == 'action':", "= self._env.env.sim.data.qpos qvel = self._env.env.sim.data.qvel \"\"\" if self._env_name == 'gym_doublePendulum':", "base_env_wrapper as bew from mbbl.env import env_register from mbbl.env import", "@brief: In this function, we could provide the ground-truth dynamics", "self._old_ob = self._get_observation() self.set_state = set_state def fdynamics(data_dict): # make", "@xpos_penalty: x ** 2 @ypos_penalty: (y - 2) ** 2", "reward(data_dict): # xpos penalty xpos = data_dict['start_state'][xpos_ob_pos] xpos_reward = -(xpos", "6}[self._env_name] ypos_ob_pos = \\ {'gym_pendulum': 1, 'gym_doublePendulum': 7}[self._env_name] ypos_target =", "** 2) * xpos_coeff # ypos penalty ypos = data_dict['start_state'][ypos_ob_pos]", "np.random.uniform(-1, 1, test_env._env.action_space.shape) new_ob, reward, _, _ = test_env.step(action) #", "== 'gym_invertedPendulum' return np.concatenate([qpos, qvel]).ravel() def _build_env(self): import gym self._current_version", "dynamics or reward \"\"\" self._set_reward_api() self._set_dynamics_api() def _set_dynamics_api(self): def set_state(data_dict):", "\\ (data_dict['start_state'][:, xpos_ob_pos]) # the ypos reward part derivative_data[:, ypos_ob_pos]", "- 2.0 * xpos_coeff # the ypos reward derivative_data[:, ypos_ob_pos,", "function so that it's more similar to the one #", "self._env_name in self.PENDULUM \"\"\" xpos_ob_pos = \\ {'gym_pendulum': 0, 'gym_doublePendulum':", "ypos_ob_pos] += \\ - 2.0 elif target == 'action-state': derivative_data", "it's possible some environments have different obs self.observation_space = \\", "= not notdone self.do_simulation(action, self.frame_skip) ob = self._get_obs() x, _,", "derivative_data = np.zeros( [num_data, self._env_info['ob_size']], dtype=np.float ) # the xpos", "= \\ {'gym_pendulum': 0, 'gym_doublePendulum': 6}[self._env_name] ypos_ob_pos = \\ {'gym_pendulum':", ") elif target == 'state-action': derivative_data = np.zeros( [num_data, self._env_info['ob_size'],", "test_env_name = ['gym_doublePendulum'] test_env_name = ['gym_invertedPendulum'] for env_name in test_env_name:", "= \\ env_util.get_gym_q_info(self._env, self._current_version) # return the reset as the", "step 1, set the zero-order reward function assert self._env_name in", "logger flag to ignore self._old_ob = np.array(ob) return ob, reward,", "= ['gym_invertedPendulum'] def __init__(self, env_name, rand_seed, misc_info): super(env, self).__init__(env_name, rand_seed,", "in GYM # ----------------------------------------------------------------------------- \"\"\" import numpy as np from", "np.isfinite(ob).all() and (np.abs(ob[1]) <= .2) done = not notdone self.do_simulation(action,", "using ground-truth dynamics or reward \"\"\" self._set_reward_api() self._set_dynamics_api() def _set_dynamics_api(self):", "(6, 7) \"\"\" # step 1, set the zero-order reward", "3 (3, 4, 5) site_pose: 2 (6, 7) \"\"\" #", "['0.7.4', '0.9.4']: site_xpos = self._env.env.data.site_xpos[:, [0, 2]] else: site_xpos =", "from mbbl.env import base_env_wrapper as bew from mbbl.env import env_register", "0.01 * x ** 2 + (y - 2) **", "qpos: 2 (0, 1) qvel: 2 (2, 3) double_pendulum: (slide,", "self._old_ob, 'action': action} ) # from mbbl.util.common.fpdb import fpdb; fpdb().set_trace()", "api_env.reset() ob, reward, _, _ = test_env.reset() for _ in", "self._current_version in ['0.7.4', '0.9.4']: site_xpos = self._env.env.data.site_xpos[:, [0, 2]] else:", "== '__main__': # test_env_name = ['gym_doublePendulum'] test_env_name = ['gym_invertedPendulum'] for", "ypos_ob_pos, ypos_ob_pos] += \\ - 2.0 elif target == 'action-state':", "class env(bew.base_env): # acrobot has applied sin/cos obs PENDULUM =", "action): _, _, _, info = self._env.step(action) ob = self._get_observation()", "api_env = env(env_name, 1234, {}) api_env.reset() ob, reward, _, _", "'InvertedPendulum-v1', } elif self._current_version == NotImplementedError: # TODO: other gym", "self._env.env.data.qvel else: qpos = self._env.env.sim.data.qpos qvel = self._env.env.sim.data.qvel \"\"\" if", "environments have different obs self.observation_space = \\ env_util.box(self._env_info['ob_size'], -1, 1)", "* \\ (data_dict['start_state'][:, xpos_ob_pos]) # the ypos reward part derivative_data[:,", "it's more similar to the one # defined in GYM", "= qvel.reshape([-1, 1]) else: self._env.env.sim.data.qpos = qpos.reshape([-1]) self._env.env.sim.data.qvel = qpos.reshape([-1])", "2 return xpos_reward + ypos_reward self.reward = reward def reward_derivative(data_dict,", "[num_data, self._env_info['action_size'], self._env_info['ob_size']], dtype=np.float ) elif target == 'state-action': derivative_data", "dtype=np.float ) else: assert False, logger.error('Invalid target {}'.format(target)) return derivative_data", "new_ob print('reward error: {}, dynamics error: {}'.format( reward_error, ob_error) )", "= np.zeros([self._len_qvel]) qpos[:] = data_dict['start_state'][:self._len_qpos] qvel[:] = data_dict['start_state'][ self._len_qpos: self._len_qpos", "__init__(self, env_name, rand_seed, misc_info): super(env, self).__init__(env_name, rand_seed, misc_info) self._base_path =", "rand_seed, misc_info): super(env, self).__init__(env_name, rand_seed, misc_info) self._base_path = init_path.get_abs_base_dir() self._len_qpos,", "[0, 2]] site_xpos = np.transpose(site_xpos) return np.concatenate([qpos, qvel, site_xpos]).ravel() else:", "ypos_ob_pos] += - 2.0 * \\ (data_dict['start_state'][:, ypos_ob_pos] - ypos_target)", "have different obs self.observation_space = \\ env_util.box(self._env_info['ob_size'], -1, 1) else:", "obs self.observation_space = \\ env_util.box(self._env_info['ob_size'], -1, 1) else: self._reset_return_obs_only =", "here _env_name = { 'gym_invertedPendulum': 'InvertedPendulum-v2', } else: raise ValueError(\"Invalid", "qpos.reshape([-1]) self._env.env.sim.data.qvel = qpos.reshape([-1]) self._env.env.model._compute_subtree() # pylint: disable=W0212 self._env.env.model.forward() self._old_ob", "np.concatenate([qpos, qvel]).ravel() def _build_env(self): import gym self._current_version = gym.__version__ if", "'state-state': derivative_data = np.zeros( [num_data, self._env_info['ob_size'], self._env_info['ob_size']], dtype=np.float ) #", "_, y = self.model.data.site_xpos[0] dist_penalty = 0.01 * x **", "* xpos_coeff * \\ (data_dict['start_state'][:, xpos_ob_pos]) # the ypos reward", "return self._old_ob.copy() else: return self._old_ob.copy(), 0.0, False, {} def _get_observation(self):", "qpos = np.zeros([self._len_qpos]) qvel = np.zeros([self._len_qvel]) qpos[:] = data_dict['start_state'][:self._len_qpos] qvel[:]", "reward \"\"\" self._set_reward_api() self._set_dynamics_api() def _set_dynamics_api(self): def set_state(data_dict): qpos =", "test_env_name: test_env = env(env_name, 1234, {}) api_env = env(env_name, 1234,", "0.0, 'gym_doublePendulum': 2}[self._env_name] xpos_coeff = \\ {'gym_pendulum': 0.0, 'gym_doublePendulum': 0.01}[self._env_name]", "qvel, site_xpos]).ravel() else: \"\"\" assert self._env_name == 'gym_invertedPendulum' return np.concatenate([qpos,", "the gym? if 'reset_type' in misc_info and misc_info['reset_type'] == 'gym':", "a): reward = 1.0 self.do_simulation(a, self.frame_skip) ob = self._get_obs() notdone", "= True self.observation_space, self.action_space = \\ self._env.observation_space, self._env.action_space # it's", "their ground-truth apis, then we cannot test the algorithm using", "1e-3 * v1**2 + 5e-3 * v2**2 alive_bonus = 10", "env(env_name, 1234, {}) api_env = env(env_name, 1234, {}) api_env.reset() ob,", "len(data_dict['start_state']) if target == 'state': derivative_data = np.zeros( [num_data, self._env_info['ob_size']],", "\"\"\" import numpy as np from mbbl.config import init_path from", "self.reward = reward def reward_derivative(data_dict, target): num_data = len(data_dict['start_state']) if", "qvel: 3 (3, 4, 5) site_pose: 2 (6, 7) \"\"\"", "similar to the one # defined in GYM # -----------------------------------------------------------------------------", "self._env_info['ob_size']], dtype=np.float ) # the xpos reward part derivative_data[:, xpos_ob_pos]", "return np.concatenate([qpos, qvel, site_xpos]).ravel() else: \"\"\" assert self._env_name == 'gym_invertedPendulum'", "= \\ {'gym_pendulum': 1, 'gym_doublePendulum': 7}[self._env_name] ypos_target = \\ {'gym_pendulum':", "env(env_name, 1234, {}) api_env.reset() ob, reward, _, _ = test_env.reset()", "False # will raise warnings -> set logger flag to", "disable=W0212 self._env.env.model.forward() self._old_ob = self._get_observation() self.set_state = set_state def fdynamics(data_dict):", "don't set their ground-truth apis, then we cannot test the", "'action': action}) reward_error = np.sum(np.abs(reward_from_api - reward)) # test the", "np.concatenate([qpos, qvel, site_xpos]).ravel() else: \"\"\" assert self._env_name == 'gym_invertedPendulum' return", "# acrobot has applied sin/cos obs PENDULUM = ['gym_invertedPendulum'] def", "self._env.env.data.qvel = qvel.reshape([-1, 1]) else: self._env.env.sim.data.qpos = qpos.reshape([-1]) self._env.env.sim.data.qvel =", "xpos_ob_pos] += - 2.0 * xpos_coeff * \\ (data_dict['start_state'][:, xpos_ob_pos])", "gym? if 'reset_type' in misc_info and misc_info['reset_type'] == 'gym': self._reset_return_obs_only", "ob, reward, done, info def reset(self, control_info={}): self._current_step = 0", "algorithm using ground-truth dynamics or reward \"\"\" self._set_reward_api() self._set_dynamics_api() def", "else: site_xpos = self._env.env.sim.data.site_xpos[:, [0, 2]] site_xpos = np.transpose(site_xpos) return", "fpdb().set_trace() # get the end signal self._current_step += 1 info['current_step']", "if self._current_step > self._env_info['max_length']: done = True else: done =", "qpos = self._env.env.data.qpos qvel = self._env.env.data.qvel else: qpos = self._env.env.sim.data.qpos", "qpos = self._env.env.sim.data.qpos qvel = self._env.env.sim.data.qvel \"\"\" if self._env_name ==", "new_ob, reward, _, _ = test_env.step(action) # test the reward", "ypos = data_dict['start_state'][ypos_ob_pos] ypos_reward = -(ypos - ypos_target) ** 2", "action} ) # from mbbl.util.common.fpdb import fpdb; fpdb().set_trace() # get", "def _get_observation(self): if self._current_version in ['0.7.4', '0.9.4']: qpos = self._env.env.data.qpos", "data_dict['start_state'][xpos_ob_pos] xpos_reward = -(xpos ** 2) * xpos_coeff # ypos", "qvel = self._env.env.sim.data.qvel \"\"\" if self._env_name == 'gym_doublePendulum': if self._current_version", "- ypos_target) ** 2 return xpos_reward + ypos_reward self.reward =", "for _ in range(100): action = np.random.uniform(-1, 1, test_env._env.action_space.shape) new_ob,", "the xpos reward part derivative_data[:, xpos_ob_pos] += - 2.0 *", "- 2.0 elif target == 'action-state': derivative_data = np.zeros( [num_data,", "= self._get_obs() x, _, y = self.model.data.site_xpos[0] dist_penalty = 0.01", "{}) api_env = env(env_name, 1234, {}) api_env.reset() ob, reward, _,", "self._current_step += 1 info['current_step'] = self._current_step if self._current_step > self._env_info['max_length']:", "and rewards APIs for the agent to call. For the", "ypos_ob_pos = \\ {'gym_pendulum': 1, 'gym_doublePendulum': 7}[self._env_name] ypos_target = \\", "[num_data, self._env_info['action_size']], dtype=np.float ) elif target == 'state-state': derivative_data =", "the algorithm using ground-truth dynamics or reward \"\"\" self._set_reward_api() self._set_dynamics_api()", "v2**2 alive_bonus = 10 r = (alive_bonus - dist_penalty -", "+= \\ - 2.0 * xpos_coeff # the ypos reward", "one # defined in GYM # ----------------------------------------------------------------------------- \"\"\" import numpy", "np.array(ob) return ob, reward, done, info def reset(self, control_info={}): self._current_step", "reward, done, info def reset(self, control_info={}): self._current_step = 0 self._env.reset()", "info = self._env.step(action) ob = self._get_observation() # get the reward", "function, we could provide the ground-truth dynamics and rewards APIs", "self._env_name == 'gym_doublePendulum': if self._current_version in ['0.7.4', '0.9.4']: site_xpos =", "0 ypos_ob_pos = 1 ypos_target = 0.0 xpos_coeff = 0.0", "done = False # will raise warnings -> set logger", "elif target == 'state-action': derivative_data = np.zeros( [num_data, self._env_info['ob_size'], self._env_info['action_size']],", "** 2 @ypos_penalty: (y - 2) ** 2 pendulum: (slide,", "= ['gym_invertedPendulum'] for env_name in test_env_name: test_env = env(env_name, 1234,", "hinge) qpos: 2 (0, 1) qvel: 2 (2, 3) double_pendulum:", "alive_bonus = 10 r = (alive_bonus - dist_penalty - vel_penalty)[0]", "[0, 2]] else: site_xpos = self._env.env.sim.data.site_xpos[:, [0, 2]] site_xpos =", "(alive_bonus - dist_penalty - vel_penalty)[0] done = bool(y <= 1)", "+= - 2.0 * xpos_coeff * \\ (data_dict['start_state'][:, xpos_ob_pos]) #", "== 'action-action': derivative_data = np.zeros( [num_data, self._env_info['action_size'], self._env_info['action_size']], dtype=np.float )", "np.zeros( [num_data, self._env_info['action_size'], self._env_info['ob_size']], dtype=np.float ) elif target == 'state-action':", "from mbbl.util.common import logger class env(bew.base_env): # acrobot has applied", "in ['0.7.4', '0.9.4']: site_xpos = self._env.env.data.site_xpos[:, [0, 2]] else: site_xpos", "+ 5e-3 * v2**2 alive_bonus = 10 r = (alive_bonus", "@ypos_penalty: (y - 2) ** 2 pendulum: (slide, hinge) qpos:", "# the xpos reward derivative_data[:, xpos_ob_pos, xpos_ob_pos] += \\ -", "= np.isfinite(ob).all() and (np.abs(ob[1]) <= .2) done = not notdone", "signal self._current_step += 1 info['current_step'] = self._current_step if self._current_step >", "reward function assert self._env_name in self.PENDULUM \"\"\" xpos_ob_pos = \\", "sure reset is called before using self.fynamics() self.set_state(data_dict) return self.step(data_dict['action'])[0]", "more similar to the one # defined in GYM #", "the state if self._current_version in ['0.7.4', '0.9.4']: self._env.env.data.qpos = qpos.reshape([-1,", "env_register from mbbl.env import env_util from mbbl.util.common import logger class", "elif target == 'action-action': derivative_data = np.zeros( [num_data, self._env_info['action_size'], self._env_info['action_size']],", "else: self._reset_return_obs_only = False def step(self, action): _, _, _,", "2) ** 2 pendulum: (slide, hinge) qpos: 2 (0, 1)", "(slide, hinge) qpos: 2 (0, 1) qvel: 2 (2, 3)", "= np.zeros( [num_data, self._env_info['ob_size'], self._env_info['action_size']], dtype=np.float ) elif target ==", "reset as the gym? if 'reset_type' in misc_info and misc_info['reset_type']", "the xpos reward derivative_data[:, xpos_ob_pos, xpos_ob_pos] += \\ - 2.0", "= np.array(ob) return ob, reward, done, info def reset(self, control_info={}):", "self._env.observation_space, self._env.action_space # it's possible some environments have different obs", "import init_path from mbbl.env import base_env_wrapper as bew from mbbl.env", "self._reset_return_obs_only = False def step(self, action): _, _, _, info", "self.observation_space, self.action_space = \\ self._env.observation_space, self._env.action_space # it's possible some", "dtype=np.float ) # the xpos reward part derivative_data[:, xpos_ob_pos] +=", ") # the xpos reward derivative_data[:, xpos_ob_pos, xpos_ob_pos] += \\", "# will raise warnings -> set logger flag to ignore", "== 'state': derivative_data = np.zeros( [num_data, self._env_info['ob_size']], dtype=np.float ) #", "derivative_data = np.zeros( [num_data, self._env_info['action_size'], self._env_info['ob_size']], dtype=np.float ) elif target", "self.fdynamics = fdynamics def _set_reward_api(self): \"\"\" def _step(self, a): reward", "assert self._env_name in self.PENDULUM \"\"\" xpos_ob_pos = \\ {'gym_pendulum': 0,", "sin/cos obs PENDULUM = ['gym_invertedPendulum'] def __init__(self, env_name, rand_seed, misc_info):", "env_util.get_gym_q_info(self._env, self._current_version) # return the reset as the gym? if" ]
[ "from .line import * from .mesh import * from .pie", ".line import * from .mesh import * from .pie import", "import * from .mesh import * from .pie import *", "from .create_session import * from .image import * from .line", "* from .image import * from .line import * from", "from .pie import * from .text import * from .VisdomFigure", ".pie import * from .text import * from .VisdomFigure import", ".create_session import * from .image import * from .line import", ".bar import * from .create_session import * from .image import", "from .image import * from .line import * from .mesh", "* from .create_session import * from .image import * from", "* from .pie import * from .text import * from", ".mesh import * from .pie import * from .text import", "* from .mesh import * from .pie import * from", ".image import * from .line import * from .mesh import", "import * from .create_session import * from .image import *", "from .mesh import * from .pie import * from .text", "import * from .pie import * from .text import *", "* from .line import * from .mesh import * from", "* from .text import * from .VisdomFigure import * from", "import * from .VisdomFigure import * from .VisdomScene import *", "from .text import * from .VisdomFigure import * from .VisdomScene", ".text import * from .VisdomFigure import * from .VisdomScene import", "from .bar import * from .create_session import * from .image", "import * from .image import * from .line import *", "import * from .text import * from .VisdomFigure import *", "import * from .line import * from .mesh import *" ]
[ "Uses zmq to speak to daemon controlling screen. from flask", "print(\"Terminating\") if message_process: message_process.terminate() atexit.register(stop_message_loop) @app.before_first_request def setup_ipc(): global message_process", "Queue() message_process = None def message_loop(message_queue): print(\"Starting message loop\") context", "atexit.register(stop_message_loop) @app.before_first_request def setup_ipc(): global message_process message_process = Process(target=message_loop, args=(message_queue,))", "try: socket = context.socket(zmq.REQ) socket.connect(\"tcp://localhost:5555\") print(\"Connected to daemon\") while True:", "Process, Queue from multiprocessing.connection import Client import atexit import time", "from multiprocessing.connection import Client import atexit import time import zmq", "def mode(name): text = request.args.get(\"val\", default=\"\", type=str) message_queue.put([MODE,name,text]) return \"\\\"OK\\\"\"", "message_loop(message_queue): print(\"Starting message loop\") context = zmq.Context() while True: try:", "= request.args.get(\"val\", default=\"\", type=str) message_queue.put([MODE,name,text]) return \"\\\"OK\\\"\" message_queue = Queue()", "UI running on flask. # Uses zmq to speak to", "= Flask(__name__) @app.route('/') def index(): return render_template('index.html') MODE=\"mode\" @app.route('/mode/<name>', methods=['POST'])", "= Process(target=message_loop, args=(message_queue,)) message_process.start() if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')", "context.socket(zmq.REQ) socket.connect(\"tcp://localhost:5555\") print(\"Connected to daemon\") while True: msg = message_queue.get()", "web UI running on flask. # Uses zmq to speak", "multiprocessing.connection import Client import atexit import time import zmq app", "msg) socket.send_json(msg) socket.recv() except Exception as ex: print(ex) time.sleep(5) def", "print(\"Connected to daemon\") while True: msg = message_queue.get() print(\"Sending \",", "message_process = Process(target=message_loop, args=(message_queue,)) message_process.start() if __name__ == '__main__': app.run(debug=True,", "daemon\") while True: msg = message_queue.get() print(\"Sending \", msg) socket.send_json(msg)", "# Uses zmq to speak to daemon controlling screen. from", "speak to daemon controlling screen. from flask import Flask, render_template,", "True: try: socket = context.socket(zmq.REQ) socket.connect(\"tcp://localhost:5555\") print(\"Connected to daemon\") while", "\"\\\"OK\\\"\" message_queue = Queue() message_process = None def message_loop(message_queue): print(\"Starting", "message_queue.get() print(\"Sending \", msg) socket.send_json(msg) socket.recv() except Exception as ex:", "= message_queue.get() print(\"Sending \", msg) socket.send_json(msg) socket.recv() except Exception as", "return \"\\\"OK\\\"\" message_queue = Queue() message_process = None def message_loop(message_queue):", "from multiprocessing import Process, Queue from multiprocessing.connection import Client import", "socket.connect(\"tcp://localhost:5555\") print(\"Connected to daemon\") while True: msg = message_queue.get() print(\"Sending", "def stop_message_loop(): print(\"Terminating\") if message_process: message_process.terminate() atexit.register(stop_message_loop) @app.before_first_request def setup_ipc():", "return render_template('index.html') MODE=\"mode\" @app.route('/mode/<name>', methods=['POST']) def mode(name): text = request.args.get(\"val\",", "= Queue() message_process = None def message_loop(message_queue): print(\"Starting message loop\")", "if message_process: message_process.terminate() atexit.register(stop_message_loop) @app.before_first_request def setup_ipc(): global message_process message_process", "socket.send_json(msg) socket.recv() except Exception as ex: print(ex) time.sleep(5) def stop_message_loop():", "def setup_ipc(): global message_process message_process = Process(target=message_loop, args=(message_queue,)) message_process.start() if", "to speak to daemon controlling screen. from flask import Flask,", "text = request.args.get(\"val\", default=\"\", type=str) message_queue.put([MODE,name,text]) return \"\\\"OK\\\"\" message_queue =", "to daemon\") while True: msg = message_queue.get() print(\"Sending \", msg)", "message_queue.put([MODE,name,text]) return \"\\\"OK\\\"\" message_queue = Queue() message_process = None def", "zmq app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') MODE=\"mode\"", "request.args.get(\"val\", default=\"\", type=str) message_queue.put([MODE,name,text]) return \"\\\"OK\\\"\" message_queue = Queue() message_process", "= None def message_loop(message_queue): print(\"Starting message loop\") context = zmq.Context()", "from flask import Flask, render_template, appcontext_tearing_down, request from multiprocessing import", "on flask. # Uses zmq to speak to daemon controlling", "context = zmq.Context() while True: try: socket = context.socket(zmq.REQ) socket.connect(\"tcp://localhost:5555\")", "= context.socket(zmq.REQ) socket.connect(\"tcp://localhost:5555\") print(\"Connected to daemon\") while True: msg =", "\", msg) socket.send_json(msg) socket.recv() except Exception as ex: print(ex) time.sleep(5)", "Pi web UI running on flask. # Uses zmq to", "screen. from flask import Flask, render_template, appcontext_tearing_down, request from multiprocessing", "as ex: print(ex) time.sleep(5) def stop_message_loop(): print(\"Terminating\") if message_process: message_process.terminate()", "to daemon controlling screen. from flask import Flask, render_template, appcontext_tearing_down,", "render_template('index.html') MODE=\"mode\" @app.route('/mode/<name>', methods=['POST']) def mode(name): text = request.args.get(\"val\", default=\"\",", "Queue from multiprocessing.connection import Client import atexit import time import", "multiprocessing import Process, Queue from multiprocessing.connection import Client import atexit", "loop\") context = zmq.Context() while True: try: socket = context.socket(zmq.REQ)", "message_process: message_process.terminate() atexit.register(stop_message_loop) @app.before_first_request def setup_ipc(): global message_process message_process =", "msg = message_queue.get() print(\"Sending \", msg) socket.send_json(msg) socket.recv() except Exception", "zmq.Context() while True: try: socket = context.socket(zmq.REQ) socket.connect(\"tcp://localhost:5555\") print(\"Connected to", "flask import Flask, render_template, appcontext_tearing_down, request from multiprocessing import Process,", "atexit import time import zmq app = Flask(__name__) @app.route('/') def", "flask. # Uses zmq to speak to daemon controlling screen.", "= zmq.Context() while True: try: socket = context.socket(zmq.REQ) socket.connect(\"tcp://localhost:5555\") print(\"Connected", "import time import zmq app = Flask(__name__) @app.route('/') def index():", "while True: try: socket = context.socket(zmq.REQ) socket.connect(\"tcp://localhost:5555\") print(\"Connected to daemon\")", "@app.before_first_request def setup_ipc(): global message_process message_process = Process(target=message_loop, args=(message_queue,)) message_process.start()", "methods=['POST']) def mode(name): text = request.args.get(\"val\", default=\"\", type=str) message_queue.put([MODE,name,text]) return", "index(): return render_template('index.html') MODE=\"mode\" @app.route('/mode/<name>', methods=['POST']) def mode(name): text =", "default=\"\", type=str) message_queue.put([MODE,name,text]) return \"\\\"OK\\\"\" message_queue = Queue() message_process =", "render_template, appcontext_tearing_down, request from multiprocessing import Process, Queue from multiprocessing.connection", "message_process = None def message_loop(message_queue): print(\"Starting message loop\") context =", "appcontext_tearing_down, request from multiprocessing import Process, Queue from multiprocessing.connection import", "except Exception as ex: print(ex) time.sleep(5) def stop_message_loop(): print(\"Terminating\") if", "time.sleep(5) def stop_message_loop(): print(\"Terminating\") if message_process: message_process.terminate() atexit.register(stop_message_loop) @app.before_first_request def", "Flask(__name__) @app.route('/') def index(): return render_template('index.html') MODE=\"mode\" @app.route('/mode/<name>', methods=['POST']) def", "import zmq app = Flask(__name__) @app.route('/') def index(): return render_template('index.html')", "socket = context.socket(zmq.REQ) socket.connect(\"tcp://localhost:5555\") print(\"Connected to daemon\") while True: msg", "@app.route('/mode/<name>', methods=['POST']) def mode(name): text = request.args.get(\"val\", default=\"\", type=str) message_queue.put([MODE,name,text])", "# Ping Pong Pi web UI running on flask. #", "import Flask, render_template, appcontext_tearing_down, request from multiprocessing import Process, Queue", "request from multiprocessing import Process, Queue from multiprocessing.connection import Client", "app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') MODE=\"mode\" @app.route('/mode/<name>',", "type=str) message_queue.put([MODE,name,text]) return \"\\\"OK\\\"\" message_queue = Queue() message_process = None", "None def message_loop(message_queue): print(\"Starting message loop\") context = zmq.Context() while", "Ping Pong Pi web UI running on flask. # Uses", "import atexit import time import zmq app = Flask(__name__) @app.route('/')", "running on flask. # Uses zmq to speak to daemon", "<gh_stars>0 # Ping Pong Pi web UI running on flask.", "Flask, render_template, appcontext_tearing_down, request from multiprocessing import Process, Queue from", "MODE=\"mode\" @app.route('/mode/<name>', methods=['POST']) def mode(name): text = request.args.get(\"val\", default=\"\", type=str)", "import Process, Queue from multiprocessing.connection import Client import atexit import", "global message_process message_process = Process(target=message_loop, args=(message_queue,)) message_process.start() if __name__ ==", "Client import atexit import time import zmq app = Flask(__name__)", "print(\"Sending \", msg) socket.send_json(msg) socket.recv() except Exception as ex: print(ex)", "controlling screen. from flask import Flask, render_template, appcontext_tearing_down, request from", "message loop\") context = zmq.Context() while True: try: socket =", "while True: msg = message_queue.get() print(\"Sending \", msg) socket.send_json(msg) socket.recv()", "message_queue = Queue() message_process = None def message_loop(message_queue): print(\"Starting message", "def message_loop(message_queue): print(\"Starting message loop\") context = zmq.Context() while True:", "import Client import atexit import time import zmq app =", "def index(): return render_template('index.html') MODE=\"mode\" @app.route('/mode/<name>', methods=['POST']) def mode(name): text", "time import zmq app = Flask(__name__) @app.route('/') def index(): return", "Pong Pi web UI running on flask. # Uses zmq", "message_process.terminate() atexit.register(stop_message_loop) @app.before_first_request def setup_ipc(): global message_process message_process = Process(target=message_loop,", "stop_message_loop(): print(\"Terminating\") if message_process: message_process.terminate() atexit.register(stop_message_loop) @app.before_first_request def setup_ipc(): global", "Exception as ex: print(ex) time.sleep(5) def stop_message_loop(): print(\"Terminating\") if message_process:", "@app.route('/') def index(): return render_template('index.html') MODE=\"mode\" @app.route('/mode/<name>', methods=['POST']) def mode(name):", "print(ex) time.sleep(5) def stop_message_loop(): print(\"Terminating\") if message_process: message_process.terminate() atexit.register(stop_message_loop) @app.before_first_request", "daemon controlling screen. from flask import Flask, render_template, appcontext_tearing_down, request", "mode(name): text = request.args.get(\"val\", default=\"\", type=str) message_queue.put([MODE,name,text]) return \"\\\"OK\\\"\" message_queue", "True: msg = message_queue.get() print(\"Sending \", msg) socket.send_json(msg) socket.recv() except", "message_process message_process = Process(target=message_loop, args=(message_queue,)) message_process.start() if __name__ == '__main__':", "setup_ipc(): global message_process message_process = Process(target=message_loop, args=(message_queue,)) message_process.start() if __name__", "print(\"Starting message loop\") context = zmq.Context() while True: try: socket", "zmq to speak to daemon controlling screen. from flask import", "ex: print(ex) time.sleep(5) def stop_message_loop(): print(\"Terminating\") if message_process: message_process.terminate() atexit.register(stop_message_loop)", "socket.recv() except Exception as ex: print(ex) time.sleep(5) def stop_message_loop(): print(\"Terminating\")" ]
[ "test_exception_model(self): self.m_c_model.return_value = None self.assertRaises( exception.ClusterStateNotDefined, self.strategy.execute) def test_exception_stale_cdm(self): self.fake_c_cluster.set_cluster_data_model_as_stale()", "2.0 (the \"License\"); # you may not use this file", "watcher.decision_engine.strategy import strategies from watcher.tests import base from watcher.tests.decision_engine.model import", "cluster self.fake_c_cluster = faker_cluster_state.FakerModelCollector() p_c_model = mock.patch.object( strategies.BaseStrategy, \"compute_model\", new_callable=mock.PropertyMock)", "overridden\"\"\" datasources = mock.Mock(datasources=['ceilometer']) self.strategy = strategies.DummyStrategy( config=datasources) m_conf.watcher_datasources.datasources =", "m_conf.watcher_datasources.datasources = \\ ['gnocchi', 'monasca', 'ceilometer'] # Make sure we", "get the correct datasource self.strategy.datasource_backend m_manager.assert_called_once_with( config=m_conf.watcher_datasources, osc=None) @mock.patch.object(strategies.BaseStrategy, 'osc',", "self.strategy = strategies.DummyStrategy(config=mock.Mock()) class TestBaseStrategyDatasource(TestBaseStrategy): def setUp(self): super(TestBaseStrategyDatasource, self).setUp() self.strategy", "underlying function. m_manager.return_value.get_backend.return_value = \\ mock.NonCallableMock() # Access the property", "self).setUp() def test_exception_model(self): self.m_c_model.return_value = None self.assertRaises( exception.ClusterStateNotDefined, self.strategy.execute) def", "super(TestBaseStrategy, self).setUp() # fake cluster self.fake_c_cluster = faker_cluster_state.FakerModelCollector() p_c_model =", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "m_conf.watcher_datasources.datasources = \\ ['ceilometer', 'monasca', 'gnocchi'] # Access the property", "['ceilometer', 'monasca', 'gnocchi'] # Access the property so that the", "global preference can be overridden\"\"\" datasources = mock.Mock(datasources=['ceilometer']) self.strategy =", "ANY KIND, either express or # implied. # See the", "language governing permissions and # limitations under the License. from", "self.m_c_model.return_value = None self.assertRaises( exception.ClusterStateNotDefined, self.strategy.execute) def test_exception_stale_cdm(self): self.fake_c_cluster.set_cluster_data_model_as_stale() self.m_c_model.return_value", "used\"\"\" m_conf.watcher_datasources.datasources = \\ ['gnocchi', 'monasca', 'ceilometer'] # Make sure", "m_conf.watcher_datasources.datasources = \\ ['ceilometer', 'monasca', 'gnocchi'] # Make sure we", "super(TestBaseStrategyDatasource, self).setUp() self.strategy = strategies.DummyStrategy( config=mock.Mock(datasources=None)) @mock.patch.object(strategies.BaseStrategy, 'osc', None) @mock.patch.object(manager,", "use this file except in compliance with the License. #", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "License. # You may obtain a copy of the License", "watcher.tests.decision_engine.model import faker_cluster_state class TestBaseStrategy(base.TestCase): def setUp(self): super(TestBaseStrategy, self).setUp() #", "under the License is distributed on an \"AS IS\" BASIS,", "License for the specific language governing permissions and # limitations", "test_global_preference(self, m_conf, m_manager): \"\"\"Test if the global preference is used\"\"\"", "manager from watcher.decision_engine.model import model_root from watcher.decision_engine.strategy import strategies from", "from watcher.decision_engine.model import model_root from watcher.decision_engine.strategy import strategies from watcher.tests", "None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_global_preference(self, m_conf, m_manager): \"\"\"Test", "class TestBaseStrategy(base.TestCase): def setUp(self): super(TestBaseStrategy, self).setUp() # fake cluster self.fake_c_cluster", "self.strategy.execute) def test_exception_stale_cdm(self): self.fake_c_cluster.set_cluster_data_model_as_stale() self.m_c_model.return_value = self.fake_c_cluster.cluster_data_model self.assertRaises( # TODO(Dantali0n)", "@mock.patch.object(strategies.BaseStrategy, 'osc', None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_global_preference_reverse(self, m_conf,", "datasource self.strategy.datasource_backend m_manager.assert_called_once_with( config=datasources, osc=None) class TestBaseStrategyException(TestBaseStrategy): def setUp(self): super(TestBaseStrategyException,", "import manager from watcher.decision_engine.model import model_root from watcher.decision_engine.strategy import strategies", "watcher.decision_engine.datasources import manager from watcher.decision_engine.model import model_root from watcher.decision_engine.strategy import", "European Organization for Nuclear Research (CERN) # # Licensed under", "@mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_global_preference_reverse(self, m_conf, m_manager): \"\"\"Test if", "limitations under the License. from unittest import mock from watcher.common", "faker_cluster_state.FakerModelCollector() p_c_model = mock.patch.object( strategies.BaseStrategy, \"compute_model\", new_callable=mock.PropertyMock) self.m_c_model = p_c_model.start()", "in compliance with the License. # You may obtain a", "and not the underlying function. m_manager.return_value.get_backend.return_value = \\ mock.NonCallableMock() #", "software # distributed under the License is distributed on an", "Copyright (c) 2019 European Organization for Nuclear Research (CERN) #", "['ceilometer', 'monasca', 'gnocchi'] # Make sure we access the property", "self.strategy = strategies.DummyStrategy( config=datasources) m_conf.watcher_datasources.datasources = \\ ['ceilometer', 'monasca', 'gnocchi']", "is used\"\"\" m_conf.watcher_datasources.datasources = \\ ['gnocchi', 'monasca', 'ceilometer'] # Make", "from watcher.decision_engine.datasources import manager from watcher.decision_engine.model import model_root from watcher.decision_engine.strategy", "= p_audit_scope.start() self.addCleanup(p_audit_scope.stop) self.m_audit_scope.return_value = mock.Mock() self.m_c_model.return_value = model_root.ModelRoot() self.strategy", "property and not the underlying function. m_manager.return_value.get_backend.return_value = \\ mock.NonCallableMock()", "setUp(self): super(TestBaseStrategyException, self).setUp() def test_exception_model(self): self.m_c_model.return_value = None self.assertRaises( exception.ClusterStateNotDefined,", "@mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_global_preference(self, m_conf, m_manager): \"\"\"Test if", "watcher.decision_engine.model import model_root from watcher.decision_engine.strategy import strategies from watcher.tests import", "from watcher.tests.decision_engine.model import faker_cluster_state class TestBaseStrategy(base.TestCase): def setUp(self): super(TestBaseStrategy, self).setUp()", "config=m_conf.watcher_datasources, osc=None) @mock.patch.object(strategies.BaseStrategy, 'osc', None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def", "self.fake_c_cluster.set_cluster_data_model_as_stale() self.m_c_model.return_value = self.fake_c_cluster.cluster_data_model self.assertRaises( # TODO(Dantali0n) This should return", "not the underlying function. m_manager.return_value.get_backend.return_value = \\ mock.NonCallableMock() # Access", "See the License for the specific language governing permissions and", "osc=None) @mock.patch.object(strategies.BaseStrategy, 'osc', None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_global_preference_reverse(self,", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "the property so that the configuration is read in order", "(c) 2019 European Organization for Nuclear Research (CERN) # #", "to in writing, software # distributed under the License is", "'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_strategy_preference_override(self, m_conf, m_manager): \"\"\"Test if the", "# See the License for the specific language governing permissions", "the configuration is read in order to # get the", "datasource self.strategy.datasource_backend m_manager.assert_called_once_with( config=m_conf.watcher_datasources, osc=None) @mock.patch.object(strategies.BaseStrategy, 'osc', None) @mock.patch.object(manager, 'DataSourceManager')", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "get the correct datasource self.strategy.datasource_backend m_manager.assert_called_once_with( config=datasources, osc=None) class TestBaseStrategyException(TestBaseStrategy):", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "be overridden\"\"\" datasources = mock.Mock(datasources=['ceilometer']) self.strategy = strategies.DummyStrategy( config=datasources) m_conf.watcher_datasources.datasources", "with the License. # You may obtain a copy of", "self.m_audit_scope = p_audit_scope.start() self.addCleanup(p_audit_scope.stop) self.m_audit_scope.return_value = mock.Mock() self.m_c_model.return_value = model_root.ModelRoot()", "= strategies.DummyStrategy( config=mock.Mock(datasources=None)) @mock.patch.object(strategies.BaseStrategy, 'osc', None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF')", "the global preference is used\"\"\" m_conf.watcher_datasources.datasources = \\ ['gnocchi', 'monasca',", "p_c_model.start() self.addCleanup(p_c_model.stop) p_audit_scope = mock.patch.object( strategies.BaseStrategy, \"audit_scope\", new_callable=mock.PropertyMock) self.m_audit_scope =", "the global preference can be overridden\"\"\" datasources = mock.Mock(datasources=['ceilometer']) self.strategy", "test_strategy_preference_override(self, m_conf, m_manager): \"\"\"Test if the global preference can be", "compliance with the License. # You may obtain a copy", "agreed to in writing, software # distributed under the License", "# get the correct datasource self.strategy.datasource_backend m_manager.assert_called_once_with( config=m_conf.watcher_datasources, osc=None) @mock.patch.object(strategies.BaseStrategy,", "distributed under the License is distributed on an \"AS IS\"", "order to # get the correct datasource self.strategy.datasource_backend m_manager.assert_called_once_with( config=datasources,", "watcher.common import exception from watcher.decision_engine.datasources import manager from watcher.decision_engine.model import", "or # implied. # See the License for the specific", "'monasca', 'ceilometer'] # Make sure we access the property and", "from watcher.tests import base from watcher.tests.decision_engine.model import faker_cluster_state class TestBaseStrategy(base.TestCase):", "(CERN) # # Licensed under the Apache License, Version 2.0", "TestBaseStrategy(base.TestCase): def setUp(self): super(TestBaseStrategy, self).setUp() # fake cluster self.fake_c_cluster =", "\\ ['ceilometer', 'monasca', 'gnocchi'] # Access the property so that", "preference can be overridden\"\"\" datasources = mock.Mock(datasources=['ceilometer']) self.strategy = strategies.DummyStrategy(", "except in compliance with the License. # You may obtain", "mock.NonCallableMock() # Access the property so that the configuration is", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "m_conf, m_manager): \"\"\"Test if the global preference can be overridden\"\"\"", "not use this file except in compliance with the License.", "express or # implied. # See the License for the", "= mock.patch.object( strategies.BaseStrategy, \"compute_model\", new_callable=mock.PropertyMock) self.m_c_model = p_c_model.start() self.addCleanup(p_c_model.stop) p_audit_scope", "writing, software # distributed under the License is distributed on", "@mock.patch.object(strategies.BaseStrategy, 'osc', None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_global_preference(self, m_conf,", "you may not use this file except in compliance with", "the property and not the underlying function. m_manager.return_value.get_backend.return_value = \\", "['gnocchi', 'monasca', 'ceilometer'] # Make sure we access the property", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_global_preference_reverse(self, m_conf, m_manager): \"\"\"Test if the", "@mock.patch.object(strategies.base, 'CONF') def test_strategy_preference_override(self, m_conf, m_manager): \"\"\"Test if the global", "Research (CERN) # # Licensed under the Apache License, Version", "in order to # get the correct datasource self.strategy.datasource_backend m_manager.assert_called_once_with(", "import faker_cluster_state class TestBaseStrategy(base.TestCase): def setUp(self): super(TestBaseStrategy, self).setUp() # fake", "governing permissions and # limitations under the License. from unittest", "if the global preference can be overridden\"\"\" datasources = mock.Mock(datasources=['ceilometer'])", "None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_strategy_preference_override(self, m_conf, m_manager): \"\"\"Test", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "self.m_c_model.return_value = model_root.ModelRoot() self.strategy = strategies.DummyStrategy(config=mock.Mock()) class TestBaseStrategyDatasource(TestBaseStrategy): def setUp(self):", "m_manager.assert_called_once_with( config=datasources, osc=None) class TestBaseStrategyException(TestBaseStrategy): def setUp(self): super(TestBaseStrategyException, self).setUp() def", "\\ ['gnocchi', 'monasca', 'ceilometer'] # Make sure we access the", "Make sure we access the property and not the underlying", "to # get the correct datasource self.strategy.datasource_backend m_manager.assert_called_once_with( config=m_conf.watcher_datasources, osc=None)", "\"compute_model\", new_callable=mock.PropertyMock) self.m_c_model = p_c_model.start() self.addCleanup(p_c_model.stop) p_audit_scope = mock.patch.object( strategies.BaseStrategy,", "= strategies.DummyStrategy( config=datasources) m_conf.watcher_datasources.datasources = \\ ['ceilometer', 'monasca', 'gnocchi'] #", "the License is distributed on an \"AS IS\" BASIS, #", "m_manager): \"\"\"Test if the global preference can be overridden\"\"\" datasources", "= self.fake_c_cluster.cluster_data_model self.assertRaises( # TODO(Dantali0n) This should return ClusterStale, #", "unittest import mock from watcher.common import exception from watcher.decision_engine.datasources import", "= mock.patch.object( strategies.BaseStrategy, \"audit_scope\", new_callable=mock.PropertyMock) self.m_audit_scope = p_audit_scope.start() self.addCleanup(p_audit_scope.stop) self.m_audit_scope.return_value", "import exception from watcher.decision_engine.datasources import manager from watcher.decision_engine.model import model_root", "sure we access the property and not the underlying function.", "fake cluster self.fake_c_cluster = faker_cluster_state.FakerModelCollector() p_c_model = mock.patch.object( strategies.BaseStrategy, \"compute_model\",", "law or agreed to in writing, software # distributed under", "mock.patch.object( strategies.BaseStrategy, \"audit_scope\", new_callable=mock.PropertyMock) self.m_audit_scope = p_audit_scope.start() self.addCleanup(p_audit_scope.stop) self.m_audit_scope.return_value =", "read in order to # get the correct datasource self.strategy.datasource_backend", "encoding: utf-8 -*- # Copyright (c) 2019 European Organization for", "# get the correct datasource self.strategy.datasource_backend m_manager.assert_called_once_with( config=datasources, osc=None) class", "# fake cluster self.fake_c_cluster = faker_cluster_state.FakerModelCollector() p_c_model = mock.patch.object( strategies.BaseStrategy,", "self).setUp() self.strategy = strategies.DummyStrategy( config=mock.Mock(datasources=None)) @mock.patch.object(strategies.BaseStrategy, 'osc', None) @mock.patch.object(manager, 'DataSourceManager')", "the underlying function. m_manager.return_value.get_backend.return_value = \\ mock.NonCallableMock() # Access the", "CONDITIONS OF ANY KIND, either express or # implied. #", "'CONF') def test_global_preference_reverse(self, m_conf, m_manager): \"\"\"Test if the global preference", "may obtain a copy of the License at # #", "strategies from watcher.tests import base from watcher.tests.decision_engine.model import faker_cluster_state class", "correct datasource self.strategy.datasource_backend m_manager.assert_called_once_with( config=datasources, osc=None) class TestBaseStrategyException(TestBaseStrategy): def setUp(self):", "config=mock.Mock(datasources=None)) @mock.patch.object(strategies.BaseStrategy, 'osc', None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_global_preference(self,", "'monasca', 'gnocchi'] # Make sure we access the property and", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "'osc', None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_global_preference_reverse(self, m_conf, m_manager):", "watcher.tests import base from watcher.tests.decision_engine.model import faker_cluster_state class TestBaseStrategy(base.TestCase): def", "may not use this file except in compliance with the", "'ceilometer'] # Make sure we access the property and not", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "exception.ClusterStateNotDefined, self.strategy.execute) def test_exception_stale_cdm(self): self.fake_c_cluster.set_cluster_data_model_as_stale() self.m_c_model.return_value = self.fake_c_cluster.cluster_data_model self.assertRaises( #", "this file except in compliance with the License. # You", "model_root from watcher.decision_engine.strategy import strategies from watcher.tests import base from", "under the License. from unittest import mock from watcher.common import", "m_manager): \"\"\"Test if the global preference is used\"\"\" m_conf.watcher_datasources.datasources =", "the License. from unittest import mock from watcher.common import exception", "mock.patch.object( strategies.BaseStrategy, \"compute_model\", new_callable=mock.PropertyMock) self.m_c_model = p_c_model.start() self.addCleanup(p_c_model.stop) p_audit_scope =", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "another order\"\"\" m_conf.watcher_datasources.datasources = \\ ['ceilometer', 'monasca', 'gnocchi'] # Make", "# # Licensed under the Apache License, Version 2.0 (the", "import strategies from watcher.tests import base from watcher.tests.decision_engine.model import faker_cluster_state", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "self.m_audit_scope.return_value = mock.Mock() self.m_c_model.return_value = model_root.ModelRoot() self.strategy = strategies.DummyStrategy(config=mock.Mock()) class", "self.strategy = strategies.DummyStrategy( config=mock.Mock(datasources=None)) @mock.patch.object(strategies.BaseStrategy, 'osc', None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base,", "osc=None) @mock.patch.object(strategies.BaseStrategy, 'osc', None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_strategy_preference_override(self,", "function. m_manager.return_value.get_backend.return_value = \\ mock.NonCallableMock() # Access the property so", "new_callable=mock.PropertyMock) self.m_c_model = p_c_model.start() self.addCleanup(p_c_model.stop) p_audit_scope = mock.patch.object( strategies.BaseStrategy, \"audit_scope\",", "self.assertRaises( exception.ClusterStateNotDefined, self.strategy.execute) def test_exception_stale_cdm(self): self.fake_c_cluster.set_cluster_data_model_as_stale() self.m_c_model.return_value = self.fake_c_cluster.cluster_data_model self.assertRaises(", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "# -*- encoding: utf-8 -*- # Copyright (c) 2019 European", "the correct datasource self.strategy.datasource_backend m_manager.assert_called_once_with( config=m_conf.watcher_datasources, osc=None) @mock.patch.object(strategies.BaseStrategy, 'osc', None)", "# Copyright (c) 2019 European Organization for Nuclear Research (CERN)", "class TestBaseStrategyDatasource(TestBaseStrategy): def setUp(self): super(TestBaseStrategyDatasource, self).setUp() self.strategy = strategies.DummyStrategy( config=mock.Mock(datasources=None))", "= None self.assertRaises( exception.ClusterStateNotDefined, self.strategy.execute) def test_exception_stale_cdm(self): self.fake_c_cluster.set_cluster_data_model_as_stale() self.m_c_model.return_value =", "\\ ['ceilometer', 'monasca', 'gnocchi'] # Make sure we access the", "@mock.patch.object(strategies.BaseStrategy, 'osc', None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_strategy_preference_override(self, m_conf,", "super(TestBaseStrategyException, self).setUp() def test_exception_model(self): self.m_c_model.return_value = None self.assertRaises( exception.ClusterStateNotDefined, self.strategy.execute)", "# limitations under the License. from unittest import mock from", "self.strategy.datasource_backend m_manager.assert_called_once_with( config=datasources, osc=None) class TestBaseStrategyException(TestBaseStrategy): def setUp(self): super(TestBaseStrategyException, self).setUp()", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "import mock from watcher.common import exception from watcher.decision_engine.datasources import manager", "self).setUp() # fake cluster self.fake_c_cluster = faker_cluster_state.FakerModelCollector() p_c_model = mock.patch.object(", "access the property and not the underlying function. m_manager.return_value.get_backend.return_value =", "is used with another order\"\"\" m_conf.watcher_datasources.datasources = \\ ['ceilometer', 'monasca',", "= \\ ['ceilometer', 'monasca', 'gnocchi'] # Make sure we access", "def setUp(self): super(TestBaseStrategyException, self).setUp() def test_exception_model(self): self.m_c_model.return_value = None self.assertRaises(", "strategies.DummyStrategy(config=mock.Mock()) class TestBaseStrategyDatasource(TestBaseStrategy): def setUp(self): super(TestBaseStrategyDatasource, self).setUp() self.strategy = strategies.DummyStrategy(", "strategies.BaseStrategy, \"compute_model\", new_callable=mock.PropertyMock) self.m_c_model = p_c_model.start() self.addCleanup(p_c_model.stop) p_audit_scope = mock.patch.object(", "strategies.DummyStrategy( config=mock.Mock(datasources=None)) @mock.patch.object(strategies.BaseStrategy, 'osc', None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def", "specific language governing permissions and # limitations under the License.", "datasources = mock.Mock(datasources=['ceilometer']) self.strategy = strategies.DummyStrategy( config=datasources) m_conf.watcher_datasources.datasources = \\", "configuration is read in order to # get the correct", "m_manager): \"\"\"Test if the global preference is used with another", "\"\"\"Test if the global preference can be overridden\"\"\" datasources =", "= \\ ['ceilometer', 'monasca', 'gnocchi'] # Access the property so", "strategies.BaseStrategy, \"audit_scope\", new_callable=mock.PropertyMock) self.m_audit_scope = p_audit_scope.start() self.addCleanup(p_audit_scope.stop) self.m_audit_scope.return_value = mock.Mock()", "p_audit_scope.start() self.addCleanup(p_audit_scope.stop) self.m_audit_scope.return_value = mock.Mock() self.m_c_model.return_value = model_root.ModelRoot() self.strategy =", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "import base from watcher.tests.decision_engine.model import faker_cluster_state class TestBaseStrategy(base.TestCase): def setUp(self):", "def setUp(self): super(TestBaseStrategyDatasource, self).setUp() self.strategy = strategies.DummyStrategy( config=mock.Mock(datasources=None)) @mock.patch.object(strategies.BaseStrategy, 'osc',", "@mock.patch.object(strategies.base, 'CONF') def test_global_preference_reverse(self, m_conf, m_manager): \"\"\"Test if the global", "None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_global_preference_reverse(self, m_conf, m_manager): \"\"\"Test", "(the \"License\"); # you may not use this file except", "# you may not use this file except in compliance", "exception from watcher.decision_engine.datasources import manager from watcher.decision_engine.model import model_root from", "mock.Mock(datasources=['ceilometer']) self.strategy = strategies.DummyStrategy( config=datasources) m_conf.watcher_datasources.datasources = \\ ['ceilometer', 'monasca',", "= \\ ['gnocchi', 'monasca', 'ceilometer'] # Make sure we access", "permissions and # limitations under the License. from unittest import", "'gnocchi'] # Access the property so that the configuration is", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or #", "# # Unless required by applicable law or agreed to", "# implied. # See the License for the specific language", "def test_global_preference_reverse(self, m_conf, m_manager): \"\"\"Test if the global preference is", "order\"\"\" m_conf.watcher_datasources.datasources = \\ ['ceilometer', 'monasca', 'gnocchi'] # Make sure", "preference is used\"\"\" m_conf.watcher_datasources.datasources = \\ ['gnocchi', 'monasca', 'ceilometer'] #", "mock from watcher.common import exception from watcher.decision_engine.datasources import manager from", "\"\"\"Test if the global preference is used\"\"\" m_conf.watcher_datasources.datasources = \\", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "= mock.Mock() self.m_c_model.return_value = model_root.ModelRoot() self.strategy = strategies.DummyStrategy(config=mock.Mock()) class TestBaseStrategyDatasource(TestBaseStrategy):", "Version 2.0 (the \"License\"); # you may not use this", "TestBaseStrategyDatasource(TestBaseStrategy): def setUp(self): super(TestBaseStrategyDatasource, self).setUp() self.strategy = strategies.DummyStrategy( config=mock.Mock(datasources=None)) @mock.patch.object(strategies.BaseStrategy,", "setUp(self): super(TestBaseStrategyDatasource, self).setUp() self.strategy = strategies.DummyStrategy( config=mock.Mock(datasources=None)) @mock.patch.object(strategies.BaseStrategy, 'osc', None)", "the correct datasource self.strategy.datasource_backend m_manager.assert_called_once_with( config=datasources, osc=None) class TestBaseStrategyException(TestBaseStrategy): def", "p_audit_scope = mock.patch.object( strategies.BaseStrategy, \"audit_scope\", new_callable=mock.PropertyMock) self.m_audit_scope = p_audit_scope.start() self.addCleanup(p_audit_scope.stop)", "def test_strategy_preference_override(self, m_conf, m_manager): \"\"\"Test if the global preference can", "@mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_strategy_preference_override(self, m_conf, m_manager): \"\"\"Test if", "= p_c_model.start() self.addCleanup(p_c_model.stop) p_audit_scope = mock.patch.object( strategies.BaseStrategy, \"audit_scope\", new_callable=mock.PropertyMock) self.m_audit_scope", "implied. # See the License for the specific language governing", "Nuclear Research (CERN) # # Licensed under the Apache License,", "under the Apache License, Version 2.0 (the \"License\"); # you", "utf-8 -*- # Copyright (c) 2019 European Organization for Nuclear", "self.strategy.datasource_backend m_manager.assert_called_once_with( config=m_conf.watcher_datasources, osc=None) @mock.patch.object(strategies.BaseStrategy, 'osc', None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base,", "p_c_model = mock.patch.object( strategies.BaseStrategy, \"compute_model\", new_callable=mock.PropertyMock) self.m_c_model = p_c_model.start() self.addCleanup(p_c_model.stop)", "faker_cluster_state class TestBaseStrategy(base.TestCase): def setUp(self): super(TestBaseStrategy, self).setUp() # fake cluster", "property so that the configuration is read in order to", "self.m_c_model.return_value = self.fake_c_cluster.cluster_data_model self.assertRaises( # TODO(Dantali0n) This should return ClusterStale,", "used with another order\"\"\" m_conf.watcher_datasources.datasources = \\ ['ceilometer', 'monasca', 'gnocchi']", "by applicable law or agreed to in writing, software #", "'CONF') def test_global_preference(self, m_conf, m_manager): \"\"\"Test if the global preference", "@mock.patch.object(strategies.base, 'CONF') def test_global_preference(self, m_conf, m_manager): \"\"\"Test if the global", "m_conf, m_manager): \"\"\"Test if the global preference is used\"\"\" m_conf.watcher_datasources.datasources", "and # limitations under the License. from unittest import mock", "'osc', None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_global_preference(self, m_conf, m_manager):", "= strategies.DummyStrategy(config=mock.Mock()) class TestBaseStrategyDatasource(TestBaseStrategy): def setUp(self): super(TestBaseStrategyDatasource, self).setUp() self.strategy =", "License. from unittest import mock from watcher.common import exception from", "OR CONDITIONS OF ANY KIND, either express or # implied.", "for Nuclear Research (CERN) # # Licensed under the Apache", "the global preference is used with another order\"\"\" m_conf.watcher_datasources.datasources =", "from unittest import mock from watcher.common import exception from watcher.decision_engine.datasources", "TestBaseStrategyException(TestBaseStrategy): def setUp(self): super(TestBaseStrategyException, self).setUp() def test_exception_model(self): self.m_c_model.return_value = None", "def test_exception_model(self): self.m_c_model.return_value = None self.assertRaises( exception.ClusterStateNotDefined, self.strategy.execute) def test_exception_stale_cdm(self):", "config=datasources, osc=None) class TestBaseStrategyException(TestBaseStrategy): def setUp(self): super(TestBaseStrategyException, self).setUp() def test_exception_model(self):", "= \\ mock.NonCallableMock() # Access the property so that the", "= faker_cluster_state.FakerModelCollector() p_c_model = mock.patch.object( strategies.BaseStrategy, \"compute_model\", new_callable=mock.PropertyMock) self.m_c_model =", "Access the property so that the configuration is read in", "\\ mock.NonCallableMock() # Access the property so that the configuration", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "Unless required by applicable law or agreed to in writing,", "self.m_c_model = p_c_model.start() self.addCleanup(p_c_model.stop) p_audit_scope = mock.patch.object( strategies.BaseStrategy, \"audit_scope\", new_callable=mock.PropertyMock)", "so that the configuration is read in order to #", "# TODO(Dantali0n) This should return ClusterStale, # improve set_cluster_data_model_as_stale(). exception.ClusterStateNotDefined,", "the specific language governing permissions and # limitations under the", "'osc', None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_strategy_preference_override(self, m_conf, m_manager):", "'CONF') def test_strategy_preference_override(self, m_conf, m_manager): \"\"\"Test if the global preference", "applicable law or agreed to in writing, software # distributed", "2019 European Organization for Nuclear Research (CERN) # # Licensed", "base from watcher.tests.decision_engine.model import faker_cluster_state class TestBaseStrategy(base.TestCase): def setUp(self): super(TestBaseStrategy,", "TODO(Dantali0n) This should return ClusterStale, # improve set_cluster_data_model_as_stale(). exception.ClusterStateNotDefined, self.strategy.execute)", "def test_exception_stale_cdm(self): self.fake_c_cluster.set_cluster_data_model_as_stale() self.m_c_model.return_value = self.fake_c_cluster.cluster_data_model self.assertRaises( # TODO(Dantali0n) This", "Organization for Nuclear Research (CERN) # # Licensed under the", "in writing, software # distributed under the License is distributed", "m_manager.assert_called_once_with( config=m_conf.watcher_datasources, osc=None) @mock.patch.object(strategies.BaseStrategy, 'osc', None) @mock.patch.object(manager, 'DataSourceManager') @mock.patch.object(strategies.base, 'CONF')", "import model_root from watcher.decision_engine.strategy import strategies from watcher.tests import base", "\"audit_scope\", new_callable=mock.PropertyMock) self.m_audit_scope = p_audit_scope.start() self.addCleanup(p_audit_scope.stop) self.m_audit_scope.return_value = mock.Mock() self.m_c_model.return_value", "if the global preference is used with another order\"\"\" m_conf.watcher_datasources.datasources", "self.fake_c_cluster.cluster_data_model self.assertRaises( # TODO(Dantali0n) This should return ClusterStale, # improve", "mock.Mock() self.m_c_model.return_value = model_root.ModelRoot() self.strategy = strategies.DummyStrategy(config=mock.Mock()) class TestBaseStrategyDatasource(TestBaseStrategy): def", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "OF ANY KIND, either express or # implied. # See", "License, Version 2.0 (the \"License\"); # you may not use", "# You may obtain a copy of the License at", "self.addCleanup(p_audit_scope.stop) self.m_audit_scope.return_value = mock.Mock() self.m_c_model.return_value = model_root.ModelRoot() self.strategy = strategies.DummyStrategy(config=mock.Mock())", "preference is used with another order\"\"\" m_conf.watcher_datasources.datasources = \\ ['ceilometer',", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "either express or # implied. # See the License for", "def setUp(self): super(TestBaseStrategy, self).setUp() # fake cluster self.fake_c_cluster = faker_cluster_state.FakerModelCollector()", "self.addCleanup(p_c_model.stop) p_audit_scope = mock.patch.object( strategies.BaseStrategy, \"audit_scope\", new_callable=mock.PropertyMock) self.m_audit_scope = p_audit_scope.start()", "\"\"\"Test if the global preference is used with another order\"\"\"", "test_exception_stale_cdm(self): self.fake_c_cluster.set_cluster_data_model_as_stale() self.m_c_model.return_value = self.fake_c_cluster.cluster_data_model self.assertRaises( # TODO(Dantali0n) This should", "the License for the specific language governing permissions and #", "Apache License, Version 2.0 (the \"License\"); # you may not", "global preference is used with another order\"\"\" m_conf.watcher_datasources.datasources = \\", "m_manager.return_value.get_backend.return_value = \\ mock.NonCallableMock() # Access the property so that", "def test_global_preference(self, m_conf, m_manager): \"\"\"Test if the global preference is", "osc=None) class TestBaseStrategyException(TestBaseStrategy): def setUp(self): super(TestBaseStrategyException, self).setUp() def test_exception_model(self): self.m_c_model.return_value", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "that the configuration is read in order to # get", "m_conf, m_manager): \"\"\"Test if the global preference is used with", "= mock.Mock(datasources=['ceilometer']) self.strategy = strategies.DummyStrategy( config=datasources) m_conf.watcher_datasources.datasources = \\ ['ceilometer',", "class TestBaseStrategyException(TestBaseStrategy): def setUp(self): super(TestBaseStrategyException, self).setUp() def test_exception_model(self): self.m_c_model.return_value =", "= model_root.ModelRoot() self.strategy = strategies.DummyStrategy(config=mock.Mock()) class TestBaseStrategyDatasource(TestBaseStrategy): def setUp(self): super(TestBaseStrategyDatasource,", "-*- # Copyright (c) 2019 European Organization for Nuclear Research", "None self.assertRaises( exception.ClusterStateNotDefined, self.strategy.execute) def test_exception_stale_cdm(self): self.fake_c_cluster.set_cluster_data_model_as_stale() self.m_c_model.return_value = self.fake_c_cluster.cluster_data_model", "self.fake_c_cluster = faker_cluster_state.FakerModelCollector() p_c_model = mock.patch.object( strategies.BaseStrategy, \"compute_model\", new_callable=mock.PropertyMock) self.m_c_model", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "'DataSourceManager') @mock.patch.object(strategies.base, 'CONF') def test_global_preference(self, m_conf, m_manager): \"\"\"Test if the", "to # get the correct datasource self.strategy.datasource_backend m_manager.assert_called_once_with( config=datasources, osc=None)", "# Make sure we access the property and not the", "'monasca', 'gnocchi'] # Access the property so that the configuration", "setUp(self): super(TestBaseStrategy, self).setUp() # fake cluster self.fake_c_cluster = faker_cluster_state.FakerModelCollector() p_c_model", "# Access the property so that the configuration is read", "KIND, either express or # implied. # See the License", "\"License\"); # you may not use this file except in", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "we access the property and not the underlying function. m_manager.return_value.get_backend.return_value", "order to # get the correct datasource self.strategy.datasource_backend m_manager.assert_called_once_with( config=m_conf.watcher_datasources,", "new_callable=mock.PropertyMock) self.m_audit_scope = p_audit_scope.start() self.addCleanup(p_audit_scope.stop) self.m_audit_scope.return_value = mock.Mock() self.m_c_model.return_value =", "'gnocchi'] # Make sure we access the property and not", "# distributed under the License is distributed on an \"AS", "# Unless required by applicable law or agreed to in", "global preference is used\"\"\" m_conf.watcher_datasources.datasources = \\ ['gnocchi', 'monasca', 'ceilometer']", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "config=datasources) m_conf.watcher_datasources.datasources = \\ ['ceilometer', 'monasca', 'gnocchi'] # Access the", "You may obtain a copy of the License at #", "correct datasource self.strategy.datasource_backend m_manager.assert_called_once_with( config=m_conf.watcher_datasources, osc=None) @mock.patch.object(strategies.BaseStrategy, 'osc', None) @mock.patch.object(manager,", "can be overridden\"\"\" datasources = mock.Mock(datasources=['ceilometer']) self.strategy = strategies.DummyStrategy( config=datasources)", "self.assertRaises( # TODO(Dantali0n) This should return ClusterStale, # improve set_cluster_data_model_as_stale().", "model_root.ModelRoot() self.strategy = strategies.DummyStrategy(config=mock.Mock()) class TestBaseStrategyDatasource(TestBaseStrategy): def setUp(self): super(TestBaseStrategyDatasource, self).setUp()", "from watcher.decision_engine.strategy import strategies from watcher.tests import base from watcher.tests.decision_engine.model", "with another order\"\"\" m_conf.watcher_datasources.datasources = \\ ['ceilometer', 'monasca', 'gnocchi'] #", "-*- encoding: utf-8 -*- # Copyright (c) 2019 European Organization", "the Apache License, Version 2.0 (the \"License\"); # you may", "if the global preference is used\"\"\" m_conf.watcher_datasources.datasources = \\ ['gnocchi',", "is read in order to # get the correct datasource", "test_global_preference_reverse(self, m_conf, m_manager): \"\"\"Test if the global preference is used", "strategies.DummyStrategy( config=datasources) m_conf.watcher_datasources.datasources = \\ ['ceilometer', 'monasca', 'gnocchi'] # Access", "from watcher.common import exception from watcher.decision_engine.datasources import manager from watcher.decision_engine.model" ]
[ "|4 3| | | 5| 7 | ------------- | 7", "| 9| 3| | ------------- | | 9| | |", "Sudoku def main(): s = Sudoku.parse( ''' ------------- | |2", "|51 | 4|9 | | 9| 3| | ------------- |", "|2 | ------------- ''' ) print(s) print(s.solve()) if __name__ ==", "98| | 83|1 |2 | ------------- ''' ) print(s) print(s.solve())", "7 | 2|8 | |51 | 4|9 | | 9|", "| | 2| | 98| | 83|1 |2 | -------------", "<filename>main.py from sudoku import Sudoku def main(): s = Sudoku.parse(", "| | 6 |4 3| | | 5| 7 |", "3| | ------------- | | 9| | | 2| |", "2|8 | |51 | 4|9 | | 9| 3| |", "| | 9| 3| | ------------- | | 9| |", "7 | ------------- | 7 | 2|8 | |51 |", "4|9 | | 9| 3| | ------------- | | 9|", "| 6 |4 3| | | 5| 7 | -------------", "9| | | 2| | 98| | 83|1 |2 |", "def main(): s = Sudoku.parse( ''' ------------- | |2 |", "| ------------- ''' ) print(s) print(s.solve()) if __name__ == '__main__':", "| 98| | 83|1 |2 | ------------- ''' ) print(s)", "6 |4 3| | | 5| 7 | ------------- |", "| ------------- | | 9| | | 2| | 98|", "------------- ''' ) print(s) print(s.solve()) if __name__ == '__main__': main()", "------------- | |2 | | | | 6 |4 3|", "3| | | 5| 7 | ------------- | 7 |", "| 2|8 | |51 | 4|9 | | 9| 3|", "| | 5| 7 | ------------- | 7 | 2|8", "from sudoku import Sudoku def main(): s = Sudoku.parse( '''", "import Sudoku def main(): s = Sudoku.parse( ''' ------------- |", "| 7 | 2|8 | |51 | 4|9 | |", "| | 9| | | 2| | 98| | 83|1", "| 2| | 98| | 83|1 |2 | ------------- '''", "------------- | | 9| | | 2| | 98| |", "| |2 | | | | 6 |4 3| |", "| 4|9 | | 9| 3| | ------------- | |", "| 83|1 |2 | ------------- ''' ) print(s) print(s.solve()) if", "| | | 6 |4 3| | | 5| 7", "| 9| | | 2| | 98| | 83|1 |2", "|2 | | | | 6 |4 3| | |", "Sudoku.parse( ''' ------------- | |2 | | | | 6", "s = Sudoku.parse( ''' ------------- | |2 | | |", "| | | | 6 |4 3| | | 5|", "sudoku import Sudoku def main(): s = Sudoku.parse( ''' -------------", "| 5| 7 | ------------- | 7 | 2|8 |", "| ------------- | 7 | 2|8 | |51 | 4|9", "| |51 | 4|9 | | 9| 3| | -------------", "------------- | 7 | 2|8 | |51 | 4|9 |", "= Sudoku.parse( ''' ------------- | |2 | | | |", "5| 7 | ------------- | 7 | 2|8 | |51", "main(): s = Sudoku.parse( ''' ------------- | |2 | |", "83|1 |2 | ------------- ''' ) print(s) print(s.solve()) if __name__", "9| 3| | ------------- | | 9| | | 2|", "''' ------------- | |2 | | | | 6 |4", "2| | 98| | 83|1 |2 | ------------- ''' )" ]
[ "pd.Series(np.concatenate([np.ones((10000)), np.zeros((100000))])) y = y.sample(frac=1.0) _test_sample(y) def test_sample_with_ndarray(): y =", "np.concatenate([ 2*np.ones((10000)), 1*np.ones((10000)), 0*np.ones((10000)), ]) sampler = MajorityUnderSampler() idx =", "y = y.sample(frac=1.0) _test_sample(y) def test_sample_with_ndarray(): y = np.concatenate([np.ones((10000)), np.zeros((100000))])", "= np.concatenate([np.ones((10000)), np.zeros((100000))]) _test_sample(y) def test_sample_for_regression(): y = np.concatenate([ 2*np.ones((10000)),", "def _test_sample(y): sampler = MajorityUnderSampler() idx = sampler.sample(y, 40000, 3.0)", "_test_sample(y) def test_sample_with_ndarray(): y = np.concatenate([np.ones((10000)), np.zeros((100000))]) _test_sample(y) def test_sample_for_regression():", "y = np.concatenate([np.ones((10000)), np.zeros((100000))]) _test_sample(y) def test_sample_for_regression(): y = np.concatenate([", "idx = sampler.sample(y, 40000, 3.0) assert len(idx) == 40000 assert", "def test_sample_with_series(): y = pd.Series(np.concatenate([np.ones((10000)), np.zeros((100000))])) y = y.sample(frac=1.0) _test_sample(y)", "import pandas as pd from autogbt.sampler import MajorityUnderSampler def _test_sample(y):", "def test_sample_with_ndarray(): y = np.concatenate([np.ones((10000)), np.zeros((100000))]) _test_sample(y) def test_sample_for_regression(): y", "= np.concatenate([ 2*np.ones((10000)), 1*np.ones((10000)), 0*np.ones((10000)), ]) sampler = MajorityUnderSampler() idx", "as np import pandas as pd from autogbt.sampler import MajorityUnderSampler", "sampler.sample(y, 40000, 3.0) assert len(idx) == 40000 assert y[idx].sum() ==", "np.zeros((100000))]) _test_sample(y) def test_sample_for_regression(): y = np.concatenate([ 2*np.ones((10000)), 1*np.ones((10000)), 0*np.ones((10000)),", "y = np.concatenate([ 2*np.ones((10000)), 1*np.ones((10000)), 0*np.ones((10000)), ]) sampler = MajorityUnderSampler()", "y = pd.Series(np.concatenate([np.ones((10000)), np.zeros((100000))])) y = y.sample(frac=1.0) _test_sample(y) def test_sample_with_ndarray():", "0*np.ones((10000)), ]) sampler = MajorityUnderSampler() idx = sampler.sample(y, 0.1, 3.0)", "40000, 3.0) assert len(idx) == 40000 assert y[idx].sum() == 10000", "MajorityUnderSampler() idx = sampler.sample(y, 0.1, 3.0) assert len(idx) == 3000", "<filename>test/test_sampler.py<gh_stars>10-100 import numpy as np import pandas as pd from", "== 10000 def test_sample_with_series(): y = pd.Series(np.concatenate([np.ones((10000)), np.zeros((100000))])) y =", "test_sample_with_ndarray(): y = np.concatenate([np.ones((10000)), np.zeros((100000))]) _test_sample(y) def test_sample_for_regression(): y =", "_test_sample(y) def test_sample_for_regression(): y = np.concatenate([ 2*np.ones((10000)), 1*np.ones((10000)), 0*np.ones((10000)), ])", "test_sample_with_series(): y = pd.Series(np.concatenate([np.ones((10000)), np.zeros((100000))])) y = y.sample(frac=1.0) _test_sample(y) def", "as pd from autogbt.sampler import MajorityUnderSampler def _test_sample(y): sampler =", "= sampler.sample(y, 40000, 3.0) assert len(idx) == 40000 assert y[idx].sum()", "np import pandas as pd from autogbt.sampler import MajorityUnderSampler def", "y.sample(frac=1.0) _test_sample(y) def test_sample_with_ndarray(): y = np.concatenate([np.ones((10000)), np.zeros((100000))]) _test_sample(y) def", "def test_sample_for_regression(): y = np.concatenate([ 2*np.ones((10000)), 1*np.ones((10000)), 0*np.ones((10000)), ]) sampler", "sampler = MajorityUnderSampler() idx = sampler.sample(y, 0.1, 3.0) assert len(idx)", "from autogbt.sampler import MajorityUnderSampler def _test_sample(y): sampler = MajorityUnderSampler() idx", "import numpy as np import pandas as pd from autogbt.sampler", "pd from autogbt.sampler import MajorityUnderSampler def _test_sample(y): sampler = MajorityUnderSampler()", "sampler = MajorityUnderSampler() idx = sampler.sample(y, 40000, 3.0) assert len(idx)", "import MajorityUnderSampler def _test_sample(y): sampler = MajorityUnderSampler() idx = sampler.sample(y,", "10000 def test_sample_with_series(): y = pd.Series(np.concatenate([np.ones((10000)), np.zeros((100000))])) y = y.sample(frac=1.0)", "]) sampler = MajorityUnderSampler() idx = sampler.sample(y, 0.1, 3.0) assert", "MajorityUnderSampler() idx = sampler.sample(y, 40000, 3.0) assert len(idx) == 40000", "autogbt.sampler import MajorityUnderSampler def _test_sample(y): sampler = MajorityUnderSampler() idx =", "MajorityUnderSampler def _test_sample(y): sampler = MajorityUnderSampler() idx = sampler.sample(y, 40000,", "= MajorityUnderSampler() idx = sampler.sample(y, 0.1, 3.0) assert len(idx) ==", "test_sample_for_regression(): y = np.concatenate([ 2*np.ones((10000)), 1*np.ones((10000)), 0*np.ones((10000)), ]) sampler =", "np.concatenate([np.ones((10000)), np.zeros((100000))]) _test_sample(y) def test_sample_for_regression(): y = np.concatenate([ 2*np.ones((10000)), 1*np.ones((10000)),", "3.0) assert len(idx) == 40000 assert y[idx].sum() == 10000 def", "numpy as np import pandas as pd from autogbt.sampler import", "1*np.ones((10000)), 0*np.ones((10000)), ]) sampler = MajorityUnderSampler() idx = sampler.sample(y, 0.1,", "len(idx) == 40000 assert y[idx].sum() == 10000 def test_sample_with_series(): y", "= pd.Series(np.concatenate([np.ones((10000)), np.zeros((100000))])) y = y.sample(frac=1.0) _test_sample(y) def test_sample_with_ndarray(): y", "2*np.ones((10000)), 1*np.ones((10000)), 0*np.ones((10000)), ]) sampler = MajorityUnderSampler() idx = sampler.sample(y,", "= MajorityUnderSampler() idx = sampler.sample(y, 40000, 3.0) assert len(idx) ==", "_test_sample(y): sampler = MajorityUnderSampler() idx = sampler.sample(y, 40000, 3.0) assert", "np.zeros((100000))])) y = y.sample(frac=1.0) _test_sample(y) def test_sample_with_ndarray(): y = np.concatenate([np.ones((10000)),", "y[idx].sum() == 10000 def test_sample_with_series(): y = pd.Series(np.concatenate([np.ones((10000)), np.zeros((100000))])) y", "== 40000 assert y[idx].sum() == 10000 def test_sample_with_series(): y =", "= y.sample(frac=1.0) _test_sample(y) def test_sample_with_ndarray(): y = np.concatenate([np.ones((10000)), np.zeros((100000))]) _test_sample(y)", "pandas as pd from autogbt.sampler import MajorityUnderSampler def _test_sample(y): sampler", "assert len(idx) == 40000 assert y[idx].sum() == 10000 def test_sample_with_series():", "assert y[idx].sum() == 10000 def test_sample_with_series(): y = pd.Series(np.concatenate([np.ones((10000)), np.zeros((100000))]))", "40000 assert y[idx].sum() == 10000 def test_sample_with_series(): y = pd.Series(np.concatenate([np.ones((10000))," ]
[ "= [2, 4, 8, 14, 16, 18, 20, 22, 24,", "if rank_result[i] == test_label[i]: num_hits += 1 acc_list.append(float(num_hits)/float(test_length)) #Bloom Wisard", "sys from timeit import default_timer as timer sys.path.append(\"../../\") from core", "data in train_data: train_bin.append(np.array([], dtype=bool)) t = 0 for v", "== test_label[i]: num_hits += 1 acc_list.append(float(num_hits)/float(test_length)) #Bloom Wisard btuple_list =", "0 for data in test_data: test_bin.append(np.array([], dtype=bool)) t = 0", "20, 22, 24, 26, 28, 30, 32, 40, 56] bacc_list", "train_bin.append(np.array([], dtype=bool)) t = 0 for v in data: binarr", "in data: binarr = ths[t].binarize(v) test_bin[i] = np.append(test_bin[i], binarr) t", "1 acc_list.append(float(num_hits)/float(test_length)) #Bloom Wisard btuple_list = [2, 4, 8, 14,", "4, 8, 14, 16, 18, 20, 22, 24, 26, 28,", "16, 18, 20, 22, 24, 26, 28, 30] acc_list =", "from encoding import thermometer from encoding import util #Load Diabetes", "bits_encoding)) train_bin = [] test_bin = [] i = 0", "wnn.BloomWisard(entry_size, t, num_classes, capacity) bwisard.train(train_bin, train_label) rank_result = bwisard.rank(test_bin) num_hits", "range(len(data_max)): ths.append(thermometer.Thermometer(data_min[i], data_max[i], bits_encoding)) train_bin = [] test_bin = []", "#Load Diabetes data base_path = \"../../dataset/diabetes/\" #2/3 Test bits_encoding =", "test_bin.append(np.array([], dtype=bool)) t = 0 for v in data: binarr", "acc_list.append(float(num_hits)/float(test_length)) #Bloom Wisard btuple_list = [2, 4, 8, 14, 16,", "i = 0 for data in train_data: train_bin.append(np.array([], dtype=bool)) t", "+= 1 i = 0 for data in test_data: test_bin.append(np.array([],", "wnn from encoding import thermometer from encoding import util #Load", "in range(test_length): if rank_result[i] == test_label[i]: num_hits += 1 acc_list.append(float(num_hits)/float(test_length))", "tuple_list = [2, 4, 8, 14, 16, 18, 20, 22,", "import numpy as np import sys from timeit import default_timer", "1 i += 1 i = 0 for data in", "in range(len(data_max)): ths.append(thermometer.Thermometer(data_min[i], data_max[i], bits_encoding)) train_bin = [] test_bin =", "encoding import util #Load Diabetes data base_path = \"../../dataset/diabetes/\" #2/3", "+= 1 #print test_label #Wisard num_classes = 2 tuple_list =", "as timer sys.path.append(\"../../\") from core import wnn from encoding import", "32, 40, 56] bacc_list = [] #capacity = len(train_bin) capacity", "import util #Load Diabetes data base_path = \"../../dataset/diabetes/\" #2/3 Test", "1 #print test_label #Wisard num_classes = 2 tuple_list = [2,", "= 20 train_data, train_label, test_data, test_label, data_min, data_max = util.load_3data(base_path)", "[2, 4, 8, 14, 16, 18, 20, 22, 24, 26,", "= ths[t].binarize(v) train_bin[i] = np.append(train_bin[i], binarr) t += 1 i", "t in tuple_list: wisard = wnn.Wisard(entry_size, t, num_classes) wisard.train(train_bin, train_label)", "in range(test_length): if rank_result[i] == test_label[i]: num_hits += 1 bacc_list.append(float(num_hits)/float(test_length))", "data in test_data: test_bin.append(np.array([], dtype=bool)) t = 0 for v", "#print entry_size for t in tuple_list: wisard = wnn.Wisard(entry_size, t,", "entry_size for t in tuple_list: wisard = wnn.Wisard(entry_size, t, num_classes)", "bwisard.train(train_bin, train_label) rank_result = bwisard.rank(test_bin) num_hits = 0 for i", "num_hits += 1 acc_list.append(float(num_hits)/float(test_length)) #Bloom Wisard btuple_list = [2, 4,", "i += 1 #print test_label #Wisard num_classes = 2 tuple_list", "num_hits = 0 for i in range(test_length): if rank_result[i] ==", "i in range(test_length): if rank_result[i] == test_label[i]: num_hits += 1", "= ths[t].binarize(v) test_bin[i] = np.append(test_bin[i], binarr) t += 1 i", "i += 1 i = 0 for data in test_data:", "for v in data: binarr = ths[t].binarize(v) train_bin[i] = np.append(train_bin[i],", "t, num_classes, capacity) bwisard.train(train_bin, train_label) rank_result = bwisard.rank(test_bin) num_hits =", "data_max = util.load_3data(base_path) ths = [] for i in range(len(data_max)):", "= \"../../dataset/diabetes/\" #2/3 Test bits_encoding = 20 train_data, train_label, test_data,", "for v in data: binarr = ths[t].binarize(v) test_bin[i] = np.append(test_bin[i],", "+= 1 i += 1 #print test_label #Wisard num_classes =", "t += 1 i += 1 #print test_label #Wisard num_classes", "16, 18, 20, 22, 24, 26, 28, 30, 32, 40,", "14, 16, 18, 20, 22, 24, 26, 28, 30] acc_list", "test_bin[i] = np.append(test_bin[i], binarr) t += 1 i += 1", "np import sys from timeit import default_timer as timer sys.path.append(\"../../\")", "i in range(len(data_max)): ths.append(thermometer.Thermometer(data_min[i], data_max[i], bits_encoding)) train_bin = [] test_bin", "#capacity = len(train_bin) capacity = 10 print capacity for t", "= np.append(test_bin[i], binarr) t += 1 i += 1 #print", "btuple_list = [2, 4, 8, 14, 16, 18, 20, 22,", "train_label) rank_result = wisard.rank(test_bin) num_hits = 0 for i in", "range(test_length): if rank_result[i] == test_label[i]: num_hits += 1 bacc_list.append(float(num_hits)/float(test_length)) print", "default_timer as timer sys.path.append(\"../../\") from core import wnn from encoding", "test_length = len(test_label) entry_size = len(train_bin[0]) #print entry_size for t", "= 0 for data in train_data: train_bin.append(np.array([], dtype=bool)) t =", "18, 20, 22, 24, 26, 28, 30, 32, 40, 56]", "0 for v in data: binarr = ths[t].binarize(v) test_bin[i] =", "rank_result[i] == test_label[i]: num_hits += 1 bacc_list.append(float(num_hits)/float(test_length)) print \"Tuples=\", tuple_list", "14, 16, 18, 20, 22, 24, 26, 28, 30, 32,", "print \"Tuples=\", tuple_list print \"Wisard Accuracy=\", acc_list print \"Tuples=\", btuple_list", "data_max[i], bits_encoding)) train_bin = [] test_bin = [] i =", "= np.append(train_bin[i], binarr) t += 1 i += 1 i", "timer sys.path.append(\"../../\") from core import wnn from encoding import thermometer", "train_data: train_bin.append(np.array([], dtype=bool)) t = 0 for v in data:", "v in data: binarr = ths[t].binarize(v) test_bin[i] = np.append(test_bin[i], binarr)", "= len(train_bin) capacity = 10 print capacity for t in", "= bwisard.rank(test_bin) num_hits = 0 for i in range(test_length): if", "bacc_list = [] #capacity = len(train_bin) capacity = 10 print", "tuple_list: wisard = wnn.Wisard(entry_size, t, num_classes) wisard.train(train_bin, train_label) rank_result =", "bwisard = wnn.BloomWisard(entry_size, t, num_classes, capacity) bwisard.train(train_bin, train_label) rank_result =", "import wnn from encoding import thermometer from encoding import util", "1 bacc_list.append(float(num_hits)/float(test_length)) print \"Tuples=\", tuple_list print \"Wisard Accuracy=\", acc_list print", "= [] test_bin = [] i = 0 for data", "[] test_length = len(test_label) entry_size = len(train_bin[0]) #print entry_size for", "range(test_length): if rank_result[i] == test_label[i]: num_hits += 1 acc_list.append(float(num_hits)/float(test_length)) #Bloom", "#Bloom Wisard btuple_list = [2, 4, 8, 14, 16, 18,", "Diabetes data base_path = \"../../dataset/diabetes/\" #2/3 Test bits_encoding = 20", "Test bits_encoding = 20 train_data, train_label, test_data, test_label, data_min, data_max", "t += 1 i += 1 i = 0 for", "wisard.rank(test_bin) num_hits = 0 for i in range(test_length): if rank_result[i]", "acc_list = [] test_length = len(test_label) entry_size = len(train_bin[0]) #print", "= [] i = 0 for data in train_data: train_bin.append(np.array([],", "= 2 tuple_list = [2, 4, 8, 14, 16, 18,", "[] for i in range(len(data_max)): ths.append(thermometer.Thermometer(data_min[i], data_max[i], bits_encoding)) train_bin =", "num_classes = 2 tuple_list = [2, 4, 8, 14, 16,", "num_classes) wisard.train(train_bin, train_label) rank_result = wisard.rank(test_bin) num_hits = 0 for", "test_label[i]: num_hits += 1 bacc_list.append(float(num_hits)/float(test_length)) print \"Tuples=\", tuple_list print \"Wisard", "= 0 for i in range(test_length): if rank_result[i] == test_label[i]:", "in btuple_list: bwisard = wnn.BloomWisard(entry_size, t, num_classes, capacity) bwisard.train(train_bin, train_label)", "18, 20, 22, 24, 26, 28, 30] acc_list = []", "2 tuple_list = [2, 4, 8, 14, 16, 18, 20,", "= 0 for v in data: binarr = ths[t].binarize(v) train_bin[i]", "wisard = wnn.Wisard(entry_size, t, num_classes) wisard.train(train_bin, train_label) rank_result = wisard.rank(test_bin)", "len(test_label) entry_size = len(train_bin[0]) #print entry_size for t in tuple_list:", "data base_path = \"../../dataset/diabetes/\" #2/3 Test bits_encoding = 20 train_data,", "train_data, train_label, test_data, test_label, data_min, data_max = util.load_3data(base_path) ths =", "ths = [] for i in range(len(data_max)): ths.append(thermometer.Thermometer(data_min[i], data_max[i], bits_encoding))", "22, 24, 26, 28, 30, 32, 40, 56] bacc_list =", "util #Load Diabetes data base_path = \"../../dataset/diabetes/\" #2/3 Test bits_encoding", "ths[t].binarize(v) train_bin[i] = np.append(train_bin[i], binarr) t += 1 i +=", "t = 0 for v in data: binarr = ths[t].binarize(v)", "#print test_label #Wisard num_classes = 2 tuple_list = [2, 4,", "encoding import thermometer from encoding import util #Load Diabetes data", "24, 26, 28, 30, 32, 40, 56] bacc_list = []", "= 0 for v in data: binarr = ths[t].binarize(v) test_bin[i]", "rank_result[i] == test_label[i]: num_hits += 1 acc_list.append(float(num_hits)/float(test_length)) #Bloom Wisard btuple_list", "rank_result = bwisard.rank(test_bin) num_hits = 0 for i in range(test_length):", "timeit import default_timer as timer sys.path.append(\"../../\") from core import wnn", "Wisard btuple_list = [2, 4, 8, 14, 16, 18, 20,", "30, 32, 40, 56] bacc_list = [] #capacity = len(train_bin)", "bwisard.rank(test_bin) num_hits = 0 for i in range(test_length): if rank_result[i]", "+= 1 acc_list.append(float(num_hits)/float(test_length)) #Bloom Wisard btuple_list = [2, 4, 8,", "[] i = 0 for data in train_data: train_bin.append(np.array([], dtype=bool))", "btuple_list: bwisard = wnn.BloomWisard(entry_size, t, num_classes, capacity) bwisard.train(train_bin, train_label) rank_result", "import default_timer as timer sys.path.append(\"../../\") from core import wnn from", "= len(train_bin[0]) #print entry_size for t in tuple_list: wisard =", "0 for i in range(test_length): if rank_result[i] == test_label[i]: num_hits", "tuple_list print \"Wisard Accuracy=\", acc_list print \"Tuples=\", btuple_list print \"BloomWisard", "= util.load_3data(base_path) ths = [] for i in range(len(data_max)): ths.append(thermometer.Thermometer(data_min[i],", "util.load_3data(base_path) ths = [] for i in range(len(data_max)): ths.append(thermometer.Thermometer(data_min[i], data_max[i],", "28, 30] acc_list = [] test_length = len(test_label) entry_size =", "[] #capacity = len(train_bin) capacity = 10 print capacity for", "import thermometer from encoding import util #Load Diabetes data base_path", "for i in range(len(data_max)): ths.append(thermometer.Thermometer(data_min[i], data_max[i], bits_encoding)) train_bin = []", "data: binarr = ths[t].binarize(v) test_bin[i] = np.append(test_bin[i], binarr) t +=", "ths[t].binarize(v) test_bin[i] = np.append(test_bin[i], binarr) t += 1 i +=", "+= 1 bacc_list.append(float(num_hits)/float(test_length)) print \"Tuples=\", tuple_list print \"Wisard Accuracy=\", acc_list", "26, 28, 30] acc_list = [] test_length = len(test_label) entry_size", "= wnn.BloomWisard(entry_size, t, num_classes, capacity) bwisard.train(train_bin, train_label) rank_result = bwisard.rank(test_bin)", "test_data: test_bin.append(np.array([], dtype=bool)) t = 0 for v in data:", "== test_label[i]: num_hits += 1 bacc_list.append(float(num_hits)/float(test_length)) print \"Tuples=\", tuple_list print", "56] bacc_list = [] #capacity = len(train_bin) capacity = 10", "bits_encoding = 20 train_data, train_label, test_data, test_label, data_min, data_max =", "np.append(train_bin[i], binarr) t += 1 i += 1 i =", "test_bin = [] i = 0 for data in train_data:", "= len(test_label) entry_size = len(train_bin[0]) #print entry_size for t in", "print \"Wisard Accuracy=\", acc_list print \"Tuples=\", btuple_list print \"BloomWisard Accuracy=\",bacc_list", "1 i += 1 #print test_label #Wisard num_classes = 2", "26, 28, 30, 32, 40, 56] bacc_list = [] #capacity", "= 10 print capacity for t in btuple_list: bwisard =", "= [] for i in range(len(data_max)): ths.append(thermometer.Thermometer(data_min[i], data_max[i], bits_encoding)) train_bin", "base_path = \"../../dataset/diabetes/\" #2/3 Test bits_encoding = 20 train_data, train_label,", "for data in train_data: train_bin.append(np.array([], dtype=bool)) t = 0 for", "= 0 for data in test_data: test_bin.append(np.array([], dtype=bool)) t =", "8, 14, 16, 18, 20, 22, 24, 26, 28, 30]", "binarr) t += 1 i += 1 #print test_label #Wisard", "for t in btuple_list: bwisard = wnn.BloomWisard(entry_size, t, num_classes, capacity)", "= [] #capacity = len(train_bin) capacity = 10 print capacity", "t in btuple_list: bwisard = wnn.BloomWisard(entry_size, t, num_classes, capacity) bwisard.train(train_bin,", "i = 0 for data in test_data: test_bin.append(np.array([], dtype=bool)) t", "np.append(test_bin[i], binarr) t += 1 i += 1 #print test_label", "data: binarr = ths[t].binarize(v) train_bin[i] = np.append(train_bin[i], binarr) t +=", "num_hits += 1 bacc_list.append(float(num_hits)/float(test_length)) print \"Tuples=\", tuple_list print \"Wisard Accuracy=\",", "train_bin[i] = np.append(train_bin[i], binarr) t += 1 i += 1", "train_bin = [] test_bin = [] i = 0 for", "capacity) bwisard.train(train_bin, train_label) rank_result = bwisard.rank(test_bin) num_hits = 0 for", "from core import wnn from encoding import thermometer from encoding", "t, num_classes) wisard.train(train_bin, train_label) rank_result = wisard.rank(test_bin) num_hits = 0", "test_label[i]: num_hits += 1 acc_list.append(float(num_hits)/float(test_length)) #Bloom Wisard btuple_list = [2,", "from timeit import default_timer as timer sys.path.append(\"../../\") from core import", "ths.append(thermometer.Thermometer(data_min[i], data_max[i], bits_encoding)) train_bin = [] test_bin = [] i", "binarr = ths[t].binarize(v) train_bin[i] = np.append(train_bin[i], binarr) t += 1", "train_label, test_data, test_label, data_min, data_max = util.load_3data(base_path) ths = []", "22, 24, 26, 28, 30] acc_list = [] test_length =", "num_classes, capacity) bwisard.train(train_bin, train_label) rank_result = bwisard.rank(test_bin) num_hits = 0", "+= 1 i += 1 i = 0 for data", "import sys from timeit import default_timer as timer sys.path.append(\"../../\") from", "= wisard.rank(test_bin) num_hits = 0 for i in range(test_length): if", "\"Tuples=\", tuple_list print \"Wisard Accuracy=\", acc_list print \"Tuples=\", btuple_list print", "in tuple_list: wisard = wnn.Wisard(entry_size, t, num_classes) wisard.train(train_bin, train_label) rank_result", "capacity = 10 print capacity for t in btuple_list: bwisard", "test_data, test_label, data_min, data_max = util.load_3data(base_path) ths = [] for", "len(train_bin[0]) #print entry_size for t in tuple_list: wisard = wnn.Wisard(entry_size,", "test_label, data_min, data_max = util.load_3data(base_path) ths = [] for i", "1 i = 0 for data in test_data: test_bin.append(np.array([], dtype=bool))", "thermometer from encoding import util #Load Diabetes data base_path =", "wisard.train(train_bin, train_label) rank_result = wisard.rank(test_bin) num_hits = 0 for i", "#2/3 Test bits_encoding = 20 train_data, train_label, test_data, test_label, data_min,", "dtype=bool)) t = 0 for v in data: binarr =", "8, 14, 16, 18, 20, 22, 24, 26, 28, 30,", "0 for v in data: binarr = ths[t].binarize(v) train_bin[i] =", "= wnn.Wisard(entry_size, t, num_classes) wisard.train(train_bin, train_label) rank_result = wisard.rank(test_bin) num_hits", "if rank_result[i] == test_label[i]: num_hits += 1 bacc_list.append(float(num_hits)/float(test_length)) print \"Tuples=\",", "sys.path.append(\"../../\") from core import wnn from encoding import thermometer from", "for i in range(test_length): if rank_result[i] == test_label[i]: num_hits +=", "in test_data: test_bin.append(np.array([], dtype=bool)) t = 0 for v in", "40, 56] bacc_list = [] #capacity = len(train_bin) capacity =", "numpy as np import sys from timeit import default_timer as", "data_min, data_max = util.load_3data(base_path) ths = [] for i in", "in data: binarr = ths[t].binarize(v) train_bin[i] = np.append(train_bin[i], binarr) t", "for data in test_data: test_bin.append(np.array([], dtype=bool)) t = 0 for", "30] acc_list = [] test_length = len(test_label) entry_size = len(train_bin[0])", "28, 30, 32, 40, 56] bacc_list = [] #capacity =", "len(train_bin) capacity = 10 print capacity for t in btuple_list:", "in train_data: train_bin.append(np.array([], dtype=bool)) t = 0 for v in", "from encoding import util #Load Diabetes data base_path = \"../../dataset/diabetes/\"", "binarr) t += 1 i += 1 i = 0", "24, 26, 28, 30] acc_list = [] test_length = len(test_label)", "print capacity for t in btuple_list: bwisard = wnn.BloomWisard(entry_size, t,", "10 print capacity for t in btuple_list: bwisard = wnn.BloomWisard(entry_size,", "core import wnn from encoding import thermometer from encoding import", "0 for data in train_data: train_bin.append(np.array([], dtype=bool)) t = 0", "rank_result = wisard.rank(test_bin) num_hits = 0 for i in range(test_length):", "#Wisard num_classes = 2 tuple_list = [2, 4, 8, 14,", "for t in tuple_list: wisard = wnn.Wisard(entry_size, t, num_classes) wisard.train(train_bin,", "as np import sys from timeit import default_timer as timer", "20, 22, 24, 26, 28, 30] acc_list = [] test_length", "\"../../dataset/diabetes/\" #2/3 Test bits_encoding = 20 train_data, train_label, test_data, test_label,", "capacity for t in btuple_list: bwisard = wnn.BloomWisard(entry_size, t, num_classes,", "wnn.Wisard(entry_size, t, num_classes) wisard.train(train_bin, train_label) rank_result = wisard.rank(test_bin) num_hits =", "train_label) rank_result = bwisard.rank(test_bin) num_hits = 0 for i in", "bacc_list.append(float(num_hits)/float(test_length)) print \"Tuples=\", tuple_list print \"Wisard Accuracy=\", acc_list print \"Tuples=\",", "binarr = ths[t].binarize(v) test_bin[i] = np.append(test_bin[i], binarr) t += 1", "test_label #Wisard num_classes = 2 tuple_list = [2, 4, 8,", "v in data: binarr = ths[t].binarize(v) train_bin[i] = np.append(train_bin[i], binarr)", "20 train_data, train_label, test_data, test_label, data_min, data_max = util.load_3data(base_path) ths", "entry_size = len(train_bin[0]) #print entry_size for t in tuple_list: wisard", "= [] test_length = len(test_label) entry_size = len(train_bin[0]) #print entry_size", "[] test_bin = [] i = 0 for data in" ]
[ "keyUp(self, key): pass def mouseUp(self, button, pos): pass def mouseMotion(self,", "pass def keyUp(self, key): pass def mouseUp(self, button, pos): pass", "random import uniform import numpy as np class Starter(PygameHelper): def", "self.w, self.h = 800, 600 PygameHelper.__init__(self, size=(self.w, self.h), fill=((0,0,0))) def", "uniform import numpy as np class Starter(PygameHelper): def __init__(self): self.w,", "def mouseMotion(self, buttons, pos, rel): pass def draw(self): self.screen.fill((np.random.random()*255, np.random.random()*255,", "def __init__(self): self.w, self.h = 800, 600 PygameHelper.__init__(self, size=(self.w, self.h),", "from pygame.locals import * from vec2d import * from random", "as np class Starter(PygameHelper): def __init__(self): self.w, self.h = 800,", "import * from random import uniform import numpy as np", "600 PygameHelper.__init__(self, size=(self.w, self.h), fill=((0,0,0))) def update(self): pass def keyUp(self,", "class Starter(PygameHelper): def __init__(self): self.w, self.h = 800, 600 PygameHelper.__init__(self,", "* from random import uniform import numpy as np class", "* from pygame import * from pygame.locals import * from", "mouseMotion(self, buttons, pos, rel): pass def draw(self): self.screen.fill((np.random.random()*255, np.random.random()*255, np.random.random()*255))", "import uniform import numpy as np class Starter(PygameHelper): def __init__(self):", "pygame import * from pygame.locals import * from vec2d import", "* from vec2d import * from random import uniform import", "= 800, 600 PygameHelper.__init__(self, size=(self.w, self.h), fill=((0,0,0))) def update(self): pass", "pos, rel): pass def draw(self): self.screen.fill((np.random.random()*255, np.random.random()*255, np.random.random()*255)) s =", "self.h = 800, 600 PygameHelper.__init__(self, size=(self.w, self.h), fill=((0,0,0))) def update(self):", "def mouseUp(self, button, pos): pass def mouseMotion(self, buttons, pos, rel):", "from vec2d import * from random import uniform import numpy", "import * from vec2d import * from random import uniform", "pygame.locals import * from vec2d import * from random import", "np class Starter(PygameHelper): def __init__(self): self.w, self.h = 800, 600", "__init__(self): self.w, self.h = 800, 600 PygameHelper.__init__(self, size=(self.w, self.h), fill=((0,0,0)))", "vec2d import * from random import uniform import numpy as", "import numpy as np class Starter(PygameHelper): def __init__(self): self.w, self.h", "numpy as np class Starter(PygameHelper): def __init__(self): self.w, self.h =", "PygameHelper.__init__(self, size=(self.w, self.h), fill=((0,0,0))) def update(self): pass def keyUp(self, key):", "button, pos): pass def mouseMotion(self, buttons, pos, rel): pass def", "pos): pass def mouseMotion(self, buttons, pos, rel): pass def draw(self):", "from pygame import * from pygame.locals import * from vec2d", "from pygamehelper import * from pygame import * from pygame.locals", "pygamehelper import * from pygame import * from pygame.locals import", "import * from pygame.locals import * from vec2d import *", "import * from pygame import * from pygame.locals import *", "* from pygame.locals import * from vec2d import * from", "800, 600 PygameHelper.__init__(self, size=(self.w, self.h), fill=((0,0,0))) def update(self): pass def", "update(self): pass def keyUp(self, key): pass def mouseUp(self, button, pos):", "pass def mouseMotion(self, buttons, pos, rel): pass def draw(self): self.screen.fill((np.random.random()*255,", "def keyUp(self, key): pass def mouseUp(self, button, pos): pass def", "pass def mouseUp(self, button, pos): pass def mouseMotion(self, buttons, pos,", "self.h), fill=((0,0,0))) def update(self): pass def keyUp(self, key): pass def", "from random import uniform import numpy as np class Starter(PygameHelper):", "<reponame>hoppfull/Legacy-Python from pygamehelper import * from pygame import * from", "mouseUp(self, button, pos): pass def mouseMotion(self, buttons, pos, rel): pass", "Starter(PygameHelper): def __init__(self): self.w, self.h = 800, 600 PygameHelper.__init__(self, size=(self.w,", "size=(self.w, self.h), fill=((0,0,0))) def update(self): pass def keyUp(self, key): pass", "buttons, pos, rel): pass def draw(self): self.screen.fill((np.random.random()*255, np.random.random()*255, np.random.random()*255)) s", "rel): pass def draw(self): self.screen.fill((np.random.random()*255, np.random.random()*255, np.random.random()*255)) s = Starter()", "def update(self): pass def keyUp(self, key): pass def mouseUp(self, button,", "pass def draw(self): self.screen.fill((np.random.random()*255, np.random.random()*255, np.random.random()*255)) s = Starter() s.mainLoop(40)", "fill=((0,0,0))) def update(self): pass def keyUp(self, key): pass def mouseUp(self,", "key): pass def mouseUp(self, button, pos): pass def mouseMotion(self, buttons," ]
[ "in all_inst: inst.start() for inst in all_inst: inst.join() def main():", "-h, --help : Help\") sys.exit(1) def load_streams(): all_inst = []", "a stream to record\") print() print(\"Usage: %s [Options]\" % (os.path.basename(sys.argv[0])))", "print(\"Options :\") print(\" -d, --dir : Output directory\") print(\" -h,", "--dir : Output directory\") print(\" -h, --help : Help\") sys.exit(1)", "import sys import utils from recorder import StreamRec OUTDIR =", ":\") print(\" -d, --dir : Output directory\") print(\" -h, --help", "a[i] in [\"-d\", \"--dir\"]: OUTDIR = a[i + 1] i", "Twitch streams!\") print(\"Check an example of .stream file in data/", "usage() if a[i] in [\"-d\", \"--dir\"]: OUTDIR = a[i +", "sys.exit(1) def load_streams(): all_inst = [] stream_files = glob.glob('data/**/*.stream', recursive=True)", "OUTDIR = \"\" def parse_args(a): global OUTDIR i = 1", "to add a stream to record\") print() print(\"Usage: %s [Options]\"", "favorite Twitch streams!\") print(\"Check an example of .stream file in", "stream_file in stream_files: inst = StreamRec(stream_file, OUTDIR) all_inst.append(inst) for inst", "OUTDIR = a[i + 1] i += 1 i +=", "import utils from recorder import StreamRec OUTDIR = \"\" def", "print(\"Record your favorite Twitch streams!\") print(\"Check an example of .stream", "OUTDIR i = 1 while i < len(a): if a[i]", "in [\"-d\", \"--dir\"]: OUTDIR = a[i + 1] i +=", "for stream_file in stream_files: inst = StreamRec(stream_file, OUTDIR) all_inst.append(inst) for", "all_inst = [] stream_files = glob.glob('data/**/*.stream', recursive=True) for stream_file in", "1 def usage(): print(\"Record your favorite Twitch streams!\") print(\"Check an", "print(\"Usage: %s [Options]\" % (os.path.basename(sys.argv[0]))) print() print(\"Options :\") print(\" -d,", "parse_args(a): global OUTDIR i = 1 while i < len(a):", "all_inst: inst.start() for inst in all_inst: inst.join() def main(): utils.welcome()", "os import sys import utils from recorder import StreamRec OUTDIR", "print() print(\"Usage: %s [Options]\" % (os.path.basename(sys.argv[0]))) print() print(\"Options :\") print(\"", "-d, --dir : Output directory\") print(\" -h, --help : Help\")", "to see how to add a stream to record\") print()", "%s [Options]\" % (os.path.basename(sys.argv[0]))) print() print(\"Options :\") print(\" -d, --dir", "% (os.path.basename(sys.argv[0]))) print() print(\"Options :\") print(\" -d, --dir : Output", "recorder import StreamRec OUTDIR = \"\" def parse_args(a): global OUTDIR", "example of .stream file in data/ to see how to", "utils from recorder import StreamRec OUTDIR = \"\" def parse_args(a):", ".stream file in data/ to see how to add a", "in stream_files: inst = StreamRec(stream_file, OUTDIR) all_inst.append(inst) for inst in", "for inst in all_inst: inst.start() for inst in all_inst: inst.join()", "< len(a): if a[i] in [\"-h\", \"--help\", \"/?\"]: usage() if", "import glob import os import sys import utils from recorder", ": Output directory\") print(\" -h, --help : Help\") sys.exit(1) def", "stream_files: inst = StreamRec(stream_file, OUTDIR) all_inst.append(inst) for inst in all_inst:", "in all_inst: inst.join() def main(): utils.welcome() parse_args(sys.argv) utils.make_directory(OUTDIR) load_streams() if", "add a stream to record\") print() print(\"Usage: %s [Options]\" %", "i = 1 while i < len(a): if a[i] in", "to record\") print() print(\"Usage: %s [Options]\" % (os.path.basename(sys.argv[0]))) print() print(\"Options", "(os.path.basename(sys.argv[0]))) print() print(\"Options :\") print(\" -d, --dir : Output directory\")", "\"--help\", \"/?\"]: usage() if a[i] in [\"-d\", \"--dir\"]: OUTDIR =", "StreamRec OUTDIR = \"\" def parse_args(a): global OUTDIR i =", "import StreamRec OUTDIR = \"\" def parse_args(a): global OUTDIR i", "inst in all_inst: inst.join() def main(): utils.welcome() parse_args(sys.argv) utils.make_directory(OUTDIR) load_streams()", "i += 1 def usage(): print(\"Record your favorite Twitch streams!\")", "1] i += 1 i += 1 def usage(): print(\"Record", "= \"\" def parse_args(a): global OUTDIR i = 1 while", "main(): utils.welcome() parse_args(sys.argv) utils.make_directory(OUTDIR) load_streams() if __name__ == '__main__': main()", "how to add a stream to record\") print() print(\"Usage: %s", "print(\" -d, --dir : Output directory\") print(\" -h, --help :", "= a[i + 1] i += 1 i += 1", "\"/?\"]: usage() if a[i] in [\"-d\", \"--dir\"]: OUTDIR = a[i", "def usage(): print(\"Record your favorite Twitch streams!\") print(\"Check an example", "in data/ to see how to add a stream to", "file in data/ to see how to add a stream", "print(\" -h, --help : Help\") sys.exit(1) def load_streams(): all_inst =", "if a[i] in [\"-h\", \"--help\", \"/?\"]: usage() if a[i] in", "\"\" def parse_args(a): global OUTDIR i = 1 while i", "inst = StreamRec(stream_file, OUTDIR) all_inst.append(inst) for inst in all_inst: inst.start()", "data/ to see how to add a stream to record\")", "def main(): utils.welcome() parse_args(sys.argv) utils.make_directory(OUTDIR) load_streams() if __name__ == '__main__':", "recursive=True) for stream_file in stream_files: inst = StreamRec(stream_file, OUTDIR) all_inst.append(inst)", "stream_files = glob.glob('data/**/*.stream', recursive=True) for stream_file in stream_files: inst =", "Output directory\") print(\" -h, --help : Help\") sys.exit(1) def load_streams():", "directory\") print(\" -h, --help : Help\") sys.exit(1) def load_streams(): all_inst", "1 while i < len(a): if a[i] in [\"-h\", \"--help\",", "from recorder import StreamRec OUTDIR = \"\" def parse_args(a): global", ": Help\") sys.exit(1) def load_streams(): all_inst = [] stream_files =", "def load_streams(): all_inst = [] stream_files = glob.glob('data/**/*.stream', recursive=True) for", "streams!\") print(\"Check an example of .stream file in data/ to", "= [] stream_files = glob.glob('data/**/*.stream', recursive=True) for stream_file in stream_files:", "= 1 while i < len(a): if a[i] in [\"-h\",", "all_inst: inst.join() def main(): utils.welcome() parse_args(sys.argv) utils.make_directory(OUTDIR) load_streams() if __name__", "OUTDIR) all_inst.append(inst) for inst in all_inst: inst.start() for inst in", "\"--dir\"]: OUTDIR = a[i + 1] i += 1 i", "load_streams(): all_inst = [] stream_files = glob.glob('data/**/*.stream', recursive=True) for stream_file", "[\"-d\", \"--dir\"]: OUTDIR = a[i + 1] i += 1", "+= 1 i += 1 def usage(): print(\"Record your favorite", "--help : Help\") sys.exit(1) def load_streams(): all_inst = [] stream_files", "import os import sys import utils from recorder import StreamRec", "usage(): print(\"Record your favorite Twitch streams!\") print(\"Check an example of", "[\"-h\", \"--help\", \"/?\"]: usage() if a[i] in [\"-d\", \"--dir\"]: OUTDIR", "an example of .stream file in data/ to see how", "all_inst.append(inst) for inst in all_inst: inst.start() for inst in all_inst:", "StreamRec(stream_file, OUTDIR) all_inst.append(inst) for inst in all_inst: inst.start() for inst", "1 i += 1 def usage(): print(\"Record your favorite Twitch", "inst.start() for inst in all_inst: inst.join() def main(): utils.welcome() parse_args(sys.argv)", "stream to record\") print() print(\"Usage: %s [Options]\" % (os.path.basename(sys.argv[0]))) print()", "glob.glob('data/**/*.stream', recursive=True) for stream_file in stream_files: inst = StreamRec(stream_file, OUTDIR)", "Help\") sys.exit(1) def load_streams(): all_inst = [] stream_files = glob.glob('data/**/*.stream',", "if a[i] in [\"-d\", \"--dir\"]: OUTDIR = a[i + 1]", "your favorite Twitch streams!\") print(\"Check an example of .stream file", "a[i + 1] i += 1 i += 1 def", "print() print(\"Options :\") print(\" -d, --dir : Output directory\") print(\"", "print(\"Check an example of .stream file in data/ to see", "[Options]\" % (os.path.basename(sys.argv[0]))) print() print(\"Options :\") print(\" -d, --dir :", "i < len(a): if a[i] in [\"-h\", \"--help\", \"/?\"]: usage()", "while i < len(a): if a[i] in [\"-h\", \"--help\", \"/?\"]:", "+ 1] i += 1 i += 1 def usage():", "record\") print() print(\"Usage: %s [Options]\" % (os.path.basename(sys.argv[0]))) print() print(\"Options :\")", "a[i] in [\"-h\", \"--help\", \"/?\"]: usage() if a[i] in [\"-d\",", "in [\"-h\", \"--help\", \"/?\"]: usage() if a[i] in [\"-d\", \"--dir\"]:", "inst.join() def main(): utils.welcome() parse_args(sys.argv) utils.make_directory(OUTDIR) load_streams() if __name__ ==", "sys import utils from recorder import StreamRec OUTDIR = \"\"", "def parse_args(a): global OUTDIR i = 1 while i <", "[] stream_files = glob.glob('data/**/*.stream', recursive=True) for stream_file in stream_files: inst", "= StreamRec(stream_file, OUTDIR) all_inst.append(inst) for inst in all_inst: inst.start() for", "see how to add a stream to record\") print() print(\"Usage:", "of .stream file in data/ to see how to add", "inst in all_inst: inst.start() for inst in all_inst: inst.join() def", "for inst in all_inst: inst.join() def main(): utils.welcome() parse_args(sys.argv) utils.make_directory(OUTDIR)", "+= 1 def usage(): print(\"Record your favorite Twitch streams!\") print(\"Check", "glob import os import sys import utils from recorder import", "len(a): if a[i] in [\"-h\", \"--help\", \"/?\"]: usage() if a[i]", "global OUTDIR i = 1 while i < len(a): if", "= glob.glob('data/**/*.stream', recursive=True) for stream_file in stream_files: inst = StreamRec(stream_file,", "i += 1 i += 1 def usage(): print(\"Record your" ]
[ "governing permissions and limitations # under the License. from oslo_policy", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "check_str=base.RULE_ADMIN_OR_OWNER, description='List protectable types.', operations=[ { 'method': 'GET', 'path': '/protectables'", "may obtain # a copy of the License at #", "description='List protectable instances.', operations=[ { 'method': 'GET', 'path': '/protectables/{protectable_type}/instances' }", "# All Rights Reserved. # # Licensed under the Apache", "# # Licensed under the Apache License, Version 2.0 (the", "All Rights Reserved. # # Licensed under the Apache License,", "agreed to in writing, software # distributed under the License", "instance.', operations=[ { 'method': 'GET', 'path': '/protectables/{protectable_type}/' 'instances/{resource_id}' } ]),", "description='Show a protectable type.', operations=[ { 'method': 'GET', 'path': '/protectables/{protectable_type}'", "Unless required by applicable law or agreed to in writing,", "GET_POLICY = 'protectable:get' GET_ALL_POLICY = 'protectable:get_all' INSTANCES_GET_POLICY = 'protectable:instance_get' INSTANCES_GET_ALL_POLICY", "distributed under the License is distributed on an \"AS IS\"", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "base GET_POLICY = 'protectable:get' GET_ALL_POLICY = 'protectable:get_all' INSTANCES_GET_POLICY = 'protectable:instance_get'", "'path': '/protectables' } ]), policy.DocumentedRuleDefault( name=INSTANCES_GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='Show a protectable", "obtain # a copy of the License at # #", "applicable law or agreed to in writing, software # distributed", "under the License. from oslo_policy import policy from karbor.policies import", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "'/protectables/{protectable_type}/' 'instances/{resource_id}' } ]), policy.DocumentedRuleDefault( name=INSTANCES_GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='List protectable instances.',", "Version 2.0 (the \"License\"); you may # not use this", "specific language governing permissions and limitations # under the License.", "# not use this file except in compliance with the", "not use this file except in compliance with the License.", "OF ANY KIND, either express or implied. See the #", "operations=[ { 'method': 'GET', 'path': '/protectables/{protectable_type}/' 'instances/{resource_id}' } ]), policy.DocumentedRuleDefault(", "from oslo_policy import policy from karbor.policies import base GET_POLICY =", "INSTANCES_GET_POLICY = 'protectable:instance_get' INSTANCES_GET_ALL_POLICY = 'protectable:instance_get_all' protectables_policies = [ policy.DocumentedRuleDefault(", "= [ policy.DocumentedRuleDefault( name=GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='Show a protectable type.', operations=[", "writing, software # distributed under the License is distributed on", "a protectable instance.', operations=[ { 'method': 'GET', 'path': '/protectables/{protectable_type}/' 'instances/{resource_id}'", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "import base GET_POLICY = 'protectable:get' GET_ALL_POLICY = 'protectable:get_all' INSTANCES_GET_POLICY =", "Copyright (c) 2017 Huawei Technologies Co., Ltd. # All Rights", "in compliance with the License. You may obtain # a", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "Technologies Co., Ltd. # All Rights Reserved. # # Licensed", "License for the specific language governing permissions and limitations #", "from karbor.policies import base GET_POLICY = 'protectable:get' GET_ALL_POLICY = 'protectable:get_all'", "Huawei Technologies Co., Ltd. # All Rights Reserved. # #", "= 'protectable:instance_get' INSTANCES_GET_ALL_POLICY = 'protectable:instance_get_all' protectables_policies = [ policy.DocumentedRuleDefault( name=GET_POLICY,", "the License. You may obtain # a copy of the", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "use this file except in compliance with the License. You", "You may obtain # a copy of the License at", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "permissions and limitations # under the License. from oslo_policy import", "'method': 'GET', 'path': '/protectables/{protectable_type}/instances' } ]), ] def list_rules(): return", "check_str=base.RULE_ADMIN_OR_OWNER, description='Show a protectable type.', operations=[ { 'method': 'GET', 'path':", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "protectable types.', operations=[ { 'method': 'GET', 'path': '/protectables' } ]),", "Rights Reserved. # # Licensed under the Apache License, Version", "'/protectables/{protectable_type}' } ]), policy.DocumentedRuleDefault( name=GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='List protectable types.', operations=[", "either express or implied. See the # License for the", "under the License is distributed on an \"AS IS\" BASIS,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "may # not use this file except in compliance with", "'method': 'GET', 'path': '/protectables' } ]), policy.DocumentedRuleDefault( name=INSTANCES_GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='Show", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "'/protectables' } ]), policy.DocumentedRuleDefault( name=INSTANCES_GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='Show a protectable instance.',", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "Co., Ltd. # All Rights Reserved. # # Licensed under", "with the License. You may obtain # a copy of", "KIND, either express or implied. See the # License for", "Reserved. # # Licensed under the Apache License, Version 2.0", "# License for the specific language governing permissions and limitations", "limitations # under the License. from oslo_policy import policy from", "you may # not use this file except in compliance", "policy.DocumentedRuleDefault( name=INSTANCES_GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='Show a protectable instance.', operations=[ { 'method':", "\"License\"); you may # not use this file except in", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "karbor.policies import base GET_POLICY = 'protectable:get' GET_ALL_POLICY = 'protectable:get_all' INSTANCES_GET_POLICY", "name=INSTANCES_GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='List protectable instances.', operations=[ { 'method': 'GET', 'path':", "types.', operations=[ { 'method': 'GET', 'path': '/protectables' } ]), policy.DocumentedRuleDefault(", "express or implied. See the # License for the specific", "this file except in compliance with the License. You may", "language governing permissions and limitations # under the License. from", "operations=[ { 'method': 'GET', 'path': '/protectables' } ]), policy.DocumentedRuleDefault( name=INSTANCES_GET_POLICY,", "compliance with the License. You may obtain # a copy", "protectable instance.', operations=[ { 'method': 'GET', 'path': '/protectables/{protectable_type}/' 'instances/{resource_id}' }", "the Apache License, Version 2.0 (the \"License\"); you may #", "the License. from oslo_policy import policy from karbor.policies import base", "GET_ALL_POLICY = 'protectable:get_all' INSTANCES_GET_POLICY = 'protectable:instance_get' INSTANCES_GET_ALL_POLICY = 'protectable:instance_get_all' protectables_policies", "'instances/{resource_id}' } ]), policy.DocumentedRuleDefault( name=INSTANCES_GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='List protectable instances.', operations=[", "= 'protectable:get_all' INSTANCES_GET_POLICY = 'protectable:instance_get' INSTANCES_GET_ALL_POLICY = 'protectable:instance_get_all' protectables_policies =", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "type.', operations=[ { 'method': 'GET', 'path': '/protectables/{protectable_type}' } ]), policy.DocumentedRuleDefault(", "description='List protectable types.', operations=[ { 'method': 'GET', 'path': '/protectables' }", "policy from karbor.policies import base GET_POLICY = 'protectable:get' GET_ALL_POLICY =", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "See the # License for the specific language governing permissions", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "} ]), policy.DocumentedRuleDefault( name=GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='List protectable types.', operations=[ {", "= 'protectable:instance_get_all' protectables_policies = [ policy.DocumentedRuleDefault( name=GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='Show a", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "the # License for the specific language governing permissions and", "name=GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='Show a protectable type.', operations=[ { 'method': 'GET',", "'GET', 'path': '/protectables' } ]), policy.DocumentedRuleDefault( name=INSTANCES_GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='Show a", "]), policy.DocumentedRuleDefault( name=INSTANCES_GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='List protectable instances.', operations=[ { 'method':", "check_str=base.RULE_ADMIN_OR_OWNER, description='List protectable instances.', operations=[ { 'method': 'GET', 'path': '/protectables/{protectable_type}/instances'", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "# # Unless required by applicable law or agreed to", "{ 'method': 'GET', 'path': '/protectables/{protectable_type}/instances' } ]), ] def list_rules():", "name=GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='List protectable types.', operations=[ { 'method': 'GET', 'path':", "operations=[ { 'method': 'GET', 'path': '/protectables/{protectable_type}/instances' } ]), ] def", "and limitations # under the License. from oslo_policy import policy", "'protectable:instance_get_all' protectables_policies = [ policy.DocumentedRuleDefault( name=GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='Show a protectable", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "'protectable:get' GET_ALL_POLICY = 'protectable:get_all' INSTANCES_GET_POLICY = 'protectable:instance_get' INSTANCES_GET_ALL_POLICY = 'protectable:instance_get_all'", "file except in compliance with the License. You may obtain", "{ 'method': 'GET', 'path': '/protectables/{protectable_type}' } ]), policy.DocumentedRuleDefault( name=GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER,", "'method': 'GET', 'path': '/protectables/{protectable_type}' } ]), policy.DocumentedRuleDefault( name=GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='List", "for the specific language governing permissions and limitations # under", "'GET', 'path': '/protectables/{protectable_type}/' 'instances/{resource_id}' } ]), policy.DocumentedRuleDefault( name=INSTANCES_GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='List", "law or agreed to in writing, software # distributed under", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "protectables_policies = [ policy.DocumentedRuleDefault( name=GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='Show a protectable type.',", "'path': '/protectables/{protectable_type}/' 'instances/{resource_id}' } ]), policy.DocumentedRuleDefault( name=INSTANCES_GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='List protectable", "under the Apache License, Version 2.0 (the \"License\"); you may", "(c) 2017 Huawei Technologies Co., Ltd. # All Rights Reserved.", "except in compliance with the License. You may obtain #", "2.0 (the \"License\"); you may # not use this file", "implied. See the # License for the specific language governing", "]), policy.DocumentedRuleDefault( name=GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='List protectable types.', operations=[ { 'method':", "policy.DocumentedRuleDefault( name=GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='Show a protectable type.', operations=[ { 'method':", "description='Show a protectable instance.', operations=[ { 'method': 'GET', 'path': '/protectables/{protectable_type}/'", "License. from oslo_policy import policy from karbor.policies import base GET_POLICY", "License. You may obtain # a copy of the License", "'GET', 'path': '/protectables/{protectable_type}' } ]), policy.DocumentedRuleDefault( name=GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='List protectable", "oslo_policy import policy from karbor.policies import base GET_POLICY = 'protectable:get'", "[ policy.DocumentedRuleDefault( name=GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='Show a protectable type.', operations=[ {", "name=INSTANCES_GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='Show a protectable instance.', operations=[ { 'method': 'GET',", "'method': 'GET', 'path': '/protectables/{protectable_type}/' 'instances/{resource_id}' } ]), policy.DocumentedRuleDefault( name=INSTANCES_GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER,", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "ANY KIND, either express or implied. See the # License", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "]), policy.DocumentedRuleDefault( name=INSTANCES_GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='Show a protectable instance.', operations=[ {", "instances.', operations=[ { 'method': 'GET', 'path': '/protectables/{protectable_type}/instances' } ]), ]", "# Unless required by applicable law or agreed to in", "protectable type.', operations=[ { 'method': 'GET', 'path': '/protectables/{protectable_type}' } ]),", "Ltd. # All Rights Reserved. # # Licensed under the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "import policy from karbor.policies import base GET_POLICY = 'protectable:get' GET_ALL_POLICY", "# Copyright (c) 2017 Huawei Technologies Co., Ltd. # All", "to in writing, software # distributed under the License is", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "operations=[ { 'method': 'GET', 'path': '/protectables/{protectable_type}' } ]), policy.DocumentedRuleDefault( name=GET_ALL_POLICY,", "} ]), policy.DocumentedRuleDefault( name=INSTANCES_GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='Show a protectable instance.', operations=[", "} ]), policy.DocumentedRuleDefault( name=INSTANCES_GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='List protectable instances.', operations=[ {", "= 'protectable:get' GET_ALL_POLICY = 'protectable:get_all' INSTANCES_GET_POLICY = 'protectable:instance_get' INSTANCES_GET_ALL_POLICY =", "'GET', 'path': '/protectables/{protectable_type}/instances' } ]), ] def list_rules(): return protectables_policies", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "'protectable:instance_get' INSTANCES_GET_ALL_POLICY = 'protectable:instance_get_all' protectables_policies = [ policy.DocumentedRuleDefault( name=GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER,", "INSTANCES_GET_ALL_POLICY = 'protectable:instance_get_all' protectables_policies = [ policy.DocumentedRuleDefault( name=GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='Show", "or agreed to in writing, software # distributed under the", "a protectable type.', operations=[ { 'method': 'GET', 'path': '/protectables/{protectable_type}' }", "required by applicable law or agreed to in writing, software", "{ 'method': 'GET', 'path': '/protectables/{protectable_type}/' 'instances/{resource_id}' } ]), policy.DocumentedRuleDefault( name=INSTANCES_GET_ALL_POLICY,", "2017 Huawei Technologies Co., Ltd. # All Rights Reserved. #", "check_str=base.RULE_ADMIN_OR_OWNER, description='Show a protectable instance.', operations=[ { 'method': 'GET', 'path':", "protectable instances.', operations=[ { 'method': 'GET', 'path': '/protectables/{protectable_type}/instances' } ]),", "'protectable:get_all' INSTANCES_GET_POLICY = 'protectable:instance_get' INSTANCES_GET_ALL_POLICY = 'protectable:instance_get_all' protectables_policies = [", "policy.DocumentedRuleDefault( name=INSTANCES_GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='List protectable instances.', operations=[ { 'method': 'GET',", "# under the License. from oslo_policy import policy from karbor.policies", "{ 'method': 'GET', 'path': '/protectables' } ]), policy.DocumentedRuleDefault( name=INSTANCES_GET_POLICY, check_str=base.RULE_ADMIN_OR_OWNER,", "policy.DocumentedRuleDefault( name=GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='List protectable types.', operations=[ { 'method': 'GET',", "'path': '/protectables/{protectable_type}' } ]), policy.DocumentedRuleDefault( name=GET_ALL_POLICY, check_str=base.RULE_ADMIN_OR_OWNER, description='List protectable types.',", "or implied. See the # License for the specific language", "Apache License, Version 2.0 (the \"License\"); you may # not" ]
[ "applications to None to disable the removal of application names", "out=True) '/fcn?query#anchor' >>> filter_url('http://domain.com/appadmin/fcn-1') '/welcome/appadmin/fcn_1' >>> filter_url('http://domain.com/welcome/appadmin/fcn_1', out=True) '/appadmin/fcn-1' >>>", "# '*' as a wildcard. # # The error handling", "maps to this application (alternative to using domains in the", "the event that the error-handling page itself returns an error,", "False, # don't map hyphens to underscores ), ) #", "# and domain makes sense only in an application-specific router.", "error_handler = dict(application='error', # controller='default', # function='index') # In the", "and language names. # languages: list of all supported languages", "are dictionaries of URL routing parameters. # # For each", ">>> filter_url('https://domain.com/welcome/appadmin/index', out=True) '/appadmin' >>> filter_url('http://domain.com/welcome/default/fcn?query', out=True) '/fcn?query' >>> filter_url('http://domain.com/welcome/default/fcn#anchor',", "router (shown below), # updated by the BASE router in", "responses. You can customize them here. # ErrorMessageTicket takes a", "filter_url('http://domain.com/admin/bad!ctl') Traceback (most recent call last): ... HTTP: 400 BAD", "the app-specific router in routes.py routers (if any), # updated", "# the (optional) application and language names. # languages: list", "# controllers = 'DEFAULT', # default_function = 'index', # default_language", "last): ... HTTP: 400 BAD REQUEST [invalid arg <bad!arg>] >>>", "Router members: # # default_application: default application name # applications:", ">>> filter_url('http://domain.com/abc', app=True) 'welcome' >>> filter_url('http://domain.com/welcome', app=True) 'welcome' >>> os.path.relpath(filter_url('http://domain.com/favicon.ico'))", "routers are dictionaries of URL routing parameters. # # For", "removal of application names from outgoing URLs. # domains: optional", "or None to disable controller-name removal. # Names in controllers", ">>> import gluon.main >>> from gluon.rewrite import load, filter_url, filter_err,", "all recognized applications, or 'ALL' to use all currently installed", "# updated by the app-specific router from applcations/app/routes.py routers (if", "# error_handler = dict(application='error', # controller='default', # function='index') # In", "BASE router, # and domain makes sense only in an", "routers = dict( # base router BASE = dict( default_application", "This validation provides a measure of security. # If it", "# the application (which may be omitted). For incoming URLs,", "an application names when they appear first in an incoming", "args # This validation provides a measure of security. #", "# Router members: # # default_application: default application name #", "out=True) '/appadmin' >>> filter_url('http://domain.com/welcome/default/fcn?query', out=True) '/fcn?query' >>> filter_url('http://domain.com/welcome/default/fcn#anchor', out=True) '/fcn#anchor'", ">>> os.path.relpath(filter_url('http://domain.com/admin/static/filename-with_underscore')) 'applications/admin/static/filename-with_underscore' >>> filter_err(200) 200 >>> filter_err(399) 399 >>>", "all applications) # or in application-specific routers. # # default_controller:", "for outgoing URLs it is taken from request.language. # If", "by adding a tuple entry with the first # value", "legal file (path) name # args_match = r'([\\w@ -]+[=.]?)+$', #", "(path) name # args_match = r'([\\w@ -]+[=.]?)+$', # legal arg", "app=True) 'welcome' >>> os.path.relpath(filter_url('http://domain.com/favicon.ico')) 'applications/welcome/static/favicon.ico' >>> filter_url('http://domain.com/abc') '/welcome/default/abc' >>> filter_url('http://domain.com/index/abc')", "out=True) '/app/ctr/fcn' >>> filter_url('https://domain.com/welcome/ctr/fcn', out=True) '/ctr/fcn' >>> filter_url('https://domain.com/welcome/default/fcn', out=True) '/fcn'", "include a controller: appx/ctlrx # path_prefix: a path fragment that", "languages # Names in controllers are always treated as language", "to this application (alternative to using domains in the BASE", "# If it is changed, the application perform its own", "back to its old static responses. You can customize them", "# domain: the domain that maps to this application (alternative", "measure of security. # If it is changed, the application", "to # request.language; for outgoing URLs it is taken from", "'static' # or None to disable controller-name removal. # Names", "domain name can include a port number: domain.com:8080 # The", "filter_err(400) 400 ''' pass if __name__ == '__main__': import doctest", "dict mapping domain names to application names # The domain", "base router BASE = dict( default_application = 'welcome', ), #", "-*- # routers are dictionaries of URL routing parameters. #", "# legal app/ctlr/fcn/ext # file_match = r'(\\w+[-=./]?)+$', # legal file", "HTTP: 400 BAD REQUEST [invalid arg <bad!arg>] >>> filter_url('https://domain.com/app/ctr/fcn', out=True)", "provides full rewrite functionality. routers = dict( # base router", "applications, or 'ALL' to use all currently installed applications #", "to redirect the user to. You may also use #", "a path to redirect the user to. You may also", "in an incoming URL. # Set applications to None to", "is disabled. # The default_language, if any, is omitted from", "r'(\\w+[-=./]?)+$', # legal file (path) name # args_match = r'([\\w@", "out=True) '/appadmin/fcn-1' >>> filter_url('http://domain.com/examples/appadmin/fcn-1') '/examples/appadmin/fcn_1' >>> filter_url('http://domain.com/examples/appadmin/fcn_1', out=True) '/examples/appadmin/fcn-1' >>>", "a port number: domain.com:8080 # The application name can include", "default_function: name of default function (all controllers) # controllers: list", "implementation details. # This simple router set overrides only the", "the current application's static/ directory) # Each application has its", "filter_url('http://domain.com/default/abc.css') '/welcome/default/abc.css' >>> filter_url('http://domain.com/default/index/abc') \"/welcome/default/index ['abc']\" >>> filter_url('http://domain.com/default/index/a bc') \"/welcome/default/index", "that is prefixed to all outgoing URLs and stripped from", "gluon.main >>> from gluon.rewrite import load, filter_url, filter_err, get_effective_router >>>", "and ticket: filter_err(status, application='app', ticket='tkt') >>> import os >>> import", "is prefixed to all outgoing URLs and stripped from all", "# ,(r'init/*', r'/init/static/fail.html') # ,(r'*/404', r'/init/static/cantfind.html') # ,(r'*/*', r'/init/error/index') #", "for application and ticket: filter_err(status, application='app', ticket='tkt') >>> import os", "names when they appear in an incoming URL after #", "to underscores ), ) # Error-handling redirects all HTTP errors", "= None, # languages = None, # root_static = ['favicon.ico',", "installed applications # Names in applications are always treated as", "# error_message_ticket = '<html><body><h1>Internal error</h1>Ticket issued: <a href=\"/admin/default/ticket/%(ticket)s\" target=\"_blank\">%(ticket)s</a></body></html>' def", "recent call last): ... HTTP: 400 BAD REQUEST [invalid arg", "( Only HTTP codes >= 400 are # routed. )", "back to hyphens in outgoing URLs. Language, args and the", "REQUEST [invalid controller] >>> filter_url('http://domain.com/admin/ctl/bad!fcn') Traceback (most recent call last):", "example: en, it-it) optionally appears in the URL following #", "values (undefined members are None): # # default_router = dict(", "# default_router = dict( # default_application = 'init', # applications", "# file_match: regex for valid file (used for static file", "value as a path to redirect the user to. You", "user to. You may also use # '*' as a", "containing (only) the # \"ticket\" key. # error_message = '<html><body><h1>Invalid", "call last): ... HTTP: 400 BAD REQUEST [invalid controller] >>>", "to None to disable the removal of application names from", "= dict(application='error', # controller='default', # function='index') # In the event", "path to redirect the user to. You may also use", "'welcome' >>> os.path.relpath(filter_url('http://domain.com/favicon.ico')) 'applications/welcome/static/favicon.ico' >>> filter_url('http://domain.com/abc') '/welcome/default/abc' >>> filter_url('http://domain.com/index/abc') \"/welcome/default/index", "static responses. You can customize them here. # ErrorMessageTicket takes", "information will be stored in the ticket. # # routes_onerror", "action in charge of error handling # # error_handler =", "domains in the BASE router) # map_hyphen: If True (default),", "= dict( # default_application = 'init', # applications = 'ALL',", "] # specify action in charge of error handling #", "# ,(r'*/404', r'/init/static/cantfind.html') # ,(r'*/*', r'/init/error/index') # ] # specify", "codes >= 400 are # routed. ) and the value", "out=True) '/examples/appadmin/fcn-1' >>> filter_url('http://domain.com/app/static/filename-with_underscore', out=True) '/app/static/filename-with_underscore' >>> os.path.relpath(filter_url('http://domain.com/admin/static/filename-with_underscore')) 'applications/admin/static/filename-with_underscore' >>>", "'ALL', # default_controller = 'default', # controllers = 'DEFAULT', #", "errors (status codes >= 400) to a specified # path.", "If you wish to use error-handling redirects, uncomment the tuple", "in the ticket. # # routes_onerror = [ # (r'init/400',", "def __routes_doctest(): ''' Dummy function for doctesting routes.py. Use filter_url()", "doctesting routes.py. Use filter_url() to test incoming or outgoing routes;", "last): ... HTTP: 400 BAD REQUEST [invalid extension] >>> filter_url('http://domain.com/admin/ctl/fcn/bad!arg')", "supported languages # Names in controllers are always treated as", "routers (if any), # updated by the app-specific router from", "... HTTP: 400 BAD REQUEST [invalid function] >>> filter_url('http://domain.com/admin/ctl/fcn.bad!ext') Traceback", "# # default_application: default application name # applications: list of", ">>> filter_url('https://domain.com/welcome/default/index', out=True) '/' >>> filter_url('https://domain.com/welcome/appadmin/index', out=True) '/appadmin' >>> filter_url('http://domain.com/welcome/default/fcn?query',", "names from outgoing URLs. # domains: optional dict mapping domain", "error, web2py will # fall back to its old static", "is omitted from the URL. # root_static: list of static", "'<html><body><h1>Internal error</h1>Ticket issued: <a href=\"/admin/default/ticket/%(ticket)s\" target=\"_blank\">%(ticket)s</a></body></html>' def __routes_doctest(): ''' Dummy", "rewrite functionality. routers = dict( # base router BASE =", "Traceback (most recent call last): ... HTTP: 400 BAD REQUEST", "language code (for example: en, it-it) optionally appears in the", "# domains = None, # map_hyphen = True, # acfe_match", "), # 'admin' application router admin = dict( controllers =", "path fragment that is prefixed to all outgoing URLs and", "use all controllers in the selected app plus 'static' #", "file_match = r'(\\w+[-=./]?)+$', # legal file (path) name # args_match", "[ # (r'init/400', r'/init/default/login') # ,(r'init/*', r'/init/static/fail.html') # ,(r'*/404', r'/init/static/cantfind.html')", "# default_application = 'init', # applications = 'ALL', # default_controller", "and stripped from all incoming URLs # # Note: default_application,", "# updated by the app-specific router in routes.py routers (if", "routers. # # default_controller: name of default controller # default_function:", "as a path to redirect the user to. You may", "default_application = 'init', # applications = 'ALL', # default_controller =", "and the query string are not affected. # map_static: By", "filter_err(399) 399 >>> filter_err(400) 400 ''' pass if __name__ ==", "all supported languages # Names in controllers are always treated", "# but provides full rewrite functionality. routers = dict( #", "= dict( default_application = 'welcome', ), # 'admin' application router", "policy. # acfe_match: regex for valid application, controller, function, extension", "languages=None, language support is disabled. # The default_language, if any,", "format. ( Only HTTP codes >= 400 are # routed.", "error_message_ticket = '<html><body><h1>Internal error</h1>Ticket issued: <a href=\"/admin/default/ticket/%(ticket)s\" target=\"_blank\">%(ticket)s</a></body></html>' def __routes_doctest():", "request.language; for outgoing URLs it is taken from request.language. #", "href=\"/admin/default/ticket/%(ticket)s\" target=\"_blank\">%(ticket)s</a></body></html>' def __routes_doctest(): ''' Dummy function for doctesting routes.py.", "# args_match = r'([\\w@ -]+[=.]?)+$', # legal arg in args", "appear in the BASE router (as defaults for all applications)", "charge of error handling # # error_handler = dict(application='error', #", "string format dictionary containing (only) the # \"ticket\" key. #", "controller] >>> filter_url('http://domain.com/admin/ctl/bad!fcn') Traceback (most recent call last): ... HTTP:", "Set applications to None to disable the removal of application", "all outgoing URLs and stripped from all incoming URLs #", "be omitted). For incoming URLs, the code is copied to", "'appName/HTTPstatusCode' format. ( Only HTTP codes >= 400 are #", "router from applcations/app/routes.py routers (if any) # # # Router", "# function='index') # In the event that the error-handling page", "If it is changed, the application perform its own validation.", "# root_static = ['favicon.ico', 'robots.txt'], # domains = None, #", "this application (alternative to using domains in the BASE router)", "[], # don't remove controller names from admin URLs map_hyphen", "bc']\" >>> filter_url('http://domain.com/admin/bad!ctl') Traceback (most recent call last): ... HTTP:", "mapping domain names to application names # The domain name", "file (path) name # args_match = r'([\\w@ -]+[=.]?)+$', # legal", "only in the BASE router, # and domain makes sense", "out=True) '/ctr/fcn' >>> filter_url('https://domain.com/welcome/default/fcn', out=True) '/fcn' >>> filter_url('https://domain.com/welcome/default/index', out=True) '/'", "function, extension /a/c/f.e # file_match: regex for valid file (used", "static/ directory) # Each application has its own root-static files.", "the BASE router) # map_hyphen: If True (default), hyphens in", "application router admin = dict( controllers = [], # don't", "by the app-specific router from applcations/app/routes.py routers (if any) #", "list of all supported languages # Names in controllers are", "recent call last): ... HTTP: 400 BAD REQUEST [invalid extension]", "adding a tuple entry with the first # value in", "rewrite.map_url_in() and rewrite.map_url_out() for implementation details. # This simple router", "'robots.txt'], # domains = None, # map_hyphen = True, #", "# In the event that the error-handling page itself returns", "(optional) application and language names. # languages: list of all", "specified # path. If you wish to use error-handling redirects,", "in an application-specific router. # The remaining members can appear", "the default application is not stripped from static URLs. Set", "accepts overrides for method and remote host: filter_url(url, method='get', remote='0.0.0.0',", "# default_language = None, # languages = None, # root_static", "is also passed the error code and ticket as #", "\"/welcome/default/index ['abc']\" >>> filter_url('http://domain.com/default/abc.css') '/welcome/default/abc.css' >>> filter_url('http://domain.com/default/index/abc') \"/welcome/default/index ['abc']\" >>>", "'/ctr/fcn' >>> filter_url('https://domain.com/welcome/default/fcn', out=True) '/fcn' >>> filter_url('https://domain.com/welcome/default/index', out=True) '/' >>>", "URLs it is taken from request.language. # If languages=None, language", "returns an error, web2py will # fall back to its", ") # Error-handling redirects all HTTP errors (status codes >=", "that the error-handling page itself returns an error, web2py will", "path_prefix are permitted only in the BASE router, # and", "they appear in an incoming URL after # the (optional)", "controller, function, extension /a/c/f.e # file_match: regex for valid file", "its own validation. # # # The built-in default router", "domains: optional dict mapping domain names to application names #", "stripped from all incoming URLs # # Note: default_application, applications,", "# # See rewrite.map_url_in() and rewrite.map_url_out() for implementation details. #", "all HTTP errors (status codes >= 400) to a specified", "import os >>> import gluon.main >>> from gluon.rewrite import load,", "hyphens in outgoing URLs. Language, args and the query string", "map_hyphen: If True (default), hyphens in incoming /a/c/f fields are", "the BASE router (as defaults for all applications) # or", "See rewrite.map_url_in() and rewrite.map_url_out() for implementation details. # This simple", "# don't map hyphens to underscores ), ) # Error-handling", "and ticket as # variables. Traceback information will be stored", "to underscores, # and back to hyphens in outgoing URLs.", "changed, the application perform its own validation. # # #", "a specified # path. If you wish to use error-handling", "filter_url('http://domain.com/welcome/default/fcn?query#anchor', out=True) '/fcn?query#anchor' >>> filter_url('http://domain.com/appadmin/fcn-1') '/welcome/appadmin/fcn_1' >>> filter_url('http://domain.com/welcome/appadmin/fcn_1', out=True) '/appadmin/fcn-1'", "not stripped from static URLs. Set map_static=True # to override", "# map_static: By default, the default application is not stripped", "will be stored in the ticket. # # routes_onerror =", "= [ # (r'init/400', r'/init/default/login') # ,(r'init/*', r'/init/static/fail.html') # ,(r'*/404',", "from static URLs. Set map_static=True # to override this policy.", "# Set applications to None to disable the removal of", ">>> filter_url('http://domain.com/admin/ctl/fcn.bad!ext') Traceback (most recent call last): ... HTTP: 400", "'/appadmin/fcn-1' >>> filter_url('http://domain.com/examples/appadmin/fcn-1') '/examples/appadmin/fcn_1' >>> filter_url('http://domain.com/examples/appadmin/fcn_1', out=True) '/examples/appadmin/fcn-1' >>> filter_url('http://domain.com/app/static/filename-with_underscore',", "app-specific router from applcations/app/routes.py routers (if any) # # #", "# If languages=None, language support is disabled. # The default_language,", "You can customize responses by adding a tuple entry with", "routes.py routers, # updated by the app-specific router in routes.py", "the # \"ticket\" key. # error_message = '<html><body><h1>Invalid request</h1></body></html>' #", "HTTP: 400 BAD REQUEST [invalid extension] >>> filter_url('http://domain.com/admin/ctl/fcn/bad!arg') Traceback (most", "the BASE router in routes.py routers, # updated by the", "members: # # default_application: default application name # applications: list", "use error-handling redirects, uncomment the tuple # below. You can", "redirect the user to. You may also use # '*'", "'/fcn' >>> filter_url('https://domain.com/welcome/default/index', out=True) '/' >>> filter_url('https://domain.com/welcome/appadmin/index', out=True) '/appadmin' >>>", "# legal file (path) name # args_match = r'([\\w@ -]+[=.]?)+$',", "out=True) '/' >>> filter_url('https://domain.com/welcome/appadmin/index', out=True) '/appadmin' >>> filter_url('http://domain.com/welcome/default/fcn?query', out=True) '/fcn?query'", "removal. # Names in controllers are always treated as controller", "# map_hyphen: If True (default), hyphens in incoming /a/c/f fields", "routes_onerror = [ # (r'init/400', r'/init/default/login') # ,(r'init/*', r'/init/static/fail.html') #", "for error redirection. filter_url() accepts overrides for method and remote", ">>> filter_url('http://domain.com/welcome/default/fcn?query#anchor', out=True) '/fcn?query#anchor' >>> filter_url('http://domain.com/appadmin/fcn-1') '/welcome/appadmin/fcn_1' >>> filter_url('http://domain.com/welcome/appadmin/fcn_1', out=True)", "If True (default), hyphens in incoming /a/c/f fields are converted", "routers (if any) # # # Router members: # #", "are not affected. # map_static: By default, the default application", "'*' as a wildcard. # # The error handling page", "languages: list of all supported languages # Names in controllers", "base router (shown below), # updated by the BASE router", "copied to # request.language; for outgoing URLs it is taken", "HTTP errors (status codes >= 400) to a specified #", "or 'ALL' to use all currently installed applications # Names", "(shown below), # updated by the BASE router in routes.py", "disable the removal of application names from outgoing URLs. #", "can include a port number: domain.com:8080 # The application name", "in an incoming URL after # the (optional) application name.", "admin = dict( controllers = [], # don't remove controller", "recent call last): ... HTTP: 400 BAD REQUEST [invalid controller]", "request.language. # If languages=None, language support is disabled. # The", "args_match: regex for valid args # This validation provides a", "of application names from outgoing URLs. # domains: optional dict", "default_language, if any, is omitted from the URL. # root_static:", "handling page is also passed the error code and ticket", "use all currently installed applications # Names in applications are", "currently installed applications # Names in applications are always treated", "r'/init/default/login') # ,(r'init/*', r'/init/static/fail.html') # ,(r'*/404', r'/init/static/cantfind.html') # ,(r'*/*', r'/init/error/index')", "# applications = 'ALL', # default_controller = 'default', # controllers", "(all controllers) # controllers: list of valid controllers in selected", "optional dict mapping domain names to application names # The", "The domain name can include a port number: domain.com:8080 #", "hyphens in incoming /a/c/f fields are converted to underscores, #", "filter_url('http://domain.com/admin/ctl/bad!fcn') Traceback (most recent call last): ... HTTP: 400 BAD", "in the BASE router (as defaults for all applications) #", "dict( # default_application = 'init', # applications = 'ALL', #", "None, # map_hyphen = True, # acfe_match = r'\\w+$', #", "redirection. filter_url() accepts overrides for method and remote host: filter_url(url,", "router supplies default values (undefined members are None): # #", "an error, web2py will # fall back to its old", "router BASE = dict( default_application = 'welcome', ), # 'admin'", "from request.language. # If languages=None, language support is disabled. #", "below), # updated by the BASE router in routes.py routers,", "any), # updated by the app-specific router from applcations/app/routes.py routers", "can customize responses by adding a tuple entry with the", "for valid args # This validation provides a measure of", "routed. ) and the value as a path to redirect", "BASE = dict( default_application = 'welcome', ), # 'admin' application", "'default', # controllers = 'DEFAULT', # default_function = 'index', #", "controller='default', # function='index') # In the event that the error-handling", "incoming URL after # the (optional) application and language names.", "to its old static responses. You can customize them here.", "to disable controller-name removal. # Names in controllers are always", "ticket: filter_err(status, application='app', ticket='tkt') >>> import os >>> import gluon.main", "as an application names when they appear first in an", "default_application = 'welcome', ), # 'admin' application router admin =", "error_message = '<html><body><h1>Invalid request</h1></body></html>' # error_message_ticket = '<html><body><h1>Internal error</h1>Ticket issued:", "# or in application-specific routers. # # default_controller: name of", "names from admin URLs map_hyphen = False, # don't map", "rewrite.map_url_out() for implementation details. # This simple router set overrides", "number: domain.com:8080 # The application name can include a controller:", "# or None to disable controller-name removal. # Names in", "domains = None, # map_hyphen = True, # acfe_match =", "\"/welcome/default/index ['abc']\" >>> filter_url('http://domain.com/default/index/a bc') \"/welcome/default/index ['a bc']\" >>> filter_url('http://domain.com/admin/bad!ctl')", ">>> filter_url('http://domain.com/welcome', app=True) 'welcome' >>> os.path.relpath(filter_url('http://domain.com/favicon.ico')) 'applications/welcome/static/favicon.ico' >>> filter_url('http://domain.com/abc') '/welcome/default/abc'", "ticket='tkt') >>> import os >>> import gluon.main >>> from gluon.rewrite", "BAD REQUEST [invalid extension] >>> filter_url('http://domain.com/admin/ctl/fcn/bad!arg') Traceback (most recent call", "root-static files. # domain: the domain that maps to this", "to hyphens in outgoing URLs. Language, args and the query", "regex for valid application, controller, function, extension /a/c/f.e # file_match:", "(r'init/400', r'/init/default/login') # ,(r'init/*', r'/init/static/fail.html') # ,(r'*/404', r'/init/static/cantfind.html') # ,(r'*/*',", "# ErrorMessageTicket takes a string format dictionary containing (only) the", "valid controllers in selected app # or \"DEFAULT\" to use", "prefixed to all outgoing URLs and stripped from all incoming", "by the app-specific router in routes.py routers (if any), #", "function='index') # In the event that the error-handling page itself", "(only) the # \"ticket\" key. # error_message = '<html><body><h1>Invalid request</h1></body></html>'", "app=True) 'welcome' >>> filter_url('http://domain.com/welcome', app=True) 'welcome' >>> os.path.relpath(filter_url('http://domain.com/favicon.ico')) 'applications/welcome/static/favicon.ico' >>>", "current application's static/ directory) # Each application has its own", "router) # map_hyphen: If True (default), hyphens in incoming /a/c/f", "own validation. # # # The built-in default router supplies", "URL routing parameters. # # For each request, the effective", "The built-in default router supplies default values (undefined members are", "details. # This simple router set overrides only the default", "handling # # error_handler = dict(application='error', # controller='default', # function='index')", "don't map hyphens to underscores ), ) # Error-handling redirects", "are # routed. ) and the value as a path", "in the selected app plus 'static' # or None to", "incoming or outgoing routes; filter_err() for error redirection. filter_url() accepts", "to disable the removal of application names from outgoing URLs.", "... HTTP: 400 BAD REQUEST [invalid arg <bad!arg>] >>> filter_url('https://domain.com/app/ctr/fcn',", "(default), hyphens in incoming /a/c/f fields are converted to underscores,", "Language, args and the query string are not affected. #", ">>> filter_url('http://domain.com/examples/appadmin/fcn_1', out=True) '/examples/appadmin/fcn-1' >>> filter_url('http://domain.com/app/static/filename-with_underscore', out=True) '/app/static/filename-with_underscore' >>> os.path.relpath(filter_url('http://domain.com/admin/static/filename-with_underscore'))", "router set overrides only the default application name, # but", "os.path.relpath(filter_url('http://domain.com/admin/static/filename-with_underscore')) 'applications/admin/static/filename-with_underscore' >>> filter_err(200) 200 >>> filter_err(399) 399 >>> filter_err(400)", "to all outgoing URLs and stripped from all incoming URLs", "application, controller, function, extension /a/c/f.e # file_match: regex for valid", "map hyphens to underscores ), ) # Error-handling redirects all", "and the value as a path to redirect the user", "from all incoming URLs # # Note: default_application, applications, domains", "application (which may be omitted). For incoming URLs, the code", "# The built-in default router supplies default values (undefined members", "default router supplies default values (undefined members are None): #", "'admin' application router admin = dict( controllers = [], #", "are converted to underscores, # and back to hyphens in", "may be omitted). For incoming URLs, the code is copied", "application name # applications: list of all recognized applications, or", "files accessed from root # (mapped to the current application's", "extension /a/c/f.e # file_match: regex for valid file (used for", "# (r'init/400', r'/init/default/login') # ,(r'init/*', r'/init/static/fail.html') # ,(r'*/404', r'/init/static/cantfind.html') #", "codes >= 400) to a specified # path. If you", "# \"ticket\" key. # error_message = '<html><body><h1>Invalid request</h1></body></html>' # error_message_ticket", "in routes.py routers, # updated by the app-specific router in", "application-specific routers. # # default_controller: name of default controller #", "[invalid extension] >>> filter_url('http://domain.com/admin/ctl/fcn/bad!arg') Traceback (most recent call last): ...", "# See rewrite.map_url_in() and rewrite.map_url_out() for implementation details. # This", "code (for example: en, it-it) optionally appears in the URL", "# # Note: default_application, applications, domains & path_prefix are permitted", "are always treated as controller names when they appear in", "# The remaining members can appear in the BASE router", "the tuple # below. You can customize responses by adding", ">>> filter_url('http://domain.com/admin/bad!ctl') Traceback (most recent call last): ... HTTP: 400", "400 ''' pass if __name__ == '__main__': import doctest doctest.testmod()", "an incoming URL. # Set applications to None to disable", ">>> filter_url('https://domain.com/welcome/ctr/fcn', out=True) '/ctr/fcn' >>> filter_url('https://domain.com/welcome/default/fcn', out=True) '/fcn' >>> filter_url('https://domain.com/welcome/default/index',", "the error-handling page itself returns an error, web2py will #", "of default controller # default_function: name of default function (all", "may also use # '*' as a wildcard. # #", "# The default_language, if any, is omitted from the URL.", ",(r'*/404', r'/init/static/cantfind.html') # ,(r'*/*', r'/init/error/index') # ] # specify action", "Traceback information will be stored in the ticket. # #", "be stored in the ticket. # # routes_onerror = [", "get_effective_router >>> load(routes=os.path.basename(__file__)) >>> filter_url('http://domain.com/abc', app=True) 'welcome' >>> filter_url('http://domain.com/welcome', app=True)", "by the BASE router in routes.py routers, # updated by", "function (all controllers) # controllers: list of valid controllers in", ",(r'init/*', r'/init/static/fail.html') # ,(r'*/404', r'/init/static/cantfind.html') # ,(r'*/*', r'/init/error/index') # ]", "controller # default_function: name of default function (all controllers) #", "os.path.relpath(filter_url('http://domain.com/favicon.ico')) 'applications/welcome/static/favicon.ico' >>> filter_url('http://domain.com/abc') '/welcome/default/abc' >>> filter_url('http://domain.com/index/abc') \"/welcome/default/index ['abc']\" >>>", "call last): ... HTTP: 400 BAD REQUEST [invalid extension] >>>", "a controller: appx/ctlrx # path_prefix: a path fragment that is", "map_hyphen = False, # don't map hyphens to underscores ),", "# default_controller: name of default controller # default_function: name of", "root_static = ['favicon.ico', 'robots.txt'], # domains = None, # map_hyphen", "event that the error-handling page itself returns an error, web2py", "default application is not stripped from static URLs. Set map_static=True", "= dict( controllers = [], # don't remove controller names", "'applications/welcome/static/favicon.ico' >>> filter_url('http://domain.com/abc') '/welcome/default/abc' >>> filter_url('http://domain.com/index/abc') \"/welcome/default/index ['abc']\" >>> filter_url('http://domain.com/default/abc.css')", "[invalid arg <bad!arg>] >>> filter_url('https://domain.com/app/ctr/fcn', out=True) '/app/ctr/fcn' >>> filter_url('https://domain.com/welcome/ctr/fcn', out=True)", "# Names in controllers are always treated as language names", "router in routes.py routers (if any), # updated by the", "HTTP: 400 BAD REQUEST [invalid function] >>> filter_url('http://domain.com/admin/ctl/fcn.bad!ext') Traceback (most", "full rewrite functionality. routers = dict( # base router BASE", "r'/init/static/fail.html') # ,(r'*/404', r'/init/static/cantfind.html') # ,(r'*/*', r'/init/error/index') # ] #", "app # or \"DEFAULT\" to use all controllers in the", "will # fall back to its old static responses. You", "and rewrite.map_url_out() for implementation details. # This simple router set", "Names in controllers are always treated as controller names when", "# specify action in charge of error handling # #", "400 BAD REQUEST [invalid function] >>> filter_url('http://domain.com/admin/ctl/fcn.bad!ext') Traceback (most recent", "appear in an incoming URL after # the (optional) application", "'/welcome/default/abc.css' >>> filter_url('http://domain.com/default/index/abc') \"/welcome/default/index ['abc']\" >>> filter_url('http://domain.com/default/index/a bc') \"/welcome/default/index ['a", "stripped from static URLs. Set map_static=True # to override this", "only in an application-specific router. # The remaining members can", "omitted). For incoming URLs, the code is copied to #", "languages = None, # root_static = ['favicon.ico', 'robots.txt'], # domains", "error code and ticket as # variables. Traceback information will", "wish to use error-handling redirects, uncomment the tuple # below.", "# path_prefix: a path fragment that is prefixed to all", "applications: list of all recognized applications, or 'ALL' to use", "out=True) '/app/static/filename-with_underscore' >>> os.path.relpath(filter_url('http://domain.com/admin/static/filename-with_underscore')) 'applications/admin/static/filename-with_underscore' >>> filter_err(200) 200 >>> filter_err(399)", ">>> filter_url('http://domain.com/welcome/default/fcn?query', out=True) '/fcn?query' >>> filter_url('http://domain.com/welcome/default/fcn#anchor', out=True) '/fcn#anchor' >>> filter_url('http://domain.com/welcome/default/fcn?query#anchor',", "this policy. # acfe_match: regex for valid application, controller, function,", "/a/c/f.e # file_match: regex for valid file (used for static", "True (default), hyphens in incoming /a/c/f fields are converted to", "acfe_match = r'\\w+$', # legal app/ctlr/fcn/ext # file_match = r'(\\w+[-=./]?)+$',", "valid args # This validation provides a measure of security.", "\"ticket\" key. # error_message = '<html><body><h1>Invalid request</h1></body></html>' # error_message_ticket =", "request</h1></body></html>' # error_message_ticket = '<html><body><h1>Internal error</h1>Ticket issued: <a href=\"/admin/default/ticket/%(ticket)s\" target=\"_blank\">%(ticket)s</a></body></html>'", "BAD REQUEST [invalid controller] >>> filter_url('http://domain.com/admin/ctl/bad!fcn') Traceback (most recent call", "'index', # default_language = None, # languages = None, #", "the effective router is: # the built-in default base router", "to override this policy. # acfe_match: regex for valid application,", "The default_language, if any, is omitted from the URL. #", "filter_url('https://domain.com/app/ctr/fcn', out=True) '/app/ctr/fcn' >>> filter_url('https://domain.com/welcome/ctr/fcn', out=True) '/ctr/fcn' >>> filter_url('https://domain.com/welcome/default/fcn', out=True)", "# This simple router set overrides only the default application", "sense only in an application-specific router. # The remaining members", "it is taken from request.language. # If languages=None, language support", "routing parameters. # # For each request, the effective router", "router (as defaults for all applications) # or in application-specific", "in an incoming URL after # the (optional) application and", "is copied to # request.language; for outgoing URLs it is", "Each application has its own root-static files. # domain: the", "query string are not affected. # map_static: By default, the", "in charge of error handling # # error_handler = dict(application='error',", "the selected app plus 'static' # or None to disable", "= 'DEFAULT', # default_function = 'index', # default_language = None,", "overrides for method and remote host: filter_url(url, method='get', remote='0.0.0.0', out=False)", "applications) # or in application-specific routers. # # default_controller: name", "default_application: default application name # applications: list of all recognized", "router. # The remaining members can appear in the BASE", "but provides full rewrite functionality. routers = dict( # base", "the removal of application names from outgoing URLs. # domains:", "are None): # # default_router = dict( # default_application =", "legal app/ctlr/fcn/ext # file_match = r'(\\w+[-=./]?)+$', # legal file (path)", "REQUEST [invalid arg <bad!arg>] >>> filter_url('https://domain.com/app/ctr/fcn', out=True) '/app/ctr/fcn' >>> filter_url('https://domain.com/welcome/ctr/fcn',", "400) to a specified # path. If you wish to", "BASE router (as defaults for all applications) # or in", "['abc']\" >>> filter_url('http://domain.com/default/index/a bc') \"/welcome/default/index ['a bc']\" >>> filter_url('http://domain.com/admin/bad!ctl') Traceback", "makes sense only in an application-specific router. # The remaining", "when they appear in an incoming URL after # the", "in the BASE router) # map_hyphen: If True (default), hyphens", "domain that maps to this application (alternative to using domains", "'DEFAULT', # default_function = 'index', # default_language = None, #", "controllers = [], # don't remove controller names from admin", "to the current application's static/ directory) # Each application has", "(status codes >= 400) to a specified # path. If", "target=\"_blank\">%(ticket)s</a></body></html>' def __routes_doctest(): ''' Dummy function for doctesting routes.py. Use", "incoming /a/c/f fields are converted to underscores, # and back", "en, it-it) optionally appears in the URL following # the", "valid application, controller, function, extension /a/c/f.e # file_match: regex for", "application name, # but provides full rewrite functionality. routers =", "are always treated as an application names when they appear", "default_router = dict( # default_application = 'init', # applications =", "controllers are always treated as language names when they appear", "default_language = None, # languages = None, # root_static =", "If languages=None, language support is disabled. # The default_language, if", "default values (undefined members are None): # # default_router =", "HTTP: 400 BAD REQUEST [invalid controller] >>> filter_url('http://domain.com/admin/ctl/bad!fcn') Traceback (most", "name of default controller # default_function: name of default function", "selected app plus 'static' # or None to disable controller-name", "# ] # specify action in charge of error handling", "utf-8 -*- # routers are dictionaries of URL routing parameters.", ">>> filter_url('https://domain.com/app/ctr/fcn', out=True) '/app/ctr/fcn' >>> filter_url('https://domain.com/welcome/ctr/fcn', out=True) '/ctr/fcn' >>> filter_url('https://domain.com/welcome/default/fcn',", "from root # (mapped to the current application's static/ directory)", "URL after # the (optional) application and language names. #", "# value in 'appName/HTTPstatusCode' format. ( Only HTTP codes >=", "= None, # map_hyphen = True, # acfe_match = r'\\w+$',", "In the event that the error-handling page itself returns an", "as language names when they appear in an incoming URL", "itself returns an error, web2py will # fall back to", "out=True) '/fcn' >>> filter_url('https://domain.com/welcome/default/index', out=True) '/' >>> filter_url('https://domain.com/welcome/appadmin/index', out=True) '/appadmin'", "'/fcn#anchor' >>> filter_url('http://domain.com/welcome/default/fcn?query#anchor', out=True) '/fcn?query#anchor' >>> filter_url('http://domain.com/appadmin/fcn-1') '/welcome/appadmin/fcn_1' >>> filter_url('http://domain.com/welcome/appadmin/fcn_1',", "the application (which may be omitted). For incoming URLs, the", "updated by the app-specific router in routes.py routers (if any),", "None to disable the removal of application names from outgoing", "language support is disabled. # The default_language, if any, is", "here. # ErrorMessageTicket takes a string format dictionary containing (only)", "function] >>> filter_url('http://domain.com/admin/ctl/fcn.bad!ext') Traceback (most recent call last): ... HTTP:", "also use # '*' as a wildcard. # # The", "# base router BASE = dict( default_application = 'welcome', ),", "# the built-in default base router (shown below), # updated", "args_match = r'([\\w@ -]+[=.]?)+$', # legal arg in args #", "a string format dictionary containing (only) the # \"ticket\" key.", "# -*- coding: utf-8 -*- # routers are dictionaries of", "args and the query string are not affected. # map_static:", ",(r'*/*', r'/init/error/index') # ] # specify action in charge of", "filter_url('http://domain.com/welcome/default/fcn?query', out=True) '/fcn?query' >>> filter_url('http://domain.com/welcome/default/fcn#anchor', out=True) '/fcn#anchor' >>> filter_url('http://domain.com/welcome/default/fcn?query#anchor', out=True)", "the domain that maps to this application (alternative to using", "For each request, the effective router is: # the built-in", "400 BAD REQUEST [invalid arg <bad!arg>] >>> filter_url('https://domain.com/app/ctr/fcn', out=True) '/app/ctr/fcn'", "None, # root_static = ['favicon.ico', 'robots.txt'], # domains = None,", "from outgoing URLs. # domains: optional dict mapping domain names", "filter_url('http://domain.com/appadmin/fcn-1') '/welcome/appadmin/fcn_1' >>> filter_url('http://domain.com/welcome/appadmin/fcn_1', out=True) '/appadmin/fcn-1' >>> filter_url('http://domain.com/examples/appadmin/fcn-1') '/examples/appadmin/fcn_1' >>>", "filter_url() accepts overrides for method and remote host: filter_url(url, method='get',", "takes a string format dictionary containing (only) the # \"ticket\"", "# the (optional) application name. # default_language # The language", "default_language # The language code (for example: en, it-it) optionally", "and remote host: filter_url(url, method='get', remote='0.0.0.0', out=False) filter_err() accepts overrides", "# legal arg in args # ) # # See", "use # '*' as a wildcard. # # The error", "URL following # the application (which may be omitted). For", "include a port number: domain.com:8080 # The application name can", "arg <bad!arg>] >>> filter_url('https://domain.com/app/ctr/fcn', out=True) '/app/ctr/fcn' >>> filter_url('https://domain.com/welcome/ctr/fcn', out=True) '/ctr/fcn'", "URLs and stripped from all incoming URLs # # Note:", "out=True) '/fcn?query' >>> filter_url('http://domain.com/welcome/default/fcn#anchor', out=True) '/fcn#anchor' >>> filter_url('http://domain.com/welcome/default/fcn?query#anchor', out=True) '/fcn?query#anchor'", "application names when they appear first in an incoming URL.", "application is not stripped from static URLs. Set map_static=True #", "(for example: en, it-it) optionally appears in the URL following", "list of all recognized applications, or 'ALL' to use all", "names. # languages: list of all supported languages # Names", "an incoming URL after # the (optional) application name. #", "You can customize them here. # ErrorMessageTicket takes a string", "supplies default values (undefined members are None): # # default_router", "affected. # map_static: By default, the default application is not", "all incoming URLs # # Note: default_application, applications, domains &", "static files accessed from root # (mapped to the current", "ErrorMessageTicket takes a string format dictionary containing (only) the #", "value in 'appName/HTTPstatusCode' format. ( Only HTTP codes >= 400", "of all recognized applications, or 'ALL' to use all currently", "a path fragment that is prefixed to all outgoing URLs", ">>> filter_url('http://domain.com/index/abc') \"/welcome/default/index ['abc']\" >>> filter_url('http://domain.com/default/abc.css') '/welcome/default/abc.css' >>> filter_url('http://domain.com/default/index/abc') \"/welcome/default/index", "name can include a port number: domain.com:8080 # The application", "override this policy. # acfe_match: regex for valid application, controller,", "to use error-handling redirects, uncomment the tuple # below. You", "following # the application (which may be omitted). For incoming", "URLs # # Note: default_application, applications, domains & path_prefix are", "admin URLs map_hyphen = False, # don't map hyphens to", "# root_static: list of static files accessed from root #", "from admin URLs map_hyphen = False, # don't map hyphens", "# to override this policy. # acfe_match: regex for valid", "Set map_static=True # to override this policy. # acfe_match: regex", "= r'\\w+$', # legal app/ctlr/fcn/ext # file_match = r'(\\w+[-=./]?)+$', #", ">>> filter_url('http://domain.com/examples/appadmin/fcn-1') '/examples/appadmin/fcn_1' >>> filter_url('http://domain.com/examples/appadmin/fcn_1', out=True) '/examples/appadmin/fcn-1' >>> filter_url('http://domain.com/app/static/filename-with_underscore', out=True)", "[invalid function] >>> filter_url('http://domain.com/admin/ctl/fcn.bad!ext') Traceback (most recent call last): ...", "to. You may also use # '*' as a wildcard.", "as controller names when they appear in an incoming URL", "# Note: default_application, applications, domains & path_prefix are permitted only", "# For each request, the effective router is: # the", "to use all controllers in the selected app plus 'static'", "The remaining members can appear in the BASE router (as", "any) # # # Router members: # # default_application: default", "default_controller = 'default', # controllers = 'DEFAULT', # default_function =", "URLs map_hyphen = False, # don't map hyphens to underscores", "validation. # # # The built-in default router supplies default", "or in application-specific routers. # # default_controller: name of default", "the error code and ticket as # variables. Traceback information", ">>> filter_url('http://domain.com/default/abc.css') '/welcome/default/abc.css' >>> filter_url('http://domain.com/default/index/abc') \"/welcome/default/index ['abc']\" >>> filter_url('http://domain.com/default/index/a bc')", ") # # See rewrite.map_url_in() and rewrite.map_url_out() for implementation details.", "r'\\w+$', # legal app/ctlr/fcn/ext # file_match = r'(\\w+[-=./]?)+$', # legal", "filter_url('http://domain.com/default/index/abc') \"/welcome/default/index ['abc']\" >>> filter_url('http://domain.com/default/index/a bc') \"/welcome/default/index ['a bc']\" >>>", "filter_url('http://domain.com/examples/appadmin/fcn_1', out=True) '/examples/appadmin/fcn-1' >>> filter_url('http://domain.com/app/static/filename-with_underscore', out=True) '/app/static/filename-with_underscore' >>> os.path.relpath(filter_url('http://domain.com/admin/static/filename-with_underscore')) 'applications/admin/static/filename-with_underscore'", "Names in controllers are always treated as language names when", "security. # If it is changed, the application perform its", "each request, the effective router is: # the built-in default", ") and the value as a path to redirect the", "'/examples/appadmin/fcn_1' >>> filter_url('http://domain.com/examples/appadmin/fcn_1', out=True) '/examples/appadmin/fcn-1' >>> filter_url('http://domain.com/app/static/filename-with_underscore', out=True) '/app/static/filename-with_underscore' >>>", "# file_match = r'(\\w+[-=./]?)+$', # legal file (path) name #", "'/fcn?query' >>> filter_url('http://domain.com/welcome/default/fcn#anchor', out=True) '/fcn#anchor' >>> filter_url('http://domain.com/welcome/default/fcn?query#anchor', out=True) '/fcn?query#anchor' >>>", "always treated as controller names when they appear in an", "# args_match: regex for valid args # This validation provides", "# path. If you wish to use error-handling redirects, uncomment", "BAD REQUEST [invalid arg <bad!arg>] >>> filter_url('https://domain.com/app/ctr/fcn', out=True) '/app/ctr/fcn' >>>", "'<html><body><h1>Invalid request</h1></body></html>' # error_message_ticket = '<html><body><h1>Internal error</h1>Ticket issued: <a href=\"/admin/default/ticket/%(ticket)s\"", "applications, domains & path_prefix are permitted only in the BASE", "filter_url('https://domain.com/welcome/default/index', out=True) '/' >>> filter_url('https://domain.com/welcome/appadmin/index', out=True) '/appadmin' >>> filter_url('http://domain.com/welcome/default/fcn?query', out=True)", "for implementation details. # This simple router set overrides only", "using domains in the BASE router) # map_hyphen: If True", "controllers) # controllers: list of valid controllers in selected app", "fall back to its old static responses. You can customize", "out=False) filter_err() accepts overrides for application and ticket: filter_err(status, application='app',", "can appear in the BASE router (as defaults for all", "effective router is: # the built-in default base router (shown", "# ,(r'*/*', r'/init/error/index') # ] # specify action in charge", "'/welcome/default/abc' >>> filter_url('http://domain.com/index/abc') \"/welcome/default/index ['abc']\" >>> filter_url('http://domain.com/default/abc.css') '/welcome/default/abc.css' >>> filter_url('http://domain.com/default/index/abc')", "r'/init/error/index') # ] # specify action in charge of error", "# don't remove controller names from admin URLs map_hyphen =", "names # The domain name can include a port number:", "treated as an application names when they appear first in", "routes.py. Use filter_url() to test incoming or outgoing routes; filter_err()", "default function (all controllers) # controllers: list of valid controllers", "filter_url('http://domain.com/index/abc') \"/welcome/default/index ['abc']\" >>> filter_url('http://domain.com/default/abc.css') '/welcome/default/abc.css' >>> filter_url('http://domain.com/default/index/abc') \"/welcome/default/index ['abc']\"", "['favicon.ico', 'robots.txt'], # domains = None, # map_hyphen = True,", "(most recent call last): ... HTTP: 400 BAD REQUEST [invalid", "updated by the BASE router in routes.py routers, # updated", "coding: utf-8 -*- # routers are dictionaries of URL routing", ">>> filter_url('http://domain.com/welcome/appadmin/fcn_1', out=True) '/appadmin/fcn-1' >>> filter_url('http://domain.com/examples/appadmin/fcn-1') '/examples/appadmin/fcn_1' >>> filter_url('http://domain.com/examples/appadmin/fcn_1', out=True)", "provides a measure of security. # If it is changed,", "tuple # below. You can customize responses by adding a", "last): ... HTTP: 400 BAD REQUEST [invalid controller] >>> filter_url('http://domain.com/admin/ctl/bad!fcn')", "filter_url('https://domain.com/welcome/ctr/fcn', out=True) '/ctr/fcn' >>> filter_url('https://domain.com/welcome/default/fcn', out=True) '/fcn' >>> filter_url('https://domain.com/welcome/default/index', out=True)", "# error_message = '<html><body><h1>Invalid request</h1></body></html>' # error_message_ticket = '<html><body><h1>Internal error</h1>Ticket", "language names when they appear in an incoming URL after", "list of static files accessed from root # (mapped to", "method='get', remote='0.0.0.0', out=False) filter_err() accepts overrides for application and ticket:", "redirects all HTTP errors (status codes >= 400) to a", "uncomment the tuple # below. You can customize responses by", "domain.com:8080 # The application name can include a controller: appx/ctlrx", "when they appear first in an incoming URL. # Set", "# # For each request, the effective router is: #", "its own root-static files. # domain: the domain that maps", "None to disable controller-name removal. # Names in controllers are", "(undefined members are None): # # default_router = dict( #", "args # ) # # See rewrite.map_url_in() and rewrite.map_url_out() for", "accessed from root # (mapped to the current application's static/", "underscores ), ) # Error-handling redirects all HTTP errors (status", "controllers in selected app # or \"DEFAULT\" to use all", "& path_prefix are permitted only in the BASE router, #", "code and ticket as # variables. Traceback information will be", "error-handling page itself returns an error, web2py will # fall", "call last): ... HTTP: 400 BAD REQUEST [invalid function] >>>", "map_hyphen = True, # acfe_match = r'\\w+$', # legal app/ctlr/fcn/ext", "'/appadmin' >>> filter_url('http://domain.com/welcome/default/fcn?query', out=True) '/fcn?query' >>> filter_url('http://domain.com/welcome/default/fcn#anchor', out=True) '/fcn#anchor' >>>", "app/ctlr/fcn/ext # file_match = r'(\\w+[-=./]?)+$', # legal file (path) name", "plus 'static' # or None to disable controller-name removal. #", "underscores, # and back to hyphens in outgoing URLs. Language,", ">>> filter_err(399) 399 >>> filter_err(400) 400 ''' pass if __name__", "out=True) '/fcn#anchor' >>> filter_url('http://domain.com/welcome/default/fcn?query#anchor', out=True) '/fcn?query#anchor' >>> filter_url('http://domain.com/appadmin/fcn-1') '/welcome/appadmin/fcn_1' >>>", "customize them here. # ErrorMessageTicket takes a string format dictionary", "'welcome' >>> filter_url('http://domain.com/welcome', app=True) 'welcome' >>> os.path.relpath(filter_url('http://domain.com/favicon.ico')) 'applications/welcome/static/favicon.ico' >>> filter_url('http://domain.com/abc')", "first in an incoming URL. # Set applications to None", ">>> filter_url('http://domain.com/app/static/filename-with_underscore', out=True) '/app/static/filename-with_underscore' >>> os.path.relpath(filter_url('http://domain.com/admin/static/filename-with_underscore')) 'applications/admin/static/filename-with_underscore' >>> filter_err(200) 200", "application (alternative to using domains in the BASE router) #", "import load, filter_url, filter_err, get_effective_router >>> load(routes=os.path.basename(__file__)) >>> filter_url('http://domain.com/abc', app=True)", "as a wildcard. # # The error handling page is", "a tuple entry with the first # value in 'appName/HTTPstatusCode'", "any, is omitted from the URL. # root_static: list of", "outgoing URLs and stripped from all incoming URLs # #", "# languages: list of all supported languages # Names in", "URL. # root_static: list of static files accessed from root", "an application-specific router. # The remaining members can appear in", "call last): ... HTTP: 400 BAD REQUEST [invalid arg <bad!arg>]", "# # # Router members: # # default_application: default application", "name # args_match = r'([\\w@ -]+[=.]?)+$', # legal arg in", "issued: <a href=\"/admin/default/ticket/%(ticket)s\" target=\"_blank\">%(ticket)s</a></body></html>' def __routes_doctest(): ''' Dummy function for", "ticket as # variables. Traceback information will be stored in", "# applications: list of all recognized applications, or 'ALL' to", "default, the default application is not stripped from static URLs.", "string are not affected. # map_static: By default, the default", "treated as language names when they appear in an incoming", "arg in args # ) # # See rewrite.map_url_in() and", "399 >>> filter_err(400) 400 ''' pass if __name__ == '__main__':", "# Names in applications are always treated as an application", "it is changed, the application perform its own validation. #", "The application name can include a controller: appx/ctlrx # path_prefix:", "None, # languages = None, # root_static = ['favicon.ico', 'robots.txt'],", "# # default_controller: name of default controller # default_function: name", "REQUEST [invalid function] >>> filter_url('http://domain.com/admin/ctl/fcn.bad!ext') Traceback (most recent call last):", "filter_url('http://domain.com/abc') '/welcome/default/abc' >>> filter_url('http://domain.com/index/abc') \"/welcome/default/index ['abc']\" >>> filter_url('http://domain.com/default/abc.css') '/welcome/default/abc.css' >>>", "from the URL. # root_static: list of static files accessed", "# default_function: name of default function (all controllers) # controllers:", "applications are always treated as an application names when they", "taken from request.language. # If languages=None, language support is disabled.", "(which may be omitted). For incoming URLs, the code is", "static URLs. Set map_static=True # to override this policy. #", "# # The error handling page is also passed the", "URL. # Set applications to None to disable the removal", "-]+[=.]?)+$', # legal arg in args # ) # #", "members can appear in the BASE router (as defaults for", "in applications are always treated as an application names when", "in 'appName/HTTPstatusCode' format. ( Only HTTP codes >= 400 are", "files. # domain: the domain that maps to this application", "the URL. # root_static: list of static files accessed from", "filter_url('http://domain.com/welcome/appadmin/fcn_1', out=True) '/appadmin/fcn-1' >>> filter_url('http://domain.com/examples/appadmin/fcn-1') '/examples/appadmin/fcn_1' >>> filter_url('http://domain.com/examples/appadmin/fcn_1', out=True) '/examples/appadmin/fcn-1'", "the first # value in 'appName/HTTPstatusCode' format. ( Only HTTP", "[invalid controller] >>> filter_url('http://domain.com/admin/ctl/bad!fcn') Traceback (most recent call last): ...", "#!/usr/bin/python # -*- coding: utf-8 -*- # routers are dictionaries", "# routes_onerror = [ # (r'init/400', r'/init/default/login') # ,(r'init/*', r'/init/static/fail.html')", "own root-static files. # domain: the domain that maps to", "to using domains in the BASE router) # map_hyphen: If", "(alternative to using domains in the BASE router) # map_hyphen:", "'welcome', ), # 'admin' application router admin = dict( controllers", "legal arg in args # ) # # See rewrite.map_url_in()", "# The error handling page is also passed the error", "(optional) application name. # default_language # The language code (for", "Dummy function for doctesting routes.py. Use filter_url() to test incoming", "application has its own root-static files. # domain: the domain", "# controller='default', # function='index') # In the event that the", "default_application, applications, domains & path_prefix are permitted only in the", "# This validation provides a measure of security. # If", "port number: domain.com:8080 # The application name can include a", "in controllers are always treated as language names when they", "filter_err, get_effective_router >>> load(routes=os.path.basename(__file__)) >>> filter_url('http://domain.com/abc', app=True) 'welcome' >>> filter_url('http://domain.com/welcome',", "# default_controller = 'default', # controllers = 'DEFAULT', # default_function", "or outgoing routes; filter_err() for error redirection. filter_url() accepts overrides", "BASE router in routes.py routers, # updated by the app-specific", "= [], # don't remove controller names from admin URLs", "format dictionary containing (only) the # \"ticket\" key. # error_message", "REQUEST [invalid extension] >>> filter_url('http://domain.com/admin/ctl/fcn/bad!arg') Traceback (most recent call last):", "controllers = 'DEFAULT', # default_function = 'index', # default_language =", "'applications/admin/static/filename-with_underscore' >>> filter_err(200) 200 >>> filter_err(399) 399 >>> filter_err(400) 400", "name can include a controller: appx/ctlrx # path_prefix: a path", "of valid controllers in selected app # or \"DEFAULT\" to", "and domain makes sense only in an application-specific router. #", "= r'([\\w@ -]+[=.]?)+$', # legal arg in args # )", "file names) # args_match: regex for valid args # This", "to test incoming or outgoing routes; filter_err() for error redirection.", "support is disabled. # The default_language, if any, is omitted", "controllers: list of valid controllers in selected app # or", "os >>> import gluon.main >>> from gluon.rewrite import load, filter_url,", "filter_url('http://domain.com/welcome/default/fcn#anchor', out=True) '/fcn#anchor' >>> filter_url('http://domain.com/welcome/default/fcn?query#anchor', out=True) '/fcn?query#anchor' >>> filter_url('http://domain.com/appadmin/fcn-1') '/welcome/appadmin/fcn_1'", "# # routes_onerror = [ # (r'init/400', r'/init/default/login') # ,(r'init/*',", "of error handling # # error_handler = dict(application='error', # controller='default',", "'/' >>> filter_url('https://domain.com/welcome/appadmin/index', out=True) '/appadmin' >>> filter_url('http://domain.com/welcome/default/fcn?query', out=True) '/fcn?query' >>>", "__routes_doctest(): ''' Dummy function for doctesting routes.py. Use filter_url() to", "default application name # applications: list of all recognized applications,", "default controller # default_function: name of default function (all controllers)", "of default function (all controllers) # controllers: list of valid", "dict( default_application = 'welcome', ), # 'admin' application router admin", ">>> load(routes=os.path.basename(__file__)) >>> filter_url('http://domain.com/abc', app=True) 'welcome' >>> filter_url('http://domain.com/welcome', app=True) 'welcome'", "default base router (shown below), # updated by the BASE", "domains & path_prefix are permitted only in the BASE router,", "remaining members can appear in the BASE router (as defaults", "it-it) optionally appears in the URL following # the application", "URLs, the code is copied to # request.language; for outgoing", "for all applications) # or in application-specific routers. # #", "perform its own validation. # # # The built-in default", "# # The built-in default router supplies default values (undefined", "# ) # # See rewrite.map_url_in() and rewrite.map_url_out() for implementation", "filter_url() to test incoming or outgoing routes; filter_err() for error", "# domains: optional dict mapping domain names to application names", "treated as controller names when they appear in an incoming", "has its own root-static files. # domain: the domain that", "path_prefix: a path fragment that is prefixed to all outgoing", "filter_err() for error redirection. filter_url() accepts overrides for method and", "= 'index', # default_language = None, # languages = None,", "Use filter_url() to test incoming or outgoing routes; filter_err() for", "BASE router) # map_hyphen: If True (default), hyphens in incoming", "request, the effective router is: # the built-in default base", "from gluon.rewrite import load, filter_url, filter_err, get_effective_router >>> load(routes=os.path.basename(__file__)) >>>", "Error-handling redirects all HTTP errors (status codes >= 400) to", "-*- coding: utf-8 -*- # routers are dictionaries of URL", "controllers are always treated as controller names when they appear", "True, # acfe_match = r'\\w+$', # legal app/ctlr/fcn/ext # file_match", "always treated as an application names when they appear first", "filter_url('https://domain.com/welcome/appadmin/index', out=True) '/appadmin' >>> filter_url('http://domain.com/welcome/default/fcn?query', out=True) '/fcn?query' >>> filter_url('http://domain.com/welcome/default/fcn#anchor', out=True)", "application and language names. # languages: list of all supported", "# Error-handling redirects all HTTP errors (status codes >= 400)", "not affected. # map_static: By default, the default application is", "recognized applications, or 'ALL' to use all currently installed applications", "is changed, the application perform its own validation. # #", "filter_url('http://domain.com/app/static/filename-with_underscore', out=True) '/app/static/filename-with_underscore' >>> os.path.relpath(filter_url('http://domain.com/admin/static/filename-with_underscore')) 'applications/admin/static/filename-with_underscore' >>> filter_err(200) 200 >>>", "members are None): # # default_router = dict( # default_application", ">>> filter_err(200) 200 >>> filter_err(399) 399 >>> filter_err(400) 400 '''", "'ALL' to use all currently installed applications # Names in", "incoming URLs # # Note: default_application, applications, domains & path_prefix", "the built-in default base router (shown below), # updated by", "validation provides a measure of security. # If it is", "is: # the built-in default base router (shown below), #", "or \"DEFAULT\" to use all controllers in the selected app", "# # default_router = dict( # default_application = 'init', #", ">>> filter_url('http://domain.com/abc') '/welcome/default/abc' >>> filter_url('http://domain.com/index/abc') \"/welcome/default/index ['abc']\" >>> filter_url('http://domain.com/default/abc.css') '/welcome/default/abc.css'", "filter_err(status, application='app', ticket='tkt') >>> import os >>> import gluon.main >>>", "ticket. # # routes_onerror = [ # (r'init/400', r'/init/default/login') #", "overrides only the default application name, # but provides full", "functionality. routers = dict( # base router BASE = dict(", "router, # and domain makes sense only in an application-specific", "# acfe_match = r'\\w+$', # legal app/ctlr/fcn/ext # file_match =", "overrides for application and ticket: filter_err(status, application='app', ticket='tkt') >>> import", "appears in the URL following # the application (which may", "of security. # If it is changed, the application perform", "as # variables. Traceback information will be stored in the", "(if any), # updated by the app-specific router from applcations/app/routes.py", "error-handling redirects, uncomment the tuple # below. You can customize", "in the URL following # the application (which may be", "the code is copied to # request.language; for outgoing URLs", "# map_hyphen = True, # acfe_match = r'\\w+$', # legal", "= dict( # base router BASE = dict( default_application =", "test incoming or outgoing routes; filter_err() for error redirection. filter_url()", "['a bc']\" >>> filter_url('http://domain.com/admin/bad!ctl') Traceback (most recent call last): ...", ">>> filter_url('http://domain.com/admin/ctl/bad!fcn') Traceback (most recent call last): ... HTTP: 400", "# (mapped to the current application's static/ directory) # Each", "error handling # # error_handler = dict(application='error', # controller='default', #", "hyphens to underscores ), ) # Error-handling redirects all HTTP", "dict( controllers = [], # don't remove controller names from", "of URL routing parameters. # # For each request, the", "filter_url('http://domain.com/admin/ctl/fcn/bad!arg') Traceback (most recent call last): ... HTTP: 400 BAD", "controller: appx/ctlrx # path_prefix: a path fragment that is prefixed", "# or \"DEFAULT\" to use all controllers in the selected", "\"DEFAULT\" to use all controllers in the selected app plus", "Note: default_application, applications, domains & path_prefix are permitted only in", "\"/welcome/default/index ['a bc']\" >>> filter_url('http://domain.com/admin/bad!ctl') Traceback (most recent call last):", ">>> filter_url('http://domain.com/welcome/default/fcn#anchor', out=True) '/fcn#anchor' >>> filter_url('http://domain.com/welcome/default/fcn?query#anchor', out=True) '/fcn?query#anchor' >>> filter_url('http://domain.com/appadmin/fcn-1')", "names when they appear first in an incoming URL. #", "# languages = None, # root_static = ['favicon.ico', 'robots.txt'], #", "# The application name can include a controller: appx/ctlrx #", "applications = 'ALL', # default_controller = 'default', # controllers =", "in the BASE router, # and domain makes sense only", "incoming URLs, the code is copied to # request.language; for", "can customize them here. # ErrorMessageTicket takes a string format", "for method and remote host: filter_url(url, method='get', remote='0.0.0.0', out=False) filter_err()", "first # value in 'appName/HTTPstatusCode' format. ( Only HTTP codes", "method and remote host: filter_url(url, method='get', remote='0.0.0.0', out=False) filter_err() accepts", "# routed. ) and the value as a path to", "the BASE router, # and domain makes sense only in", "web2py will # fall back to its old static responses.", "# The domain name can include a port number: domain.com:8080", "r'/init/static/cantfind.html') # ,(r'*/*', r'/init/error/index') # ] # specify action in", "to use all currently installed applications # Names in applications", "defaults for all applications) # or in application-specific routers. #", "# default_application: default application name # applications: list of all", "# variables. Traceback information will be stored in the ticket.", "error redirection. filter_url() accepts overrides for method and remote host:", "# The language code (for example: en, it-it) optionally appears", "regex for valid file (used for static file names) #", "load(routes=os.path.basename(__file__)) >>> filter_url('http://domain.com/abc', app=True) 'welcome' >>> filter_url('http://domain.com/welcome', app=True) 'welcome' >>>", "static file names) # args_match: regex for valid args #", "names) # args_match: regex for valid args # This validation", "outgoing URLs. Language, args and the query string are not", "in routes.py routers (if any), # updated by the app-specific", "the (optional) application name. # default_language # The language code", "variables. Traceback information will be stored in the ticket. #", "set overrides only the default application name, # but provides", "the app-specific router from applcations/app/routes.py routers (if any) # #", "= 'init', # applications = 'ALL', # default_controller = 'default',", "# and back to hyphens in outgoing URLs. Language, args", "fragment that is prefixed to all outgoing URLs and stripped", "= ['favicon.ico', 'robots.txt'], # domains = None, # map_hyphen =", "of static files accessed from root # (mapped to the", "dict( # base router BASE = dict( default_application = 'welcome',", "appear first in an incoming URL. # Set applications to", "default_function = 'index', # default_language = None, # languages =", "# 'admin' application router admin = dict( controllers = [],", "filter_url, filter_err, get_effective_router >>> load(routes=os.path.basename(__file__)) >>> filter_url('http://domain.com/abc', app=True) 'welcome' >>>", "disable controller-name removal. # Names in controllers are always treated", "to a specified # path. If you wish to use", "fields are converted to underscores, # and back to hyphens", "filter_url('http://domain.com/examples/appadmin/fcn-1') '/examples/appadmin/fcn_1' >>> filter_url('http://domain.com/examples/appadmin/fcn_1', out=True) '/examples/appadmin/fcn-1' >>> filter_url('http://domain.com/app/static/filename-with_underscore', out=True) '/app/static/filename-with_underscore'", "(as defaults for all applications) # or in application-specific routers.", "router is: # the built-in default base router (shown below),", ">>> filter_url('http://domain.com/default/index/abc') \"/welcome/default/index ['abc']\" >>> filter_url('http://domain.com/default/index/a bc') \"/welcome/default/index ['a bc']\"", "in application-specific routers. # # default_controller: name of default controller", "accepts overrides for application and ticket: filter_err(status, application='app', ticket='tkt') >>>", "if any, is omitted from the URL. # root_static: list", "router in routes.py routers, # updated by the app-specific router", "updated by the app-specific router from applcations/app/routes.py routers (if any)", "application's static/ directory) # Each application has its own root-static", "simple router set overrides only the default application name, #", "an incoming URL after # the (optional) application and language", "# default_function = 'index', # default_language = None, # languages", "error handling page is also passed the error code and", "names to application names # The domain name can include", "application name can include a controller: appx/ctlrx # path_prefix: a", "HTTP codes >= 400 are # routed. ) and the", "a wildcard. # # The error handling page is also", "selected app # or \"DEFAULT\" to use all controllers in", "remove controller names from admin URLs map_hyphen = False, #", "... HTTP: 400 BAD REQUEST [invalid controller] >>> filter_url('http://domain.com/admin/ctl/bad!fcn') Traceback", "domain makes sense only in an application-specific router. # The", "routers, # updated by the app-specific router in routes.py routers", "a measure of security. # If it is changed, the", "200 >>> filter_err(399) 399 >>> filter_err(400) 400 ''' pass if", "you wish to use error-handling redirects, uncomment the tuple #", "You may also use # '*' as a wildcard. #", "domain names to application names # The domain name can", "routes.py routers (if any), # updated by the app-specific router", "# below. You can customize responses by adding a tuple", "are always treated as language names when they appear in", "they appear first in an incoming URL. # Set applications", "after # the (optional) application and language names. # languages:", "key. # error_message = '<html><body><h1>Invalid request</h1></body></html>' # error_message_ticket = '<html><body><h1>Internal", ">>> filter_url('http://domain.com/default/index/a bc') \"/welcome/default/index ['a bc']\" >>> filter_url('http://domain.com/admin/bad!ctl') Traceback (most", "URLs. # domains: optional dict mapping domain names to application", "regex for valid args # This validation provides a measure", "= '<html><body><h1>Invalid request</h1></body></html>' # error_message_ticket = '<html><body><h1>Internal error</h1>Ticket issued: <a", "400 BAD REQUEST [invalid extension] >>> filter_url('http://domain.com/admin/ctl/fcn/bad!arg') Traceback (most recent", "error</h1>Ticket issued: <a href=\"/admin/default/ticket/%(ticket)s\" target=\"_blank\">%(ticket)s</a></body></html>' def __routes_doctest(): ''' Dummy function", "= False, # don't map hyphens to underscores ), )", "controller-name removal. # Names in controllers are always treated as", "is not stripped from static URLs. Set map_static=True # to", "URLs. Language, args and the query string are not affected.", "The language code (for example: en, it-it) optionally appears in", "= True, # acfe_match = r'\\w+$', # legal app/ctlr/fcn/ext #", "in controllers are always treated as controller names when they", "# fall back to its old static responses. You can", "= None, # root_static = ['favicon.ico', 'robots.txt'], # domains =", "filter_err() accepts overrides for application and ticket: filter_err(status, application='app', ticket='tkt')", "= '<html><body><h1>Internal error</h1>Ticket issued: <a href=\"/admin/default/ticket/%(ticket)s\" target=\"_blank\">%(ticket)s</a></body></html>' def __routes_doctest(): '''", "in selected app # or \"DEFAULT\" to use all controllers", "(mapped to the current application's static/ directory) # Each application", "domain: the domain that maps to this application (alternative to", "load, filter_url, filter_err, get_effective_router >>> load(routes=os.path.basename(__file__)) >>> filter_url('http://domain.com/abc', app=True) 'welcome'", "= 'welcome', ), # 'admin' application router admin = dict(", "file (used for static file names) # args_match: regex for", "the user to. You may also use # '*' as", "for doctesting routes.py. Use filter_url() to test incoming or outgoing", "and back to hyphens in outgoing URLs. Language, args and", "# default_language # The language code (for example: en, it-it)", "By default, the default application is not stripped from static", "# request.language; for outgoing URLs it is taken from request.language.", "# routers are dictionaries of URL routing parameters. # #", "the (optional) application and language names. # languages: list of", "# Each application has its own root-static files. # domain:", "redirects, uncomment the tuple # below. You can customize responses", "valid file (used for static file names) # args_match: regex", "customize responses by adding a tuple entry with the first", "# acfe_match: regex for valid application, controller, function, extension /a/c/f.e", "root # (mapped to the current application's static/ directory) #", "name, # but provides full rewrite functionality. routers = dict(", "wildcard. # # The error handling page is also passed", "parameters. # # For each request, the effective router is:", "(if any) # # # Router members: # # default_application:", "default_controller: name of default controller # default_function: name of default", "entry with the first # value in 'appName/HTTPstatusCode' format. (", "can include a controller: appx/ctlrx # path_prefix: a path fragment", "in args # ) # # See rewrite.map_url_in() and rewrite.map_url_out()", "code is copied to # request.language; for outgoing URLs it", "None): # # default_router = dict( # default_application = 'init',", "don't remove controller names from admin URLs map_hyphen = False,", "built-in default base router (shown below), # updated by the", "its old static responses. You can customize them here. #", "host: filter_url(url, method='get', remote='0.0.0.0', out=False) filter_err() accepts overrides for application", "filter_url(url, method='get', remote='0.0.0.0', out=False) filter_err() accepts overrides for application and", "the ticket. # # routes_onerror = [ # (r'init/400', r'/init/default/login')", "gluon.rewrite import load, filter_url, filter_err, get_effective_router >>> load(routes=os.path.basename(__file__)) >>> filter_url('http://domain.com/abc',", "path. If you wish to use error-handling redirects, uncomment the", "Only HTTP codes >= 400 are # routed. ) and", ">= 400 are # routed. ) and the value as", "['abc']\" >>> filter_url('http://domain.com/default/abc.css') '/welcome/default/abc.css' >>> filter_url('http://domain.com/default/index/abc') \"/welcome/default/index ['abc']\" >>> filter_url('http://domain.com/default/index/a", "filter_url('http://domain.com/default/index/a bc') \"/welcome/default/index ['a bc']\" >>> filter_url('http://domain.com/admin/bad!ctl') Traceback (most recent", "filter_url('http://domain.com/welcome', app=True) 'welcome' >>> os.path.relpath(filter_url('http://domain.com/favicon.ico')) 'applications/welcome/static/favicon.ico' >>> filter_url('http://domain.com/abc') '/welcome/default/abc' >>>", ">>> filter_url('https://domain.com/welcome/default/fcn', out=True) '/fcn' >>> filter_url('https://domain.com/welcome/default/index', out=True) '/' >>> filter_url('https://domain.com/welcome/appadmin/index',", "filter_url('http://domain.com/admin/ctl/fcn.bad!ext') Traceback (most recent call last): ... HTTP: 400 BAD", "filter_url('https://domain.com/welcome/default/fcn', out=True) '/fcn' >>> filter_url('https://domain.com/welcome/default/index', out=True) '/' >>> filter_url('https://domain.com/welcome/appadmin/index', out=True)", "filter_err(200) 200 >>> filter_err(399) 399 >>> filter_err(400) 400 ''' pass", "# # error_handler = dict(application='error', # controller='default', # function='index') #", "<bad!arg>] >>> filter_url('https://domain.com/app/ctr/fcn', out=True) '/app/ctr/fcn' >>> filter_url('https://domain.com/welcome/ctr/fcn', out=True) '/ctr/fcn' >>>", "list of valid controllers in selected app # or \"DEFAULT\"", "specify action in charge of error handling # # error_handler", "default application name, # but provides full rewrite functionality. routers", "function for doctesting routes.py. Use filter_url() to test incoming or", "file_match: regex for valid file (used for static file names)", "recent call last): ... HTTP: 400 BAD REQUEST [invalid function]", "in outgoing URLs. Language, args and the query string are", "application='app', ticket='tkt') >>> import os >>> import gluon.main >>> from", "name # applications: list of all recognized applications, or 'ALL'", "app-specific router in routes.py routers (if any), # updated by", "400 BAD REQUEST [invalid controller] >>> filter_url('http://domain.com/admin/ctl/bad!fcn') Traceback (most recent", "This simple router set overrides only the default application name,", "root_static: list of static files accessed from root # (mapped", "# # # The built-in default router supplies default values", "with the first # value in 'appName/HTTPstatusCode' format. ( Only", "<a href=\"/admin/default/ticket/%(ticket)s\" target=\"_blank\">%(ticket)s</a></body></html>' def __routes_doctest(): ''' Dummy function for doctesting", "''' Dummy function for doctesting routes.py. Use filter_url() to test", "appx/ctlrx # path_prefix: a path fragment that is prefixed to", "map_static: By default, the default application is not stripped from", "language names. # languages: list of all supported languages #", "application and ticket: filter_err(status, application='app', ticket='tkt') >>> import os >>>", "dictionary containing (only) the # \"ticket\" key. # error_message =", "below. You can customize responses by adding a tuple entry", "filter_url('http://domain.com/abc', app=True) 'welcome' >>> filter_url('http://domain.com/welcome', app=True) 'welcome' >>> os.path.relpath(filter_url('http://domain.com/favicon.ico')) 'applications/welcome/static/favicon.ico'", "to application names # The domain name can include a", "last): ... HTTP: 400 BAD REQUEST [invalid function] >>> filter_url('http://domain.com/admin/ctl/fcn.bad!ext')", "applications # Names in applications are always treated as an", "'/app/ctr/fcn' >>> filter_url('https://domain.com/welcome/ctr/fcn', out=True) '/ctr/fcn' >>> filter_url('https://domain.com/welcome/default/fcn', out=True) '/fcn' >>>", "URL after # the (optional) application name. # default_language #", "acfe_match: regex for valid application, controller, function, extension /a/c/f.e #", "extension] >>> filter_url('http://domain.com/admin/ctl/fcn/bad!arg') Traceback (most recent call last): ... HTTP:", "after # the (optional) application name. # default_language # The", "that maps to this application (alternative to using domains in", "the application perform its own validation. # # # The", "= r'(\\w+[-=./]?)+$', # legal file (path) name # args_match =", "the query string are not affected. # map_static: By default,", "responses by adding a tuple entry with the first #", "all currently installed applications # Names in applications are always", ">>> os.path.relpath(filter_url('http://domain.com/favicon.ico')) 'applications/welcome/static/favicon.ico' >>> filter_url('http://domain.com/abc') '/welcome/default/abc' >>> filter_url('http://domain.com/index/abc') \"/welcome/default/index ['abc']\"", ">>> filter_err(400) 400 ''' pass if __name__ == '__main__': import", "incoming URL after # the (optional) application name. # default_language", "# controllers: list of valid controllers in selected app #", "import gluon.main >>> from gluon.rewrite import load, filter_url, filter_err, get_effective_router", "remote='0.0.0.0', out=False) filter_err() accepts overrides for application and ticket: filter_err(status,", ">>> from gluon.rewrite import load, filter_url, filter_err, get_effective_router >>> load(routes=os.path.basename(__file__))", "remote host: filter_url(url, method='get', remote='0.0.0.0', out=False) filter_err() accepts overrides for", "bc') \"/welcome/default/index ['a bc']\" >>> filter_url('http://domain.com/admin/bad!ctl') Traceback (most recent call", "for static file names) # args_match: regex for valid args", "tuple entry with the first # value in 'appName/HTTPstatusCode' format.", ">= 400) to a specified # path. If you wish", "only the default application name, # but provides full rewrite", "passed the error code and ticket as # variables. Traceback", "application names # The domain name can include a port", "dictionaries of URL routing parameters. # # For each request,", "disabled. # The default_language, if any, is omitted from the", "400 are # routed. ) and the value as a", "for valid file (used for static file names) # args_match:", "For incoming URLs, the code is copied to # request.language;", "'/fcn?query#anchor' >>> filter_url('http://domain.com/appadmin/fcn-1') '/welcome/appadmin/fcn_1' >>> filter_url('http://domain.com/welcome/appadmin/fcn_1', out=True) '/appadmin/fcn-1' >>> filter_url('http://domain.com/examples/appadmin/fcn-1')", "of all supported languages # Names in controllers are always", "application perform its own validation. # # # The built-in", "for valid application, controller, function, extension /a/c/f.e # file_match: regex", "'init', # applications = 'ALL', # default_controller = 'default', #", "URLs. Set map_static=True # to override this policy. # acfe_match:", "app plus 'static' # or None to disable controller-name removal.", "are permitted only in the BASE router, # and domain", "outgoing URLs it is taken from request.language. # If languages=None,", "/a/c/f fields are converted to underscores, # and back to", "# updated by the BASE router in routes.py routers, #", "dict(application='error', # controller='default', # function='index') # In the event that", "old static responses. You can customize them here. # ErrorMessageTicket", "), ) # Error-handling redirects all HTTP errors (status codes", "controllers in the selected app plus 'static' # or None", "Names in applications are always treated as an application names", "in incoming /a/c/f fields are converted to underscores, # and", "'/examples/appadmin/fcn-1' >>> filter_url('http://domain.com/app/static/filename-with_underscore', out=True) '/app/static/filename-with_underscore' >>> os.path.relpath(filter_url('http://domain.com/admin/static/filename-with_underscore')) 'applications/admin/static/filename-with_underscore' >>> filter_err(200)", "controller names when they appear in an incoming URL after", "The error handling page is also passed the error code", "BAD REQUEST [invalid function] >>> filter_url('http://domain.com/admin/ctl/fcn.bad!ext') Traceback (most recent call", "incoming URL. # Set applications to None to disable the", "outgoing routes; filter_err() for error redirection. filter_url() accepts overrides for", "all controllers in the selected app plus 'static' # or", "map_static=True # to override this policy. # acfe_match: regex for", "page is also passed the error code and ticket as", "routes; filter_err() for error redirection. filter_url() accepts overrides for method", "them here. # ErrorMessageTicket takes a string format dictionary containing", "permitted only in the BASE router, # and domain makes", "application name. # default_language # The language code (for example:", "always treated as language names when they appear in an", "omitted from the URL. # root_static: list of static files", "applcations/app/routes.py routers (if any) # # # Router members: #", "converted to underscores, # and back to hyphens in outgoing", "= 'ALL', # default_controller = 'default', # controllers = 'DEFAULT',", "'/app/static/filename-with_underscore' >>> os.path.relpath(filter_url('http://domain.com/admin/static/filename-with_underscore')) 'applications/admin/static/filename-with_underscore' >>> filter_err(200) 200 >>> filter_err(399) 399", "'/welcome/appadmin/fcn_1' >>> filter_url('http://domain.com/welcome/appadmin/fcn_1', out=True) '/appadmin/fcn-1' >>> filter_url('http://domain.com/examples/appadmin/fcn-1') '/examples/appadmin/fcn_1' >>> filter_url('http://domain.com/examples/appadmin/fcn_1',", ">>> filter_url('http://domain.com/admin/ctl/fcn/bad!arg') Traceback (most recent call last): ... HTTP: 400", "r'([\\w@ -]+[=.]?)+$', # legal arg in args # ) #", "built-in default router supplies default values (undefined members are None):", "the default application name, # but provides full rewrite functionality.", "(used for static file names) # args_match: regex for valid", "stored in the ticket. # # routes_onerror = [ #", "controller names from admin URLs map_hyphen = False, # don't", "# Names in controllers are always treated as controller names", "# # Router members: # # default_application: default application name", "router admin = dict( controllers = [], # don't remove", "page itself returns an error, web2py will # fall back", "directory) # Each application has its own root-static files. #", "name. # default_language # The language code (for example: en,", "application-specific router. # The remaining members can appear in the", "name of default function (all controllers) # controllers: list of", "... HTTP: 400 BAD REQUEST [invalid extension] >>> filter_url('http://domain.com/admin/ctl/fcn/bad!arg') Traceback", "optionally appears in the URL following # the application (which", "is taken from request.language. # If languages=None, language support is", "application names from outgoing URLs. # domains: optional dict mapping", "the value as a path to redirect the user to.", "the URL following # the application (which may be omitted).", "from applcations/app/routes.py routers (if any) # # # Router members:", "outgoing URLs. # domains: optional dict mapping domain names to", ">>> import os >>> import gluon.main >>> from gluon.rewrite import", "= 'default', # controllers = 'DEFAULT', # default_function = 'index',", ">>> filter_url('http://domain.com/appadmin/fcn-1') '/welcome/appadmin/fcn_1' >>> filter_url('http://domain.com/welcome/appadmin/fcn_1', out=True) '/appadmin/fcn-1' >>> filter_url('http://domain.com/examples/appadmin/fcn-1') '/examples/appadmin/fcn_1'", "also passed the error code and ticket as # variables." ]
[ "def Always(a: T) -> CCallableUnary[T, CContent]: ... #%% register(Call(Always(w(\"a\")), w(\"idx\")),", "a, idx: a) #%% a_ten = Always(s) #%% s =", "CContent]: ... #%% register(Call(Always(w(\"a\")), w(\"idx\")), lambda a, idx: a) #%%", "w(\"idx\")), lambda a, idx: a) #%% a_ten = Always(s) #%%", "from uarray.core import * #%% s = Scalar(Int(10)) #%% @operation", "... #%% register(Call(Always(w(\"a\")), w(\"idx\")), lambda a, idx: a) #%% a_ten", "CCallableUnary[T, CContent]: ... #%% register(Call(Always(w(\"a\")), w(\"idx\")), lambda a, idx: a)", "register(Call(Always(w(\"a\")), w(\"idx\")), lambda a, idx: a) #%% a_ten = Always(s)", "Scalar(Int(10)) #%% @operation def Always(a: T) -> CCallableUnary[T, CContent]: ...", "@operation def Always(a: T) -> CCallableUnary[T, CContent]: ... #%% register(Call(Always(w(\"a\")),", "a) #%% a_ten = Always(s) #%% s = Sequence(Int(10), a_ten)", "s = Scalar(Int(10)) #%% @operation def Always(a: T) -> CCallableUnary[T,", "#%% from uarray.core import * #%% s = Scalar(Int(10)) #%%", "-> CCallableUnary[T, CContent]: ... #%% register(Call(Always(w(\"a\")), w(\"idx\")), lambda a, idx:", "idx: a) #%% a_ten = Always(s) #%% s = Sequence(Int(10),", "lambda a, idx: a) #%% a_ten = Always(s) #%% s", "* #%% s = Scalar(Int(10)) #%% @operation def Always(a: T)", "import * #%% s = Scalar(Int(10)) #%% @operation def Always(a:", "uarray.core import * #%% s = Scalar(Int(10)) #%% @operation def", "#%% register(Call(Always(w(\"a\")), w(\"idx\")), lambda a, idx: a) #%% a_ten =", "#%% s = Scalar(Int(10)) #%% @operation def Always(a: T) ->", "Always(a: T) -> CCallableUnary[T, CContent]: ... #%% register(Call(Always(w(\"a\")), w(\"idx\")), lambda", "= Scalar(Int(10)) #%% @operation def Always(a: T) -> CCallableUnary[T, CContent]:", "#%% @operation def Always(a: T) -> CCallableUnary[T, CContent]: ... #%%", "T) -> CCallableUnary[T, CContent]: ... #%% register(Call(Always(w(\"a\")), w(\"idx\")), lambda a,", "<reponame>costrouc/uarray #%% from uarray.core import * #%% s = Scalar(Int(10))" ]
[ "#8843 and #8689 for examples of setuptools added as a", "of hand-formatting. In return, Black gives you speed, determinism, and", "\"https://github.com/psf/black\" url = \"https://pypi.io/packages/source/b/black/black-20.8b1.tar.gz\" version('20.8b1', sha256='1c02557aa099101b9d21496f8a914e9ed2222ef70336404eeeac8edba836fbea') version('19.3b0', sha256='68950ffd4d9169716bcb8719a56c07a2f4485354fec061cdd5910aa07369731c') version('18.9b0', sha256='e030a9a28f542debc08acceb273f228ac422798e5215ba2a791a6ddeaaca22a5')", "depends_on('py-aiohttp@3.3.2:', when='+d', type=('build', 'run')) depends_on('py-aiohttp-cors', when='+d', type=('build', 'run')) @property def", "over minutiae of hand-formatting. In return, Black gives you speed,", "when='+d', type=('build', 'run')) @property def import_modules(self): modules = ['blib2to3', 'blib2to3.pgen2',", "'run')) depends_on('py-appdirs', type=('build', 'run')) depends_on('py-toml@0.9.4:', type=('build', 'run')) depends_on('py-toml@0.10.1:', when='@20.8b1:', type=('build',", "for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack", "when='@20.8b1:', type=('build', 'run')) depends_on('py-typed-ast@1.4.0:', when='@19.10b0:', type=('build', 'run')) depends_on('py-regex@2020.1.8:', when='@20.8b0:', type=('build',", "examples of setuptools added as a runtime dep depends_on('py-setuptools', type=('build',", "when='@19.10b0:', type=('build', 'run')) depends_on('py-regex@2020.1.8:', when='@20.8b0:', type=('build', 'run')) depends_on('py-pathspec@0.6:0.999', when='@19.10b0:', type=('build',", "By using it, you agree to cede control over minutiae", "depends_on('py-click@6.5:', type=('build', 'run')) depends_on('py-click@7.1.2:', when='@20.8b1:', type=('build', 'run')) depends_on('py-attrs@18.1.0:', when='@:20.8b0', type=('build',", "depends_on('py-typed-ast@1.4.0:', when='@19.10b0:', type=('build', 'run')) depends_on('py-regex@2020.1.8:', when='@20.8b0:', type=('build', 'run')) depends_on('py-pathspec@0.6:0.999', when='@19.10b0:',", "'run')) @property def import_modules(self): modules = ['blib2to3', 'blib2to3.pgen2', 'black'] if", "nagging about formatting. \"\"\" homepage = \"https://github.com/psf/black\" url = \"https://pypi.io/packages/source/b/black/black-20.8b1.tar.gz\"", "speed, determinism, and freedom from pycodestyle nagging about formatting. \"\"\"", "spack import * class PyBlack(PythonPackage): \"\"\"Black is the uncompromising Python", "version('19.3b0', sha256='68950ffd4d9169716bcb8719a56c07a2f4485354fec061cdd5910aa07369731c') version('18.9b0', sha256='e030a9a28f542debc08acceb273f228ac422798e5215ba2a791a6ddeaaca22a5') variant('d', default=False, description='enable blackd HTTP server')", "formatting. \"\"\" homepage = \"https://github.com/psf/black\" url = \"https://pypi.io/packages/source/b/black/black-20.8b1.tar.gz\" version('20.8b1', sha256='1c02557aa099101b9d21496f8a914e9ed2222ef70336404eeeac8edba836fbea')", "sha256='1c02557aa099101b9d21496f8a914e9ed2222ef70336404eeeac8edba836fbea') version('19.3b0', sha256='68950ffd4d9169716bcb8719a56c07a2f4485354fec061cdd5910aa07369731c') version('18.9b0', sha256='e030a9a28f542debc08acceb273f228ac422798e5215ba2a791a6ddeaaca22a5') variant('d', default=False, description='enable blackd HTTP", "'run')) depends_on('py-typed-ast@1.4.0:', when='@19.10b0:', type=('build', 'run')) depends_on('py-regex@2020.1.8:', when='@20.8b0:', type=('build', 'run')) depends_on('py-pathspec@0.6:0.999',", "runtime dep depends_on('py-setuptools', type=('build', 'run')) # Translated from black's setup.py:", "PyBlack(PythonPackage): \"\"\"Black is the uncompromising Python code formatter. By using", "determinism, and freedom from pycodestyle nagging about formatting. \"\"\" homepage", "blackd HTTP server') depends_on('python@3.6.0:') # Needs setuptools at runtime so", "runtime so that `import pkg_resources` succeeds # See #8843 and", "using it, you agree to cede control over minutiae of", "return, Black gives you speed, determinism, and freedom from pycodestyle", "Lawrence Livermore National Security, LLC and other # Spack Project", "type=('build', 'run')) depends_on('py-attrs@18.1.0:', when='@:20.8b0', type=('build', 'run')) depends_on('py-appdirs', type=('build', 'run')) depends_on('py-toml@0.9.4:',", "\"\"\"Black is the uncompromising Python code formatter. By using it,", "# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other", "depends_on('py-toml@0.9.4:', type=('build', 'run')) depends_on('py-toml@0.10.1:', when='@20.8b1:', type=('build', 'run')) depends_on('py-typed-ast@1.4.0:', when='@19.10b0:', type=('build',", "depends_on('py-regex@2020.1.8:', when='@20.8b0:', type=('build', 'run')) depends_on('py-pathspec@0.6:0.999', when='@19.10b0:', type=('build', 'run')) depends_on('py-dataclasses@0.6:', when='@20.8b0:^python@:3.6',", "server') depends_on('python@3.6.0:') # Needs setuptools at runtime so that `import", "2013-2020 Lawrence Livermore National Security, LLC and other # Spack", "of setuptools added as a runtime dep depends_on('py-setuptools', type=('build', 'run'))", "MIT) from spack import * class PyBlack(PythonPackage): \"\"\"Black is the", "'run')) depends_on('py-mypy-extensions@0.4.3:', when='@20.8b0:', type=('build', 'run')) depends_on('py-aiohttp@3.3.2:', when='+d', type=('build', 'run')) depends_on('py-aiohttp-cors',", "formatter. By using it, you agree to cede control over", "type=('build', 'run')) depends_on('py-aiohttp@3.3.2:', when='+d', type=('build', 'run')) depends_on('py-aiohttp-cors', when='+d', type=('build', 'run'))", "homepage = \"https://github.com/psf/black\" url = \"https://pypi.io/packages/source/b/black/black-20.8b1.tar.gz\" version('20.8b1', sha256='1c02557aa099101b9d21496f8a914e9ed2222ef70336404eeeac8edba836fbea') version('19.3b0', sha256='68950ffd4d9169716bcb8719a56c07a2f4485354fec061cdd5910aa07369731c')", "depends_on('py-pathspec@0.6:0.999', when='@19.10b0:', type=('build', 'run')) depends_on('py-dataclasses@0.6:', when='@20.8b0:^python@:3.6', type=('build', 'run')) depends_on('py-typing-extensions@3.7.4:', when='@20.8b0:',", "a runtime dep depends_on('py-setuptools', type=('build', 'run')) # Translated from black's", "Spack Project Developers. See the top-level COPYRIGHT file for details.", "'run')) # Translated from black's setup.py: # https://github.com/ambv/black/blob/master/setup.py depends_on('py-click@6.5:', type=('build',", "type=('build', 'run')) depends_on('py-click@7.1.2:', when='@20.8b1:', type=('build', 'run')) depends_on('py-attrs@18.1.0:', when='@:20.8b0', type=('build', 'run'))", "that `import pkg_resources` succeeds # See #8843 and #8689 for", "National Security, LLC and other # Spack Project Developers. See", "# https://github.com/ambv/black/blob/master/setup.py depends_on('py-click@6.5:', type=('build', 'run')) depends_on('py-click@7.1.2:', when='@20.8b1:', type=('build', 'run')) depends_on('py-attrs@18.1.0:',", "'run')) depends_on('py-dataclasses@0.6:', when='@20.8b0:^python@:3.6', type=('build', 'run')) depends_on('py-typing-extensions@3.7.4:', when='@20.8b0:', type=('build', 'run')) depends_on('py-mypy-extensions@0.4.3:',", "about formatting. \"\"\" homepage = \"https://github.com/psf/black\" url = \"https://pypi.io/packages/source/b/black/black-20.8b1.tar.gz\" version('20.8b1',", "Black gives you speed, determinism, and freedom from pycodestyle nagging", "type=('build', 'run')) depends_on('py-appdirs', type=('build', 'run')) depends_on('py-toml@0.9.4:', type=('build', 'run')) depends_on('py-toml@0.10.1:', when='@20.8b1:',", "cede control over minutiae of hand-formatting. In return, Black gives", "when='@20.8b0:', type=('build', 'run')) depends_on('py-mypy-extensions@0.4.3:', when='@20.8b0:', type=('build', 'run')) depends_on('py-aiohttp@3.3.2:', when='+d', type=('build',", "Security, LLC and other # Spack Project Developers. See the", "depends_on('python@3.6.0:') # Needs setuptools at runtime so that `import pkg_resources`", "depends_on('py-setuptools', type=('build', 'run')) # Translated from black's setup.py: # https://github.com/ambv/black/blob/master/setup.py", "description='enable blackd HTTP server') depends_on('python@3.6.0:') # Needs setuptools at runtime", "# Needs setuptools at runtime so that `import pkg_resources` succeeds", "= \"https://github.com/psf/black\" url = \"https://pypi.io/packages/source/b/black/black-20.8b1.tar.gz\" version('20.8b1', sha256='1c02557aa099101b9d21496f8a914e9ed2222ef70336404eeeac8edba836fbea') version('19.3b0', sha256='68950ffd4d9169716bcb8719a56c07a2f4485354fec061cdd5910aa07369731c') version('18.9b0',", "as a runtime dep depends_on('py-setuptools', type=('build', 'run')) # Translated from", "depends_on('py-attrs@18.1.0:', when='@:20.8b0', type=('build', 'run')) depends_on('py-appdirs', type=('build', 'run')) depends_on('py-toml@0.9.4:', type=('build', 'run'))", "you speed, determinism, and freedom from pycodestyle nagging about formatting.", "depends_on('py-click@7.1.2:', when='@20.8b1:', type=('build', 'run')) depends_on('py-attrs@18.1.0:', when='@:20.8b0', type=('build', 'run')) depends_on('py-appdirs', type=('build',", "minutiae of hand-formatting. In return, Black gives you speed, determinism,", "depends_on('py-typing-extensions@3.7.4:', when='@20.8b0:', type=('build', 'run')) depends_on('py-mypy-extensions@0.4.3:', when='@20.8b0:', type=('build', 'run')) depends_on('py-aiohttp@3.3.2:', when='+d',", "type=('build', 'run')) depends_on('py-toml@0.9.4:', type=('build', 'run')) depends_on('py-toml@0.10.1:', when='@20.8b1:', type=('build', 'run')) depends_on('py-typed-ast@1.4.0:',", "type=('build', 'run')) depends_on('py-aiohttp-cors', when='+d', type=('build', 'run')) @property def import_modules(self): modules", "# # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import *", "freedom from pycodestyle nagging about formatting. \"\"\" homepage = \"https://github.com/psf/black\"", "at runtime so that `import pkg_resources` succeeds # See #8843", "the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0", "type=('build', 'run')) depends_on('py-toml@0.10.1:', when='@20.8b1:', type=('build', 'run')) depends_on('py-typed-ast@1.4.0:', when='@19.10b0:', type=('build', 'run'))", "when='@20.8b0:^python@:3.6', type=('build', 'run')) depends_on('py-typing-extensions@3.7.4:', when='@20.8b0:', type=('build', 'run')) depends_on('py-mypy-extensions@0.4.3:', when='@20.8b0:', type=('build',", "file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from", "# Spack Project Developers. See the top-level COPYRIGHT file for", "In return, Black gives you speed, determinism, and freedom from", "variant('d', default=False, description='enable blackd HTTP server') depends_on('python@3.6.0:') # Needs setuptools", "pycodestyle nagging about formatting. \"\"\" homepage = \"https://github.com/psf/black\" url =", "and #8689 for examples of setuptools added as a runtime", "sha256='68950ffd4d9169716bcb8719a56c07a2f4485354fec061cdd5910aa07369731c') version('18.9b0', sha256='e030a9a28f542debc08acceb273f228ac422798e5215ba2a791a6ddeaaca22a5') variant('d', default=False, description='enable blackd HTTP server') depends_on('python@3.6.0:')", "when='@20.8b0:', type=('build', 'run')) depends_on('py-pathspec@0.6:0.999', when='@19.10b0:', type=('build', 'run')) depends_on('py-dataclasses@0.6:', when='@20.8b0:^python@:3.6', type=('build',", "depends_on('py-toml@0.10.1:', when='@20.8b1:', type=('build', 'run')) depends_on('py-typed-ast@1.4.0:', when='@19.10b0:', type=('build', 'run')) depends_on('py-regex@2020.1.8:', when='@20.8b0:',", "Livermore National Security, LLC and other # Spack Project Developers.", "import_modules(self): modules = ['blib2to3', 'blib2to3.pgen2', 'black'] if '+d' in self.spec:", "HTTP server') depends_on('python@3.6.0:') # Needs setuptools at runtime so that", "version('20.8b1', sha256='1c02557aa099101b9d21496f8a914e9ed2222ef70336404eeeac8edba836fbea') version('19.3b0', sha256='68950ffd4d9169716bcb8719a56c07a2f4485354fec061cdd5910aa07369731c') version('18.9b0', sha256='e030a9a28f542debc08acceb273f228ac422798e5215ba2a791a6ddeaaca22a5') variant('d', default=False, description='enable blackd", "gives you speed, determinism, and freedom from pycodestyle nagging about", "See #8843 and #8689 for examples of setuptools added as", "type=('build', 'run')) depends_on('py-regex@2020.1.8:', when='@20.8b0:', type=('build', 'run')) depends_on('py-pathspec@0.6:0.999', when='@19.10b0:', type=('build', 'run'))", "the uncompromising Python code formatter. By using it, you agree", "'run')) depends_on('py-regex@2020.1.8:', when='@20.8b0:', type=('build', 'run')) depends_on('py-pathspec@0.6:0.999', when='@19.10b0:', type=('build', 'run')) depends_on('py-dataclasses@0.6:',", "'run')) depends_on('py-toml@0.10.1:', when='@20.8b1:', type=('build', 'run')) depends_on('py-typed-ast@1.4.0:', when='@19.10b0:', type=('build', 'run')) depends_on('py-regex@2020.1.8:',", "setup.py: # https://github.com/ambv/black/blob/master/setup.py depends_on('py-click@6.5:', type=('build', 'run')) depends_on('py-click@7.1.2:', when='@20.8b1:', type=('build', 'run'))", "Python code formatter. By using it, you agree to cede", "version('18.9b0', sha256='e030a9a28f542debc08acceb273f228ac422798e5215ba2a791a6ddeaaca22a5') variant('d', default=False, description='enable blackd HTTP server') depends_on('python@3.6.0:') #", "'run')) depends_on('py-click@7.1.2:', when='@20.8b1:', type=('build', 'run')) depends_on('py-attrs@18.1.0:', when='@:20.8b0', type=('build', 'run')) depends_on('py-appdirs',", "code formatter. By using it, you agree to cede control", "\"https://pypi.io/packages/source/b/black/black-20.8b1.tar.gz\" version('20.8b1', sha256='1c02557aa099101b9d21496f8a914e9ed2222ef70336404eeeac8edba836fbea') version('19.3b0', sha256='68950ffd4d9169716bcb8719a56c07a2f4485354fec061cdd5910aa07369731c') version('18.9b0', sha256='e030a9a28f542debc08acceb273f228ac422798e5215ba2a791a6ddeaaca22a5') variant('d', default=False, description='enable", "depends_on('py-appdirs', type=('build', 'run')) depends_on('py-toml@0.9.4:', type=('build', 'run')) depends_on('py-toml@0.10.1:', when='@20.8b1:', type=('build', 'run'))", "(Apache-2.0 OR MIT) from spack import * class PyBlack(PythonPackage): \"\"\"Black", "LLC and other # Spack Project Developers. See the top-level", "pkg_resources` succeeds # See #8843 and #8689 for examples of", "@property def import_modules(self): modules = ['blib2to3', 'blib2to3.pgen2', 'black'] if '+d'", "details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import", "# See #8843 and #8689 for examples of setuptools added", "def import_modules(self): modules = ['blib2to3', 'blib2to3.pgen2', 'black'] if '+d' in", "added as a runtime dep depends_on('py-setuptools', type=('build', 'run')) # Translated", "* class PyBlack(PythonPackage): \"\"\"Black is the uncompromising Python code formatter.", "sha256='e030a9a28f542debc08acceb273f228ac422798e5215ba2a791a6ddeaaca22a5') variant('d', default=False, description='enable blackd HTTP server') depends_on('python@3.6.0:') # Needs", "hand-formatting. In return, Black gives you speed, determinism, and freedom", "it, you agree to cede control over minutiae of hand-formatting.", "when='+d', type=('build', 'run')) depends_on('py-aiohttp-cors', when='+d', type=('build', 'run')) @property def import_modules(self):", "uncompromising Python code formatter. By using it, you agree to", "#8689 for examples of setuptools added as a runtime dep", "type=('build', 'run')) depends_on('py-typed-ast@1.4.0:', when='@19.10b0:', type=('build', 'run')) depends_on('py-regex@2020.1.8:', when='@20.8b0:', type=('build', 'run'))", "depends_on('py-dataclasses@0.6:', when='@20.8b0:^python@:3.6', type=('build', 'run')) depends_on('py-typing-extensions@3.7.4:', when='@20.8b0:', type=('build', 'run')) depends_on('py-mypy-extensions@0.4.3:', when='@20.8b0:',", "setuptools added as a runtime dep depends_on('py-setuptools', type=('build', 'run')) #", "type=('build', 'run')) # Translated from black's setup.py: # https://github.com/ambv/black/blob/master/setup.py depends_on('py-click@6.5:',", "# Translated from black's setup.py: # https://github.com/ambv/black/blob/master/setup.py depends_on('py-click@6.5:', type=('build', 'run'))", "type=('build', 'run')) depends_on('py-dataclasses@0.6:', when='@20.8b0:^python@:3.6', type=('build', 'run')) depends_on('py-typing-extensions@3.7.4:', when='@20.8b0:', type=('build', 'run'))", "Developers. See the top-level COPYRIGHT file for details. # #", "when='@20.8b0:', type=('build', 'run')) depends_on('py-aiohttp@3.3.2:', when='+d', type=('build', 'run')) depends_on('py-aiohttp-cors', when='+d', type=('build',", "['blib2to3', 'blib2to3.pgen2', 'black'] if '+d' in self.spec: modules.append('blackd') return modules", "from black's setup.py: # https://github.com/ambv/black/blob/master/setup.py depends_on('py-click@6.5:', type=('build', 'run')) depends_on('py-click@7.1.2:', when='@20.8b1:',", "\"\"\" homepage = \"https://github.com/psf/black\" url = \"https://pypi.io/packages/source/b/black/black-20.8b1.tar.gz\" version('20.8b1', sha256='1c02557aa099101b9d21496f8a914e9ed2222ef70336404eeeac8edba836fbea') version('19.3b0',", "import * class PyBlack(PythonPackage): \"\"\"Black is the uncompromising Python code", "Needs setuptools at runtime so that `import pkg_resources` succeeds #", "Copyright 2013-2020 Lawrence Livermore National Security, LLC and other #", "when='@:20.8b0', type=('build', 'run')) depends_on('py-appdirs', type=('build', 'run')) depends_on('py-toml@0.9.4:', type=('build', 'run')) depends_on('py-toml@0.10.1:',", "when='@19.10b0:', type=('build', 'run')) depends_on('py-dataclasses@0.6:', when='@20.8b0:^python@:3.6', type=('build', 'run')) depends_on('py-typing-extensions@3.7.4:', when='@20.8b0:', type=('build',", "depends_on('py-mypy-extensions@0.4.3:', when='@20.8b0:', type=('build', 'run')) depends_on('py-aiohttp@3.3.2:', when='+d', type=('build', 'run')) depends_on('py-aiohttp-cors', when='+d',", "# SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class", "'run')) depends_on('py-attrs@18.1.0:', when='@:20.8b0', type=('build', 'run')) depends_on('py-appdirs', type=('build', 'run')) depends_on('py-toml@0.9.4:', type=('build',", "'run')) depends_on('py-aiohttp@3.3.2:', when='+d', type=('build', 'run')) depends_on('py-aiohttp-cors', when='+d', type=('build', 'run')) @property", "succeeds # See #8843 and #8689 for examples of setuptools", "SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyBlack(PythonPackage):", "type=('build', 'run')) @property def import_modules(self): modules = ['blib2to3', 'blib2to3.pgen2', 'black']", "depends_on('py-aiohttp-cors', when='+d', type=('build', 'run')) @property def import_modules(self): modules = ['blib2to3',", "class PyBlack(PythonPackage): \"\"\"Black is the uncompromising Python code formatter. By", "agree to cede control over minutiae of hand-formatting. In return,", "you agree to cede control over minutiae of hand-formatting. In", "control over minutiae of hand-formatting. In return, Black gives you", "= ['blib2to3', 'blib2to3.pgen2', 'black'] if '+d' in self.spec: modules.append('blackd') return", "is the uncompromising Python code formatter. By using it, you", "default=False, description='enable blackd HTTP server') depends_on('python@3.6.0:') # Needs setuptools at", "'run')) depends_on('py-typing-extensions@3.7.4:', when='@20.8b0:', type=('build', 'run')) depends_on('py-mypy-extensions@0.4.3:', when='@20.8b0:', type=('build', 'run')) depends_on('py-aiohttp@3.3.2:',", "'run')) depends_on('py-pathspec@0.6:0.999', when='@19.10b0:', type=('build', 'run')) depends_on('py-dataclasses@0.6:', when='@20.8b0:^python@:3.6', type=('build', 'run')) depends_on('py-typing-extensions@3.7.4:',", "'run')) depends_on('py-toml@0.9.4:', type=('build', 'run')) depends_on('py-toml@0.10.1:', when='@20.8b1:', type=('build', 'run')) depends_on('py-typed-ast@1.4.0:', when='@19.10b0:',", "setuptools at runtime so that `import pkg_resources` succeeds # See", "black's setup.py: # https://github.com/ambv/black/blob/master/setup.py depends_on('py-click@6.5:', type=('build', 'run')) depends_on('py-click@7.1.2:', when='@20.8b1:', type=('build',", "See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier:", "and freedom from pycodestyle nagging about formatting. \"\"\" homepage =", "when='@20.8b1:', type=('build', 'run')) depends_on('py-attrs@18.1.0:', when='@:20.8b0', type=('build', 'run')) depends_on('py-appdirs', type=('build', 'run'))", "and other # Spack Project Developers. See the top-level COPYRIGHT", "'run')) depends_on('py-aiohttp-cors', when='+d', type=('build', 'run')) @property def import_modules(self): modules =", "OR MIT) from spack import * class PyBlack(PythonPackage): \"\"\"Black is", "dep depends_on('py-setuptools', type=('build', 'run')) # Translated from black's setup.py: #", "type=('build', 'run')) depends_on('py-mypy-extensions@0.4.3:', when='@20.8b0:', type=('build', 'run')) depends_on('py-aiohttp@3.3.2:', when='+d', type=('build', 'run'))", "url = \"https://pypi.io/packages/source/b/black/black-20.8b1.tar.gz\" version('20.8b1', sha256='1c02557aa099101b9d21496f8a914e9ed2222ef70336404eeeac8edba836fbea') version('19.3b0', sha256='68950ffd4d9169716bcb8719a56c07a2f4485354fec061cdd5910aa07369731c') version('18.9b0', sha256='e030a9a28f542debc08acceb273f228ac422798e5215ba2a791a6ddeaaca22a5') variant('d',", "type=('build', 'run')) depends_on('py-typing-extensions@3.7.4:', when='@20.8b0:', type=('build', 'run')) depends_on('py-mypy-extensions@0.4.3:', when='@20.8b0:', type=('build', 'run'))", "so that `import pkg_resources` succeeds # See #8843 and #8689", "`import pkg_resources` succeeds # See #8843 and #8689 for examples", "Project Developers. See the top-level COPYRIGHT file for details. #", "https://github.com/ambv/black/blob/master/setup.py depends_on('py-click@6.5:', type=('build', 'run')) depends_on('py-click@7.1.2:', when='@20.8b1:', type=('build', 'run')) depends_on('py-attrs@18.1.0:', when='@:20.8b0',", "for examples of setuptools added as a runtime dep depends_on('py-setuptools',", "Translated from black's setup.py: # https://github.com/ambv/black/blob/master/setup.py depends_on('py-click@6.5:', type=('build', 'run')) depends_on('py-click@7.1.2:',", "other # Spack Project Developers. See the top-level COPYRIGHT file", "modules = ['blib2to3', 'blib2to3.pgen2', 'black'] if '+d' in self.spec: modules.append('blackd')", "to cede control over minutiae of hand-formatting. In return, Black", "COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT)", "from spack import * class PyBlack(PythonPackage): \"\"\"Black is the uncompromising", "= \"https://pypi.io/packages/source/b/black/black-20.8b1.tar.gz\" version('20.8b1', sha256='1c02557aa099101b9d21496f8a914e9ed2222ef70336404eeeac8edba836fbea') version('19.3b0', sha256='68950ffd4d9169716bcb8719a56c07a2f4485354fec061cdd5910aa07369731c') version('18.9b0', sha256='e030a9a28f542debc08acceb273f228ac422798e5215ba2a791a6ddeaaca22a5') variant('d', default=False,", "type=('build', 'run')) depends_on('py-pathspec@0.6:0.999', when='@19.10b0:', type=('build', 'run')) depends_on('py-dataclasses@0.6:', when='@20.8b0:^python@:3.6', type=('build', 'run'))", "top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR", "from pycodestyle nagging about formatting. \"\"\" homepage = \"https://github.com/psf/black\" url" ]
[ "testeos[0].estado == estado: send = \"selected\" return send @register.filter(name='addattrs') def", "= compras[0] return p.estado in [\"ST\", \"VD\", \"OL\", \"VT\"] and", "args_parse = args.replace(\"'\", '\"') attr = json.loads(args_parse) except Exception as", "get_producto_pk(f): return f.get_producto_pk() @register.filter(name='addcss') def addcss(field, css): return field.as_widget(attrs={\"class\":css}) @register.filter(name='reparacion')", "= Presupuesto.objects.filter(producto__pk=p.id)[0] return pres.notas_cliente except: return \"\" @register.filter(name='num_pres') def num_pres(p):", "try: pres = Presupuesto.objects.filter(producto__pk=p.id)[0] return pres.notas_cliente except: return \"\" @register.filter(name='num_pres')", "27-Aug-2017 # @Email: <EMAIL> # @Filename: admin_extras.py # @Last modified", "in [\"RP\", \"OK\", \"PD\"]: return reverse(\"get_presupuesto_pdf\", args=[p.pk]) elif p.estado ==", "else: return \"#\" @register.filter(name='have_sign') def have_sign(p): compras = Compras.objects.filter(producto__id=p.pk) compra", "precio_usado(p): return \"{0:.2f} €\".format(p.modelo.precio_usado * p.tipo.incremento) @register.filter(name='document_show') def document_show(p): compras", "ImportError: from django.urls import reverse from adminshop.models import Testeo, Compras,", "* p.tipo.incremento) @register.filter(name='document_show') def document_show(p): compras = Compras.objects.filter(producto__id=p.pk) if len(compras)", "args=[p.pk]) elif p.estado == \"VD\": return reverse(\"get_all_document\", args=[p.pk]) else: return", "error: print(error) return field.as_widget(attrs=attr) @register.filter('klass') def klass(ob): return ob.field.widget.__class__.__name__ @register.filter('display')", "if len(compras) > 0: compra = compras[0] return p.estado in", "= {} try: args_parse = args.replace(\"'\", '\"') attr = json.loads(args_parse)", "return f.get_nombre_cliente() @register.filter(name='enviado') def enviado(f): return \"No\" if not f.enviado", "def num_pres(p): try: pres = Presupuesto.objects.filter(producto__pk=p.id)[0] return pres.pk except: return", "'\"') attr = json.loads(args_parse) except Exception as error: print(error) return", "Compras() return p.estado in [\"ST\", \"VD\", \"OL\", \"VT\"] @register.filter(name='document_href') def", "return str(p.modelo) else: return p.detalle @register.filter('marca') def marca(p): if p.modelo", "return field.as_widget(attrs={\"class\":css}) @register.filter(name='reparacion') def reparacion(p): try: pres = Presupuesto.objects.filter(producto__pk=p.id)[0] return", "except ImportError: from django.urls import reverse from adminshop.models import Testeo,", "in [\"ST\", \"OL\", \"VT\"] @register.simple_tag(name='get_estado_value') def get_estado_value(test_id, p_id, estado): testeos", "def klass(ob): return ob.field.widget.__class__.__name__ @register.filter('display') def display(form, value): return dict(form.field.choices)[value]", "field.as_widget(attrs={\"class\":css}) @register.filter(name='reparacion') def reparacion(p): try: pres = Presupuesto.objects.filter(producto__pk=p.id)[0] return pres.notas_cliente", "estado: send = \"selected\" return send @register.filter(name='addattrs') def addattrs(field, args):", "import Q try: from django.core.urlresolvers import reverse except ImportError: from", "len(compras) > 0: compra = compras[0] else: compra = Compras()", "return f.get_producto_pk() @register.filter(name='addcss') def addcss(field, css): return field.as_widget(attrs={\"class\":css}) @register.filter(name='reparacion') def", "> 0 and testeos[0].estado == estado: send = \"selected\" return", "return pres.notas_cliente except: return \"\" @register.filter(name='num_pres') def num_pres(p): try: pres", "display(form, value): return dict(form.field.choices)[value] @register.filter('modelo') def modelo(p): if p.modelo !=", "!= None: return str(p.modelo) else: return p.detalle @register.filter('marca') def marca(p):", "[\"ST\", \"VD\", \"OL\", \"VT\"] @register.filter(name='document_href') def document_href(p): if p.estado in", "try: from django.core.urlresolvers import reverse except ImportError: from django.urls import", "except: return -1 @register.filter(name='precio_venta') def precio_venta(p): precio = 0 if", "args=[p.pk]) else: return \"#\" @register.filter(name='have_sign') def have_sign(p): compras = Compras.objects.filter(producto__id=p.pk)", "\"VD\", \"OL\", \"VT\"] and compra.firma == \"\" @register.filter(name='editable') def editable(p):", "= Compras() return p.estado in [\"ST\", \"VD\", \"OL\", \"VT\"] @register.filter(name='document_href')", "def get_user(f): return f.get_user() @register.filter(name='get_ns_imei') def get_ns_imei(f): return f.get_ns_imei() @register.filter(name='get_producto_pk')", "# @Last modified time: 02-Feb-2018 # @License: Apache license vesion", "@Filename: admin_extras.py # @Last modified by: valle # @Last modified", "and testeos[0].estado == estado: send = \"selected\" return send @register.filter(name='addattrs')", "@Email: <EMAIL> # @Filename: admin_extras.py # @Last modified by: valle", "template from django.db.models import Q try: from django.core.urlresolvers import reverse", "enviado(f): return \"No\" if not f.enviado else \"Si\" @register.filter(name='get_user') def", "def addcss(field, css): return field.as_widget(attrs={\"class\":css}) @register.filter(name='reparacion') def reparacion(p): try: pres", "json import sys register = template.Library() @register.filter(name='get_nombre_cliente') def get_nombre_cliente(f): return", "@register.filter(name='enviado') def enviado(f): return \"No\" if not f.enviado else \"Si\"", "document_href(p): if p.estado in [\"ST\", \"VT\", \"OL\"]: return reverse(\"get_document_by_id\", args=[p.pk])", "elif p.estado in [\"RP\", \"OK\", \"PD\"]: return reverse(\"get_presupuesto_pdf\", args=[p.pk]) elif", "@Last modified by: valle # @Last modified time: 02-Feb-2018 #", "editable(p): return p.estado in [\"ST\", \"OL\", \"VT\"] @register.simple_tag(name='get_estado_value') def get_estado_value(test_id,", "== None else p.precio_venta return \"{0:.2f} €\".format(precio) @register.filter(name='precio_usado') def precio_usado(p):", "ob.field.widget.__class__.__name__ @register.filter('display') def display(form, value): return dict(form.field.choices)[value] @register.filter('modelo') def modelo(p):", "> 0: compra = compras[0] else: compra = Compras() return", "\"{0:.2f} €\".format(p.modelo.precio_usado * p.tipo.incremento) @register.filter(name='document_show') def document_show(p): compras = Compras.objects.filter(producto__id=p.pk)", "def precio_usado(p): return \"{0:.2f} €\".format(p.modelo.precio_usado * p.tipo.incremento) @register.filter(name='document_show') def document_show(p):", "f.get_nombre_cliente() @register.filter(name='enviado') def enviado(f): return \"No\" if not f.enviado else", "def reparacion(p): try: pres = Presupuesto.objects.filter(producto__pk=p.id)[0] return pres.notas_cliente except: return", "from django.urls import reverse from adminshop.models import Testeo, Compras, Presupuesto", "print(error) return field.as_widget(attrs=attr) @register.filter('klass') def klass(ob): return ob.field.widget.__class__.__name__ @register.filter('display') def", "adminshop.models import Testeo, Compras, Presupuesto import json import sys register", "@Author: <NAME> <valle> # @Date: 27-Aug-2017 # @Email: <EMAIL> #", "reverse(\"get_presupuesto_pdf\", args=[p.pk]) elif p.estado == \"VD\": return reverse(\"get_all_document\", args=[p.pk]) else:", "if p.precio_venta == None else p.precio_venta return \"{0:.2f} €\".format(precio) @register.filter(name='precio_usado')", "\"VD\": return reverse(\"get_all_document\", args=[p.pk]) else: return \"#\" @register.filter(name='have_sign') def have_sign(p):", "p.estado in [\"RP\", \"OK\", \"PD\"]: return reverse(\"get_presupuesto_pdf\", args=[p.pk]) elif p.estado", "def document_show(p): compras = Compras.objects.filter(producto__id=p.pk) if len(compras) > 0: compra", "@register.filter(name='editable') def editable(p): return p.estado in [\"ST\", \"OL\", \"VT\"] @register.simple_tag(name='get_estado_value')", "\"VT\", \"OL\"]: return reverse(\"get_document_by_id\", args=[p.pk]) elif p.estado in [\"RP\", \"OK\",", "return \"\" @register.filter(name='num_pres') def num_pres(p): try: pres = Presupuesto.objects.filter(producto__pk=p.id)[0] return", "f.get_ns_imei() @register.filter(name='get_producto_pk') def get_producto_pk(f): return f.get_producto_pk() @register.filter(name='addcss') def addcss(field, css):", "testeos = Testeo.objects.filter(Q(descripcion__pk=test_id) & Q(producto__pk=p_id)) send = \"\" if len(testeos)", "if len(testeos) > 0 and testeos[0].estado == estado: send =", "return ob.field.widget.__class__.__name__ @register.filter('display') def display(form, value): return dict(form.field.choices)[value] @register.filter('modelo') def", "@register.filter(name='num_pres') def num_pres(p): try: pres = Presupuesto.objects.filter(producto__pk=p.id)[0] return pres.pk except:", "= \"selected\" return send @register.filter(name='addattrs') def addattrs(field, args): attr =", "p.estado in [\"ST\", \"OL\", \"VT\"] @register.simple_tag(name='get_estado_value') def get_estado_value(test_id, p_id, estado):", "in [\"ST\", \"VD\", \"OL\", \"VT\"] and compra.firma == \"\" @register.filter(name='editable')", "@Date: 27-Aug-2017 # @Email: <EMAIL> # @Filename: admin_extras.py # @Last", "[\"RP\", \"OK\", \"PD\"]: return reverse(\"get_presupuesto_pdf\", args=[p.pk]) elif p.estado == \"VD\":", "02-Feb-2018 # @License: Apache license vesion 2.0 from django import", "import template from django.db.models import Q try: from django.core.urlresolvers import", "in [\"ST\", \"VT\", \"OL\"]: return reverse(\"get_document_by_id\", args=[p.pk]) elif p.estado in", "len(testeos) > 0 and testeos[0].estado == estado: send = \"selected\"", "== estado: send = \"selected\" return send @register.filter(name='addattrs') def addattrs(field,", "# -*- coding: utf-8 -*- # @Author: <NAME> <valle> #", "<filename>store/adminshop/templatetags/admin_extras.py # -*- coding: utf-8 -*- # @Author: <NAME> <valle>", "import sys register = template.Library() @register.filter(name='get_nombre_cliente') def get_nombre_cliente(f): return f.get_nombre_cliente()", "Compras, Presupuesto import json import sys register = template.Library() @register.filter(name='get_nombre_cliente')", "vesion 2.0 from django import template from django.db.models import Q", "= Presupuesto.objects.filter(producto__pk=p.id)[0] return pres.pk except: return -1 @register.filter(name='precio_venta') def precio_venta(p):", "import reverse except ImportError: from django.urls import reverse from adminshop.models", "p.estado in [\"ST\", \"VD\", \"OL\", \"VT\"] and compra.firma == \"\"", "compra = compras[0] else: compra = Compras() return p.estado in", "\"VT\"] @register.filter(name='document_href') def document_href(p): if p.estado in [\"ST\", \"VT\", \"OL\"]:", "pres = Presupuesto.objects.filter(producto__pk=p.id)[0] return pres.pk except: return -1 @register.filter(name='precio_venta') def", "str(p.modelo) else: return p.detalle @register.filter('marca') def marca(p): if p.modelo !=", "{} try: args_parse = args.replace(\"'\", '\"') attr = json.loads(args_parse) except", "modified by: valle # @Last modified time: 02-Feb-2018 # @License:", "sys register = template.Library() @register.filter(name='get_nombre_cliente') def get_nombre_cliente(f): return f.get_nombre_cliente() @register.filter(name='enviado')", "@register.filter('modelo') def modelo(p): if p.modelo != None: return str(p.modelo) else:", "precio = 0 if p.precio_venta == None else p.precio_venta return", "attr = {} try: args_parse = args.replace(\"'\", '\"') attr =", "return p.estado in [\"ST\", \"VD\", \"OL\", \"VT\"] and compra.firma ==", "p.precio_venta == None else p.precio_venta return \"{0:.2f} €\".format(precio) @register.filter(name='precio_usado') def", "f.get_user() @register.filter(name='get_ns_imei') def get_ns_imei(f): return f.get_ns_imei() @register.filter(name='get_producto_pk') def get_producto_pk(f): return", "except: return \"\" @register.filter(name='num_pres') def num_pres(p): try: pres = Presupuesto.objects.filter(producto__pk=p.id)[0]", "# @License: Apache license vesion 2.0 from django import template", "= Testeo.objects.filter(Q(descripcion__pk=test_id) & Q(producto__pk=p_id)) send = \"\" if len(testeos) >", "def marca(p): if p.modelo != None: return str(p.modelo.marca) else: return", "= 0 if p.precio_venta == None else p.precio_venta return \"{0:.2f}", "field.as_widget(attrs=attr) @register.filter('klass') def klass(ob): return ob.field.widget.__class__.__name__ @register.filter('display') def display(form, value):", "return -1 @register.filter(name='precio_venta') def precio_venta(p): precio = 0 if p.precio_venta", "compra = Compras() return p.estado in [\"ST\", \"VD\", \"OL\", \"VT\"]", "from django.db.models import Q try: from django.core.urlresolvers import reverse except", "<valle> # @Date: 27-Aug-2017 # @Email: <EMAIL> # @Filename: admin_extras.py", "@register.filter(name='precio_usado') def precio_usado(p): return \"{0:.2f} €\".format(p.modelo.precio_usado * p.tipo.incremento) @register.filter(name='document_show') def", "\"\" if len(testeos) > 0 and testeos[0].estado == estado: send", "precio_venta(p): precio = 0 if p.precio_venta == None else p.precio_venta", "from adminshop.models import Testeo, Compras, Presupuesto import json import sys", "Compras.objects.filter(producto__id=p.pk) compra = Compras() if len(compras) > 0: compra =", "def addattrs(field, args): attr = {} try: args_parse = args.replace(\"'\",", "and compra.firma == \"\" @register.filter(name='editable') def editable(p): return p.estado in", "\"VD\", \"OL\", \"VT\"] @register.filter(name='document_href') def document_href(p): if p.estado in [\"ST\",", "@register.filter('klass') def klass(ob): return ob.field.widget.__class__.__name__ @register.filter('display') def display(form, value): return", "compra = compras[0] return p.estado in [\"ST\", \"VD\", \"OL\", \"VT\"]", "else p.precio_venta return \"{0:.2f} €\".format(precio) @register.filter(name='precio_usado') def precio_usado(p): return \"{0:.2f}", "time: 02-Feb-2018 # @License: Apache license vesion 2.0 from django", "\"OL\"]: return reverse(\"get_document_by_id\", args=[p.pk]) elif p.estado in [\"RP\", \"OK\", \"PD\"]:", "def have_sign(p): compras = Compras.objects.filter(producto__id=p.pk) compra = Compras() if len(compras)", "return reverse(\"get_document_by_id\", args=[p.pk]) elif p.estado in [\"RP\", \"OK\", \"PD\"]: return", "klass(ob): return ob.field.widget.__class__.__name__ @register.filter('display') def display(form, value): return dict(form.field.choices)[value] @register.filter('modelo')", "django.core.urlresolvers import reverse except ImportError: from django.urls import reverse from", "Compras.objects.filter(producto__id=p.pk) if len(compras) > 0: compra = compras[0] else: compra", "attr = json.loads(args_parse) except Exception as error: print(error) return field.as_widget(attrs=attr)", "django.db.models import Q try: from django.core.urlresolvers import reverse except ImportError:", "<EMAIL> # @Filename: admin_extras.py # @Last modified by: valle #", "args=[p.pk]) elif p.estado in [\"RP\", \"OK\", \"PD\"]: return reverse(\"get_presupuesto_pdf\", args=[p.pk])", "\"{0:.2f} €\".format(precio) @register.filter(name='precio_usado') def precio_usado(p): return \"{0:.2f} €\".format(p.modelo.precio_usado * p.tipo.incremento)", "return p.estado in [\"ST\", \"VD\", \"OL\", \"VT\"] @register.filter(name='document_href') def document_href(p):", "-*- coding: utf-8 -*- # @Author: <NAME> <valle> # @Date:", "get_user(f): return f.get_user() @register.filter(name='get_ns_imei') def get_ns_imei(f): return f.get_ns_imei() @register.filter(name='get_producto_pk') def", "return dict(form.field.choices)[value] @register.filter('modelo') def modelo(p): if p.modelo != None: return", "valle # @Last modified time: 02-Feb-2018 # @License: Apache license", "@register.filter(name='addcss') def addcss(field, css): return field.as_widget(attrs={\"class\":css}) @register.filter(name='reparacion') def reparacion(p): try:", "from django.core.urlresolvers import reverse except ImportError: from django.urls import reverse", "-*- # @Author: <NAME> <valle> # @Date: 27-Aug-2017 # @Email:", "[\"ST\", \"VT\", \"OL\"]: return reverse(\"get_document_by_id\", args=[p.pk]) elif p.estado in [\"RP\",", "f.get_producto_pk() @register.filter(name='addcss') def addcss(field, css): return field.as_widget(attrs={\"class\":css}) @register.filter(name='reparacion') def reparacion(p):", "p.estado == \"VD\": return reverse(\"get_all_document\", args=[p.pk]) else: return \"#\" @register.filter(name='have_sign')", "addcss(field, css): return field.as_widget(attrs={\"class\":css}) @register.filter(name='reparacion') def reparacion(p): try: pres =", "get_estado_value(test_id, p_id, estado): testeos = Testeo.objects.filter(Q(descripcion__pk=test_id) & Q(producto__pk=p_id)) send =", "# @Author: <NAME> <valle> # @Date: 27-Aug-2017 # @Email: <EMAIL>", "template.Library() @register.filter(name='get_nombre_cliente') def get_nombre_cliente(f): return f.get_nombre_cliente() @register.filter(name='enviado') def enviado(f): return", "def display(form, value): return dict(form.field.choices)[value] @register.filter('modelo') def modelo(p): if p.modelo", "@License: Apache license vesion 2.0 from django import template from", "args): attr = {} try: args_parse = args.replace(\"'\", '\"') attr", "# @Date: 27-Aug-2017 # @Email: <EMAIL> # @Filename: admin_extras.py #", "if p.modelo != None: return str(p.modelo) else: return p.detalle @register.filter('marca')", "if p.estado in [\"ST\", \"VT\", \"OL\"]: return reverse(\"get_document_by_id\", args=[p.pk]) elif", "== \"\" @register.filter(name='editable') def editable(p): return p.estado in [\"ST\", \"OL\",", "Presupuesto.objects.filter(producto__pk=p.id)[0] return pres.notas_cliente except: return \"\" @register.filter(name='num_pres') def num_pres(p): try:", "addattrs(field, args): attr = {} try: args_parse = args.replace(\"'\", '\"')", "f.enviado else \"Si\" @register.filter(name='get_user') def get_user(f): return f.get_user() @register.filter(name='get_ns_imei') def", "@register.filter(name='reparacion') def reparacion(p): try: pres = Presupuesto.objects.filter(producto__pk=p.id)[0] return pres.notas_cliente except:", "pres = Presupuesto.objects.filter(producto__pk=p.id)[0] return pres.notas_cliente except: return \"\" @register.filter(name='num_pres') def", "import reverse from adminshop.models import Testeo, Compras, Presupuesto import json", "coding: utf-8 -*- # @Author: <NAME> <valle> # @Date: 27-Aug-2017", "try: pres = Presupuesto.objects.filter(producto__pk=p.id)[0] return pres.pk except: return -1 @register.filter(name='precio_venta')", "\"VT\"] @register.simple_tag(name='get_estado_value') def get_estado_value(test_id, p_id, estado): testeos = Testeo.objects.filter(Q(descripcion__pk=test_id) &", "[\"ST\", \"OL\", \"VT\"] @register.simple_tag(name='get_estado_value') def get_estado_value(test_id, p_id, estado): testeos =", "admin_extras.py # @Last modified by: valle # @Last modified time:", "marca(p): if p.modelo != None: return str(p.modelo.marca) else: return \"\"", "@register.filter(name='get_user') def get_user(f): return f.get_user() @register.filter(name='get_ns_imei') def get_ns_imei(f): return f.get_ns_imei()", "return \"{0:.2f} €\".format(precio) @register.filter(name='precio_usado') def precio_usado(p): return \"{0:.2f} €\".format(p.modelo.precio_usado *", "= compras[0] else: compra = Compras() return p.estado in [\"ST\",", "= \"\" if len(testeos) > 0 and testeos[0].estado == estado:", "# @Filename: admin_extras.py # @Last modified by: valle # @Last", "return p.estado in [\"ST\", \"OL\", \"VT\"] @register.simple_tag(name='get_estado_value') def get_estado_value(test_id, p_id,", "Q try: from django.core.urlresolvers import reverse except ImportError: from django.urls", "except Exception as error: print(error) return field.as_widget(attrs=attr) @register.filter('klass') def klass(ob):", "return reverse(\"get_all_document\", args=[p.pk]) else: return \"#\" @register.filter(name='have_sign') def have_sign(p): compras", "from django import template from django.db.models import Q try: from", "in [\"ST\", \"VD\", \"OL\", \"VT\"] @register.filter(name='document_href') def document_href(p): if p.estado", "def editable(p): return p.estado in [\"ST\", \"OL\", \"VT\"] @register.simple_tag(name='get_estado_value') def", "return send @register.filter(name='addattrs') def addattrs(field, args): attr = {} try:", "compra.firma == \"\" @register.filter(name='editable') def editable(p): return p.estado in [\"ST\",", "Testeo.objects.filter(Q(descripcion__pk=test_id) & Q(producto__pk=p_id)) send = \"\" if len(testeos) > 0", "\"Si\" @register.filter(name='get_user') def get_user(f): return f.get_user() @register.filter(name='get_ns_imei') def get_ns_imei(f): return", "= args.replace(\"'\", '\"') attr = json.loads(args_parse) except Exception as error:", "compras = Compras.objects.filter(producto__id=p.pk) compra = Compras() if len(compras) > 0:", "p.tipo.incremento) @register.filter(name='document_show') def document_show(p): compras = Compras.objects.filter(producto__id=p.pk) if len(compras) >", "p.modelo != None: return str(p.modelo) else: return p.detalle @register.filter('marca') def", "send @register.filter(name='addattrs') def addattrs(field, args): attr = {} try: args_parse", "send = \"selected\" return send @register.filter(name='addattrs') def addattrs(field, args): attr", "p.precio_venta return \"{0:.2f} €\".format(precio) @register.filter(name='precio_usado') def precio_usado(p): return \"{0:.2f} €\".format(p.modelo.precio_usado", "return \"{0:.2f} €\".format(p.modelo.precio_usado * p.tipo.incremento) @register.filter(name='document_show') def document_show(p): compras =", "return p.detalle @register.filter('marca') def marca(p): if p.modelo != None: return", "reverse(\"get_document_by_id\", args=[p.pk]) elif p.estado in [\"RP\", \"OK\", \"PD\"]: return reverse(\"get_presupuesto_pdf\",", "= Compras() if len(compras) > 0: compra = compras[0] return", "@register.filter('display') def display(form, value): return dict(form.field.choices)[value] @register.filter('modelo') def modelo(p): if", "\"OL\", \"VT\"] @register.simple_tag(name='get_estado_value') def get_estado_value(test_id, p_id, estado): testeos = Testeo.objects.filter(Q(descripcion__pk=test_id)", "def enviado(f): return \"No\" if not f.enviado else \"Si\" @register.filter(name='get_user')", "€\".format(precio) @register.filter(name='precio_usado') def precio_usado(p): return \"{0:.2f} €\".format(p.modelo.precio_usado * p.tipo.incremento) @register.filter(name='document_show')", "p_id, estado): testeos = Testeo.objects.filter(Q(descripcion__pk=test_id) & Q(producto__pk=p_id)) send = \"\"", "\"OL\", \"VT\"] @register.filter(name='document_href') def document_href(p): if p.estado in [\"ST\", \"VT\",", "= Compras.objects.filter(producto__id=p.pk) if len(compras) > 0: compra = compras[0] else:", "document_show(p): compras = Compras.objects.filter(producto__id=p.pk) if len(compras) > 0: compra =", "else: return p.detalle @register.filter('marca') def marca(p): if p.modelo != None:", "Q(producto__pk=p_id)) send = \"\" if len(testeos) > 0 and testeos[0].estado", "elif p.estado == \"VD\": return reverse(\"get_all_document\", args=[p.pk]) else: return \"#\"", "None else p.precio_venta return \"{0:.2f} €\".format(precio) @register.filter(name='precio_usado') def precio_usado(p): return", "-1 @register.filter(name='precio_venta') def precio_venta(p): precio = 0 if p.precio_venta ==", "\"#\" @register.filter(name='have_sign') def have_sign(p): compras = Compras.objects.filter(producto__id=p.pk) compra = Compras()", "args.replace(\"'\", '\"') attr = json.loads(args_parse) except Exception as error: print(error)", "Compras() if len(compras) > 0: compra = compras[0] return p.estado", "reverse from adminshop.models import Testeo, Compras, Presupuesto import json import", "import Testeo, Compras, Presupuesto import json import sys register =", "else: compra = Compras() return p.estado in [\"ST\", \"VD\", \"OL\",", "p.estado in [\"ST\", \"VT\", \"OL\"]: return reverse(\"get_document_by_id\", args=[p.pk]) elif p.estado", "@register.filter(name='document_href') def document_href(p): if p.estado in [\"ST\", \"VT\", \"OL\"]: return", "@Last modified time: 02-Feb-2018 # @License: Apache license vesion 2.0", "get_nombre_cliente(f): return f.get_nombre_cliente() @register.filter(name='enviado') def enviado(f): return \"No\" if not", "\"OK\", \"PD\"]: return reverse(\"get_presupuesto_pdf\", args=[p.pk]) elif p.estado == \"VD\": return", "@register.filter(name='have_sign') def have_sign(p): compras = Compras.objects.filter(producto__id=p.pk) compra = Compras() if", "compra = Compras() if len(compras) > 0: compra = compras[0]", "Testeo, Compras, Presupuesto import json import sys register = template.Library()", "def get_ns_imei(f): return f.get_ns_imei() @register.filter(name='get_producto_pk') def get_producto_pk(f): return f.get_producto_pk() @register.filter(name='addcss')", "& Q(producto__pk=p_id)) send = \"\" if len(testeos) > 0 and", "pres.notas_cliente except: return \"\" @register.filter(name='num_pres') def num_pres(p): try: pres =", "\"No\" if not f.enviado else \"Si\" @register.filter(name='get_user') def get_user(f): return", "def modelo(p): if p.modelo != None: return str(p.modelo) else: return", "None: return str(p.modelo) else: return p.detalle @register.filter('marca') def marca(p): if", "@register.filter(name='get_ns_imei') def get_ns_imei(f): return f.get_ns_imei() @register.filter(name='get_producto_pk') def get_producto_pk(f): return f.get_producto_pk()", "== \"VD\": return reverse(\"get_all_document\", args=[p.pk]) else: return \"#\" @register.filter(name='have_sign') def", "p.detalle @register.filter('marca') def marca(p): if p.modelo != None: return str(p.modelo.marca)", "compras[0] else: compra = Compras() return p.estado in [\"ST\", \"VD\",", "€\".format(p.modelo.precio_usado * p.tipo.incremento) @register.filter(name='document_show') def document_show(p): compras = Compras.objects.filter(producto__id=p.pk) if", "django import template from django.db.models import Q try: from django.core.urlresolvers", "compras[0] return p.estado in [\"ST\", \"VD\", \"OL\", \"VT\"] and compra.firma", "import json import sys register = template.Library() @register.filter(name='get_nombre_cliente') def get_nombre_cliente(f):", "return f.get_ns_imei() @register.filter(name='get_producto_pk') def get_producto_pk(f): return f.get_producto_pk() @register.filter(name='addcss') def addcss(field,", "json.loads(args_parse) except Exception as error: print(error) return field.as_widget(attrs=attr) @register.filter('klass') def", "css): return field.as_widget(attrs={\"class\":css}) @register.filter(name='reparacion') def reparacion(p): try: pres = Presupuesto.objects.filter(producto__pk=p.id)[0]", "@register.filter(name='get_nombre_cliente') def get_nombre_cliente(f): return f.get_nombre_cliente() @register.filter(name='enviado') def enviado(f): return \"No\"", "\"OL\", \"VT\"] and compra.firma == \"\" @register.filter(name='editable') def editable(p): return", "@register.filter(name='precio_venta') def precio_venta(p): precio = 0 if p.precio_venta == None", "\"\" @register.filter(name='editable') def editable(p): return p.estado in [\"ST\", \"OL\", \"VT\"]", "@register.filter(name='get_producto_pk') def get_producto_pk(f): return f.get_producto_pk() @register.filter(name='addcss') def addcss(field, css): return", "estado): testeos = Testeo.objects.filter(Q(descripcion__pk=test_id) & Q(producto__pk=p_id)) send = \"\" if", "reverse(\"get_all_document\", args=[p.pk]) else: return \"#\" @register.filter(name='have_sign') def have_sign(p): compras =", "len(compras) > 0: compra = compras[0] return p.estado in [\"ST\",", "\"selected\" return send @register.filter(name='addattrs') def addattrs(field, args): attr = {}", "reverse except ImportError: from django.urls import reverse from adminshop.models import", "def precio_venta(p): precio = 0 if p.precio_venta == None else", "2.0 from django import template from django.db.models import Q try:", "@register.filter(name='document_show') def document_show(p): compras = Compras.objects.filter(producto__id=p.pk) if len(compras) > 0:", "p.estado in [\"ST\", \"VD\", \"OL\", \"VT\"] @register.filter(name='document_href') def document_href(p): if", "django.urls import reverse from adminshop.models import Testeo, Compras, Presupuesto import", "send = \"\" if len(testeos) > 0 and testeos[0].estado ==", "def get_estado_value(test_id, p_id, estado): testeos = Testeo.objects.filter(Q(descripcion__pk=test_id) & Q(producto__pk=p_id)) send", "\"VT\"] and compra.firma == \"\" @register.filter(name='editable') def editable(p): return p.estado", "\"\" @register.filter(name='num_pres') def num_pres(p): try: pres = Presupuesto.objects.filter(producto__pk=p.id)[0] return pres.pk", "@register.filter('marca') def marca(p): if p.modelo != None: return str(p.modelo.marca) else:", "compras = Compras.objects.filter(producto__id=p.pk) if len(compras) > 0: compra = compras[0]", "dict(form.field.choices)[value] @register.filter('modelo') def modelo(p): if p.modelo != None: return str(p.modelo)", "return f.get_user() @register.filter(name='get_ns_imei') def get_ns_imei(f): return f.get_ns_imei() @register.filter(name='get_producto_pk') def get_producto_pk(f):", "def document_href(p): if p.estado in [\"ST\", \"VT\", \"OL\"]: return reverse(\"get_document_by_id\",", "modified time: 02-Feb-2018 # @License: Apache license vesion 2.0 from", "0: compra = compras[0] else: compra = Compras() return p.estado", "register = template.Library() @register.filter(name='get_nombre_cliente') def get_nombre_cliente(f): return f.get_nombre_cliente() @register.filter(name='enviado') def", "get_ns_imei(f): return f.get_ns_imei() @register.filter(name='get_producto_pk') def get_producto_pk(f): return f.get_producto_pk() @register.filter(name='addcss') def", "0 and testeos[0].estado == estado: send = \"selected\" return send", "return reverse(\"get_presupuesto_pdf\", args=[p.pk]) elif p.estado == \"VD\": return reverse(\"get_all_document\", args=[p.pk])", "@register.simple_tag(name='get_estado_value') def get_estado_value(test_id, p_id, estado): testeos = Testeo.objects.filter(Q(descripcion__pk=test_id) & Q(producto__pk=p_id))", "try: args_parse = args.replace(\"'\", '\"') attr = json.loads(args_parse) except Exception", "= json.loads(args_parse) except Exception as error: print(error) return field.as_widget(attrs=attr) @register.filter('klass')", "<NAME> <valle> # @Date: 27-Aug-2017 # @Email: <EMAIL> # @Filename:", "license vesion 2.0 from django import template from django.db.models import", "0: compra = compras[0] return p.estado in [\"ST\", \"VD\", \"OL\",", "modelo(p): if p.modelo != None: return str(p.modelo) else: return p.detalle", "num_pres(p): try: pres = Presupuesto.objects.filter(producto__pk=p.id)[0] return pres.pk except: return -1", "Presupuesto import json import sys register = template.Library() @register.filter(name='get_nombre_cliente') def", "have_sign(p): compras = Compras.objects.filter(producto__id=p.pk) compra = Compras() if len(compras) >", "utf-8 -*- # @Author: <NAME> <valle> # @Date: 27-Aug-2017 #", "else \"Si\" @register.filter(name='get_user') def get_user(f): return f.get_user() @register.filter(name='get_ns_imei') def get_ns_imei(f):", "# @Last modified by: valle # @Last modified time: 02-Feb-2018", "reparacion(p): try: pres = Presupuesto.objects.filter(producto__pk=p.id)[0] return pres.notas_cliente except: return \"\"", "pres.pk except: return -1 @register.filter(name='precio_venta') def precio_venta(p): precio = 0", "return pres.pk except: return -1 @register.filter(name='precio_venta') def precio_venta(p): precio =", "> 0: compra = compras[0] return p.estado in [\"ST\", \"VD\",", "if not f.enviado else \"Si\" @register.filter(name='get_user') def get_user(f): return f.get_user()", "not f.enviado else \"Si\" @register.filter(name='get_user') def get_user(f): return f.get_user() @register.filter(name='get_ns_imei')", "= Compras.objects.filter(producto__id=p.pk) compra = Compras() if len(compras) > 0: compra", "value): return dict(form.field.choices)[value] @register.filter('modelo') def modelo(p): if p.modelo != None:", "def get_nombre_cliente(f): return f.get_nombre_cliente() @register.filter(name='enviado') def enviado(f): return \"No\" if", "[\"ST\", \"VD\", \"OL\", \"VT\"] and compra.firma == \"\" @register.filter(name='editable') def", "\"PD\"]: return reverse(\"get_presupuesto_pdf\", args=[p.pk]) elif p.estado == \"VD\": return reverse(\"get_all_document\",", "0 if p.precio_venta == None else p.precio_venta return \"{0:.2f} €\".format(precio)", "= template.Library() @register.filter(name='get_nombre_cliente') def get_nombre_cliente(f): return f.get_nombre_cliente() @register.filter(name='enviado') def enviado(f):", "Apache license vesion 2.0 from django import template from django.db.models", "if len(compras) > 0: compra = compras[0] else: compra =", "Presupuesto.objects.filter(producto__pk=p.id)[0] return pres.pk except: return -1 @register.filter(name='precio_venta') def precio_venta(p): precio", "return \"#\" @register.filter(name='have_sign') def have_sign(p): compras = Compras.objects.filter(producto__id=p.pk) compra =", "by: valle # @Last modified time: 02-Feb-2018 # @License: Apache", "Exception as error: print(error) return field.as_widget(attrs=attr) @register.filter('klass') def klass(ob): return", "as error: print(error) return field.as_widget(attrs=attr) @register.filter('klass') def klass(ob): return ob.field.widget.__class__.__name__", "@register.filter(name='addattrs') def addattrs(field, args): attr = {} try: args_parse =", "return \"No\" if not f.enviado else \"Si\" @register.filter(name='get_user') def get_user(f):", "return field.as_widget(attrs=attr) @register.filter('klass') def klass(ob): return ob.field.widget.__class__.__name__ @register.filter('display') def display(form,", "def get_producto_pk(f): return f.get_producto_pk() @register.filter(name='addcss') def addcss(field, css): return field.as_widget(attrs={\"class\":css})", "# @Email: <EMAIL> # @Filename: admin_extras.py # @Last modified by:" ]
[ "i3))}}[(0, 0)]<gpuarray>(GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[-1.]}, y, GpuElemwise{Cast{float32}}[]<gpuarray>.0, GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0,", "Aesara symbolic variables x = aesara.shared(D[0], name=\"x\") y = aesara.shared(D[1],", "- ((scalar_sigmoid((-i0)) * i1 * i4) / i3))}}[(0, 0)](Elemwise{Composite{((-i0) -", "tt.log(1 - p_1) # Cross-entropy cost = tt.cast(xent.mean(), \"float32\") +", "0 InplaceGpuDimShuffle{x}(b) 0.3% 99.6% 0.011s 1.14e-06s 10000 2 InplaceGpuDimShuffle{1,0}(x) 0.2%", "profiling results for each function # in the script, followed", "aesara import 2.864s Class --- <% time> <sum %> <apply", "the runtime) Apply ------ <% time> <sum %> <apply time>", "Apply instances account for 0.00%(0.00s) of the runtime) # 2.2", "TensorConstant{(1,) of 0.5}) 1.0% 97.4% 0.011s 1.14e-06s 10000 14 Sum{acc_dtype=float64}(Elemwise{Composite{(((scalar_sigmoid(i0)", "1 Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}} 1.0% 97.4% 0.011s 1.14e-06s C 10000 1", "Cross-entropy cost = tt.cast(xent.mean(), \"float32\") + 0.01 * (w **", "- (i1 * i2))}}[(0, 0)] 0.0% 100.0% 0.000s 4.77e-06s C", "their overhead. Notice that each of the GPU ops consumes", "C 80001 9 aesara.tensor.elemwise.Elemwise 1.0% 98.6% 0.011s 1.14e-06s C 10000", "Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) - ((scalar_sigmoid((-i0)) *", "0.061s 6.10e-06s 10000 6 GpuFromHost<None>(Shape_i{0}.0) 0.7% 99.0% 0.026s 2.59e-06s 10000", "- (i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray>.0) 1.6% 98.3% 0.061s 6.10e-06s", "99.8% 0.026s 2.59e-06s C 10001 2 aesara.sandbox.gpuarray.basic_ops.GpuAllocEmpty 0.2% 100.0% 0.008s", "1 1 GpuElemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}}[]<gpuarray> ... (remaining 0 Ops", "59.5% 2.329s 1.16e-04s C 20001 3 aesara.sandbox.gpuarray.blas.GpuGemv 29.8% 89.3% 1.166s", "as possible data transfers between GPU and CPU, you can", "but by making as few as possible data transfers between", "produced using an Intel(R) Core(TM) i7-5930K CPU @ 3.50GHz Function", "0)] 0.0% 100.0% 0.000s 4.77e-06s C 1 1 Elemwise{Composite{GT(scalar_sigmoid((-((-i0) -", "* scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[(0, 4)] 8.9%", "0.011s 1.14e-06s 10000 14 Sum{acc_dtype=float64}(Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) /", "name=\"w\") b = aesara.shared(np.asarray(0.0, dtype=aesara.config.floatX), name=\"b\") x.tag.test_value = D[0] y.tag.test_value", "4 aesara.sandbox.gpuarray.elemwise.GpuDimShuffle 0.7% 99.8% 0.026s 2.59e-06s C 10001 2 aesara.sandbox.gpuarray.basic_ops.GpuAllocEmpty", "1 GpuElemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)]<gpuarray> 2.5% 96.7% 0.096s", "0.2% 99.8% 0.008s 7.94e-07s 10000 8 InplaceGpuDimShuffle{x}(GpuFromHost<None>.0) 0.1% 99.9% 0.005s", "93.4% 0.162s 8.10e-06s C 20001 3 aesara.sandbox.gpuarray.basic_ops.HostFromGpu 3.3% 96.7% 0.131s", "the runtime) # 2.2 Profiling for GPU computations # In", "train() # print \"Final model:\" # print w.get_value(), b.get_value() print(\"target", "64.5% 64.5% 0.747s 3.73e-05s C 20001 3 aesara.tensor.blas_c.CGemv 33.1% 97.7%", "0.0% 100.0% 0.000s 1.19e-06s 1 0 InplaceDimShuffle{x}(b) ... (remaining 2", "of 0.5}) 1.0% 97.4% 0.011s 1.14e-06s 10000 14 Sum{acc_dtype=float64}(Elemwise{Composite{(((scalar_sigmoid(i0) *", "script: Used the gpu target values for D prediction on", "prediction that is done: 0 or 1 xent = -y", "0.0% 100.0% 0.000s 3.89e-05s 1 3 CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0}, x, w,", "[\"GpuGemm\", \"GpuGemv\"] for n in train.maker.fgraph.toposort() ] ): print(\"Used the", "i1 * i2) / i3) - ((i4 * i1 *", "0)]<gpuarray>.0) 2.6% 90.1% 0.102s 1.02e-05s 10000 20 GpuElemwise{Composite{(i0 - (i1", "74.6% 0.141s 1.41e-05s 10000 16 GpuElemwise{gt,no_inplace}(GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[ 0.5]}) 3.4%", "Declare Aesara symbolic variables x = aesara.shared(D[0], name=\"x\") y =", "Sum of all(2) printed profiles at exit excluding Scan op", "compare 'Ops' summaries for CPU and GPU. Usually GPU ops", "CPU @ 3.50GHz Function profiling ================== Message: Sum of all(2)", "1.6% 98.3% 0.061s 6.10e-06s C 10000 1 GpuFromHost<None> 0.7% 99.0%", "per call> <type> <#call> <#apply> <Op name> 59.5% 59.5% 2.329s", "10000 1 Elemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3 *", "runtime) # 2.2 Profiling for GPU computations # In your", "0)] 0.2% 99.9% 0.002s 1.98e-07s C 10000 1 Elemwise{Cast{float32}} 0.1%", "0.2% 99.2% 0.003s 2.65e-07s 10000 9 Elemwise{Composite{((-i0) - i1)}}[(0, 0)](CGemv{inplace}.0,", "0.162s 8.10e-06s C 20001 3 aesara.sandbox.gpuarray.basic_ops.HostFromGpu 3.3% 96.7% 0.131s 1.31e-05s", "values for D prediction on D Results were produced using", "making as few as possible data transfers between GPU and", "C 10000 1 GpuCAReduceCuda{add} 2.9% 91.7% 0.112s 1.12e-05s C 10000", "- i1))), i2)}}[]<gpuarray> ... (remaining 0 Ops account for 0.00%(0.00s)", "i3) - ((i4 * i1 * i5) / i3))}}[(0, 0)]<gpuarray>.0)", "aesara.sandbox.gpuarray.basic_ops.HostFromGpu 3.3% 96.7% 0.131s 1.31e-05s C 10000 1 aesara.sandbox.gpuarray.elemwise.GpuCAReduceCuda 1.6%", "results for each function # in the script, followed by", "D prediction on D Results were produced using a GeForce", "1.31e-05s C 10000 1 GpuCAReduceCuda{add} 2.9% 91.7% 0.112s 1.12e-05s C", "/ i3) - ((i4 * i1 * i5) / i3))}}[(0,", "98.3% 0.061s 6.10e-06s C 10000 1 GpuFromHost<None> 0.7% 99.0% 0.026s", "n in train.maker.fgraph.toposort() ] ): print(\"Used the gpu\") else: print(\"ERROR,", "8.10e-06s C 20001 3 HostFromGpu(gpuarray) 4.0% 67.6% 0.157s 1.57e-05s C", "scalar_softplus(i4)))}}[]<gpuarray>(y, GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[-1.]}, GpuElemwise{sub,no_inplace}.0, GpuElemwise{neg,no_inplace}.0) 3.8% 67.3%", "98.3% 0.061s 6.10e-06s C 10000 1 aesara.sandbox.gpuarray.basic_ops.GpuFromHost 0.8% 99.1% 0.033s", "0.133s 1.33e-05s 10000 9 GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>(GpuGemv{inplace=True}.0, InplaceGpuDimShuffle{x}.0) 3.3%", "* scalar_softplus(i4)))}}[]<gpuarray>(y, GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[-1.]}, GpuElemwise{sub,no_inplace}.0, GpuElemwise{neg,no_inplace}.0) 3.8%", "0.131s 1.31e-05s C 10000 1 GpuCAReduceCuda{add} 2.9% 91.7% 0.112s 1.12e-05s", "C 20001 3 aesara.sandbox.gpuarray.basic_ops.HostFromGpu 3.3% 96.7% 0.131s 1.31e-05s C 10000", "GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) - ((i4 *", "1.0}, y) 0.3% 98.1% 0.004s 3.76e-07s 10000 0 InplaceDimShuffle{x}(b) 0.3%", "C 10001 2 aesara.sandbox.gpuarray.basic_ops.GpuAllocEmpty 0.2% 100.0% 0.008s 3.95e-07s C 20001", "each of the GPU ops consumes more time than its", "# print \"Final model:\" # print w.get_value(), b.get_value() print(\"target values", "0.002s 1.90e-07s 10000 6 InplaceDimShuffle{x}(Shape_i{0}.0) 0.1% 99.9% 0.002s 1.54e-07s 10000", "3.3% 88.8% 0.131s 1.31e-05s C 10000 1 GpuCAReduceCuda{add} 2.9% 91.7%", "InplaceGpuDimShuffle{1,0}.0, GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) - ((i4", "call to aesara.grad() 3.286195e-02s Time since aesara import 15.415s Class", "print(D[1]) print(\"prediction on D\") print(predict()) \"\"\" # 2. Profiling #", "GPU ops consumes more time than its CPU counterpart. This", "6.10e-06s C 10000 1 aesara.sandbox.gpuarray.basic_ops.GpuFromHost 0.8% 99.1% 0.033s 1.09e-06s C", "* i3 * scalar_softplus(i4)))}}[]<gpuarray> 3.8% 71.4% 0.149s 1.49e-05s C 10000", "(93.646%) Total compile time: 9.256095e+00s Number of Apply nodes: 21", "scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray> 3.8% 71.4% 0.149s", "%> <apply time> <time per call> <#call> <id> <Apply name>", "aesara.shared(rng.randn(feats).astype(aesara.config.floatX), name=\"w\") b = aesara.shared(np.asarray(0.0, dtype=aesara.config.floatX), name=\"b\") x.tag.test_value = D[0]", "gb = tt.grad(cost, [w, b]) # Compile expressions to functions", "import aesara import aesara.tensor as tt aesara.config.floatX = \"float32\" rng", "10001 2 aesara.sandbox.gpuarray.basic_ops.GpuAllocEmpty 0.2% 100.0% 0.008s 3.95e-07s C 20001 3", "a GeForce GTX TITAN X # Profiling summary for all", "type: $ THEANO_FLAGS=profile=True,device=cpu python using_gpu_solution_1.py # You'll see first the", "size (e.g. set N = 4000), you will see a", "(remaining 2 Apply instances account for 0.00%(0.00s) of the runtime)", "C 90001 10 aesara.sandbox.gpuarray.elemwise.GpuElemwise 4.1% 93.4% 0.162s 8.10e-06s C 20001", "D[0] y.tag.test_value = D[1] # print \"Initial model:\" # print", "0.176s 1.76e-05s 10000 18 GpuGemv{inplace=True}(w, TensorConstant{-0.00999999977648}, InplaceGpuDimShuffle{1,0}.0, GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1", "InplaceGpuDimShuffle{1,0} 0.2% 100.0% 0.008s 3.95e-07s C 20001 3 Shape_i{0} 0.0%", "8.922548e-01s Number of Apply nodes: 17 Aesara Optimizer time: 6.270301e-01s", "3.89e-05s 1 3 CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0}) 0.0% 100.0%", "x, w, TensorConstant{0.0}) 0.0% 100.0% 0.000s 4.77e-06s 1 4 Elemwise{Composite{GT(scalar_sigmoid((-((-i0)", "((i4 * i1 * i5) / i3))}}[(0, 0)]<gpuarray>.0, TensorConstant{0.999800026417}) 4.0%", "0.3% 99.2% 0.004s 1.78e-07s C 20001 3 Shape_i{0} 0.2% 99.5%", "94.9% 0.090s 9.04e-06s 10000 19 HostFromGpu(gpuarray)(GpuElemwise{gt,no_inplace}.0) 1.8% 96.7% 0.072s 7.16e-06s", "2.154s 2.15e-04s 10000 7 GpuGemv{inplace=True}(GpuAllocEmpty{dtype='float32', context_name=None}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0})", "0.004s 3.76e-07s 10000 0 InplaceDimShuffle{x}(b) 0.3% 98.4% 0.004s 3.70e-07s 10000", "0.001s 1.34e-07s 10000 3 Shape_i{0}(y) 0.0% 100.0% 0.000s 3.89e-05s 1", "op profile. Time in 10001 calls to Function.__call__: 4.181247e+00s Time", "of the runtime) Apply ------ <% time> <sum %> <apply", "0.0% 100.0% 0.000s 4.77e-06s 1 4 Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}}(CGemv{inplace}.0,", "C 20001 3 CGemv{inplace} 18.7% 83.2% 0.217s 2.17e-05s C 10000", "(i2 * i3 * scalar_softplus(i4)))}}[(0, 4)] 8.9% 92.1% 0.103s 1.03e-05s", "cost = tt.cast(xent.mean(), \"float32\") + 0.01 * (w ** 2).sum()", "3.64e-07s C 10001 2 AllocEmpty{dtype='float32'} 0.3% 99.2% 0.004s 1.78e-07s C", "i3) - ((scalar_sigmoid((-i0)) * i1 * i4) / i3))}}[(0, 0)].0,", "3 InplaceGpuDimShuffle{x} 0.3% 99.8% 0.011s 1.14e-06s C 10000 1 InplaceGpuDimShuffle{1,0}", "GpuGemv{inplace=True} 4.1% 63.6% 0.162s 8.10e-06s C 20001 3 HostFromGpu(gpuarray) 4.0%", "99.7% 0.003s 2.65e-07s C 10000 1 Elemwise{Composite{((-i0) - i1)}}[(0, 0)]", "used the cpu or the gpu\") print(train.maker.fgraph.toposort()) for i in", "i1)}} 1.0% 97.4% 0.011s 1.14e-06s C 10000 1 Sum{acc_dtype=float64} 0.5%", "3 CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0}) 0.0% 100.0% 0.000s 4.77e-06s", "= aesara.shared(np.asarray(0.0, dtype=aesara.config.floatX), name=\"b\") x.tag.test_value = D[0] y.tag.test_value = D[1]", "by making as few as possible data transfers between GPU", "1.14e-06s C 10000 1 aesara.tensor.elemwise.Sum 0.7% 99.4% 0.009s 2.85e-07s C", "Aesara validate time: 6.523132e-03s Aesara Linker time (includes C, CUDA", "C 10000 1 GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray> 3.3% 88.8% 0.131s", "GpuArrayConstant{0.00999999977648}, GpuCAReduceCuda{add}.0) 2.5% 92.6% 0.096s 9.63e-06s 10000 13 GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>(GpuElemwise{neg,no_inplace}.0)", "10001 calls to Function.__call__: 1.300452e+00s Time in Function.fn.__call__: 1.215823e+00s (93.492%)", "print \"Final model:\" # print w.get_value(), b.get_value() print(\"target values for", "0.000s 3.89e-05s 1 3 CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0}) 0.0%", "] ): print(\"Used the cpu\") elif any( [ n.op.__class__.__name__ in", "time (includes C, CUDA code generation/compiling): 2.949309e-02s Import time 3.543139e-03s", "3.915566e+00s (93.646%) Total compile time: 9.256095e+00s Number of Apply nodes:", "amount of extra time, but by making as few as", "for 0.00%(0.00s) of the runtime) # 2.2 Profiling for GPU", "time: 9.996419e-01s Aesara validate time: 6.523132e-03s Aesara Linker time (includes", "10001 2 aesara.tensor.basic.AllocEmpty 0.3% 100.0% 0.004s 1.78e-07s C 20001 3", "here only the summary: Results were produced using an Intel(R)", "10000 9 GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>(GpuGemv{inplace=True}.0, InplaceGpuDimShuffle{x}.0) 3.3% 84.7% 0.131s", "** 2).sum() # The cost to optimize gw, gb =", "1.0% 97.4% 0.011s 1.14e-06s 10000 14 Sum{acc_dtype=float64}(Elemwise{Composite{(((scalar_sigmoid(i0) * i1 *", "C 10000 1 GpuElemwise{sub,no_inplace} 3.6% 78.7% 0.141s 1.41e-05s C 10000", "55.0% 2.154s 2.15e-04s 10000 7 GpuGemv{inplace=True}(GpuAllocEmpty{dtype='float32', context_name=None}.0, TensorConstant{1.0}, x, w,", "of the script: Used the gpu target values for D", "i3 * scalar_softplus(i4)))}}[]<gpuarray>.0) 1.6% 98.3% 0.061s 6.10e-06s 10000 6 GpuFromHost<None>(Shape_i{0}.0)", "0.005s 5.27e-07s 10000 1 Shape_i{0}(x) ... (remaining 7 Apply instances", "print w.get_value(), b.get_value() # Construct Aesara expression graph p_1 =", "# In your terminal, type: $ THEANO_FLAGS=profile=True,device=cpu python using_gpu_solution_1.py #", "10000 12 Elemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3 *", "3.70e-07s 10000 10 Elemwise{neg,no_inplace}(Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0) 0.3% 98.7% 0.004s", "1 Shape_i{0}(x) 0.2% 99.6% 0.002s 1.98e-07s 10000 8 Elemwise{Cast{float32}}(InplaceDimShuffle{x}.0) 0.2%", "1 aesara.sandbox.gpuarray.basic_ops.GpuFromHost 0.8% 99.1% 0.033s 1.09e-06s C 30001 4 aesara.sandbox.gpuarray.elemwise.GpuDimShuffle", "1.215823e+00s (93.492%) Time in thunks: 1.157602e+00s (89.015%) Total compile time:", "2).sum() # The cost to optimize gw, gb = tt.grad(cost,", "0)]<gpuarray>.0, GpuArrayConstant{[-1.]}, GpuElemwise{sub,no_inplace}.0, GpuElemwise{neg,no_inplace}.0) 3.8% 67.3% 0.149s 1.49e-05s 10000 15", "- i1)}}[(0, 0)]<gpuarray>.0) 2.6% 90.1% 0.102s 1.02e-05s 10000 20 GpuElemwise{Composite{(i0", "the cpu target values for D prediction on D #", "w) - b)) # Probability of having a one prediction", "3.53e-05s 10000 15 CGemv{inplace}(w, TensorConstant{-0.00999999977648}, x.T, Elemwise{Composite{(((scalar_sigmoid(i0) * i1 *", "i3 * scalar_softplus(i4)))}}[]<gpuarray>(y, GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[-1.]}, GpuElemwise{sub,no_inplace}.0, GpuElemwise{neg,no_inplace}.0)", "aesara.function(inputs=[], outputs=prediction, name=\"predict\") if any( [ n.op.__class__.__name__ in [\"Gemv\", \"CGemv\",", "name=\"train\", ) predict = aesara.function(inputs=[], outputs=prediction, name=\"predict\") if any( [", "i1)}}[(0, 0)](CGemv{inplace}.0, InplaceDimShuffle{x}.0) 0.2% 99.4% 0.002s 2.21e-07s 10000 1 Shape_i{0}(x)", "you can minimize their overhead. Notice that each of the", "context_name=None}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0}) 4.5% 59.5% 0.176s 1.76e-05s 10000", "<id> <Apply name> 55.0% 55.0% 2.154s 2.15e-04s 10000 7 GpuGemv{inplace=True}(GpuAllocEmpty{dtype='float32',", "0.004s 3.70e-07s C 10000 1 Elemwise{neg,no_inplace} 0.3% 98.9% 0.004s 3.64e-07s", "((scalar_sigmoid((-i0)) * i1 * i4) / i3))}}[(0, 0)] 4.3% 96.4%", "as np import aesara import aesara.tensor as tt aesara.config.floatX =", "gw, gb = tt.grad(cost, [w, b]) # Compile expressions to", "1.34e-07s 10000 3 Shape_i{0}(y) 0.0% 100.0% 0.000s 3.89e-05s 1 3", "done: 0 or 1 xent = -y * tt.log(p_1) -", "of the runtime) # 3. Conclusions Examine and compare 'Ops'", "CPU and GPU. Usually GPU ops 'GpuFromHost' and 'HostFromGpu' by", "on small inputs; if you increase the input data size", "produced using a GeForce GTX TITAN X # Profiling summary", "99.9% 0.005s 5.27e-07s 10000 1 Shape_i{0}(x) ... (remaining 7 Apply", "1.33e-05s 10000 10 GpuElemwise{Cast{float32}}[]<gpuarray>(InplaceGpuDimShuffle{x}.0) 3.4% 81.4% 0.133s 1.33e-05s 10000 9", "i2))}}[(0, 0)]<gpuarray>(b, GpuArrayConstant{0.00999999977648}, GpuCAReduceCuda{add}.0) 2.5% 92.6% 0.096s 9.63e-06s 10000 13", "i1)}}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[-1.]}, GpuElemwise{sub,no_inplace}.0, GpuElemwise{neg,no_inplace}.0) 3.8% 67.3% 0.149s 1.49e-05s 10000", "you increase the input data size (e.g. set N =", "- b)) # Probability of having a one prediction =", "at exit excluding Scan op profile. Time in 10001 calls", "0.112s 1.12e-05s 10000 11 GpuElemwise{neg,no_inplace}(GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0) 2.6% 90.1%", "0.2% 99.9% 0.002s 1.98e-07s C 10000 1 Elemwise{Cast{float32}} 0.1% 100.0%", "30.5% 64.5% 0.353s 3.53e-05s 10000 15 CGemv{inplace}(w, TensorConstant{-0.00999999977648}, x.T, Elemwise{Composite{(((scalar_sigmoid(i0)", "<Op name> 64.5% 64.5% 0.747s 3.73e-05s C 20001 3 CGemv{inplace}", "GpuElemwise{gt,no_inplace}(GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[ 0.5]}) 3.4% 78.0% 0.133s 1.33e-05s 10000 10", "98.1% 0.004s 3.76e-07s 10000 0 InplaceDimShuffle{x}(b) 0.3% 98.4% 0.004s 3.70e-07s", "3.95e-07s C 20001 3 aesara.compile.ops.Shape_i ... (remaining 0 Classes account", "InplaceGpuDimShuffle{1,0}(x) 0.2% 99.8% 0.008s 7.94e-07s 10000 8 InplaceGpuDimShuffle{x}(GpuFromHost<None>.0) 0.1% 99.9%", "first the output of the script: Used the cpu target", "3.73e-05s C 20001 3 aesara.tensor.blas_c.CGemv 33.1% 97.7% 0.384s 4.79e-06s C", "GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray> 3.8%", "[ n.op.__class__.__name__ in [\"Gemv\", \"CGemv\", \"Gemm\", \"CGemm\"] for n in", "Aesara Optimizer time: 6.270301e-01s Aesara validate time: 5.993605e-03s Aesara Linker", "'Using the GPU' # 1. Raw results import numpy as", "InplaceDimShuffle{x}(Shape_i{0}.0) 0.1% 99.9% 0.002s 1.54e-07s 10000 16 Elemwise{Composite{(i0 - (i1", "transfers between GPU and CPU, you can minimize their overhead.", "This is because the ops operate on small inputs; if", "i in range(training_steps): pred, err = train() # print \"Final", "Ops --- <% time> <sum %> <apply time> <time per", "Elemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)](b, TensorConstant{0.00999999977648}, Sum{acc_dtype=float64}.0) 0.1% 100.0%", "C 10000 1 Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3)", "Elemwise{sub,no_inplace}.0) 4.3% 96.4% 0.050s 4.98e-06s 10000 11 Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}}(Elemwise{neg,no_inplace}.0, TensorConstant{(1,)", "9.63e-06s C 10000 1 GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray> 1.6% 98.3% 0.061s 6.10e-06s", "aesara.tensor.elemwise.DimShuffle 0.3% 99.7% 0.004s 3.64e-07s C 10001 2 aesara.tensor.basic.AllocEmpty 0.3%", "any( [ n.op.__class__.__name__ in [\"Gemv\", \"CGemv\", \"Gemm\", \"CGemm\"] for n", "HostFromGpu(gpuarray)(GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray>.0) 1.6%", "print(\"ERROR, not able to tell if aesara used the cpu", "Function.fn.__call__: 1.215823e+00s (93.492%) Time in thunks: 1.157602e+00s (89.015%) Total compile", "2.6% 94.3% 0.102s 1.02e-05s C 10000 1 GpuElemwise{Composite{(i0 - (i1", "0.103s 1.03e-05s 10000 13 Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) /", "y) * tt.log(1 - p_1) # Cross-entropy cost = tt.cast(xent.mean(),", "of the runtime) Ops --- <% time> <sum %> <apply", "values for D\") print(D[1]) print(\"prediction on D\") print(predict()) \"\"\" #", "C 10000 1 aesara.sandbox.gpuarray.elemwise.GpuCAReduceCuda 1.6% 98.3% 0.061s 6.10e-06s C 10000", "99.6% 0.011s 1.14e-06s 10000 2 InplaceGpuDimShuffle{1,0}(x) 0.2% 99.8% 0.008s 7.94e-07s", "profiling ================== Message: Sum of all(2) printed profiles at exit", "Shape_i{0} 0.2% 99.5% 0.003s 2.88e-07s C 10000 1 InplaceDimShuffle{1,0} 0.2%", "* (w ** 2).sum() # The cost to optimize gw,", "the runtime) # 3. Conclusions Examine and compare 'Ops' summaries", "runtime) Ops --- <% time> <sum %> <apply time> <time", "34.0% 34.0% 0.394s 3.94e-05s 10000 7 CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0}, x, w,", "GPU ops 'GpuFromHost' and 'HostFromGpu' by themselves consume a large", "the cpu or the gpu\") print(train.maker.fgraph.toposort()) for i in range(training_steps):", "(i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray> 3.8% 71.4% 0.149s 1.49e-05s C", "inputs=[], outputs=[prediction, xent], updates=[(w, w - 0.01 * gw), (b,", "you will see a gain from using the GPU. \"\"\"", "<gh_stars>0 #!/usr/bin/env python # Aesara tutorial # Solution to Exercise", "5.27e-07s 10000 1 Shape_i{0}(x) ... (remaining 7 Apply instances account", "63.6% 0.162s 8.10e-06s C 20001 3 HostFromGpu(gpuarray) 4.0% 67.6% 0.157s", "0.3% 98.7% 0.004s 3.64e-07s 10000 5 AllocEmpty{dtype='float32'}(Shape_i{0}.0) 0.2% 99.0% 0.003s", ") predict = aesara.function(inputs=[], outputs=prediction, name=\"predict\") if any( [ n.op.__class__.__name__", "= p_1 > 0.5 # The prediction that is done:", "3.3% 84.7% 0.131s 1.31e-05s 10000 17 GpuCAReduceCuda{add}(GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 *", "i4) / i3))}}[(0, 0)](Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0, TensorConstant{(1,) of -1.0},", "2 InplaceGpuDimShuffle{1,0}(x) 0.2% 99.8% 0.008s 7.94e-07s 10000 8 InplaceGpuDimShuffle{x}(GpuFromHost<None>.0) 0.1%", "can minimize their overhead. Notice that each of the GPU", "model:\" # print w.get_value(), b.get_value() # Construct Aesara expression graph", "10000 7 GpuGemv{inplace=True}(GpuAllocEmpty{dtype='float32', context_name=None}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0}) 4.5% 59.5%", "1 / (1 + tt.exp(-tt.dot(x, w) - b)) # Probability", "scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[(0, 4)](y, Elemwise{Composite{((-i0) -", "i5) / i3))}}[(0, 0)]<gpuarray>.0) 2.9% 87.5% 0.112s 1.12e-05s 10000 11", "2 InplaceDimShuffle{1,0}(x) 0.2% 99.2% 0.003s 2.65e-07s 10000 9 Elemwise{Composite{((-i0) -", "... (remaining 7 Apply instances account for 0.07%(0.00s) of the", "calls to Function.__call__: 4.181247e+00s Time in Function.fn.__call__: 4.081113e+00s (97.605%) Time", "(89.015%) Total compile time: 8.922548e-01s Number of Apply nodes: 17", "print(\"target values for D\") print(D[1]) print(\"prediction on D\") print(predict()) \"\"\"", "if aesara used the cpu or the gpu\") print(train.maker.fgraph.toposort()) for", "10000 1 Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}} 1.0% 97.4% 0.011s 1.14e-06s C 10000", "C 10000 1 GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3)", "1.12e-05s C 10000 1 GpuElemwise{neg,no_inplace} 2.6% 94.3% 0.102s 1.02e-05s C", "python # Aesara tutorial # Solution to Exercise in section", "8.10e-06s C 20001 3 aesara.sandbox.gpuarray.basic_ops.HostFromGpu 3.3% 96.7% 0.131s 1.31e-05s C", "<time per call> <#call> <id> <Apply name> 55.0% 55.0% 2.154s", "functions. # We'll show here only the summary: Results were", "your terminal, type: $ CUDA_LAUNCH_BLOCKING=1 THEANO_FLAGS=profile=True,device=cuda python using_gpu_solution_1.py # You'll", "- i1)}}[(0, 0)] 0.2% 99.9% 0.002s 1.98e-07s C 10000 1", "<#apply> <Class name> 64.5% 64.5% 0.747s 3.73e-05s C 20001 3", "outputs=prediction, name=\"predict\") if any( [ n.op.__class__.__name__ in [\"Gemv\", \"CGemv\", \"Gemm\",", "the runtime) Ops --- <% time> <sum %> <apply time>", "to optimize gw, gb = tt.grad(cost, [w, b]) # Compile", "Time in thunks: 3.915566e+00s (93.646%) Total compile time: 9.256095e+00s Number", "i3))}}[(0, 0)](Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0, TensorConstant{(1,) of -1.0}, y, Elemwise{Cast{float32}}.0,", "1 aesara.sandbox.gpuarray.elemwise.GpuCAReduceCuda 1.6% 98.3% 0.061s 6.10e-06s C 10000 1 aesara.sandbox.gpuarray.basic_ops.GpuFromHost", "i3) - ((scalar_sigmoid((-i0)) * i1 * i4) / i3))}}[(0, 0)]", "err = train() # print \"Final model:\" # print w.get_value(),", "Elemwise{Composite{((-i0) - i1)}}[(0, 0)] 0.2% 99.9% 0.002s 1.98e-07s C 10000", "call> <type> <#call> <#apply> <Op name> 64.5% 64.5% 0.747s 3.73e-05s", "97.9% 0.006s 2.83e-07s C 20001 3 InplaceDimShuffle{x} 0.4% 98.3% 0.004s", "20 GpuElemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)]<gpuarray>(b, GpuArrayConstant{0.00999999977648}, GpuCAReduceCuda{add}.0) 2.5%", "for 0.07%(0.00s) of the runtime) # 3. Conclusions Examine and", "op profile. Time in 10001 calls to Function.__call__: 1.300452e+00s Time", "= ( rng.randn(N, feats).astype(aesara.config.floatX), rng.randint(size=N, low=0, high=2).astype(aesara.config.floatX), ) training_steps =", "print(predict()) \"\"\" # 2. Profiling # 2.1 Profiling for CPU", "i2))}}[(0, 0)](b, TensorConstant{0.00999999977648}, Sum{acc_dtype=float64}.0) 0.1% 100.0% 0.001s 1.34e-07s 10000 3", "in all call to aesara.grad() 3.286195e-02s Time since aesara import", "for all functions: Function profiling ================== Message: Sum of all(2)", "5.993605e-03s Aesara Linker time (includes C, CUDA code generation/compiling): 2.949309e-02s", "compile time: 8.922548e-01s Number of Apply nodes: 17 Aesara Optimizer", "1.49e-05s C 10000 1 GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) /", "for D prediction on D # Followed by the output", "67.6% 0.157s 1.57e-05s C 10000 1 GpuElemwise{Composite{((i0 * scalar_softplus(i1)) -", "4.3% 96.4% 0.050s 4.98e-06s 10000 11 Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}}(Elemwise{neg,no_inplace}.0, TensorConstant{(1,) of", "100.0% 0.008s 3.95e-07s C 20001 3 Shape_i{0} 0.0% 100.0% 0.000s", "1 Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) - ((scalar_sigmoid((-i0))", "Conclusions Examine and compare 'Ops' summaries for CPU and GPU.", "p_1 = 1 / (1 + tt.exp(-tt.dot(x, w) - b))", "GpuFromHost<None>(Shape_i{0}.0) 0.7% 99.0% 0.026s 2.59e-06s 10000 5 GpuAllocEmpty{dtype='float32', context_name=None}(Shape_i{0}.0) 0.3%", "* i1 * i4) / i3))}}[(0, 0)](Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0,", "- ((i4 * i1 * i5) / i3))}}[(0, 0)]<gpuarray>.0, TensorConstant{0.999800026417})", "1.6% 98.3% 0.061s 6.10e-06s 10000 6 GpuFromHost<None>(Shape_i{0}.0) 0.7% 99.0% 0.026s", "were produced using an Intel(R) Core(TM) i7-5930K CPU @ 3.50GHz", "in thunks: 1.157602e+00s (89.015%) Total compile time: 8.922548e-01s Number of", "55.0% 55.0% 2.154s 2.15e-04s 10000 7 GpuGemv{inplace=True}(GpuAllocEmpty{dtype='float32', context_name=None}.0, TensorConstant{1.0}, x,", "8.239602e+00s Import time 4.228115e-03s Time in all call to aesara.grad()", "Raw results import numpy as np import aesara import aesara.tensor", "print w.get_value(), b.get_value() print(\"target values for D\") print(D[1]) print(\"prediction on", "time: 5.993605e-03s Aesara Linker time (includes C, CUDA code generation/compiling):", "96.4% 0.050s 4.98e-06s 10000 11 Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}}(Elemwise{neg,no_inplace}.0, TensorConstant{(1,) of 0.5})", "= \"float32\" rng = np.random N = 400 feats =", "2. Profiling # 2.1 Profiling for CPU computations # In", "terminal, type: $ CUDA_LAUNCH_BLOCKING=1 THEANO_FLAGS=profile=True,device=cuda python using_gpu_solution_1.py # You'll see", "# Cross-entropy cost = tt.cast(xent.mean(), \"float32\") + 0.01 * (w", "(97.605%) Time in thunks: 3.915566e+00s (93.646%) Total compile time: 9.256095e+00s", "- i1))), i2)}} ... (remaining 0 Ops account for 0.00%(0.00s)", "* i2))}}[(0, 0)](b, TensorConstant{0.00999999977648}, Sum{acc_dtype=float64}.0) 0.1% 100.0% 0.001s 1.34e-07s 10000", "10000 2 InplaceDimShuffle{1,0}(x) 0.2% 99.2% 0.003s 2.65e-07s 10000 9 Elemwise{Composite{((-i0)", "b.get_value() # Construct Aesara expression graph p_1 = 1 /", "to aesara.grad() 1.848292e-02s Time since aesara import 2.864s Class ---", "for D prediction on D Results were produced using a", "aesara.config.floatX = \"float32\" rng = np.random N = 400 feats", "w - 0.01 * gw), (b, b - 0.01 *", "i1 * i5) / i3))}}[(0, 0)]<gpuarray> 3.7% 75.1% 0.144s 1.44e-05s", "(i2 * i3 * scalar_softplus(i4)))}}[(0, 4)](y, Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0,", "aesara.sandbox.gpuarray.elemwise.GpuCAReduceCuda 1.6% 98.3% 0.061s 6.10e-06s C 10000 1 aesara.sandbox.gpuarray.basic_ops.GpuFromHost 0.8%", "of all(2) printed profiles at exit excluding Scan op profile.", "on D # Followed by the output of profiling.. You'll", "TensorConstant{-0.00999999977648}, InplaceGpuDimShuffle{1,0}.0, GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) -", "10000 12 GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3 *", "p_1 > 0.5 # The prediction that is done: 0", "11 GpuElemwise{neg,no_inplace}(GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0) 2.6% 90.1% 0.102s 1.02e-05s 10000", "print(train.maker.fgraph.toposort()) for i in range(training_steps): pred, err = train() #", "<#call> <id> <Apply name> 34.0% 34.0% 0.394s 3.94e-05s 10000 7", "((i4 * i1 * i5) / i3))}}[(0, 0)]<gpuarray>.0) 2.9% 87.5%", "output of the script: Used the cpu target values for", "1.78e-07s C 20001 3 aesara.compile.ops.Shape_i ... (remaining 0 Classes account", "6.10e-06s C 10000 1 GpuFromHost<None> 0.7% 99.0% 0.026s 2.59e-06s C", "aesara.shared(D[0], name=\"x\") y = aesara.shared(D[1], name=\"y\") w = aesara.shared(rng.randn(feats).astype(aesara.config.floatX), name=\"w\")", "D # Followed by the output of profiling.. You'll see", "time: 6.523132e-03s Aesara Linker time (includes C, CUDA code generation/compiling):", "3.6% 78.7% 0.141s 1.41e-05s C 10000 1 GpuElemwise{gt,no_inplace} 3.4% 82.1%", "* gw), (b, b - 0.01 * gb)], name=\"train\", )", "Aesara expression graph p_1 = 1 / (1 + tt.exp(-tt.dot(x,", "i1 * i5) / i3))}}[(0, 0)]<gpuarray>.0, TensorConstant{0.999800026417}) 4.0% 63.5% 0.157s", "0 or 1 xent = -y * tt.log(p_1) - (1", "Apply nodes: 21 Aesara Optimizer time: 9.996419e-01s Aesara validate time:", "large amount of extra time, but by making as few", "TensorConstant{(1,) of -1.0}, y, Elemwise{Cast{float32}}.0, Elemwise{sub,no_inplace}.0) 4.3% 96.4% 0.050s 4.98e-06s", "Elemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[(0, 4)](y,", "0.00%(0.00s) of the runtime) Ops --- <% time> <sum %>", "i1)}}[(0, 0)].0) 0.3% 98.7% 0.004s 3.64e-07s 10000 5 AllocEmpty{dtype='float32'}(Shape_i{0}.0) 0.2%", "89.3% 1.166s 1.30e-05s C 90001 10 aesara.sandbox.gpuarray.elemwise.GpuElemwise 4.1% 93.4% 0.162s", "y) 0.3% 98.1% 0.004s 3.76e-07s 10000 0 InplaceDimShuffle{x}(b) 0.3% 98.4%", "In your terminal, type: $ THEANO_FLAGS=profile=True,device=cpu python using_gpu_solution_1.py # You'll", "GPU' # 1. Raw results import numpy as np import", "0.157s 1.57e-05s C 10000 1 GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2", "10000 1 Elemwise{Cast{float32}} 0.1% 100.0% 0.002s 1.54e-07s C 10000 1", "Shape_i{0}(x) 0.2% 99.6% 0.002s 1.98e-07s 10000 8 Elemwise{Cast{float32}}(InplaceDimShuffle{x}.0) 0.2% 99.7%", "b - 0.01 * gb)], name=\"train\", ) predict = aesara.function(inputs=[],", "i2)}} ... (remaining 0 Ops account for 0.00%(0.00s) of the", "0.000s 4.77e-06s 1 4 Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}}(CGemv{inplace}.0, InplaceDimShuffle{x}.0, TensorConstant{(1,)", "10000 0 InplaceGpuDimShuffle{x}(b) 0.3% 99.6% 0.011s 1.14e-06s 10000 2 InplaceGpuDimShuffle{1,0}(x)", "99.7% 0.004s 3.64e-07s C 10001 2 aesara.tensor.basic.AllocEmpty 0.3% 100.0% 0.004s", "InplaceDimShuffle{x}(b) 0.3% 98.4% 0.004s 3.70e-07s 10000 10 Elemwise{neg,no_inplace}(Elemwise{Composite{((-i0) - i1)}}[(0,", "30001 4 aesara.tensor.elemwise.DimShuffle 0.3% 99.7% 0.004s 3.64e-07s C 10001 2", "name> 64.5% 64.5% 0.747s 3.73e-05s C 20001 3 aesara.tensor.blas_c.CGemv 33.1%", "1.49e-05s 10000 15 GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3)", "2.15e-04s 10000 7 GpuGemv{inplace=True}(GpuAllocEmpty{dtype='float32', context_name=None}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0}) 4.5%", "generation/compiling): 2.949309e-02s Import time 3.543139e-03s Time in all call to", "10000 1 GpuElemwise{Cast{float32}}[]<gpuarray> 3.4% 85.5% 0.133s 1.33e-05s C 10000 1", "GpuElemwise{neg,no_inplace} 2.6% 94.3% 0.102s 1.02e-05s C 10000 1 GpuElemwise{Composite{(i0 -", "2.83e-07s C 20001 3 InplaceDimShuffle{x} 0.4% 98.3% 0.004s 4.22e-07s C", "10000 20 GpuElemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)]<gpuarray>(b, GpuArrayConstant{0.00999999977648}, GpuCAReduceCuda{add}.0)", "400 feats = 784 D = ( rng.randn(N, feats).astype(aesara.config.floatX), rng.randint(size=N,", "3.64e-07s C 10001 2 aesara.tensor.basic.AllocEmpty 0.3% 100.0% 0.004s 1.78e-07s C", "3.76e-07s 10000 0 InplaceDimShuffle{x}(b) 0.3% 98.4% 0.004s 3.70e-07s 10000 10", "0 Classes account for 0.00%(0.00s) of the runtime) Ops ---", "0.003s 2.65e-07s 10000 9 Elemwise{Composite{((-i0) - i1)}}[(0, 0)](CGemv{inplace}.0, InplaceDimShuffle{x}.0) 0.2%", "1.54e-07s C 10000 1 Elemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)]", "0.000s 2.00e-05s C 1 1 GpuElemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}}[]<gpuarray> ...", "the output of profiling.. You'll see profiling results for each", "* tt.log(1 - p_1) # Cross-entropy cost = tt.cast(xent.mean(), \"float32\")", "10000 13 Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) -", "((i4 * i1 * i5) / i3))}}[(0, 0)]<gpuarray> 3.7% 75.1%", "16 GpuElemwise{gt,no_inplace}(GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[ 0.5]}) 3.4% 78.0% 0.133s 1.33e-05s 10000", "runtime) # 3. Conclusions Examine and compare 'Ops' summaries for", "pred, err = train() # print \"Final model:\" # print", "* scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray> 3.8% 71.4%", "profile. Time in 10001 calls to Function.__call__: 4.181247e+00s Time in", "[ n.op.__class__.__name__ in [\"GpuGemm\", \"GpuGemv\"] for n in train.maker.fgraph.toposort() ]", "): print(\"Used the gpu\") else: print(\"ERROR, not able to tell", "by themselves consume a large amount of extra time, but", "3.4% 81.4% 0.133s 1.33e-05s 10000 9 GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>(GpuGemv{inplace=True}.0,", "[w, b]) # Compile expressions to functions train = aesara.function(", "runtime) Apply ------ <% time> <sum %> <apply time> <time", "1 3 CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0}) 0.0% 100.0% 0.000s", "0.747s 3.73e-05s C 20001 3 aesara.tensor.blas_c.CGemv 33.1% 97.7% 0.384s 4.79e-06s", "= tt.cast(xent.mean(), \"float32\") + 0.01 * (w ** 2).sum() #", "InplaceGpuDimShuffle{x} 0.3% 99.8% 0.011s 1.14e-06s C 10000 1 InplaceGpuDimShuffle{1,0} 0.2%", "b]) # Compile expressions to functions train = aesara.function( inputs=[],", "1.03e-05s C 10000 1 Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) /", "for CPU and GPU. Usually GPU ops 'GpuFromHost' and 'HostFromGpu'", "0)].0, TensorConstant{(1,) of -1.0}, Elemwise{sub,no_inplace}.0, Elemwise{neg,no_inplace}.0) 8.9% 92.1% 0.103s 1.03e-05s", "for CPU computations # In your terminal, type: $ THEANO_FLAGS=profile=True,device=cpu", "having a one prediction = p_1 > 0.5 # The", "generation/compiling): 8.239602e+00s Import time 4.228115e-03s Time in all call to", "You'll see first the output of the script: Used the", "computations # In your terminal, type: $ CUDA_LAUNCH_BLOCKING=1 THEANO_FLAGS=profile=True,device=cuda python", "TensorConstant{(1,) of -1.0}, Elemwise{sub,no_inplace}.0, Elemwise{neg,no_inplace}.0) 8.9% 92.1% 0.103s 1.03e-05s 10000", "gb)], name=\"train\", ) predict = aesara.function(inputs=[], outputs=prediction, name=\"predict\") if any(", "= 10000 # Declare Aesara symbolic variables x = aesara.shared(D[0],", "<apply time> <time per call> <#call> <id> <Apply name> 55.0%", "i1))), i2)}}[]<gpuarray> ... (remaining 0 Ops account for 0.00%(0.00s) of", "1.31e-05s C 10000 1 aesara.sandbox.gpuarray.elemwise.GpuCAReduceCuda 1.6% 98.3% 0.061s 6.10e-06s C", "7 Apply instances account for 0.07%(0.00s) of the runtime) #", "Used the gpu target values for D prediction on D", "4.98e-06s 10000 11 Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}}(Elemwise{neg,no_inplace}.0, TensorConstant{(1,) of 0.5}) 1.0% 97.4%", "rng.randint(size=N, low=0, high=2).astype(aesara.config.floatX), ) training_steps = 10000 # Declare Aesara", "Profiling for GPU computations # In your terminal, type: $", "the summary: Results were produced using an Intel(R) Core(TM) i7-5930K", "0.096s 9.63e-06s 10000 13 GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>(GpuElemwise{neg,no_inplace}.0) 2.3% 94.9% 0.090s 9.04e-06s", "11 Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}}(Elemwise{neg,no_inplace}.0, TensorConstant{(1,) of 0.5}) 1.0% 97.4% 0.011s 1.14e-06s", "python using_gpu_solution_1.py # You'll see first the output of the", "2.65e-07s 10000 9 Elemwise{Composite{((-i0) - i1)}}[(0, 0)](CGemv{inplace}.0, InplaceDimShuffle{x}.0) 0.2% 99.4%", "13 Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) - ((scalar_sigmoid((-i0))", "0.008s 7.94e-07s 10000 8 InplaceGpuDimShuffle{x}(GpuFromHost<None>.0) 0.1% 99.9% 0.005s 5.27e-07s 10000", "per call> <type> <#call> <#apply> <Op name> 64.5% 64.5% 0.747s", "i3) - ((scalar_sigmoid((-i0)) * i1 * i4) / i3))}}[(0, 0)].0)", "i1)}}[(0, 0)]<gpuarray>(GpuGemv{inplace=True}.0, InplaceGpuDimShuffle{x}.0) 3.3% 84.7% 0.131s 1.31e-05s 10000 17 GpuCAReduceCuda{add}(GpuElemwise{Composite{(((scalar_sigmoid(i0)", "aesara.sandbox.gpuarray.elemwise.GpuDimShuffle 0.7% 99.8% 0.026s 2.59e-06s C 10001 2 aesara.sandbox.gpuarray.basic_ops.GpuAllocEmpty 0.2%", "* scalar_softplus(i4)))}}[(0, 4)] 8.9% 92.1% 0.103s 1.03e-05s C 10000 1", "4.0% 67.6% 0.157s 1.57e-05s C 10000 1 GpuElemwise{Composite{((i0 * scalar_softplus(i1))", "all functions. # We'll show here only the summary: Results", "3 GpuGemv{inplace=True} 4.1% 63.6% 0.162s 8.10e-06s C 20001 3 HostFromGpu(gpuarray)", "10000 1 GpuCAReduceCuda{add} 2.9% 91.7% 0.112s 1.12e-05s C 10000 1", "10000 1 GpuFromHost<None> 0.7% 99.0% 0.026s 2.59e-06s C 10001 2", "i1)}}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[-1.]}, y, GpuElemwise{Cast{float32}}[]<gpuarray>.0, GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0, GpuElemwise{sub,no_inplace}.0) 3.7% 71.0%", "10000 19 HostFromGpu(gpuarray)(GpuElemwise{gt,no_inplace}.0) 1.8% 96.7% 0.072s 7.16e-06s 10000 14 HostFromGpu(gpuarray)(GpuElemwise{Composite{((i0", "if any( [ n.op.__class__.__name__ in [\"Gemv\", \"CGemv\", \"Gemm\", \"CGemm\"] for", "dtype=aesara.config.floatX), name=\"b\") x.tag.test_value = D[0] y.tag.test_value = D[1] # print", "(includes C, CUDA code generation/compiling): 2.949309e-02s Import time 3.543139e-03s Time", "in [\"Gemv\", \"CGemv\", \"Gemm\", \"CGemm\"] for n in train.maker.fgraph.toposort() ]", "InplaceDimShuffle{x} 0.4% 98.3% 0.004s 4.22e-07s C 10000 1 Elemwise{sub,no_inplace} 0.3%", "the script, followed by a summary for all functions. #", "4 aesara.tensor.elemwise.DimShuffle 0.3% 99.7% 0.004s 3.64e-07s C 10001 2 aesara.tensor.basic.AllocEmpty", "10000 1 Elemwise{neg,no_inplace} 0.3% 98.9% 0.004s 3.64e-07s C 10001 2", "0.2% 99.5% 0.003s 2.88e-07s C 10000 1 InplaceDimShuffle{1,0} 0.2% 99.7%", "prediction = p_1 > 0.5 # The prediction that is", "0.000s 1.19e-06s 1 0 InplaceDimShuffle{x}(b) ... (remaining 2 Apply instances", "# Probability of having a one prediction = p_1 >", "call> <#call> <id> <Apply name> 55.0% 55.0% 2.154s 2.15e-04s 10000", "- ((i4 * i1 * i5) / i3))}}[(0, 0)]<gpuarray> 3.7%", "99.0% 0.026s 2.59e-06s 10000 5 GpuAllocEmpty{dtype='float32', context_name=None}(Shape_i{0}.0) 0.3% 99.3% 0.013s", "TensorConstant{0.0}) 0.0% 100.0% 0.000s 4.77e-06s 1 4 Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))),", "low=0, high=2).astype(aesara.config.floatX), ) training_steps = 10000 # Declare Aesara symbolic", "20001 3 HostFromGpu(gpuarray) 4.0% 67.6% 0.157s 1.57e-05s C 10000 1", "C 20001 3 HostFromGpu(gpuarray) 4.0% 67.6% 0.157s 1.57e-05s C 10000", "output of the script: Used the gpu target values for", "(i1 * i2))}}[(0, 0)]<gpuarray>(b, GpuArrayConstant{0.00999999977648}, GpuCAReduceCuda{add}.0) 2.5% 92.6% 0.096s 9.63e-06s", "the gpu\") print(train.maker.fgraph.toposort()) for i in range(training_steps): pred, err =", "10000 8 Elemwise{Cast{float32}}(InplaceDimShuffle{x}.0) 0.2% 99.7% 0.002s 1.90e-07s 10000 6 InplaceDimShuffle{x}(Shape_i{0}.0)", "2.9% 87.5% 0.112s 1.12e-05s 10000 11 GpuElemwise{neg,no_inplace}(GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0)", "per call> <type> <#call> <#apply> <Class name> 64.5% 64.5% 0.747s", "in train.maker.fgraph.toposort() ] ): print(\"Used the gpu\") else: print(\"ERROR, not", "the GPU' # 1. Raw results import numpy as np", "2 aesara.tensor.basic.AllocEmpty 0.3% 100.0% 0.004s 1.78e-07s C 20001 3 aesara.compile.ops.Shape_i", "the input data size (e.g. set N = 4000), you", "0)]<gpuarray>.0) 2.9% 87.5% 0.112s 1.12e-05s 10000 11 GpuElemwise{neg,no_inplace}(GpuElemwise{Composite{((-i0) - i1)}}[(0,", "10000 0 InplaceDimShuffle{x}(b) 0.3% 98.4% 0.004s 3.70e-07s 10000 10 Elemwise{neg,no_inplace}(Elemwise{Composite{((-i0)", "Total compile time: 8.922548e-01s Number of Apply nodes: 17 Aesara", "for all functions. # We'll show here only the summary:", "i2)}}(CGemv{inplace}.0, InplaceDimShuffle{x}.0, TensorConstant{(1,) of 0.5}) 0.0% 100.0% 0.000s 1.19e-06s 1", "<sum %> <apply time> <time per call> <type> <#call> <#apply>", "Aesara validate time: 5.993605e-03s Aesara Linker time (includes C, CUDA", "and 'HostFromGpu' by themselves consume a large amount of extra", "see profiling results for each function # in the script,", "C 20001 3 aesara.tensor.blas_c.CGemv 33.1% 97.7% 0.384s 4.79e-06s C 80001", "the cpu\") elif any( [ n.op.__class__.__name__ in [\"GpuGemm\", \"GpuGemv\"] for", "0.131s 1.31e-05s 10000 17 GpuCAReduceCuda{add}(GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) /", "98.3% 0.061s 6.10e-06s 10000 6 GpuFromHost<None>(Shape_i{0}.0) 0.7% 99.0% 0.026s 2.59e-06s", "1 Elemwise{neg,no_inplace} 0.3% 98.9% 0.004s 3.64e-07s C 10001 2 AllocEmpty{dtype='float32'}", "(i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray>.0) 1.6% 98.3% 0.061s 6.10e-06s 10000", "Elemwise{sub,no_inplace} 0.3% 98.6% 0.004s 3.70e-07s C 10000 1 Elemwise{neg,no_inplace} 0.3%", "Apply instances account for 0.07%(0.00s) of the runtime) # 3.", "CGemv{inplace}(w, TensorConstant{-0.00999999977648}, x.T, Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3)", "model:\" # print w.get_value(), b.get_value() print(\"target values for D\") print(D[1])", "0.3% 98.6% 0.004s 3.70e-07s C 10000 1 Elemwise{neg,no_inplace} 0.3% 98.9%", "0.144s 1.44e-05s 10000 4 GpuElemwise{sub,no_inplace}(GpuArrayConstant{[ 1.]}, y) 3.6% 74.6% 0.141s", "GpuElemwise{sub,no_inplace}.0) 3.7% 71.0% 0.144s 1.44e-05s 10000 4 GpuElemwise{sub,no_inplace}(GpuArrayConstant{[ 1.]}, y)", "10000 1 GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray> 3.3% 88.8% 0.131s 1.31e-05s", "15.415s Class --- <% time> <sum %> <apply time> <time", "name=\"x\") y = aesara.shared(D[1], name=\"y\") w = aesara.shared(rng.randn(feats).astype(aesara.config.floatX), name=\"w\") b", "<Op name> 59.5% 59.5% 2.329s 1.16e-04s C 20001 3 GpuGemv{inplace=True}", "The prediction that is done: 0 or 1 xent =", "summary: Results were produced using an Intel(R) Core(TM) i7-5930K CPU", "an Intel(R) Core(TM) i7-5930K CPU @ 3.50GHz Function profiling ==================", "i5) / i3))}}[(0, 0)]<gpuarray>.0, TensorConstant{0.999800026417}) 4.0% 63.5% 0.157s 1.57e-05s 10000", "aesara.function( inputs=[], outputs=[prediction, xent], updates=[(w, w - 0.01 * gw),", "0.0% 100.0% 0.000s 4.77e-06s C 1 1 Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))),", "i1 * i4) / i3))}}[(0, 0)](Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0, TensorConstant{(1,)", "- (i1 * i2))}}[(0, 0)](b, TensorConstant{0.00999999977648}, Sum{acc_dtype=float64}.0) 0.1% 100.0% 0.001s", "14 HostFromGpu(gpuarray)(GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray>.0)", "1.98e-07s C 10000 1 Elemwise{Cast{float32}} 0.1% 100.0% 0.002s 1.54e-07s C", "b)) # Probability of having a one prediction = p_1", "4.228115e-03s Time in all call to aesara.grad() 3.286195e-02s Time since", "n.op.__class__.__name__ in [\"GpuGemm\", \"GpuGemv\"] for n in train.maker.fgraph.toposort() ] ):", "9 GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>(GpuGemv{inplace=True}.0, InplaceGpuDimShuffle{x}.0) 3.3% 84.7% 0.131s 1.31e-05s", "<Apply name> 34.0% 34.0% 0.394s 3.94e-05s 10000 7 CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0},", "20001 3 aesara.compile.ops.Shape_i ... (remaining 0 Classes account for 0.00%(0.00s)", "7.94e-07s 10000 8 InplaceGpuDimShuffle{x}(GpuFromHost<None>.0) 0.1% 99.9% 0.005s 5.27e-07s 10000 1", "/ i3))}}[(0, 0)](Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0, TensorConstant{(1,) of -1.0}, y,", "a one prediction = p_1 > 0.5 # The prediction", "GTX TITAN X # Profiling summary for all functions: Function", "1.14e-06s 10000 2 InplaceGpuDimShuffle{1,0}(x) 0.2% 99.8% 0.008s 7.94e-07s 10000 8", "i5) / i3))}}[(0, 0)]<gpuarray> 3.7% 75.1% 0.144s 1.44e-05s C 10000", "i3 * scalar_softplus(i4)))}}[]<gpuarray> 3.8% 71.4% 0.149s 1.49e-05s C 10000 1", "validate time: 6.523132e-03s Aesara Linker time (includes C, CUDA code", "variables x = aesara.shared(D[0], name=\"x\") y = aesara.shared(D[1], name=\"y\") w", "Results were produced using a GeForce GTX TITAN X #", "- 0.01 * gb)], name=\"train\", ) predict = aesara.function(inputs=[], outputs=prediction,", "1.31e-05s 10000 17 GpuCAReduceCuda{add}(GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3)", "y = aesara.shared(D[1], name=\"y\") w = aesara.shared(rng.randn(feats).astype(aesara.config.floatX), name=\"w\") b =", "aesara used the cpu or the gpu\") print(train.maker.fgraph.toposort()) for i", "0.3% 99.8% 0.011s 1.14e-06s C 10000 1 InplaceGpuDimShuffle{1,0} 0.2% 100.0%", "using a GeForce GTX TITAN X # Profiling summary for", "2.1 Profiling for CPU computations # In your terminal, type:", "* i1 * i5) / i3))}}[(0, 0)]<gpuarray>.0) 2.9% 87.5% 0.112s", "20001 3 InplaceGpuDimShuffle{x} 0.3% 99.8% 0.011s 1.14e-06s C 10000 1", "C 1 1 Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}} ... (remaining 0", "<#call> <#apply> <Class name> 64.5% 64.5% 0.747s 3.73e-05s C 20001", "\"float32\") + 0.01 * (w ** 2).sum() # The cost", "0.2% 100.0% 0.008s 3.95e-07s C 20001 3 Shape_i{0} 0.0% 100.0%", "2 Apply instances account for 0.00%(0.00s) of the runtime) #", "10000 9 Elemwise{Composite{((-i0) - i1)}}[(0, 0)](CGemv{inplace}.0, InplaceDimShuffle{x}.0) 0.2% 99.4% 0.002s", "thunks: 3.915566e+00s (93.646%) Total compile time: 9.256095e+00s Number of Apply", "n in train.maker.fgraph.toposort() ] ): print(\"Used the cpu\") elif any(", "InplaceDimShuffle{1,0}(x) 0.2% 99.2% 0.003s 2.65e-07s 10000 9 Elemwise{Composite{((-i0) - i1)}}[(0,", "3 Shape_i{0}(y) 0.0% 100.0% 0.000s 3.89e-05s 1 3 CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0},", "100.0% 0.000s 1.19e-06s 1 0 InplaceDimShuffle{x}(b) ... (remaining 2 Apply", "in 10001 calls to Function.__call__: 1.300452e+00s Time in Function.fn.__call__: 1.215823e+00s", "x.T, Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) - ((scalar_sigmoid((-i0))", "100.0% 0.000s 2.00e-05s C 1 1 GpuElemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}}[]<gpuarray>", "Message: Sum of all(2) printed profiles at exit excluding Scan", "script, followed by a summary for all functions. # We'll", "10000 17 GpuCAReduceCuda{add}(GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) -", "* scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[(0, 4)](y, Elemwise{Composite{((-i0)", "2.329s 1.16e-04s C 20001 3 GpuGemv{inplace=True} 4.1% 63.6% 0.162s 8.10e-06s", "3.4% 85.5% 0.133s 1.33e-05s C 10000 1 GpuElemwise{Composite{((-i0) - i1)}}[(0,", "and compare 'Ops' summaries for CPU and GPU. Usually GPU", "in train.maker.fgraph.toposort() ] ): print(\"Used the cpu\") elif any( [", "71.4% 0.149s 1.49e-05s C 10000 1 GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 *", "D = ( rng.randn(N, feats).astype(aesara.config.floatX), rng.randint(size=N, low=0, high=2).astype(aesara.config.floatX), ) training_steps", "1.76e-05s 10000 18 GpuGemv{inplace=True}(w, TensorConstant{-0.00999999977648}, InplaceGpuDimShuffle{1,0}.0, GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 *", "- i1)}}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[-1.]}, GpuElemwise{sub,no_inplace}.0, GpuElemwise{neg,no_inplace}.0) 3.8% 67.3% 0.149s 1.49e-05s", "97.4% 0.011s 1.14e-06s 10000 14 Sum{acc_dtype=float64}(Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2)", "2.5% 92.6% 0.096s 9.63e-06s 10000 13 GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>(GpuElemwise{neg,no_inplace}.0) 2.3% 94.9%", "/ i3))}}[(0, 0)]<gpuarray>(GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[-1.]}, y, GpuElemwise{Cast{float32}}[]<gpuarray>.0, GpuElemwise{ScalarSigmoid}[(0,", "================== Message: Sum of all(2) printed profiles at exit excluding", "consumes more time than its CPU counterpart. This is because", "- (i2 * i3 * scalar_softplus(i4)))}}[(0, 4)](y, Elemwise{Composite{((-i0) - i1)}}[(0,", "97.7% 0.384s 4.79e-06s C 80001 9 aesara.tensor.elemwise.Elemwise 1.0% 98.6% 0.011s", "name=\"b\") x.tag.test_value = D[0] y.tag.test_value = D[1] # print \"Initial", "time> <time per call> <type> <#call> <#apply> <Class name> 59.5%", "context_name=None} 0.5% 99.5% 0.021s 1.06e-06s C 20001 3 InplaceGpuDimShuffle{x} 0.3%", "10000 1 aesara.sandbox.gpuarray.elemwise.GpuCAReduceCuda 1.6% 98.3% 0.061s 6.10e-06s C 10000 1", "4)] 8.9% 92.1% 0.103s 1.03e-05s C 10000 1 Elemwise{Composite{(((scalar_sigmoid(i0) *", "3. Conclusions Examine and compare 'Ops' summaries for CPU and", "5 GpuAllocEmpty{dtype='float32', context_name=None}(Shape_i{0}.0) 0.3% 99.3% 0.013s 1.33e-06s 10000 0 InplaceGpuDimShuffle{x}(b)", "GpuElemwise{gt,no_inplace} 3.4% 82.1% 0.133s 1.33e-05s C 10000 1 GpuElemwise{Cast{float32}}[]<gpuarray> 3.4%", "C 10001 2 AllocEmpty{dtype='float32'} 0.3% 99.2% 0.004s 1.78e-07s C 20001", "TensorConstant{0.999800026417}) 18.7% 83.2% 0.217s 2.17e-05s 10000 12 Elemwise{Composite{((i0 * scalar_softplus(i1))", "2.329s 1.16e-04s C 20001 3 aesara.sandbox.gpuarray.blas.GpuGemv 29.8% 89.3% 1.166s 1.30e-05s", "Probability of having a one prediction = p_1 > 0.5", "in thunks: 3.915566e+00s (93.646%) Total compile time: 9.256095e+00s Number of", "C 10000 1 GpuElemwise{neg,no_inplace} 2.6% 94.3% 0.102s 1.02e-05s C 10000", "Shape_i{0}(x) ... (remaining 7 Apply instances account for 0.07%(0.00s) of", "1 Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}} ... (remaining 0 Ops account", "59.5% 2.329s 1.16e-04s C 20001 3 GpuGemv{inplace=True} 4.1% 63.6% 0.162s", "6 InplaceDimShuffle{x}(Shape_i{0}.0) 0.1% 99.9% 0.002s 1.54e-07s 10000 16 Elemwise{Composite{(i0 -", "using an Intel(R) Core(TM) i7-5930K CPU @ 3.50GHz Function profiling", "10000 1 GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray> 1.6% 98.3% 0.061s 6.10e-06s C 10000", "thunks: 1.157602e+00s (89.015%) Total compile time: 8.922548e-01s Number of Apply", "Sum{acc_dtype=float64}.0) 0.1% 100.0% 0.001s 1.34e-07s 10000 3 Shape_i{0}(y) 0.0% 100.0%", "0.00%(0.00s) of the runtime) Apply ------ <% time> <sum %>", "4.1% 93.4% 0.162s 8.10e-06s C 20001 3 aesara.sandbox.gpuarray.basic_ops.HostFromGpu 3.3% 96.7%", "i3))}}[(0, 0)].0, TensorConstant{0.999800026417}) 18.7% 83.2% 0.217s 2.17e-05s 10000 12 Elemwise{Composite{((i0", "We'll show here only the summary: Results were produced using", "... (remaining 2 Apply instances account for 0.00%(0.00s) of the", "w, TensorConstant{0.0}) 0.0% 100.0% 0.000s 4.77e-06s 1 4 Elemwise{Composite{GT(scalar_sigmoid((-((-i0) -", "Elemwise{Cast{float32}} 0.1% 100.0% 0.002s 1.54e-07s C 10000 1 Elemwise{Composite{(i0 -", "(1 - y) * tt.log(1 - p_1) # Cross-entropy cost", "12 GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray>(y,", "<time per call> <type> <#call> <#apply> <Op name> 64.5% 64.5%", "2.59e-06s C 10001 2 aesara.sandbox.gpuarray.basic_ops.GpuAllocEmpty 0.2% 100.0% 0.008s 3.95e-07s C", "InplaceGpuDimShuffle{x}.0) 3.3% 84.7% 0.131s 1.31e-05s 10000 17 GpuCAReduceCuda{add}(GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1", "time> <time per call> <type> <#call> <#apply> <Class name> 64.5%", "1 1 Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}} ... (remaining 0 Ops", "train = aesara.function( inputs=[], outputs=[prediction, xent], updates=[(w, w - 0.01", "C 20001 3 Shape_i{0} 0.0% 100.0% 0.000s 2.00e-05s C 1", "time, but by making as few as possible data transfers", "6.523132e-03s Aesara Linker time (includes C, CUDA code generation/compiling): 8.239602e+00s", "\"GpuGemv\"] for n in train.maker.fgraph.toposort() ] ): print(\"Used the gpu\")", "i4) / i3))}}[(0, 0)].0) 0.4% 97.8% 0.004s 4.22e-07s 10000 4", "<time per call> <type> <#call> <#apply> <Class name> 64.5% 64.5%", "on D\") print(predict()) \"\"\" # 2. Profiling # 2.1 Profiling", "4.181247e+00s Time in Function.fn.__call__: 4.081113e+00s (97.605%) Time in thunks: 3.915566e+00s", "scalar_softplus(i4)))}}[]<gpuarray>.0) 1.6% 98.3% 0.061s 6.10e-06s 10000 6 GpuFromHost<None>(Shape_i{0}.0) 0.7% 99.0%", "w.get_value(), b.get_value() print(\"target values for D\") print(D[1]) print(\"prediction on D\")", "1 Sum{acc_dtype=float64} 0.5% 97.9% 0.006s 2.83e-07s C 20001 3 InplaceDimShuffle{x}", "GpuElemwise{Cast{float32}}[]<gpuarray> 3.4% 85.5% 0.133s 1.33e-05s C 10000 1 GpuElemwise{Composite{((-i0) -", "the gpu\") else: print(\"ERROR, not able to tell if aesara", "1 aesara.tensor.elemwise.Sum 0.7% 99.4% 0.009s 2.85e-07s C 30001 4 aesara.tensor.elemwise.DimShuffle", "0.050s 4.98e-06s C 10000 1 Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}} 1.0% 97.4% 0.011s", "$ THEANO_FLAGS=profile=True,device=cpu python using_gpu_solution_1.py # You'll see first the output", "0.003s 2.65e-07s C 10000 1 Elemwise{Composite{((-i0) - i1)}}[(0, 0)] 0.2%", "1 GpuFromHost<None> 0.7% 99.0% 0.026s 2.59e-06s C 10001 2 GpuAllocEmpty{dtype='float32',", "2.00e-05s C 1 1 GpuElemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}}[]<gpuarray> ... (remaining", "0.3% 100.0% 0.004s 1.78e-07s C 20001 3 aesara.compile.ops.Shape_i ... (remaining", "1.03e-05s 10000 13 Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3)", "in Function.fn.__call__: 1.215823e+00s (93.492%) Time in thunks: 1.157602e+00s (89.015%) Total", "\"CGemv\", \"Gemm\", \"CGemm\"] for n in train.maker.fgraph.toposort() ] ): print(\"Used", "81.4% 0.133s 1.33e-05s 10000 9 GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>(GpuGemv{inplace=True}.0, InplaceGpuDimShuffle{x}.0)", "* scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray>.0) 1.6% 98.3%", "Function.__call__: 4.181247e+00s Time in Function.fn.__call__: 4.081113e+00s (97.605%) Time in thunks:", "GpuArrayConstant{[-1.]}, y, GpuElemwise{Cast{float32}}[]<gpuarray>.0, GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0, GpuElemwise{sub,no_inplace}.0) 3.7% 71.0% 0.144s 1.44e-05s", "0.2% 99.0% 0.003s 2.88e-07s 10000 2 InplaceDimShuffle{1,0}(x) 0.2% 99.2% 0.003s", "see first the output of the script: Used the gpu", "per call> <#call> <id> <Apply name> 34.0% 34.0% 0.394s 3.94e-05s", "99.6% 0.002s 1.98e-07s 10000 8 Elemwise{Cast{float32}}(InplaceDimShuffle{x}.0) 0.2% 99.7% 0.002s 1.90e-07s", "C 10000 1 Elemwise{sub,no_inplace} 0.3% 98.6% 0.004s 3.70e-07s C 10000", "only the summary: Results were produced using an Intel(R) Core(TM)", "- i1)}}[(0, 0)].0, TensorConstant{(1,) of -1.0}, Elemwise{sub,no_inplace}.0, Elemwise{neg,no_inplace}.0) 8.9% 92.1%", "Elemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)] 0.0% 100.0% 0.000s 4.77e-06s", "0.1% 99.9% 0.005s 5.27e-07s 10000 1 Shape_i{0}(x) ... (remaining 7", "0)]<gpuarray>(GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[-1.]}, y, GpuElemwise{Cast{float32}}[]<gpuarray>.0, GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0, GpuElemwise{sub,no_inplace}.0)", "8.9% 92.1% 0.103s 1.03e-05s C 10000 1 Elemwise{Composite{(((scalar_sigmoid(i0) * i1", "0)](b, TensorConstant{0.00999999977648}, Sum{acc_dtype=float64}.0) 0.1% 100.0% 0.001s 1.34e-07s 10000 3 Shape_i{0}(y)", "3.7% 71.0% 0.144s 1.44e-05s 10000 4 GpuElemwise{sub,no_inplace}(GpuArrayConstant{[ 1.]}, y) 3.6%", "C 10000 1 Elemwise{Composite{((-i0) - i1)}}[(0, 0)] 0.2% 99.9% 0.002s", "------ <% time> <sum %> <apply time> <time per call>", "the script: Used the gpu target values for D prediction", "0.002s 1.98e-07s 10000 8 Elemwise{Cast{float32}}(InplaceDimShuffle{x}.0) 0.2% 99.7% 0.002s 1.90e-07s 10000", "prediction on D Results were produced using a GeForce GTX", "99.2% 0.003s 2.65e-07s 10000 9 Elemwise{Composite{((-i0) - i1)}}[(0, 0)](CGemv{inplace}.0, InplaceDimShuffle{x}.0)", "- (i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray>(y, GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0,", "type: $ CUDA_LAUNCH_BLOCKING=1 THEANO_FLAGS=profile=True,device=cuda python using_gpu_solution_1.py # You'll see first", "90001 10 aesara.sandbox.gpuarray.elemwise.GpuElemwise 4.1% 93.4% 0.162s 8.10e-06s C 20001 3", "of the runtime) # 2.2 Profiling for GPU computations #", "GpuElemwise{neg,no_inplace}(GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0) 2.6% 90.1% 0.102s 1.02e-05s 10000 20", "more time than its CPU counterpart. This is because the", "Elemwise{neg,no_inplace} 0.3% 98.9% 0.004s 3.64e-07s C 10001 2 AllocEmpty{dtype='float32'} 0.3%", "20001 3 CGemv{inplace} 18.7% 83.2% 0.217s 2.17e-05s C 10000 1", "i1)}}[(0, 0)].0, TensorConstant{(1,) of -1.0}, Elemwise{sub,no_inplace}.0, Elemwise{neg,no_inplace}.0) 8.9% 92.1% 0.103s", "10001 calls to Function.__call__: 4.181247e+00s Time in Function.fn.__call__: 4.081113e+00s (97.605%)", "scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[(0, 4)] 8.9% 92.1%", "1.33e-05s C 10000 1 GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray> 3.3% 88.8%", "16 Elemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)](b, TensorConstant{0.00999999977648}, Sum{acc_dtype=float64}.0) 0.1%", "w.get_value(), b.get_value() # Construct Aesara expression graph p_1 = 1", "0.102s 1.02e-05s C 10000 1 GpuElemwise{Composite{(i0 - (i1 * i2))}}[(0,", "C, CUDA code generation/compiling): 8.239602e+00s Import time 4.228115e-03s Time in", "3.50GHz Function profiling ================== Message: Sum of all(2) printed profiles", "Compile expressions to functions train = aesara.function( inputs=[], outputs=[prediction, xent],", "/ i3))}}[(0, 0)]<gpuarray> 3.7% 75.1% 0.144s 1.44e-05s C 10000 1", "10000 1 Elemwise{sub,no_inplace} 0.3% 98.6% 0.004s 3.70e-07s C 10000 1", "(remaining 0 Classes account for 0.00%(0.00s) of the runtime) Ops", "tt.cast(xent.mean(), \"float32\") + 0.01 * (w ** 2).sum() # The", "1.09e-06s C 30001 4 aesara.sandbox.gpuarray.elemwise.GpuDimShuffle 0.7% 99.8% 0.026s 2.59e-06s C", "3 Shape_i{0} 0.0% 100.0% 0.000s 2.00e-05s C 1 1 GpuElemwise{Composite{GT(scalar_sigmoid((-((-i0)", "Followed by the output of profiling.. You'll see profiling results", "gpu\") else: print(\"ERROR, not able to tell if aesara used", "7.16e-06s 10000 14 HostFromGpu(gpuarray)(GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3", "- (i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray> 3.8% 71.4% 0.149s 1.49e-05s", "<% time> <sum %> <apply time> <time per call> <type>", "code generation/compiling): 2.949309e-02s Import time 3.543139e-03s Time in all call", "'GpuFromHost' and 'HostFromGpu' by themselves consume a large amount of", "summary for all functions. # We'll show here only the", "0.1% 99.9% 0.002s 1.54e-07s 10000 16 Elemwise{Composite{(i0 - (i1 *", "Total compile time: 9.256095e+00s Number of Apply nodes: 21 Aesara", "aesara.tensor.elemwise.Elemwise 1.0% 98.6% 0.011s 1.14e-06s C 10000 1 aesara.tensor.elemwise.Sum 0.7%", "Time in Function.fn.__call__: 1.215823e+00s (93.492%) Time in thunks: 1.157602e+00s (89.015%)", "100.0% 0.000s 4.77e-06s 1 4 Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}}(CGemv{inplace}.0, InplaceDimShuffle{x}.0,", "GpuFromHost<None> 0.7% 99.0% 0.026s 2.59e-06s C 10001 2 GpuAllocEmpty{dtype='float32', context_name=None}", "GpuArrayConstant{[-1.]}, GpuElemwise{sub,no_inplace}.0, GpuElemwise{neg,no_inplace}.0) 3.8% 67.3% 0.149s 1.49e-05s 10000 15 GpuElemwise{Composite{(((scalar_sigmoid(i0)", "19 HostFromGpu(gpuarray)(GpuElemwise{gt,no_inplace}.0) 1.8% 96.7% 0.072s 7.16e-06s 10000 14 HostFromGpu(gpuarray)(GpuElemwise{Composite{((i0 *", "10000 11 GpuElemwise{neg,no_inplace}(GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0) 2.6% 90.1% 0.102s 1.02e-05s", "2.88e-07s 10000 2 InplaceDimShuffle{1,0}(x) 0.2% 99.2% 0.003s 2.65e-07s 10000 9", "0.394s 3.94e-05s 10000 7 CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0}) 30.5%", "functions: Function profiling ================== Message: Sum of all(2) printed profiles", "expressions to functions train = aesara.function( inputs=[], outputs=[prediction, xent], updates=[(w,", "THEANO_FLAGS=profile=True,device=cpu python using_gpu_solution_1.py # You'll see first the output of", "9.63e-06s 10000 13 GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>(GpuElemwise{neg,no_inplace}.0) 2.3% 94.9% 0.090s 9.04e-06s 10000", "20001 3 InplaceDimShuffle{x} 0.4% 98.3% 0.004s 4.22e-07s C 10000 1", "counterpart. This is because the ops operate on small inputs;", "0.141s 1.41e-05s 10000 16 GpuElemwise{gt,no_inplace}(GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[ 0.5]}) 3.4% 78.0%", "C 10000 1 Elemwise{Cast{float32}} 0.1% 100.0% 0.002s 1.54e-07s C 10000", "* i3 * scalar_softplus(i4)))}}[]<gpuarray>.0) 1.6% 98.3% 0.061s 6.10e-06s 10000 6", "if you increase the input data size (e.g. set N", "\"float32\" rng = np.random N = 400 feats = 784", "import 15.415s Class --- <% time> <sum %> <apply time>", "2.2 Profiling for GPU computations # In your terminal, type:", "values for D prediction on D # Followed by the", "able to tell if aesara used the cpu or the", "x, w, TensorConstant{0.0}) 4.5% 59.5% 0.176s 1.76e-05s 10000 18 GpuGemv{inplace=True}(w,", "/ i3))}}[(0, 0)].0, TensorConstant{0.999800026417}) 18.7% 83.2% 0.217s 2.17e-05s 10000 12", "instances account for 0.07%(0.00s) of the runtime) # 3. Conclusions", "3.64e-07s 10000 5 AllocEmpty{dtype='float32'}(Shape_i{0}.0) 0.2% 99.0% 0.003s 2.88e-07s 10000 2", "0.141s 1.41e-05s C 10000 1 GpuElemwise{gt,no_inplace} 3.4% 82.1% 0.133s 1.33e-05s", "0 Ops account for 0.00%(0.00s) of the runtime) Apply ------", "* i5) / i3))}}[(0, 0)]<gpuarray>(GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[-1.]}, y,", "1.8% 96.7% 0.072s 7.16e-06s 10000 14 HostFromGpu(gpuarray)(GpuElemwise{Composite{((i0 * scalar_softplus(i1)) -", "else: print(\"ERROR, not able to tell if aesara used the", "input data size (e.g. set N = 4000), you will", "1 Elemwise{sub,no_inplace} 0.3% 98.6% 0.004s 3.70e-07s C 10000 1 Elemwise{neg,no_inplace}", "* gb)], name=\"train\", ) predict = aesara.function(inputs=[], outputs=prediction, name=\"predict\") if", "Apply nodes: 17 Aesara Optimizer time: 6.270301e-01s Aesara validate time:", "# print w.get_value(), b.get_value() # Construct Aesara expression graph p_1", "1 GpuElemwise{Cast{float32}}[]<gpuarray> 3.4% 85.5% 0.133s 1.33e-05s C 10000 1 GpuElemwise{Composite{((-i0)", "by a summary for all functions. # We'll show here", "<sum %> <apply time> <time per call> <#call> <id> <Apply", "time> <sum %> <apply time> <time per call> <#call> <id>", "0.004s 1.78e-07s C 20001 3 Shape_i{0} 0.2% 99.5% 0.003s 2.88e-07s", "= 400 feats = 784 D = ( rng.randn(N, feats).astype(aesara.config.floatX),", "* i1 * i2) / i3) - ((i4 * i1", "# Profiling summary for all functions: Function profiling ================== Message:", "i1 * i4) / i3))}}[(0, 0)].0) 0.4% 97.8% 0.004s 4.22e-07s", "aesara.sandbox.gpuarray.basic_ops.GpuFromHost 0.8% 99.1% 0.033s 1.09e-06s C 30001 4 aesara.sandbox.gpuarray.elemwise.GpuDimShuffle 0.7%", "90.1% 0.102s 1.02e-05s 10000 20 GpuElemwise{Composite{(i0 - (i1 * i2))}}[(0,", "InplaceGpuDimShuffle{x}(b) 0.3% 99.6% 0.011s 1.14e-06s 10000 2 InplaceGpuDimShuffle{1,0}(x) 0.2% 99.8%", "as few as possible data transfers between GPU and CPU,", "CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0}) 30.5% 64.5% 0.353s 3.53e-05s 10000", "* scalar_softplus(i4)))}}[]<gpuarray>.0) 1.6% 98.3% 0.061s 6.10e-06s 10000 6 GpuFromHost<None>(Shape_i{0}.0) 0.7%", "10000 4 Elemwise{sub,no_inplace}(TensorConstant{(1,) of 1.0}, y) 0.3% 98.1% 0.004s 3.76e-07s", "1.14e-06s C 10000 1 Sum{acc_dtype=float64} 0.5% 97.9% 0.006s 2.83e-07s C", "10000 1 InplaceGpuDimShuffle{1,0} 0.2% 100.0% 0.008s 3.95e-07s C 20001 3", "training_steps = 10000 # Declare Aesara symbolic variables x =", "* i4) / i3))}}[(0, 0)].0, TensorConstant{0.999800026417}) 18.7% 83.2% 0.217s 2.17e-05s", "print \"Initial model:\" # print w.get_value(), b.get_value() # Construct Aesara", "33.1% 97.7% 0.384s 4.79e-06s C 80001 9 aesara.tensor.elemwise.Elemwise 1.0% 98.6%", "b = aesara.shared(np.asarray(0.0, dtype=aesara.config.floatX), name=\"b\") x.tag.test_value = D[0] y.tag.test_value =", "0.5}) 1.0% 97.4% 0.011s 1.14e-06s 10000 14 Sum{acc_dtype=float64}(Elemwise{Composite{(((scalar_sigmoid(i0) * i1", "for GPU computations # In your terminal, type: $ CUDA_LAUNCH_BLOCKING=1", "0)](CGemv{inplace}.0, InplaceDimShuffle{x}.0) 0.2% 99.4% 0.002s 2.21e-07s 10000 1 Shape_i{0}(x) 0.2%", "* i2))}}[(0, 0)] 0.0% 100.0% 0.000s 4.77e-06s C 1 1", "10000 15 GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) -", "i7-5930K CPU @ 3.50GHz Function profiling ================== Message: Sum of", "1.54e-07s 10000 16 Elemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)](b, TensorConstant{0.00999999977648},", "21 Aesara Optimizer time: 9.996419e-01s Aesara validate time: 6.523132e-03s Aesara", "0.162s 8.10e-06s C 20001 3 HostFromGpu(gpuarray) 4.0% 67.6% 0.157s 1.57e-05s", "computations # In your terminal, type: $ THEANO_FLAGS=profile=True,device=cpu python using_gpu_solution_1.py", "= aesara.shared(D[0], name=\"x\") y = aesara.shared(D[1], name=\"y\") w = aesara.shared(rng.randn(feats).astype(aesara.config.floatX),", "output of profiling.. You'll see profiling results for each function", "0.5% 97.9% 0.006s 2.83e-07s C 20001 3 InplaceDimShuffle{x} 0.4% 98.3%", "aesara.shared(D[1], name=\"y\") w = aesara.shared(rng.randn(feats).astype(aesara.config.floatX), name=\"w\") b = aesara.shared(np.asarray(0.0, dtype=aesara.config.floatX),", "increase the input data size (e.g. set N = 4000),", "10000 8 InplaceGpuDimShuffle{x}(GpuFromHost<None>.0) 0.1% 99.9% 0.005s 5.27e-07s 10000 1 Shape_i{0}(x)", "0)]<gpuarray>(GpuGemv{inplace=True}.0, InplaceGpuDimShuffle{x}.0) 3.3% 84.7% 0.131s 1.31e-05s 10000 17 GpuCAReduceCuda{add}(GpuElemwise{Composite{(((scalar_sigmoid(i0) *", "0.009s 2.85e-07s C 30001 4 aesara.tensor.elemwise.DimShuffle 0.3% 99.7% 0.004s 3.64e-07s", "GeForce GTX TITAN X # Profiling summary for all functions:", "10000 5 AllocEmpty{dtype='float32'}(Shape_i{0}.0) 0.2% 99.0% 0.003s 2.88e-07s 10000 2 InplaceDimShuffle{1,0}(x)", "your terminal, type: $ THEANO_FLAGS=profile=True,device=cpu python using_gpu_solution_1.py # You'll see", "\"Final model:\" # print w.get_value(), b.get_value() print(\"target values for D\")", "aesara.compile.ops.Shape_i ... (remaining 0 Classes account for 0.00%(0.00s) of the", "elif any( [ n.op.__class__.__name__ in [\"GpuGemm\", \"GpuGemv\"] for n in", "InplaceDimShuffle{x}.0) 0.2% 99.4% 0.002s 2.21e-07s 10000 1 Shape_i{0}(x) 0.2% 99.6%", "GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0, GpuElemwise{sub,no_inplace}.0) 3.7% 71.0% 0.144s 1.44e-05s 10000 4 GpuElemwise{sub,no_inplace}(GpuArrayConstant{[", "Function profiling ================== Message: Sum of all(2) printed profiles at", "Classes account for 0.00%(0.00s) of the runtime) Ops --- <%", "You'll see profiling results for each function # in the", "xent = -y * tt.log(p_1) - (1 - y) *", "1.06e-06s C 20001 3 InplaceGpuDimShuffle{x} 0.3% 99.8% 0.011s 1.14e-06s C", "0.000s 4.77e-06s C 1 1 Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}} ...", "ops operate on small inputs; if you increase the input", "of Apply nodes: 21 Aesara Optimizer time: 9.996419e-01s Aesara validate", "a summary for all functions. # We'll show here only", "y) 3.6% 74.6% 0.141s 1.41e-05s 10000 16 GpuElemwise{gt,no_inplace}(GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[", "= 784 D = ( rng.randn(N, feats).astype(aesara.config.floatX), rng.randint(size=N, low=0, high=2).astype(aesara.config.floatX),", "10000 11 Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}}(Elemwise{neg,no_inplace}.0, TensorConstant{(1,) of 0.5}) 1.0% 97.4% 0.011s", "Elemwise{sub,no_inplace}.0, Elemwise{neg,no_inplace}.0) 8.9% 92.1% 0.103s 1.03e-05s 10000 13 Elemwise{Composite{(((scalar_sigmoid(i0) *", "/ i3))}}[(0, 0)] 4.3% 96.4% 0.050s 4.98e-06s C 10000 1", "* i1 * i5) / i3))}}[(0, 0)]<gpuarray>(GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0,", "i2) / i3) - ((i4 * i1 * i5) /", "Apply ------ <% time> <sum %> <apply time> <time per", "82.1% 0.133s 1.33e-05s C 10000 1 GpuElemwise{Cast{float32}}[]<gpuarray> 3.4% 85.5% 0.133s", "98.6% 0.004s 3.70e-07s C 10000 1 Elemwise{neg,no_inplace} 0.3% 98.9% 0.004s", "10000 3 Shape_i{0}(y) 0.0% 100.0% 0.000s 3.89e-05s 1 3 CGemv{inplace}(AllocEmpty{dtype='float32'}.0,", "1.41e-05s 10000 16 GpuElemwise{gt,no_inplace}(GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[ 0.5]}) 3.4% 78.0% 0.133s", "6.270301e-01s Aesara validate time: 5.993605e-03s Aesara Linker time (includes C,", "10000 1 GpuElemwise{gt,no_inplace} 3.4% 82.1% 0.133s 1.33e-05s C 10000 1", "Sum{acc_dtype=float64}(Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) - ((scalar_sigmoid((-i0)) *", "100.0% 0.000s 3.89e-05s 1 3 CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0})", "2.3% 94.9% 0.090s 9.04e-06s 10000 19 HostFromGpu(gpuarray)(GpuElemwise{gt,no_inplace}.0) 1.8% 96.7% 0.072s", "0.096s 9.63e-06s C 10000 1 GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray> 1.6% 98.3% 0.061s", "98.7% 0.004s 3.64e-07s 10000 5 AllocEmpty{dtype='float32'}(Shape_i{0}.0) 0.2% 99.0% 0.003s 2.88e-07s", "gpu\") print(train.maker.fgraph.toposort()) for i in range(training_steps): pred, err = train()", "8.9% 92.1% 0.103s 1.03e-05s 10000 13 Elemwise{Composite{(((scalar_sigmoid(i0) * i1 *", "+ tt.exp(-tt.dot(x, w) - b)) # Probability of having a", "scalar_softplus(i4)))}}[(0, 4)](y, Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0, TensorConstant{(1,) of -1.0}, Elemwise{sub,no_inplace}.0,", "GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray> 3.3% 88.8% 0.131s 1.31e-05s C 10000", "call> <type> <#call> <#apply> <Class name> 64.5% 64.5% 0.747s 3.73e-05s", "#!/usr/bin/env python # Aesara tutorial # Solution to Exercise in", "C 10000 1 GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3", "0.003s 2.88e-07s 10000 2 InplaceDimShuffle{1,0}(x) 0.2% 99.2% 0.003s 2.65e-07s 10000", "0)]<gpuarray>.0, GpuElemwise{sub,no_inplace}.0) 3.7% 71.0% 0.144s 1.44e-05s 10000 4 GpuElemwise{sub,no_inplace}(GpuArrayConstant{[ 1.]},", "aesara.sandbox.gpuarray.elemwise.GpuElemwise 4.1% 93.4% 0.162s 8.10e-06s C 20001 3 aesara.sandbox.gpuarray.basic_ops.HostFromGpu 3.3%", "y, GpuElemwise{Cast{float32}}[]<gpuarray>.0, GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0, GpuElemwise{sub,no_inplace}.0) 3.7% 71.0% 0.144s 1.44e-05s 10000", "<#apply> <Op name> 59.5% 59.5% 2.329s 1.16e-04s C 20001 3", "# 2.1 Profiling for CPU computations # In your terminal,", "10000 1 InplaceDimShuffle{1,0} 0.2% 99.7% 0.003s 2.65e-07s C 10000 1", "as tt aesara.config.floatX = \"float32\" rng = np.random N =", "GpuElemwise{neg,no_inplace}.0) 3.8% 67.3% 0.149s 1.49e-05s 10000 15 GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1", "and GPU. Usually GPU ops 'GpuFromHost' and 'HostFromGpu' by themselves", "-1.0}, y, Elemwise{Cast{float32}}.0, Elemwise{sub,no_inplace}.0) 4.3% 96.4% 0.050s 4.98e-06s 10000 11", "59.5% 59.5% 2.329s 1.16e-04s C 20001 3 aesara.sandbox.gpuarray.blas.GpuGemv 29.8% 89.3%", "aesara.tensor.basic.AllocEmpty 0.3% 100.0% 0.004s 1.78e-07s C 20001 3 aesara.compile.ops.Shape_i ...", "CPU counterpart. This is because the ops operate on small", ") training_steps = 10000 # Declare Aesara symbolic variables x", "since aesara import 15.415s Class --- <% time> <sum %>", "5 AllocEmpty{dtype='float32'}(Shape_i{0}.0) 0.2% 99.0% 0.003s 2.88e-07s 10000 2 InplaceDimShuffle{1,0}(x) 0.2%", "(i1 * i2))}}[(0, 0)] 0.0% 100.0% 0.000s 4.77e-06s C 1", "3.95e-07s C 20001 3 Shape_i{0} 0.0% 100.0% 0.000s 2.00e-05s C", "Linker time (includes C, CUDA code generation/compiling): 2.949309e-02s Import time", "1.6% 98.3% 0.061s 6.10e-06s C 10000 1 aesara.sandbox.gpuarray.basic_ops.GpuFromHost 0.8% 99.1%", "0.384s 4.79e-06s C 80001 9 aesara.tensor.elemwise.Elemwise 1.0% 98.6% 0.011s 1.14e-06s", "10000 1 GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) -", "= -y * tt.log(p_1) - (1 - y) * tt.log(1", "1.02e-05s C 10000 1 GpuElemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)]<gpuarray>", "C 10000 1 aesara.tensor.elemwise.Sum 0.7% 99.4% 0.009s 2.85e-07s C 30001", "%> <apply time> <time per call> <type> <#call> <#apply> <Op", "10001 2 GpuAllocEmpty{dtype='float32', context_name=None} 0.5% 99.5% 0.021s 1.06e-06s C 20001", "# In your terminal, type: $ CUDA_LAUNCH_BLOCKING=1 THEANO_FLAGS=profile=True,device=cuda python using_gpu_solution_1.py", "'HostFromGpu' by themselves consume a large amount of extra time,", "of 1.0}, y) 0.3% 98.1% 0.004s 3.76e-07s 10000 0 InplaceDimShuffle{x}(b)", "99.7% 0.002s 1.90e-07s 10000 6 InplaceDimShuffle{x}(Shape_i{0}.0) 0.1% 99.9% 0.002s 1.54e-07s", "w, TensorConstant{0.0}) 4.5% 59.5% 0.176s 1.76e-05s 10000 18 GpuGemv{inplace=True}(w, TensorConstant{-0.00999999977648},", "GpuGemv{inplace=True}(GpuAllocEmpty{dtype='float32', context_name=None}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0}) 4.5% 59.5% 0.176s 1.76e-05s", "* i1 * i5) / i3))}}[(0, 0)]<gpuarray>.0, TensorConstant{0.999800026417}) 4.0% 63.5%", "per call> <type> <#call> <#apply> <Class name> 59.5% 59.5% 2.329s", "or the gpu\") print(train.maker.fgraph.toposort()) for i in range(training_steps): pred, err", "1 GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray> 3.3% 88.8% 0.131s 1.31e-05s C", "3 InplaceDimShuffle{x} 0.4% 98.3% 0.004s 4.22e-07s C 10000 1 Elemwise{sub,no_inplace}", "* tt.log(p_1) - (1 - y) * tt.log(1 - p_1)", "<Class name> 64.5% 64.5% 0.747s 3.73e-05s C 20001 3 aesara.tensor.blas_c.CGemv", "100.0% 0.004s 1.78e-07s C 20001 3 aesara.compile.ops.Shape_i ... (remaining 0", "of the script: Used the cpu target values for D", "- ((i4 * i1 * i5) / i3))}}[(0, 0)]<gpuarray>.0) 2.9%", "Time in 10001 calls to Function.__call__: 1.300452e+00s Time in Function.fn.__call__:", "Core(TM) i7-5930K CPU @ 3.50GHz Function profiling ================== Message: Sum", "of -1.0}, y, Elemwise{Cast{float32}}.0, Elemwise{sub,no_inplace}.0) 4.3% 96.4% 0.050s 4.98e-06s 10000", "GpuElemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)]<gpuarray> 2.5% 96.7% 0.096s 9.63e-06s", "i3))}}[(0, 0)]<gpuarray>.0, TensorConstant{0.999800026417}) 4.0% 63.5% 0.157s 1.57e-05s 10000 12 GpuElemwise{Composite{((i0", "20001 3 Shape_i{0} 0.2% 99.5% 0.003s 2.88e-07s C 10000 1", "((scalar_sigmoid((-i0)) * i1 * i4) / i3))}}[(0, 0)].0) 0.4% 97.8%", "TensorConstant{1.0}, x, w, TensorConstant{0.0}) 4.5% 59.5% 0.176s 1.76e-05s 10000 18", "CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0}) 0.0% 100.0% 0.000s 4.77e-06s 1", "$ CUDA_LAUNCH_BLOCKING=1 THEANO_FLAGS=profile=True,device=cuda python using_gpu_solution_1.py # You'll see first the", "1 GpuElemwise{sub,no_inplace} 3.6% 78.7% 0.141s 1.41e-05s C 10000 1 GpuElemwise{gt,no_inplace}", "59.5% 0.176s 1.76e-05s 10000 18 GpuGemv{inplace=True}(w, TensorConstant{-0.00999999977648}, InplaceGpuDimShuffle{1,0}.0, GpuElemwise{Composite{(((scalar_sigmoid(i0) *", "3 aesara.tensor.blas_c.CGemv 33.1% 97.7% 0.384s 4.79e-06s C 80001 9 aesara.tensor.elemwise.Elemwise", "7 CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0}) 30.5% 64.5% 0.353s 3.53e-05s", "Usually GPU ops 'GpuFromHost' and 'HostFromGpu' by themselves consume a", "1.44e-05s 10000 4 GpuElemwise{sub,no_inplace}(GpuArrayConstant{[ 1.]}, y) 3.6% 74.6% 0.141s 1.41e-05s", "- (i1 * i2))}}[(0, 0)]<gpuarray> 2.5% 96.7% 0.096s 9.63e-06s C", "* i1 * i4) / i3))}}[(0, 0)] 4.3% 96.4% 0.050s", "96.4% 0.050s 4.98e-06s C 10000 1 Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}} 1.0% 97.4%", "0.3% 99.6% 0.011s 1.14e-06s 10000 2 InplaceGpuDimShuffle{1,0}(x) 0.2% 99.8% 0.008s", "4.0% 63.5% 0.157s 1.57e-05s 10000 12 GpuElemwise{Composite{((i0 * scalar_softplus(i1)) -", "i3))}}[(0, 0)]<gpuarray>.0) 2.9% 87.5% 0.112s 1.12e-05s 10000 11 GpuElemwise{neg,no_inplace}(GpuElemwise{Composite{((-i0) -", "i3))}}[(0, 0)] 4.3% 96.4% 0.050s 4.98e-06s C 10000 1 Elemwise{Composite{GT(scalar_sigmoid(i0),", "Time in all call to aesara.grad() 3.286195e-02s Time since aesara", "- p_1) # Cross-entropy cost = tt.cast(xent.mean(), \"float32\") + 0.01", "4.081113e+00s (97.605%) Time in thunks: 3.915566e+00s (93.646%) Total compile time:", "- i1)}}[(0, 0)](CGemv{inplace}.0, InplaceDimShuffle{x}.0) 0.2% 99.4% 0.002s 2.21e-07s 10000 1", "of 0.5}) 0.0% 100.0% 0.000s 1.19e-06s 1 0 InplaceDimShuffle{x}(b) ...", "4 GpuElemwise{sub,no_inplace}(GpuArrayConstant{[ 1.]}, y) 3.6% 74.6% 0.141s 1.41e-05s 10000 16", "15 GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) - ((i4", "tt.grad(cost, [w, b]) # Compile expressions to functions train =", "* i4) / i3))}}[(0, 0)] 4.3% 96.4% 0.050s 4.98e-06s C", "to tell if aesara used the cpu or the gpu\")", "name> 59.5% 59.5% 2.329s 1.16e-04s C 20001 3 aesara.sandbox.gpuarray.blas.GpuGemv 29.8%", "* i2))}}[(0, 0)]<gpuarray>(b, GpuArrayConstant{0.00999999977648}, GpuCAReduceCuda{add}.0) 2.5% 92.6% 0.096s 9.63e-06s 10000", "cpu target values for D prediction on D # Followed", "10000 5 GpuAllocEmpty{dtype='float32', context_name=None}(Shape_i{0}.0) 0.3% 99.3% 0.013s 1.33e-06s 10000 0", "Elemwise{Cast{float32}}.0, Elemwise{sub,no_inplace}.0) 4.3% 96.4% 0.050s 4.98e-06s 10000 11 Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}}(Elemwise{neg,no_inplace}.0,", "* scalar_softplus(i4)))}}[(0, 4)](y, Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0, TensorConstant{(1,) of -1.0},", "name> 55.0% 55.0% 2.154s 2.15e-04s 10000 7 GpuGemv{inplace=True}(GpuAllocEmpty{dtype='float32', context_name=None}.0, TensorConstant{1.0},", "99.4% 0.009s 2.85e-07s C 30001 4 aesara.tensor.elemwise.DimShuffle 0.3% 99.7% 0.004s", "its CPU counterpart. This is because the ops operate on", "Class --- <% time> <sum %> <apply time> <time per", "CPU, you can minimize their overhead. Notice that each of", "instances account for 0.00%(0.00s) of the runtime) # 2.2 Profiling", "1 GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray> 1.6% 98.3% 0.061s 6.10e-06s C 10000 1", "aesara.tensor.blas_c.CGemv 33.1% 97.7% 0.384s 4.79e-06s C 80001 9 aesara.tensor.elemwise.Elemwise 1.0%", "0.026s 2.59e-06s 10000 5 GpuAllocEmpty{dtype='float32', context_name=None}(Shape_i{0}.0) 0.3% 99.3% 0.013s 1.33e-06s", "each function # in the script, followed by a summary", "64.5% 64.5% 0.747s 3.73e-05s C 20001 3 CGemv{inplace} 18.7% 83.2%", "GpuElemwise{Cast{float32}}[]<gpuarray>(InplaceGpuDimShuffle{x}.0) 3.4% 81.4% 0.133s 1.33e-05s 10000 9 GpuElemwise{Composite{((-i0) - i1)}}[(0,", "printed profiles at exit excluding Scan op profile. Time in", "time> <time per call> <type> <#call> <#apply> <Op name> 64.5%", "2.59e-06s C 10001 2 GpuAllocEmpty{dtype='float32', context_name=None} 0.5% 99.5% 0.021s 1.06e-06s", "(1 + tt.exp(-tt.dot(x, w) - b)) # Probability of having", "# Aesara tutorial # Solution to Exercise in section 'Using", "= tt.grad(cost, [w, b]) # Compile expressions to functions train", "Aesara Linker time (includes C, CUDA code generation/compiling): 2.949309e-02s Import", "80001 9 aesara.tensor.elemwise.Elemwise 1.0% 98.6% 0.011s 1.14e-06s C 10000 1", "2.59e-06s 10000 5 GpuAllocEmpty{dtype='float32', context_name=None}(Shape_i{0}.0) 0.3% 99.3% 0.013s 1.33e-06s 10000", "i3) - ((i4 * i1 * i5) / i3))}}[(0, 0)]<gpuarray>(GpuElemwise{Composite{((-i0)", "0)]<gpuarray> 1.6% 98.3% 0.061s 6.10e-06s C 10000 1 GpuFromHost<None> 0.7%", "- i1)}}[(0, 0)].0, TensorConstant{(1,) of -1.0}, y, Elemwise{Cast{float32}}.0, Elemwise{sub,no_inplace}.0) 4.3%", "(i1 * i2))}}[(0, 0)]<gpuarray> 2.5% 96.7% 0.096s 9.63e-06s C 10000", "i1 * i5) / i3))}}[(0, 0)]<gpuarray>.0) 2.9% 87.5% 0.112s 1.12e-05s", "C 10000 1 GpuElemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)]<gpuarray> 2.5%", "0.747s 3.73e-05s C 20001 3 CGemv{inplace} 18.7% 83.2% 0.217s 2.17e-05s", "data size (e.g. set N = 4000), you will see", "17 Aesara Optimizer time: 6.270301e-01s Aesara validate time: 5.993605e-03s Aesara", "Optimizer time: 6.270301e-01s Aesara validate time: 5.993605e-03s Aesara Linker time", "0.002s 2.21e-07s 10000 1 Shape_i{0}(x) 0.2% 99.6% 0.002s 1.98e-07s 10000", "10000 1 Elemwise{Composite{((-i0) - i1)}}[(0, 0)] 0.2% 99.9% 0.002s 1.98e-07s", "10000 10 GpuElemwise{Cast{float32}}[]<gpuarray>(InplaceGpuDimShuffle{x}.0) 3.4% 81.4% 0.133s 1.33e-05s 10000 9 GpuElemwise{Composite{((-i0)", "profile. Time in 10001 calls to Function.__call__: 1.300452e+00s Time in", "C 10000 1 InplaceGpuDimShuffle{1,0} 0.2% 100.0% 0.008s 3.95e-07s C 20001", "18.7% 83.2% 0.217s 2.17e-05s C 10000 1 Elemwise{Composite{((i0 * scalar_softplus(i1))", "- (i1 * i2))}}[(0, 0)]<gpuarray>(b, GpuArrayConstant{0.00999999977648}, GpuCAReduceCuda{add}.0) 2.5% 92.6% 0.096s", "4.22e-07s 10000 4 Elemwise{sub,no_inplace}(TensorConstant{(1,) of 1.0}, y) 0.3% 98.1% 0.004s", "0.149s 1.49e-05s 10000 15 GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) /", "- i1)}}[(0, 0)]<gpuarray>(GpuGemv{inplace=True}.0, InplaceGpuDimShuffle{x}.0) 3.3% 84.7% 0.131s 1.31e-05s 10000 17", "0.050s 4.98e-06s 10000 11 Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}}(Elemwise{neg,no_inplace}.0, TensorConstant{(1,) of 0.5}) 1.0%", "few as possible data transfers between GPU and CPU, you", "* i5) / i3))}}[(0, 0)]<gpuarray> 3.7% 75.1% 0.144s 1.44e-05s C", "3.4% 82.1% 0.133s 1.33e-05s C 10000 1 GpuElemwise{Cast{float32}}[]<gpuarray> 3.4% 85.5%", "account for 0.00%(0.00s) of the runtime) Ops --- <% time>", "expression graph p_1 = 1 / (1 + tt.exp(-tt.dot(x, w)", "96.7% 0.096s 9.63e-06s C 10000 1 GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray> 1.6% 98.3%", "18 GpuGemv{inplace=True}(w, TensorConstant{-0.00999999977648}, InplaceGpuDimShuffle{1,0}.0, GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) /", "print(\"prediction on D\") print(predict()) \"\"\" # 2. Profiling # 2.1", "97.4% 0.011s 1.14e-06s C 10000 1 Sum{acc_dtype=float64} 0.5% 97.9% 0.006s", "Notice that each of the GPU ops consumes more time", "time than its CPU counterpart. This is because the ops", "in all call to aesara.grad() 1.848292e-02s Time since aesara import", "/ i3))}}[(0, 0)]<gpuarray>.0) 2.9% 87.5% 0.112s 1.12e-05s 10000 11 GpuElemwise{neg,no_inplace}(GpuElemwise{Composite{((-i0)", "GpuElemwise{sub,no_inplace} 3.6% 78.7% 0.141s 1.41e-05s C 10000 1 GpuElemwise{gt,no_inplace} 3.4%", "a large amount of extra time, but by making as", "0.026s 2.59e-06s C 10001 2 aesara.sandbox.gpuarray.basic_ops.GpuAllocEmpty 0.2% 100.0% 0.008s 3.95e-07s", "30001 4 aesara.sandbox.gpuarray.elemwise.GpuDimShuffle 0.7% 99.8% 0.026s 2.59e-06s C 10001 2", "followed by a summary for all functions. # We'll show", "# in the script, followed by a summary for all", "0.006s 2.83e-07s C 20001 3 InplaceDimShuffle{x} 0.4% 98.3% 0.004s 4.22e-07s", "train.maker.fgraph.toposort() ] ): print(\"Used the gpu\") else: print(\"ERROR, not able", "in section 'Using the GPU' # 1. Raw results import", "3.286195e-02s Time since aesara import 15.415s Class --- <% time>", "92.1% 0.103s 1.03e-05s 10000 13 Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2)", "outputs=[prediction, xent], updates=[(w, w - 0.01 * gw), (b, b", "- ((scalar_sigmoid((-i0)) * i1 * i4) / i3))}}[(0, 0)].0) 0.4%", "C 10001 2 aesara.tensor.basic.AllocEmpty 0.3% 100.0% 0.004s 1.78e-07s C 20001", "profiles at exit excluding Scan op profile. Time in 10001", "3.6% 74.6% 0.141s 1.41e-05s 10000 16 GpuElemwise{gt,no_inplace}(GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[ 0.5]})", "C 20001 3 InplaceGpuDimShuffle{x} 0.3% 99.8% 0.011s 1.14e-06s C 10000", "2 GpuAllocEmpty{dtype='float32', context_name=None} 0.5% 99.5% 0.021s 1.06e-06s C 20001 3", "1 Shape_i{0}(x) ... (remaining 7 Apply instances account for 0.07%(0.00s)", "10000 14 Sum{acc_dtype=float64}(Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) -", "np.random N = 400 feats = 784 D = (", "0.011s 1.14e-06s C 10000 1 Sum{acc_dtype=float64} 0.5% 97.9% 0.006s 2.83e-07s", "all functions: Function profiling ================== Message: Sum of all(2) printed", "98.4% 0.004s 3.70e-07s 10000 10 Elemwise{neg,no_inplace}(Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0) 0.3%", "3.3% 96.7% 0.131s 1.31e-05s C 10000 1 aesara.sandbox.gpuarray.elemwise.GpuCAReduceCuda 1.6% 98.3%", "3.543139e-03s Time in all call to aesara.grad() 1.848292e-02s Time since", "import numpy as np import aesara import aesara.tensor as tt", "X # Profiling summary for all functions: Function profiling ==================", "to Exercise in section 'Using the GPU' # 1. Raw", "0)](Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0, TensorConstant{(1,) of -1.0}, y, Elemwise{Cast{float32}}.0, Elemwise{sub,no_inplace}.0)", "feats = 784 D = ( rng.randn(N, feats).astype(aesara.config.floatX), rng.randint(size=N, low=0,", "<time per call> <type> <#call> <#apply> <Op name> 59.5% 59.5%", "3 CGemv{inplace} 18.7% 83.2% 0.217s 2.17e-05s C 10000 1 Elemwise{Composite{((i0", "0.2% 99.7% 0.002s 1.90e-07s 10000 6 InplaceDimShuffle{x}(Shape_i{0}.0) 0.1% 99.9% 0.002s", "10000 1 aesara.tensor.elemwise.Sum 0.7% 99.4% 0.009s 2.85e-07s C 30001 4", "call> <type> <#call> <#apply> <Class name> 59.5% 59.5% 2.329s 1.16e-04s", "D[1] # print \"Initial model:\" # print w.get_value(), b.get_value() #", "Function.__call__: 1.300452e+00s Time in Function.fn.__call__: 1.215823e+00s (93.492%) Time in thunks:", "0.157s 1.57e-05s 10000 12 GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 *", "3.8% 67.3% 0.149s 1.49e-05s 10000 15 GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 *", "is done: 0 or 1 xent = -y * tt.log(p_1)", "of the GPU ops consumes more time than its CPU", "0)]<gpuarray> 2.5% 96.7% 0.096s 9.63e-06s C 10000 1 GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>", "function # in the script, followed by a summary for", "i2) / i3) - ((scalar_sigmoid((-i0)) * i1 * i4) /", "the output of the script: Used the gpu target values", "scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray>(y, GpuElemwise{Composite{((-i0) - i1)}}[(0,", "y.tag.test_value = D[1] # print \"Initial model:\" # print w.get_value(),", "2.85e-07s C 30001 4 aesara.tensor.elemwise.DimShuffle 0.3% 99.7% 0.004s 3.64e-07s C", "1.30e-05s C 90001 10 aesara.sandbox.gpuarray.elemwise.GpuElemwise 4.1% 93.4% 0.162s 8.10e-06s C", "or 1 xent = -y * tt.log(p_1) - (1 -", "account for 0.00%(0.00s) of the runtime) Apply ------ <% time>", "i1)}}[(0, 0)]<gpuarray> 3.3% 88.8% 0.131s 1.31e-05s C 10000 1 GpuCAReduceCuda{add}", "<apply time> <time per call> <type> <#call> <#apply> <Class name>", "97.8% 0.004s 4.22e-07s 10000 4 Elemwise{sub,no_inplace}(TensorConstant{(1,) of 1.0}, y) 0.3%", "67.3% 0.149s 1.49e-05s 10000 15 GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2)", "small inputs; if you increase the input data size (e.g.", "- y) * tt.log(1 - p_1) # Cross-entropy cost =", "in [\"GpuGemm\", \"GpuGemv\"] for n in train.maker.fgraph.toposort() ] ): print(\"Used", "rng = np.random N = 400 feats = 784 D", "ops 'GpuFromHost' and 'HostFromGpu' by themselves consume a large amount", "<#call> <#apply> <Class name> 59.5% 59.5% 2.329s 1.16e-04s C 20001", "8 InplaceGpuDimShuffle{x}(GpuFromHost<None>.0) 0.1% 99.9% 0.005s 5.27e-07s 10000 1 Shape_i{0}(x) ...", "account for 0.00%(0.00s) of the runtime) # 2.2 Profiling for", "0)].0) 0.4% 97.8% 0.004s 4.22e-07s 10000 4 Elemwise{sub,no_inplace}(TensorConstant{(1,) of 1.0},", "1 GpuElemwise{neg,no_inplace} 2.6% 94.3% 0.102s 1.02e-05s C 10000 1 GpuElemwise{Composite{(i0", "<type> <#call> <#apply> <Op name> 64.5% 64.5% 0.747s 3.73e-05s C", "0.5% 99.5% 0.021s 1.06e-06s C 20001 3 InplaceGpuDimShuffle{x} 0.3% 99.8%", "C 10001 2 GpuAllocEmpty{dtype='float32', context_name=None} 0.5% 99.5% 0.021s 1.06e-06s C", "themselves consume a large amount of extra time, but by", "0.2% 99.6% 0.002s 1.98e-07s 10000 8 Elemwise{Cast{float32}}(InplaceDimShuffle{x}.0) 0.2% 99.7% 0.002s", "xent], updates=[(w, w - 0.01 * gw), (b, b -", "Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}}(Elemwise{neg,no_inplace}.0, TensorConstant{(1,) of 0.5}) 1.0% 97.4% 0.011s 1.14e-06s 10000", "Import time 4.228115e-03s Time in all call to aesara.grad() 3.286195e-02s", "'Ops' summaries for CPU and GPU. Usually GPU ops 'GpuFromHost'", "InplaceGpuDimShuffle{x}(GpuFromHost<None>.0) 0.1% 99.9% 0.005s 5.27e-07s 10000 1 Shape_i{0}(x) ... (remaining", "the gpu target values for D prediction on D Results", "34.0% 0.394s 3.94e-05s 10000 7 CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0})", "71.0% 0.144s 1.44e-05s 10000 4 GpuElemwise{sub,no_inplace}(GpuArrayConstant{[ 1.]}, y) 3.6% 74.6%", "64.5% 0.353s 3.53e-05s 10000 15 CGemv{inplace}(w, TensorConstant{-0.00999999977648}, x.T, Elemwise{Composite{(((scalar_sigmoid(i0) *", "Elemwise{neg,no_inplace}.0) 8.9% 92.1% 0.103s 1.03e-05s 10000 13 Elemwise{Composite{(((scalar_sigmoid(i0) * i1", "] ): print(\"Used the gpu\") else: print(\"ERROR, not able to", "<#apply> <Op name> 64.5% 64.5% 0.747s 3.73e-05s C 20001 3", "C 10000 1 aesara.sandbox.gpuarray.basic_ops.GpuFromHost 0.8% 99.1% 0.033s 1.09e-06s C 30001", "0.090s 9.04e-06s 10000 19 HostFromGpu(gpuarray)(GpuElemwise{gt,no_inplace}.0) 1.8% 96.7% 0.072s 7.16e-06s 10000", "4.5% 59.5% 0.176s 1.76e-05s 10000 18 GpuGemv{inplace=True}(w, TensorConstant{-0.00999999977648}, InplaceGpuDimShuffle{1,0}.0, GpuElemwise{Composite{(((scalar_sigmoid(i0)", "0.004s 4.22e-07s 10000 4 Elemwise{sub,no_inplace}(TensorConstant{(1,) of 1.0}, y) 0.3% 98.1%", "C 20001 3 Shape_i{0} 0.2% 99.5% 0.003s 2.88e-07s C 10000", "all(2) printed profiles at exit excluding Scan op profile. Time", "Examine and compare 'Ops' summaries for CPU and GPU. Usually", "The cost to optimize gw, gb = tt.grad(cost, [w, b])", "<apply time> <time per call> <type> <#call> <#apply> <Op name>", "C 10000 1 GpuElemwise{Cast{float32}}[]<gpuarray> 3.4% 85.5% 0.133s 1.33e-05s C 10000", "0.008s 3.95e-07s C 20001 3 aesara.compile.ops.Shape_i ... (remaining 0 Classes", "time: 9.256095e+00s Number of Apply nodes: 21 Aesara Optimizer time:", "%> <apply time> <time per call> <type> <#call> <#apply> <Class", "8 Elemwise{Cast{float32}}(InplaceDimShuffle{x}.0) 0.2% 99.7% 0.002s 1.90e-07s 10000 6 InplaceDimShuffle{x}(Shape_i{0}.0) 0.1%", "1.41e-05s C 10000 1 GpuElemwise{gt,no_inplace} 3.4% 82.1% 0.133s 1.33e-05s C", "98.6% 0.011s 1.14e-06s C 10000 1 aesara.tensor.elemwise.Sum 0.7% 99.4% 0.009s", "<type> <#call> <#apply> <Class name> 59.5% 59.5% 2.329s 1.16e-04s C", "# 3. Conclusions Examine and compare 'Ops' summaries for CPU", "code generation/compiling): 8.239602e+00s Import time 4.228115e-03s Time in all call", "tt.exp(-tt.dot(x, w) - b)) # Probability of having a one", "for each function # in the script, followed by a", "3.70e-07s C 10000 1 Elemwise{neg,no_inplace} 0.3% 98.9% 0.004s 3.64e-07s C", "(i1 * i2))}}[(0, 0)](b, TensorConstant{0.00999999977648}, Sum{acc_dtype=float64}.0) 0.1% 100.0% 0.001s 1.34e-07s", "feats).astype(aesara.config.floatX), rng.randint(size=N, low=0, high=2).astype(aesara.config.floatX), ) training_steps = 10000 # Declare", "all call to aesara.grad() 1.848292e-02s Time since aesara import 2.864s", "Scan op profile. Time in 10001 calls to Function.__call__: 4.181247e+00s", "InplaceDimShuffle{1,0} 0.2% 99.7% 0.003s 2.65e-07s C 10000 1 Elemwise{Composite{((-i0) -", "call> <#call> <id> <Apply name> 34.0% 34.0% 0.394s 3.94e-05s 10000", "= 1 / (1 + tt.exp(-tt.dot(x, w) - b)) #", "0.01 * gw), (b, b - 0.01 * gb)], name=\"train\",", "<apply time> <time per call> <#call> <id> <Apply name> 34.0%", "TensorConstant{0.0}) 4.5% 59.5% 0.176s 1.76e-05s 10000 18 GpuGemv{inplace=True}(w, TensorConstant{-0.00999999977648}, InplaceGpuDimShuffle{1,0}.0,", "of extra time, but by making as few as possible", "Elemwise{sub,no_inplace}(TensorConstant{(1,) of 1.0}, y) 0.3% 98.1% 0.004s 3.76e-07s 10000 0", "using_gpu_solution_1.py # You'll see first the output of the script:", "AllocEmpty{dtype='float32'} 0.3% 99.2% 0.004s 1.78e-07s C 20001 3 Shape_i{0} 0.2%", "overhead. Notice that each of the GPU ops consumes more", "because the ops operate on small inputs; if you increase", "0.4% 98.3% 0.004s 4.22e-07s C 10000 1 Elemwise{sub,no_inplace} 0.3% 98.6%", "TensorConstant{0.0}) 30.5% 64.5% 0.353s 3.53e-05s 10000 15 CGemv{inplace}(w, TensorConstant{-0.00999999977648}, x.T,", "<Apply name> 55.0% 55.0% 2.154s 2.15e-04s 10000 7 GpuGemv{inplace=True}(GpuAllocEmpty{dtype='float32', context_name=None}.0,", "\"\"\" # 2. Profiling # 2.1 Profiling for CPU computations", "0.7% 99.0% 0.026s 2.59e-06s 10000 5 GpuAllocEmpty{dtype='float32', context_name=None}(Shape_i{0}.0) 0.3% 99.3%", "3 HostFromGpu(gpuarray) 4.0% 67.6% 0.157s 1.57e-05s C 10000 1 GpuElemwise{Composite{((i0", "# Declare Aesara symbolic variables x = aesara.shared(D[0], name=\"x\") y", "y, Elemwise{Cast{float32}}.0, Elemwise{sub,no_inplace}.0) 4.3% 96.4% 0.050s 4.98e-06s 10000 11 Elemwise{Composite{GT(scalar_sigmoid(i0),", "GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>(GpuElemwise{neg,no_inplace}.0) 2.3% 94.9% 0.090s 9.04e-06s 10000 19 HostFromGpu(gpuarray)(GpuElemwise{gt,no_inplace}.0) 1.8%", "data transfers between GPU and CPU, you can minimize their", "i1 * i4) / i3))}}[(0, 0)].0, TensorConstant{0.999800026417}) 18.7% 83.2% 0.217s", "train.maker.fgraph.toposort() ] ): print(\"Used the cpu\") elif any( [ n.op.__class__.__name__", "64.5% 0.747s 3.73e-05s C 20001 3 aesara.tensor.blas_c.CGemv 33.1% 97.7% 0.384s", "4.77e-06s C 1 1 Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}} ... (remaining", "D\") print(D[1]) print(\"prediction on D\") print(predict()) \"\"\" # 2. Profiling", "63.5% 0.157s 1.57e-05s 10000 12 GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2", "operate on small inputs; if you increase the input data", "0.008s 3.95e-07s C 20001 3 Shape_i{0} 0.0% 100.0% 0.000s 2.00e-05s", "20001 3 aesara.tensor.blas_c.CGemv 33.1% 97.7% 0.384s 4.79e-06s C 80001 9", "* scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray>(y, GpuElemwise{Composite{((-i0) -", "were produced using a GeForce GTX TITAN X # Profiling", "1.848292e-02s Time since aesara import 2.864s Class --- <% time>", "0.061s 6.10e-06s C 10000 1 aesara.sandbox.gpuarray.basic_ops.GpuFromHost 0.8% 99.1% 0.033s 1.09e-06s", "29.8% 89.3% 1.166s 1.30e-05s C 90001 10 aesara.sandbox.gpuarray.elemwise.GpuElemwise 4.1% 93.4%", "Scan op profile. Time in 10001 calls to Function.__call__: 1.300452e+00s", "i3) - ((i4 * i1 * i5) / i3))}}[(0, 0)]<gpuarray>.0,", "13 GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>(GpuElemwise{neg,no_inplace}.0) 2.3% 94.9% 0.090s 9.04e-06s 10000 19 HostFromGpu(gpuarray)(GpuElemwise{gt,no_inplace}.0)", "<#call> <#apply> <Op name> 59.5% 59.5% 2.329s 1.16e-04s C 20001", "1.16e-04s C 20001 3 GpuGemv{inplace=True} 4.1% 63.6% 0.162s 8.10e-06s C", "x.tag.test_value = D[0] y.tag.test_value = D[1] # print \"Initial model:\"", "\"CGemm\"] for n in train.maker.fgraph.toposort() ] ): print(\"Used the cpu\")", "= aesara.shared(rng.randn(feats).astype(aesara.config.floatX), name=\"w\") b = aesara.shared(np.asarray(0.0, dtype=aesara.config.floatX), name=\"b\") x.tag.test_value =", "1.0% 98.6% 0.011s 1.14e-06s C 10000 1 aesara.tensor.elemwise.Sum 0.7% 99.4%", "-y * tt.log(p_1) - (1 - y) * tt.log(1 -", "prediction on D # Followed by the output of profiling..", "0 InplaceDimShuffle{x}(b) ... (remaining 2 Apply instances account for 0.00%(0.00s)", "0.021s 1.06e-06s C 20001 3 InplaceGpuDimShuffle{x} 0.3% 99.8% 0.011s 1.14e-06s", "C 10000 1 GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray> 1.6% 98.3% 0.061s 6.10e-06s C", "i4) / i3))}}[(0, 0)].0, TensorConstant{0.999800026417}) 18.7% 83.2% 0.217s 2.17e-05s 10000", "i5) / i3))}}[(0, 0)]<gpuarray>(GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[-1.]}, y, GpuElemwise{Cast{float32}}[]<gpuarray>.0,", "99.5% 0.021s 1.06e-06s C 20001 3 InplaceGpuDimShuffle{x} 0.3% 99.8% 0.011s", "excluding Scan op profile. Time in 10001 calls to Function.__call__:", "aesara import aesara.tensor as tt aesara.config.floatX = \"float32\" rng =", "i3 * scalar_softplus(i4)))}}[(0, 4)](y, Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0, TensorConstant{(1,) of", "i1))), i2)}} ... (remaining 0 Ops account for 0.00%(0.00s) of", "consume a large amount of extra time, but by making", "0.004s 3.70e-07s 10000 10 Elemwise{neg,no_inplace}(Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0) 0.3% 98.7%", "0)]<gpuarray> 3.3% 88.8% 0.131s 1.31e-05s C 10000 1 GpuCAReduceCuda{add} 2.9%", "GPU and CPU, you can minimize their overhead. Notice that", "GPU computations # In your terminal, type: $ CUDA_LAUNCH_BLOCKING=1 THEANO_FLAGS=profile=True,device=cuda", "Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}} 1.0% 97.4% 0.011s 1.14e-06s C 10000 1 Sum{acc_dtype=float64}", "4)](y, Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0, TensorConstant{(1,) of -1.0}, Elemwise{sub,no_inplace}.0, Elemwise{neg,no_inplace}.0)", "set N = 4000), you will see a gain from", "InplaceDimShuffle{x}.0, TensorConstant{(1,) of 0.5}) 0.0% 100.0% 0.000s 1.19e-06s 1 0", "first the output of the script: Used the gpu target", "<#call> <#apply> <Op name> 64.5% 64.5% 0.747s 3.73e-05s C 20001", "* i1 * i2) / i3) - ((scalar_sigmoid((-i0)) * i1", "w, TensorConstant{0.0}) 30.5% 64.5% 0.353s 3.53e-05s 10000 15 CGemv{inplace}(w, TensorConstant{-0.00999999977648},", "4.79e-06s C 80001 9 aesara.tensor.elemwise.Elemwise 1.0% 98.6% 0.011s 1.14e-06s C", "Sum{acc_dtype=float64} 0.5% 97.9% 0.006s 2.83e-07s C 20001 3 InplaceDimShuffle{x} 0.4%", "3.94e-05s 10000 7 CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0}) 30.5% 64.5%", "Elemwise{neg,no_inplace}(Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0) 0.3% 98.7% 0.004s 3.64e-07s 10000 5", "10000 1 GpuElemwise{neg,no_inplace} 2.6% 94.3% 0.102s 1.02e-05s C 10000 1", "99.4% 0.002s 2.21e-07s 10000 1 Shape_i{0}(x) 0.2% 99.6% 0.002s 1.98e-07s", "* i5) / i3))}}[(0, 0)]<gpuarray>.0, TensorConstant{0.999800026417}) 4.0% 63.5% 0.157s 1.57e-05s", "since aesara import 2.864s Class --- <% time> <sum %>", "* i3 * scalar_softplus(i4)))}}[(0, 4)](y, Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0, TensorConstant{(1,)", "- ((i4 * i1 * i5) / i3))}}[(0, 0)]<gpuarray>(GpuElemwise{Composite{((-i0) -", "2.6% 90.1% 0.102s 1.02e-05s 10000 20 GpuElemwise{Composite{(i0 - (i1 *", "aesara.tensor as tt aesara.config.floatX = \"float32\" rng = np.random N", "= train() # print \"Final model:\" # print w.get_value(), b.get_value()", "i4) / i3))}}[(0, 0)] 4.3% 96.4% 0.050s 4.98e-06s C 10000", "10000 1 Shape_i{0}(x) ... (remaining 7 Apply instances account for", "0.033s 1.09e-06s C 30001 4 aesara.sandbox.gpuarray.elemwise.GpuDimShuffle 0.7% 99.8% 0.026s 2.59e-06s", "GpuElemwise{Cast{float32}}[]<gpuarray>.0, GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0, GpuElemwise{sub,no_inplace}.0) 3.7% 71.0% 0.144s 1.44e-05s 10000 4", "99.9% 0.002s 1.54e-07s 10000 16 Elemwise{Composite{(i0 - (i1 * i2))}}[(0,", "target values for D prediction on D Results were produced", "1. Raw results import numpy as np import aesara import", "2.864s Class --- <% time> <sum %> <apply time> <time", "0.013s 1.33e-06s 10000 0 InplaceGpuDimShuffle{x}(b) 0.3% 99.6% 0.011s 1.14e-06s 10000", "= D[1] # print \"Initial model:\" # print w.get_value(), b.get_value()", "0.5}) 0.0% 100.0% 0.000s 1.19e-06s 1 0 InplaceDimShuffle{x}(b) ... (remaining", "<type> <#call> <#apply> <Class name> 64.5% 64.5% 0.747s 3.73e-05s C", "<#apply> <Class name> 59.5% 59.5% 2.329s 1.16e-04s C 20001 3", "GpuElemwise{sub,no_inplace}(GpuArrayConstant{[ 1.]}, y) 3.6% 74.6% 0.141s 1.41e-05s 10000 16 GpuElemwise{gt,no_inplace}(GpuElemwise{ScalarSigmoid}[(0,", "C 30001 4 aesara.tensor.elemwise.DimShuffle 0.3% 99.7% 0.004s 3.64e-07s C 10001", "calls to Function.__call__: 1.300452e+00s Time in Function.fn.__call__: 1.215823e+00s (93.492%) Time", "2.88e-07s C 10000 1 InplaceDimShuffle{1,0} 0.2% 99.7% 0.003s 2.65e-07s C", "- i1))), i2)}}(CGemv{inplace}.0, InplaceDimShuffle{x}.0, TensorConstant{(1,) of 0.5}) 0.0% 100.0% 0.000s", "2.9% 91.7% 0.112s 1.12e-05s C 10000 1 GpuElemwise{neg,no_inplace} 2.6% 94.3%", "2.5% 96.7% 0.096s 9.63e-06s C 10000 1 GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray> 1.6%", "20001 3 GpuGemv{inplace=True} 4.1% 63.6% 0.162s 8.10e-06s C 20001 3", "= D[0] y.tag.test_value = D[1] # print \"Initial model:\" #", "GpuCAReduceCuda{add}(GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) - ((i4 *", "CUDA code generation/compiling): 8.239602e+00s Import time 4.228115e-03s Time in all", "Elemwise{Composite{((-i0) - i1)}}[(0, 0)](CGemv{inplace}.0, InplaceDimShuffle{x}.0) 0.2% 99.4% 0.002s 2.21e-07s 10000", "- (i2 * i3 * scalar_softplus(i4)))}}[(0, 4)] 8.9% 92.1% 0.103s", "83.2% 0.217s 2.17e-05s 10000 12 Elemwise{Composite{((i0 * scalar_softplus(i1)) - (i2", "Used the cpu target values for D prediction on D", "# You'll see first the output of the script: Used", "\"Gemm\", \"CGemm\"] for n in train.maker.fgraph.toposort() ] ): print(\"Used the", "cpu\") elif any( [ n.op.__class__.__name__ in [\"GpuGemm\", \"GpuGemv\"] for n", "1.19e-06s 1 0 InplaceDimShuffle{x}(b) ... (remaining 2 Apply instances account", "1 xent = -y * tt.log(p_1) - (1 - y)", "time> <sum %> <apply time> <time per call> <type> <#call>", "time> <time per call> <#call> <id> <Apply name> 34.0% 34.0%", "predict = aesara.function(inputs=[], outputs=prediction, name=\"predict\") if any( [ n.op.__class__.__name__ in", "validate time: 5.993605e-03s Aesara Linker time (includes C, CUDA code", "C 10000 1 Elemwise{neg,no_inplace} 0.3% 98.9% 0.004s 3.64e-07s C 10001", "for 0.00%(0.00s) of the runtime) Apply ------ <% time> <sum", "64.5% 0.747s 3.73e-05s C 20001 3 CGemv{inplace} 18.7% 83.2% 0.217s", "in Function.fn.__call__: 4.081113e+00s (97.605%) Time in thunks: 3.915566e+00s (93.646%) Total", "0.149s 1.49e-05s C 10000 1 GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2)", "6 GpuFromHost<None>(Shape_i{0}.0) 0.7% 99.0% 0.026s 2.59e-06s 10000 5 GpuAllocEmpty{dtype='float32', context_name=None}(Shape_i{0}.0)", "3 aesara.compile.ops.Shape_i ... (remaining 0 Classes account for 0.00%(0.00s) of", "85.5% 0.133s 1.33e-05s C 10000 1 GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>", "tutorial # Solution to Exercise in section 'Using the GPU'", "name> 59.5% 59.5% 2.329s 1.16e-04s C 20001 3 GpuGemv{inplace=True} 4.1%", "* i5) / i3))}}[(0, 0)]<gpuarray>.0) 2.9% 87.5% 0.112s 1.12e-05s 10000", "nodes: 17 Aesara Optimizer time: 6.270301e-01s Aesara validate time: 5.993605e-03s", "75.1% 0.144s 1.44e-05s C 10000 1 GpuElemwise{sub,no_inplace} 3.6% 78.7% 0.141s", "In your terminal, type: $ CUDA_LAUNCH_BLOCKING=1 THEANO_FLAGS=profile=True,device=cuda python using_gpu_solution_1.py #", "tt.log(p_1) - (1 - y) * tt.log(1 - p_1) #", "i2)}}[]<gpuarray> ... (remaining 0 Ops account for 0.00%(0.00s) of the", "10001 2 AllocEmpty{dtype='float32'} 0.3% 99.2% 0.004s 1.78e-07s C 20001 3", "D Results were produced using a GeForce GTX TITAN X", "TensorConstant{0.00999999977648}, Sum{acc_dtype=float64}.0) 0.1% 100.0% 0.001s 1.34e-07s 10000 3 Shape_i{0}(y) 0.0%", "i1 * i4) / i3))}}[(0, 0)] 4.3% 96.4% 0.050s 4.98e-06s", "Function.fn.__call__: 4.081113e+00s (97.605%) Time in thunks: 3.915566e+00s (93.646%) Total compile", "20001 3 aesara.sandbox.gpuarray.blas.GpuGemv 29.8% 89.3% 1.166s 1.30e-05s C 90001 10", "graph p_1 = 1 / (1 + tt.exp(-tt.dot(x, w) -", "1 0 InplaceDimShuffle{x}(b) ... (remaining 2 Apply instances account for", "<time per call> <type> <#call> <#apply> <Class name> 59.5% 59.5%", "0.144s 1.44e-05s C 10000 1 GpuElemwise{sub,no_inplace} 3.6% 78.7% 0.141s 1.41e-05s", "99.3% 0.013s 1.33e-06s 10000 0 InplaceGpuDimShuffle{x}(b) 0.3% 99.6% 0.011s 1.14e-06s", "0.002s 1.54e-07s 10000 16 Elemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)](b,", "np import aesara import aesara.tensor as tt aesara.config.floatX = \"float32\"", "1.16e-04s C 20001 3 aesara.sandbox.gpuarray.blas.GpuGemv 29.8% 89.3% 1.166s 1.30e-05s C", "9.04e-06s 10000 19 HostFromGpu(gpuarray)(GpuElemwise{gt,no_inplace}.0) 1.8% 96.7% 0.072s 7.16e-06s 10000 14", "59.5% 59.5% 2.329s 1.16e-04s C 20001 3 GpuGemv{inplace=True} 4.1% 63.6%", "10000 16 Elemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)](b, TensorConstant{0.00999999977648}, Sum{acc_dtype=float64}.0)", "0.8% 99.1% 0.033s 1.09e-06s C 30001 4 aesara.sandbox.gpuarray.elemwise.GpuDimShuffle 0.7% 99.8%", "10000 15 CGemv{inplace}(w, TensorConstant{-0.00999999977648}, x.T, Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2)", "* i2) / i3) - ((i4 * i1 * i5)", "i3) - ((i4 * i1 * i5) / i3))}}[(0, 0)]<gpuarray>", "= aesara.function( inputs=[], outputs=[prediction, xent], updates=[(w, w - 0.01 *", "* i1 * i4) / i3))}}[(0, 0)].0, TensorConstant{0.999800026417}) 18.7% 83.2%", "<id> <Apply name> 34.0% 34.0% 0.394s 3.94e-05s 10000 7 CGemv{inplace}(AllocEmpty{dtype='float32'}.0,", "0.133s 1.33e-05s C 10000 1 GpuElemwise{Cast{float32}}[]<gpuarray> 3.4% 85.5% 0.133s 1.33e-05s", "10000 10 Elemwise{neg,no_inplace}(Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0) 0.3% 98.7% 0.004s 3.64e-07s", "Time in 10001 calls to Function.__call__: 4.181247e+00s Time in Function.fn.__call__:", "1 Elemwise{Composite{((-i0) - i1)}}[(0, 0)] 0.2% 99.9% 0.002s 1.98e-07s C", "Elemwise{Cast{float32}}(InplaceDimShuffle{x}.0) 0.2% 99.7% 0.002s 1.90e-07s 10000 6 InplaceDimShuffle{x}(Shape_i{0}.0) 0.1% 99.9%", "0.133s 1.33e-05s C 10000 1 GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray> 3.3%", "of profiling.. You'll see profiling results for each function #", "0.011s 1.14e-06s C 10000 1 aesara.tensor.elemwise.Sum 0.7% 99.4% 0.009s 2.85e-07s", "n.op.__class__.__name__ in [\"Gemv\", \"CGemv\", \"Gemm\", \"CGemm\"] for n in train.maker.fgraph.toposort()", "of Apply nodes: 17 Aesara Optimizer time: 6.270301e-01s Aesara validate", "6.10e-06s 10000 6 GpuFromHost<None>(Shape_i{0}.0) 0.7% 99.0% 0.026s 2.59e-06s 10000 5", "# Compile expressions to functions train = aesara.function( inputs=[], outputs=[prediction,", "Aesara tutorial # Solution to Exercise in section 'Using the", "tell if aesara used the cpu or the gpu\") print(train.maker.fgraph.toposort())", "CUDA_LAUNCH_BLOCKING=1 THEANO_FLAGS=profile=True,device=cuda python using_gpu_solution_1.py # You'll see first the output", "99.1% 0.033s 1.09e-06s C 30001 4 aesara.sandbox.gpuarray.elemwise.GpuDimShuffle 0.7% 99.8% 0.026s", "-1.0}, Elemwise{sub,no_inplace}.0, Elemwise{neg,no_inplace}.0) 8.9% 92.1% 0.103s 1.03e-05s 10000 13 Elemwise{Composite{(((scalar_sigmoid(i0)", "10000 1 Sum{acc_dtype=float64} 0.5% 97.9% 0.006s 2.83e-07s C 20001 3", "0.004s 4.22e-07s C 10000 1 Elemwise{sub,no_inplace} 0.3% 98.6% 0.004s 3.70e-07s", "Aesara Linker time (includes C, CUDA code generation/compiling): 8.239602e+00s Import", "99.8% 0.011s 1.14e-06s C 10000 1 InplaceGpuDimShuffle{1,0} 0.2% 100.0% 0.008s", "between GPU and CPU, you can minimize their overhead. Notice", "0.1% 100.0% 0.001s 1.34e-07s 10000 3 Shape_i{0}(y) 0.0% 100.0% 0.000s", "script: Used the cpu target values for D prediction on", "((scalar_sigmoid((-i0)) * i1 * i4) / i3))}}[(0, 0)](Elemwise{Composite{((-i0) - i1)}}[(0,", "Profiling summary for all functions: Function profiling ================== Message: Sum", "0.00%(0.00s) of the runtime) # 2.2 Profiling for GPU computations", "1 Elemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[(0,", "20001 3 Shape_i{0} 0.0% 100.0% 0.000s 2.00e-05s C 1 1", "functions train = aesara.function( inputs=[], outputs=[prediction, xent], updates=[(w, w -", "GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>(GpuGemv{inplace=True}.0, InplaceGpuDimShuffle{x}.0) 3.3% 84.7% 0.131s 1.31e-05s 10000", "i1))), i2)}}(CGemv{inplace}.0, InplaceDimShuffle{x}.0, TensorConstant{(1,) of 0.5}) 0.0% 100.0% 0.000s 1.19e-06s", "C 20001 3 aesara.compile.ops.Shape_i ... (remaining 0 Classes account for", "0)]<gpuarray> 3.7% 75.1% 0.144s 1.44e-05s C 10000 1 GpuElemwise{sub,no_inplace} 3.6%", "1.90e-07s 10000 6 InplaceDimShuffle{x}(Shape_i{0}.0) 0.1% 99.9% 0.002s 1.54e-07s 10000 16", "call> <type> <#call> <#apply> <Op name> 59.5% 59.5% 2.329s 1.16e-04s", "the output of the script: Used the cpu target values", "# Followed by the output of profiling.. You'll see profiling", "import aesara.tensor as tt aesara.config.floatX = \"float32\" rng = np.random", "C 10000 1 Elemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)] 0.0%", "3 aesara.sandbox.gpuarray.basic_ops.HostFromGpu 3.3% 96.7% 0.131s 1.31e-05s C 10000 1 aesara.sandbox.gpuarray.elemwise.GpuCAReduceCuda", "Time since aesara import 2.864s Class --- <% time> <sum", "<#call> <id> <Apply name> 55.0% 55.0% 2.154s 2.15e-04s 10000 7", "10000 14 HostFromGpu(gpuarray)(GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3 *", "of having a one prediction = p_1 > 0.5 #", "10000 16 GpuElemwise{gt,no_inplace}(GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[ 0.5]}) 3.4% 78.0% 0.133s 1.33e-05s", "1.02e-05s 10000 20 GpuElemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)]<gpuarray>(b, GpuArrayConstant{0.00999999977648},", "0.112s 1.12e-05s C 10000 1 GpuElemwise{neg,no_inplace} 2.6% 94.3% 0.102s 1.02e-05s", "i3 * scalar_softplus(i4)))}}[(0, 4)] 8.9% 92.1% 0.103s 1.03e-05s C 10000", "Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0, TensorConstant{(1,) of -1.0}, Elemwise{sub,no_inplace}.0, Elemwise{neg,no_inplace}.0) 8.9%", "10000 1 Shape_i{0}(x) 0.2% 99.6% 0.002s 1.98e-07s 10000 8 Elemwise{Cast{float32}}(InplaceDimShuffle{x}.0)", "1.166s 1.30e-05s C 90001 10 aesara.sandbox.gpuarray.elemwise.GpuElemwise 4.1% 93.4% 0.162s 8.10e-06s", "updates=[(w, w - 0.01 * gw), (b, b - 0.01", "88.8% 0.131s 1.31e-05s C 10000 1 GpuCAReduceCuda{add} 2.9% 91.7% 0.112s", "1 4 Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}}(CGemv{inplace}.0, InplaceDimShuffle{x}.0, TensorConstant{(1,) of 0.5})", "the ops operate on small inputs; if you increase the", "# The prediction that is done: 0 or 1 xent", "TensorConstant{1.0}, x, w, TensorConstant{0.0}) 30.5% 64.5% 0.353s 3.53e-05s 10000 15", "Time in thunks: 1.157602e+00s (89.015%) Total compile time: 8.922548e-01s Number", "TensorConstant{(1,) of 0.5}) 0.0% 100.0% 0.000s 1.19e-06s 1 0 InplaceDimShuffle{x}(b)", "((i4 * i1 * i5) / i3))}}[(0, 0)]<gpuarray>(GpuElemwise{Composite{((-i0) - i1)}}[(0,", "1.33e-05s 10000 9 GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>(GpuGemv{inplace=True}.0, InplaceGpuDimShuffle{x}.0) 3.3% 84.7%", "0.026s 2.59e-06s C 10001 2 GpuAllocEmpty{dtype='float32', context_name=None} 0.5% 99.5% 0.021s", "1.33e-05s C 10000 1 GpuElemwise{Cast{float32}}[]<gpuarray> 3.4% 85.5% 0.133s 1.33e-05s C", "CUDA code generation/compiling): 2.949309e-02s Import time 3.543139e-03s Time in all", "to Function.__call__: 1.300452e+00s Time in Function.fn.__call__: 1.215823e+00s (93.492%) Time in", "2.21e-07s 10000 1 Shape_i{0}(x) 0.2% 99.6% 0.002s 1.98e-07s 10000 8", "+ 0.01 * (w ** 2).sum() # The cost to", "... (remaining 0 Ops account for 0.00%(0.00s) of the runtime)", "AllocEmpty{dtype='float32'}(Shape_i{0}.0) 0.2% 99.0% 0.003s 2.88e-07s 10000 2 InplaceDimShuffle{1,0}(x) 0.2% 99.2%", "GpuAllocEmpty{dtype='float32', context_name=None} 0.5% 99.5% 0.021s 1.06e-06s C 20001 3 InplaceGpuDimShuffle{x}", "* i4) / i3))}}[(0, 0)](Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0, TensorConstant{(1,) of", "name> 64.5% 64.5% 0.747s 3.73e-05s C 20001 3 CGemv{inplace} 18.7%", "3.8% 71.4% 0.149s 1.49e-05s C 10000 1 GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1", "see first the output of the script: Used the cpu", "Linker time (includes C, CUDA code generation/compiling): 8.239602e+00s Import time", "1.157602e+00s (89.015%) Total compile time: 8.922548e-01s Number of Apply nodes:", "100.0% 0.001s 1.34e-07s 10000 3 Shape_i{0}(y) 0.0% 100.0% 0.000s 3.89e-05s", "18.7% 83.2% 0.217s 2.17e-05s 10000 12 Elemwise{Composite{((i0 * scalar_softplus(i1)) -", "0.2% 99.4% 0.002s 2.21e-07s 10000 1 Shape_i{0}(x) 0.2% 99.6% 0.002s", "Import time 3.543139e-03s Time in all call to aesara.grad() 1.848292e-02s", "aesara.sandbox.gpuarray.blas.GpuGemv 29.8% 89.3% 1.166s 1.30e-05s C 90001 10 aesara.sandbox.gpuarray.elemwise.GpuElemwise 4.1%", "inputs; if you increase the input data size (e.g. set", "per call> <#call> <id> <Apply name> 55.0% 55.0% 2.154s 2.15e-04s", "terminal, type: $ THEANO_FLAGS=profile=True,device=cpu python using_gpu_solution_1.py # You'll see first", "1.14e-06s 10000 14 Sum{acc_dtype=float64}(Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3)", "0)]<gpuarray>.0, TensorConstant{0.999800026417}) 4.0% 63.5% 0.157s 1.57e-05s 10000 12 GpuElemwise{Composite{((i0 *", "99.8% 0.008s 7.94e-07s 10000 8 InplaceGpuDimShuffle{x}(GpuFromHost<None>.0) 0.1% 99.9% 0.005s 5.27e-07s", "i1)}}[(0, 0)] 0.2% 99.9% 0.002s 1.98e-07s C 10000 1 Elemwise{Cast{float32}}", "i3) - ((scalar_sigmoid((-i0)) * i1 * i4) / i3))}}[(0, 0)](Elemwise{Composite{((-i0)", "0.002s 1.54e-07s C 10000 1 Elemwise{Composite{(i0 - (i1 * i2))}}[(0,", "94.3% 0.102s 1.02e-05s C 10000 1 GpuElemwise{Composite{(i0 - (i1 *", "C 10000 1 Elemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3", "one prediction = p_1 > 0.5 # The prediction that", "i1 * i2) / i3) - ((scalar_sigmoid((-i0)) * i1 *", "rng.randn(N, feats).astype(aesara.config.floatX), rng.randint(size=N, low=0, high=2).astype(aesara.config.floatX), ) training_steps = 10000 #", "1.57e-05s C 10000 1 GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 *", "D\") print(predict()) \"\"\" # 2. Profiling # 2.1 Profiling for", "99.9% 0.002s 1.98e-07s C 10000 1 Elemwise{Cast{float32}} 0.1% 100.0% 0.002s", "--- <% time> <sum %> <apply time> <time per call>", "w = aesara.shared(rng.randn(feats).astype(aesara.config.floatX), name=\"w\") b = aesara.shared(np.asarray(0.0, dtype=aesara.config.floatX), name=\"b\") x.tag.test_value", "i1 * i5) / i3))}}[(0, 0)]<gpuarray>(GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[-1.]},", "Construct Aesara expression graph p_1 = 1 / (1 +", "that each of the GPU ops consumes more time than", "target values for D prediction on D # Followed by", "i1)}}[(0, 0)]<gpuarray>.0) 2.6% 90.1% 0.102s 1.02e-05s 10000 20 GpuElemwise{Composite{(i0 -", "9 aesara.tensor.elemwise.Elemwise 1.0% 98.6% 0.011s 1.14e-06s C 10000 1 aesara.tensor.elemwise.Sum", "0.2% 99.7% 0.003s 2.65e-07s C 10000 1 Elemwise{Composite{((-i0) - i1)}}[(0,", "for D\") print(D[1]) print(\"prediction on D\") print(predict()) \"\"\" # 2.", "1.0% 97.4% 0.011s 1.14e-06s C 10000 1 Sum{acc_dtype=float64} 0.5% 97.9%", "1 Elemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)] 0.0% 100.0% 0.000s", "compile time: 9.256095e+00s Number of Apply nodes: 21 Aesara Optimizer", "Ops account for 0.00%(0.00s) of the runtime) Apply ------ <%", "0.004s 3.64e-07s 10000 5 AllocEmpty{dtype='float32'}(Shape_i{0}.0) 0.2% 99.0% 0.003s 2.88e-07s 10000", "78.0% 0.133s 1.33e-05s 10000 10 GpuElemwise{Cast{float32}}[]<gpuarray>(InplaceGpuDimShuffle{x}.0) 3.4% 81.4% 0.133s 1.33e-05s", "10000 1 GpuElemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)]<gpuarray> 2.5% 96.7%", "0.7% 99.4% 0.009s 2.85e-07s C 30001 4 aesara.tensor.elemwise.DimShuffle 0.3% 99.7%", "4 Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}}(CGemv{inplace}.0, InplaceDimShuffle{x}.0, TensorConstant{(1,) of 0.5}) 0.0%", "1.98e-07s 10000 8 Elemwise{Cast{float32}}(InplaceDimShuffle{x}.0) 0.2% 99.7% 0.002s 1.90e-07s 10000 6", "/ i3))}}[(0, 0)]<gpuarray>.0, TensorConstant{0.999800026417}) 4.0% 63.5% 0.157s 1.57e-05s 10000 12", "Shape_i{0}(y) 0.0% 100.0% 0.000s 3.89e-05s 1 3 CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0}, x,", "C, CUDA code generation/compiling): 2.949309e-02s Import time 3.543139e-03s Time in", "/ i3))}}[(0, 0)].0) 0.4% 97.8% 0.004s 4.22e-07s 10000 4 Elemwise{sub,no_inplace}(TensorConstant{(1,)", "3 aesara.sandbox.gpuarray.blas.GpuGemv 29.8% 89.3% 1.166s 1.30e-05s C 90001 10 aesara.sandbox.gpuarray.elemwise.GpuElemwise", "C 10000 1 InplaceDimShuffle{1,0} 0.2% 99.7% 0.003s 2.65e-07s C 10000", "name> 34.0% 34.0% 0.394s 3.94e-05s 10000 7 CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0}, x,", "96.7% 0.072s 7.16e-06s 10000 14 HostFromGpu(gpuarray)(GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2", "nodes: 21 Aesara Optimizer time: 9.996419e-01s Aesara validate time: 6.523132e-03s", "* i3 * scalar_softplus(i4)))}}[(0, 4)] 8.9% 92.1% 0.103s 1.03e-05s C", "(remaining 7 Apply instances account for 0.07%(0.00s) of the runtime)", "1.14e-06s C 10000 1 InplaceGpuDimShuffle{1,0} 0.2% 100.0% 0.008s 3.95e-07s C", "4.98e-06s C 10000 1 Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}} 1.0% 97.4% 0.011s 1.14e-06s", "((scalar_sigmoid((-i0)) * i1 * i4) / i3))}}[(0, 0)].0, TensorConstant{0.999800026417}) 18.7%", "0)]<gpuarray>(b, GpuArrayConstant{0.00999999977648}, GpuCAReduceCuda{add}.0) 2.5% 92.6% 0.096s 9.63e-06s 10000 13 GpuElemwise{ScalarSigmoid}[(0,", "10 Elemwise{neg,no_inplace}(Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0) 0.3% 98.7% 0.004s 3.64e-07s 10000", "Elemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[(0, 4)]", "N = 4000), you will see a gain from using", "1 GpuElemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}}[]<gpuarray> ... (remaining 0 Ops account", "1.78e-07s C 20001 3 Shape_i{0} 0.2% 99.5% 0.003s 2.88e-07s C", "i2))}}[(0, 0)]<gpuarray> 2.5% 96.7% 0.096s 9.63e-06s C 10000 1 GpuElemwise{ScalarSigmoid}[(0,", "- i1)}}[(0, 0)].0) 0.3% 98.7% 0.004s 3.64e-07s 10000 5 AllocEmpty{dtype='float32'}(Shape_i{0}.0)", "0.217s 2.17e-05s 10000 12 Elemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 *", "exit excluding Scan op profile. Time in 10001 calls to", "for n in train.maker.fgraph.toposort() ] ): print(\"Used the cpu\") elif", "98.9% 0.004s 3.64e-07s C 10001 2 AllocEmpty{dtype='float32'} 0.3% 99.2% 0.004s", "0)]<gpuarray>(GpuElemwise{neg,no_inplace}.0) 2.3% 94.9% 0.090s 9.04e-06s 10000 19 HostFromGpu(gpuarray)(GpuElemwise{gt,no_inplace}.0) 1.8% 96.7%", "CPU computations # In your terminal, type: $ THEANO_FLAGS=profile=True,device=cpu python", "on D Results were produced using a GeForce GTX TITAN", "15 CGemv{inplace}(w, TensorConstant{-0.00999999977648}, x.T, Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) /", "x = aesara.shared(D[0], name=\"x\") y = aesara.shared(D[1], name=\"y\") w =", "Exercise in section 'Using the GPU' # 1. Raw results", "GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[-1.]}, GpuElemwise{sub,no_inplace}.0, GpuElemwise{neg,no_inplace}.0) 3.8% 67.3% 0.149s", "GpuElemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)]<gpuarray>(b, GpuArrayConstant{0.00999999977648}, GpuCAReduceCuda{add}.0) 2.5% 92.6%", "TensorConstant{0.999800026417}) 4.0% 63.5% 0.157s 1.57e-05s 10000 12 GpuElemwise{Composite{((i0 * scalar_softplus(i1))", "<Class name> 59.5% 59.5% 2.329s 1.16e-04s C 20001 3 aesara.sandbox.gpuarray.blas.GpuGemv", "for i in range(training_steps): pred, err = train() # print", "Optimizer time: 9.996419e-01s Aesara validate time: 6.523132e-03s Aesara Linker time", "Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}} ... (remaining 0 Ops account for", "96.7% 0.131s 1.31e-05s C 10000 1 aesara.sandbox.gpuarray.elemwise.GpuCAReduceCuda 1.6% 98.3% 0.061s", "1.44e-05s C 10000 1 GpuElemwise{sub,no_inplace} 3.6% 78.7% 0.141s 1.41e-05s C", "0.5]}) 3.4% 78.0% 0.133s 1.33e-05s 10000 10 GpuElemwise{Cast{float32}}[]<gpuarray>(InplaceGpuDimShuffle{x}.0) 3.4% 81.4%", "for 0.00%(0.00s) of the runtime) Ops --- <% time> <sum", "0.103s 1.03e-05s C 10000 1 Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2)", "(remaining 0 Ops account for 0.00%(0.00s) of the runtime) Apply", "GpuCAReduceCuda{add}.0) 2.5% 92.6% 0.096s 9.63e-06s 10000 13 GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>(GpuElemwise{neg,no_inplace}.0) 2.3%", "1.300452e+00s Time in Function.fn.__call__: 1.215823e+00s (93.492%) Time in thunks: 1.157602e+00s", "@ 3.50GHz Function profiling ================== Message: Sum of all(2) printed", "0.4% 97.8% 0.004s 4.22e-07s 10000 4 Elemwise{sub,no_inplace}(TensorConstant{(1,) of 1.0}, y)", "* i3 * scalar_softplus(i4)))}}[]<gpuarray>(y, GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[-1.]}, GpuElemwise{sub,no_inplace}.0,", "1 InplaceDimShuffle{1,0} 0.2% 99.7% 0.003s 2.65e-07s C 10000 1 Elemwise{Composite{((-i0)", "InplaceDimShuffle{x}(b) ... (remaining 2 Apply instances account for 0.00%(0.00s) of", "time> <time per call> <#call> <id> <Apply name> 55.0% 55.0%", "<type> <#call> <#apply> <Op name> 59.5% 59.5% 2.329s 1.16e-04s C", "> 0.5 # The prediction that is done: 0 or", "9.256095e+00s Number of Apply nodes: 21 Aesara Optimizer time: 9.996419e-01s", "0.217s 2.17e-05s C 10000 1 Elemwise{Composite{((i0 * scalar_softplus(i1)) - (i2", "(includes C, CUDA code generation/compiling): 8.239602e+00s Import time 4.228115e-03s Time", "GpuElemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}}[]<gpuarray> ... (remaining 0 Ops account for", "to functions train = aesara.function( inputs=[], outputs=[prediction, xent], updates=[(w, w", "99.0% 0.003s 2.88e-07s 10000 2 InplaceDimShuffle{1,0}(x) 0.2% 99.2% 0.003s 2.65e-07s", "... (remaining 0 Classes account for 0.00%(0.00s) of the runtime)", "that is done: 0 or 1 xent = -y *", "100.0% 0.000s 4.77e-06s C 1 1 Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}}", "range(training_steps): pred, err = train() # print \"Final model:\" #", "(i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray>(y, GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[-1.]},", "0.011s 1.14e-06s C 10000 1 InplaceGpuDimShuffle{1,0} 0.2% 100.0% 0.008s 3.95e-07s", "# The cost to optimize gw, gb = tt.grad(cost, [w,", "N = 400 feats = 784 D = ( rng.randn(N,", "# Solution to Exercise in section 'Using the GPU' #", "0.3% 98.1% 0.004s 3.76e-07s 10000 0 InplaceDimShuffle{x}(b) 0.3% 98.4% 0.004s", "TensorConstant{-0.00999999977648}, x.T, Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) -", "gpu target values for D prediction on D Results were", "9.996419e-01s Aesara validate time: 6.523132e-03s Aesara Linker time (includes C,", "C 10000 1 GpuElemwise{gt,no_inplace} 3.4% 82.1% 0.133s 1.33e-05s C 10000", "call to aesara.grad() 1.848292e-02s Time since aesara import 2.864s Class", "by the output of profiling.. You'll see profiling results for", "* i1 * i4) / i3))}}[(0, 0)].0) 0.4% 97.8% 0.004s", "7 GpuGemv{inplace=True}(GpuAllocEmpty{dtype='float32', context_name=None}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0}) 4.5% 59.5% 0.176s", "summaries for CPU and GPU. Usually GPU ops 'GpuFromHost' and", "than its CPU counterpart. This is because the ops operate", "): print(\"Used the cpu\") elif any( [ n.op.__class__.__name__ in [\"GpuGemm\",", "92.1% 0.103s 1.03e-05s C 10000 1 Elemwise{Composite{(((scalar_sigmoid(i0) * i1 *", "0.5 # The prediction that is done: 0 or 1", "cpu or the gpu\") print(train.maker.fgraph.toposort()) for i in range(training_steps): pred,", "20001 3 aesara.sandbox.gpuarray.basic_ops.HostFromGpu 3.3% 96.7% 0.131s 1.31e-05s C 10000 1", "the script: Used the cpu target values for D prediction", "0.2% 100.0% 0.008s 3.95e-07s C 20001 3 aesara.compile.ops.Shape_i ... (remaining", "<% time> <sum %> <apply time> <time per call> <#call>", "* i2) / i3) - ((scalar_sigmoid((-i0)) * i1 * i4)", "i3))}}[(0, 0)].0) 0.4% 97.8% 0.004s 4.22e-07s 10000 4 Elemwise{sub,no_inplace}(TensorConstant{(1,) of", "C 20001 3 GpuGemv{inplace=True} 4.1% 63.6% 0.162s 8.10e-06s C 20001", "[\"Gemv\", \"CGemv\", \"Gemm\", \"CGemm\"] for n in train.maker.fgraph.toposort() ] ):", "tt aesara.config.floatX = \"float32\" rng = np.random N = 400", "profiling.. You'll see profiling results for each function # in", "0 InplaceDimShuffle{x}(b) 0.3% 98.4% 0.004s 3.70e-07s 10000 10 Elemwise{neg,no_inplace}(Elemwise{Composite{((-i0) -", "Profiling # 2.1 Profiling for CPU computations # In your", "results import numpy as np import aesara import aesara.tensor as", "2 AllocEmpty{dtype='float32'} 0.3% 99.2% 0.004s 1.78e-07s C 20001 3 Shape_i{0}", "* scalar_softplus(i4)))}}[]<gpuarray> 3.8% 71.4% 0.149s 1.49e-05s C 10000 1 GpuElemwise{Composite{(((scalar_sigmoid(i0)", "0.061s 6.10e-06s C 10000 1 GpuFromHost<None> 0.7% 99.0% 0.026s 2.59e-06s", "1.57e-05s 10000 12 GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3", "10000 7 CGemv{inplace}(AllocEmpty{dtype='float32'}.0, TensorConstant{1.0}, x, w, TensorConstant{0.0}) 30.5% 64.5% 0.353s", "Number of Apply nodes: 21 Aesara Optimizer time: 9.996419e-01s Aesara", "HostFromGpu(gpuarray) 4.0% 67.6% 0.157s 1.57e-05s C 10000 1 GpuElemwise{Composite{((i0 *", "91.7% 0.112s 1.12e-05s C 10000 1 GpuElemwise{neg,no_inplace} 2.6% 94.3% 0.102s", "aesara import 15.415s Class --- <% time> <sum %> <apply", "- ((scalar_sigmoid((-i0)) * i1 * i4) / i3))}}[(0, 0)].0, TensorConstant{0.999800026417})", "2.949309e-02s Import time 3.543139e-03s Time in all call to aesara.grad()", "0)].0) 0.3% 98.7% 0.004s 3.64e-07s 10000 5 AllocEmpty{dtype='float32'}(Shape_i{0}.0) 0.2% 99.0%", "in range(training_steps): pred, err = train() # print \"Final model:\"", "0.07%(0.00s) of the runtime) # 3. Conclusions Examine and compare", "0.133s 1.33e-05s 10000 10 GpuElemwise{Cast{float32}}[]<gpuarray>(InplaceGpuDimShuffle{x}.0) 3.4% 81.4% 0.133s 1.33e-05s 10000", "not able to tell if aesara used the cpu or", "0.131s 1.31e-05s C 10000 1 aesara.sandbox.gpuarray.elemwise.GpuCAReduceCuda 1.6% 98.3% 0.061s 6.10e-06s", "(93.492%) Time in thunks: 1.157602e+00s (89.015%) Total compile time: 8.922548e-01s", "(w ** 2).sum() # The cost to optimize gw, gb", "summary for all functions: Function profiling ================== Message: Sum of", "0.7% 99.8% 0.026s 2.59e-06s C 10001 2 aesara.sandbox.gpuarray.basic_ops.GpuAllocEmpty 0.2% 100.0%", "and CPU, you can minimize their overhead. Notice that each", "Time since aesara import 15.415s Class --- <% time> <sum", "100.0% 0.008s 3.95e-07s C 20001 3 aesara.compile.ops.Shape_i ... (remaining 0", "# We'll show here only the summary: Results were produced", "= aesara.function(inputs=[], outputs=prediction, name=\"predict\") if any( [ n.op.__class__.__name__ in [\"Gemv\",", "aesara.shared(np.asarray(0.0, dtype=aesara.config.floatX), name=\"b\") x.tag.test_value = D[0] y.tag.test_value = D[1] #", "i1)}}[(0, 0)].0, TensorConstant{(1,) of -1.0}, y, Elemwise{Cast{float32}}.0, Elemwise{sub,no_inplace}.0) 4.3% 96.4%", "* i4) / i3))}}[(0, 0)].0) 0.4% 97.8% 0.004s 4.22e-07s 10000", "C 10000 1 GpuFromHost<None> 0.7% 99.0% 0.026s 2.59e-06s C 10001", "0.3% 99.7% 0.004s 3.64e-07s C 10001 2 aesara.tensor.basic.AllocEmpty 0.3% 100.0%", "C 10000 1 Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}} 1.0% 97.4% 0.011s 1.14e-06s C", "10000 2 InplaceGpuDimShuffle{1,0}(x) 0.2% 99.8% 0.008s 7.94e-07s 10000 8 InplaceGpuDimShuffle{x}(GpuFromHost<None>.0)", "0)] 4.3% 96.4% 0.050s 4.98e-06s C 10000 1 Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}}", "* i1 * i5) / i3))}}[(0, 0)]<gpuarray> 3.7% 75.1% 0.144s", "10 GpuElemwise{Cast{float32}}[]<gpuarray>(InplaceGpuDimShuffle{x}.0) 3.4% 81.4% 0.133s 1.33e-05s 10000 9 GpuElemwise{Composite{((-i0) -", "84.7% 0.131s 1.31e-05s 10000 17 GpuCAReduceCuda{add}(GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2)", "98.3% 0.004s 4.22e-07s C 10000 1 Elemwise{sub,no_inplace} 0.3% 98.6% 0.004s", "time 3.543139e-03s Time in all call to aesara.grad() 1.848292e-02s Time", "all call to aesara.grad() 3.286195e-02s Time since aesara import 15.415s", "0)].0, TensorConstant{(1,) of -1.0}, y, Elemwise{Cast{float32}}.0, Elemwise{sub,no_inplace}.0) 4.3% 96.4% 0.050s", "Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}}(CGemv{inplace}.0, InplaceDimShuffle{x}.0, TensorConstant{(1,) of 0.5}) 0.0% 100.0%", "# print w.get_value(), b.get_value() print(\"target values for D\") print(D[1]) print(\"prediction", "GPU. Usually GPU ops 'GpuFromHost' and 'HostFromGpu' by themselves consume", "9 Elemwise{Composite{((-i0) - i1)}}[(0, 0)](CGemv{inplace}.0, InplaceDimShuffle{x}.0) 0.2% 99.4% 0.002s 2.21e-07s", "4 Elemwise{sub,no_inplace}(TensorConstant{(1,) of 1.0}, y) 0.3% 98.1% 0.004s 3.76e-07s 10000", "0)].0, TensorConstant{0.999800026417}) 18.7% 83.2% 0.217s 2.17e-05s 10000 12 Elemwise{Composite{((i0 *", "1.12e-05s 10000 11 GpuElemwise{neg,no_inplace}(GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0) 2.6% 90.1% 0.102s", "* i2))}}[(0, 0)]<gpuarray> 2.5% 96.7% 0.096s 9.63e-06s C 10000 1", "# 2. Profiling # 2.1 Profiling for CPU computations #", "0)]<gpuarray>.0, GpuArrayConstant{[ 0.5]}) 3.4% 78.0% 0.133s 1.33e-05s 10000 10 GpuElemwise{Cast{float32}}[]<gpuarray>(InplaceGpuDimShuffle{x}.0)", "0.7% 99.0% 0.026s 2.59e-06s C 10001 2 GpuAllocEmpty{dtype='float32', context_name=None} 0.5%", "print(\"Used the gpu\") else: print(\"ERROR, not able to tell if", "D prediction on D # Followed by the output of", "C 20001 3 InplaceDimShuffle{x} 0.4% 98.3% 0.004s 4.22e-07s C 10000", "optimize gw, gb = tt.grad(cost, [w, b]) # Compile expressions", "100.0% 0.002s 1.54e-07s C 10000 1 Elemwise{Composite{(i0 - (i1 *", "- (1 - y) * tt.log(1 - p_1) # Cross-entropy", "/ (1 + tt.exp(-tt.dot(x, w) - b)) # Probability of", "C 1 1 GpuElemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}}[]<gpuarray> ... (remaining 0", "/ i3) - ((scalar_sigmoid((-i0)) * i1 * i4) / i3))}}[(0,", "4.3% 96.4% 0.050s 4.98e-06s C 10000 1 Elemwise{Composite{GT(scalar_sigmoid(i0), i1)}} 1.0%", "0.3% 98.9% 0.004s 3.64e-07s C 10001 2 AllocEmpty{dtype='float32'} 0.3% 99.2%", "extra time, but by making as few as possible data", "print(\"Used the cpu\") elif any( [ n.op.__class__.__name__ in [\"GpuGemm\", \"GpuGemv\"]", "show here only the summary: Results were produced using an", "(e.g. set N = 4000), you will see a gain", "ops consumes more time than its CPU counterpart. This is", "scalar_softplus(i4)))}}[]<gpuarray> 3.8% 71.4% 0.149s 1.49e-05s C 10000 1 GpuElemwise{Composite{(((scalar_sigmoid(i0) *", "0)]<gpuarray>.0, GpuArrayConstant{[-1.]}, y, GpuElemwise{Cast{float32}}[]<gpuarray>.0, GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0, GpuElemwise{sub,no_inplace}.0) 3.7% 71.0% 0.144s", "10000 6 GpuFromHost<None>(Shape_i{0}.0) 0.7% 99.0% 0.026s 2.59e-06s 10000 5 GpuAllocEmpty{dtype='float32',", "2.65e-07s C 10000 1 Elemwise{Composite{((-i0) - i1)}}[(0, 0)] 0.2% 99.9%", "- i1)}}[(0, 0)]<gpuarray> 3.3% 88.8% 0.131s 1.31e-05s C 10000 1", "Results were produced using an Intel(R) Core(TM) i7-5930K CPU @", "1 GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray>", "1 GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) - ((i4", "10000 1 Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) -", "GpuElemwise{sub,no_inplace}.0, GpuElemwise{neg,no_inplace}.0) 3.8% 67.3% 0.149s 1.49e-05s 10000 15 GpuElemwise{Composite{(((scalar_sigmoid(i0) *", "# 2.2 Profiling for GPU computations # In your terminal,", "possible data transfers between GPU and CPU, you can minimize", "cost to optimize gw, gb = tt.grad(cost, [w, b]) #", "3.4% 78.0% 0.133s 1.33e-05s 10000 10 GpuElemwise{Cast{float32}}[]<gpuarray>(InplaceGpuDimShuffle{x}.0) 3.4% 81.4% 0.133s", "import 2.864s Class --- <% time> <sum %> <apply time>", "CGemv{inplace} 18.7% 83.2% 0.217s 2.17e-05s C 10000 1 Elemwise{Composite{((i0 *", "1 GpuElemwise{gt,no_inplace} 3.4% 82.1% 0.133s 1.33e-05s C 10000 1 GpuElemwise{Cast{float32}}[]<gpuarray>", "numpy as np import aesara import aesara.tensor as tt aesara.config.floatX", "TensorConstant{1.0}, x, w, TensorConstant{0.0}) 0.0% 100.0% 0.000s 4.77e-06s 1 4", "= aesara.shared(D[1], name=\"y\") w = aesara.shared(rng.randn(feats).astype(aesara.config.floatX), name=\"w\") b = aesara.shared(np.asarray(0.0,", "17 GpuCAReduceCuda{add}(GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) - ((i4", "99.5% 0.003s 2.88e-07s C 10000 1 InplaceDimShuffle{1,0} 0.2% 99.7% 0.003s", "2 aesara.sandbox.gpuarray.basic_ops.GpuAllocEmpty 0.2% 100.0% 0.008s 3.95e-07s C 20001 3 aesara.compile.ops.Shape_i", "Intel(R) Core(TM) i7-5930K CPU @ 3.50GHz Function profiling ================== Message:", "Shape_i{0} 0.0% 100.0% 0.000s 2.00e-05s C 1 1 GpuElemwise{Composite{GT(scalar_sigmoid((-((-i0) -", "\"Initial model:\" # print w.get_value(), b.get_value() # Construct Aesara expression", "GpuArrayConstant{[ 0.5]}) 3.4% 78.0% 0.133s 1.33e-05s 10000 10 GpuElemwise{Cast{float32}}[]<gpuarray>(InplaceGpuDimShuffle{x}.0) 3.4%", "# Construct Aesara expression graph p_1 = 1 / (1", "<time per call> <#call> <id> <Apply name> 34.0% 34.0% 0.394s", "10000 1 Elemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)] 0.0% 100.0%", "section 'Using the GPU' # 1. Raw results import numpy", "83.2% 0.217s 2.17e-05s C 10000 1 Elemwise{Composite{((i0 * scalar_softplus(i1)) -", "784 D = ( rng.randn(N, feats).astype(aesara.config.floatX), rng.randint(size=N, low=0, high=2).astype(aesara.config.floatX), )", "2.17e-05s C 10000 1 Elemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 *", "i3))}}[(0, 0)]<gpuarray> 3.7% 75.1% 0.144s 1.44e-05s C 10000 1 GpuElemwise{sub,no_inplace}", "account for 0.07%(0.00s) of the runtime) # 3. Conclusions Examine", "1.]}, y) 3.6% 74.6% 0.141s 1.41e-05s 10000 16 GpuElemwise{gt,no_inplace}(GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0,", "4.1% 63.6% 0.162s 8.10e-06s C 20001 3 HostFromGpu(gpuarray) 4.0% 67.6%", "1.33e-06s 10000 0 InplaceGpuDimShuffle{x}(b) 0.3% 99.6% 0.011s 1.14e-06s 10000 2", "0.353s 3.53e-05s 10000 15 CGemv{inplace}(w, TensorConstant{-0.00999999977648}, x.T, Elemwise{Composite{(((scalar_sigmoid(i0) * i1", "99.2% 0.004s 1.78e-07s C 20001 3 Shape_i{0} 0.2% 99.5% 0.003s", "C 10000 1 Sum{acc_dtype=float64} 0.5% 97.9% 0.006s 2.83e-07s C 20001", "3.73e-05s C 20001 3 CGemv{inplace} 18.7% 83.2% 0.217s 2.17e-05s C", "0.011s 1.14e-06s 10000 2 InplaceGpuDimShuffle{1,0}(x) 0.2% 99.8% 0.008s 7.94e-07s 10000", "99.0% 0.026s 2.59e-06s C 10001 2 GpuAllocEmpty{dtype='float32', context_name=None} 0.5% 99.5%", "minimize their overhead. Notice that each of the GPU ops", "b.get_value() print(\"target values for D\") print(D[1]) print(\"prediction on D\") print(predict())", "x, w, TensorConstant{0.0}) 30.5% 64.5% 0.353s 3.53e-05s 10000 15 CGemv{inplace}(w,", "TITAN X # Profiling summary for all functions: Function profiling", "78.7% 0.141s 1.41e-05s C 10000 1 GpuElemwise{gt,no_inplace} 3.4% 82.1% 0.133s", "10000 1 aesara.sandbox.gpuarray.basic_ops.GpuFromHost 0.8% 99.1% 0.033s 1.09e-06s C 30001 4", "Solution to Exercise in section 'Using the GPU' # 1.", "HostFromGpu(gpuarray)(GpuElemwise{gt,no_inplace}.0) 1.8% 96.7% 0.072s 7.16e-06s 10000 14 HostFromGpu(gpuarray)(GpuElemwise{Composite{((i0 * scalar_softplus(i1))", "Profiling for CPU computations # In your terminal, type: $", "10000 1 GpuElemwise{sub,no_inplace} 3.6% 78.7% 0.141s 1.41e-05s C 10000 1", "= 4000), you will see a gain from using the", "time: 6.270301e-01s Aesara validate time: 5.993605e-03s Aesara Linker time (includes", "4.22e-07s C 10000 1 Elemwise{sub,no_inplace} 0.3% 98.6% 0.004s 3.70e-07s C", "GpuGemv{inplace=True}(w, TensorConstant{-0.00999999977648}, InplaceGpuDimShuffle{1,0}.0, GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3)", "name=\"y\") w = aesara.shared(rng.randn(feats).astype(aesara.config.floatX), name=\"w\") b = aesara.shared(np.asarray(0.0, dtype=aesara.config.floatX), name=\"b\")", "GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray>(y, GpuElemwise{Composite{((-i0)", "to Function.__call__: 4.181247e+00s Time in Function.fn.__call__: 4.081113e+00s (97.605%) Time in", "10000 18 GpuGemv{inplace=True}(w, TensorConstant{-0.00999999977648}, InplaceGpuDimShuffle{1,0}.0, GpuElemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2)", "name=\"predict\") if any( [ n.op.__class__.__name__ in [\"Gemv\", \"CGemv\", \"Gemm\", \"CGemm\"]", "of -1.0}, Elemwise{sub,no_inplace}.0, Elemwise{neg,no_inplace}.0) 8.9% 92.1% 0.103s 1.03e-05s 10000 13", "0.002s 1.98e-07s C 10000 1 Elemwise{Cast{float32}} 0.1% 100.0% 0.002s 1.54e-07s", "aesara.tensor.elemwise.Sum 0.7% 99.4% 0.009s 2.85e-07s C 30001 4 aesara.tensor.elemwise.DimShuffle 0.3%", "Time in all call to aesara.grad() 1.848292e-02s Time since aesara", "0.004s 3.64e-07s C 10001 2 AllocEmpty{dtype='float32'} 0.3% 99.2% 0.004s 1.78e-07s", "3.7% 75.1% 0.144s 1.44e-05s C 10000 1 GpuElemwise{sub,no_inplace} 3.6% 78.7%", "0.0% 100.0% 0.000s 2.00e-05s C 1 1 GpuElemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))),", "10000 1 GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3 *", "( rng.randn(N, feats).astype(aesara.config.floatX), rng.randint(size=N, low=0, high=2).astype(aesara.config.floatX), ) training_steps = 10000", "in 10001 calls to Function.__call__: 4.181247e+00s Time in Function.fn.__call__: 4.081113e+00s", "symbolic variables x = aesara.shared(D[0], name=\"x\") y = aesara.shared(D[1], name=\"y\")", "87.5% 0.112s 1.12e-05s 10000 11 GpuElemwise{neg,no_inplace}(GpuElemwise{Composite{((-i0) - i1)}}[(0, 0)]<gpuarray>.0) 2.6%", "0.01 * (w ** 2).sum() # The cost to optimize", "THEANO_FLAGS=profile=True,device=cuda python using_gpu_solution_1.py # You'll see first the output of", "0.102s 1.02e-05s 10000 20 GpuElemwise{Composite{(i0 - (i1 * i2))}}[(0, 0)]<gpuarray>(b,", "1 GpuCAReduceCuda{add} 2.9% 91.7% 0.112s 1.12e-05s C 10000 1 GpuElemwise{neg,no_inplace}", "- 0.01 * gw), (b, b - 0.01 * gb)],", "0.004s 1.78e-07s C 20001 3 aesara.compile.ops.Shape_i ... (remaining 0 Classes", "time (includes C, CUDA code generation/compiling): 8.239602e+00s Import time 4.228115e-03s", "14 Sum{acc_dtype=float64}(Elemwise{Composite{(((scalar_sigmoid(i0) * i1 * i2) / i3) - ((scalar_sigmoid((-i0))", "the GPU ops consumes more time than its CPU counterpart.", "scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[]<gpuarray>.0) 1.6% 98.3% 0.061s", "time 4.228115e-03s Time in all call to aesara.grad() 3.286195e-02s Time", "10 aesara.sandbox.gpuarray.elemwise.GpuElemwise 4.1% 93.4% 0.162s 8.10e-06s C 20001 3 aesara.sandbox.gpuarray.basic_ops.HostFromGpu", "2.17e-05s 10000 12 Elemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3", "0.01 * gb)], name=\"train\", ) predict = aesara.function(inputs=[], outputs=prediction, name=\"predict\")", "GpuAllocEmpty{dtype='float32', context_name=None}(Shape_i{0}.0) 0.3% 99.3% 0.013s 1.33e-06s 10000 0 InplaceGpuDimShuffle{x}(b) 0.3%", "GpuCAReduceCuda{add} 2.9% 91.7% 0.112s 1.12e-05s C 10000 1 GpuElemwise{neg,no_inplace} 2.6%", "10000 13 GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>(GpuElemwise{neg,no_inplace}.0) 2.3% 94.9% 0.090s 9.04e-06s 10000 19", "high=2).astype(aesara.config.floatX), ) training_steps = 10000 # Declare Aesara symbolic variables", "GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray> 1.6% 98.3% 0.061s 6.10e-06s C 10000 1 GpuFromHost<None>", "# 1. Raw results import numpy as np import aesara", "is because the ops operate on small inputs; if you", "10000 # Declare Aesara symbolic variables x = aesara.shared(D[0], name=\"x\")", "0.3% 98.4% 0.004s 3.70e-07s 10000 10 Elemwise{neg,no_inplace}(Elemwise{Composite{((-i0) - i1)}}[(0, 0)].0)", "time: 8.922548e-01s Number of Apply nodes: 17 Aesara Optimizer time:", "p_1) # Cross-entropy cost = tt.cast(xent.mean(), \"float32\") + 0.01 *", "# print \"Initial model:\" # print w.get_value(), b.get_value() # Construct", "in the script, followed by a summary for all functions.", "aesara.grad() 3.286195e-02s Time since aesara import 15.415s Class --- <%", "(b, b - 0.01 * gb)], name=\"train\", ) predict =", "12 Elemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 * i3 * scalar_softplus(i4)))}}[(0,", "C 20001 3 aesara.sandbox.gpuarray.blas.GpuGemv 29.8% 89.3% 1.166s 1.30e-05s C 90001", "for n in train.maker.fgraph.toposort() ] ): print(\"Used the gpu\") else:", "any( [ n.op.__class__.__name__ in [\"GpuGemm\", \"GpuGemv\"] for n in train.maker.fgraph.toposort()", "context_name=None}(Shape_i{0}.0) 0.3% 99.3% 0.013s 1.33e-06s 10000 0 InplaceGpuDimShuffle{x}(b) 0.3% 99.6%", "Number of Apply nodes: 17 Aesara Optimizer time: 6.270301e-01s Aesara", "scalar_softplus(i4)))}}[(0, 4)] 8.9% 92.1% 0.103s 1.03e-05s C 10000 1 Elemwise{Composite{(((scalar_sigmoid(i0)", "10000 6 InplaceDimShuffle{x}(Shape_i{0}.0) 0.1% 99.9% 0.002s 1.54e-07s 10000 16 Elemwise{Composite{(i0", "3 Shape_i{0} 0.2% 99.5% 0.003s 2.88e-07s C 10000 1 InplaceDimShuffle{1,0}", "92.6% 0.096s 9.63e-06s 10000 13 GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>(GpuElemwise{neg,no_inplace}.0) 2.3% 94.9% 0.090s", "i2))}}[(0, 0)] 0.0% 100.0% 0.000s 4.77e-06s C 1 1 Elemwise{Composite{GT(scalar_sigmoid((-((-i0)", "gw), (b, b - 0.01 * gb)], name=\"train\", ) predict", "4.77e-06s 1 4 Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}}(CGemv{inplace}.0, InplaceDimShuffle{x}.0, TensorConstant{(1,) of", "0.072s 7.16e-06s 10000 14 HostFromGpu(gpuarray)(GpuElemwise{Composite{((i0 * scalar_softplus(i1)) - (i2 *", "1 Elemwise{Cast{float32}} 0.1% 100.0% 0.002s 1.54e-07s C 10000 1 Elemwise{Composite{(i0", "= np.random N = 400 feats = 784 D =", "4000), you will see a gain from using the GPU.", "aesara.sandbox.gpuarray.basic_ops.GpuAllocEmpty 0.2% 100.0% 0.008s 3.95e-07s C 20001 3 aesara.compile.ops.Shape_i ...", "0.003s 2.88e-07s C 10000 1 InplaceDimShuffle{1,0} 0.2% 99.7% 0.003s 2.65e-07s", "10000 4 GpuElemwise{sub,no_inplace}(GpuArrayConstant{[ 1.]}, y) 3.6% 74.6% 0.141s 1.41e-05s 10000", "- ((scalar_sigmoid((-i0)) * i1 * i4) / i3))}}[(0, 0)] 4.3%", "0.1% 100.0% 0.002s 1.54e-07s C 10000 1 Elemwise{Composite{(i0 - (i1", "1 InplaceGpuDimShuffle{1,0} 0.2% 100.0% 0.008s 3.95e-07s C 20001 3 Shape_i{0}", "C 30001 4 aesara.sandbox.gpuarray.elemwise.GpuDimShuffle 0.7% 99.8% 0.026s 2.59e-06s C 10001", "aesara.grad() 1.848292e-02s Time since aesara import 2.864s Class --- <%", "0.004s 3.64e-07s C 10001 2 aesara.tensor.basic.AllocEmpty 0.3% 100.0% 0.004s 1.78e-07s", "0.3% 99.3% 0.013s 1.33e-06s 10000 0 InplaceGpuDimShuffle{x}(b) 0.3% 99.6% 0.011s", "time> <time per call> <type> <#call> <#apply> <Op name> 59.5%", "- i1)}}[(0, 0)]<gpuarray>.0, GpuArrayConstant{[-1.]}, y, GpuElemwise{Cast{float32}}[]<gpuarray>.0, GpuElemwise{ScalarSigmoid}[(0, 0)]<gpuarray>.0, GpuElemwise{sub,no_inplace}.0) 3.7%", "Time in Function.fn.__call__: 4.081113e+00s (97.605%) Time in thunks: 3.915566e+00s (93.646%)", "to aesara.grad() 3.286195e-02s Time since aesara import 15.415s Class ---", "Aesara Optimizer time: 9.996419e-01s Aesara validate time: 6.523132e-03s Aesara Linker", "i1)}}(Elemwise{neg,no_inplace}.0, TensorConstant{(1,) of 0.5}) 1.0% 97.4% 0.011s 1.14e-06s 10000 14" ]
[ "shape is :math:`(R, 4)`. :math:`R` is the number of bounding", "+= (y_offset, x_offset) out_bbox[:, 2:] += (y_offset, x_offset) return out_bbox", "axis. Returns: ~numpy.ndarray: Bounding boxes translated according to the given", "point of the image from coordinate :math:`(0, 0)` to coordinate", "number of bounding boxes in the image. The second axis", "tensor of shape :math:`(R, 4)`, where :math:`R` is the number", "four attributes are coordinates of the top left and the", ":math:`R` is the number of bounding boxes in the image.", "along x axis. Returns: ~numpy.ndarray: Bounding boxes translated according to", "= bbox.copy() out_bbox[:, :2] += (y_offset, x_offset) out_bbox[:, 2:] +=", "(~numpy.ndarray): Bounding boxes to be transformed. The shape is :math:`(R,", "float): The offset along x axis. Returns: ~numpy.ndarray: Bounding boxes", "translate_bbox(bbox, y_offset=0, x_offset=0): \"\"\"Translate bounding boxes. This method is mainly", "translates the left top point of the image from coordinate", "the bounding box. They are :math:`(y_{min}, x_{min}, y_{max}, x_{max})`, where", "x_{min}, y_{max}, x_{max})`, where the four attributes are coordinates of", "is the number of bounding boxes. y_offset (int or float):", "are coordinates of the top left and the bottom right", "bounding boxes. This method is mainly used together with image", "top left and the bottom right vertices. Args: bbox (~numpy.ndarray):", "the bottom right vertices. Args: bbox (~numpy.ndarray): Bounding boxes to", "is :math:`(R, 4)`. :math:`R` is the number of bounding boxes.", "left top point of the image from coordinate :math:`(0, 0)`", "from coordinate :math:`(0, 0)` to coordinate :math:`(y, x) = (y_{offset},", "of shape :math:`(R, 4)`, where :math:`R` is the number of", "padding and cropping, which translates the left top point of", ":2] += (y_offset, x_offset) out_bbox[:, 2:] += (y_offset, x_offset) return", "boxes are expected to be packed into a two dimensional", "image transforms, such as padding and cropping, which translates the", "(int or float): The offset along y axis. x_offset (int", ":math:`(R, 4)`, where :math:`R` is the number of bounding boxes", "the top left and the bottom right vertices. Args: bbox", "~numpy.ndarray: Bounding boxes translated according to the given offsets. \"\"\"", "y_offset=0, x_offset=0): \"\"\"Translate bounding boxes. This method is mainly used", "vertices. Args: bbox (~numpy.ndarray): Bounding boxes to be transformed. The", "a two dimensional tensor of shape :math:`(R, 4)`, where :math:`R`", "bbox.copy() out_bbox[:, :2] += (y_offset, x_offset) out_bbox[:, 2:] += (y_offset,", ":math:`(0, 0)` to coordinate :math:`(y, x) = (y_{offset}, x_{offset})`. The", "such as padding and cropping, which translates the left top", "= (y_{offset}, x_{offset})`. The bounding boxes are expected to be", "are expected to be packed into a two dimensional tensor", "The shape is :math:`(R, 4)`. :math:`R` is the number of", "x) = (y_{offset}, x_{offset})`. The bounding boxes are expected to", ":math:`R` is the number of bounding boxes. y_offset (int or", "be packed into a two dimensional tensor of shape :math:`(R,", "bounding boxes in the image. The second axis represents attributes", "The bounding boxes are expected to be packed into a", "or float): The offset along x axis. Returns: ~numpy.ndarray: Bounding", "to the given offsets. \"\"\" out_bbox = bbox.copy() out_bbox[:, :2]", "mainly used together with image transforms, such as padding and", "bottom right vertices. Args: bbox (~numpy.ndarray): Bounding boxes to be", "bbox (~numpy.ndarray): Bounding boxes to be transformed. The shape is", "which translates the left top point of the image from", "Bounding boxes translated according to the given offsets. \"\"\" out_bbox", "boxes. y_offset (int or float): The offset along y axis.", "expected to be packed into a two dimensional tensor of", "bounding boxes. y_offset (int or float): The offset along y", "and the bottom right vertices. Args: bbox (~numpy.ndarray): Bounding boxes", "\"\"\"Translate bounding boxes. This method is mainly used together with", "into a two dimensional tensor of shape :math:`(R, 4)`, where", "according to the given offsets. \"\"\" out_bbox = bbox.copy() out_bbox[:,", "the four attributes are coordinates of the top left and", "Bounding boxes to be transformed. The shape is :math:`(R, 4)`.", "4)`, where :math:`R` is the number of bounding boxes in", "boxes in the image. The second axis represents attributes of", "attributes are coordinates of the top left and the bottom", "x_{offset})`. The bounding boxes are expected to be packed into", "the image. The second axis represents attributes of the bounding", "They are :math:`(y_{min}, x_{min}, y_{max}, x_{max})`, where the four attributes", "represents attributes of the bounding box. They are :math:`(y_{min}, x_{min},", "right vertices. Args: bbox (~numpy.ndarray): Bounding boxes to be transformed.", "of bounding boxes. y_offset (int or float): The offset along", "used together with image transforms, such as padding and cropping,", "as padding and cropping, which translates the left top point", "in the image. The second axis represents attributes of the", "of bounding boxes in the image. The second axis represents", "and cropping, which translates the left top point of the", "coordinate :math:`(0, 0)` to coordinate :math:`(y, x) = (y_{offset}, x_{offset})`.", "transformed. The shape is :math:`(R, 4)`. :math:`R` is the number", "bounding boxes are expected to be packed into a two", "method is mainly used together with image transforms, such as", "y axis. x_offset (int or float): The offset along x", "or float): The offset along y axis. x_offset (int or", "y_offset (int or float): The offset along y axis. x_offset", "0)` to coordinate :math:`(y, x) = (y_{offset}, x_{offset})`. The bounding", "This method is mainly used together with image transforms, such", "transforms, such as padding and cropping, which translates the left", "The offset along x axis. Returns: ~numpy.ndarray: Bounding boxes translated", "number of bounding boxes. y_offset (int or float): The offset", "offset along x axis. Returns: ~numpy.ndarray: Bounding boxes translated according", "(y_{offset}, x_{offset})`. The bounding boxes are expected to be packed", "where :math:`R` is the number of bounding boxes in the", "Args: bbox (~numpy.ndarray): Bounding boxes to be transformed. The shape", "x_offset=0): \"\"\"Translate bounding boxes. This method is mainly used together", "x_{max})`, where the four attributes are coordinates of the top", "boxes. This method is mainly used together with image transforms,", "the image from coordinate :math:`(0, 0)` to coordinate :math:`(y, x)", "\"\"\" out_bbox = bbox.copy() out_bbox[:, :2] += (y_offset, x_offset) out_bbox[:,", "out_bbox = bbox.copy() out_bbox[:, :2] += (y_offset, x_offset) out_bbox[:, 2:]", "offset along y axis. x_offset (int or float): The offset", "the left top point of the image from coordinate :math:`(0,", "x_offset (int or float): The offset along x axis. Returns:", "box. They are :math:`(y_{min}, x_{min}, y_{max}, x_{max})`, where the four", "of the image from coordinate :math:`(0, 0)` to coordinate :math:`(y,", "The second axis represents attributes of the bounding box. They", "of the top left and the bottom right vertices. Args:", "bounding box. They are :math:`(y_{min}, x_{min}, y_{max}, x_{max})`, where the", "4)`. :math:`R` is the number of bounding boxes. y_offset (int", "x axis. Returns: ~numpy.ndarray: Bounding boxes translated according to the", "the given offsets. \"\"\" out_bbox = bbox.copy() out_bbox[:, :2] +=", "with image transforms, such as padding and cropping, which translates", "cropping, which translates the left top point of the image", ":math:`(R, 4)`. :math:`R` is the number of bounding boxes. y_offset", "along y axis. x_offset (int or float): The offset along", "boxes translated according to the given offsets. \"\"\" out_bbox =", "together with image transforms, such as padding and cropping, which", "coordinate :math:`(y, x) = (y_{offset}, x_{offset})`. The bounding boxes are", "two dimensional tensor of shape :math:`(R, 4)`, where :math:`R` is", "the number of bounding boxes in the image. The second", "float): The offset along y axis. x_offset (int or float):", "are :math:`(y_{min}, x_{min}, y_{max}, x_{max})`, where the four attributes are", ":math:`(y, x) = (y_{offset}, x_{offset})`. The bounding boxes are expected", "to coordinate :math:`(y, x) = (y_{offset}, x_{offset})`. The bounding boxes", "where the four attributes are coordinates of the top left", "(int or float): The offset along x axis. Returns: ~numpy.ndarray:", "image from coordinate :math:`(0, 0)` to coordinate :math:`(y, x) =", ":math:`(y_{min}, x_{min}, y_{max}, x_{max})`, where the four attributes are coordinates", "boxes to be transformed. The shape is :math:`(R, 4)`. :math:`R`", "be transformed. The shape is :math:`(R, 4)`. :math:`R` is the", "shape :math:`(R, 4)`, where :math:`R` is the number of bounding", "packed into a two dimensional tensor of shape :math:`(R, 4)`,", "y_{max}, x_{max})`, where the four attributes are coordinates of the", "translated according to the given offsets. \"\"\" out_bbox = bbox.copy()", "def translate_bbox(bbox, y_offset=0, x_offset=0): \"\"\"Translate bounding boxes. This method is", "second axis represents attributes of the bounding box. They are", "is the number of bounding boxes in the image. The", "coordinates of the top left and the bottom right vertices.", "attributes of the bounding box. They are :math:`(y_{min}, x_{min}, y_{max},", "top point of the image from coordinate :math:`(0, 0)` to", "out_bbox[:, :2] += (y_offset, x_offset) out_bbox[:, 2:] += (y_offset, x_offset)", "is mainly used together with image transforms, such as padding", "to be transformed. The shape is :math:`(R, 4)`. :math:`R` is", "offsets. \"\"\" out_bbox = bbox.copy() out_bbox[:, :2] += (y_offset, x_offset)", "The offset along y axis. x_offset (int or float): The", "axis. x_offset (int or float): The offset along x axis.", "the number of bounding boxes. y_offset (int or float): The", "dimensional tensor of shape :math:`(R, 4)`, where :math:`R` is the", "image. The second axis represents attributes of the bounding box.", "to be packed into a two dimensional tensor of shape", "of the bounding box. They are :math:`(y_{min}, x_{min}, y_{max}, x_{max})`,", "Returns: ~numpy.ndarray: Bounding boxes translated according to the given offsets.", "left and the bottom right vertices. Args: bbox (~numpy.ndarray): Bounding", "axis represents attributes of the bounding box. They are :math:`(y_{min},", "given offsets. \"\"\" out_bbox = bbox.copy() out_bbox[:, :2] += (y_offset," ]
[ "import ConfigParser from helper.helper_web import get_browser def before_all(context): config =", "type from the configuration file helper_func = get_browser(config.get('Environment', 'Browser')) context.helperfunc", "'setup.cfg'))) my_file = (os.path.join(os.getcwd(), 'setup.cfg')) config.read(my_file) # Reading the browser", "from the configuration file helper_func = get_browser(config.get('Environment', 'Browser')) context.helperfunc =", "configparser import ConfigParser from helper.helper_web import get_browser def before_all(context): config", "<gh_stars>1-10 import os from configparser import ConfigParser from helper.helper_web import", "get_browser def before_all(context): config = ConfigParser() print((os.path.join(os.getcwd(), 'setup.cfg'))) my_file =", "(os.path.join(os.getcwd(), 'setup.cfg')) config.read(my_file) # Reading the browser type from the", "= ConfigParser() print((os.path.join(os.getcwd(), 'setup.cfg'))) my_file = (os.path.join(os.getcwd(), 'setup.cfg')) config.read(my_file) #", "os from configparser import ConfigParser from helper.helper_web import get_browser def", "config = ConfigParser() print((os.path.join(os.getcwd(), 'setup.cfg'))) my_file = (os.path.join(os.getcwd(), 'setup.cfg')) config.read(my_file)", "Reading the browser type from the configuration file helper_func =", "def before_all(context): config = ConfigParser() print((os.path.join(os.getcwd(), 'setup.cfg'))) my_file = (os.path.join(os.getcwd(),", "ConfigParser() print((os.path.join(os.getcwd(), 'setup.cfg'))) my_file = (os.path.join(os.getcwd(), 'setup.cfg')) config.read(my_file) # Reading", "before_all(context): config = ConfigParser() print((os.path.join(os.getcwd(), 'setup.cfg'))) my_file = (os.path.join(os.getcwd(), 'setup.cfg'))", "browser type from the configuration file helper_func = get_browser(config.get('Environment', 'Browser'))", "the configuration file helper_func = get_browser(config.get('Environment', 'Browser')) context.helperfunc = helper_func", "'setup.cfg')) config.read(my_file) # Reading the browser type from the configuration", "print((os.path.join(os.getcwd(), 'setup.cfg'))) my_file = (os.path.join(os.getcwd(), 'setup.cfg')) config.read(my_file) # Reading the", "import os from configparser import ConfigParser from helper.helper_web import get_browser", "the browser type from the configuration file helper_func = get_browser(config.get('Environment',", "config.read(my_file) # Reading the browser type from the configuration file", "# Reading the browser type from the configuration file helper_func", "import get_browser def before_all(context): config = ConfigParser() print((os.path.join(os.getcwd(), 'setup.cfg'))) my_file", "file helper_func = get_browser(config.get('Environment', 'Browser')) context.helperfunc = helper_func def after_all(context):", "helper.helper_web import get_browser def before_all(context): config = ConfigParser() print((os.path.join(os.getcwd(), 'setup.cfg')))", "from helper.helper_web import get_browser def before_all(context): config = ConfigParser() print((os.path.join(os.getcwd(),", "configuration file helper_func = get_browser(config.get('Environment', 'Browser')) context.helperfunc = helper_func def", "my_file = (os.path.join(os.getcwd(), 'setup.cfg')) config.read(my_file) # Reading the browser type", "ConfigParser from helper.helper_web import get_browser def before_all(context): config = ConfigParser()", "helper_func = get_browser(config.get('Environment', 'Browser')) context.helperfunc = helper_func def after_all(context): context.helperfunc.close()", "= (os.path.join(os.getcwd(), 'setup.cfg')) config.read(my_file) # Reading the browser type from", "from configparser import ConfigParser from helper.helper_web import get_browser def before_all(context):" ]
[ "def __get_row_index(self) -> int: current_index = self._row_index self._row_index += 1", "<filename>recipe_organizer/gui/recipe_list/recipe_source.py from pathlib import Path from tkinter import Frame, Label", "= file.read() try: recipe = Recipe.from_json(json_data) except KeyError: pass else:", "if event.event_type == EventType.SOURCE_SET: self._label_source_directory.configure(text=event.payload.name) self.__load_recipes(event.payload) def __get_row_index(self) -> int:", "Path from tkinter import Frame, Label from recipe_organizer.events.event import Event,", "from recipe_organizer.events.event_observer import EventObserver from recipe_organizer.events.event_publisher import EventPublisher from recipe_organizer.gui.interfaces.widget_container", "define_layout(self) -> None: self._label_source_directory.grid(row=self.__get_row_index()) def notify(self, event: Event) -> None:", "import Path from tkinter import Frame, Label from recipe_organizer.events.event import", "parent) self.define_widgets() self.define_layout() EventPublisher.add(self) def define_widgets(self) -> None: self._label_source_directory =", "__create_list(self, recipes: [Recipe]): current_row_index = self.__get_row_index() for index, recipe in", "-> int: current_index = self._row_index self._row_index += 1 return current_index", "1 return current_index def __load_recipes(self, directory: Path): recipes: [Recipe] =", "recipe = Recipe.from_json(json_data) except KeyError: pass else: recipes.append(recipe) self.__create_list(recipes) def", "directory: Path): recipes: [Recipe] = [] file_paths = directory.glob(\"**/*.json\") for", "[] _row_index = 0 def __init__(self, parent): Frame.__init__(self, parent) self.define_widgets()", "from recipe_organizer.gui.recipe_summary.recipe_summary import RecipeSummary from recipe_organizer.recipe.recipe import Recipe class RecipeSource(Frame,", "[Recipe] = [] file_paths = directory.glob(\"**/*.json\") for file_path in file_paths:", "None: self._label_source_directory.grid(row=self.__get_row_index()) def notify(self, event: Event) -> None: if event.event_type", "def __load_recipes(self, directory: Path): recipes: [Recipe] = [] file_paths =", "def notify(self, event: Event) -> None: if event.event_type == EventType.SOURCE_SET:", "pass else: recipes.append(recipe) self.__create_list(recipes) def __create_list(self, recipes: [Recipe]): current_row_index =", "= self.__get_row_index() recipe_summary = RecipeSummary(self, recipe) recipe_summary.grid(row=current_row_index, column=index % self._MAX_COLUMN_COUNT,", "_row_index = 0 def __init__(self, parent): Frame.__init__(self, parent) self.define_widgets() self.define_layout()", "= 0 def __init__(self, parent): Frame.__init__(self, parent) self.define_widgets() self.define_layout() EventPublisher.add(self)", "import WidgetContainer from recipe_organizer.gui.recipe_summary.recipe_summary import RecipeSummary from recipe_organizer.recipe.recipe import Recipe", "recipes: [Recipe] = [] file_paths = directory.glob(\"**/*.json\") for file_path in", "recipes: [Recipe]): current_row_index = self.__get_row_index() for index, recipe in enumerate(recipes):", "= Recipe.from_json(json_data) except KeyError: pass else: recipes.append(recipe) self.__create_list(recipes) def __create_list(self,", "-> None: self._label_source_directory.grid(row=self.__get_row_index()) def notify(self, event: Event) -> None: if", "encoding=\"utf-8\") as file: json_data = file.read() try: recipe = Recipe.from_json(json_data)", "__load_recipes(self, directory: Path): recipes: [Recipe] = [] file_paths = directory.glob(\"**/*.json\")", "== EventType.SOURCE_SET: self._label_source_directory.configure(text=event.payload.name) self.__load_recipes(event.payload) def __get_row_index(self) -> int: current_index =", "import EventPublisher from recipe_organizer.gui.interfaces.widget_container import WidgetContainer from recipe_organizer.gui.recipe_summary.recipe_summary import RecipeSummary", "Event) -> None: if event.event_type == EventType.SOURCE_SET: self._label_source_directory.configure(text=event.payload.name) self.__load_recipes(event.payload) def", "event: Event) -> None: if event.event_type == EventType.SOURCE_SET: self._label_source_directory.configure(text=event.payload.name) self.__load_recipes(event.payload)", "RecipeSource(Frame, WidgetContainer, EventObserver): _MAX_COLUMN_COUNT = 6 _label_source_directory: Label _recipe_summaries: [RecipeSummary]", "import Recipe class RecipeSource(Frame, WidgetContainer, EventObserver): _MAX_COLUMN_COUNT = 6 _label_source_directory:", "index, recipe in enumerate(recipes): if index % self._MAX_COLUMN_COUNT == 0:", "self._MAX_COLUMN_COUNT == 0: current_row_index = self.__get_row_index() recipe_summary = RecipeSummary(self, recipe)", "WidgetContainer, EventObserver): _MAX_COLUMN_COUNT = 6 _label_source_directory: Label _recipe_summaries: [RecipeSummary] =", "None: if event.event_type == EventType.SOURCE_SET: self._label_source_directory.configure(text=event.payload.name) self.__load_recipes(event.payload) def __get_row_index(self) ->", "self._label_source_directory.configure(text=event.payload.name) self.__load_recipes(event.payload) def __get_row_index(self) -> int: current_index = self._row_index self._row_index", "in enumerate(recipes): if index % self._MAX_COLUMN_COUNT == 0: current_row_index =", "__init__(self, parent): Frame.__init__(self, parent) self.define_widgets() self.define_layout() EventPublisher.add(self) def define_widgets(self) ->", "Frame.__init__(self, parent) self.define_widgets() self.define_layout() EventPublisher.add(self) def define_widgets(self) -> None: self._label_source_directory", "EventType.SOURCE_SET: self._label_source_directory.configure(text=event.payload.name) self.__load_recipes(event.payload) def __get_row_index(self) -> int: current_index = self._row_index", "else: recipes.append(recipe) self.__create_list(recipes) def __create_list(self, recipes: [Recipe]): current_row_index = self.__get_row_index()", "== 0: current_row_index = self.__get_row_index() recipe_summary = RecipeSummary(self, recipe) recipe_summary.grid(row=current_row_index,", "except KeyError: pass else: recipes.append(recipe) self.__create_list(recipes) def __create_list(self, recipes: [Recipe]):", "pathlib import Path from tkinter import Frame, Label from recipe_organizer.events.event", "[RecipeSummary] = [] _row_index = 0 def __init__(self, parent): Frame.__init__(self,", "recipe_summary = RecipeSummary(self, recipe) recipe_summary.grid(row=current_row_index, column=index % self._MAX_COLUMN_COUNT, padx=16, pady=10)", "[Recipe]): current_row_index = self.__get_row_index() for index, recipe in enumerate(recipes): if", "import EventObserver from recipe_organizer.events.event_publisher import EventPublisher from recipe_organizer.gui.interfaces.widget_container import WidgetContainer", "if index % self._MAX_COLUMN_COUNT == 0: current_row_index = self.__get_row_index() recipe_summary", "= [] file_paths = directory.glob(\"**/*.json\") for file_path in file_paths: with", "self._row_index += 1 return current_index def __load_recipes(self, directory: Path): recipes:", "define_widgets(self) -> None: self._label_source_directory = Label(self, text=\"-\") def define_layout(self) ->", "from recipe_organizer.gui.interfaces.widget_container import WidgetContainer from recipe_organizer.gui.recipe_summary.recipe_summary import RecipeSummary from recipe_organizer.recipe.recipe", "current_row_index = self.__get_row_index() for index, recipe in enumerate(recipes): if index", "self.__load_recipes(event.payload) def __get_row_index(self) -> int: current_index = self._row_index self._row_index +=", "__get_row_index(self) -> int: current_index = self._row_index self._row_index += 1 return", "EventType from recipe_organizer.events.event_observer import EventObserver from recipe_organizer.events.event_publisher import EventPublisher from", "recipe_organizer.gui.interfaces.widget_container import WidgetContainer from recipe_organizer.gui.recipe_summary.recipe_summary import RecipeSummary from recipe_organizer.recipe.recipe import", "index % self._MAX_COLUMN_COUNT == 0: current_row_index = self.__get_row_index() recipe_summary =", "recipe) recipe_summary.grid(row=current_row_index, column=index % self._MAX_COLUMN_COUNT, padx=16, pady=10) self.columnconfigure(index, minsize=200) self._recipe_summaries.append(recipe_summary)", "current_index = self._row_index self._row_index += 1 return current_index def __load_recipes(self,", "def __create_list(self, recipes: [Recipe]): current_row_index = self.__get_row_index() for index, recipe", "return current_index def __load_recipes(self, directory: Path): recipes: [Recipe] = []", "current_index def __load_recipes(self, directory: Path): recipes: [Recipe] = [] file_paths", "-> None: if event.event_type == EventType.SOURCE_SET: self._label_source_directory.configure(text=event.payload.name) self.__load_recipes(event.payload) def __get_row_index(self)", "in file_paths: with open(file_path, \"r\", encoding=\"utf-8\") as file: json_data =", "file_paths: with open(file_path, \"r\", encoding=\"utf-8\") as file: json_data = file.read()", "directory.glob(\"**/*.json\") for file_path in file_paths: with open(file_path, \"r\", encoding=\"utf-8\") as", "self._label_source_directory = Label(self, text=\"-\") def define_layout(self) -> None: self._label_source_directory.grid(row=self.__get_row_index()) def", "import Event, EventType from recipe_organizer.events.event_observer import EventObserver from recipe_organizer.events.event_publisher import", "def define_layout(self) -> None: self._label_source_directory.grid(row=self.__get_row_index()) def notify(self, event: Event) ->", "-> None: self._label_source_directory = Label(self, text=\"-\") def define_layout(self) -> None:", "file_paths = directory.glob(\"**/*.json\") for file_path in file_paths: with open(file_path, \"r\",", "open(file_path, \"r\", encoding=\"utf-8\") as file: json_data = file.read() try: recipe", "event.event_type == EventType.SOURCE_SET: self._label_source_directory.configure(text=event.payload.name) self.__load_recipes(event.payload) def __get_row_index(self) -> int: current_index", "= directory.glob(\"**/*.json\") for file_path in file_paths: with open(file_path, \"r\", encoding=\"utf-8\")", "import Frame, Label from recipe_organizer.events.event import Event, EventType from recipe_organizer.events.event_observer", "self.define_layout() EventPublisher.add(self) def define_widgets(self) -> None: self._label_source_directory = Label(self, text=\"-\")", "file.read() try: recipe = Recipe.from_json(json_data) except KeyError: pass else: recipes.append(recipe)", "tkinter import Frame, Label from recipe_organizer.events.event import Event, EventType from", "try: recipe = Recipe.from_json(json_data) except KeyError: pass else: recipes.append(recipe) self.__create_list(recipes)", "Label _recipe_summaries: [RecipeSummary] = [] _row_index = 0 def __init__(self,", "= [] _row_index = 0 def __init__(self, parent): Frame.__init__(self, parent)", "= 6 _label_source_directory: Label _recipe_summaries: [RecipeSummary] = [] _row_index =", "json_data = file.read() try: recipe = Recipe.from_json(json_data) except KeyError: pass", "for index, recipe in enumerate(recipes): if index % self._MAX_COLUMN_COUNT ==", "WidgetContainer from recipe_organizer.gui.recipe_summary.recipe_summary import RecipeSummary from recipe_organizer.recipe.recipe import Recipe class", "6 _label_source_directory: Label _recipe_summaries: [RecipeSummary] = [] _row_index = 0", "= self._row_index self._row_index += 1 return current_index def __load_recipes(self, directory:", "% self._MAX_COLUMN_COUNT == 0: current_row_index = self.__get_row_index() recipe_summary = RecipeSummary(self,", "self.define_widgets() self.define_layout() EventPublisher.add(self) def define_widgets(self) -> None: self._label_source_directory = Label(self,", "class RecipeSource(Frame, WidgetContainer, EventObserver): _MAX_COLUMN_COUNT = 6 _label_source_directory: Label _recipe_summaries:", "_label_source_directory: Label _recipe_summaries: [RecipeSummary] = [] _row_index = 0 def", "self._row_index self._row_index += 1 return current_index def __load_recipes(self, directory: Path):", "import RecipeSummary from recipe_organizer.recipe.recipe import Recipe class RecipeSource(Frame, WidgetContainer, EventObserver):", "= RecipeSummary(self, recipe) recipe_summary.grid(row=current_row_index, column=index % self._MAX_COLUMN_COUNT, padx=16, pady=10) self.columnconfigure(index,", "_recipe_summaries: [RecipeSummary] = [] _row_index = 0 def __init__(self, parent):", "from pathlib import Path from tkinter import Frame, Label from", "None: self._label_source_directory = Label(self, text=\"-\") def define_layout(self) -> None: self._label_source_directory.grid(row=self.__get_row_index())", "Label from recipe_organizer.events.event import Event, EventType from recipe_organizer.events.event_observer import EventObserver", "0 def __init__(self, parent): Frame.__init__(self, parent) self.define_widgets() self.define_layout() EventPublisher.add(self) def", "as file: json_data = file.read() try: recipe = Recipe.from_json(json_data) except", "from recipe_organizer.events.event import Event, EventType from recipe_organizer.events.event_observer import EventObserver from", "notify(self, event: Event) -> None: if event.event_type == EventType.SOURCE_SET: self._label_source_directory.configure(text=event.payload.name)", "Recipe.from_json(json_data) except KeyError: pass else: recipes.append(recipe) self.__create_list(recipes) def __create_list(self, recipes:", "recipes.append(recipe) self.__create_list(recipes) def __create_list(self, recipes: [Recipe]): current_row_index = self.__get_row_index() for", "file_path in file_paths: with open(file_path, \"r\", encoding=\"utf-8\") as file: json_data", "self._label_source_directory.grid(row=self.__get_row_index()) def notify(self, event: Event) -> None: if event.event_type ==", "EventObserver): _MAX_COLUMN_COUNT = 6 _label_source_directory: Label _recipe_summaries: [RecipeSummary] = []", "= self.__get_row_index() for index, recipe in enumerate(recipes): if index %", "Recipe class RecipeSource(Frame, WidgetContainer, EventObserver): _MAX_COLUMN_COUNT = 6 _label_source_directory: Label", "RecipeSummary(self, recipe) recipe_summary.grid(row=current_row_index, column=index % self._MAX_COLUMN_COUNT, padx=16, pady=10) self.columnconfigure(index, minsize=200)", "with open(file_path, \"r\", encoding=\"utf-8\") as file: json_data = file.read() try:", "recipe_organizer.recipe.recipe import Recipe class RecipeSource(Frame, WidgetContainer, EventObserver): _MAX_COLUMN_COUNT = 6", "recipe_organizer.events.event_publisher import EventPublisher from recipe_organizer.gui.interfaces.widget_container import WidgetContainer from recipe_organizer.gui.recipe_summary.recipe_summary import", "self.__get_row_index() for index, recipe in enumerate(recipes): if index % self._MAX_COLUMN_COUNT", "def define_widgets(self) -> None: self._label_source_directory = Label(self, text=\"-\") def define_layout(self)", "self.__get_row_index() recipe_summary = RecipeSummary(self, recipe) recipe_summary.grid(row=current_row_index, column=index % self._MAX_COLUMN_COUNT, padx=16,", "current_row_index = self.__get_row_index() recipe_summary = RecipeSummary(self, recipe) recipe_summary.grid(row=current_row_index, column=index %", "from recipe_organizer.events.event_publisher import EventPublisher from recipe_organizer.gui.interfaces.widget_container import WidgetContainer from recipe_organizer.gui.recipe_summary.recipe_summary", "recipe_organizer.gui.recipe_summary.recipe_summary import RecipeSummary from recipe_organizer.recipe.recipe import Recipe class RecipeSource(Frame, WidgetContainer,", "recipe_organizer.events.event import Event, EventType from recipe_organizer.events.event_observer import EventObserver from recipe_organizer.events.event_publisher", "recipe in enumerate(recipes): if index % self._MAX_COLUMN_COUNT == 0: current_row_index", "0: current_row_index = self.__get_row_index() recipe_summary = RecipeSummary(self, recipe) recipe_summary.grid(row=current_row_index, column=index", "parent): Frame.__init__(self, parent) self.define_widgets() self.define_layout() EventPublisher.add(self) def define_widgets(self) -> None:", "EventObserver from recipe_organizer.events.event_publisher import EventPublisher from recipe_organizer.gui.interfaces.widget_container import WidgetContainer from", "def __init__(self, parent): Frame.__init__(self, parent) self.define_widgets() self.define_layout() EventPublisher.add(self) def define_widgets(self)", "Path): recipes: [Recipe] = [] file_paths = directory.glob(\"**/*.json\") for file_path", "Event, EventType from recipe_organizer.events.event_observer import EventObserver from recipe_organizer.events.event_publisher import EventPublisher", "\"r\", encoding=\"utf-8\") as file: json_data = file.read() try: recipe =", "+= 1 return current_index def __load_recipes(self, directory: Path): recipes: [Recipe]", "= Label(self, text=\"-\") def define_layout(self) -> None: self._label_source_directory.grid(row=self.__get_row_index()) def notify(self,", "self.__create_list(recipes) def __create_list(self, recipes: [Recipe]): current_row_index = self.__get_row_index() for index,", "recipe_organizer.events.event_observer import EventObserver from recipe_organizer.events.event_publisher import EventPublisher from recipe_organizer.gui.interfaces.widget_container import", "_MAX_COLUMN_COUNT = 6 _label_source_directory: Label _recipe_summaries: [RecipeSummary] = [] _row_index", "EventPublisher from recipe_organizer.gui.interfaces.widget_container import WidgetContainer from recipe_organizer.gui.recipe_summary.recipe_summary import RecipeSummary from", "from recipe_organizer.recipe.recipe import Recipe class RecipeSource(Frame, WidgetContainer, EventObserver): _MAX_COLUMN_COUNT =", "EventPublisher.add(self) def define_widgets(self) -> None: self._label_source_directory = Label(self, text=\"-\") def", "Label(self, text=\"-\") def define_layout(self) -> None: self._label_source_directory.grid(row=self.__get_row_index()) def notify(self, event:", "KeyError: pass else: recipes.append(recipe) self.__create_list(recipes) def __create_list(self, recipes: [Recipe]): current_row_index", "from tkinter import Frame, Label from recipe_organizer.events.event import Event, EventType", "RecipeSummary from recipe_organizer.recipe.recipe import Recipe class RecipeSource(Frame, WidgetContainer, EventObserver): _MAX_COLUMN_COUNT", "[] file_paths = directory.glob(\"**/*.json\") for file_path in file_paths: with open(file_path,", "enumerate(recipes): if index % self._MAX_COLUMN_COUNT == 0: current_row_index = self.__get_row_index()", "text=\"-\") def define_layout(self) -> None: self._label_source_directory.grid(row=self.__get_row_index()) def notify(self, event: Event)", "Frame, Label from recipe_organizer.events.event import Event, EventType from recipe_organizer.events.event_observer import", "int: current_index = self._row_index self._row_index += 1 return current_index def", "for file_path in file_paths: with open(file_path, \"r\", encoding=\"utf-8\") as file:", "file: json_data = file.read() try: recipe = Recipe.from_json(json_data) except KeyError:" ]
[ "manipulation and model checking.\"\"\" homepage = \"https://spot.lrde.epita.fr/\" url = \"http://www.lrde.epita.fr/dload/spot/spot-1.99.3.tar.gz\"", "# SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class", "C++11 library for omega-automata manipulation and model checking.\"\"\" homepage =", "default=True, description='Enable python API') depends_on(\"python@3.3:\", when='@1.99.5: +python') depends_on(\"python@3.2:\", when='@1.99: +python')", "\"\"\"Spot is a C++11 library for omega-automata manipulation and model", "for omega-automata manipulation and model checking.\"\"\" homepage = \"https://spot.lrde.epita.fr/\" url", "for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack", "Spack Project Developers. See the top-level COPYRIGHT file for details.", "= \"https://spot.lrde.epita.fr/\" url = \"http://www.lrde.epita.fr/dload/spot/spot-1.99.3.tar.gz\" version('1.99.3', sha256='86964af559994af4451a8dca663a9e1db6e869ed60e747ab60ce72dddc31b61b') version('1.2.6', sha256='360678c75f6741f697e8e56cdbc9937f104eb723a839c3629f0dc5dc6de11bfc') variant('python',", "python API') depends_on(\"python@3.3:\", when='@1.99.5: +python') depends_on(\"python@3.2:\", when='@1.99: +python') depends_on(\"python@2:\", when='+python')", "National Security, LLC and other # Spack Project Developers. See", "variant('python', default=True, description='Enable python API') depends_on(\"python@3.3:\", when='@1.99.5: +python') depends_on(\"python@3.2:\", when='@1.99:", "spack import * class Spot(AutotoolsPackage): \"\"\"Spot is a C++11 library", "LLC and other # Spack Project Developers. See the top-level", "sha256='86964af559994af4451a8dca663a9e1db6e869ed60e747ab60ce72dddc31b61b') version('1.2.6', sha256='360678c75f6741f697e8e56cdbc9937f104eb723a839c3629f0dc5dc6de11bfc') variant('python', default=True, description='Enable python API') depends_on(\"python@3.3:\", when='@1.99.5:", "version('1.2.6', sha256='360678c75f6741f697e8e56cdbc9937f104eb723a839c3629f0dc5dc6de11bfc') variant('python', default=True, description='Enable python API') depends_on(\"python@3.3:\", when='@1.99.5: +python')", "Security, LLC and other # Spack Project Developers. See the", "details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import", "a C++11 library for omega-automata manipulation and model checking.\"\"\" homepage", "class Spot(AutotoolsPackage): \"\"\"Spot is a C++11 library for omega-automata manipulation", "version('1.99.3', sha256='86964af559994af4451a8dca663a9e1db6e869ed60e747ab60ce72dddc31b61b') version('1.2.6', sha256='360678c75f6741f697e8e56cdbc9937f104eb723a839c3629f0dc5dc6de11bfc') variant('python', default=True, description='Enable python API') depends_on(\"python@3.3:\",", "See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier:", "checking.\"\"\" homepage = \"https://spot.lrde.epita.fr/\" url = \"http://www.lrde.epita.fr/dload/spot/spot-1.99.3.tar.gz\" version('1.99.3', sha256='86964af559994af4451a8dca663a9e1db6e869ed60e747ab60ce72dddc31b61b') version('1.2.6',", "Spot(AutotoolsPackage): \"\"\"Spot is a C++11 library for omega-automata manipulation and", "sha256='360678c75f6741f697e8e56cdbc9937f104eb723a839c3629f0dc5dc6de11bfc') variant('python', default=True, description='Enable python API') depends_on(\"python@3.3:\", when='@1.99.5: +python') depends_on(\"python@3.2:\",", "is a C++11 library for omega-automata manipulation and model checking.\"\"\"", "and other # Spack Project Developers. See the top-level COPYRIGHT", "* class Spot(AutotoolsPackage): \"\"\"Spot is a C++11 library for omega-automata", "# # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import *", "and model checking.\"\"\" homepage = \"https://spot.lrde.epita.fr/\" url = \"http://www.lrde.epita.fr/dload/spot/spot-1.99.3.tar.gz\" version('1.99.3',", "url = \"http://www.lrde.epita.fr/dload/spot/spot-1.99.3.tar.gz\" version('1.99.3', sha256='86964af559994af4451a8dca663a9e1db6e869ed60e747ab60ce72dddc31b61b') version('1.2.6', sha256='360678c75f6741f697e8e56cdbc9937f104eb723a839c3629f0dc5dc6de11bfc') variant('python', default=True, description='Enable", "the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0", "MIT) from spack import * class Spot(AutotoolsPackage): \"\"\"Spot is a", "library for omega-automata manipulation and model checking.\"\"\" homepage = \"https://spot.lrde.epita.fr/\"", "file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from", "# Spack Project Developers. See the top-level COPYRIGHT file for", "(Apache-2.0 OR MIT) from spack import * class Spot(AutotoolsPackage): \"\"\"Spot", "homepage = \"https://spot.lrde.epita.fr/\" url = \"http://www.lrde.epita.fr/dload/spot/spot-1.99.3.tar.gz\" version('1.99.3', sha256='86964af559994af4451a8dca663a9e1db6e869ed60e747ab60ce72dddc31b61b') version('1.2.6', sha256='360678c75f6741f697e8e56cdbc9937f104eb723a839c3629f0dc5dc6de11bfc')", "depends_on(\"python@3.3:\", when='@1.99.5: +python') depends_on(\"python@3.2:\", when='@1.99: +python') depends_on(\"python@2:\", when='+python') depends_on('boost', when='@:1.2.6')", "Project Developers. See the top-level COPYRIGHT file for details. #", "Lawrence Livermore National Security, LLC and other # Spack Project", "SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Spot(AutotoolsPackage):", "Developers. See the top-level COPYRIGHT file for details. # #", "from spack import * class Spot(AutotoolsPackage): \"\"\"Spot is a C++11", "description='Enable python API') depends_on(\"python@3.3:\", when='@1.99.5: +python') depends_on(\"python@3.2:\", when='@1.99: +python') depends_on(\"python@2:\",", "import * class Spot(AutotoolsPackage): \"\"\"Spot is a C++11 library for", "# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other", "API') depends_on(\"python@3.3:\", when='@1.99.5: +python') depends_on(\"python@3.2:\", when='@1.99: +python') depends_on(\"python@2:\", when='+python') depends_on('boost',", "Livermore National Security, LLC and other # Spack Project Developers.", "other # Spack Project Developers. See the top-level COPYRIGHT file", "OR MIT) from spack import * class Spot(AutotoolsPackage): \"\"\"Spot is", "2013-2020 Lawrence Livermore National Security, LLC and other # Spack", "= \"http://www.lrde.epita.fr/dload/spot/spot-1.99.3.tar.gz\" version('1.99.3', sha256='86964af559994af4451a8dca663a9e1db6e869ed60e747ab60ce72dddc31b61b') version('1.2.6', sha256='360678c75f6741f697e8e56cdbc9937f104eb723a839c3629f0dc5dc6de11bfc') variant('python', default=True, description='Enable python", "Copyright 2013-2020 Lawrence Livermore National Security, LLC and other #", "COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT)", "model checking.\"\"\" homepage = \"https://spot.lrde.epita.fr/\" url = \"http://www.lrde.epita.fr/dload/spot/spot-1.99.3.tar.gz\" version('1.99.3', sha256='86964af559994af4451a8dca663a9e1db6e869ed60e747ab60ce72dddc31b61b')", "\"https://spot.lrde.epita.fr/\" url = \"http://www.lrde.epita.fr/dload/spot/spot-1.99.3.tar.gz\" version('1.99.3', sha256='86964af559994af4451a8dca663a9e1db6e869ed60e747ab60ce72dddc31b61b') version('1.2.6', sha256='360678c75f6741f697e8e56cdbc9937f104eb723a839c3629f0dc5dc6de11bfc') variant('python', default=True,", "omega-automata manipulation and model checking.\"\"\" homepage = \"https://spot.lrde.epita.fr/\" url =", "<filename>var/spack/repos/builtin/packages/spot/package.py # Copyright 2013-2020 Lawrence Livermore National Security, LLC and", "top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR", "\"http://www.lrde.epita.fr/dload/spot/spot-1.99.3.tar.gz\" version('1.99.3', sha256='86964af559994af4451a8dca663a9e1db6e869ed60e747ab60ce72dddc31b61b') version('1.2.6', sha256='360678c75f6741f697e8e56cdbc9937f104eb723a839c3629f0dc5dc6de11bfc') variant('python', default=True, description='Enable python API')" ]
[]
[ "np.pi, 5 * np.pi]) axs[0].set_xticklabels(['', '', '', '', '', ''])", "axis += 1 plt.savefig('jss_figures/Duffing_equation_imfs.png') plt.show() hs_ouputs = hilbert_spectrum(t, emd_duff, emd_ht_duff,", "emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=2, verbose=False) fig, axs = plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10)", "plt.figure(figsize=(9, 4)) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('First Iteration of Sifting", "plt.show() # plot 3 a = 0.25 width = 0.2", "= time[inflection_bool] inflection_y = time_series[inflection_bool] fluctuation = emd_mean.Fluctuation(time=time, time_series=time_series) maxima_envelope", "np.linspace(-5.5, 5.5, 101), 'k--', label='Zoomed region') plt.savefig('jss_figures/DFA_different_trends.png') plt.show() # plot", "width, 101) min_dash_2 = np.linspace(minima_y[-2] - width, minima_y[-2] + width,", "5 * np.pi), (r'4$\\pi$', r'5$\\pi$')) plt.yticks((-2, -1, 0, 1, 2),", "bbox_to_anchor=(1, -0.15)) box_1 = axs[1].get_position() axs[1].set_position([box_1.x0 - 0.05, box_1.y0, box_1.width", "100 # forward -> P = np.zeros((int(neural_network_k + 1), neural_network_m))", "'', '']) box_1 = axs[1].get_position() axs[1].set_position([box_1.x0 - 0.05, box_1.y0, box_1.width", "import matplotlib.pyplot as plt from scipy.integrate import odeint from scipy.ndimage", "+ (minima_x[-1] - minima_x[-2]), 0.35 + (minima_y[-1] - minima_y[-2]), r'$s_1$')", "np.linspace(time[-1] - width, time[-1] + width, 101) end_signal = time_series[-1]", "* np.ones(100), c='k') plt.plot(((time_extended[-1001] + time_extended[-1002]) / 2) * np.ones(100),", "improved_slope_based_minimum_time = slope_based_minimum_time improved_slope_based_minimum = improved_slope_based_maximum + s2 * (improved_slope_based_minimum_time", "1.55 * np.pi) axs[1].plot(time, time_series, label='Time series') axs[1].plot(time, imfs_31[1, :]", "101), 'k--') axs[1].plot(1.55 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101),", "np.ones(100), np.linspace(-2.75, 2.75, 100), c='k') plt.plot(((time[-202] + time[-201]) / 2)", "bbox_to_anchor=(1, 0.5), fontsize=8) axs[2].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101),", "10)) plt.plot(time, np.cos(time), c='black', label='True mean') plt.xticks((0, 1 * np.pi,", "1, 2), ('-3', '-2', '-1', '0', '1', '2')) box_0 =", "slope_based_minimum_time = minima_x[-1] + (minima_x[-1] - minima_x[-2]) slope_based_minimum = slope_based_maximum", "-1, 0, 1, 2), ('-2', '-1', '0', '1', '2')) plt.xlim(-0.25", "\\ emd_utils.Utility(time=time_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))], time_series=time_series_extended[int(len(lsq_signal) - 1 -", "(- train_input) # guess average gradients average_gradients = np.mean(gradients, axis=1)", "ax.set_xticklabels(x_names) axis += 1 plt.savefig('jss_figures/Duffing_equation.png') plt.show() # compare other packages", "other packages Duffing - bottom emd_duffing = AdvEMDpy.EMD(time=t, time_series=x) emd_duff,", "plt.scatter(Average_min_time, Average_min, c='cyan', zorder=4, label=textwrap.fill('Average minimum', 14)) plt.scatter(maxima_x, maxima_y, c='r',", "label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.scatter(time[optimal_maxima], time_series[optimal_maxima], c='darkred', zorder=4,", "= np.linspace(minima_y[-2], maxima_y[-2], 101) dash_max_min_2_x_time = 5.3 * np.pi *", "12)) axs[0].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean filter', 12)) axs[0].plot(preprocess_time, preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median filter',", "smooth=True) min_unsmoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima', smooth=False) min_smoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima',", "max_discard * np.ones_like(max_discard_dash_time) dash_2_time = np.linspace(minima_x[-1], max_discard_time, 101) dash_2 =", "12)) plt.scatter(minima_extrapolate_time, minima_extrapolate, c='cyan', zorder=4, label=textwrap.fill('Extrapolated minima', 12)) plt.plot(((time[-302] +", "utils_Huang.min_bool_func_1st_order_fd() utils_Coughlin = emd_utils.Utility(time=time, time_series=Coughlin_wave) Coughlin_max_bool = utils_Coughlin.max_bool_func_1st_order_fd() Coughlin_min_bool =", "10)) plt.scatter(Huang_min_time, Huang_min, c='lime', zorder=4, label=textwrap.fill('Huang minimum', 10)) plt.scatter(Coughlin_max_time, Coughlin_max,", "0].set_title('IMF 1') axs[1, 1].set_title('Residual') plt.gcf().subplots_adjust(bottom=0.15) plt.savefig('jss_figures/CO2_EMD.png') plt.show() hs_ouputs = hilbert_spectrum(time,", "* s1 max_dash_time_3 = slope_based_maximum_time * np.ones_like(max_dash_1) max_dash_3 = np.linspace(slope_based_maximum", "_ = \\ emd_example.empirical_mode_decomposition(knots=knots, knot_time=time, verbose=False) print(f'AdvEMDpy annual frequency error:", "r'$2\\pi$']) axs[0].plot(knots[0][0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots')", "= axs[1].get_position() axs[1].set_position([box_1.x0 - 0.05, box_1.y0, box_1.width * 0.85, box_1.height])", "np.ones(101) symmetry_axis_2_time = time[-1] * np.ones(101) symmetry_axis = np.linspace(-2, 2,", "imfs[0, :], label='Smoothed') axs[0, 1].legend(loc='lower right') axs[1, 0].plot(time, imfs[1, :])", "np.linspace(-2.75, 2.75, 100), c='gray', linestyle='dashed') plt.xlim(3.4 * np.pi, 5.6 *", "np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') plt.legend(loc='upper left') plt.savefig('jss_figures/boundary_bases.png') plt.show() #", "-3.2, r'$\\Delta{t^{min}_{m}}$') plt.text(4.74 * np.pi, -3.2, r'$\\Delta{t^{min}_{m}}$') plt.text(4.12 * np.pi,", "2 * np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[1].plot(pseudo_alg_time,", "3 with 51 knots', 19)) print(f'DFA fluctuation with 31 knots:", "1)) objective = cvx.Minimize(cvx.norm((2 * (vx * P) + 1", "$', r'$ \\tau_1 $']) plt.xlim(4.4, 6.6) plt.plot(5 * np.ones(100), np.linspace(-0.2,", "1101) basis = emd_basis.Basis(time=time, time_series=time) b_spline_basis = basis.cubic_b_spline(knots) chsi_basis =", "* 0.85, box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[0].set_ylim(-5.5, 5.5)", "0: ax.set(ylabel=R'C0$_2$ concentration') if axis == 1: pass if axis", "label=textwrap.fill('EMD envelope', 10)) plt.plot(time, minima_envelope, c='darkblue') plt.plot(time, (maxima_envelope + minima_envelope)", "c='dodgerblue', zorder=4, label=textwrap.fill('Coughlin minimum', 14)) plt.scatter(Average_max_time, Average_max, c='orangered', zorder=4, label=textwrap.fill('Average", "= -2.1 * np.ones_like(dash_max_min_1_y_time) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Characteristic Wave", "ax.label_outer() if axis == 0: ax.set_ylabel('x(t)') ax.set_yticks(y_points_1) if axis ==", "'k--') axs[0].plot(0.95 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--')", "plt.plot(knot * np.ones(101), np.linspace(-3.0, -2.0, 101), '--', c='grey', zorder=1) plt.plot(knots[-1]", "3 * np.ones(101), '--', c='black') axs[0].plot(0.85 * np.pi * np.ones(101),", "of IMF 1 and IMF 2 with 31 knots', 19))", "= hilbert_spectrum(t, emd_duff, emd_ht_duff, emd_if_duff, max_frequency=1.3, plot=False) ax = plt.subplot(111)", "* time) + np.cos(4 * time) + np.cos(8 * time)", "series') axs[2].plot(time, imfs_11[1, :], label='IMF 1 with 11 knots') axs[2].plot(time,", "Analysis Examples') plt.plot(time, time_series, LineWidth=2, label='Time series') plt.scatter(maxima_x, maxima_y, c='r',", "np.linspace(minima_x[-1], slope_based_maximum_time, 101) dash_3 = np.linspace(minima_y[-1], slope_based_maximum, 101) s2 =", "- maxima_x[-1] + minima_x[-1] max_discard_dash_time = np.linspace(max_discard_time - width, max_discard_time", "y / (2 * np.pi) z_min, z_max = 0, np.abs(z).max()", "= cvx.Minimize(cvx.norm((2 * (vx * P) + 1 - t),", "plt.plot(time, time_series, LineWidth=2, label='Signal') plt.title('Symmetry Edge Effects Example') plt.plot(time_reflect, time_series_reflect,", "pseudo_alg_time_series, label=r'$h_{(1,0)}(t)$', zorder=1) plt.scatter(pseudo_alg_time[pseudo_utils.max_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.max_bool_func_1st_order_fd()], c='r', label=r'$M(t_i)$', zorder=2) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time)", "bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/neural_network.png') plt.show() # plot 6a np.random.seed(0) time =", "axs[0].plot(t, x) axs[0].set_title('Duffing Equation Displacement') axs[0].set_ylim([-2, 2]) axs[0].set_xlim([0, 150]) axs[1].plot(t,", "& decimated', 11)) downsampled = preprocess.downsample(decimate=False) axs[0].plot(downsampled[0], downsampled[1], label=textwrap.fill('Downsampled', 13))", "50)) x_hs, y, z = hs_ouputs z_min, z_max = 0,", "util.min_bool_func_1st_order_fd() ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title(textwrap.fill('Plot Demonstrating Unsmoothed Extrema Envelopes", "11)) downsampled = preprocess.downsample(decimate=False) axs[0].plot(downsampled[0], downsampled[1], label=textwrap.fill('Downsampled', 13)) axs[0].plot(np.linspace(0.85 *", "len(lsq_signal) - 1): time_series_extended[int(len(lsq_signal) - 2 - i_left)] = \\", "int(2 * (len(lsq_signal) - 1) + 1 - neural_network_k +", "filter', 14)) axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.90)[1], c='grey', label=textwrap.fill('Quantile window', 12)) axs[1].plot(preprocess_time,", "box_0.width * 0.75, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))", "'minima', smooth=False, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] minima_envelope_smooth = fluctuation.envelope_basis_function_approximation(knots, 'minima', smooth=True,", "ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht_pyemd.png') plt.show() plt.show() emd_sift = emd040.sift.sift(x)", "the Atmosphere', 35)) plt.ylabel('Parts per million') plt.xlabel('Time (years)') plt.savefig('jss_figures/CO2_concentration.png') plt.show()", "box_2.width * 0.85, box_2.height]) axs[2].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[2].plot(np.linspace(0.95", "hs_ouputs z_min, z_max = 0, np.abs(z).max() ax.pcolormesh(x_hs, y, np.abs(z), cmap='gist_rainbow',", "= plt.subplots(2, 1) plt.subplots_adjust(hspace=0.2) axs[0].plot(t, x) axs[0].set_title('Duffing Equation Displacement') axs[0].set_ylim([-2,", "range(3): for j in range(1, len(knots[i])): axs[i].plot(knots[i][j] * np.ones(101), np.linspace(-2,", "== 2: ax.set(ylabel=R'C0$_2$ concentration') ax.set(xlabel='Time (years)') if axis == 3:", "* np.pi, 101) time_extended = time_extension(time) time_series_extended = np.zeros_like(time_extended) /", "output = np.matmul(weights, train_input) error = (t - output) gradients", "axis == 0: ax.set_ylabel(r'$\\gamma_1(t)$') ax.set_yticks([-2, 0, 2]) if axis ==", "np.pi, -2.2, r'$\\frac{p_2}{2}$') plt.plot(max_1_x_time, max_1_x, 'k-') plt.plot(max_1_x_time_side, max_1_x, 'k-') plt.plot(min_1_x_time,", "symmetry', 10), zorder=1) plt.text(5.1 * np.pi, -0.7, r'$\\beta$L') plt.text(5.34 *", "np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots[0]", "'k-') plt.plot(end_time, end_signal, 'k-') plt.plot(symmetry_axis_1_time, symmetry_axis, 'r--', zorder=1) plt.plot(anti_symmetric_time, anti_symmetric_signal,", "axs[1].plot(preprocess_time, preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott smoothing', 12)) axs[1].plot(preprocess_time, preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker smoothing', 13))", "* np.ones_like(min_1_y) dash_max_min_1_y_time = np.linspace(minima_x[-1], maxima_x[-1], 101) dash_max_min_1_y = -2.1", "* np.pi, 101), 5.5 * np.ones(101), 'k--') axs[2].plot(np.linspace(0.95 * np.pi,", "2, 101), '--', c='grey', label='Knots') axs[2].plot(knots[2][0] * np.ones(101), np.linspace(-2, 2,", "axs[0].plot(downsampled_and_decimated[0], downsampled_and_decimated[1], label=textwrap.fill('Downsampled & decimated', 11)) downsampled = preprocess.downsample(decimate=False) axs[0].plot(downsampled[0],", "# Duffing Equation Example def duffing_equation(xy, ts): gamma = 0.1", "emd040.spectra.define_hist_bins(0, 0.2, 100) hht = emd040.spectra.hilberthuang(IF, IA, freq_edges) hht =", "slope-based method and improved slope-based method more clear time_series[time >=", "if axis == 0: ax.set(ylabel=R'C0$_2$ concentration') if axis == 1:", "plt.plot(dash_max_min_1_y_time, dash_max_min_1_y, 'k--') plt.text(4.48 * np.pi, -2.5, r'$\\frac{p_1}{2}$') plt.xlim(3.9 *", "emd_hilbert import Hilbert, hilbert_spectrum from emd_preprocess import Preprocess from emd_mean", "0.5, 101) anti_symmetric_signal = time_series[-1] * np.ones_like(anti_symmetric_time) ax = plt.subplot(111)", "c='purple', zorder=4, label=textwrap.fill('Slope-based minimum', 11)) plt.scatter(improved_slope_based_maximum_time, improved_slope_based_maximum, c='deeppink', zorder=4, label=textwrap.fill('Improved", "import gaussian_filter from emd_utils import time_extension, Utility from scipy.interpolate import", "edge_effect='symmetric_anchor', verbose=False)[:3] knots_11 = np.linspace(0, 5 * np.pi, 11) imfs_11,", "0.2]) box_0 = ax.get_position() ax.set_position([box_0.x0, box_0.y0, box_0.width * 0.85, box_0.height])", "'k-') plt.plot(maxima_dash_time_1, maxima_dash, 'k-') plt.plot(maxima_dash_time_2, maxima_dash, 'k-') plt.plot(maxima_dash_time_3, maxima_dash, 'k-')", "t = lsq_signal[-neural_network_m:] # test - top seed_weights = np.ones(neural_network_k)", "8 * np.ones_like(x_hs[0, :]), '--', label=r'$\\omega = 8$', Linewidth=3) ax.plot(x_hs[0,", "zorder=4, label=textwrap.fill('Symmetric Discard maxima', 10)) plt.scatter(end_point_time, end_point, c='orange', zorder=4, label=textwrap.fill('Symmetric", "np.linspace(-5, 5, 101), '--', c='grey', zorder=1, label='Knots') axs[1].set_xticks([0, np.pi, 2", "2 * np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1 and Dynamically", "plt.plot(((time[-302] + time[-301]) / 2) * np.ones(100), np.linspace(-2.75, 2.75, 100),", "axs[1].plot(knots[1][0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[2].plot(knots[2][0]", "label=textwrap.fill('Sum of IMF 2 and IMF 3 with 51 knots',", "101), '--', c='grey', zorder=1, label='Knots') axs[2].set_xticks([0, np.pi, 2 * np.pi,", "+ width, 101) max_dash_time_1 = maxima_x[-1] * np.ones_like(max_dash_1) max_dash_time_2 =", "box_0.y0, box_0.width * 0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/detrended_fluctuation_analysis.png')", "plot 1a - addition knot_demonstrate_time = np.linspace(0, 2 * np.pi,", "- width, 5.4 * np.pi + width, 101) max_1_x =", "1 + i_right)], 1))) i_right += 1 if i_right >", "bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht.png') plt.show() # Carbon Dioxide Concentration Example CO2_data", "c='darkgreen') plt.plot(time, (EEMD_maxima_envelope + EEMD_minima_envelope) / 2, c='darkgreen') plt.plot(time, inflection_points_envelope,", "plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.plot(Huang_time, Huang_wave, '--', c='darkviolet', label=textwrap.fill('Huang", "label=textwrap.fill('Windsorize interpolation filter', 14)) axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.90)[1], c='grey', label=textwrap.fill('Quantile window',", "end_time = np.linspace(time[-1] - width, time[-1] + width, 101) end_signal", "1, False] optimal_minima = np.r_[False, utils.derivative_forward_diff() > 0, False] &", "\\dfrac{dx(t)}{dt} $') ax.set(xlabel='t') ax.set_yticks(y_points_2) ax.set_xticks(x_points) ax.set_xticklabels(x_names) axis += 1 plt.savefig('jss_figures/Duffing_equation.png')", "label=textwrap.fill('Slope-based minimum', 11)) plt.scatter(improved_slope_based_maximum_time, improved_slope_based_maximum, c='deeppink', zorder=4, label=textwrap.fill('Improved slope-based maximum',", "1.2, 100), 'k-') plt.plot(6 * np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-')", "'k-') plt.plot(min_dash_time, min_dash, 'k-') plt.plot(dash_1_time, dash_1, 'k--') plt.plot(dash_2_time, dash_2, 'k--')", "+ width, 101) min_2_x_time_side = np.linspace(5.3 * np.pi - width,", "fig, ax = plt.subplots() figure_size = plt.gcf().get_size_inches() factor = 0.7", "- 0.1, 100), -2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1002])", "axs[1, 1].plot(time, imfs[2, :]) axis = 0 for ax in", "minima_x[-1] + width, 101) min_dash = minima_y[-1] * np.ones_like(min_dash_time) dash_1_time", "'--', c='purple', label=r'$\\tilde{h}_{(1,0)}^{\\mu}(t)$', zorder=5) plt.yticks(ticks=[-2, -1, 0, 1, 2]) plt.xticks(ticks=[0,", "np.pi * t / 200) util_nn = emd_utils.Utility(time=t, time_series=signal_orig) maxima", "1 # for additive constant t = lsq_signal[-neural_network_m:] # test", "fluctuation with 31 knots: {np.round(np.var(time_series - (imfs_31[1, :] + imfs_31[2,", "time[-1] improved_slope_based_maximum = time_series[-1] improved_slope_based_minimum_time = slope_based_minimum_time improved_slope_based_minimum = improved_slope_based_maximum", "5.4 * np.pi * np.ones_like(dash_max_min_1_x) max_1_y = np.linspace(maxima_y[-1] - width,", "preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median filter', 13)) axs[1].plot(preprocess_time, preprocess.winsorize(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize filter', 12))", "* np.pi - width, 5.4 * np.pi + width, 101)", "c='darkred', label=textwrap.fill('SEMD envelope', 10)) plt.plot(time, minima_envelope_smooth, c='darkred') plt.plot(time, (maxima_envelope_smooth +", "left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_slope_based.png') plt.show() # plot 5 a =", "np.pi * np.ones_like(length_distance) length_time = np.linspace(point_1 * np.pi - width,", "- width, minima_y[-1] + width, 101) min_1_y_side = np.linspace(-2.1 -", "fluctuation with 11 knots: {np.round(np.var(time_series - imfs_51[3, :]), 3)}') for", "minima_envelope = fluctuation.envelope_basis_function_approximation(knots, 'minima', smooth=False, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] minima_envelope_smooth =", "= Huang_time[Huang_min_bool] Huang_min = Huang_wave[Huang_min_bool] Coughlin_max_time = Coughlin_time[Coughlin_max_bool] Coughlin_max =", "improved_slope_based_maximum, c='deeppink', zorder=4, label=textwrap.fill('Improved slope-based maximum', 11)) plt.scatter(improved_slope_based_minimum_time, improved_slope_based_minimum, c='dodgerblue',", "box_0.width * 0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_characteristic_wave.png') plt.show()", "Coughlin_wave[Coughlin_max_bool] Coughlin_min_time = Coughlin_time[Coughlin_min_bool] Coughlin_min = Coughlin_wave[Coughlin_min_bool] max_2_x_time = np.linspace(maxima_x[-2]", "101) end_time = np.linspace(time[-1] - width, time[-1] + width, 101)", "zorder=4, label=textwrap.fill('Average maximum', 14)) plt.scatter(Average_min_time, Average_min, c='cyan', zorder=4, label=textwrap.fill('Average minimum',", "and (i_left < len(lsq_signal) - 1): time_series_extended[int(len(lsq_signal) - 2 -", "13)) plt.plot(np.linspace(((time[-302] + time[-301]) / 2), ((time[-302] + time[-301]) /", "plt.gcf().subplots_adjust(bottom=0.10) plt.title('Single Neuron Neural Network Example') plt.plot(time, lsq_signal, zorder=2, label='Signal')", "13)) axs[0].plot(np.linspace(0.85 * np.pi, 1.15 * np.pi, 101), -3 *", "np.linspace(maxima_x[-1] - width, maxima_x[-1] + width, 101) max_dash = maxima_y[-1]", "= np.linspace(maxima_y[-1] - width, maxima_y[-1] + width, 101) max_dash_2 =", "* np.pi, 5 * np.pi]) axs[1].set_xticklabels(['', '', '', '', '',", "c='blue') for knot in knots[:-1]: plt.plot(knot * np.ones(101), np.linspace(-3.0, -2.0,", "imfs[2, :]) axis = 0 for ax in axs.flat: if", "label='Time series', zorder=2, LineWidth=2) plt.scatter(time[maxima], time_series[maxima], c='r', label='Maxima', zorder=10) plt.scatter(time[minima],", "r'$\\Delta{t^{max}_{M}}$') plt.text(4.50 * np.pi, 2, r'$\\Delta{t^{max}_{M}}$') plt.text(4.30 * np.pi, 0.35,", "2]) axs[2].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots[0][0]", "plt.plot(6 * np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') plt.legend(loc='upper left') plt.savefig('jss_figures/boundary_bases.png')", "= fluctuation.envelope_basis_function_approximation(knots, 'minima', smooth=True, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] inflection_points_envelope = fluctuation.direct_detrended_fluctuation_estimation(knots,", "box_0 = ax.get_position() ax.set_position([box_0.x0, box_0.y0, box_0.width * 0.85, box_0.height]) ax.legend(loc='center", "1] fig, axs = plt.subplots(2, 1) plt.subplots_adjust(hspace=0.2) axs[0].plot(t, x) axs[0].set_title('Duffing", "P2 = 2 * np.abs(maxima_x[-2] - minima_x[-2]) P1 = 2", "1') axs[0].set_ylim([-2, 2]) axs[0].set_xlim([0, 150]) axs[1].plot(t, emd_duff[2, :], label='AdvEMDpy') print(f'AdvEMDpy", "'--', c='grey', zorder=1, label='Knots') axs[2].set_xticks([0, np.pi, 2 * np.pi, 3", "import emd_basis import emd_utils import numpy as np import pandas", "addition fig = plt.figure(figsize=(9, 4)) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('First", "= np.linspace(0, 2 * np.pi, 51) emd = EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series)", "1)) and (i_right < len(lsq_signal) - 1): time_series_extended[int(2 * (len(lsq_signal)", "smooth=False, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] maxima_envelope_smooth = fluctuation.envelope_basis_function_approximation(knots, 'maxima', smooth=True, smoothing_penalty=0.2,", "2 with 31 knots') axs[2].plot(time, imfs_51[3, :], label='IMF 3 with", "print(f'DFA fluctuation with 51 knots: {np.round(np.var(time_series - (imfs_51[1, :] +", "box_0.width * 0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/neural_network.png') plt.show()", "= fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima', smooth=False) min_smoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima', smooth=True) util", "max_discard_time, 101) dash_2 = np.linspace(minima_y[-1], max_discard, 101) end_point_time = time[-1]", "range(1, len(knots[i])): axs[i].plot(knots[i][j] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey')", "plt.plot(min_2_x_time_side, min_2_x, 'k-') plt.plot(dash_max_min_2_x_time, dash_max_min_2_x, 'k--') plt.text(5.16 * np.pi, 0.85,", "max_count_right = 0 min_count_right = 0 i_right = 0 while", "Carbon Dioxide in the Atmosphere', 35)) plt.ylabel('Parts per million') plt.xlabel('Time", "point envelope', 10)) plt.plot(time, binomial_points_envelope, c='deeppink', label=textwrap.fill('Binomial average envelope', 10))", "time_series=time_series_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))]) if sum(emd_utils_min.min_bool_func_1st_order_fd()) > 0: min_count_left", "plt.gcf().get_size_inches() factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) axs[0].plot(t, emd_duff[1,", "vx = cvx.Variable(int(neural_network_k + 1)) objective = cvx.Minimize(cvx.norm((2 * (vx", "r'4$\\pi$', r'5$\\pi$')) plt.yticks((-2, -1, 0, 1, 2), ('-2', '-1', '0',", "Neural Network Example') plt.plot(time, lsq_signal, zorder=2, label='Signal') plt.plot(time_extended, time_series_extended, c='g',", "* np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1) axs[0].plot(knot *", "hilbert_spectrum(time, imfs, hts, ifs, max_frequency=10, which_imfs=[1], plot=False) x_hs, y, z", "minima_y[-1]), r'$s_2$') plt.plot(minima_line_dash_time, minima_line_dash, 'k--') plt.plot(maxima_line_dash_time, maxima_line_dash, 'k--') plt.plot(dash_1_time, dash_1,", "\\/ import random import textwrap import emd_mean import AdvEMDpy import", "axs[1].plot(preprocess_time, preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median filter', 13)) axs[1].plot(preprocess_time, preprocess.winsorize(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize filter',", "ax.set_xticks(x_points) ax.set_xticklabels(x_names) axis += 1 plt.savefig('jss_figures/Duffing_equation.png') plt.show() # compare other", "knot in knots_51: axs[0].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--',", "13)) downsampled_and_decimated = preprocess.downsample() axs[0].plot(downsampled_and_decimated[0], downsampled_and_decimated[1], label=textwrap.fill('Downsampled & decimated', 11))", "* sum(weights_left * np.hstack((time_series_extended[int(len(lsq_signal) - 1 - i_left): int(len(lsq_signal) -", "+ a) * np.pi, (5 - a) * np.pi, 11)", "2, sharey=True) axs[0].set_title('Cubic B-Spline Bases') axs[0].plot(time, b_spline_basis[2, :].T, '--', label='Basis", "anti_max_point_time = time_reflect[anti_max_bool] anti_max_point = time_series_anti_reflect[anti_max_bool] utils = emd_utils.Utility(time=time, time_series=time_series_reflect)", "= np.asarray(signal) time = CO2_data['month'] time = np.asarray(time) # compare", "IMF 1 and IMF 2 with 31 knots', 19)) axs[1].plot(time,", "axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2, 101), '--',", "+ i_right + 1)]) if sum(emd_utils_max.max_bool_func_1st_order_fd()) > 0: max_count_right +=", "* 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht.png') plt.show() # Carbon", "ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht_emd.png') plt.show() # compare other packages", "technique='binomial_average', order=21, increment=20)[0] derivative_of_lsq = utils.derivative_forward_diff() derivative_time = time[:-1] derivative_knots", "time[-1] * np.ones(101) symmetry_axis = np.linspace(-2, 2, 101) end_time =", "xy[0] - epsilon * xy[0] ** 3 + gamma *", "+ time[-201]) / 2) + 0.1, 100), 2.75 * np.ones(100),", "inputs', 13)) plt.plot(np.linspace(((time[-302] + time[-301]) / 2), ((time[-302] + time[-301])", "zorder=3) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time) - 1, '--', c='c', label=r'$\\tilde{h}_{(1,0)}^m(t)$', zorder=5) plt.plot(pseudo_alg_time,", "= np.linspace(minima_y[-2] - width, minima_y[-2] + width, 101) min_dash_time_1 =", "Example') plt.plot(time_reflect, time_series_reflect, 'g--', LineWidth=2, label=textwrap.fill('Symmetric signal', 10)) plt.plot(time_reflect[:51], time_series_anti_reflect[:51],", "zorder=4, label=textwrap.fill('Coughlin maximum', 14)) plt.scatter(Coughlin_min_time, Coughlin_min, c='dodgerblue', zorder=4, label=textwrap.fill('Coughlin minimum',", "width, 101) max_1_x = maxima_y[-1] * np.ones_like(max_1_x_time) min_1_x_time = np.linspace(minima_x[-1]", "np.ones(100), c='k') plt.plot(np.linspace(((time[-302] + time[-301]) / 2), ((time[-302] + time[-301])", "with 11 knots') axs[2].plot(time, imfs_31[2, :], label='IMF 2 with 31", "fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima', smooth=False) max_smoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima', smooth=True) min_unsmoothed =", "region') box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.05, box_0.y0, box_0.width *", "= 0.21 width = 0.2 time = np.linspace(0, (5 -", "np.pi) plt.xticks((4 * np.pi, 5 * np.pi), (r'4$\\pi$', r'5$\\pi$')) plt.yticks((-3,", "range(3): for j in range(1, len(knots)): axs[i].plot(knots[j] * np.ones(101), np.linspace(-2,", "Algorithm') plt.plot(pseudo_alg_time, pseudo_alg_time_series, label=r'$h_{(1,0)}(t)$', zorder=1) plt.scatter(pseudo_alg_time[pseudo_utils.max_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.max_bool_func_1st_order_fd()], c='r', label=r'$M(t_i)$', zorder=2)", "'--', c='r', label=r'$\\tilde{h}_{(1,0)}^M(t)$', zorder=4) plt.scatter(pseudo_alg_time[pseudo_utils.min_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.min_bool_func_1st_order_fd()], c='c', label=r'$m(t_j)$', zorder=3) plt.plot(pseudo_alg_time,", "'--', label=r'$\\omega = 4$', Linewidth=3) ax.plot(x_hs[0, :], 2 * np.ones_like(x_hs[0,", "slope_based_maximum, c='orange', zorder=4, label=textwrap.fill('Slope-based maximum', 11)) plt.scatter(slope_based_minimum_time, slope_based_minimum, c='purple', zorder=4,", "plt.gcf().get_size_inches() factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered", "while ((max_count_right < 1) or (min_count_right < 1)) and (i_right", "Cubic B-Spline Bases at Boundary') plt.plot(time[500:], b_spline_basis[2, 500:].T, '--', label=r'$", "= np.linspace(0, 5 * np.pi, 31) imfs_31, hts_31, ifs_31 =", "- 0.05, box_1.y0, box_1.width * 0.85, box_1.height]) axs[1].legend(loc='center left', bbox_to_anchor=(1,", "time[inflection_bool] inflection_y = time_series[inflection_bool] fluctuation = emd_mean.Fluctuation(time=time, time_series=time_series) maxima_envelope =", "(slope_based_minimum_time - minima_x[-1]), -0.20 + (slope_based_minimum - minima_y[-1]), r'$s_2$') plt.text(4.50", "* np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') axs[1].set_xticks([5, 6]) axs[1].set_xticklabels([r'$ \\tau_k", "= emd040.spectra.frequency_transform(py_emd.T, 10, 'hilbert') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 0.2, 100)", "= emd040.spectra.hilberthuang(IF, IA, freq_edges) hht = gaussian_filter(hht, sigma=1) ax =", "axis += 1 plt.gcf().subplots_adjust(bottom=0.15) axs[0, 0].set_title(r'Original CO$_2$ Concentration') axs[0, 1].set_title('Smoothed", "np.pi - width, point_2 * np.pi + width, 101) length_top_2", "c='magenta', zorder=3, label=textwrap.fill('Extrapolated maxima', 12)) plt.scatter(minima_extrapolate_time, minima_extrapolate, c='cyan', zorder=4, label=textwrap.fill('Extrapolated", "= (maxima_y[-2] + maxima_y[-1]) / 2 Average_min_time = minima_x[-1] +", "width, 101) max_2_y_side = np.linspace(-1.8 - width, -1.8 + width,", "error * (- train_input) # guess average gradients average_gradients =", "2 and Uniform Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2, zorder=100) axs[2].set_yticks(ticks=[-2,", "1.5 * (time_series[time >= minima_x[-1]] - time_series[time == minima_x[-1]]) +", "(imfs_51[1, :] + imfs_51[2, :] + imfs_51[3, :])), 3)}') for", "col] = lsq_signal[int(col + 1):int(col + neural_network_k + 1)] P[-1,", "(3) debug (confusing with external debugging) emd = AdvEMDpy.EMD(time=derivative_time, time_series=derivative_of_lsq)", "plt.show() signal = CO2_data['decimal date'] signal = np.asarray(signal) time =", "IA = emd040.spectra.frequency_transform(py_emd.T, 10, 'hilbert') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 0.2,", "10)) plt.scatter(anti_max_point_time, anti_max_point, c='green', zorder=4, label=textwrap.fill('Anti-Symmetric maxima', 10)) plt.scatter(no_anchor_max_time, no_anchor_max,", "\\ np.r_[utils.zero_crossing() == 1, False] EEMD_maxima_envelope = fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'maxima', optimal_maxima,", "np.linspace(-0.2, 1.2, 100), 'k-') axs[1].set_xticks([5, 6]) axs[1].set_xticklabels([r'$ \\tau_k $', r'$", "* np.ones_like(min_dash_1) dash_1_time = np.linspace(maxima_x[-1], minima_x[-1], 101) dash_1 = np.linspace(maxima_y[-1],", "max_dash_time_3 = slope_based_maximum_time * np.ones_like(max_dash_1) max_dash_3 = np.linspace(slope_based_maximum - width,", "11) imfs_11, hts_11, ifs_11 = advemdpy.empirical_mode_decomposition(knots=knots_11, max_imfs=1, edge_effect='symmetric_anchor', verbose=False)[:3] fig,", "3 * np.pi, 4 * np.pi]) ax.set_xticklabels(['$0$', r'$\\pi$', r'$2\\pi$', r'$3\\pi$',", "# plot 0 - addition fig = plt.figure(figsize=(9, 4)) ax", "max_1_x, 'k-') plt.plot(max_1_x_time_side, max_1_x, 'k-') plt.plot(min_1_x_time, min_1_x, 'k-') plt.plot(min_1_x_time_side, min_1_x,", "2 * np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots[0][0] * np.ones(101), np.linspace(-2,", ":] / (2 * np.pi) - np.ones_like(ifs[1, :]))), 3)}') fig,", "1 omega = ((2 * np.pi) / 25) return [xy[1],", "(minima_x[-1] - minima_x[-2]) Average_min = (minima_y[-2] + minima_y[-1]) / 2", "fluctuation.envelope_basis_function_approximation(knots, 'minima', smooth=False, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] minima_envelope_smooth = fluctuation.envelope_basis_function_approximation(knots, 'minima',", "label=textwrap.fill('Smoothed minima envelope', 10), c='blue') for knot in knots[:-1]: plt.plot(knot", "81 fig, axs = plt.subplots(2, 1) fig.subplots_adjust(hspace=0.4) figure_size = plt.gcf().get_size_inches()", "np.ones_like(max_dash_time) min_dash_time = np.linspace(minima_x[-1] - width, minima_x[-1] + width, 101)", "j in range(1, len(knots[i])): axs[i].plot(knots[i][j] * np.ones(101), np.linspace(-2, 2, 101),", "i in random.sample(range(1000), 500): preprocess_time_series[i] += np.random.normal(0, 1) preprocess =", "imfs_51, hts_51, ifs_51 = advemdpy.empirical_mode_decomposition(knots=knots_51, max_imfs=3, edge_effect='symmetric_anchor', verbose=False)[:3] knots_31 =", "'--', c='grey', label='Knots') axs[2].plot(knots[2][0] * np.ones(101), np.linspace(-2, 2, 101), '--',", "np.pi, 101), 3 * np.ones(101), '--', c='black') axs[0].plot(0.85 * np.pi", "preprocess.winsorize_interpolate(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize interpolation filter', 14)) axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.90)[1], c='grey',", "Neuron Neural Network Example') plt.plot(time, lsq_signal, zorder=2, label='Signal') plt.plot(time_extended, time_series_extended,", "c='r', label=r'$M(t_i)$', zorder=2) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time) + 1, '--', c='r', label=r'$\\tilde{h}_{(1,0)}^M(t)$',", "= np.linspace(maxima_y[-2] - width, maxima_y[-2] + width, 101) max_dash_time_1 =", "= np.r_[False, utils.derivative_forward_diff() < 0, False] & \\ np.r_[utils.zero_crossing() ==", "101) max_dash = maxima_y[-1] * np.ones_like(max_dash_time) min_dash_time = np.linspace(minima_x[-1] -", "* figure_size[1])) ax.pcolormesh(x_hs, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) ax.set_title(textwrap.fill(r'Gaussian Filtered", "0.5)) plt.savefig('jss_figures/Duffing_equation_ht_emd.png') plt.show() # compare other packages Duffing - bottom", "2.75 * np.ones(100), c='gray') plt.plot(((time_extended[-1001] + time_extended[-1000]) / 2) *", "c='grey', zorder=1) plt.plot(knots[-1] * np.ones(101), np.linspace(-3.0, -2.0, 101), '--', c='grey',", "31 knots') axs[2].plot(time, imfs_51[3, :], label='IMF 3 with 51 knots')", "preprocess_time_series, label='x(t)') axs[1].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time series', 12))", "c='gray', zorder=4, label=textwrap.fill('Symmetric maxima', 10)) plt.xlim(3.9 * np.pi, 5.5 *", "'k-') plt.plot(min_2_y_time, min_2_y, 'k-') plt.plot(min_2_y_time, min_2_y_side, 'k-') plt.plot(dash_max_min_2_y_time, dash_max_min_2_y, 'k--')", "& IMF 3 with 51 knots', 21)) for knot in", "= plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Uniform Knots')", "i_right)] = \\ sum(weights_right * np.hstack((time_series_extended[ int(2 * (len(lsq_signal) -", "time_series[min_bool] max_dash_1 = np.linspace(maxima_y[-1] - width, maxima_y[-1] + width, 101)", "len(preprocess_time)) for i in random.sample(range(1000), 500): preprocess_time_series[i] += np.random.normal(0, 1)", "plt.subplots(2, 1) fig.subplots_adjust(hspace=0.4) figure_size = plt.gcf().get_size_inches() factor = 0.8 plt.gcf().set_size_inches((figure_size[0],", "* np.pi) box_0 = ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width", "(minima_x[-1] - minima_x[-2]) slope_based_minimum = slope_based_maximum - (slope_based_maximum_time - slope_based_minimum_time)", "c='b', zorder=4, label='Minima') plt.scatter(max_discard_time, max_discard, c='purple', zorder=4, label=textwrap.fill('Symmetric Discard maxima',", "for j in range(1, len(knots)): axs[i].plot(knots[j] * np.ones(101), np.linspace(-2, 2,", "t = np.linspace(5, 95, 100) signal_orig = np.cos(2 * np.pi", "width, 101) dash_4_time = np.linspace(slope_based_maximum_time, slope_based_minimum_time) dash_4 = np.linspace(slope_based_maximum, slope_based_minimum)", "ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht.png') plt.show() # Carbon Dioxide Concentration", "axs[1].set_ylim([-0.2, 0.4]) axs[1].set_xlim([0, 150]) axis = 0 for ax in", "emd_example = AdvEMDpy.EMD(time=time, time_series=signal) imfs, hts, ifs, _, _, _,", "+ 1), neural_network_m)) for col in range(neural_network_m): P[:-1, col] =", "if i_left > 1: emd_utils_max = \\ emd_utils.Utility(time=time_extended[int(len(lsq_signal) - 1", "np.r_[utils.zero_crossing() == 1, False] EEMD_maxima_envelope = fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'maxima', optimal_maxima, optimal_minima,", "= np.ones(neural_network_k) / neural_network_k weights = 0 * seed_weights.copy() train_input", "r'$\\pi$', r'$2\\pi$']) box_0 = ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width", "Hermite Spline Bases') axs[1].plot(time, chsi_basis[10, :].T, '--') axs[1].plot(time, chsi_basis[11, :].T,", "= np.linspace(minima_y[-2] - width, minima_y[-2] + width, 101) min_2_y_side =", "1') axs[1, 1].set_title('Residual') plt.gcf().subplots_adjust(bottom=0.15) plt.savefig('jss_figures/CO2_EMD.png') plt.show() hs_ouputs = hilbert_spectrum(time, imfs,", "label='PyEMD 0.2.10') print(f'PyEMD driving function error: {np.round(sum(abs(0.1 * np.cos(0.04 *", "plt.show() # plot 1c - addition knot_demonstrate_time = np.linspace(0, 2", "axs[1].set_xticks(ticks=[np.pi]) axs[1].set_xticklabels(labels=[r'$\\pi$']) box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.06, box_0.y0, box_0.width", "imfs_51[2, :] + imfs_51[3, :])), 3)}') for knot in knots_51:", "np.linspace(-5.5, 5.5, 101), 'k--', label='Zoomed region') box_0 = axs[0].get_position() axs[0].set_position([box_0.x0", "'--', c='grey', label='Knots') for i in range(3): for j in", "'k--') axs[0].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), -5.5 *", ":], label=textwrap.fill('Sum of IMF 1 and IMF 2 with 31", "(P1 / P2) * (time[time >= maxima_x[-2]] - time[time ==", "axs[2].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots_uniform[0] *", "using emd 0.3.3', 40)) plt.pcolormesh(t, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht))))", "B_{0,4}(t) $') plt.plot(time[500:], b_spline_basis[6, 500:].T, '--', label=r'$ B_{1,4}(t) $') plt.xticks([5,", "1].plot(time, signal) axs[0, 1].plot(time, imfs[0, :], label='Smoothed') axs[0, 1].legend(loc='lower right')", "c='black') axs[0].plot(0.85 * np.pi * np.ones(101), np.linspace(-3, 3, 101), '--',", "Coughlin_max_time = Coughlin_time[Coughlin_max_bool] Coughlin_max = Coughlin_wave[Coughlin_max_bool] Coughlin_min_time = Coughlin_time[Coughlin_min_bool] Coughlin_min", "c='grey', label=textwrap.fill('Quantile window', 12)) axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.10)[1], c='grey') axs[0].plot(np.linspace(0.85 *", "np.abs(z).max() fig, ax = plt.subplots() figure_size = plt.gcf().get_size_inches() factor =", "width, -3.4 + width, 101) minima_dash_time_1 = minima_x[-2] * np.ones_like(minima_dash)", "* np.pi, 101), -5.5 * np.ones(101), 'k--') axs[2].plot(0.95 * np.pi", "min_dash_2 = np.linspace(minima_y[-2] - width, minima_y[-2] + width, 101) min_dash_time_1", "and Uniform Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2, zorder=100) axs[0].set_yticks(ticks=[-2, 0, 2])", "CO2_data['month'] time = np.asarray(time) # compare other packages Carbon Dioxide", "1: ax.set_ylabel(r'$ \\dfrac{dx(t)}{dt} $') ax.set(xlabel='t') ax.set_yticks(y_points_2) ax.set_xticks(x_points) ax.set_xticklabels(x_names) axis +=", "0 min_count_left = 0 i_left = 0 while ((max_count_left <", "length_top = maxima_y[-1] * np.ones_like(length_time) length_bottom = minima_y[-1] * np.ones_like(length_time)", "np.pi * (1 / P1) * (Coughlin_time - Coughlin_time[0])) Average_max_time", "max_dash, 'k-') plt.plot(min_dash_time, min_dash, 'k-') plt.plot(dash_1_time, dash_1, 'k--') plt.plot(dash_2_time, dash_2,", "* np.ones_like(max_2_x_time) min_2_x_time = np.linspace(minima_x[-2] - width, minima_x[-2] + width,", "np.cos(omega * ts)] t = np.linspace(0, 150, 1501) XY0 =", "= plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Detrended Fluctuation Analysis Examples') plt.plot(time, time_series, LineWidth=2,", "5.4 length_distance = np.linspace(maxima_y[-1], minima_y[-1], 101) length_distance_time = point_1 *", "min_2_y_side, 'k-') plt.plot(dash_max_min_2_y_time, dash_max_min_2_y, 'k--') plt.text(4.08 * np.pi, -2.2, r'$\\frac{p_2}{2}$')", "c='gray', linestyle='dashed', label=textwrap.fill('Neural network targets', 13)) plt.plot(np.linspace(((time[-202] + time[-201]) /", "emd_utils.Utility(time=time_extended, time_series=time_series_extended) maxima = lsq_signal[lsq_utils.max_bool_func_1st_order_fd()] maxima_time = time[lsq_utils.max_bool_func_1st_order_fd()] maxima_extrapolate =", "EMD # alternate packages from PyEMD import EMD as pyemd0215", "time_series, LineWidth=2, label='Signal') plt.scatter(Huang_max_time, Huang_max, c='magenta', zorder=4, label=textwrap.fill('Huang maximum', 10))", "t = lsq_signal[:neural_network_m] vx = cvx.Variable(int(neural_network_k + 1)) objective =", "np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2, 101),", "200 neural_network_k = 100 # forward -> P = np.zeros((int(neural_network_k", "1 plt.savefig('jss_figures/Duffing_equation_imfs.png') plt.show() hs_ouputs = hilbert_spectrum(t, emd_duff, emd_ht_duff, emd_if_duff, max_frequency=1.3,", "max_discard, c='purple', zorder=4, label=textwrap.fill('Symmetric Discard maxima', 10)) plt.scatter(end_point_time, end_point, c='orange',", "(len(lsq_signal) - 1) + 1 + i_right)] = \\ sum(weights_right", "'k-') plt.plot(length_time, length_bottom, 'k-') plt.plot(length_time_2, length_top_2, 'k-') plt.plot(length_time_2, length_bottom_2, 'k-')", "plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title(textwrap.fill('Plot Demonstrating Unsmoothed Extrema Envelopes if Schoenberg–Whitney Conditions", "length_distance_2, 'k--') plt.plot(length_time, length_top, 'k-') plt.plot(length_time, length_bottom, 'k-') plt.plot(length_time_2, length_top_2,", "axs[2].set_title('IMF 2 and Dynamically Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2, zorder=100)", "ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width * 0.85, box_0.height]) ax.legend(loc='center", "* (len(lsq_signal) - 1) + 1 + i_right + 1)],", "LineWidth=2, label='Time series') plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y,", "2), ('-3', '-2', '-1', '0', '1', '2')) box_0 = ax.get_position()", "1001) knot_demonstrate_time_series = np.sin(knot_demonstrate_time) + np.sin(5 * knot_demonstrate_time) emd =", "ax.pcolormesh(x, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) plt.plot(t[:-1], 0.124 * np.ones_like(t[:-1]),", "plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Duffing Equation using emd 0.3.3',", "minima_x[-1] * np.ones_like(minima_dash) minima_dash_time_3 = slope_based_minimum_time * np.ones_like(minima_dash) minima_line_dash_time =", "* np.cos(0.04 * 2 * np.pi * t), '--', label=r'$0.1$cos$(0.08{\\pi}t)$')", "# compare other packages Duffing - bottom emd_duffing = AdvEMDpy.EMD(time=t,", "max_dash_3 = np.linspace(slope_based_maximum - width, slope_based_maximum + width, 101) dash_3_time", "= np.linspace(0, 150, 1501) XY0 = [1, 1] solution =", "r'$\\pi$', r'2$\\pi$', r'3$\\pi$', r'4$\\pi$', r'5$\\pi$')) plt.yticks((-2, -1, 0, 1, 2),", "min_1_x_time_side = np.linspace(5.4 * np.pi - width, 5.4 * np.pi", "plt.show() # plot 6 t = np.linspace(5, 95, 100) signal_orig", "annual frequency error: {np.round(sum(np.abs(IF - np.ones_like(IF)))[0], 3)}') freq_edges, freq_bins =", "compare other packages Duffing - bottom emd_duffing = AdvEMDpy.EMD(time=t, time_series=x)", "axs[0].plot(time, time_series, label='Time series') axs[0].plot(time, imfs_51[1, :] + imfs_51[2, :]", "Wave Effects Example') plt.plot(time, time_series, LineWidth=2, label='Signal') plt.scatter(Huang_max_time, Huang_max, c='magenta',", "= lsq_signal[int(col + 1):int(col + neural_network_k + 1)] P[-1, col]", "np.pi]) axs[1].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2 and Dynamically Knots') axs[2].plot(knot_demonstrate_time,", "in range(1, len(knots)): axs[i].plot(knots[j] * np.ones(101), np.linspace(-2, 2, 101), '--',", "interpolation filter', 14)) axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.90)[1], c='grey', label=textwrap.fill('Quantile window', 12))", "0 i_right = 0 while ((max_count_right < 1) or (min_count_right", "= np.linspace(point_1 * np.pi - width, point_1 * np.pi +", "anti_max_point, c='green', zorder=4, label=textwrap.fill('Anti-Symmetric maxima', 10)) plt.scatter(no_anchor_max_time, no_anchor_max, c='gray', zorder=4,", "5.2 length_distance_2 = np.linspace(time_series[-1], minima_y[-1], 101) length_distance_time_2 = point_2 *", "zorder=1) plt.xticks((0, 1 * np.pi, 2 * np.pi, 3 *", "plt.plot(end_time, end_signal, 'k-') plt.plot(symmetry_axis_1_time, symmetry_axis, 'r--', zorder=1) plt.plot(anti_symmetric_time, anti_symmetric_signal, 'r--',", "plt.text(4.34 * np.pi, -3.2, r'$\\Delta{t^{min}_{m}}$') plt.text(4.74 * np.pi, -3.2, r'$\\Delta{t^{min}_{m}}$')", "((max_count_left < 1) or (min_count_left < 1)) and (i_left <", "101) minima_dash_time_1 = minima_x[-2] * np.ones_like(minima_dash) minima_dash_time_2 = minima_x[-1] *", "time[-1] + 0.5, 101) anti_symmetric_signal = time_series[-1] * np.ones_like(anti_symmetric_time) ax", "10)) plt.plot(time, minima_envelope, c='darkblue') plt.plot(time, (maxima_envelope + minima_envelope) / 2,", "ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title(textwrap.fill('Plot Demonstrating Unsmoothed Extrema Envelopes if", "hilbert_spectrum from emd_preprocess import Preprocess from emd_mean import Fluctuation from", "maxima_envelope = fluctuation.envelope_basis_function_approximation(knots, 'maxima', smooth=False, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] maxima_envelope_smooth =", "bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_slope_based.png') plt.show() # plot 5 a = 0.25", "0.05, box_1.y0, box_1.width * 0.85, box_1.height]) axs[1].legend(loc='center left', bbox_to_anchor=(1, 0.5),", "ax in axs.flat: if axis == 0: ax.set(ylabel=R'C0$_2$ concentration') if", "* np.pi, 5 * np.pi), (r'4$\\pi$', r'5$\\pi$')) plt.yticks((-3, -2, -1,", "Coughlin_max = Coughlin_wave[Coughlin_max_bool] Coughlin_min_time = Coughlin_time[Coughlin_min_bool] Coughlin_min = Coughlin_wave[Coughlin_min_bool] max_2_x_time", "# plot 3 a = 0.25 width = 0.2 time", "axs[0].set_position([box_0.x0 - 0.06, box_0.y0, box_0.width * 0.85, box_0.height]) axs[0].legend(loc='center left',", "ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width * 0.95, box_0.height]) ax.legend(loc='center", "plt.yticks((-3, -2, -1, 0, 1, 2), ('-3', '-2', '-1', '0',", "label=textwrap.fill('Huang Characteristic Wave', 14)) plt.plot(Coughlin_time, Coughlin_wave, '--', c='darkgreen', label=textwrap.fill('Coughlin Characteristic", "dash_max_min_2_x, 'k--') plt.text(5.16 * np.pi, 0.85, r'$2a_2$') plt.plot(max_2_y_time, max_2_y, 'k-')", "* np.pi, -0.20, r'$s_2$') plt.text(4.30 * np.pi + (minima_x[-1] -", "* np.ones_like(minima_dash) minima_dash_time_3 = slope_based_minimum_time * np.ones_like(minima_dash) minima_line_dash_time = np.linspace(minima_x[-2],", "plt.subplots() figure_size = plt.gcf().get_size_inches() factor = 0.7 plt.gcf().set_size_inches((figure_size[0], factor *", "knot_demonstrate_time_series = np.sin(knot_demonstrate_time) + np.sin(5 * knot_demonstrate_time) emd = EMD(time=knot_demonstrate_time,", "time_series_extended[utils_extended.max_bool_func_1st_order_fd()][-1] maxima_extrapolate_time = time_extended[utils_extended.max_bool_func_1st_order_fd()][-1] minima = lsq_signal[lsq_utils.min_bool_func_1st_order_fd()] minima_time = time[lsq_utils.min_bool_func_1st_order_fd()]", "optimal_maxima, optimal_minima, smooth=False, smoothing_penalty=0.2, edge_effect='none')[0] ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Detrended", "error: {np.round(sum(np.abs(IF[:, 0] - np.ones_like(IF[:, 0]))), 3)}') freq_edges, freq_bins =", "= fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima', smooth=False) max_smoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima', smooth=True) min_unsmoothed", "np.cos(0.04 * 2 * np.pi * t) - emd_duff[2, :])),", "2, 101), '--', c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots[1][0] * np.ones(101),", "- lr * average_gradients # adjustment = - lr *", ">= maxima_x[-2]] - time[time == maxima_x[-2]]) + maxima_x[-1] Huang_wave =", "= utils.max_bool_func_1st_order_fd() anti_max_point_time = time_reflect[anti_max_bool] anti_max_point = time_series_anti_reflect[anti_max_bool] utils =", "A1 * np.cos(2 * np.pi * (1 / P1) *", "plt.plot(CO2_data['month'], CO2_data['decimal date']) plt.title(textwrap.fill('Mean Monthly Concentration of Carbon Dioxide in", "= 81 fig, axs = plt.subplots(2, 1) fig.subplots_adjust(hspace=0.4) figure_size =", "axs[2].set_title('IMF 2 and Statically Optimised Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2,", "emd040.spectra.frequency_transform(py_emd.T, 10, 'hilbert') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 0.2, 100) hht", "-2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1002]) / 2), ((time_extended[-1001]", "-0.7, r'$\\beta$L') plt.text(5.34 * np.pi, -0.05, 'L') plt.scatter(maxima_x, maxima_y, c='r',", "np.pi, 1001) pseudo_alg_time_series = np.sin(pseudo_alg_time) + np.sin(5 * pseudo_alg_time) pseudo_utils", "r'$2\\pi$']) axs[0].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots')", "in knots[:-1]: plt.plot(knot * np.ones(101), np.linspace(-3.0, -2.0, 101), '--', c='grey',", "0.21 width = 0.2 time = np.linspace(0, (5 - a)", "approximation', 15)) plt.plot(t[:-1], 0.04 * np.ones_like(t[:-1]), 'g--', label=textwrap.fill('Driving function frequency',", "Coughlin_wave, '--', c='darkgreen', label=textwrap.fill('Coughlin Characteristic Wave', 14)) plt.plot(max_2_x_time, max_2_x, 'k-')", "- 0.05, box_0.y0, box_0.width * 0.85, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1,", "np.cos(5 * np.linspace((5 - 2.6 * a) * np.pi, (5", "1) fig.subplots_adjust(hspace=0.4) figure_size = plt.gcf().get_size_inches() factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor", "== maxima_x[-2]]) + maxima_y[-1] Coughlin_time = Huang_time Coughlin_wave = A1", "preprocess.winsorize(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize filter', 12)) axs[0].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize interpolation", "np.ones_like(dash_max_min_1_x) max_1_y = np.linspace(maxima_y[-1] - width, maxima_y[-1] + width, 101)", "* np.ones_like(dash_max_min_1_y_time) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Characteristic Wave Effects Example')", "box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_symmetry_anti.png') plt.show() # plot 4", "* np.pi, 101)) + np.cos(5 * np.linspace((5 - 2.6 *", "if axis == 1: ax.set_ylabel(r'$\\gamma_2(t)$') ax.set_yticks([-0.2, 0, 0.2]) box_0 =", "dash_2, 'k--') plt.plot(length_distance_time, length_distance, 'k--') plt.plot(length_distance_time_2, length_distance_2, 'k--') plt.plot(length_time, length_top,", "* np.ones(100), c='gray') plt.plot(np.linspace(((time[-202] + time[-201]) / 2), ((time[-202] +", "plt.plot(t[:-1], 0.124 * np.ones_like(t[:-1]), '--', label=textwrap.fill('Hamiltonian frequency approximation', 15)) plt.plot(t[:-1],", "slope_based_minimum + width, 101) dash_4_time = np.linspace(slope_based_maximum_time, slope_based_minimum_time) dash_4 =", "backward <- P = np.zeros((int(neural_network_k + 1), neural_network_m)) for col", "date'] signal = np.asarray(signal) time = CO2_data['month'] time = np.asarray(time)", "fluctuation.envelope_basis_function_approximation(knots, 'maxima', smooth=True, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] minima_envelope = fluctuation.envelope_basis_function_approximation(knots, 'minima',", "y.max()]) box_0 = ax.get_position() ax.set_position([box_0.x0 + 0.0125, box_0.y0 + 0.075,", "a) * np.pi, (5 - a) * np.pi, 101)) +", "maximum', 11)) plt.scatter(slope_based_minimum_time, slope_based_minimum, c='purple', zorder=4, label=textwrap.fill('Slope-based minimum', 11)) plt.scatter(improved_slope_based_maximum_time,", "* np.ones_like(x_hs[0, :]), '--', label=r'$\\omega = 4$', Linewidth=3) ax.plot(x_hs[0, :],", "emd_utils import time_extension, Utility from scipy.interpolate import CubicSpline from emd_hilbert", "fig, axs = plt.subplots(2, 1) plt.subplots_adjust(hspace=0.3) figure_size = plt.gcf().get_size_inches() factor", "r'$\\Delta{t^{max}_{M}}$') plt.text(4.30 * np.pi, 0.35, r'$s_1$') plt.text(4.43 * np.pi, -0.20,", "axs[0].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].plot(time, time_series, label='Time series') axs[1].plot(time,", "[r'$ \\tau_0 $', r'$ \\tau_1 $']) plt.xlim(4.4, 6.6) plt.plot(5 *", "# \\/ import random import textwrap import emd_mean import AdvEMDpy", "of CO$_{2}$ Concentration using AdvEMDpy', 40)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)')", "np.pi, 2 * np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].plot(preprocess_time, preprocess_time_series, label='x(t)')", "+ 1 - t), 2)) # linear activation function is", "emd_utils.Utility(time=time_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))], time_series=time_series_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))])", "edge_effect='none', spline_method='b_spline')[0] minima_envelope = fluctuation.envelope_basis_function_approximation(knots, 'minima', smooth=False, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0]", "freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(time, np.ones_like(time), 'k--', label=textwrap.fill('Annual cycle',", "'k--') axs[2].plot(1.55 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--',", "c='grey', label='Knots') axs[2].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey',", "0].plot(time, imfs[1, :]) axs[1, 1].plot(time, imfs[2, :]) axis = 0", "101) max_discard_dash = max_discard * np.ones_like(max_discard_dash_time) dash_2_time = np.linspace(minima_x[-1], max_discard_time,", "* np.ones_like(length_time_2) symmetry_axis_1_time = minima_x[-1] * np.ones(101) symmetry_axis_2_time = time[-1]", "'k-') plt.plot(dash_max_min_1_y_time, dash_max_min_1_y, 'k--') plt.text(4.48 * np.pi, -2.5, r'$\\frac{p_1}{2}$') plt.xlim(3.9", "* np.ones_like(maxima_dash) maxima_dash_time_2 = maxima_x[-1] * np.ones_like(maxima_dash) maxima_dash_time_3 = slope_based_maximum_time", "Region', 40)) plt.subplots_adjust(hspace=0.1) axs[0].plot(time, time_series, label='Time series') axs[0].plot(time, imfs_51[1, :]", "plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time) + 1, '--', c='r', label=r'$\\tilde{h}_{(1,0)}^M(t)$', zorder=4) plt.scatter(pseudo_alg_time[pseudo_utils.min_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.min_bool_func_1st_order_fd()],", "sum(emd_utils_max.max_bool_func_1st_order_fd()) > 0: max_count_left += 1 emd_utils_min = \\ emd_utils.Utility(time=time_extended[int(len(lsq_signal)", "* np.pi, -3.2, r'$\\Delta{t^{min}_{m}}$') plt.text(4.12 * np.pi, 2, r'$\\Delta{t^{max}_{M}}$') plt.text(4.50", "= np.linspace(0, 5 * np.pi, 11) imfs_11, hts_11, ifs_11 =", "label=textwrap.fill('Symmetric Anchor maxima', 10)) plt.scatter(anti_max_point_time, anti_max_point, c='green', zorder=4, label=textwrap.fill('Anti-Symmetric maxima',", "4 * np.pi, 5 * np.pi), (r'$0$', r'$\\pi$', r'2$\\pi$', r'3$\\pi$',", "cmap='gist_rainbow', vmin=z_min, vmax=z_max) ax.plot(x_hs[0, :], 8 * np.ones_like(x_hs[0, :]), '--',", "min_unsmoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima', smooth=False) min_smoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima', smooth=True)", "CO2_data = pd.read_csv('Data/co2_mm_mlo.csv', header=51) plt.plot(CO2_data['month'], CO2_data['decimal date']) plt.title(textwrap.fill('Mean Monthly Concentration", "1') axs[0].plot(time, b_spline_basis[3, :].T, '--', label='Basis 2') axs[0].plot(time, b_spline_basis[4, :].T,", "* np.pi, 3 * np.pi, 4 * np.pi]) ax.set_xticklabels(['$0$', r'$\\pi$',", "- 1) + 1 + i_right + 1)]) if sum(emd_utils_max.max_bool_func_1st_order_fd())", "np.pi), (r'$0$', r'$\\pi$', r'2$\\pi$', r'3$\\pi$', r'4$\\pi$', r'5$\\pi$')) plt.yticks((-2, -1, 0,", "np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1, label='Knots') axs[0].set_xticks([0, np.pi,", "0.5)) plt.savefig('jss_figures/CO2_Hilbert_emd.png') plt.show() # compare other packages Carbon Dioxide -", "axs = plt.subplots(2, 1) fig.subplots_adjust(hspace=0.4) figure_size = plt.gcf().get_size_inches() factor =", "- minima_x[-2]), 0.35 + (minima_y[-1] - minima_y[-2]), r'$s_1$') plt.text(4.43 *", "time[lsq_utils.min_bool_func_1st_order_fd()] minima_extrapolate = time_series_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] minima_extrapolate_time = time_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] ax = plt.subplot(111)", "= slope_based_minimum_time improved_slope_based_minimum = improved_slope_based_maximum + s2 * (improved_slope_based_minimum_time -", "axs = plt.subplots(1, 2, sharey=True) axs[0].set_title('Cubic B-Spline Bases') axs[0].plot(time, b_spline_basis[2,", "Schoenberg–Whitney Conditions are Not Satisfied', 50)) plt.plot(time, time_series, label='Time series',", "3 with 51 knots', 21)) for knot in knots_51: axs[0].plot(knot", "max_2_x = maxima_y[-2] * np.ones_like(max_2_x_time) min_2_x_time = np.linspace(minima_x[-2] - width,", "- width, -1.8 + width, 101) min_2_y_time = minima_x[-2] *", "5.3 * np.pi * np.ones_like(dash_max_min_2_x) max_2_y = np.linspace(maxima_y[-2] - width,", "minima_envelope_smooth, c='darkred') plt.plot(time, (maxima_envelope_smooth + minima_envelope_smooth) / 2, c='darkred') plt.plot(time,", "import seaborn as sns import matplotlib.pyplot as plt from scipy.integrate", "emd040.spectra.frequency_transform(emd_sift, 10, 'hilbert') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 0.2, 100) hht", "1 + i_right + 1)]) if sum(emd_utils_min.min_bool_func_1st_order_fd()) > 0: min_count_right", "plt.plot(symmetry_axis_2_time, symmetry_axis, 'r--', label=textwrap.fill('Axes of symmetry', 10), zorder=1) plt.text(5.1 *", "0.5)) plt.savefig('jss_figures/detrended_fluctuation_analysis.png') plt.show() # Duffing Equation Example def duffing_equation(xy, ts):", "\\tau_k $', r'$ \\tau_{k+1} $']) axs[1].set_xlim(4.5, 6.5) plt.savefig('jss_figures/comparing_bases.png') plt.show() #", "'k--') plt.text(4.48 * np.pi, -2.5, r'$\\frac{p_1}{2}$') plt.xlim(3.9 * np.pi, 5.6", "max_count_left += 1 emd_utils_min = \\ emd_utils.Utility(time=time_extended[int(len(lsq_signal) - 1 -", "= maxima_y[-1] * np.ones_like(max_dash_time) min_dash_time = np.linspace(minima_x[-1] - width, minima_x[-1]", "10)) plt.plot(time, minima_envelope_smooth, c='darkred') plt.plot(time, (maxima_envelope_smooth + minima_envelope_smooth) / 2,", "0.3.3', 45)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)') plt.pcolormesh(time, freq_bins, hht, cmap='gist_rainbow',", "axs[2].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[2].set_ylim(-5.5, 5.5) axs[2].set_xlim(0.95 * np.pi,", "maxima_x[-1] + minima_x[-1] max_discard_dash_time = np.linspace(max_discard_time - width, max_discard_time +", "Region') axs[0].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[0].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time", "= slope_based_minimum_time * np.ones_like(minima_dash) minima_line_dash_time = np.linspace(minima_x[-2], slope_based_minimum_time, 101) minima_line_dash", "'--', c='c', label=r'$\\tilde{h}_{(1,0)}^m(t)$', zorder=5) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time), '--', c='purple', label=r'$\\tilde{h}_{(1,0)}^{\\mu}(t)$', zorder=5)", "101), -5.5 * np.ones(101), 'k--') axs[0].plot(0.95 * np.pi * np.ones(101),", "width, minima_y[-1] + width, 101) min_dash_2 = np.linspace(minima_y[-2] - width,", "Huang_min_time = Huang_time[Huang_min_bool] Huang_min = Huang_wave[Huang_min_bool] Coughlin_max_time = Coughlin_time[Coughlin_max_bool] Coughlin_max", "np.pi, 1.55 * np.pi, 101), 5.5 * np.ones(101), 'k--') axs[0].plot(np.linspace(0.95", "10)) plt.plot(time, maxima_envelope, c='darkblue', label=textwrap.fill('EMD envelope', 10)) plt.plot(time, minima_envelope, c='darkblue')", "= advemdpy.empirical_mode_decomposition(knots=knots_31, max_imfs=2, edge_effect='symmetric_anchor', verbose=False)[:3] knots_11 = np.linspace(0, 5 *", "width = 0.2 time = np.linspace(0, (5 - a) *", "plt.scatter(Huang_min_time, Huang_min, c='lime', zorder=4, label=textwrap.fill('Huang minimum', 10)) plt.scatter(Coughlin_max_time, Coughlin_max, c='darkorange',", "a = 0.25 width = 0.2 time = np.linspace((0 +", "zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.scatter(slope_based_maximum_time, slope_based_maximum, c='orange',", "EEMD_maxima_envelope = fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'maxima', optimal_maxima, optimal_minima, smooth=False, smoothing_penalty=0.2, edge_effect='none')[0] EEMD_minima_envelope", "3, 101), '--', c='black') axs[0].plot(1.15 * np.pi * np.ones(101), np.linspace(-3,", "time_series, label='Time series') axs[0].plot(time, imfs_51[1, :] + imfs_51[2, :] +", "slope-based maximum', 11)) plt.scatter(improved_slope_based_minimum_time, improved_slope_based_minimum, c='dodgerblue', zorder=4, label=textwrap.fill('Improved slope-based minimum',", "+ neural_network_k - col)):(-(neural_network_m - col))] P[-1, col] = 1", "i_right + 1)]) if sum(emd_utils_min.min_bool_func_1st_order_fd()) > 0: min_count_right += 1", "ifs_51 = advemdpy.empirical_mode_decomposition(knots=knots_51, max_imfs=3, edge_effect='symmetric_anchor', verbose=False)[:3] knots_31 = np.linspace(0, 5", "axis == 1: ax.set_ylabel(r'$ \\dfrac{dx(t)}{dt} $') ax.set(xlabel='t') ax.set_yticks(y_points_2) ax.set_xticks(x_points) ax.set_xticklabels(x_names)", "'']) box_1 = axs[1].get_position() axs[1].set_position([box_1.x0 - 0.05, box_1.y0, box_1.width *", "np.zeros_like(time_extended) / 0 time_series_extended[int(len(lsq_signal) - 1):int(2 * (len(lsq_signal) - 1)", "0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Schoenberg_Whitney_Conditions.png') plt.show() # plot", "point_2 = 5.2 length_distance_2 = np.linspace(time_series[-1], minima_y[-1], 101) length_distance_time_2 =", "4') axs[0].legend(loc='upper left') axs[0].plot(5 * np.ones(100), np.linspace(-0.2, 0.8, 100), 'k-')", "np.sin(5 * knot_demonstrate_time) emd = EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series) imfs, _, _,", "r'$3\\pi$', r'$4\\pi$']) plt.ylabel(r'Frequency (rad.s$^{-1}$)') plt.xlabel('Time (s)') box_0 = ax.get_position() ax.set_position([box_0.x0,", "+ width, 101) max_1_x_time_side = np.linspace(5.4 * np.pi - width,", "b_spline_basis[2, 500:].T, '--', label=r'$ B_{-3,4}(t) $') plt.plot(time[500:], b_spline_basis[3, 500:].T, '--',", "* np.pi]) axs[0].set_xticklabels(['', '', '', '', '', '']) box_0 =", "= np.mean(gradients, axis=1) # steepest descent max_gradient_vector = average_gradients *", "minima_envelope_smooth) / 2, c='darkred') plt.plot(time, EEMD_maxima_envelope, c='darkgreen', label=textwrap.fill('EEMD envelope', 10))", "Examples') plt.plot(time, time_series, LineWidth=2, label='Time series') plt.scatter(maxima_x, maxima_y, c='r', zorder=4,", "np.pi, -3.2, r'$\\Delta{t^{min}_{m}}$') plt.text(4.12 * np.pi, 2, r'$\\Delta{t^{max}_{M}}$') plt.text(4.50 *", "* t / 50) + 0.6 * np.cos(2 * np.pi", "minima_envelope, c='darkblue') plt.plot(time, (maxima_envelope + minima_envelope) / 2, c='darkblue') plt.plot(time,", "* (- train_input) # guess average gradients average_gradients = np.mean(gradients,", "'-1', '0', '1', '2')) box_0 = ax.get_position() ax.set_position([box_0.x0 - 0.05,", "seed_weights = np.ones(neural_network_k) / neural_network_k weights = 0 * seed_weights.copy()", "compare other packages Carbon Dioxide - top pyemd = pyemd0215()", "min_2_x = minima_y[-2] * np.ones_like(min_2_x_time) dash_max_min_2_x = np.linspace(minima_y[-2], maxima_y[-2], 101)", "0.75, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht.png') plt.show()", "== 0: ax.set_ylabel(r'$\\gamma_1(t)$') ax.set_yticks([-2, 0, 2]) if axis == 1:", "101), -5.5 * np.ones(101), 'k--') axs[1].plot(0.95 * np.pi * np.ones(101),", "optimise_knots=1, verbose=False) fig, axs = plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time", "= np.r_[False, utils.derivative_forward_diff() > 0, False] & \\ np.r_[utils.zero_crossing() ==", "maxima_x[-2], 101) dash_max_min_2_y = -1.8 * np.ones_like(dash_max_min_2_y_time) max_1_x_time = np.linspace(maxima_x[-1]", "additive constant t = lsq_signal[-neural_network_m:] # test - top seed_weights", "= np.linspace(5, 95, 100) signal_orig = np.cos(2 * np.pi *", "or (min_count_right < 1)) and (i_right < len(lsq_signal) - 1):", "'--', c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots[0] * np.ones(101), np.linspace(-2, 2,", "axs[0].set_position([box_0.x0 - 0.05, box_0.y0, box_0.width * 0.85, box_0.height]) axs[0].legend(loc='center left',", "maxima_y[-1] Coughlin_time = Huang_time Coughlin_wave = A1 * np.cos(2 *", "minima_x[-2]) Average_min = (minima_y[-2] + minima_y[-1]) / 2 utils_Huang =", "np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots_uniform[0]", "0.05, box_0.y0, box_0.width * 0.95, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))", "j in range(1, len(knots_uniform)): axs[i].plot(knots_uniform[j] * np.ones(101), np.linspace(-2, 2, 101),", "plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Statically Optimised Knots')", ":], 4 * np.ones_like(x_hs[0, :]), '--', label=r'$\\omega = 4$', Linewidth=3)", "ax.get_position() ax.set_position([box_0.x0, box_0.y0 + 0.05, box_0.width * 0.85, box_0.height *", "np.pi - width, point_1 * np.pi + width, 101) length_top", "minima_y[-2], 101) s1 = (minima_y[-2] - maxima_y[-1]) / (minima_x[-2] -", "c='orange', zorder=4, label=textwrap.fill('Slope-based maximum', 11)) plt.scatter(slope_based_minimum_time, slope_based_minimum, c='purple', zorder=4, label=textwrap.fill('Slope-based", "smooth=True) util = Utility(time=time, time_series=time_series) maxima = util.max_bool_func_1st_order_fd() minima =", "minimum', 14)) plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b',", "plt.show() plt.show() emd_sift = emd040.sift.sift(x) IP, IF, IA = emd040.spectra.frequency_transform(emd_sift,", "11)) plt.scatter(improved_slope_based_minimum_time, improved_slope_based_minimum, c='dodgerblue', zorder=4, label=textwrap.fill('Improved slope-based minimum', 11)) plt.xlim(3.9", "'k-') plt.plot(length_time_2, length_bottom_2, 'k-') plt.plot(end_time, end_signal, 'k-') plt.plot(symmetry_axis_1_time, symmetry_axis, 'r--',", "preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott smoothing', 12)) axs[0].plot(preprocess_time, preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker smoothing', 13)) downsampled_and_decimated", "Duffing Equation using emd 0.3.3', 40)) plt.pcolormesh(t, freq_bins, hht, cmap='gist_rainbow',", "- minima_y[-1]), r'$s_2$') plt.plot(minima_line_dash_time, minima_line_dash, 'k--') plt.plot(maxima_line_dash_time, maxima_line_dash, 'k--') plt.plot(dash_1_time,", "np.linspace(-0.2, 1.2, 100), 'k-') plt.legend(loc='upper left') plt.savefig('jss_figures/boundary_bases.png') plt.show() # plot", "axs[1].set_xticklabels(labels=[r'$\\pi$']) box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.05, box_0.y0, box_0.width *", "(maxima_envelope_smooth + minima_envelope_smooth) / 2, c='darkred') plt.plot(time, EEMD_maxima_envelope, c='darkgreen', label=textwrap.fill('EEMD", "- (imfs_31[1, :] + imfs_31[2, :])), 3)}') for knot in", "time_extended[-1002]) / 2) * np.ones(100), np.linspace(-2.75, 2.75, 100), c='k') plt.plot(((time[-202]", "dxdt = solution[:, 1] x_points = [0, 50, 100, 150]", ":], label='AdvEMDpy') print(f'AdvEMDpy driving function error: {np.round(sum(abs(0.1 * np.cos(0.04 *", "0.1, len(preprocess_time)) for i in random.sample(range(1000), 500): preprocess_time_series[i] += np.random.normal(0,", "- 0.1, 100), 2.75 * np.ones(100), c='gray') plt.plot(((time_extended[-1001] + time_extended[-1000])", "np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1) axs[0].plot(knot * np.ones(101),", "np.linspace((5 - a) * np.pi, (5 + a) * np.pi,", "1001) knots = np.linspace((0 + a) * np.pi, (5 -", "= np.linspace(slope_based_maximum, slope_based_minimum) maxima_dash = np.linspace(2.5 - width, 2.5 +", "figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess Smoothing Demonstration') axs[1].set_title('Zoomed Region') axs[0].plot(preprocess_time, preprocess_time_series, label='x(t)')", "anti_symmetric_time = np.linspace(time[-1] - 0.5, time[-1] + 0.5, 101) anti_symmetric_signal", "= \\ emd_utils.Utility(time=time_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))], time_series=time_series_extended[int(len(lsq_signal) - 1", "r'$\\frac{3}{2}\\pi$']) box_2 = axs[2].get_position() axs[2].set_position([box_2.x0 - 0.05, box_2.y0, box_2.width *", "+ imfs_51[3, :])), 3)}') for knot in knots_51: axs[0].plot(knot *", "label='True mean') plt.xticks((0, 1 * np.pi, 2 * np.pi, 3", "0, 0.2]) box_0 = ax.get_position() ax.set_position([box_0.x0, box_0.y0, box_0.width * 0.85,", "= pyemd0215() py_emd = pyemd(signal) IP, IF, IA = emd040.spectra.frequency_transform(py_emd[:2,", "ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Schoenberg_Whitney_Conditions.png') plt.show() # plot 7 a", "axis += 1 plt.savefig('jss_figures/Duffing_equation.png') plt.show() # compare other packages Duffing", "min_dash_time_4 = improved_slope_based_minimum_time * np.ones_like(min_dash_4) dash_final_time = np.linspace(improved_slope_based_maximum_time, improved_slope_based_minimum_time, 101)", "_, _ = emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=1, verbose=False) fig, axs = plt.subplots(3,", "= 0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess Filtering Demonstration')", "np.ones(100), c='gray') plt.plot(np.linspace(((time[-202] + time[-201]) / 2), ((time[-202] + time[-201])", "+ minima_envelope) / 2, c='darkblue') plt.plot(time, maxima_envelope_smooth, c='darkred', label=textwrap.fill('SEMD envelope',", "Carbon Dioxide - bottom knots = np.linspace(time[0], time[-1], 200) emd_example", "EMD as pyemd0215 import emd as emd040 sns.set(style='darkgrid') pseudo_alg_time =", "minima_x[-1]] = 1.5 * (time_series[time >= minima_x[-1]] - time_series[time ==", "of Carbon Dioxide in the Atmosphere', 35)) plt.ylabel('Parts per million')", "12)) axs[0].plot(preprocess_time, preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median filter', 13)) axs[0].plot(preprocess_time, preprocess.winsorize(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize", "plot 6 t = np.linspace(5, 95, 100) signal_orig = np.cos(2", "min_2_y_time = minima_x[-2] * np.ones_like(min_2_y) dash_max_min_2_y_time = np.linspace(minima_x[-2], maxima_x[-2], 101)", "= time_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Single Neuron Neural Network", "'', '', '', '', '']) box_1 = axs[1].get_position() axs[1].set_position([box_1.x0 -", "axs[1].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[1].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1],", "return [xy[1], xy[0] - epsilon * xy[0] ** 3 +", "(minima_y[-1] - maxima_y[-1]) / (minima_x[-1] - maxima_x[-1]) slope_based_minimum_time = minima_x[-1]", "plt.plot(time, minima_envelope_smooth, c='darkred') plt.plot(time, (maxima_envelope_smooth + minima_envelope_smooth) / 2, c='darkred')", "width, slope_based_minimum + width, 101) dash_4_time = np.linspace(slope_based_maximum_time, slope_based_minimum_time) dash_4", "a) * np.pi, 101) time_series_reflect = np.flip(np.cos(np.linspace((5 - 2.6 *", "3 with 51 knots', 21)) print(f'DFA fluctuation with 51 knots:", "fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Dynamically Optimised Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series,", "Added Noise', 50)) x_hs, y, z = hs_ouputs z_min, z_max", "np.linspace(5, 95, 100) signal_orig = np.cos(2 * np.pi * t", "in range(neural_network_m): P[:-1, col] = lsq_signal[int(col + 1):int(col + neural_network_k", "minima envelope', 10), c='cyan') plt.plot(time, min_smoothed[0], label=textwrap.fill('Smoothed minima envelope', 10),", "time_series_anti_reflect[:51], '--', c='purple', LineWidth=2, label=textwrap.fill('Anti-symmetric signal', 10)) plt.plot(max_dash_time, max_dash, 'k-')", "+ np.random.normal(0, 0.1, len(preprocess_time)) for i in random.sample(range(1000), 500): preprocess_time_series[i]", "101) dash_2 = np.linspace(maxima_y[-1], minima_y[-2], 101) s1 = (minima_y[-2] -", "emd as emd040 sns.set(style='darkgrid') pseudo_alg_time = np.linspace(0, 2 * np.pi,", "0.85, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_slope_based.png') plt.show() # plot", "15)) plt.plot(t[:-1], 0.04 * np.ones_like(t[:-1]), 'g--', label=textwrap.fill('Driving function frequency', 15))", "'--', c='black') axs[0].plot(0.85 * np.pi * np.ones(101), np.linspace(-3, 3, 101),", "$') ax.set(xlabel='t') ax.set_yticks(y_points_2) ax.set_xticks(x_points) ax.set_xticklabels(x_names) axis += 1 plt.savefig('jss_figures/Duffing_equation.png') plt.show()", "cvxpy as cvx import seaborn as sns import matplotlib.pyplot as", "1), neural_network_m)) for col in range(neural_network_m): P[:-1, col] = lsq_signal[(-(neural_network_m", "plt.title('First Iteration of Sifting Algorithm') plt.plot(pseudo_alg_time, pseudo_alg_time_series, label=r'$h_{(1,0)}(t)$', zorder=1) plt.scatter(pseudo_alg_time[pseudo_utils.max_bool_func_1st_order_fd()],", "plt.plot(minima_line_dash_time, minima_line_dash, 'k--') plt.plot(maxima_line_dash_time, maxima_line_dash, 'k--') plt.plot(dash_1_time, dash_1, 'k--') plt.plot(dash_2_time,", "+ 1 + i_right)], 1))) i_right += 1 if i_right", "dxdt) axs[1].set_title('Duffing Equation Velocity') axs[1].set_ylim([-1.5, 1.5]) axs[1].set_xlim([0, 150]) axis =", "* np.pi, 1.55 * np.pi) axs[2].plot(time, time_series, label='Time series') axs[2].plot(time,", "axs[1].set_title('Cubic Hermite Spline Bases') axs[1].plot(time, chsi_basis[10, :].T, '--') axs[1].plot(time, chsi_basis[11,", "ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/pseudo_algorithm.png') plt.show() knots = np.arange(12) time", "* 0.85, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) ax.set_xticks(x_points) ax.set_xticklabels(x_names)", "* np.ones_like(length_distance) length_time = np.linspace(point_1 * np.pi - width, point_1", "45)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)') plt.pcolormesh(time, freq_bins, hht, cmap='gist_rainbow', vmin=0,", "* np.ones(101), '--', c='black', label=textwrap.fill('Zoomed region', 10)) axs[0].plot(np.linspace(0.85 * np.pi,", "label='Minima') plt.scatter(max_discard_time, max_discard, c='purple', zorder=4, label=textwrap.fill('Symmetric Discard maxima', 10)) plt.scatter(end_point_time,", "minima_dash_time_3 = slope_based_minimum_time * np.ones_like(minima_dash) minima_line_dash_time = np.linspace(minima_x[-2], slope_based_minimum_time, 101)", "with 31 knots') axs[2].plot(time, imfs_51[3, :], label='IMF 3 with 51", "axs[0, 1].plot(time, imfs[0, :], label='Smoothed') axs[0, 1].legend(loc='lower right') axs[1, 0].plot(time,", "neural_network_m)) for col in range(neural_network_m): P[:-1, col] = lsq_signal[int(col +", "box_0.width * 0.85, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) ax.set_xticks(x_points)", "axs[1].plot(time, time_series, label='Time series') axs[1].plot(time, imfs_31[1, :] + imfs_31[2, :],", "+ 1)]) if sum(emd_utils_min.min_bool_func_1st_order_fd()) > 0: min_count_right += 1 #", "minima_x[-2]) P1 = 2 * np.abs(maxima_x[-1] - minima_x[-1]) Huang_time =", "pyemd0215 import emd as emd040 sns.set(style='darkgrid') pseudo_alg_time = np.linspace(0, 2", "LineWidth=2, label='Signal') plt.title('Slope-Based Edge Effects Example') plt.plot(max_dash_time_1, max_dash_1, 'k-') plt.plot(max_dash_time_2,", "for ax in axs.flat: ax.label_outer() if axis == 0: ax.set_ylabel('x(t)')", "* np.ones(100), np.linspace(-0.2, 0.8, 100), 'k-') axs[0].plot(6 * np.ones(100), np.linspace(-0.2,", "np.pi + width, 101) min_2_x = minima_y[-2] * np.ones_like(min_2_x_time) dash_max_min_2_x", "max_discard = maxima_y[-1] max_discard_time = minima_x[-1] - maxima_x[-1] + minima_x[-1]", "plt.plot(((time[-202] + time[-201]) / 2) * np.ones(100), np.linspace(-2.75, 2.75, 100),", "2) - 0.1, 100), 2.75 * np.ones(100), c='k') plt.plot(((time_extended[-1001] +", "pyemd(signal) IP, IF, IA = emd040.spectra.frequency_transform(py_emd[:2, :].T, 12, 'hilbert') print(f'PyEMD", "* np.pi - width, 5.3 * np.pi + width, 101)", "101) dash_3_time = np.linspace(minima_x[-1], slope_based_maximum_time, 101) dash_3 = np.linspace(minima_y[-1], slope_based_maximum,", "+ 1)]) if sum(emd_utils_max.max_bool_func_1st_order_fd()) > 0: max_count_right += 1 emd_utils_min", "= np.arange(12) time = np.linspace(0, 11, 1101) basis = emd_basis.Basis(time=time,", "* np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--') axs[1].plot(1.55 *", "utils.min_bool_func_1st_order_fd() minima_x = time[min_bool] minima_y = time_series[min_bool] max_dash_time = np.linspace(maxima_x[-1]", "min_2_x_time_side = np.linspace(5.3 * np.pi - width, 5.3 * np.pi", "left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_symmetry_anti.png') plt.show() # plot 4 a =", "minima_y[-2] + width, 101) min_2_y_side = np.linspace(-1.8 - width, -1.8", "Filtered Hilbert Spectrum of Duffing Equation using AdvEMDpy', 40)) x,", "np.linspace(maxima_x[-1], minima_x[-1], 101) dash_1 = np.linspace(maxima_y[-1], minima_y[-1], 101) max_discard =", "6]) axs[0].set_xticklabels([r'$ \\tau_k $', r'$ \\tau_{k+1} $']) axs[0].set_xlim(4.5, 6.5) axs[1].set_title('Cubic", "label='Zoomed region') axs[2].plot(time, time_series, label='Time series') axs[2].plot(time, imfs_11[1, :], label='IMF", "11, 1101) basis = emd_basis.Basis(time=time, time_series=time) b_spline_basis = basis.cubic_b_spline(knots) chsi_basis", "envelope', 10)) plt.plot(time, minima_envelope_smooth, c='darkred') plt.plot(time, (maxima_envelope_smooth + minima_envelope_smooth) /", "* np.pi, 1.15 * np.pi, 101), -3 * np.ones(101), '--',", "P = np.zeros((int(neural_network_k + 1), neural_network_m)) for col in range(neural_network_m):", "derivative_of_lsq = utils.derivative_forward_diff() derivative_time = time[:-1] derivative_knots = np.linspace(knots[0], knots[-1],", "'--', c='grey') plt.savefig('jss_figures/knot_1.png') plt.show() # plot 1c - addition knot_demonstrate_time", "emd 0.3.3', 45)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)') plt.pcolormesh(time, freq_bins, hht,", "if sum(emd_utils_max.max_bool_func_1st_order_fd()) > 0: max_count_left += 1 emd_utils_min = \\", "EEMD_minima_envelope = fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'minima', optimal_maxima, optimal_minima, smooth=False, smoothing_penalty=0.2, edge_effect='none')[0] ax", "'--', label='Basis 3') axs[0].plot(time, b_spline_basis[5, :].T, '--', label='Basis 4') axs[0].legend(loc='upper", "plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Duffing", "- addition knot_demonstrate_time = np.linspace(0, 2 * np.pi, 1001) knot_demonstrate_time_series", "ax.set(ylabel=R'C0$_2$ concentration') if axis == 1: pass if axis ==", "box_1.height]) axs[1].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].plot(np.linspace(0.95 * np.pi, 1.55", "verbose=False)[:3] fig, axs = plt.subplots(3, 1) plt.suptitle(textwrap.fill('Comparison of Trends Extracted", "imfs_51[3, :], label=textwrap.fill('Sum of IMF 1, IMF 2, & IMF", "= maxima_y[-1] * np.ones_like(max_1_x_time) min_1_x_time = np.linspace(minima_x[-1] - width, minima_x[-1]", "vmax=z_max) ax.set_title(textwrap.fill(r'Gaussian Filtered Hilbert Spectrum of CO$_{2}$ Concentration using AdvEMDpy',", "axs[1].set_yticks(ticks=[-2, 0, 2]) axs[1].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[1].set_xticklabels(labels=['0', r'$\\pi$',", "0.5), fontsize=8) axs[2].set_ylim(-5.5, 5.5) axs[2].set_xlim(0.95 * np.pi, 1.55 * np.pi)", "time_series[minima], c='b', label='Minima', zorder=10) plt.plot(time, max_unsmoothed[0], label=textwrap.fill('Unsmoothed maxima envelope', 10),", "_ = emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=1, verbose=False) fig, axs = plt.subplots(3, 1)", "5.3 * np.pi + width, 101) min_2_x = minima_y[-2] *", "fontsize=8) axs[1].set_ylim(-5.5, 5.5) axs[1].set_xlim(0.95 * np.pi, 1.55 * np.pi) axs[2].plot(time,", ":].T, '--') axs[1].plot(time, chsi_basis[13, :].T, '--') axs[1].plot(5 * np.ones(100), np.linspace(-0.2,", "* np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[0].legend(loc='lower left')", "_, _, _, knots, _, _ = emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=2, verbose=False)", "slope_based_maximum_time * np.ones_like(maxima_dash) maxima_line_dash_time = np.linspace(maxima_x[-2], slope_based_maximum_time, 101) maxima_line_dash =", "13)) axs[1].plot(downsampled[0], downsampled[1], label=textwrap.fill('Downsampled', 13)) axs[1].set_xlim(0.85 * np.pi, 1.15 *", "plot 1e - addition fig, axs = plt.subplots(2, 1) fig.subplots_adjust(hspace=0.4)", "- 0.06, box_1.y0, box_1.width * 0.85, box_1.height]) plt.savefig('jss_figures/preprocess_smooth.png') plt.show() #", "0.06, box_0.y0, box_0.width * 0.85, box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, -0.15))", "plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.scatter(slope_based_maximum_time, slope_based_maximum, c='orange', zorder=4, label=textwrap.fill('Slope-based", "* np.ones(100), np.linspace(-2.75, 2.75, 100), c='k') plt.plot(((time[-202] + time[-201]) /", "lsq_signal[-neural_network_m:] # test - top seed_weights = np.ones(neural_network_k) / neural_network_k", "zorder=1) plt.plot(anti_symmetric_time, anti_symmetric_signal, 'r--', zorder=1) plt.plot(symmetry_axis_2_time, symmetry_axis, 'r--', label=textwrap.fill('Axes of", "/ 2) - 0.1, 100), -2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time_extended[-1001]", "_, _, _, _ = emd_duffing.empirical_mode_decomposition(verbose=False) fig, axs = plt.subplots(2,", "= lsq_signal neural_network_m = 200 neural_network_k = 100 # forward", "slope_based_minimum_time improved_slope_based_minimum = improved_slope_based_maximum + s2 * (improved_slope_based_minimum_time - improved_slope_based_maximum_time)", "np.ones(100), c='gray') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1000]) / 2), ((time_extended[-1001] + time_extended[-1000])", "extrema_type='maxima', smooth=False) max_smoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima', smooth=True) min_unsmoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots,", "width, 101) max_1_y_time = maxima_x[-1] * np.ones_like(max_1_y) min_1_y = np.linspace(minima_y[-1]", "label=textwrap.fill('SEMD envelope', 10)) plt.plot(time, minima_envelope_smooth, c='darkred') plt.plot(time, (maxima_envelope_smooth + minima_envelope_smooth)", "left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Schoenberg_Whitney_Conditions.png') plt.show() # plot 7 a =", "maxima_x = time[max_bool] maxima_y = time_series[max_bool] min_bool = utils.min_bool_func_1st_order_fd() minima_x", "* time) utils = emd_utils.Utility(time=time, time_series=time_series) max_bool = utils.max_bool_func_1st_order_fd() maxima_x", "= 0 while ((max_count_left < 1) or (min_count_left < 1))", "axs[1].plot(t, emd_sift[:, 1], '--', label='emd 0.3.3') print(f'emd driving function error:", "import numpy as np import pandas as pd import cvxpy", "Huang_time[Huang_min_bool] Huang_min = Huang_wave[Huang_min_bool] Coughlin_max_time = Coughlin_time[Coughlin_max_bool] Coughlin_max = Coughlin_wave[Coughlin_max_bool]", "c='darkblue') plt.plot(time, (maxima_envelope + minima_envelope) / 2, c='darkblue') plt.plot(time, maxima_envelope_smooth,", "2 * np.pi * t) - emd_duff[2, :])), 3)}') axs[1].plot(t,", "np.ones_like(anti_symmetric_time) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time, time_series, LineWidth=2, label='Signal') plt.title('Symmetry", "np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots[0][0] * np.ones(101), np.linspace(-2, 2, 101),", "c='grey', label='Knots') for i in range(3): for j in range(1,", "* np.ones_like(end_time) anti_symmetric_time = np.linspace(time[-1] - 0.5, time[-1] + 0.5,", "2, 100) hht = emd040.spectra.hilberthuang(IF, IA, freq_edges) hht = gaussian_filter(hht,", "y_points_2 = [-1, 0, 1] fig, axs = plt.subplots(2, 1)", "derivative_time = time[:-1] derivative_knots = np.linspace(knots[0], knots[-1], 31) # change", "12)) axs[1].plot(preprocess_time, preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott smoothing', 12)) axs[1].plot(preprocess_time, preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker smoothing',", "= Huang_time Coughlin_wave = A1 * np.cos(2 * np.pi *", "r'$4\\pi$']) plt.ylabel(r'Frequency (rad.s$^{-1}$)') plt.xlabel('Time (s)') box_0 = ax.get_position() ax.set_position([box_0.x0, box_0.y0", "plt.show() # plot 6c time = np.linspace(0, 5 * np.pi,", "B-Spline Bases at Boundary') plt.plot(time[500:], b_spline_basis[2, 500:].T, '--', label=r'$ B_{-3,4}(t)", "Duffing Equation Example def duffing_equation(xy, ts): gamma = 0.1 epsilon", "Effects Example') plt.plot(max_dash_time_1, max_dash_1, 'k-') plt.plot(max_dash_time_2, max_dash_2, 'k-') plt.plot(max_dash_time_3, max_dash_3,", "= 2$', Linewidth=3) ax.set_xticks([0, np.pi, 2 * np.pi, 3 *", "zorder=100) axs[1].set_yticks(ticks=[-2, 0, 2]) axs[1].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[1].set_xticklabels(labels=['0',", ":].T, '--', label='Basis 3') axs[0].plot(time, b_spline_basis[5, :].T, '--', label='Basis 4')", "3)}') axs[1].plot(t, 0.1 * np.cos(0.04 * 2 * np.pi *", "= plt.gcf().get_size_inches() factor = 0.9 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian", "width, 101) minima_dash_time_1 = minima_x[-2] * np.ones_like(minima_dash) minima_dash_time_2 = minima_x[-1]", "* np.pi, 4 * np.pi, 5 * np.pi]) axs[0].set_xticklabels(['', '',", "* (np.abs(average_gradients) == max(np.abs(average_gradients))) adjustment = - lr * average_gradients", "Average_max_time = maxima_x[-1] + (maxima_x[-1] - maxima_x[-2]) Average_max = (maxima_y[-2]", "101), '--', c='grey', zorder=1, label='Knots') axs[2].set_xticks([np.pi, (3 / 2) *", "np.linspace(time[0], time[-1], 200) emd_example = AdvEMDpy.EMD(time=time, time_series=signal) imfs, hts, ifs,", "plt.savefig('jss_figures/comparing_bases.png') plt.show() # plot 3 a = 0.25 width =", "1) + 1 + i_right + 1)]) if sum(emd_utils_min.min_bool_func_1st_order_fd()) >", "Hilbert Spectrum of Duffing Equation using PyEMD 0.2.10', 40)) plt.pcolormesh(t,", "time[-1], 200) emd_example = AdvEMDpy.EMD(time=time, time_series=signal) imfs, hts, ifs, _,", "np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) ax.set_title(textwrap.fill(r'Gaussian Filtered Hilbert Spectrum of CO$_{2}$", "1.2, 100), 'k-') plt.legend(loc='upper left') plt.savefig('jss_figures/boundary_bases.png') plt.show() # plot 1a", "(rad.s$^{-1}$)') plt.xlabel('Time (s)') box_0 = ax.get_position() ax.set_position([box_0.x0, box_0.y0 + 0.05,", "-1, 0, 1, 2), ('-2', '-1', '0', '1', '2')) box_0", "time_series[-1] improved_slope_based_minimum_time = slope_based_minimum_time improved_slope_based_minimum = improved_slope_based_maximum + s2 *", "label='Knots') for i in range(3): for j in range(1, len(knots[i])):", "np.pi * t) - py_emd[1, :])), 3)}') axs[1].plot(t, emd_sift[:, 1],", "a) * np.pi, (5 + a) * np.pi, 101) time_series_reflect", ":]), 3)}') for knot in knots_11: axs[2].plot(knot * np.ones(101), np.linspace(-5,", "envelope', 10), c='red') plt.plot(time, min_unsmoothed[0], label=textwrap.fill('Unsmoothed minima envelope', 10), c='cyan')", "* np.ones_like(min_dash_4) dash_final_time = np.linspace(improved_slope_based_maximum_time, improved_slope_based_minimum_time, 101) dash_final = np.linspace(improved_slope_based_maximum,", "plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('First Iteration of Sifting Algorithm') plt.plot(pseudo_alg_time, pseudo_alg_time_series, label=r'$h_{(1,0)}(t)$',", "101), '--', c='grey', zorder=1) plt.plot(knots[-1] * np.ones(101), np.linspace(-3.0, -2.0, 101),", "= np.linspace((5 - a) * np.pi, (5 + a) *", "time_series=knot_demonstrate_time_series) imfs, _, _, _, knots, _, _ = emd.empirical_mode_decomposition(edge_effect='anti-symmetric',", "= emd_utils.Utility(time=time, time_series=time_series_anti_reflect) anti_max_bool = utils.max_bool_func_1st_order_fd() anti_max_point_time = time_reflect[anti_max_bool] anti_max_point", "& IMF 3 with 51 knots', 21)) print(f'DFA fluctuation with", ":], 2 * np.ones_like(x_hs[0, :]), '--', label=r'$\\omega = 2$', Linewidth=3)", "pyemd = pyemd0215() py_emd = pyemd(x) IP, IF, IA =", "np.ones_like(length_time_2) length_bottom_2 = minima_y[-1] * np.ones_like(length_time_2) symmetry_axis_1_time = minima_x[-1] *", "plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of CO$_{2}$ Concentration using emd 0.3.3',", "box_2.height]) axs[2].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[2].set_ylim(-5.5, 5.5) axs[2].set_xlim(0.95 *", "0.3.3', 40)) plt.pcolormesh(t, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(t[:-1], 0.124", "time_series[optimal_maxima], c='darkred', zorder=4, label=textwrap.fill('Optimal maxima', 10)) plt.scatter(time[optimal_minima], time_series[optimal_minima], c='darkblue', zorder=4,", "c='purple', zorder=4, label=textwrap.fill('Symmetric Discard maxima', 10)) plt.scatter(end_point_time, end_point, c='orange', zorder=4,", "as emd040 sns.set(style='darkgrid') pseudo_alg_time = np.linspace(0, 2 * np.pi, 1001)", "np.pi, 5.6 * np.pi) plt.xticks((4 * np.pi, 5 * np.pi),", "r'2$\\pi$', r'3$\\pi$', r'4$\\pi$', r'5$\\pi$')) plt.yticks((-2, -1, 0, 1, 2), ('-2',", "1.55 * np.pi, 101), 5.5 * np.ones(101), 'k--') axs[2].plot(np.linspace(0.95 *", "i_left = 0 while ((max_count_left < 1) or (min_count_left <", "box_2 = axs[2].get_position() axs[2].set_position([box_2.x0 - 0.05, box_2.y0, box_2.width * 0.85,", "plt.plot(time, time_series, label='Time series', zorder=2, LineWidth=2) plt.scatter(time[maxima], time_series[maxima], c='r', label='Maxima',", "import odeint from scipy.ndimage import gaussian_filter from emd_utils import time_extension,", "plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Duffing Equation using PyEMD 0.2.10',", "2 * np.pi]) axs[1].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2 and Dynamically", "= np.linspace(maxima_y[-1], minima_y[-2], 101) s1 = (minima_y[-2] - maxima_y[-1]) /", "/ (2 * np.pi) - np.ones_like(ifs[1, :]))), 3)}') fig, axs", "np.ones_like(length_distance) length_time = np.linspace(point_1 * np.pi - width, point_1 *", "* np.pi, 4 * np.pi, 5 * np.pi]) axs[2].set_xticklabels(['$0$', r'$\\pi$',", "/ 25) return [xy[1], xy[0] - epsilon * xy[0] **", "plt.show() # plot 6b fig, axs = plt.subplots(3, 1) plt.suptitle(textwrap.fill('Comparison", "b_spline_basis[2, :].T, '--', label='Basis 1') axs[0].plot(time, b_spline_basis[3, :].T, '--', label='Basis", "101), '--', c='grey', zorder=1, label='Knots') axs[1].set_xticks([0, np.pi, 2 * np.pi,", "of symmetry', 10), zorder=1) plt.text(5.1 * np.pi, -0.7, r'$\\beta$L') plt.text(5.34", "axs[1, 0].plot(time, imfs[1, :]) axs[1, 1].plot(time, imfs[2, :]) axis =", "* np.ones_like(min_2_x_time) dash_max_min_2_x = np.linspace(minima_y[-2], maxima_y[-2], 101) dash_max_min_2_x_time = 5.3", "- maxima_x[-2]) Average_max = (maxima_y[-2] + maxima_y[-1]) / 2 Average_min_time", "= np.linspace(minima_y[-1] - width, minima_y[-1] + width, 101) min_dash_2 =", "np.pi + width, 101) max_1_x = maxima_y[-1] * np.ones_like(max_1_x_time) min_1_x_time", "* np.ones(100), c='k') plt.plot(np.linspace(((time[-302] + time[-301]) / 2), ((time[-302] +", "top seed_weights = np.ones(neural_network_k) / neural_network_k weights = 0 *", "- 1):int(2 * (len(lsq_signal) - 1) + 1)] = lsq_signal", "plt.text(4.74 * np.pi, -3.2, r'$\\Delta{t^{min}_{m}}$') plt.text(4.12 * np.pi, 2, r'$\\Delta{t^{max}_{M}}$')", "/ 2) + 0.1, 100), 2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time_extended[-1001]", "frequency', 15)) plt.xticks([0, 50, 100, 150]) plt.yticks([0, 0.1, 0.2]) plt.ylabel('Frequency", "maxima_dash = np.linspace(2.5 - width, 2.5 + width, 101) maxima_dash_time_1", "plt.xticks((4 * np.pi, 5 * np.pi), (r'4$\\pi$', r'5$\\pi$')) plt.yticks((-2, -1,", "'1', '2')) box_0 = ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width", "preprocess.quantile_filter(window_width=window, q=0.10)[1], c='grey') axs[0].plot(np.linspace(0.85 * np.pi, 1.15 * np.pi, 101),", "imfs_11[1, :], label='IMF 1 with 11 knots') axs[2].plot(time, imfs_31[2, :],", "* np.sin(2 * np.pi * t / 200) util_nn =", "c='grey') plt.savefig('jss_figures/knot_uniform.png') plt.show() # plot 1b - addition knot_demonstrate_time =", "+ width, 101) min_2_x = minima_y[-2] * np.ones_like(min_2_x_time) dash_max_min_2_x =", "axs[0].set_title('Preprocess Filtering Demonstration') axs[1].set_title('Zoomed Region') preprocess_time = pseudo_alg_time.copy() np.random.seed(1) random.seed(1)", "0.1, 100), -2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time[-202] + time[-201]) /", "plot 6b fig, axs = plt.subplots(3, 1) plt.suptitle(textwrap.fill('Comparison of Trends", "extrema_type='minima', smooth=True) util = Utility(time=time, time_series=time_series) maxima = util.max_bool_func_1st_order_fd() minima", "= time_series[-1] time_reflect = np.linspace((5 - a) * np.pi, (5", "axs[0].set_xlim([0, 150]) axs[1].plot(t, emd_duff[2, :], label='AdvEMDpy') print(f'AdvEMDpy driving function error:", "0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of", "bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert_pyemd.png') plt.show() emd_sift = emd040.sift.sift(signal) IP, IF, IA", "pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[0].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean", "left') axs[1].plot(knots[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots')", "21)) print(f'DFA fluctuation with 51 knots: {np.round(np.var(time_series - (imfs_51[1, :]", "5 * np.pi]) axs[0].set_xticklabels(['', '', '', '', '', '']) box_0", "plt.savefig('jss_figures/preprocess_smooth.png') plt.show() # plot 2 fig, axs = plt.subplots(1, 2,", "0]))), 3)}') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 2, 100) hht =", "s2 = (minima_y[-1] - maxima_y[-1]) / (minima_x[-1] - maxima_x[-1]) slope_based_minimum_time", "a) * np.pi, (5 - a) * np.pi, 1001) knots", "* np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--') axs[1].plot(1.55 * np.pi *", "2 A1 = np.abs(maxima_y[-1] - minima_y[-1]) / 2 P2 =", "axs[2].plot(knots[2][0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') for", "dash_max_min_1_y = -2.1 * np.ones_like(dash_max_min_1_y_time) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Characteristic", "* s2 min_dash_time_3 = slope_based_minimum_time * np.ones_like(min_dash_1) min_dash_3 = np.linspace(slope_based_minimum", "r'$2\\pi$']) axs[2].set_title('IMF 2 and Dynamically Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2,", "zorder=1, label='Knots') axs[2].set_xticks([0, np.pi, 2 * np.pi, 3 * np.pi,", "dash_max_min_2_x = np.linspace(minima_y[-2], maxima_y[-2], 101) dash_max_min_2_x_time = 5.3 * np.pi", "freq_bins = emd040.spectra.define_hist_bins(0, 2, 100) hht = emd040.spectra.hilberthuang(IF, IA, freq_edges)", "Average_max, c='orangered', zorder=4, label=textwrap.fill('Average maximum', 14)) plt.scatter(Average_min_time, Average_min, c='cyan', zorder=4,", "axs[0].plot(np.linspace(0.85 * np.pi, 1.15 * np.pi, 101), 3 * np.ones(101),", "np.linspace(-0.2, 1.2, 100), 'k-') plt.plot(6 * np.ones(100), np.linspace(-0.2, 1.2, 100),", "axs[1].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2 and Dynamically Knots') axs[2].plot(knot_demonstrate_time, imfs[2,", "101) dash_3 = np.linspace(minima_y[-1], slope_based_maximum, 101) s2 = (minima_y[-1] -", "for i in range(3): for j in range(1, len(knots_uniform)): axs[i].plot(knots_uniform[j]", "zorder=10) plt.plot(time, max_unsmoothed[0], label=textwrap.fill('Unsmoothed maxima envelope', 10), c='darkorange') plt.plot(time, max_smoothed[0],", "dash_2 = np.linspace(minima_y[-1], max_discard, 101) end_point_time = time[-1] end_point =", "np.linspace(improved_slope_based_maximum_time, improved_slope_based_minimum_time, 101) dash_final = np.linspace(improved_slope_based_maximum, improved_slope_based_minimum, 101) ax =", "plot 3 a = 0.25 width = 0.2 time =", "plt.title('Single Neuron Neural Network Example') plt.plot(time, lsq_signal, zorder=2, label='Signal') plt.plot(time_extended,", "time_series=time_series_reflect) no_anchor_max_time = time_reflect[utils.max_bool_func_1st_order_fd()] no_anchor_max = time_series_reflect[utils.max_bool_func_1st_order_fd()] point_1 = 5.4", "plt.savefig('jss_figures/CO2_Hilbert_pyemd.png') plt.show() emd_sift = emd040.sift.sift(signal) IP, IF, IA = emd040.spectra.frequency_transform(emd_sift[:,", "= error * (- train_input) # guess average gradients average_gradients", "25) return [xy[1], xy[0] - epsilon * xy[0] ** 3", "Filtered Hilbert Spectrum of CO$_{2}$ Concentration using PyEMD 0.2.10', 45))", "\\ time_series[time == minima_x[-1]] improved_slope_based_maximum_time = time[-1] improved_slope_based_maximum = time_series[-1]", "axs[1].get_position() axs[1].set_position([box_1.x0 - 0.05, box_1.y0, box_1.width * 0.85, box_1.height]) plt.savefig('jss_figures/preprocess_filter.png')", "max_1_y = np.linspace(maxima_y[-1] - width, maxima_y[-1] + width, 101) max_1_y_side", "max_2_y, 'k-') plt.plot(max_2_y_time, max_2_y_side, 'k-') plt.plot(min_2_y_time, min_2_y, 'k-') plt.plot(min_2_y_time, min_2_y_side,", "maxima) cs_min = CubicSpline(t[util_nn.min_bool_func_1st_order_fd()], minima) time = np.linspace(0, 5 *", "plt.scatter(maxima_extrapolate_time, maxima_extrapolate, c='magenta', zorder=3, label=textwrap.fill('Extrapolated maxima', 12)) plt.scatter(minima_extrapolate_time, minima_extrapolate, c='cyan',", "np.pi, 11) time_series = np.cos(time) + np.cos(5 * time) utils", "preprocess_time = pseudo_alg_time.copy() np.random.seed(1) random.seed(1) preprocess_time_series = pseudo_alg_time_series + np.random.normal(0,", "plt.subplot(111) figure_size = plt.gcf().get_size_inches() factor = 0.9 plt.gcf().set_size_inches((figure_size[0], factor *", "len(time_series)) time_series += noise advemdpy = EMD(time=time, time_series=time_series) imfs_51, hts_51,", "i in range(3): for j in range(1, len(knots[i])): axs[i].plot(knots[i][j] *", "= np.linspace(5.3 * np.pi - width, 5.3 * np.pi +", "plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Dynamically Optimised Knots')", "zorder=4, label=textwrap.fill('Huang minimum', 10)) plt.scatter(Coughlin_max_time, Coughlin_max, c='darkorange', zorder=4, label=textwrap.fill('Coughlin maximum',", "0, 1, 2]) plt.xticks(ticks=[0, np.pi, 2 * np.pi], labels=[r'0', r'$\\pi$',", "box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht.png') plt.show() #", "+ width, 101) min_1_y_side = np.linspace(-2.1 - width, -2.1 +", "forward -> P = np.zeros((int(neural_network_k + 1), neural_network_m)) for col", "1 + i_right)] = \\ sum(weights_right * np.hstack((time_series_extended[ int(2 *", "+ time[-301]) / 2) * np.ones(100), np.linspace(-2.75, 2.75, 100), c='k',", "np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1) axs[2].plot(knot * np.ones(101),", "Optimised Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2, zorder=100) axs[0].set_yticks(ticks=[-2, 0, 2]) axs[0].set_xticks(ticks=[0,", "= axs[0].get_position() axs[0].set_position([box_0.x0 - 0.05, box_0.y0, box_0.width * 0.85, box_0.height])", "= np.linspace(2.5 - width, 2.5 + width, 101) maxima_dash_time_1 =", "= minima_x[-1] * np.ones(101) symmetry_axis_2_time = time[-1] * np.ones(101) symmetry_axis", "max(np.abs(average_gradients))) adjustment = - lr * average_gradients # adjustment =", "0.85, box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, -0.15)) box_1 = axs[1].get_position() axs[1].set_position([box_1.x0", "0.8, 100), 'k-') axs[0].set_xticks([5, 6]) axs[0].set_xticklabels([r'$ \\tau_k $', r'$ \\tau_{k+1}", "smooth=False, smoothing_penalty=0.2, edge_effect='none')[0] EEMD_minima_envelope = fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'minima', optimal_maxima, optimal_minima, smooth=False,", "width, 101) max_dash_2 = np.linspace(maxima_y[-2] - width, maxima_y[-2] + width,", "+ (slope_based_minimum - minima_y[-1]), r'$s_2$') plt.plot(minima_line_dash_time, minima_line_dash, 'k--') plt.plot(maxima_line_dash_time, maxima_line_dash,", "label=textwrap.fill('Downsampled & decimated', 11)) downsampled = preprocess.downsample(decimate=False) axs[0].plot(downsampled[0], downsampled[1], label=textwrap.fill('Downsampled',", "of CO$_{2}$ Concentration using PyEMD 0.2.10', 45)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time", "py_emd = pyemd(x) IP, IF, IA = emd040.spectra.frequency_transform(py_emd.T, 10, 'hilbert')", "axs[0].legend(loc='lower left') axs[1].plot(knots[1][0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey',", "plot 6a np.random.seed(0) time = np.linspace(0, 5 * np.pi, 1001)", "= hilbert_spectrum(time, imfs_51, hts_51, ifs_51, max_frequency=12, plot=False) # plot 6c", "40)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)') plt.plot(x_hs[0, :], np.ones_like(x_hs[0, :]), 'k--',", "left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[0].set_ylim(-5.5, 5.5) axs[0].set_xlim(0.95 * np.pi, 1.55", "- maxima_x[-2]) slope_based_maximum = minima_y[-1] + (slope_based_maximum_time - minima_x[-1]) *", "Uniform Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2, zorder=100) axs[0].set_yticks(ticks=[-2, 0, 2]) axs[0].set_xticks(ticks=[0,", "label=textwrap.fill('Downsampled', 13)) axs[0].plot(np.linspace(0.85 * np.pi, 1.15 * np.pi, 101), -3", "max_1_y_side = np.linspace(-2.1 - width, -2.1 + width, 101) max_1_y_time", "40)) plt.pcolormesh(t, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(t[:-1], 0.124 *", "101) time_extended = time_extension(time) time_series_extended = np.zeros_like(time_extended) / 0 time_series_extended[int(len(lsq_signal)", "ax.plot(x_hs[0, :], 8 * np.ones_like(x_hs[0, :]), '--', label=r'$\\omega = 8$',", "time) knots = np.linspace(0, 5 * np.pi, 101) time_extended =", "0 time_series_extended[int(len(lsq_signal) - 1):int(2 * (len(lsq_signal) - 1) + 1)]", "= np.linspace(0, 5 * np.pi, 1001) lsq_signal = np.cos(time) +", "2.5 + width, 101) maxima_dash_time_1 = maxima_x[-2] * np.ones_like(maxima_dash) maxima_dash_time_2", "0.9 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time, time_series, LineWidth=2, label='Signal')", "* np.pi, 2, r'$\\Delta{t^{max}_{M}}$') plt.text(4.50 * np.pi, 2, r'$\\Delta{t^{max}_{M}}$') plt.text(4.30", "plt.legend(loc='upper left') plt.savefig('jss_figures/boundary_bases.png') plt.show() # plot 1a - addition knot_demonstrate_time", "101) dash_2 = np.linspace(minima_y[-1], max_discard, 101) end_point_time = time[-1] end_point", "np.abs(maxima_y[-2] - minima_y[-2]) / 2 A1 = np.abs(maxima_y[-1] - minima_y[-1])", "* 0.85, box_1.height]) plt.savefig('jss_figures/preprocess_smooth.png') plt.show() # plot 2 fig, axs", "np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--') axs[2].plot(1.55 * np.pi * np.ones(101),", "'hilbert') print(f'emd annual frequency error: {np.round(sum(np.abs(IF - np.ones_like(IF)))[0], 3)}') freq_edges,", "np.ones(101), np.linspace(-3.0, -2.0, 101), '--', c='grey', label='Knots', zorder=1) plt.xticks((0, 1", "Huang_min = Huang_wave[Huang_min_bool] Coughlin_max_time = Coughlin_time[Coughlin_max_bool] Coughlin_max = Coughlin_wave[Coughlin_max_bool] Coughlin_min_time", "1: emd_utils_max = \\ emd_utils.Utility(time=time_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))], time_series=time_series_extended[int(len(lsq_signal)", "+ 0.05, box_0.width * 0.75, box_0.height * 0.9]) ax.legend(loc='center left',", "2 * np.pi, 3 * np.pi, 4 * np.pi]) ax.set_xticklabels(['$0$',", "1 and IMF 2 with 31 knots', 19)) axs[1].plot(time, imfs_51[2,", "min_1_y = np.linspace(minima_y[-1] - width, minima_y[-1] + width, 101) min_1_y_side", "5 * np.pi]) axs[0].set_xticklabels(['', '', '', '', '', '']) axs[0].plot(np.linspace(0.95", "imfs_31[2, :])), 3)}') for knot in knots_31: axs[1].plot(knot * np.ones(101),", "axs[2].set_title('IMF 2 and Uniform Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2, zorder=100)", "smooth=True, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] minima_envelope = fluctuation.envelope_basis_function_approximation(knots, 'minima', smooth=False, smoothing_penalty=0.2,", "advemdpy.empirical_mode_decomposition(knots=knots_51, max_imfs=3, edge_effect='symmetric_anchor', verbose=False)[:3] knots_31 = np.linspace(0, 5 * np.pi,", "= 5.4 length_distance = np.linspace(maxima_y[-1], minima_y[-1], 101) length_distance_time = point_1", "preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median filter', 13)) axs[0].plot(preprocess_time, preprocess.winsorize(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize filter', 12))", "max_dash_2 = np.linspace(maxima_y[-2] - width, maxima_y[-2] + width, 101) max_dash_time_1", "101) min_dash_time_1 = minima_x[-1] * np.ones_like(min_dash_1) min_dash_time_2 = minima_x[-2] *", "maxima_x[-2]] - time[time == maxima_x[-2]]) + maxima_x[-1] Huang_wave = (A1", "+ 1 + i_right)] = \\ sum(weights_right * np.hstack((time_series_extended[ int(2", "figure_size = plt.gcf().get_size_inches() factor = 0.7 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1]))", "8$', Linewidth=3) ax.plot(x_hs[0, :], 4 * np.ones_like(x_hs[0, :]), '--', label=r'$\\omega", "improved_slope_based_maximum_time) min_dash_4 = np.linspace(improved_slope_based_minimum - width, improved_slope_based_minimum + width, 101)", "- np.ones_like(IF[:, 0]))), 3)}') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 2, 100)", "np.linspace(slope_based_maximum, slope_based_minimum) maxima_dash = np.linspace(2.5 - width, 2.5 + width,", "np.linspace(0, 5 * np.pi, 51) time_series = np.cos(2 * time)", "axis == 0: ax.set(ylabel=R'C0$_2$ concentration') if axis == 1: pass", "'--', label=r'$\\omega = 2$', Linewidth=3) ax.set_xticks([0, np.pi, 2 * np.pi,", "np.pi, 1001) knot_demonstrate_time_series = np.sin(knot_demonstrate_time) + np.sin(5 * knot_demonstrate_time) knots_uniform", "Fluctuation from AdvEMDpy import EMD # alternate packages from PyEMD", "i_left):int(len(lsq_signal))], time_series=time_series_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))]) if sum(emd_utils_max.max_bool_func_1st_order_fd()) > 0:", "'k-') plt.legend(loc='upper left') plt.savefig('jss_figures/boundary_bases.png') plt.show() # plot 1a - addition", "Optimised Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2, zorder=100) axs[1].set_yticks(ticks=[-2, 0, 2])", "6.5) axs[1].set_title('Cubic Hermite Spline Bases') axs[1].plot(time, chsi_basis[10, :].T, '--') axs[1].plot(time,", "= emd_utils.Utility(time=time, time_series=time_series_reflect) no_anchor_max_time = time_reflect[utils.max_bool_func_1st_order_fd()] no_anchor_max = time_series_reflect[utils.max_bool_func_1st_order_fd()] point_1", "1] solution = odeint(duffing_equation, XY0, t) x = solution[:, 0]", "label=textwrap.fill('Coughlin minimum', 14)) plt.scatter(Average_max_time, Average_max, c='orangered', zorder=4, label=textwrap.fill('Average maximum', 14))", "label=textwrap.fill('Optimal maxima', 10)) plt.scatter(time[optimal_minima], time_series[optimal_minima], c='darkblue', zorder=4, label=textwrap.fill('Optimal minima', 10))", "0.35 + (minima_y[-1] - minima_y[-2]), r'$s_1$') plt.text(4.43 * np.pi +", "np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') axs[1].set_xticks([5, 6]) axs[1].set_xticklabels([r'$ \\tau_k $',", "axs[0].set_title('Time Series and Dynamically Optimised Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2, zorder=100)", "factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) axs[0].plot(t, emd_duff[1, :],", "np.linspace(-2, 2, 101), '--', c='grey', label='Knots') for i in range(3):", "Concentration using emd 0.3.3', 45)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)') plt.pcolormesh(time,", "c='darkviolet', label=textwrap.fill('Huang Characteristic Wave', 14)) plt.plot(Coughlin_time, Coughlin_wave, '--', c='darkgreen', label=textwrap.fill('Coughlin", "= CO2_data['month'] time = np.asarray(time) # compare other packages Carbon", "= plt.subplot(111) figure_size = plt.gcf().get_size_inches() factor = 1.0 plt.gcf().set_size_inches((figure_size[0], factor", "= slope_based_maximum - (slope_based_maximum_time - slope_based_minimum_time) * s2 min_dash_time_3 =", "Spectrum of Duffing Equation using AdvEMDpy', 40)) x, y, z", "lsq_signal[lsq_utils.min_bool_func_1st_order_fd()] minima_time = time[lsq_utils.min_bool_func_1st_order_fd()] minima_extrapolate = time_series_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] minima_extrapolate_time = time_extended[utils_extended.min_bool_func_1st_order_fd()][-2:]", "0.5)) plt.savefig('jss_figures/DFA_hilbert_spectrum.png') plt.show() # plot 6c time = np.linspace(0, 5", ":] + imfs_51[2, :] + imfs_51[3, :], label=textwrap.fill('Sum of IMF", "min_dash_1, 'k-') plt.plot(min_dash_time_2, min_dash_2, 'k-') plt.plot(min_dash_time_3, min_dash_3, 'k-') plt.plot(min_dash_time_4, min_dash_4,", "= time_series_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] minima_extrapolate_time = time_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Single", "scipy.ndimage import gaussian_filter from emd_utils import time_extension, Utility from scipy.interpolate", "/ 2 utils_Huang = emd_utils.Utility(time=time, time_series=Huang_wave) Huang_max_bool = utils_Huang.max_bool_func_1st_order_fd() Huang_min_bool", "r'$2\\pi$']) axs[1].set_title('IMF 1 and Uniform Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2,", "np.sin(5 * knot_demonstrate_time) knots_uniform = np.linspace(0, 2 * np.pi, 51)", "* np.ones_like(maxima_dash) maxima_dash_time_3 = slope_based_maximum_time * np.ones_like(maxima_dash) maxima_line_dash_time = np.linspace(maxima_x[-2],", "3: ax.set(xlabel='Time (years)') axis += 1 plt.gcf().subplots_adjust(bottom=0.15) axs[0, 0].set_title(r'Original CO$_2$", "* max_gradient_vector weights += adjustment # test - bottom weights_right", "= np.asarray(time) # compare other packages Carbon Dioxide - top", "zorder=4, label=textwrap.fill('Coughlin minimum', 14)) plt.scatter(Average_max_time, Average_max, c='orangered', zorder=4, label=textwrap.fill('Average maximum',", "plt.show() hs_ouputs = hilbert_spectrum(t, emd_duff, emd_ht_duff, emd_if_duff, max_frequency=1.3, plot=False) ax", "spline_method='b_spline')[0] inflection_points_envelope = fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True, smoothing_penalty=0.2, technique='inflection_points')[0] binomial_points_envelope = fluctuation.direct_detrended_fluctuation_estimation(knots,", "/ # \\ / # \\ / # \\/ import", "+ 1)] = lsq_signal neural_network_m = 200 neural_network_k = 100", "minima_x[-1] * np.ones_like(min_dash_1) min_dash_time_2 = minima_x[-2] * np.ones_like(min_dash_1) dash_1_time =", "minima_y[-1] * np.ones_like(min_dash_time) dash_1_time = np.linspace(maxima_x[-1], minima_x[-1], 101) dash_1 =", "minima_line_dash_time = np.linspace(minima_x[-2], slope_based_minimum_time, 101) minima_line_dash = -3.4 * np.ones_like(minima_line_dash_time)", "c='r', label='Maxima', zorder=10) plt.scatter(time[minima], time_series[minima], c='b', label='Minima', zorder=10) plt.plot(time, max_unsmoothed[0],", "2) + 0.1, 100), -2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time[-302] +", "width, minima_x[-2] + width, 101) min_2_x_time_side = np.linspace(5.3 * np.pi", "2) - 0.1, 100), -2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time_extended[-1001] +", "annual frequency error: {np.round(sum(np.abs(ifs[1, :] / (2 * np.pi) -", "len(knots[i])): axs[i].plot(knots[i][j] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey') plt.savefig('jss_figures/knot_2.png')", "plt.show() # compare other packages Duffing - top pyemd =", "vmax=np.max(np.max(np.abs(hht)))) plt.plot(time, np.ones_like(time), 'k--', label=textwrap.fill('Annual cycle', 10)) box_0 = ax.get_position()", "plt.scatter(slope_based_maximum_time, slope_based_maximum, c='orange', zorder=4, label=textwrap.fill('Slope-based maximum', 11)) plt.scatter(slope_based_minimum_time, slope_based_minimum, c='purple',", "= plt.subplot(111) figure_size = plt.gcf().get_size_inches() factor = 0.9 plt.gcf().set_size_inches((figure_size[0], factor", "np.linspace(maxima_y[-1], minima_y[-1], 101) max_discard = maxima_y[-1] max_discard_time = minima_x[-1] -", "= np.linspace(knots[0], knots[-1], 31) # change (1) detrended_fluctuation_technique and (2)", "0, 1, 2), ('-2', '-1', '0', '1', '2')) box_0 =", "c='darkgreen') plt.plot(time, inflection_points_envelope, c='darkorange', label=textwrap.fill('Inflection point envelope', 10)) plt.plot(time, binomial_points_envelope,", "* np.pi, (5 + a) * np.pi, 101) time_series_reflect =", "'hilbert') print(f'PyEMD annual frequency error: {np.round(sum(np.abs(IF[:, 0] - np.ones_like(IF[:, 0]))),", "'1', '2')) plt.xlim(-0.25 * np.pi, 5.25 * np.pi) box_0 =", "1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Statically Optimised Knots') axs[0].plot(knot_demonstrate_time,", "# plot 4 a = 0.21 width = 0.2 time", "= utils.derivative_forward_diff() derivative_time = time[:-1] derivative_knots = np.linspace(knots[0], knots[-1], 31)", "Coughlin_wave = A1 * np.cos(2 * np.pi * (1 /", "* np.ones_like(minima_dash) minima_dash_time_2 = minima_x[-1] * np.ones_like(minima_dash) minima_dash_time_3 = slope_based_minimum_time", "= 2 * np.abs(maxima_x[-2] - minima_x[-2]) P1 = 2 *", "int(2 * (len(lsq_signal) - 1) + 1 + i_right +", ":], '--', label='PyEMD 0.2.10') print(f'PyEMD driving function error: {np.round(sum(abs(0.1 *", "time_series=Coughlin_wave) Coughlin_max_bool = utils_Coughlin.max_bool_func_1st_order_fd() Coughlin_min_bool = utils_Coughlin.min_bool_func_1st_order_fd() Huang_max_time = Huang_time[Huang_max_bool]", "np.linspace(point_2 * np.pi - width, point_2 * np.pi + width,", "* 0.75, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht_emd.png')", "min_dash, 'k-') plt.plot(dash_1_time, dash_1, 'k--') plt.plot(dash_2_time, dash_2, 'k--') plt.plot(length_distance_time, length_distance,", ":].T, '--', label='Basis 2') axs[0].plot(time, b_spline_basis[4, :].T, '--', label='Basis 3')", "np.linspace(maxima_x[-1], minima_x[-2], 101) dash_2 = np.linspace(maxima_y[-1], minima_y[-2], 101) s1 =", "inflection_points_envelope, c='darkorange', label=textwrap.fill('Inflection point envelope', 10)) plt.plot(time, binomial_points_envelope, c='deeppink', label=textwrap.fill('Binomial", "plt.savefig('jss_figures/knot_uniform.png') plt.show() # plot 1b - addition knot_demonstrate_time = np.linspace(0,", "'k--') plt.plot(maxima_line_dash_time, maxima_line_dash, 'k--') plt.plot(dash_1_time, dash_1, 'k--') plt.plot(dash_2_time, dash_2, 'k--')", "label='Time series') plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b',", "cmap='gist_rainbow', vmin=z_min, vmax=z_max) ax.set_title(textwrap.fill(r'Gaussian Filtered Hilbert Spectrum of CO$_{2}$ Concentration", "[0, 50, 100, 150] x_names = {0, 50, 100, 150}", "* np.ones(101) symmetry_axis_2_time = time[-1] * np.ones(101) symmetry_axis = np.linspace(-2,", "adjustment = - lr * max_gradient_vector weights += adjustment #", "for iterations in range(1000): output = np.matmul(weights, train_input) error =", "EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series) imfs = emd.empirical_mode_decomposition(knots=knots_uniform, edge_effect='anti-symmetric', verbose=False)[0] fig, axs =", "# test - bottom weights_right = np.hstack((weights, 0)) max_count_right =", "slope_based_minimum) maxima_dash = np.linspace(2.5 - width, 2.5 + width, 101)", "* np.pi, -3.2, r'$\\Delta{t^{min}_{m}}$') plt.text(4.74 * np.pi, -3.2, r'$\\Delta{t^{min}_{m}}$') plt.text(4.12", "+ i_right)], 1))) i_right += 1 if i_right > 1:", "objective = cvx.Minimize(cvx.norm((2 * (vx * P) + 1 -", "Velocity') axs[1].set_ylim([-1.5, 1.5]) axs[1].set_xlim([0, 150]) axis = 0 for ax", "0.2.10', 40)) plt.pcolormesh(t, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(t[:-1], 0.124", "maxima_y[-1] max_discard_time = minima_x[-1] - maxima_x[-1] + minima_x[-1] max_discard_dash_time =", "101) minima_line_dash = -3.4 * np.ones_like(minima_line_dash_time) # slightly edit signal", "r'$\\Delta{t^{min}_{m}}$') plt.text(4.74 * np.pi, -3.2, r'$\\Delta{t^{min}_{m}}$') plt.text(4.12 * np.pi, 2,", "101), '--', c='grey', label='Knots') for i in range(3): for j", "np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') axs[1].plot(6 * np.ones(100), np.linspace(-0.2, 1.2,", "11)) plt.scatter(improved_slope_based_maximum_time, improved_slope_based_maximum, c='deeppink', zorder=4, label=textwrap.fill('Improved slope-based maximum', 11)) plt.scatter(improved_slope_based_minimum_time,", "2), ('-2', '-1', '0', '1', '2')) box_0 = ax.get_position() ax.set_position([box_0.x0", "np.pi + (slope_based_minimum_time - minima_x[-1]), -0.20 + (slope_based_minimum - minima_y[-1]),", ":])), 3)}') for knot in knots_31: axs[1].plot(knot * np.ones(101), np.linspace(-5,", "Sequences Zoomed Region', 40)) plt.subplots_adjust(hspace=0.1) axs[0].plot(time, time_series, label='Time series') axs[0].plot(time,", "= np.linspace(point_2 * np.pi - width, point_2 * np.pi +", "minima_x[-1]), -0.20 + (slope_based_minimum - minima_y[-1]), r'$s_2$') plt.text(4.50 * np.pi", "0.05, box_0.width * 0.75, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1,", "IP, IF, IA = emd040.spectra.frequency_transform(emd_sift[:, :1], 12, 'hilbert') print(f'emd annual", "preprocess.quantile_filter(window_width=window, q=0.90)[1], c='grey', label=textwrap.fill('Quantile window', 12)) axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.10)[1], c='grey')", "anti_max_point = time_series_anti_reflect[anti_max_bool] utils = emd_utils.Utility(time=time, time_series=time_series_reflect) no_anchor_max_time = time_reflect[utils.max_bool_func_1st_order_fd()]", "* np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots[0][0] * np.ones(101), np.linspace(-2, 2,", "Time Seres with Added Noise', 50)) x_hs, y, z =", "101) max_dash_time_1 = maxima_x[-1] * np.ones_like(max_dash_1) max_dash_time_2 = maxima_x[-2] *", "* np.pi, (5 - a) * np.pi, 11) time_series =", "101))) time_series_anti_reflect = time_series_reflect[0] - time_series_reflect utils = emd_utils.Utility(time=time, time_series=time_series_anti_reflect)", "j in range(1, len(knots)): axs[i].plot(knots[j] * np.ones(101), np.linspace(-2, 2, 101),", "time[min_bool] minima_y = time_series[min_bool] max_dash_time = np.linspace(maxima_x[-1] - width, maxima_x[-1]", "plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1002]) / 2), ((time_extended[-1001] + time_extended[-1002]) / 2)", "Sequences', 40)) plt.subplots_adjust(hspace=0.1) axs[0].plot(time, time_series, label='Time series') axs[0].plot(time, imfs_51[1, :]", "hht = emd040.spectra.hilberthuang(IF, IA, freq_edges) hht = gaussian_filter(hht, sigma=1) ax", "2, & IMF 3 with 51 knots', 21)) print(f'DFA fluctuation", "= ax.get_position() ax.set_position([box_0.x0 + 0.0125, box_0.y0 + 0.075, box_0.width *", "np.ones_like(min_1_x_time) dash_max_min_1_x = np.linspace(minima_y[-1], maxima_y[-1], 101) dash_max_min_1_x_time = 5.4 *", "col] = 1 # for additive constant t = lsq_signal[:neural_network_m]", "binomial_points_envelope, c='deeppink', label=textwrap.fill('Binomial average envelope', 10)) plt.plot(time, np.cos(time), c='black', label='True", "0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess Smoothing Demonstration') axs[1].set_title('Zoomed", "smooth=True, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] inflection_points_envelope = fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True, smoothing_penalty=0.2, technique='inflection_points')[0]", "0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) axs[0].plot(t, emd_duff[1, :], label='AdvEMDpy') axs[0].plot(t,", "which_imfs=[1], plot=False) x_hs, y, z = hs_ouputs y = y", "in range(3): for j in range(1, len(knots_uniform)): axs[i].plot(knots_uniform[j] * np.ones(101),", "minima_dash, 'k-') plt.plot(minima_dash_time_3, minima_dash, 'k-') plt.text(4.34 * np.pi, -3.2, r'$\\Delta{t^{min}_{m}}$')", "= Huang_time[Huang_max_bool] Huang_max = Huang_wave[Huang_max_bool] Huang_min_time = Huang_time[Huang_min_bool] Huang_min =", "101) max_1_y_side = np.linspace(-2.1 - width, -2.1 + width, 101)", "axs[1].set_yticks(ticks=[-2, 0, 2]) axs[1].set_xticks(ticks=[np.pi]) axs[1].set_xticklabels(labels=[r'$\\pi$']) box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 -", "5.5, 101), 'k--') axs[0].plot(1.55 * np.pi * np.ones(101), np.linspace(-5.5, 5.5,", "gaussian_filter(hht, sigma=1) ax = plt.subplot(111) figure_size = plt.gcf().get_size_inches() factor =", "'k-') plt.plot(min_dash_time_1, min_dash_1, 'k-') plt.plot(min_dash_time_2, min_dash_2, 'k-') plt.plot(min_dash_time_3, min_dash_3, 'k-')", "= (minima_y[-1] - maxima_y[-1]) / (minima_x[-1] - maxima_x[-1]) slope_based_minimum_time =", "* np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') axs[1].plot(6 * np.ones(100), np.linspace(-0.2,", "axs[0].plot(preprocess_time, preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median filter', 13)) axs[0].plot(preprocess_time, preprocess.winsorize(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize filter',", "* np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[2].plot(knots[0] *", "np.pi, 3 * np.pi, 4 * np.pi, 5 * np.pi])", "axs[0].plot(np.linspace(0.85 * np.pi, 1.15 * np.pi, 101), -3 * np.ones(101),", "= np.linspace(max_discard_time - width, max_discard_time + width, 101) max_discard_dash =", "+ 0.5, 101) anti_symmetric_signal = time_series[-1] * np.ones_like(anti_symmetric_time) ax =", "bbox_to_anchor=(1, -0.15)) box_1 = axs[1].get_position() axs[1].set_position([box_1.x0 - 0.06, box_1.y0, box_1.width", "2 * np.pi, 1001) pseudo_alg_time_series = np.sin(pseudo_alg_time) + np.sin(5 *", "= slope_based_minimum_time * np.ones_like(min_dash_1) min_dash_3 = np.linspace(slope_based_minimum - width, slope_based_minimum", "epsilon = 1 omega = ((2 * np.pi) / 25)", "3 + gamma * np.cos(omega * ts)] t = np.linspace(0,", "Coughlin_time[Coughlin_min_bool] Coughlin_min = Coughlin_wave[Coughlin_min_bool] max_2_x_time = np.linspace(maxima_x[-2] - width, maxima_x[-2]", "= axs[2].get_position() axs[2].set_position([box_2.x0 - 0.05, box_2.y0, box_2.width * 0.85, box_2.height])", "== minima_x[-1]] improved_slope_based_maximum_time = time[-1] improved_slope_based_maximum = time_series[-1] improved_slope_based_minimum_time =", "label=textwrap.fill('Sum of IMF 1 and IMF 2 with 31 knots',", "Hilbert Spectrum of CO$_{2}$ Concentration using PyEMD 0.2.10', 45)) plt.ylabel('Frequency", "emd_utils.Utility(time=time, time_series=time_series_anti_reflect) anti_max_bool = utils.max_bool_func_1st_order_fd() anti_max_point_time = time_reflect[anti_max_bool] anti_max_point =", "* np.pi, 1.55 * np.pi, 101), -5.5 * np.ones(101), 'k--')", "axs[0].legend(loc='center left', bbox_to_anchor=(1, -0.15)) box_1 = axs[1].get_position() axs[1].set_position([box_1.x0 - 0.06,", "axs[2].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), 5.5 * np.ones(101),", "plt.xticks([5, 6], [r'$ \\tau_0 $', r'$ \\tau_1 $']) plt.xlim(4.4, 6.6)", "plt.show() # plot 6a np.random.seed(0) time = np.linspace(0, 5 *", "= np.linspace(maxima_x[-1] - width, maxima_x[-1] + width, 101) max_dash =", "emd_utils.Utility(time=t, time_series=signal_orig) maxima = signal_orig[util_nn.max_bool_func_1st_order_fd()] minima = signal_orig[util_nn.min_bool_func_1st_order_fd()] cs_max =", "101), '--', c='black') axs[0].plot(1.15 * np.pi * np.ones(101), np.linspace(-3, 3,", "np.pi * t) - emd_sift[:, 1])), 3)}') axs[1].plot(t, 0.1 *", "'k--') plt.plot(dash_3_time, dash_3, 'k--') plt.plot(dash_4_time, dash_4, 'k--') plt.plot(dash_final_time, dash_final, 'k--')", "compare other packages Duffing - top pyemd = pyemd0215() py_emd", "95, 100) signal_orig = np.cos(2 * np.pi * t /", "/ 2, c='darkgreen') plt.plot(time, inflection_points_envelope, c='darkorange', label=textwrap.fill('Inflection point envelope', 10))", "= time_series[-1] * np.ones_like(end_time) anti_symmetric_time = np.linspace(time[-1] - 0.5, time[-1]", "= improved_slope_based_minimum_time * np.ones_like(min_dash_4) dash_final_time = np.linspace(improved_slope_based_maximum_time, improved_slope_based_minimum_time, 101) dash_final", "with Different Knot Sequences', 40)) plt.subplots_adjust(hspace=0.1) axs[0].plot(time, time_series, label='Time series')", "- minima_x[-2]) P1 = 2 * np.abs(maxima_x[-1] - minima_x[-1]) Huang_time", "c='grey', zorder=1) axs[1].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey',", "for j in range(1, len(knots_uniform)): axs[i].plot(knots_uniform[j] * np.ones(101), np.linspace(-2, 2,", "c='grey', label='Knots') axs[2].plot(knots[2][0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey',", "* np.ones_like(length_time) point_2 = 5.2 length_distance_2 = np.linspace(time_series[-1], minima_y[-1], 101)", "IP, IF, IA = emd040.spectra.frequency_transform(py_emd[:2, :].T, 12, 'hilbert') print(f'PyEMD annual", "factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time, time_series, LineWidth=2, label='Signal') plt.title('Slope-Based Edge", "import random import textwrap import emd_mean import AdvEMDpy import emd_basis", "= time_series_reflect[0] - time_series_reflect utils = emd_utils.Utility(time=time, time_series=time_series_anti_reflect) anti_max_bool =", "emd_utils.Utility(time=time, time_series=time_series) max_bool = utils.max_bool_func_1st_order_fd() maxima_x = time[max_bool] maxima_y =", "+ i_right + 1)]) if sum(emd_utils_min.min_bool_func_1st_order_fd()) > 0: min_count_right +=", "imfs_51[3, :], label=textwrap.fill('Sum of IMF 2 and IMF 3 with", "12)) axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.10)[1], c='grey') axs[0].plot(np.linspace(0.85 * np.pi, 1.15 *", "$') plt.plot(time[500:], b_spline_basis[4, 500:].T, '--', label=r'$ B_{-1,4}(t) $') plt.plot(time[500:], b_spline_basis[5,", "r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2 and Statically Optimised Knots') axs[2].plot(knot_demonstrate_time, imfs[2,", "emd_utils.Utility(time=time_extended[int(2 * (len(lsq_signal) - 1) + 1): int(2 * (len(lsq_signal)", "dash_max_min_2_y = -1.8 * np.ones_like(dash_max_min_2_y_time) max_1_x_time = np.linspace(maxima_x[-1] - width,", "Demonstration') axs[1].set_title('Zoomed Region') preprocess_time = pseudo_alg_time.copy() np.random.seed(1) random.seed(1) preprocess_time_series =", "axs[1].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2 and Uniform Knots') axs[2].plot(knot_demonstrate_time, imfs[2,", "((time_extended[-1001] + time_extended[-1000]) / 2) - 0.1, 100), -2.75 *", "2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1000]) / 2), ((time_extended[-1001]", "0.7 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) ax.pcolormesh(x_hs, y, np.abs(z), cmap='gist_rainbow', vmin=z_min,", "width, 101) max_2_x_time_side = np.linspace(5.3 * np.pi - width, 5.3", "0.5), fontsize=8) axs[1].plot(time, time_series, label='Time series') axs[1].plot(time, imfs_31[1, :] +", "minima_dash_time_2 = minima_x[-1] * np.ones_like(minima_dash) minima_dash_time_3 = slope_based_minimum_time * np.ones_like(minima_dash)", "- a) * np.pi, 1001) knots = np.linspace((0 + a)", "dash_3, 'k--') plt.plot(dash_4_time, dash_4, 'k--') plt.plot(dash_final_time, dash_final, 'k--') plt.scatter(maxima_x, maxima_y,", "np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[1].plot(pseudo_alg_time, pseudo_alg_time_series, '--',", "a) * np.pi, 1001) time_series = np.cos(time) + np.cos(5 *", "figure_size[1])) ax.pcolormesh(x_hs, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) ax.set_title(textwrap.fill(r'Gaussian Filtered Hilbert", "* np.ones_like(length_distance_2) length_time_2 = np.linspace(point_2 * np.pi - width, point_2", "left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_characteristic_wave.png') plt.show() # plot 6 t =", "knot_demonstrate_time) knots_uniform = np.linspace(0, 2 * np.pi, 51) emd =", "util_nn = emd_utils.Utility(time=t, time_series=signal_orig) maxima = signal_orig[util_nn.max_bool_func_1st_order_fd()] minima = signal_orig[util_nn.min_bool_func_1st_order_fd()]", "emd_basis import emd_utils import numpy as np import pandas as", "other packages Carbon Dioxide - top pyemd = pyemd0215() py_emd", "0].set_title(r'Original CO$_2$ Concentration') axs[0, 1].set_title('Smoothed CO$_2$ Concentration') axs[1, 0].set_title('IMF 1')", "addition fig, axs = plt.subplots(2, 1) fig.subplots_adjust(hspace=0.4) figure_size = plt.gcf().get_size_inches()", "1.15 * np.pi, 101), -3 * np.ones(101), '--', c='black', label=textwrap.fill('Zoomed", "np.ones_like(t[:-1]), 'g--', label=textwrap.fill('Driving function frequency', 15)) plt.xticks([0, 50, 100, 150])", "np.pi) axs[1].plot(time, time_series, label='Time series') axs[1].plot(time, imfs_31[1, :] + imfs_31[2,", "are Not Satisfied', 50)) plt.plot(time, time_series, label='Time series', zorder=2, LineWidth=2)", "101) max_1_y_time = maxima_x[-1] * np.ones_like(max_1_y) min_1_y = np.linspace(minima_y[-1] -", "z_max = 0, np.abs(z).max() figure_size = plt.gcf().get_size_inches() factor = 1.0", "= plt.gcf().get_size_inches() factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10)", "* np.pi * np.ones_like(dash_max_min_2_x) max_2_y = np.linspace(maxima_y[-2] - width, maxima_y[-2]", "200) emd_example = AdvEMDpy.EMD(time=time, time_series=signal) imfs, hts, ifs, _, _,", "= Coughlin_time[Coughlin_min_bool] Coughlin_min = Coughlin_wave[Coughlin_min_bool] max_2_x_time = np.linspace(maxima_x[-2] - width,", "test - top seed_weights = np.ones(neural_network_k) / neural_network_k weights =", "plt.plot(time, binomial_points_envelope, c='deeppink', label=textwrap.fill('Binomial average envelope', 10)) plt.plot(time, np.cos(time), c='black',", "slope_based_minimum_time) dash_4 = np.linspace(slope_based_maximum, slope_based_minimum) maxima_dash = np.linspace(2.5 - width,", "util = Utility(time=time, time_series=time_series) maxima = util.max_bool_func_1st_order_fd() minima = util.min_bool_func_1st_order_fd()", "np.linspace(improved_slope_based_maximum, improved_slope_based_minimum, 101) ax = plt.subplot(111) figure_size = plt.gcf().get_size_inches() factor", "and (i_right < len(lsq_signal) - 1): time_series_extended[int(2 * (len(lsq_signal) -", "XY0 = [1, 1] solution = odeint(duffing_equation, XY0, t) x", "2]) axs[2].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots[0]", "2 * np.pi], labels=[r'0', r'$\\pi$', r'$2\\pi$']) box_0 = ax.get_position() ax.set_position([box_0.x0", "label=textwrap.fill('Henderson-Whittaker smoothing', 13)) downsampled_and_decimated = preprocess.downsample() axs[0].plot(downsampled_and_decimated[0], downsampled_and_decimated[1], label=textwrap.fill('Downsampled &", "'L') plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4,", "3 * np.pi, 4 * np.pi, 5 * np.pi]) axs[2].set_xticklabels(['$0$',", "width, maxima_y[-1] + width, 101) max_1_y_side = np.linspace(-2.1 - width,", "bottom emd_duffing = AdvEMDpy.EMD(time=t, time_series=x) emd_duff, emd_ht_duff, emd_if_duff, _, _,", "+ 1 i_left += 1 if i_left > 1: emd_utils_max", "np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--') axs[0].plot(1.55 * np.pi", "Coughlin_min_time = Coughlin_time[Coughlin_min_bool] Coughlin_min = Coughlin_wave[Coughlin_min_bool] max_2_x_time = np.linspace(maxima_x[-2] -", "* np.pi) z_min, z_max = 0, np.abs(z).max() fig, ax =", "y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) plt.plot(t[:-1], 0.124 * np.ones_like(t[:-1]), '--',", "1 lsq_utils = emd_utils.Utility(time=time, time_series=lsq_signal) utils_extended = emd_utils.Utility(time=time_extended, time_series=time_series_extended) maxima", "101), '--', c='grey', label='Knots') axs[2].plot(knots[0] * np.ones(101), np.linspace(-2, 2, 101),", "= np.sin(knot_demonstrate_time) + np.sin(5 * knot_demonstrate_time) emd = EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series)", "and (2) max_internal_iter and (3) debug (confusing with external debugging)", "plt.xlabel('Time (years)') plt.pcolormesh(time, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(time, np.ones_like(time),", "axs[1].plot(t, emd_duff[2, :], label='AdvEMDpy') print(f'AdvEMDpy driving function error: {np.round(sum(abs(0.1 *", "max_2_y_side, 'k-') plt.plot(min_2_y_time, min_2_y, 'k-') plt.plot(min_2_y_time, min_2_y_side, 'k-') plt.plot(dash_max_min_2_y_time, dash_max_min_2_y,", "= minima_y[-1] * np.ones_like(length_time) point_2 = 5.2 length_distance_2 = np.linspace(time_series[-1],", "= emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=1, verbose=False) fig, axs = plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6)", "np.array(vx.value) max_count_left = 0 min_count_left = 0 i_left = 0", "lsq_utils = emd_utils.Utility(time=time, time_series=lsq_signal) utils_extended = emd_utils.Utility(time=time_extended, time_series=time_series_extended) maxima =", "= minima_x[-2] * np.ones_like(minima_dash) minima_dash_time_2 = minima_x[-1] * np.ones_like(minima_dash) minima_dash_time_3", "np.pi, 5.25 * np.pi) box_0 = ax.get_position() ax.set_position([box_0.x0 - 0.05,", "* np.ones(101), 'k--') axs[2].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101),", "np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--') axs[1].plot(1.55 * np.pi", "average gradients average_gradients = np.mean(gradients, axis=1) # steepest descent max_gradient_vector", "1): time_series_extended[int(len(lsq_signal) - 2 - i_left)] = \\ 2 *", "- np.ones_like(ifs[1, :]))), 3)}') fig, axs = plt.subplots(2, 2) plt.subplots_adjust(hspace=0.5)", "* np.ones_like(minima_line_dash_time) # slightly edit signal to make difference between", "b_spline_basis[4, 500:].T, '--', label=r'$ B_{-1,4}(t) $') plt.plot(time[500:], b_spline_basis[5, 500:].T, '--',", "+= 1 # backward <- P = np.zeros((int(neural_network_k + 1),", "width, 101) min_2_x_time_side = np.linspace(5.3 * np.pi - width, 5.3", "2.75, 100), c='k') plt.plot(((time[-202] + time[-201]) / 2) * np.ones(100),", "0.8, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert_emd.png') plt.show()", "+ 1)) objective = cvx.Minimize(cvx.norm((2 * (vx * P) +", "chsi_basis[11, :].T, '--') axs[1].plot(time, chsi_basis[12, :].T, '--') axs[1].plot(time, chsi_basis[13, :].T,", "axs[0].set_title('Time Series and Uniform Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2, zorder=100) axs[0].set_yticks(ticks=[-2,", "Average_max = (maxima_y[-2] + maxima_y[-1]) / 2 Average_min_time = minima_x[-1]", "* np.pi * t) - emd_duff[2, :])), 3)}') axs[1].plot(t, py_emd[1,", "c='b', zorder=4, label='Minima') plt.plot(Huang_time, Huang_wave, '--', c='darkviolet', label=textwrap.fill('Huang Characteristic Wave',", "* np.pi * np.ones_like(length_distance_2) length_time_2 = np.linspace(point_2 * np.pi -", "maxima_x[-2] * np.ones_like(maxima_dash) maxima_dash_time_2 = maxima_x[-1] * np.ones_like(maxima_dash) maxima_dash_time_3 =", "np.ones_like(max_dash_1) min_dash_1 = np.linspace(minima_y[-1] - width, minima_y[-1] + width, 101)", "minima_y[-1], 101) max_discard = maxima_y[-1] max_discard_time = minima_x[-1] - maxima_x[-1]", "lsq_signal[(-(neural_network_m + neural_network_k - col)):(-(neural_network_m - col))] P[-1, col] =", "np.pi, 101), 5.5 * np.ones(101), 'k--') axs[0].plot(np.linspace(0.95 * np.pi, 1.55", "'--', c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[1].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean filter',", "= np.linspace(minima_x[-2], slope_based_minimum_time, 101) minima_line_dash = -3.4 * np.ones_like(minima_line_dash_time) #", "np.linspace(0, 5 * np.pi, 1001) lsq_signal = np.cos(time) + np.cos(5", "minima_y[-1] * np.ones_like(length_time) point_2 = 5.2 length_distance_2 = np.linspace(time_series[-1], minima_y[-1],", "imfs[2, :], Linewidth=2, zorder=100) axs[2].set_yticks(ticks=[-2, 0, 2]) axs[2].set_xticks(ticks=[0, np.pi, 2", "np.pi - width, 5.3 * np.pi + width, 101) max_2_x", "1 and Statically Optimised Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2, zorder=100)", "- minima_y[-1]), r'$s_2$') plt.text(4.50 * np.pi + (slope_based_minimum_time - minima_x[-1]),", "minima_envelope_smooth = fluctuation.envelope_basis_function_approximation(knots, 'minima', smooth=True, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] inflection_points_envelope =", "zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.scatter(time[optimal_maxima], time_series[optimal_maxima], c='darkred',", "plt.subplots(3, 1) plt.suptitle(textwrap.fill('Comparison of Trends Extracted with Different Knot Sequences", "1, False] EEMD_maxima_envelope = fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'maxima', optimal_maxima, optimal_minima, smooth=False, smoothing_penalty=0.2,", "IMF 3 with 51 knots', 19)) for knot in knots_31:", "box_1.height]) axs[1].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].set_ylim(-5.5, 5.5) axs[1].set_xlim(0.95 *", "Series and Dynamically Optimised Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2, zorder=100) axs[0].set_yticks(ticks=[-2,", "derivative_knots = np.linspace(knots[0], knots[-1], 31) # change (1) detrended_fluctuation_technique and", "np.ones(101), np.linspace(-3, 3, 101), '--', c='black') axs[0].plot(1.15 * np.pi *", "optimal_maxima, optimal_minima, smooth=False, smoothing_penalty=0.2, edge_effect='none')[0] EEMD_minima_envelope = fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'minima', optimal_maxima,", "101), 3 * np.ones(101), '--', c='black') axs[0].plot(0.85 * np.pi *", "ax.set_position([box_0.x0, box_0.y0 + 0.05, box_0.width * 0.85, box_0.height * 0.9])", "* np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1, label='Knots') axs[2].set_xticks([np.pi,", "series') axs[1].plot(time, imfs_31[1, :] + imfs_31[2, :], label=textwrap.fill('Sum of IMF", "plot 1 plt.title('Non-Natural Cubic B-Spline Bases at Boundary') plt.plot(time[500:], b_spline_basis[2,", "$']) plt.xlim(4.4, 6.6) plt.plot(5 * np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-')", "- 1) + 1 + i_right)] = \\ sum(weights_right *", "knots[-1], 31) # change (1) detrended_fluctuation_technique and (2) max_internal_iter and", "'k-') axs[1].set_xticks([5, 6]) axs[1].set_xticklabels([r'$ \\tau_k $', r'$ \\tau_{k+1} $']) axs[1].set_xlim(4.5,", "in range(neural_network_m): P[:-1, col] = lsq_signal[(-(neural_network_m + neural_network_k - col)):(-(neural_network_m", "np.pi, 1001) knots = np.linspace((0 + a) * np.pi, (5", "51) fluc = Fluctuation(time=time, time_series=time_series) max_unsmoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima', smooth=False)", "factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess Filtering", "time_series_reflect, 'g--', LineWidth=2, label=textwrap.fill('Symmetric signal', 10)) plt.plot(time_reflect[:51], time_series_anti_reflect[:51], '--', c='purple',", "np.linspace((0 + a) * np.pi, (5 - a) * np.pi,", "# plot 6 t = np.linspace(5, 95, 100) signal_orig =", "(r'4$\\pi$', r'5$\\pi$')) plt.yticks((-3, -2, -1, 0, 1, 2), ('-3', '-2',", "axs[2].set_xlim(0.95 * np.pi, 1.55 * np.pi) plt.savefig('jss_figures/DFA_different_trends_zoomed.png') plt.show() hs_ouputs =", "1) or (min_count_right < 1)) and (i_right < len(lsq_signal) -", "Trends Extracted with Different Knot Sequences', 40)) plt.subplots_adjust(hspace=0.1) axs[0].plot(time, time_series,", "# \\ / # \\/ import random import textwrap import", "label=textwrap.fill('Quantile window', 12)) axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.10)[1], c='grey') axs[1].set_xlim(0.85 * np.pi,", "2 and IMF 3 with 51 knots', 19)) for knot", "0.05, box_0.width * 0.85, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1,", "maxima_x[-1] * np.ones_like(maxima_dash) maxima_dash_time_3 = slope_based_maximum_time * np.ones_like(maxima_dash) maxima_line_dash_time =", "np.pi, 1.15 * np.pi) axs[1].set_ylim(-3, 3) axs[1].set_yticks(ticks=[-2, 0, 2]) axs[1].set_xticks(ticks=[np.pi])", "# plot 5 a = 0.25 width = 0.2 time", "label=r'$ B_{0,4}(t) $') plt.plot(time[500:], b_spline_basis[6, 500:].T, '--', label=r'$ B_{1,4}(t) $')", "max_1_y, 'k-') plt.plot(max_1_y_time, max_1_y_side, 'k-') plt.plot(min_1_y_time, min_1_y, 'k-') plt.plot(min_1_y_time, min_1_y_side,", "Hilbert Spectrum of Duffing Equation using AdvEMDpy', 40)) x, y,", "axs[1].plot(downsampled[0], downsampled[1], label=textwrap.fill('Downsampled', 13)) axs[1].set_xlim(0.85 * np.pi, 1.15 * np.pi)", "'k--') plt.plot(length_time, length_top, 'k-') plt.plot(length_time, length_bottom, 'k-') plt.plot(length_time_2, length_top_2, 'k-')", "plt.plot(length_time, length_top, 'k-') plt.plot(length_time, length_bottom, 'k-') plt.plot(length_time_2, length_top_2, 'k-') plt.plot(length_time_2,", "3)}') for knot in knots_11: axs[2].plot(knot * np.ones(101), np.linspace(-5, 5,", "axs[2].set_ylim(-5.5, 5.5) axs[2].set_xlim(0.95 * np.pi, 1.55 * np.pi) plt.savefig('jss_figures/DFA_different_trends_zoomed.png') plt.show()", "* np.pi + width, 101) min_1_x = minima_y[-1] * np.ones_like(min_1_x_time)", "factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Duffing Equation", "= 0 i_left = 0 while ((max_count_left < 1) or", "Coughlin_min_bool = utils_Coughlin.min_bool_func_1st_order_fd() Huang_max_time = Huang_time[Huang_max_bool] Huang_max = Huang_wave[Huang_max_bool] Huang_min_time", "slope_based_maximum_time * np.ones_like(max_dash_1) max_dash_3 = np.linspace(slope_based_maximum - width, slope_based_maximum +", "smoothing', 12)) axs[1].plot(preprocess_time, preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker smoothing', 13)) axs[1].plot(downsampled_and_decimated[0], downsampled_and_decimated[1], label=textwrap.fill('Downsampled", "= Coughlin_wave[Coughlin_min_bool] max_2_x_time = np.linspace(maxima_x[-2] - width, maxima_x[-2] + width,", "emd_if_duff, _, _, _, _ = emd_duffing.empirical_mode_decomposition(verbose=False) fig, axs =", "axs[2].set_xticklabels(['$0$', r'$\\pi$', r'$2\\pi$', r'$3\\pi$', r'$4\\pi$', r'$5\\pi$']) box_2 = axs[2].get_position() axs[2].set_position([box_2.x0", "knots, _, _ = emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=1, verbose=False) fig, axs =", "range(neural_network_m): P[:-1, col] = lsq_signal[(-(neural_network_m + neural_network_k - col)):(-(neural_network_m -", "minima_x = time[min_bool] minima_y = time_series[min_bool] max_dash_1 = np.linspace(maxima_y[-1] -", "0: ax.set_ylabel('x(t)') ax.set_yticks(y_points_1) if axis == 1: ax.set_ylabel(r'$ \\dfrac{dx(t)}{dt} $')", "np.linspace(-1.8 - width, -1.8 + width, 101) max_2_y_time = maxima_x[-2]", "additive constant t = lsq_signal[:neural_network_m] vx = cvx.Variable(int(neural_network_k + 1))", "utils = emd_utils.Utility(time=time, time_series=time_series_anti_reflect) anti_max_bool = utils.max_bool_func_1st_order_fd() anti_max_point_time = time_reflect[anti_max_bool]", "= np.cos(time) + np.cos(5 * time) knots = np.linspace(0, 5", "= fluctuation.envelope_basis_function_approximation(knots, 'maxima', smooth=False, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] maxima_envelope_smooth = fluctuation.envelope_basis_function_approximation(knots,", "Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2, zorder=100) axs[2].set_yticks(ticks=[-2, 0, 2]) axs[2].set_xticks(ticks=[0,", "= plt.subplots(1, 2, sharey=True) axs[0].set_title('Cubic B-Spline Bases') axs[0].plot(time, b_spline_basis[2, :].T,", "activation function is arbitrary prob = cvx.Problem(objective) result = prob.solve(verbose=True,", "0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht_pyemd.png') plt.show() plt.show() emd_sift =", "2 * np.pi, 3 * np.pi, 4 * np.pi, 5", "5 * np.pi, 51) time_series = np.cos(2 * time) +", "ts): gamma = 0.1 epsilon = 1 omega = ((2", "maxima_envelope_smooth, c='darkred', label=textwrap.fill('SEMD envelope', 10)) plt.plot(time, minima_envelope_smooth, c='darkred') plt.plot(time, (maxima_envelope_smooth", "= plt.subplots(3, 1) plt.suptitle(textwrap.fill('Comparison of Trends Extracted with Different Knot", "= pyemd0215() py_emd = pyemd(x) IP, IF, IA = emd040.spectra.frequency_transform(py_emd.T,", "time_series=preprocess_time_series) axs[0].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[0].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time", "hht = gaussian_filter(hht, sigma=1) fig, ax = plt.subplots() figure_size =", "np.linspace(maxima_y[-2] - width, maxima_y[-2] + width, 101) max_dash_time_1 = maxima_x[-1]", "length_bottom, 'k-') plt.plot(length_time_2, length_top_2, 'k-') plt.plot(length_time_2, length_bottom_2, 'k-') plt.plot(end_time, end_signal,", "'--', c='grey') plt.savefig('jss_figures/knot_uniform.png') plt.show() # plot 1b - addition knot_demonstrate_time", "plt.plot(dash_1_time, dash_1, 'k--') plt.plot(dash_2_time, dash_2, 'k--') plt.plot(dash_3_time, dash_3, 'k--') plt.plot(dash_4_time,", "np.r_[False, utils.derivative_forward_diff() > 0, False] & \\ np.r_[utils.zero_crossing() == 1,", "optimal_minima = np.r_[False, utils.derivative_forward_diff() > 0, False] & \\ np.r_[utils.zero_crossing()", "plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time, time_series, LineWidth=2, label='Signal') plt.title('Slope-Based Edge Effects Example') plt.plot(max_dash_time_1,", "spline_method='b_spline')[0] minima_envelope = fluctuation.envelope_basis_function_approximation(knots, 'minima', smooth=False, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] minima_envelope_smooth", "* np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1) axs[1].plot(knot *", "max_dash_2, 'k-') plt.plot(max_dash_time_3, max_dash_3, 'k-') plt.plot(min_dash_time_1, min_dash_1, 'k-') plt.plot(min_dash_time_2, min_dash_2,", "* np.pi + (minima_x[-1] - minima_x[-2]), 0.35 + (minima_y[-1] -", "np.matmul(weights, train_input) error = (t - output) gradients = error", "width, -1.8 + width, 101) max_2_y_time = maxima_x[-2] * np.ones_like(max_2_y)", "fig.subplots_adjust(hspace=0.4) figure_size = plt.gcf().get_size_inches() factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor *", "* (improved_slope_based_minimum_time - improved_slope_based_maximum_time) min_dash_4 = np.linspace(improved_slope_based_minimum - width, improved_slope_based_minimum", "i_right): int(2 * (len(lsq_signal) - 1) + 1 + i_right)],", "r'$2a_2$') plt.plot(max_2_y_time, max_2_y, 'k-') plt.plot(max_2_y_time, max_2_y_side, 'k-') plt.plot(min_2_y_time, min_2_y, 'k-')", "40)) plt.subplots_adjust(hspace=0.1) axs[0].plot(time, time_series, label='Time series') axs[0].plot(time, imfs_51[1, :] +", "extrema_type='minima', smooth=False) min_smoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima', smooth=True) util = Utility(time=time,", "maxima_x[-1], 101) dash_max_min_1_y = -2.1 * np.ones_like(dash_max_min_1_y_time) ax = plt.subplot(111)", "hilbert_spectrum(t, emd_duff, emd_ht_duff, emd_if_duff, max_frequency=1.3, plot=False) ax = plt.subplot(111) plt.title(textwrap.fill('Gaussian", "LineWidth=2, label=textwrap.fill('Symmetric signal', 10)) plt.plot(time_reflect[:51], time_series_anti_reflect[:51], '--', c='purple', LineWidth=2, label=textwrap.fill('Anti-symmetric", "plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.scatter(time[optimal_maxima], time_series[optimal_maxima], c='darkred', zorder=4, label=textwrap.fill('Optimal", ":] + imfs_51[2, :] + imfs_51[3, :])), 3)}') for knot", "box_0.width * 0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/detrended_fluctuation_analysis.png') plt.show()", "= time_series[min_bool] max_dash_time = np.linspace(maxima_x[-1] - width, maxima_x[-1] + width,", "lr = 0.01 for iterations in range(1000): output = np.matmul(weights,", "axs[1].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), 5.5 * np.ones(101),", "= np.flip(np.cos(np.linspace((5 - 2.6 * a) * np.pi, (5 -", "Huang_wave[Huang_min_bool] Coughlin_max_time = Coughlin_time[Coughlin_max_bool] Coughlin_max = Coughlin_wave[Coughlin_max_bool] Coughlin_min_time = Coughlin_time[Coughlin_min_bool]", "in range(1000): output = np.matmul(weights, train_input) error = (t -", "axs[1, 1].set_title('Residual') plt.gcf().subplots_adjust(bottom=0.15) plt.savefig('jss_figures/CO2_EMD.png') plt.show() hs_ouputs = hilbert_spectrum(time, imfs, hts,", "'--', c='purple', LineWidth=2, label=textwrap.fill('Anti-symmetric signal', 10)) plt.plot(max_dash_time, max_dash, 'k-') plt.plot(min_dash_time,", "z_min, z_max = 0, np.abs(z).max() figure_size = plt.gcf().get_size_inches() factor =", "maxima_line_dash_time = np.linspace(maxima_x[-2], slope_based_maximum_time, 101) maxima_line_dash = 2.5 * np.ones_like(maxima_line_dash_time)", "np.linspace(minima_y[-2] - width, minima_y[-2] + width, 101) min_2_y_side = np.linspace(-1.8", "3 with 51 knots', 19)) for knot in knots_31: axs[1].plot(knot", "100), c='gray', linestyle='dashed', label=textwrap.fill('Neural network targets', 13)) plt.plot(np.linspace(((time[-202] + time[-201])", "maxima_x[-2]) Average_max = (maxima_y[-2] + maxima_y[-1]) / 2 Average_min_time =", ":].T, '--', label='Basis 4') axs[0].legend(loc='upper left') axs[0].plot(5 * np.ones(100), np.linspace(-0.2,", "length_top_2, 'k-') plt.plot(length_time_2, length_bottom_2, 'k-') plt.plot(end_time, end_signal, 'k-') plt.plot(symmetry_axis_1_time, symmetry_axis,", "- width, minima_x[-2] + width, 101) min_2_x_time_side = np.linspace(5.3 *", "np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) plt.plot(t[:-1], 0.124 * np.ones_like(t[:-1]), '--', label=textwrap.fill('Hamiltonian", "addition knot_demonstrate_time = np.linspace(0, 2 * np.pi, 1001) knot_demonstrate_time_series =", "axs[1].set_xticks([5, 6]) axs[1].set_xticklabels([r'$ \\tau_k $', r'$ \\tau_{k+1} $']) axs[1].set_xlim(4.5, 6.5)", "101), 5.5 * np.ones(101), 'k--') axs[1].plot(np.linspace(0.95 * np.pi, 1.55 *", "((time_extended[-1001] + time_extended[-1002]) / 2) - 0.1, 100), -2.75 *", "maxima_y[-2], 101) dash_max_min_2_x_time = 5.3 * np.pi * np.ones_like(dash_max_min_2_x) max_2_y", "+ width, 101) max_dash = maxima_y[-1] * np.ones_like(max_dash_time) min_dash_time =", "= maxima_x[-2] * np.ones_like(max_dash_1) min_dash_1 = np.linspace(minima_y[-1] - width, minima_y[-1]", "symmetry_axis_1_time = minima_x[-1] * np.ones(101) symmetry_axis_2_time = time[-1] * np.ones(101)", "101) time_series_reflect = np.flip(np.cos(np.linspace((5 - 2.6 * a) * np.pi,", "- width, maxima_y[-1] + width, 101) max_1_y_side = np.linspace(-2.1 -", "np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--') axs[0].plot(1.55 * np.pi * np.ones(101),", "axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.90)[1], c='grey', label=textwrap.fill('Quantile window', 12)) axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.10)[1],", "axs[0].legend(loc='upper left') axs[0].plot(5 * np.ones(100), np.linspace(-0.2, 0.8, 100), 'k-') axs[0].plot(6", "np.pi, 3 * np.pi, 4 * np.pi]) ax.set_xticklabels(['$0$', r'$\\pi$', r'$2\\pi$',", "neural_network_k weights = 0 * seed_weights.copy() train_input = P[:-1, :]", "* np.pi) axs[2].plot(time, time_series, label='Time series') axs[2].plot(time, imfs_11[1, :], label='IMF", "'-1', '0', '1', '2')) plt.xlim(-0.25 * np.pi, 5.25 * np.pi)", "dash_max_min_2_y_time = np.linspace(minima_x[-2], maxima_x[-2], 101) dash_max_min_2_y = -1.8 * np.ones_like(dash_max_min_2_y_time)", "time_series=knot_demonstrate_time_series) imfs = emd.empirical_mode_decomposition(knots=knots_uniform, edge_effect='anti-symmetric', verbose=False)[0] fig, axs = plt.subplots(3,", "(min_count_right < 1)) and (i_right < len(lsq_signal) - 1): time_series_extended[int(2", "label='Smoothed') axs[0, 1].legend(loc='lower right') axs[1, 0].plot(time, imfs[1, :]) axs[1, 1].plot(time,", "label='Basis 2') axs[0].plot(time, b_spline_basis[4, :].T, '--', label='Basis 3') axs[0].plot(time, b_spline_basis[5,", "* np.pi * t / 25) + 0.5 * np.sin(2", "dash_4_time = np.linspace(slope_based_maximum_time, slope_based_minimum_time) dash_4 = np.linspace(slope_based_maximum, slope_based_minimum) maxima_dash =", "150] x_names = {0, 50, 100, 150} y_points_1 = [-2,", "10)) plt.plot(time, binomial_points_envelope, c='deeppink', label=textwrap.fill('Binomial average envelope', 10)) plt.plot(time, np.cos(time),", "plt.xticks((0, 1 * np.pi, 2 * np.pi, 3 * np.pi,", "+ width, 101) max_2_x = maxima_y[-2] * np.ones_like(max_2_x_time) min_2_x_time =", "axs[2].get_position() axs[2].set_position([box_2.x0 - 0.05, box_2.y0, box_2.width * 0.85, box_2.height]) axs[2].legend(loc='center", "linestyle='dashed', label=textwrap.fill('Neural network targets', 13)) plt.plot(np.linspace(((time[-202] + time[-201]) / 2),", "- Coughlin_time[0])) Average_max_time = maxima_x[-1] + (maxima_x[-1] - maxima_x[-2]) Average_max", "100), -2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1000]) / 2),", "= plt.gcf().get_size_inches() factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian", "zorder=5) plt.yticks(ticks=[-2, -1, 0, 1, 2]) plt.xticks(ticks=[0, np.pi, 2 *", "* np.ones(101), np.linspace(-2, 2, 101), '--', c='grey') plt.savefig('jss_figures/knot_2.png') plt.show() #", "minima_y, c='b', zorder=4, label='Minima') plt.plot(Huang_time, Huang_wave, '--', c='darkviolet', label=textwrap.fill('Huang Characteristic", "np.linspace(-0.2, 0.8, 100), 'k-') axs[0].plot(6 * np.ones(100), np.linspace(-0.2, 0.8, 100),", "print(f'DFA fluctuation with 31 knots: {np.round(np.var(time_series - (imfs_31[1, :] +", "plt.plot(minima_dash_time_3, minima_dash, 'k-') plt.text(4.34 * np.pi, -3.2, r'$\\Delta{t^{min}_{m}}$') plt.text(4.74 *", "label=textwrap.fill('Slope-based maximum', 11)) plt.scatter(slope_based_minimum_time, slope_based_minimum, c='purple', zorder=4, label=textwrap.fill('Slope-based minimum', 11))", "(time_series[time >= maxima_x[-2]] - time_series[time == maxima_x[-2]]) + maxima_y[-1] Coughlin_time", "((time[-302] + time[-301]) / 2) + 0.1, 100), 2.75 *", "= odeint(duffing_equation, XY0, t) x = solution[:, 0] dxdt =", "error = (t - output) gradients = error * (-", "label=r'$\\omega = 4$', Linewidth=3) ax.plot(x_hs[0, :], 2 * np.ones_like(x_hs[0, :]),", "= np.linspace(minima_x[-2], maxima_x[-2], 101) dash_max_min_2_y = -1.8 * np.ones_like(dash_max_min_2_y_time) max_1_x_time", "150]) axs[1].plot(t, dxdt) axs[1].set_title('Duffing Equation Velocity') axs[1].set_ylim([-1.5, 1.5]) axs[1].set_xlim([0, 150])", "2 * np.abs(maxima_x[-2] - minima_x[-2]) P1 = 2 * np.abs(maxima_x[-1]", "0].plot(time, signal) axs[0, 1].plot(time, signal) axs[0, 1].plot(time, imfs[0, :], label='Smoothed')", "axs[0].set_xlim(0.95 * np.pi, 1.55 * np.pi) axs[1].plot(time, time_series, label='Time series')", "label=textwrap.fill('Neural network inputs', 13)) plt.plot(np.linspace(((time[-302] + time[-301]) / 2), ((time[-302]", "2, 101), '--', c='grey') plt.savefig('jss_figures/knot_1.png') plt.show() # plot 1c -", "fontsize=8) axs[2].set_ylim(-5.5, 5.5) axs[2].set_xlim(0.95 * np.pi, 1.55 * np.pi) plt.savefig('jss_figures/DFA_different_trends_zoomed.png')", "False] EEMD_maxima_envelope = fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'maxima', optimal_maxima, optimal_minima, smooth=False, smoothing_penalty=0.2, edge_effect='none')[0]", "slope_based_minimum_time, 101) minima_line_dash = -3.4 * np.ones_like(minima_line_dash_time) # slightly edit", "minima_y[-1]), r'$s_2$') plt.text(4.50 * np.pi + (slope_based_minimum_time - minima_x[-1]), 1.20", "figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Duffing Equation using PyEMD", "# plot 7 a = 0.25 width = 0.2 time", "100), -2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time[-202] + time[-201]) / 2),", "- minima_x[-2]) slope_based_minimum = slope_based_maximum - (slope_based_maximum_time - slope_based_minimum_time) *", "* np.pi, 51) emd = EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series) imfs = emd.empirical_mode_decomposition(knots=knots_uniform,", "+ time_extended[-1000]) / 2) * np.ones(100), np.linspace(-2.75, 2.75, 100), c='gray',", "imfs_51[1, :] + imfs_51[2, :] + imfs_51[3, :], label=textwrap.fill('Sum of", "np.linspace(maxima_x[-1] - width, maxima_x[-1] + width, 101) max_1_x_time_side = np.linspace(5.4", "max_2_y = np.linspace(maxima_y[-2] - width, maxima_y[-2] + width, 101) max_2_y_side", "knots = np.linspace(0, 5 * np.pi, 51) fluc = Fluctuation(time=time,", "('-2', '-1', '0', '1', '2')) box_0 = ax.get_position() ax.set_position([box_0.x0 -", "Duffing - bottom emd_duffing = AdvEMDpy.EMD(time=t, time_series=x) emd_duff, emd_ht_duff, emd_if_duff,", "imfs_51[3, :])), 3)}') for knot in knots_51: axs[0].plot(knot * np.ones(101),", "'--', c='grey', zorder=1) axs[1].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--',", "axis == 3: ax.set(xlabel='Time (years)') axis += 1 plt.gcf().subplots_adjust(bottom=0.15) axs[0,", "14)) axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.90)[1], c='grey', label=textwrap.fill('Quantile window', 12)) axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window,", "= 0.9 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum", "101), '--', c='grey', zorder=1) axs[1].plot(knot * np.ones(101), np.linspace(-5, 5, 101),", "figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time, time_series, LineWidth=2, label='Signal') plt.title('Slope-Based Edge Effects Example')", "np.linspace(slope_based_maximum_time, slope_based_minimum_time) dash_4 = np.linspace(slope_based_maximum, slope_based_minimum) maxima_dash = np.linspace(2.5 -", "label='Knots') for i in range(3): for j in range(1, len(knots_uniform)):", "+ time[-201]) / 2) + 0.1, 100), -2.75 * np.ones(100),", "Envelopes if Schoenberg–Whitney Conditions are Not Satisfied', 50)) plt.plot(time, time_series,", "0: ax.set_ylabel(r'$\\gamma_1(t)$') ax.set_yticks([-2, 0, 2]) if axis == 1: ax.set_ylabel(r'$\\gamma_2(t)$')", "* np.ones(101), 'k--') axs[0].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101),", "downsampled_and_decimated = preprocess.downsample() axs[0].plot(downsampled_and_decimated[0], downsampled_and_decimated[1], label=textwrap.fill('Downsampled & decimated', 11)) downsampled", "np.asarray(time) # compare other packages Carbon Dioxide - top pyemd", "np.cos(time) + np.cos(5 * time) utils = emd_utils.Utility(time=time, time_series=time_series) max_bool", "Spectrum of Duffing Equation using emd 0.3.3', 40)) plt.pcolormesh(t, freq_bins,", "odeint(duffing_equation, XY0, t) x = solution[:, 0] dxdt = solution[:,", "np.linspace(-2.75, 2.75, 100), c='gray', linestyle='dashed', label=textwrap.fill('Neural network targets', 13)) plt.plot(np.linspace(((time[-202]", "dash_max_min_1_y_time = np.linspace(minima_x[-1], maxima_x[-1], 101) dash_max_min_1_y = -2.1 * np.ones_like(dash_max_min_1_y_time)", "print(f'AdvEMDpy driving function error: {np.round(sum(abs(0.1 * np.cos(0.04 * 2 *", "+ (slope_based_maximum_time - minima_x[-1]) * s1 max_dash_time_3 = slope_based_maximum_time *", "& \\ np.r_[utils.zero_crossing() == 1, False] EEMD_maxima_envelope = fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'maxima',", "maxima', 10)) plt.scatter(time[optimal_minima], time_series[optimal_minima], c='darkblue', zorder=4, label=textwrap.fill('Optimal minima', 10)) plt.scatter(inflection_x,", "filter', 12)) axs[0].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize interpolation filter', 14)) axs[0].plot(preprocess_time,", "0.5)) plt.savefig('jss_figures/neural_network.png') plt.show() # plot 6a np.random.seed(0) time = np.linspace(0,", "r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1 and Statically Optimised Knots') axs[1].plot(knot_demonstrate_time, imfs[1,", "c='darkorange', zorder=4, label=textwrap.fill('Coughlin maximum', 14)) plt.scatter(Coughlin_min_time, Coughlin_min, c='dodgerblue', zorder=4, label=textwrap.fill('Coughlin", "label='Maxima', zorder=10) plt.scatter(time[minima], time_series[minima], c='b', label='Minima', zorder=10) plt.plot(time, max_unsmoothed[0], label=textwrap.fill('Unsmoothed", "width, 101) min_dash = minima_y[-1] * np.ones_like(min_dash_time) dash_1_time = np.linspace(maxima_x[-1],", "smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] inflection_points_envelope = fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True, smoothing_penalty=0.2, technique='inflection_points')[0] binomial_points_envelope", "plt.subplot(111) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Duffing Equation using AdvEMDpy',", "0 min_count_right = 0 i_right = 0 while ((max_count_right <", "ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert_pyemd.png') plt.show() emd_sift = emd040.sift.sift(signal) IP,", "time = np.linspace(0, 5 * np.pi, 1001) time_series = np.cos(time)", "axs[2].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots[0][0] *", "t / 200) util_nn = emd_utils.Utility(time=t, time_series=signal_orig) maxima = signal_orig[util_nn.max_bool_func_1st_order_fd()]", "np.pi, 5 * np.pi]) axs[1].set_xticklabels(['', '', '', '', '', ''])", "r'$ \\tau_{k+1} $']) axs[0].set_xlim(4.5, 6.5) axs[1].set_title('Cubic Hermite Spline Bases') axs[1].plot(time,", "plt.subplots(2, 1) plt.subplots_adjust(hspace=0.3) figure_size = plt.gcf().get_size_inches() factor = 0.8 plt.gcf().set_size_inches((figure_size[0],", "0.85, box_1.height]) plt.savefig('jss_figures/preprocess_filter.png') plt.show() # plot 1e - addition fig,", "11 knots') axs[2].plot(time, imfs_31[2, :], label='IMF 2 with 31 knots')", "emd.empirical_mode_decomposition(knots=derivative_knots, knot_time=derivative_time, text=False, verbose=False)[0][1, :] utils = emd_utils.Utility(time=time[:-1], time_series=imf_1_of_derivative) optimal_maxima", "< 0, False] & \\ np.r_[utils.zero_crossing() == 1, False] optimal_minima", "= np.linspace(-2.1 - width, -2.1 + width, 101) max_1_y_time =", "2) * np.pi]) axs[2].set_xticklabels([r'$\\pi$', r'$\\frac{3}{2}\\pi$']) box_2 = axs[2].get_position() axs[2].set_position([box_2.x0 -", "zorder=1) axs[1].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1,", "left') plt.savefig('jss_figures/boundary_bases.png') plt.show() # plot 1a - addition knot_demonstrate_time =", "= emd_utils.Utility(time=time, time_series=time_series) max_bool = utils.max_bool_func_1st_order_fd() maxima_x = time[max_bool] maxima_y", "q=0.10)[1], c='grey') axs[0].plot(np.linspace(0.85 * np.pi, 1.15 * np.pi, 101), -3", "ax = plt.subplots() figure_size = plt.gcf().get_size_inches() factor = 0.8 plt.gcf().set_size_inches((figure_size[0],", "max_dash_time = np.linspace(maxima_x[-1] - width, maxima_x[-1] + width, 101) max_dash", "slope_based_maximum + width, 101) dash_3_time = np.linspace(minima_x[-1], slope_based_maximum_time, 101) dash_3", "= \\ sum(weights_right * np.hstack((time_series_extended[ int(2 * (len(lsq_signal) - 1)", "= 8$', Linewidth=3) ax.plot(x_hs[0, :], 4 * np.ones_like(x_hs[0, :]), '--',", "- time_series[time == minima_x[-1]]) + \\ time_series[time == minima_x[-1]] improved_slope_based_maximum_time", "for i in range(3): for j in range(1, len(knots[i])): axs[i].plot(knots[i][j]", "* t / 25) + 0.5 * np.sin(2 * np.pi", "3)}') for knot in knots_31: axs[1].plot(knot * np.ones(101), np.linspace(-5, 5,", "min_dash_time_3 = slope_based_minimum_time * np.ones_like(min_dash_1) min_dash_3 = np.linspace(slope_based_minimum - width,", "* t) - emd_sift[:, 1])), 3)}') axs[1].plot(t, 0.1 * np.cos(0.04", "np.pi, (5 - a) * np.pi, 1001) knots = np.linspace((0", "left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert_emd.png') plt.show() # compare other packages Carbon", "box_1.width * 0.85, box_1.height]) plt.savefig('jss_figures/preprocess_smooth.png') plt.show() # plot 2 fig,", "* time) knots = np.linspace(0, 5 * np.pi, 101) time_extended", "and improved slope-based method more clear time_series[time >= minima_x[-1]] =", "/ 25) + 0.5 * np.sin(2 * np.pi * t", "= fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'maxima', optimal_maxima, optimal_minima, smooth=False, smoothing_penalty=0.2, edge_effect='none')[0] EEMD_minima_envelope =", "maxima_dash, 'k-') plt.plot(maxima_dash_time_3, maxima_dash, 'k-') plt.plot(minima_dash_time_1, minima_dash, 'k-') plt.plot(minima_dash_time_2, minima_dash,", "- width, slope_based_minimum + width, 101) dash_4_time = np.linspace(slope_based_maximum_time, slope_based_minimum_time)", "< len(lsq_signal) - 1): time_series_extended[int(len(lsq_signal) - 2 - i_left)] =", "plt.scatter(time[minima], time_series[minima], c='b', label='Minima', zorder=10) plt.plot(time, max_unsmoothed[0], label=textwrap.fill('Unsmoothed maxima envelope',", "- 1 - i_left):int(len(lsq_signal))]) if sum(emd_utils_max.max_bool_func_1st_order_fd()) > 0: max_count_left +=", "plot 6c time = np.linspace(0, 5 * np.pi, 1001) time_series", "minima_x[-2]) slope_based_minimum = slope_based_maximum - (slope_based_maximum_time - slope_based_minimum_time) * s2", "maxima_x[-1]) slope_based_maximum_time = maxima_x[-1] + (maxima_x[-1] - maxima_x[-2]) slope_based_maximum =", "linear activation function is arbitrary prob = cvx.Problem(objective) result =", "101) dash_1 = np.linspace(maxima_y[-1], minima_y[-1], 101) max_discard = maxima_y[-1] max_discard_time", "plt.scatter(maxima_time, maxima, c='r', zorder=3, label='Maxima') plt.scatter(minima_time, minima, c='b', zorder=3, label='Minima')", "label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.scatter(slope_based_maximum_time, slope_based_maximum, c='orange', zorder=4,", "ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Detrended Fluctuation Analysis Examples') plt.plot(time, time_series,", "axs[2].set_position([box_2.x0 - 0.05, box_2.y0, box_2.width * 0.85, box_2.height]) axs[2].legend(loc='center left',", "51 knots', 19)) print(f'DFA fluctuation with 31 knots: {np.round(np.var(time_series -", "'r--', zorder=1) plt.plot(symmetry_axis_2_time, symmetry_axis, 'r--', label=textwrap.fill('Axes of symmetry', 10), zorder=1)", "signal to make difference between slope-based method and improved slope-based", "weights_left = np.array(vx.value) max_count_left = 0 min_count_left = 0 i_left", "* (time[time >= maxima_x[-2]] - time[time == maxima_x[-2]]) + maxima_x[-1]", "= 0 for ax in axs.flat: ax.label_outer() if axis ==", "np.pi * t / 50) + 0.6 * np.cos(2 *", "c='gray') plt.plot(((time_extended[-1001] + time_extended[-1000]) / 2) * np.ones(100), np.linspace(-2.75, 2.75,", "symmetry_axis_2_time = time[-1] * np.ones(101) symmetry_axis = np.linspace(-2, 2, 101)", "-1, 0, 1, 2), ('-3', '-2', '-1', '0', '1', '2'))", "knots') axs[2].plot(time, imfs_51[3, :], label='IMF 3 with 51 knots') for", "np.ones(101), 'k--') axs[1].plot(0.95 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101),", "label=r'$0.1$cos$(0.08{\\pi}t)$') axs[1].set_title('IMF 2') axs[1].set_ylim([-0.2, 0.4]) axs[1].set_xlim([0, 150]) axis = 0", "'--', label=textwrap.fill('Hamiltonian frequency approximation', 15)) plt.plot(t[:-1], 0.04 * np.ones_like(t[:-1]), 'g--',", "= emd_mean.Fluctuation(time=time, time_series=time_series) maxima_envelope = fluctuation.envelope_basis_function_approximation(knots, 'maxima', smooth=False, smoothing_penalty=0.2, edge_effect='none',", "driving function error: {np.round(sum(abs(0.1 * np.cos(0.04 * 2 * np.pi", "AdvEMDpy', 40)) x, y, z = hs_ouputs y = y", "-1, 0, 1, 2]) plt.xticks(ticks=[0, np.pi, 2 * np.pi], labels=[r'0',", "1))) i_right += 1 if i_right > 1: emd_utils_max =", "+ imfs_31[2, :])), 3)}') for knot in knots_31: axs[1].plot(knot *", "1 plt.savefig('jss_figures/Duffing_equation.png') plt.show() # compare other packages Duffing - top", "s2 * (improved_slope_based_minimum_time - improved_slope_based_maximum_time) min_dash_4 = np.linspace(improved_slope_based_minimum - width,", "= np.linspace(minima_x[-1] - width, minima_x[-1] + width, 101) min_dash =", "0: min_count_left += 1 lsq_utils = emd_utils.Utility(time=time, time_series=lsq_signal) utils_extended =", "axs[2].plot(time, imfs_31[2, :], label='IMF 2 with 31 knots') axs[2].plot(time, imfs_51[3,", "c='black', label='True mean') plt.xticks((0, 1 * np.pi, 2 * np.pi,", "imfs_51[3, :], label='IMF 3 with 51 knots') for knot in", "t = np.linspace(0, 150, 1501) XY0 = [1, 1] solution", "maxima_x[-2] * np.ones_like(max_2_y) min_2_y = np.linspace(minima_y[-2] - width, minima_y[-2] +", "maxima envelope', 10), c='darkorange') plt.plot(time, max_smoothed[0], label=textwrap.fill('Smoothed maxima envelope', 10),", "'maxima', smooth=False, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] maxima_envelope_smooth = fluctuation.envelope_basis_function_approximation(knots, 'maxima', smooth=True,", "- width, 5.3 * np.pi + width, 101) min_2_x =", "plt.gcf().subplots_adjust(bottom=0.10) plt.title(textwrap.fill('Plot Demonstrating Unsmoothed Extrema Envelopes if Schoenberg–Whitney Conditions are", "pseudo_alg_time = np.linspace(0, 2 * np.pi, 1001) pseudo_alg_time_series = np.sin(pseudo_alg_time)", "1.55 * np.pi, 101), 5.5 * np.ones(101), 'k--') axs[1].plot(np.linspace(0.95 *", "np.ones_like(x_hs[0, :]), 'k--', label=textwrap.fill('Annual cycle', 10)) ax.axis([x_hs.min(), x_hs.max(), y.min(), y.max()])", "False] & \\ np.r_[utils.zero_crossing() == 1, False] EEMD_maxima_envelope = fluctuation.envelope_basis_function_approximation_fixed_points(knots,", "preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker smoothing', 13)) downsampled_and_decimated = preprocess.downsample() axs[0].plot(downsampled_and_decimated[0], downsampled_and_decimated[1], label=textwrap.fill('Downsampled", "improved_slope_based_maximum = time_series[-1] improved_slope_based_minimum_time = slope_based_minimum_time improved_slope_based_minimum = improved_slope_based_maximum +", "* np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2,", "0, False] & \\ np.r_[utils.zero_crossing() == 1, False] optimal_minima =", "label='Time series') axs[2].plot(time, imfs_11[1, :], label='IMF 1 with 11 knots')", "(i_left < len(lsq_signal) - 1): time_series_extended[int(len(lsq_signal) - 2 - i_left)]", "# change (1) detrended_fluctuation_technique and (2) max_internal_iter and (3) debug", "with 31 knots', 19)) axs[1].plot(time, imfs_51[2, :] + imfs_51[3, :],", "signal) axs[0, 1].plot(time, imfs[0, :], label='Smoothed') axs[0, 1].legend(loc='lower right') axs[1,", "* np.ones_like(max_discard_dash_time) dash_2_time = np.linspace(minima_x[-1], max_discard_time, 101) dash_2 = np.linspace(minima_y[-1],", "chsi_basis[10, :].T, '--') axs[1].plot(time, chsi_basis[11, :].T, '--') axs[1].plot(time, chsi_basis[12, :].T,", "* np.pi), (r'4$\\pi$', r'5$\\pi$')) plt.yticks((-2, -1, 0, 1, 2), ('-2',", "0.85, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_symmetry_anti.png') plt.show() # plot", "1: ax.set_ylabel(r'$\\gamma_2(t)$') ax.set_yticks([-0.2, 0, 0.2]) box_0 = ax.get_position() ax.set_position([box_0.x0, box_0.y0,", "label='IMF 1 with 11 knots') axs[2].plot(time, imfs_31[2, :], label='IMF 2", "end_point_time = time[-1] end_point = time_series[-1] time_reflect = np.linspace((5 -", "(time_series[time >= minima_x[-1]] - time_series[time == minima_x[-1]]) + \\ time_series[time", "axs[0].plot(preprocess_time, preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott smoothing', 12)) axs[0].plot(preprocess_time, preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker smoothing', 13))", "length_distance_time_2 = point_2 * np.pi * np.ones_like(length_distance_2) length_time_2 = np.linspace(point_2", "+ (slope_based_minimum_time - minima_x[-1]), 1.20 + (slope_based_minimum - minima_y[-1]), r'$s_2$')", "'2')) plt.xlim(-0.25 * np.pi, 5.25 * np.pi) box_0 = ax.get_position()", "101) min_2_y_side = np.linspace(-1.8 - width, -1.8 + width, 101)", "lr * max_gradient_vector weights += adjustment # test - bottom", "box_0.y0 + 0.05, box_0.width * 0.85, box_0.height * 0.9]) ax.legend(loc='center", "5, 101), '--', c='grey', zorder=1) axs[1].plot(knot * np.ones(101), np.linspace(-5, 5,", "Not Satisfied', 50)) plt.plot(time, time_series, label='Time series', zorder=2, LineWidth=2) plt.scatter(time[maxima],", "Dynamically Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2, zorder=100) axs[1].set_yticks(ticks=[-2, 0, 2])", "r'$2\\pi$']) axs[1].set_title('IMF 1 and Statically Optimised Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :],", "time_series=lsq_signal) utils_extended = emd_utils.Utility(time=time_extended, time_series=time_series_extended) maxima = lsq_signal[lsq_utils.max_bool_func_1st_order_fd()] maxima_time =", "minima_x[-1]] - time_series[time == minima_x[-1]]) + \\ time_series[time == minima_x[-1]]", "1, '--', c='r', label=r'$\\tilde{h}_{(1,0)}^M(t)$', zorder=4) plt.scatter(pseudo_alg_time[pseudo_utils.min_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.min_bool_func_1st_order_fd()], c='c', label=r'$m(t_j)$', zorder=3)", "= time_series[-1] * np.ones_like(length_time_2) length_bottom_2 = minima_y[-1] * np.ones_like(length_time_2) symmetry_axis_1_time", "plot=False) ax = plt.subplot(111) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Duffing", "'--', c='grey', label='Knots', zorder=1) plt.xticks((0, 1 * np.pi, 2 *", "np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--') axs[1].plot(1.55 * np.pi * np.ones(101),", "time_series=signal_orig) maxima = signal_orig[util_nn.max_bool_func_1st_order_fd()] minima = signal_orig[util_nn.min_bool_func_1st_order_fd()] cs_max = CubicSpline(t[util_nn.max_bool_func_1st_order_fd()],", "maxima_x[-1] + (maxima_x[-1] - maxima_x[-2]) slope_based_maximum = minima_y[-1] + (slope_based_maximum_time", "width, minima_y[-2] + width, 101) min_dash_time_1 = minima_x[-1] * np.ones_like(min_dash_1)", "-2.1 + width, 101) min_1_y_time = minima_x[-1] * np.ones_like(min_1_y) dash_max_min_1_y_time", "+ width, 101) max_discard_dash = max_discard * np.ones_like(max_discard_dash_time) dash_2_time =", "np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') for i in", "(year$^{-1}$)') plt.xlabel('Time (years)') plt.plot(x_hs[0, :], np.ones_like(x_hs[0, :]), 'k--', label=textwrap.fill('Annual cycle',", "r'5$\\pi$')) plt.yticks((-3, -2, -1, 0, 1, 2), ('-3', '-2', '-1',", "10)) box_0 = ax.get_position() ax.set_position([box_0.x0 + 0.0125, box_0.y0 + 0.075,", "np.hstack((time_series_extended[ int(2 * (len(lsq_signal) - 1) + 1 - neural_network_k", "= np.linspace(time_series[-1], minima_y[-1], 101) length_distance_time_2 = point_2 * np.pi *", "freq_bins = emd040.spectra.define_hist_bins(0, 0.2, 100) hht = emd040.spectra.hilberthuang(IF, IA, freq_edges)", "max_dash_time_2 = maxima_x[-2] * np.ones_like(max_dash_1) min_dash_1 = np.linspace(minima_y[-1] - width,", "minima_x[-1]]) + \\ time_series[time == minima_x[-1]] improved_slope_based_maximum_time = time[-1] improved_slope_based_maximum", "= emd.empirical_mode_decomposition(knots=knots_uniform, edge_effect='anti-symmetric', verbose=False)[0] fig, axs = plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6)", "i in range(3): for j in range(1, len(knots)): axs[i].plot(knots[j] *", "zorder=4, label=textwrap.fill('Inflection points', 10)) plt.plot(time, maxima_envelope, c='darkblue', label=textwrap.fill('EMD envelope', 10))", "maxima_y[-1] * np.ones_like(max_dash_time) min_dash_time = np.linspace(minima_x[-1] - width, minima_x[-1] +", "fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True, smoothing_penalty=0.2, technique='binomial_average', order=21, increment=20)[0] derivative_of_lsq = utils.derivative_forward_diff() derivative_time", "box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.05, box_0.y0, box_0.width * 0.85,", "+ time[-301]) / 2) + 0.1, 100), -2.75 * np.ones(100),", "np.pi, (5 - a) * np.pi, 101))) time_series_anti_reflect = time_series_reflect[0]", "* np.pi]) axs[1].set_xticklabels(['', '', '', '', '', '']) box_1 =", "* np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--') axs[0].plot(1.55 *", "signal = np.asarray(signal) time = CO2_data['month'] time = np.asarray(time) #", "ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width * 0.95, box_0.height]) ax.legend(loc='center left',", "factor * figure_size[1])) ax.pcolormesh(x_hs, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) ax.set_title(textwrap.fill(r'Gaussian", "6]) axs[1].set_xticklabels([r'$ \\tau_k $', r'$ \\tau_{k+1} $']) axs[1].set_xlim(4.5, 6.5) plt.savefig('jss_figures/comparing_bases.png')", "Huang_wave = (A1 / A2) * (time_series[time >= maxima_x[-2]] -", "time_series=time_series) max_unsmoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima', smooth=False) max_smoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima',", "dash_1_time = np.linspace(maxima_x[-1], minima_x[-1], 101) dash_1 = np.linspace(maxima_y[-1], minima_y[-1], 101)", "label=textwrap.fill('Hamiltonian frequency approximation', 15)) plt.plot(t[:-1], 0.04 * np.ones_like(t[:-1]), 'g--', label=textwrap.fill('Driving", "* knot_demonstrate_time) knots_uniform = np.linspace(0, 2 * np.pi, 51) emd", "+ (slope_based_minimum_time - minima_x[-1]), -0.20 + (slope_based_minimum - minima_y[-1]), r'$s_2$')", "axs = plt.subplots(2, 2) plt.subplots_adjust(hspace=0.5) axs[0, 0].plot(time, signal) axs[0, 1].plot(time,", "5, 101), '--', c='grey', zorder=1) axs[2].plot(knot * np.ones(101), np.linspace(-5, 5,", "'k-') axs[0].set_xticks([5, 6]) axs[0].set_xticklabels([r'$ \\tau_k $', r'$ \\tau_{k+1} $']) axs[0].set_xlim(4.5,", "pyemd = pyemd0215() py_emd = pyemd(signal) IP, IF, IA =", "np.ones_like(min_1_y) dash_max_min_1_y_time = np.linspace(minima_x[-1], maxima_x[-1], 101) dash_max_min_1_y = -2.1 *", "'k--') plt.text(5.42 * np.pi, -0.1, r'$2a_1$') plt.plot(max_1_y_time, max_1_y, 'k-') plt.plot(max_1_y_time,", "np.mean(gradients, axis=1) # steepest descent max_gradient_vector = average_gradients * (np.abs(average_gradients)", "Huang_min_bool = utils_Huang.min_bool_func_1st_order_fd() utils_Coughlin = emd_utils.Utility(time=time, time_series=Coughlin_wave) Coughlin_max_bool = utils_Coughlin.max_bool_func_1st_order_fd()", "minima) time = np.linspace(0, 5 * np.pi, 1001) lsq_signal =", "= 4$', Linewidth=3) ax.plot(x_hs[0, :], 2 * np.ones_like(x_hs[0, :]), '--',", "np.pi]) axs[1].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2 and Uniform Knots') axs[2].plot(knot_demonstrate_time,", "max_smoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima', smooth=True) min_unsmoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima', smooth=False)", "emd040.spectra.define_hist_bins(0, 2, 100) hht = emd040.spectra.hilberthuang(IF, IA, freq_edges) hht =", "101) length_distance_time = point_1 * np.pi * np.ones_like(length_distance) length_time =", "c='darkblue') plt.plot(time, maxima_envelope_smooth, c='darkred', label=textwrap.fill('SEMD envelope', 10)) plt.plot(time, minima_envelope_smooth, c='darkred')", "Filtered Hilbert Spectrum of Duffing Equation using emd 0.3.3', 40))", "hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(t[:-1], 0.124 * np.ones_like(t[:-1]), '--', label=textwrap.fill('Hamiltonian", "plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time, time_series, LineWidth=2, label='Signal') plt.title('Symmetry Edge Effects Example') plt.plot(time_reflect,", "i_right > 1: emd_utils_max = \\ emd_utils.Utility(time=time_extended[int(2 * (len(lsq_signal) -", "frequency error: {np.round(sum(np.abs(IF[:, 0] - np.ones_like(IF[:, 0]))), 3)}') freq_edges, freq_bins", "np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') plt.plot(6 * np.ones(100), np.linspace(-0.2, 1.2,", "- width, improved_slope_based_minimum + width, 101) min_dash_time_4 = improved_slope_based_minimum_time *", "smoothing_penalty=0.2, edge_effect='none')[0] EEMD_minima_envelope = fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'minima', optimal_maxima, optimal_minima, smooth=False, smoothing_penalty=0.2,", "* knot_demonstrate_time) emd = EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series) imfs, _, _, _,", "1.2, 100), 'k-') axs[1].set_xticks([5, 6]) axs[1].set_xticklabels([r'$ \\tau_k $', r'$ \\tau_{k+1}", "2), ((time[-202] + time[-201]) / 2) + 0.1, 100), -2.75", "emd_sift[:, 0], '--', label='emd 0.3.3') axs[0].set_title('IMF 1') axs[0].set_ylim([-2, 2]) axs[0].set_xlim([0,", "Coughlin_time = Huang_time Coughlin_wave = A1 * np.cos(2 * np.pi", "ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Characteristic Wave Effects Example') plt.plot(time, time_series,", "axs[1].set_xlim([0, 150]) axis = 0 for ax in axs.flat: ax.label_outer()", "* np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--') axs[0].plot(1.55 * np.pi *", "* np.ones(100), np.linspace(-2.75, 2.75, 100), c='gray', linestyle='dashed', label=textwrap.fill('Neural network targets',", "np.ones_like(end_time) anti_symmetric_time = np.linspace(time[-1] - 0.5, time[-1] + 0.5, 101)", "np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[2].plot(knots[0] * np.ones(101), np.linspace(-2,", "= 0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) axs[0].plot(t, emd_duff[1, :], label='AdvEMDpy')", "np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots_uniform[0] *", "plt.savefig('jss_figures/Duffing_equation.png') plt.show() # compare other packages Duffing - top pyemd", "plt.pcolormesh(time, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(time, np.ones_like(time), 'k--', label=textwrap.fill('Annual", "time_reflect[anti_max_bool] anti_max_point = time_series_anti_reflect[anti_max_bool] utils = emd_utils.Utility(time=time, time_series=time_series_reflect) no_anchor_max_time =", "= time[-1] end_point = time_series[-1] time_reflect = np.linspace((5 - a)", "- neural_network_k + i_right): int(2 * (len(lsq_signal) - 1) +", "numpy as np import pandas as pd import cvxpy as", "10), c='cyan') plt.plot(time, min_smoothed[0], label=textwrap.fill('Smoothed minima envelope', 10), c='blue') for", "len(knots)): axs[i].plot(knots[j] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey') plt.savefig('jss_figures/knot_1.png')", "- 2 - i_left)] = \\ 2 * sum(weights_left *", "* 0.85, box_1.height]) axs[1].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].plot(np.linspace(0.95 *", "= minima_x[-1] + (minima_x[-1] - minima_x[-2]) Average_min = (minima_y[-2] +", "'k--', label='Zoomed region') axs[2].plot(time, time_series, label='Time series') axs[2].plot(time, imfs_11[1, :],", "-2, -1, 0, 1, 2), ('-3', '-2', '-1', '0', '1',", "ax.set_position([box_0.x0, box_0.y0 + 0.05, box_0.width * 0.75, box_0.height * 0.9])", "- imfs_51[3, :]), 3)}') for knot in knots_11: axs[2].plot(knot *", "ax.axis([x_hs.min(), x_hs.max(), y.min(), y.max()]) box_0 = ax.get_position() ax.set_position([box_0.x0 + 0.0125,", "(len(lsq_signal) - 1) + 1 + i_right)], 1))) i_right +=", "np.cos(5 * time) utils = emd_utils.Utility(time=time, time_series=time_series) max_bool = utils.max_bool_func_1st_order_fd()", "'--') axs[1].plot(time, chsi_basis[13, :].T, '--') axs[1].plot(5 * np.ones(100), np.linspace(-0.2, 1.2,", "label=textwrap.fill('Driving function frequency', 15)) plt.xticks([0, 50, 100, 150]) plt.yticks([0, 0.1,", "utils.min_bool_func_1st_order_fd() minima_x = time[min_bool] minima_y = time_series[min_bool] A2 = np.abs(maxima_y[-2]", "emd_utils_max = \\ emd_utils.Utility(time=time_extended[int(2 * (len(lsq_signal) - 1) + 1):", "for ax in axs.flat: ax.label_outer() if axis == 0: ax.set_ylabel(r'$\\gamma_1(t)$')", "= time[-1] improved_slope_based_maximum = time_series[-1] improved_slope_based_minimum_time = slope_based_minimum_time improved_slope_based_minimum =", "axs[0].plot(preprocess_time, preprocess.winsorize(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize filter', 12)) axs[0].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize", "left') axs[1].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots')", "axs[0].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].plot(preprocess_time, preprocess_time_series,", "make difference between slope-based method and improved slope-based method more", "edge_effect='none')[0] ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Detrended Fluctuation Analysis Examples') plt.plot(time,", "plt.gcf().subplots_adjust(bottom=0.10) plt.title('First Iteration of Sifting Algorithm') plt.plot(pseudo_alg_time, pseudo_alg_time_series, label=r'$h_{(1,0)}(t)$', zorder=1)", "* 0.85, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_slope_based.png') plt.show() #", "- 0.05, box_2.y0, box_2.width * 0.85, box_2.height]) axs[2].legend(loc='center left', bbox_to_anchor=(1,", "col] = 1 # for additive constant t = lsq_signal[-neural_network_m:]", "/ 2), ((time_extended[-1001] + time_extended[-1002]) / 2) - 0.1, 100),", "(min_count_left < 1)) and (i_left < len(lsq_signal) - 1): time_series_extended[int(len(lsq_signal)", "zorder=4, label=textwrap.fill('Slope-based minimum', 11)) plt.scatter(improved_slope_based_maximum_time, improved_slope_based_maximum, c='deeppink', zorder=4, label=textwrap.fill('Improved slope-based", "np.cos(0.04 * 2 * np.pi * t) - emd_sift[:, 1])),", "101) maxima_line_dash = 2.5 * np.ones_like(maxima_line_dash_time) minima_dash = np.linspace(-3.4 -", "axs[0].legend(loc='lower left') axs[1].plot(knots[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey',", "'k-') plt.plot(min_dash_time_2, min_dash_2, 'k-') plt.plot(min_dash_time_3, min_dash_3, 'k-') plt.plot(min_dash_time_4, min_dash_4, 'k-')", "with 51 knots') print(f'DFA fluctuation with 11 knots: {np.round(np.var(time_series -", "label=textwrap.fill('Zoomed region', 10)) axs[0].plot(np.linspace(0.85 * np.pi, 1.15 * np.pi, 101),", "time_series[time == maxima_x[-2]]) + maxima_y[-1] Coughlin_time = Huang_time Coughlin_wave =", "np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1 and Statically Optimised Knots')", "'--', c='darkgreen', label=textwrap.fill('Coughlin Characteristic Wave', 14)) plt.plot(max_2_x_time, max_2_x, 'k-') plt.plot(max_2_x_time_side,", "plt.savefig('jss_figures/Duffing_equation_imfs.png') plt.show() hs_ouputs = hilbert_spectrum(t, emd_duff, emd_ht_duff, emd_if_duff, max_frequency=1.3, plot=False)", "emd_duff[2, :], label='AdvEMDpy') print(f'AdvEMDpy driving function error: {np.round(sum(abs(0.1 * np.cos(0.04", "plt.ylabel('Parts per million') plt.xlabel('Time (years)') plt.savefig('jss_figures/CO2_concentration.png') plt.show() signal = CO2_data['decimal", "minima_x[-1] * np.ones_like(min_1_y) dash_max_min_1_y_time = np.linspace(minima_x[-1], maxima_x[-1], 101) dash_max_min_1_y =", "np.linspace(-2, 2, 101), '--', c='grey') plt.savefig('jss_figures/knot_uniform.png') plt.show() # plot 1b", "c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[1].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean filter', 12))", "500:].T, '--', label=r'$ B_{-1,4}(t) $') plt.plot(time[500:], b_spline_basis[5, 500:].T, '--', label=r'$", "minima_y = time_series[min_bool] max_dash_time = np.linspace(maxima_x[-1] - width, maxima_x[-1] +", "Sinusoidal Time Seres with Added Noise', 50)) x_hs, y, z", "gamma * np.cos(omega * ts)] t = np.linspace(0, 150, 1501)", "ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/detrended_fluctuation_analysis.png') plt.show() # Duffing Equation Example", "1) + 1)] = lsq_signal neural_network_m = 200 neural_network_k =", "as pd import cvxpy as cvx import seaborn as sns", "Example def duffing_equation(xy, ts): gamma = 0.1 epsilon = 1", "Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2, zorder=100) axs[0].set_yticks(ticks=[-2, 0, 2]) axs[0].set_xticks(ticks=[0, np.pi,", "0.2]) plt.ylabel('Frequency (Hz)') plt.xlabel('Time (s)') box_0 = ax.get_position() ax.set_position([box_0.x0, box_0.y0", "plt.plot(max_1_y_time, max_1_y_side, 'k-') plt.plot(min_1_y_time, min_1_y, 'k-') plt.plot(min_1_y_time, min_1_y_side, 'k-') plt.plot(dash_max_min_1_y_time,", "maxima = signal_orig[util_nn.max_bool_func_1st_order_fd()] minima = signal_orig[util_nn.min_bool_func_1st_order_fd()] cs_max = CubicSpline(t[util_nn.max_bool_func_1st_order_fd()], maxima)", "101), '--', c='grey', zorder=1) axs[0].plot(knot * np.ones(101), np.linspace(-5, 5, 101),", "plt.suptitle(textwrap.fill('Comparison of Trends Extracted with Different Knot Sequences', 40)) plt.subplots_adjust(hspace=0.1)", "IA = emd040.spectra.frequency_transform(py_emd[:2, :].T, 12, 'hilbert') print(f'PyEMD annual frequency error:", "import EMD as pyemd0215 import emd as emd040 sns.set(style='darkgrid') pseudo_alg_time", "ax.get_position() ax.set_position([box_0.x0, box_0.y0 + 0.05, box_0.width * 0.75, box_0.height *", "= 0.7 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) ax.pcolormesh(x_hs, y, np.abs(z), cmap='gist_rainbow',", "axs[0].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean filter', 12)) axs[0].plot(preprocess_time, preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median filter', 13))", "ax.set(xlabel='Time (years)') axis += 1 plt.gcf().subplots_adjust(bottom=0.15) axs[0, 0].set_title(r'Original CO$_2$ Concentration')", "1001) time_series = np.cos(time) + np.cos(5 * time) utils =", "label=textwrap.fill('Mean filter', 12)) axs[1].plot(preprocess_time, preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median filter', 13)) axs[1].plot(preprocess_time, preprocess.winsorize(window_width=window,", "+ width, 101) length_top = maxima_y[-1] * np.ones_like(length_time) length_bottom =", "13)) axs[1].plot(downsampled_and_decimated[0], downsampled_and_decimated[1], label=textwrap.fill('Downsampled & decimated', 13)) axs[1].plot(downsampled[0], downsampled[1], label=textwrap.fill('Downsampled',", "in axs.flat: ax.label_outer() if axis == 0: ax.set_ylabel(r'$\\gamma_1(t)$') ax.set_yticks([-2, 0,", "* np.pi, 1001) lsq_signal = np.cos(time) + np.cos(5 * time)", "time series', 12)) axs[0].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean filter', 12)) axs[0].plot(preprocess_time, preprocess.median_filter(window_width=window)[1],", "np.linspace(-2, 2, 101), '--', c='grey') plt.savefig('jss_figures/knot_2.png') plt.show() # plot 1d", "* np.pi, -0.05, 'L') plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x,", "box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht_pyemd.png') plt.show() plt.show()", "plt.plot(dash_final_time, dash_final, 'k--') plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y,", "0.1 * np.cos(0.04 * 2 * np.pi * t), '--',", "np.sin(knot_demonstrate_time) + np.sin(5 * knot_demonstrate_time) emd = EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series) imfs,", "vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(time, np.ones_like(time), 'k--', label=textwrap.fill('Annual cycle', 10)) box_0 =", "Effects Example') plt.plot(time, time_series, LineWidth=2, label='Signal') plt.scatter(Huang_max_time, Huang_max, c='magenta', zorder=4,", "time[-201]) / 2) * np.ones(100), np.linspace(-2.75, 2.75, 100), c='gray', linestyle='dashed',", "2.6 * a) * np.pi, (5 - a) * np.pi,", "ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert_emd.png') plt.show() # compare other packages", "* np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1, label='Knots') axs[1].set_xticks([0,", "np.linspace(improved_slope_based_minimum - width, improved_slope_based_minimum + width, 101) min_dash_time_4 = improved_slope_based_minimum_time", "Concentration using AdvEMDpy', 40)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)') plt.plot(x_hs[0, :],", "slope-based method more clear time_series[time >= minima_x[-1]] = 1.5 *", "= point_1 * np.pi * np.ones_like(length_distance) length_time = np.linspace(point_1 *", "= 200 neural_network_k = 100 # forward -> P =", "np.linspace(maxima_y[-1] - width, maxima_y[-1] + width, 101) max_dash_2 = np.linspace(maxima_y[-2]", "101) min_2_x_time_side = np.linspace(5.3 * np.pi - width, 5.3 *", "if sum(emd_utils_min.min_bool_func_1st_order_fd()) > 0: min_count_left += 1 lsq_utils = emd_utils.Utility(time=time,", "window = 81 fig, axs = plt.subplots(2, 1) fig.subplots_adjust(hspace=0.4) figure_size", "plt.show() # plot 7 a = 0.25 width = 0.2", "plt.yticks([0, 0.1, 0.2]) plt.ylabel('Frequency (Hz)') plt.xlabel('Time (s)') box_0 = ax.get_position()", "np.linspace(maxima_y[-1], minima_y[-1], 101) length_distance_time = point_1 * np.pi * np.ones_like(length_distance)", "1 plt.gcf().subplots_adjust(bottom=0.15) axs[0, 0].set_title(r'Original CO$_2$ Concentration') axs[0, 1].set_title('Smoothed CO$_2$ Concentration')", "+ maxima_y[-1]) / 2 Average_min_time = minima_x[-1] + (minima_x[-1] -", "min_1_y_side, 'k-') plt.plot(dash_max_min_1_y_time, dash_max_min_1_y, 'k--') plt.text(4.48 * np.pi, -2.5, r'$\\frac{p_1}{2}$')", "c='b', zorder=3, label='Minima') plt.scatter(maxima_extrapolate_time, maxima_extrapolate, c='magenta', zorder=3, label=textwrap.fill('Extrapolated maxima', 12))", "axs[0].legend(loc='lower left') axs[1].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey',", "np.pi, 11) imfs_11, hts_11, ifs_11 = advemdpy.empirical_mode_decomposition(knots=knots_11, max_imfs=1, edge_effect='symmetric_anchor', verbose=False)[:3]", "plt.show() # Duffing Equation Example def duffing_equation(xy, ts): gamma =", "time = np.linspace(0, 5 * np.pi, 1001) knots_51 = np.linspace(0,", "0 while ((max_count_right < 1) or (min_count_right < 1)) and", "* np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--', label='Zoomed region') axs[2].plot(time, time_series,", "= plt.gcf().get_size_inches() factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) axs[0].plot(t,", "_, knots, _, _ = emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=1, verbose=False) fig, axs", "np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots[0] * np.ones(101), np.linspace(-2, 2, 101),", "np.cos(0.04 * 2 * np.pi * t) - py_emd[1, :])),", "plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess Filtering Demonstration') axs[1].set_title('Zoomed Region') preprocess_time = pseudo_alg_time.copy() np.random.seed(1)", "axs[1].set_position([box_1.x0 - 0.05, box_1.y0, box_1.width * 0.85, box_1.height]) plt.savefig('jss_figures/preprocess_filter.png') plt.show()", "for ax in axs.flat: if axis == 0: ax.set(ylabel=R'C0$_2$ concentration')", "* np.pi) plt.xticks((4 * np.pi, 5 * np.pi), (r'4$\\pi$', r'5$\\pi$'))", "51 knots') for knot in knots_11: axs[2].plot(knot * np.ones(101), np.linspace(-5,", "maxima envelope', 10), c='red') plt.plot(time, min_unsmoothed[0], label=textwrap.fill('Unsmoothed minima envelope', 10),", "2, 101) end_time = np.linspace(time[-1] - width, time[-1] + width,", "- width, minima_x[-1] + width, 101) min_1_x_time_side = np.linspace(5.4 *", "time_series, LineWidth=2, label='Time series') plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x,", "axs[0].plot(0.95 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--') axs[0].plot(1.55", "+ 1, '--', c='r', label=r'$\\tilde{h}_{(1,0)}^M(t)$', zorder=4) plt.scatter(pseudo_alg_time[pseudo_utils.min_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.min_bool_func_1st_order_fd()], c='c', label=r'$m(t_j)$',", "2 with 31 knots', 19)) axs[1].plot(time, imfs_51[2, :] + imfs_51[3,", "axs[1].plot(6 * np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') axs[1].set_xticks([5, 6]) axs[1].set_xticklabels([r'$", "smooth=True, smoothing_penalty=0.2, technique='inflection_points')[0] binomial_points_envelope = fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True, smoothing_penalty=0.2, technique='binomial_average', order=21,", "/ A2) * (time_series[time >= maxima_x[-2]] - time_series[time == maxima_x[-2]])", "axs[0].set_ylim(-5.5, 5.5) axs[0].set_xlim(0.95 * np.pi, 1.55 * np.pi) axs[1].plot(time, time_series,", "** 3 + gamma * np.cos(omega * ts)] t =", ":] + imfs_51[3, :])), 3)}') for knot in knots_51: axs[0].plot(knot", "width, 101) maxima_dash_time_1 = maxima_x[-2] * np.ones_like(maxima_dash) maxima_dash_time_2 = maxima_x[-1]", "minima_x[-1]), 1.20 + (slope_based_minimum - minima_y[-1]), r'$s_2$') plt.plot(minima_line_dash_time, minima_line_dash, 'k--')", "plt.plot(max_dash_time_1, max_dash_1, 'k-') plt.plot(max_dash_time_2, max_dash_2, 'k-') plt.plot(max_dash_time_3, max_dash_3, 'k-') plt.plot(min_dash_time_1,", "/ (minima_x[-2] - maxima_x[-1]) slope_based_maximum_time = maxima_x[-1] + (maxima_x[-1] -", "hilbert_spectrum(time, imfs_51, hts_51, ifs_51, max_frequency=12, plot=False) # plot 6c ax", "((time_extended[-1001] + time_extended[-1002]) / 2) - 0.1, 100), 2.75 *", "np.pi * t) - emd_duff[2, :])), 3)}') axs[1].plot(t, py_emd[1, :],", "Edge Effects Example') plt.plot(time_reflect, time_series_reflect, 'g--', LineWidth=2, label=textwrap.fill('Symmetric signal', 10))", "width, 5.4 * np.pi + width, 101) min_1_x = minima_y[-1]", "plt.plot(time, (maxima_envelope + minima_envelope) / 2, c='darkblue') plt.plot(time, maxima_envelope_smooth, c='darkred',", "col in range(neural_network_m): P[:-1, col] = lsq_signal[(-(neural_network_m + neural_network_k -", "1) + 1): int(2 * (len(lsq_signal) - 1) + 1", "per million') plt.xlabel('Time (years)') plt.savefig('jss_figures/CO2_concentration.png') plt.show() signal = CO2_data['decimal date']", "with 31 knots: {np.round(np.var(time_series - (imfs_31[1, :] + imfs_31[2, :])),", "minima = lsq_signal[lsq_utils.min_bool_func_1st_order_fd()] minima_time = time[lsq_utils.min_bool_func_1st_order_fd()] minima_extrapolate = time_series_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] minima_extrapolate_time", "= np.linspace(0, 5 * np.pi, 51) time_series = np.cos(2 *", "emd_utils.Utility(time=time, time_series=time_series_reflect) no_anchor_max_time = time_reflect[utils.max_bool_func_1st_order_fd()] no_anchor_max = time_series_reflect[utils.max_bool_func_1st_order_fd()] point_1 =", "plt.scatter(improved_slope_based_maximum_time, improved_slope_based_maximum, c='deeppink', zorder=4, label=textwrap.fill('Improved slope-based maximum', 11)) plt.scatter(improved_slope_based_minimum_time, improved_slope_based_minimum,", "imfs_31[1, :] + imfs_31[2, :], label=textwrap.fill('Sum of IMF 1 and", "= \\ emd_example.empirical_mode_decomposition(knots=knots, knot_time=time, verbose=False) print(f'AdvEMDpy annual frequency error: {np.round(sum(np.abs(ifs[1,", "== 0: ax.set(ylabel=R'C0$_2$ concentration') if axis == 1: pass if", "5.5, 101), 'k--') axs[1].plot(1.55 * np.pi * np.ones(101), np.linspace(-5.5, 5.5,", "Example CO2_data = pd.read_csv('Data/co2_mm_mlo.csv', header=51) plt.plot(CO2_data['month'], CO2_data['decimal date']) plt.title(textwrap.fill('Mean Monthly", "+ np.cos(8 * time) noise = np.random.normal(0, 1, len(time_series)) time_series", "101) length_top_2 = time_series[-1] * np.ones_like(length_time_2) length_bottom_2 = minima_y[-1] *", "time[min_bool] minima_y = time_series[min_bool] A2 = np.abs(maxima_y[-2] - minima_y[-2]) /", "maxima_dash_time_1 = maxima_x[-2] * np.ones_like(maxima_dash) maxima_dash_time_2 = maxima_x[-1] * np.ones_like(maxima_dash)", "0.2 time = np.linspace(0, (5 - a) * np.pi, 1001)", "= 5.2 length_distance_2 = np.linspace(time_series[-1], minima_y[-1], 101) length_distance_time_2 = point_2", "label=r'$M(t_i)$', zorder=2) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time) + 1, '--', c='r', label=r'$\\tilde{h}_{(1,0)}^M(t)$', zorder=4)", "inflection_x = time[inflection_bool] inflection_y = time_series[inflection_bool] fluctuation = emd_mean.Fluctuation(time=time, time_series=time_series)", "(Coughlin_time - Coughlin_time[0])) Average_max_time = maxima_x[-1] + (maxima_x[-1] - maxima_x[-2])", "knot in knots_11: axs[2].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--',", "preprocess_time_series = pseudo_alg_time_series + np.random.normal(0, 0.1, len(preprocess_time)) for i in", "plt.plot(min_dash_time, min_dash, 'k-') plt.plot(dash_1_time, dash_1, 'k--') plt.plot(dash_2_time, dash_2, 'k--') plt.plot(length_distance_time,", "axs.flat: if axis == 0: ax.set(ylabel=R'C0$_2$ concentration') if axis ==", "4 * np.pi, 5 * np.pi]) axs[2].set_xticklabels(['$0$', r'$\\pi$', r'$2\\pi$', r'$3\\pi$',", "= 0 min_count_left = 0 i_left = 0 while ((max_count_left", "ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('First Iteration of Sifting Algorithm') plt.plot(pseudo_alg_time,", "sigma=1) fig, ax = plt.subplots() figure_size = plt.gcf().get_size_inches() factor =", "linestyle='dashed') plt.xlim(3.4 * np.pi, 5.6 * np.pi) plt.xticks((4 * np.pi,", "'--', label=r'$ B_{-1,4}(t) $') plt.plot(time[500:], b_spline_basis[5, 500:].T, '--', label=r'$ B_{0,4}(t)", "maxima_y[-1] * np.ones_like(length_time) length_bottom = minima_y[-1] * np.ones_like(length_time) point_2 =", "0, 1, 2), ('-2', '-1', '0', '1', '2')) plt.xlim(-0.25 *", "external debugging) emd = AdvEMDpy.EMD(time=derivative_time, time_series=derivative_of_lsq) imf_1_of_derivative = emd.empirical_mode_decomposition(knots=derivative_knots, knot_time=derivative_time,", "'0', '1', '2')) plt.xlim(-0.25 * np.pi, 5.25 * np.pi) box_0", "axs[1].plot(time, chsi_basis[12, :].T, '--') axs[1].plot(time, chsi_basis[13, :].T, '--') axs[1].plot(5 *", "+ time_extended[-1000]) / 2) - 0.1, 100), 2.75 * np.ones(100),", "i_right + 1)], time_series=time_series_extended[int(2 * (len(lsq_signal) - 1) + 1):", "plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Uniform Knots') axs[0].plot(knot_demonstrate_time,", "in knots_31: axs[1].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey',", "-0.20 + (slope_based_minimum - minima_y[-1]), r'$s_2$') plt.text(4.50 * np.pi +", "13)) axs[1].plot(preprocess_time, preprocess.winsorize(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize filter', 12)) axs[1].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window, a=0.8)[1],", "time_series[time >= minima_x[-1]] = 1.5 * (time_series[time >= minima_x[-1]] -", "1] x_points = [0, 50, 100, 150] x_names = {0,", "- 1) + 1)] = lsq_signal neural_network_m = 200 neural_network_k", "error: {np.round(sum(np.abs(ifs[1, :] / (2 * np.pi) - np.ones_like(ifs[1, :]))),", "plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of CO$_{2}$", "- 1, '--', c='c', label=r'$\\tilde{h}_{(1,0)}^m(t)$', zorder=5) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time), '--', c='purple',", "101) min_1_x = minima_y[-1] * np.ones_like(min_1_x_time) dash_max_min_1_x = np.linspace(minima_y[-1], maxima_y[-1],", "= ax.get_position() ax.set_position([box_0.x0, box_0.y0 + 0.05, box_0.width * 0.75, box_0.height", "51 knots', 19)) for knot in knots_31: axs[1].plot(knot * np.ones(101),", "Trends Extracted with Different Knot Sequences Zoomed Region', 40)) plt.subplots_adjust(hspace=0.1)", "c='purple', LineWidth=2, label=textwrap.fill('Anti-symmetric signal', 10)) plt.plot(max_dash_time, max_dash, 'k-') plt.plot(min_dash_time, min_dash,", "width, maxima_x[-1] + width, 101) max_1_x_time_side = np.linspace(5.4 * np.pi", "'k--') axs[1].plot(1.55 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--',", "packages Carbon Dioxide - top pyemd = pyemd0215() py_emd =", "max_2_x, 'k-') plt.plot(max_2_x_time_side, max_2_x, 'k-') plt.plot(min_2_x_time, min_2_x, 'k-') plt.plot(min_2_x_time_side, min_2_x,", ":], label=textwrap.fill('Sum of IMF 1, IMF 2, & IMF 3", "and Dynamically Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2, zorder=100) axs[2].set_yticks(ticks=[-2, 0,", "plt.scatter(time[optimal_minima], time_series[optimal_minima], c='darkblue', zorder=4, label=textwrap.fill('Optimal minima', 10)) plt.scatter(inflection_x, inflection_y, c='magenta',", "label=r'$m(t_j)$', zorder=3) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time) - 1, '--', c='c', label=r'$\\tilde{h}_{(1,0)}^m(t)$', zorder=5)", "box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) ax.set_xticks(x_points) ax.set_xticklabels(x_names) axis +=", "maxima_dash, 'k-') plt.plot(maxima_dash_time_2, maxima_dash, 'k-') plt.plot(maxima_dash_time_3, maxima_dash, 'k-') plt.plot(minima_dash_time_1, minima_dash,", "0.85, box_2.height]) axs[2].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[2].plot(np.linspace(0.95 * np.pi,", "= np.linspace(minima_x[-2] - width, minima_x[-2] + width, 101) min_2_x_time_side =", "AdvEMDpy', 40)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)') plt.plot(x_hs[0, :], np.ones_like(x_hs[0, :]),", "point_1 * np.pi + width, 101) length_top = maxima_y[-1] *", "fluc = Fluctuation(time=time, time_series=time_series) max_unsmoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima', smooth=False) max_smoothed", "2) * np.ones(100), np.linspace(-2.75, 2.75, 100), c='k') plt.plot(((time[-202] + time[-201])", "= minima_y[-1] * np.ones_like(min_dash_time) dash_1_time = np.linspace(maxima_x[-1], minima_x[-1], 101) dash_1", "* np.pi, 0.85, r'$2a_2$') plt.plot(max_2_y_time, max_2_y, 'k-') plt.plot(max_2_y_time, max_2_y_side, 'k-')", "time_series=time_series_extended[int(2 * (len(lsq_signal) - 1) + 1): int(2 * (len(lsq_signal)", "ax.get_position() ax.set_position([box_0.x0, box_0.y0, box_0.width * 0.85, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1,", "labels=[r'0', r'$\\pi$', r'$2\\pi$']) box_0 = ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0,", "5, 101), '--', c='grey', zorder=1, label='Knots') axs[2].set_xticks([np.pi, (3 / 2)", "axs[1].plot(time, imfs_31[1, :] + imfs_31[2, :], label=textwrap.fill('Sum of IMF 1", "= fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'minima', optimal_maxima, optimal_minima, smooth=False, smoothing_penalty=0.2, edge_effect='none')[0] ax =", "time_series_reflect[utils.max_bool_func_1st_order_fd()] point_1 = 5.4 length_distance = np.linspace(maxima_y[-1], minima_y[-1], 101) length_distance_time", "from AdvEMDpy import EMD # alternate packages from PyEMD import", "ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width * 0.85, box_0.height]) ax.legend(loc='center left',", "# alternate packages from PyEMD import EMD as pyemd0215 import", "Spectrum of CO$_{2}$ Concentration using PyEMD 0.2.10', 45)) plt.ylabel('Frequency (year$^{-1}$)')", "* np.pi]) axs[1].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2 and Uniform Knots')", "* np.ones(101) symmetry_axis = np.linspace(-2, 2, 101) end_time = np.linspace(time[-1]", "fontsize=8) axs[1].plot(time, time_series, label='Time series') axs[1].plot(time, imfs_31[1, :] + imfs_31[2,", "5 * np.pi, 51) fluc = Fluctuation(time=time, time_series=time_series) max_unsmoothed =", "np.pi, 1.15 * np.pi, 101), 3 * np.ones(101), '--', c='black')", "plt.plot(time, (EEMD_maxima_envelope + EEMD_minima_envelope) / 2, c='darkgreen') plt.plot(time, inflection_points_envelope, c='darkorange',", "slope_based_minimum, c='purple', zorder=4, label=textwrap.fill('Slope-based minimum', 11)) plt.scatter(improved_slope_based_maximum_time, improved_slope_based_maximum, c='deeppink', zorder=4,", "left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi,", "* np.pi, 3 * np.pi, 4 * np.pi, 5 *", "0)) max_count_right = 0 min_count_right = 0 i_right = 0", "* np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') plt.plot(6 * np.ones(100), np.linspace(-0.2,", "min_2_x_time = np.linspace(minima_x[-2] - width, minima_x[-2] + width, 101) min_2_x_time_side", "+ 1 + i_right + 1)]) if sum(emd_utils_max.max_bool_func_1st_order_fd()) > 0:", "Huang_max_time = Huang_time[Huang_max_bool] Huang_max = Huang_wave[Huang_max_bool] Huang_min_time = Huang_time[Huang_min_bool] Huang_min", "preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean filter', 12)) axs[0].plot(preprocess_time, preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median filter', 13)) axs[0].plot(preprocess_time,", "1 - i_left):int(len(lsq_signal))], time_series=time_series_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))]) if sum(emd_utils_max.max_bool_func_1st_order_fd())", "10), c='darkorange') plt.plot(time, max_smoothed[0], label=textwrap.fill('Smoothed maxima envelope', 10), c='red') plt.plot(time,", "* np.pi, 101), -3 * np.ones(101), '--', c='black', label=textwrap.fill('Zoomed region',", "= (t - output) gradients = error * (- train_input)", "np.linspace(0, 150, 1501) XY0 = [1, 1] solution = odeint(duffing_equation,", "packages from PyEMD import EMD as pyemd0215 import emd as", "Hilbert Spectrum of CO$_{2}$ Concentration using emd 0.3.3', 45)) plt.ylabel('Frequency", "= plt.gcf().get_size_inches() factor = 1.0 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian", "-2.0, 101), '--', c='grey', zorder=1) plt.plot(knots[-1] * np.ones(101), np.linspace(-3.0, -2.0,", "plt.plot(min_1_x_time_side, min_1_x, 'k-') plt.plot(dash_max_min_1_x_time, dash_max_min_1_x, 'k--') plt.text(5.42 * np.pi, -0.1,", "plt.plot(dash_2_time, dash_2, 'k--') plt.plot(length_distance_time, length_distance, 'k--') plt.plot(length_distance_time_2, length_distance_2, 'k--') plt.plot(length_time,", "downsampled[1], label=textwrap.fill('Downsampled', 13)) axs[0].plot(np.linspace(0.85 * np.pi, 1.15 * np.pi, 101),", "= maxima_x[-2] * np.ones_like(maxima_dash) maxima_dash_time_2 = maxima_x[-1] * np.ones_like(maxima_dash) maxima_dash_time_3", "+ time[-301]) / 2), ((time[-302] + time[-301]) / 2) +", "* 0.85, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_symmetry_anti.png') plt.show() #", "time[-301]) / 2) + 0.1, 100), -2.75 * np.ones(100), c='k')", "* 0.85, box_1.height]) plt.savefig('jss_figures/preprocess_filter.png') plt.show() # plot 1e - addition", "neural_network_k = 100 # forward -> P = np.zeros((int(neural_network_k +", "4 * np.pi, 5 * np.pi]) axs[0].set_xticklabels(['', '', '', '',", "minima_y[-2] + width, 101) min_dash_time_1 = minima_x[-1] * np.ones_like(min_dash_1) min_dash_time_2", "1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Uniform Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series,", "1.20 + (slope_based_minimum - minima_y[-1]), r'$s_2$') plt.plot(minima_line_dash_time, minima_line_dash, 'k--') plt.plot(maxima_line_dash_time,", "np.ones(101), 'k--') axs[1].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), -5.5", "- width, maxima_y[-2] + width, 101) max_dash_time_1 = maxima_x[-1] *", "verbose=False) fig, axs = plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series", "100), 'k-') axs[0].plot(6 * np.ones(100), np.linspace(-0.2, 0.8, 100), 'k-') axs[0].set_xticks([5,", "knots') axs[2].plot(time, imfs_31[2, :], label='IMF 2 with 31 knots') axs[2].plot(time,", "= plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title(textwrap.fill('Plot Demonstrating Unsmoothed Extrema Envelopes if Schoenberg–Whitney", "axs[1].plot(time, chsi_basis[10, :].T, '--') axs[1].plot(time, chsi_basis[11, :].T, '--') axs[1].plot(time, chsi_basis[12,", "label=textwrap.fill('Windsorize filter', 12)) axs[1].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize interpolation filter', 14))", "101), '--', c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots[1][0] * np.ones(101), np.linspace(-2,", "= Fluctuation(time=time, time_series=time_series) max_unsmoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima', smooth=False) max_smoothed =", "[-2, 0, 2] y_points_2 = [-1, 0, 1] fig, axs", "101) min_dash = minima_y[-1] * np.ones_like(min_dash_time) dash_1_time = np.linspace(maxima_x[-1], minima_x[-1],", "vmin=z_min, vmax=z_max) ax.plot(x_hs[0, :], 8 * np.ones_like(x_hs[0, :]), '--', label=r'$\\omega", "* 0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_characteristic_wave.png') plt.show() #", "width, 101) length_top = maxima_y[-1] * np.ones_like(length_time) length_bottom = minima_y[-1]", "+= 1 lsq_utils = emd_utils.Utility(time=time, time_series=lsq_signal) utils_extended = emd_utils.Utility(time=time_extended, time_series=time_series_extended)", "\\tau_{k+1} $']) axs[1].set_xlim(4.5, 6.5) plt.savefig('jss_figures/comparing_bases.png') plt.show() # plot 3 a", "50, 100, 150] x_names = {0, 50, 100, 150} y_points_1", "* 0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/neural_network.png') plt.show() #", "zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.scatter(max_discard_time, max_discard, c='purple',", "a) * np.pi, 101))) time_series_anti_reflect = time_series_reflect[0] - time_series_reflect utils", "+ 0.1, 100), 2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1000])", "of Duffing Equation using PyEMD 0.2.10', 40)) plt.pcolormesh(t, freq_bins, hht,", "np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[2].plot(knots[2][0] * np.ones(101),", "np.linspace(0, 5 * np.pi, 1001) time_series = np.cos(time) + np.cos(5", "np.linspace(5.4 * np.pi - width, 5.4 * np.pi + width,", "= time_series_reflect[utils.max_bool_func_1st_order_fd()] point_1 = 5.4 length_distance = np.linspace(maxima_y[-1], minima_y[-1], 101)", "plt.plot(time, inflection_points_envelope, c='darkorange', label=textwrap.fill('Inflection point envelope', 10)) plt.plot(time, binomial_points_envelope, c='deeppink',", "'--', label=r'$ B_{-3,4}(t) $') plt.plot(time[500:], b_spline_basis[3, 500:].T, '--', label=r'$ B_{-2,4}(t)", "plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.scatter(max_discard_time, max_discard, c='purple', zorder=4, label=textwrap.fill('Symmetric", "np.pi, 2 * np.pi, 3 * np.pi, 4 * np.pi,", "as np import pandas as pd import cvxpy as cvx", "= maxima_x[-2] * np.ones_like(max_2_y) min_2_y = np.linspace(minima_y[-2] - width, minima_y[-2]", "time_series, LineWidth=2, label='Signal') plt.title('Symmetry Edge Effects Example') plt.plot(time_reflect, time_series_reflect, 'g--',", "np.hstack((time_series_extended[int(len(lsq_signal) - 1 - i_left): int(len(lsq_signal) - 1 - i_left", "* np.pi, 51) time_series = np.cos(2 * time) + np.cos(4", "= 0 min_count_right = 0 i_right = 0 while ((max_count_right", "plt.plot(time, time_series, LineWidth=2, label='Signal') plt.title('Slope-Based Edge Effects Example') plt.plot(max_dash_time_1, max_dash_1,", "IF, IA = emd040.spectra.frequency_transform(py_emd[:2, :].T, 12, 'hilbert') print(f'PyEMD annual frequency", "factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert", "smoothing_penalty=0.2, technique='inflection_points')[0] binomial_points_envelope = fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True, smoothing_penalty=0.2, technique='binomial_average', order=21, increment=20)[0]", "= 0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess Smoothing Demonstration')", "box_2.height]) axs[2].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[2].plot(np.linspace(0.95 * np.pi, 1.55", "= 0 for ax in axs.flat: if axis == 0:", "np.linspace(-2.1 - width, -2.1 + width, 101) min_1_y_time = minima_x[-1]", "> 0: max_count_left += 1 emd_utils_min = \\ emd_utils.Utility(time=time_extended[int(len(lsq_signal) -", "- time_series[time == maxima_x[-2]]) + maxima_y[-1] Coughlin_time = Huang_time Coughlin_wave", "/ 2) * np.ones(100), np.linspace(-2.75, 2.75, 100), c='gray', linestyle='dashed') plt.xlim(3.4", "np.ones(101) symmetry_axis = np.linspace(-2, 2, 101) end_time = np.linspace(time[-1] -", "axs[1].plot(t, 0.1 * np.cos(0.04 * 2 * np.pi * t),", "axs[1].plot(0.95 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--') axs[1].plot(1.55", "- width, max_discard_time + width, 101) max_discard_dash = max_discard *", "100), 2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1000]) / 2),", "= np.abs(maxima_y[-2] - minima_y[-2]) / 2 A1 = np.abs(maxima_y[-1] -", "label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.plot(Huang_time, Huang_wave, '--', c='darkviolet',", "0.01 for iterations in range(1000): output = np.matmul(weights, train_input) error", "/ 2) - 0.1, 100), 2.75 * np.ones(100), c='gray') plt.plot(((time_extended[-1001]", "vmax=np.max(np.max(np.abs(hht)))) plt.plot(t[:-1], 0.124 * np.ones_like(t[:-1]), '--', label=textwrap.fill('Hamiltonian frequency approximation', 15))", "Filtering Demonstration') axs[1].set_title('Zoomed Region') preprocess_time = pseudo_alg_time.copy() np.random.seed(1) random.seed(1) preprocess_time_series", "* xy[0] ** 3 + gamma * np.cos(omega * ts)]", "np.linspace(5.3 * np.pi - width, 5.3 * np.pi + width,", "LineWidth=2, label='Signal') plt.title('Symmetry Edge Effects Example') plt.plot(time_reflect, time_series_reflect, 'g--', LineWidth=2,", "label='Knots') axs[1].set_xticks([0, np.pi, 2 * np.pi, 3 * np.pi, 4", "= plt.subplot(111) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Duffing Equation using", "5.5, 101), 'k--', label='Zoomed region') plt.savefig('jss_figures/DFA_different_trends.png') plt.show() # plot 6b", "c='grey', zorder=1, label='Knots') axs[2].set_xticks([np.pi, (3 / 2) * np.pi]) axs[2].set_xticklabels([r'$\\pi$',", "knot_demonstrate_time) emd = EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series) imfs, _, _, _, knots,", "factor = 1.0 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) ax.pcolormesh(x, y, np.abs(z),", "dash_final, 'k--') plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b',", "envelope', 10)) plt.plot(time, binomial_points_envelope, c='deeppink', label=textwrap.fill('Binomial average envelope', 10)) plt.plot(time,", "t), '--', label=r'$0.1$cos$(0.08{\\pi}t)$') axs[1].set_title('IMF 2') axs[1].set_ylim([-0.2, 0.4]) axs[1].set_xlim([0, 150]) axis", "- emd_sift[:, 1])), 3)}') axs[1].plot(t, 0.1 * np.cos(0.04 * 2", "np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--') axs[2].plot(1.55 * np.pi", "'minima', smooth=True, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] inflection_points_envelope = fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True, smoothing_penalty=0.2,", "== maxima_x[-2]]) + maxima_x[-1] Huang_wave = (A1 / A2) *", "axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.90)[1], c='grey', label=textwrap.fill('Quantile window', 12)) axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.10)[1],", "# / # \\ / # \\ / # \\/", "1501) XY0 = [1, 1] solution = odeint(duffing_equation, XY0, t)", "debug (confusing with external debugging) emd = AdvEMDpy.EMD(time=derivative_time, time_series=derivative_of_lsq) imf_1_of_derivative", "plt.plot(max_2_y_time, max_2_y, 'k-') plt.plot(max_2_y_time, max_2_y_side, 'k-') plt.plot(min_2_y_time, min_2_y, 'k-') plt.plot(min_2_y_time,", "np.pi, 101))) time_series_anti_reflect = time_series_reflect[0] - time_series_reflect utils = emd_utils.Utility(time=time,", "a=0.8)[1], label=textwrap.fill('Windsorize filter', 12)) axs[0].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize interpolation filter',", "+ width, 101) max_2_y_time = maxima_x[-2] * np.ones_like(max_2_y) min_2_y =", "Monthly Concentration of Carbon Dioxide in the Atmosphere', 35)) plt.ylabel('Parts", "np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[2].plot(knots[2][0] * np.ones(101), np.linspace(-2,", "np.pi, 51) emd = EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series) imfs = emd.empirical_mode_decomposition(knots=knots_uniform, edge_effect='anti-symmetric',", "zorder=2, label='Signal') plt.plot(time_extended, time_series_extended, c='g', zorder=1, label=textwrap.fill('Extrapolated signal', 12)) plt.scatter(maxima_time,", "axs[0, 1].plot(time, signal) axs[0, 1].plot(time, imfs[0, :], label='Smoothed') axs[0, 1].legend(loc='lower", "box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert_emd.png') plt.show() #", "plot=False) # plot 6c ax = plt.subplot(111) figure_size = plt.gcf().get_size_inches()", "plt.plot(time, min_smoothed[0], label=textwrap.fill('Smoothed minima envelope', 10), c='blue') for knot in", "edit signal to make difference between slope-based method and improved", "Huang_wave, '--', c='darkviolet', label=textwrap.fill('Huang Characteristic Wave', 14)) plt.plot(Coughlin_time, Coughlin_wave, '--',", "Extrema Envelopes if Schoenberg–Whitney Conditions are Not Satisfied', 50)) plt.plot(time,", "+ time_extended[-1002]) / 2), ((time_extended[-1001] + time_extended[-1002]) / 2) -", "# adjustment = - lr * max_gradient_vector weights += adjustment", "plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess Smoothing Demonstration') axs[1].set_title('Zoomed Region') axs[0].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[0].plot(pseudo_alg_time,", "35)) plt.ylabel('Parts per million') plt.xlabel('Time (years)') plt.savefig('jss_figures/CO2_concentration.png') plt.show() signal =", "plt.show() # plot 2 fig, axs = plt.subplots(1, 2, sharey=True)", "plt.savefig('jss_figures/detrended_fluctuation_analysis.png') plt.show() # Duffing Equation Example def duffing_equation(xy, ts): gamma", "'--', c='grey', zorder=1, label='Knots') axs[1].set_xticks([0, np.pi, 2 * np.pi, 3", "plt.savefig('jss_figures/knot_2.png') plt.show() # plot 1d - addition window = 81", "pseudo_alg_time_series[pseudo_utils.min_bool_func_1st_order_fd()], c='c', label=r'$m(t_j)$', zorder=3) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time) - 1, '--', c='c',", "= gaussian_filter(hht, sigma=1) fig, ax = plt.subplots() figure_size = plt.gcf().get_size_inches()", "header=51) plt.plot(CO2_data['month'], CO2_data['decimal date']) plt.title(textwrap.fill('Mean Monthly Concentration of Carbon Dioxide", "chsi_basis = basis.chsi_basis(knots) # plot 1 plt.title('Non-Natural Cubic B-Spline Bases", "'--', c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[0].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean filter',", "preprocess.quantile_filter(window_width=window, q=0.10)[1], c='grey') axs[1].set_xlim(0.85 * np.pi, 1.15 * np.pi) axs[1].set_ylim(-3,", "np.pi, 1.55 * np.pi, 101), 5.5 * np.ones(101), 'k--') axs[2].plot(np.linspace(0.95", "i_right + 1)]) if sum(emd_utils_max.max_bool_func_1st_order_fd()) > 0: max_count_right += 1", "0.5), fontsize=8) axs[0].set_ylim(-5.5, 5.5) axs[0].set_xlim(0.95 * np.pi, 1.55 * np.pi)", "= np.linspace(time[-1] - 0.5, time[-1] + 0.5, 101) anti_symmetric_signal =", "- 1): time_series_extended[int(2 * (len(lsq_signal) - 1) + 1 +", "axs[0, 1].legend(loc='lower right') axs[1, 0].plot(time, imfs[1, :]) axs[1, 1].plot(time, imfs[2,", "network targets', 13)) plt.plot(np.linspace(((time[-202] + time[-201]) / 2), ((time[-202] +", "plt.plot(time, min_unsmoothed[0], label=textwrap.fill('Unsmoothed minima envelope', 10), c='cyan') plt.plot(time, min_smoothed[0], label=textwrap.fill('Smoothed", "is arbitrary prob = cvx.Problem(objective) result = prob.solve(verbose=True, solver=cvx.ECOS) weights_left", "< len(lsq_signal) - 1): time_series_extended[int(2 * (len(lsq_signal) - 1) +", "zorder=4, label=textwrap.fill('Anti-Symmetric maxima', 10)) plt.scatter(no_anchor_max_time, no_anchor_max, c='gray', zorder=4, label=textwrap.fill('Symmetric maxima',", "np.linspace(0, 5 * np.pi, 31) imfs_31, hts_31, ifs_31 = advemdpy.empirical_mode_decomposition(knots=knots_31,", "axs[0].set_yticks(ticks=[-2, 0, 2]) axs[0].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$',", "= solution[:, 1] x_points = [0, 50, 100, 150] x_names", "-2.1 + width, 101) max_1_y_time = maxima_x[-1] * np.ones_like(max_1_y) min_1_y", "box_1.height]) plt.savefig('jss_figures/preprocess_filter.png') plt.show() # plot 1e - addition fig, axs", "15)) plt.xticks([0, 50, 100, 150]) plt.yticks([0, 0.1, 0.2]) plt.ylabel('Frequency (Hz)')", "= np.linspace(maxima_x[-1], minima_x[-1], 101) dash_1 = np.linspace(maxima_y[-1], minima_y[-1], 101) dash_2_time", "label='Zoomed region') box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.05, box_0.y0, box_0.width", "length_top, 'k-') plt.plot(length_time, length_bottom, 'k-') plt.plot(length_time_2, length_top_2, 'k-') plt.plot(length_time_2, length_bottom_2,", "plt.show() hs_ouputs = hilbert_spectrum(time, imfs_51, hts_51, ifs_51, max_frequency=12, plot=False) #", "r'$s_1$') plt.text(4.43 * np.pi + (slope_based_minimum_time - minima_x[-1]), -0.20 +", "CO$_2$ Concentration') axs[1, 0].set_title('IMF 1') axs[1, 1].set_title('Residual') plt.gcf().subplots_adjust(bottom=0.15) plt.savefig('jss_figures/CO2_EMD.png') plt.show()", "import emd_mean import AdvEMDpy import emd_basis import emd_utils import numpy", "knot in knots_31: axs[1].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--',", "a) * np.pi, (5 - a) * np.pi, 101))) time_series_anti_reflect", "plt.savefig('jss_figures/Duffing_equation_ht_pyemd.png') plt.show() plt.show() emd_sift = emd040.sift.sift(x) IP, IF, IA =", "time_series[min_bool] inflection_bool = utils.inflection_point() inflection_x = time[inflection_bool] inflection_y = time_series[inflection_bool]", "0.25 width = 0.2 time = np.linspace((0 + a) *", "improved_slope_based_minimum + width, 101) min_dash_time_4 = improved_slope_based_minimum_time * np.ones_like(min_dash_4) dash_final_time", "- top pyemd = pyemd0215() py_emd = pyemd(signal) IP, IF,", "left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert_pyemd.png') plt.show() emd_sift = emd040.sift.sift(signal) IP, IF,", "c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.scatter(time[optimal_maxima], time_series[optimal_maxima],", "axis == 1: pass if axis == 2: ax.set(ylabel=R'C0$_2$ concentration')", "* np.ones(101), np.linspace(-3, 3, 101), '--', c='black') axs[0].set_yticks(ticks=[-2, 0, 2])", "zorder=4, label='Minima') plt.scatter(max_discard_time, max_discard, c='purple', zorder=4, label=textwrap.fill('Symmetric Discard maxima', 10))", "\\ / # \\/ import random import textwrap import emd_mean", "{np.round(np.var(time_series - (imfs_51[1, :] + imfs_51[2, :] + imfs_51[3, :])),", "+ 0.6 * np.cos(2 * np.pi * t / 25)", "ax.set_ylabel('x(t)') ax.set_yticks(y_points_1) if axis == 1: ax.set_ylabel(r'$ \\dfrac{dx(t)}{dt} $') ax.set(xlabel='t')", "inflection_bool = utils.inflection_point() inflection_x = time[inflection_bool] inflection_y = time_series[inflection_bool] fluctuation", "6b fig, axs = plt.subplots(3, 1) plt.suptitle(textwrap.fill('Comparison of Trends Extracted", "min_1_y_time = minima_x[-1] * np.ones_like(min_1_y) dash_max_min_1_y_time = np.linspace(minima_x[-1], maxima_x[-1], 101)", "(5 + a) * np.pi, 101) time_series_reflect = np.flip(np.cos(np.linspace((5 -", "np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--', label='Zoomed region') plt.savefig('jss_figures/DFA_different_trends.png') plt.show() #", "width, max_discard_time + width, 101) max_discard_dash = max_discard * np.ones_like(max_discard_dash_time)", "* np.pi, 101), 5.5 * np.ones(101), 'k--') axs[1].plot(np.linspace(0.95 * np.pi,", "* P) + 1 - t), 2)) # linear activation", "np.linspace(maxima_x[-2], slope_based_maximum_time, 101) maxima_line_dash = 2.5 * np.ones_like(maxima_line_dash_time) minima_dash =", "length_bottom_2, 'k-') plt.plot(end_time, end_signal, 'k-') plt.plot(symmetry_axis_1_time, symmetry_axis, 'r--', zorder=1) plt.plot(anti_symmetric_time,", "np.linspace(-5, 5, 101), '--', c='grey', zorder=1, label='Knots') axs[0].set_xticks([0, np.pi, 2", "len(knots_uniform)): axs[i].plot(knots_uniform[j] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey') plt.savefig('jss_figures/knot_uniform.png')", "1 - i_left):int(len(lsq_signal))], time_series=time_series_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))]) if sum(emd_utils_min.min_bool_func_1st_order_fd())", "maximum', 14)) plt.scatter(Coughlin_min_time, Coughlin_min, c='dodgerblue', zorder=4, label=textwrap.fill('Coughlin minimum', 14)) plt.scatter(Average_max_time,", "* np.pi, -2.2, r'$\\frac{p_2}{2}$') plt.plot(max_1_x_time, max_1_x, 'k-') plt.plot(max_1_x_time_side, max_1_x, 'k-')", "maxima_x[-2]]) + maxima_x[-1] Huang_wave = (A1 / A2) * (time_series[time", "= 0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum", "plt.show() # compare other packages Duffing - bottom emd_duffing =", "________ # / # \\ / # \\ / #", "fontsize=8) axs[2].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), 5.5 *", "0, 2] y_points_2 = [-1, 0, 1] fig, axs =", "b_spline_basis = basis.cubic_b_spline(knots) chsi_basis = basis.chsi_basis(knots) # plot 1 plt.title('Non-Natural", "dash_final = np.linspace(improved_slope_based_maximum, improved_slope_based_minimum, 101) ax = plt.subplot(111) figure_size =", "'maxima', optimal_maxima, optimal_minima, smooth=False, smoothing_penalty=0.2, edge_effect='none')[0] EEMD_minima_envelope = fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'minima',", "if sum(emd_utils_min.min_bool_func_1st_order_fd()) > 0: min_count_right += 1 # backward <-", "dash_2 = np.linspace(maxima_y[-1], minima_y[-2], 101) s1 = (minima_y[-2] - maxima_y[-1])", "max_frequency=10, which_imfs=[1], plot=False) x_hs, y, z = hs_ouputs y =", "plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of CO$_{2}$ Concentration using PyEMD 0.2.10',", ":].T, '--') axs[1].plot(time, chsi_basis[11, :].T, '--') axs[1].plot(time, chsi_basis[12, :].T, '--')", "* np.pi, 101), -5.5 * np.ones(101), 'k--') axs[0].plot(0.95 * np.pi", "cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(t[:-1], 0.124 * np.ones_like(t[:-1]), '--', label=textwrap.fill('Hamiltonian frequency", "box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_slope_based.png') plt.show() # plot 5", "* np.pi) plt.savefig('jss_figures/DFA_different_trends_zoomed.png') plt.show() hs_ouputs = hilbert_spectrum(time, imfs_51, hts_51, ifs_51,", ":], label='IMF 3 with 51 knots') print(f'DFA fluctuation with 11", "* (len(lsq_signal) - 1) + 1)] = lsq_signal neural_network_m =", "* np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--') axs[2].plot(1.55 * np.pi *", "= 0.1 epsilon = 1 omega = ((2 * np.pi)", "factor = 0.9 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time, time_series,", "knots') for knot in knots_11: axs[2].plot(knot * np.ones(101), np.linspace(-5, 5,", "time_extended[-1002]) / 2), ((time_extended[-1001] + time_extended[-1002]) / 2) - 0.1,", "axs[2].plot(time, imfs_11[1, :], label='IMF 1 with 11 knots') axs[2].plot(time, imfs_31[2,", "5.5 * np.ones(101), 'k--') axs[0].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi,", "2)) # linear activation function is arbitrary prob = cvx.Problem(objective)", "edge_effect='symmetric_anchor', verbose=False)[:3] fig, axs = plt.subplots(3, 1) plt.suptitle(textwrap.fill('Comparison of Trends", "5.4 * np.pi + width, 101) max_1_x = maxima_y[-1] *", "of Trends Extracted with Different Knot Sequences', 40)) plt.subplots_adjust(hspace=0.1) axs[0].plot(time,", "Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2, zorder=100) axs[1].set_yticks(ticks=[-2, 0, 2]) axs[1].set_xticks(ticks=[0,", "plt.subplots(2, 1) plt.subplots_adjust(hspace=0.2) axs[0].plot(t, x) axs[0].set_title('Duffing Equation Displacement') axs[0].set_ylim([-2, 2])", "maxima_x[-2] * np.ones_like(max_dash_1) min_dash_1 = np.linspace(minima_y[-1] - width, minima_y[-1] +", "= y / (2 * np.pi) z_min, z_max = 0,", "2] y_points_2 = [-1, 0, 1] fig, axs = plt.subplots(2,", "c='magenta', zorder=4, label=textwrap.fill('Huang maximum', 10)) plt.scatter(Huang_min_time, Huang_min, c='lime', zorder=4, label=textwrap.fill('Huang", "for col in range(neural_network_m): P[:-1, col] = lsq_signal[int(col + 1):int(col", "knots', 21)) print(f'DFA fluctuation with 51 knots: {np.round(np.var(time_series - (imfs_51[1,", "100), 'k-') axs[1].plot(6 * np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') axs[1].set_xticks([5,", "+ maxima_x[-1] Huang_wave = (A1 / A2) * (time_series[time >=", "'r--', zorder=1) plt.plot(anti_symmetric_time, anti_symmetric_signal, 'r--', zorder=1) plt.plot(symmetry_axis_2_time, symmetry_axis, 'r--', label=textwrap.fill('Axes", "1): int(2 * (len(lsq_signal) - 1) + 1 + i_right", "plt.savefig('jss_figures/edge_effects_slope_based.png') plt.show() # plot 5 a = 0.25 width =", "\\ np.r_[utils.zero_crossing() == 1, False] optimal_minima = np.r_[False, utils.derivative_forward_diff() >", "np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) ax.plot(x_hs[0, :], 8 * np.ones_like(x_hs[0, :]),", "import CubicSpline from emd_hilbert import Hilbert, hilbert_spectrum from emd_preprocess import", "x_hs.max(), y.min(), y.max()]) box_0 = ax.get_position() ax.set_position([box_0.x0 + 0.0125, box_0.y0", "0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/detrended_fluctuation_analysis.png') plt.show() # Duffing", "np.pi, 2 * np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots[0][0] * np.ones(101),", "Spectrum of CO$_{2}$ Concentration using AdvEMDpy', 40)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time", "minima_y = time_series[min_bool] max_dash_1 = np.linspace(maxima_y[-1] - width, maxima_y[-1] +", "+ width, 101) max_2_x_time_side = np.linspace(5.3 * np.pi - width,", "random import textwrap import emd_mean import AdvEMDpy import emd_basis import", "plt.plot(time, np.ones_like(time), 'k--', label=textwrap.fill('Annual cycle', 10)) box_0 = ax.get_position() ax.set_position([box_0.x0", "0.05, box_2.y0, box_2.width * 0.85, box_2.height]) axs[2].legend(loc='center left', bbox_to_anchor=(1, 0.5),", "advemdpy.empirical_mode_decomposition(knots=knots_11, max_imfs=1, edge_effect='symmetric_anchor', verbose=False)[:3] fig, axs = plt.subplots(3, 1) plt.suptitle(textwrap.fill('Comparison", "np.cos(5 * time) knots = np.linspace(0, 5 * np.pi, 101)", "Bases') axs[0].plot(time, b_spline_basis[2, :].T, '--', label='Basis 1') axs[0].plot(time, b_spline_basis[3, :].T,", "= emd040.spectra.frequency_transform(emd_sift[:, :1], 12, 'hilbert') print(f'emd annual frequency error: {np.round(sum(np.abs(IF", "edge_effect='none', spline_method='b_spline')[0] inflection_points_envelope = fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True, smoothing_penalty=0.2, technique='inflection_points')[0] binomial_points_envelope =", "utils_Coughlin.max_bool_func_1st_order_fd() Coughlin_min_bool = utils_Coughlin.min_bool_func_1st_order_fd() Huang_max_time = Huang_time[Huang_max_bool] Huang_max = Huang_wave[Huang_max_bool]", "(r'$0$', r'$\\pi$', r'2$\\pi$', r'3$\\pi$', r'4$\\pi$', r'5$\\pi$')) plt.yticks((-2, -1, 0, 1,", "ifs, _, _, _, _ = \\ emd_example.empirical_mode_decomposition(knots=knots, knot_time=time, verbose=False)", "0.1, 100), 2.75 * np.ones(100), c='k') plt.plot(((time_extended[-1001] + time_extended[-1002]) /", "box_0.y0 + 0.075, box_0.width * 0.8, box_0.height * 0.9]) ax.legend(loc='center", "+ width, 101) max_2_y_side = np.linspace(-1.8 - width, -1.8 +", "101), '--', c='grey', label='Knots', zorder=1) plt.xticks((0, 1 * np.pi, 2", "Extracted with Different Knot Sequences Zoomed Region', 40)) plt.subplots_adjust(hspace=0.1) axs[0].plot(time,", "= utils.inflection_point() inflection_x = time[inflection_bool] inflection_y = time_series[inflection_bool] fluctuation =", "IA = emd040.spectra.frequency_transform(emd_sift[:, :1], 12, 'hilbert') print(f'emd annual frequency error:", "(maxima_y[-2] + maxima_y[-1]) / 2 Average_min_time = minima_x[-1] + (minima_x[-1]", "plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)') plt.pcolormesh(time, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht))))", "- minima_x[-1]), -0.20 + (slope_based_minimum - minima_y[-1]), r'$s_2$') plt.text(4.50 *", "axs[1].set_xlim(4.5, 6.5) plt.savefig('jss_figures/comparing_bases.png') plt.show() # plot 3 a = 0.25", "(minima_x[-1] - minima_x[-2]), 0.35 + (minima_y[-1] - minima_y[-2]), r'$s_1$') plt.text(4.43", ":].T, '--', label='Basis 1') axs[0].plot(time, b_spline_basis[3, :].T, '--', label='Basis 2')", "if i_right > 1: emd_utils_max = \\ emd_utils.Utility(time=time_extended[int(2 * (len(lsq_signal)", "IF, IA = emd040.spectra.frequency_transform(py_emd.T, 10, 'hilbert') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0,", "r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1 and Dynamically Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :],", "= maxima_x[-1] + (maxima_x[-1] - maxima_x[-2]) Average_max = (maxima_y[-2] +", "dash_max_min_1_x, 'k--') plt.text(5.42 * np.pi, -0.1, r'$2a_1$') plt.plot(max_1_y_time, max_1_y, 'k-')", "in knots_11: axs[2].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey',", "= emd040.sift.sift(signal) IP, IF, IA = emd040.spectra.frequency_transform(emd_sift[:, :1], 12, 'hilbert')", "duffing_equation(xy, ts): gamma = 0.1 epsilon = 1 omega =", "max_2_y_side = np.linspace(-1.8 - width, -1.8 + width, 101) max_2_y_time", "emd_if_duff, max_frequency=1.3, plot=False) ax = plt.subplot(111) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum", "2) * np.ones(100), np.linspace(-2.75, 2.75, 100), c='gray', linestyle='dashed') plt.xlim(3.4 *", "150, 1501) XY0 = [1, 1] solution = odeint(duffing_equation, XY0,", "np.linspace(-5, 5, 101), '--', c='grey', zorder=1) axs[1].plot(knot * np.ones(101), np.linspace(-5,", "* np.ones_like(max_1_x_time) min_1_x_time = np.linspace(minima_x[-1] - width, minima_x[-1] + width,", "1.15 * np.pi, 101), 3 * np.ones(101), '--', c='black') axs[0].plot(0.85", "preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott smoothing', 12)) axs[1].plot(preprocess_time, preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker smoothing', 13)) axs[1].plot(downsampled_and_decimated[0],", "max_count_left = 0 min_count_left = 0 i_left = 0 while", "150]) plt.yticks([0, 0.1, 0.2]) plt.ylabel('Frequency (Hz)') plt.xlabel('Time (s)') box_0 =", "label=textwrap.fill('Extrapolated maxima', 12)) plt.scatter(minima_extrapolate_time, minima_extrapolate, c='cyan', zorder=4, label=textwrap.fill('Extrapolated minima', 12))", "2 * sum(weights_left * np.hstack((time_series_extended[int(len(lsq_signal) - 1 - i_left): int(len(lsq_signal)", "plt.text(4.12 * np.pi, 2, r'$\\Delta{t^{max}_{M}}$') plt.text(4.50 * np.pi, 2, r'$\\Delta{t^{max}_{M}}$')", "plt.plot(min_2_y_time, min_2_y_side, 'k-') plt.plot(dash_max_min_2_y_time, dash_max_min_2_y, 'k--') plt.text(4.08 * np.pi, -2.2,", "101) max_1_x = maxima_y[-1] * np.ones_like(max_1_x_time) min_1_x_time = np.linspace(minima_x[-1] -", "1001) time_series = np.cos(time) + np.cos(5 * time) knots =", "y, z = hs_ouputs y = y / (2 *", "* np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') for i", "/ 2), ((time_extended[-1001] + time_extended[-1000]) / 2) - 0.1, 100),", "'--', c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[0].plot(preprocess_time, preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott smoothing',", "extrema_type='maxima', smooth=True) min_unsmoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima', smooth=False) min_smoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots,", "dash_2_time = np.linspace(minima_x[-1], max_discard_time, 101) dash_2 = np.linspace(minima_y[-1], max_discard, 101)", "* np.ones_like(dash_max_min_2_y_time) max_1_x_time = np.linspace(maxima_x[-1] - width, maxima_x[-1] + width,", "time_series[time == minima_x[-1]]) + \\ time_series[time == minima_x[-1]] improved_slope_based_maximum_time =", "axs[0].plot(t, emd_sift[:, 0], '--', label='emd 0.3.3') axs[0].set_title('IMF 1') axs[0].set_ylim([-2, 2])", "t / 50) + 0.6 * np.cos(2 * np.pi *", "np.ones_like(min_dash_4) dash_final_time = np.linspace(improved_slope_based_maximum_time, improved_slope_based_minimum_time, 101) dash_final = np.linspace(improved_slope_based_maximum, improved_slope_based_minimum,", "axs[0].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1) axs[0].plot(knot", "bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht_pyemd.png') plt.show() plt.show() emd_sift = emd040.sift.sift(x) IP, IF,", "-0.20, r'$s_2$') plt.text(4.30 * np.pi + (minima_x[-1] - minima_x[-2]), 0.35", "0.1, 100), 2.75 * np.ones(100), c='gray') plt.plot(((time_extended[-1001] + time_extended[-1000]) /", "freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 0.2, 100) hht = emd040.spectra.hilberthuang(IF, IA,", "np.linspace(time_series[-1], minima_y[-1], 101) length_distance_time_2 = point_2 * np.pi * np.ones_like(length_distance_2)", "101) dash_max_min_2_y = -1.8 * np.ones_like(dash_max_min_2_y_time) max_1_x_time = np.linspace(maxima_x[-1] -", "2, 101), '--', c='grey') plt.savefig('jss_figures/knot_2.png') plt.show() # plot 1d -", "zorder=1, label='Knots') axs[2].set_xticks([np.pi, (3 / 2) * np.pi]) axs[2].set_xticklabels([r'$\\pi$', r'$\\frac{3}{2}\\pi$'])", "2 * np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots_uniform[0] * np.ones(101), np.linspace(-2,", "filter', 12)) axs[0].plot(preprocess_time, preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median filter', 13)) axs[0].plot(preprocess_time, preprocess.winsorize(window_width=window, a=0.8)[1],", "0.1, 0.2]) plt.ylabel('Frequency (Hz)') plt.xlabel('Time (s)') box_0 = ax.get_position() ax.set_position([box_0.x0,", "+ imfs_51[2, :] + imfs_51[3, :], label=textwrap.fill('Sum of IMF 1,", "Huang_wave[Huang_max_bool] Huang_min_time = Huang_time[Huang_min_bool] Huang_min = Huang_wave[Huang_min_bool] Coughlin_max_time = Coughlin_time[Coughlin_max_bool]", "50) + 0.6 * np.cos(2 * np.pi * t /", "ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width * 0.84, box_0.height]) ax.legend(loc='center left',", "100), 'k-') plt.legend(loc='upper left') plt.savefig('jss_figures/boundary_bases.png') plt.show() # plot 1a -", "r'3$\\pi$', r'4$\\pi$', r'5$\\pi$')) plt.yticks((-2, -1, 0, 1, 2), ('-2', '-1',", "= np.linspace((0 + a) * np.pi, (5 - a) *", "= emd040.sift.sift(x) IP, IF, IA = emd040.spectra.frequency_transform(emd_sift, 10, 'hilbert') freq_edges,", "- top seed_weights = np.ones(neural_network_k) / neural_network_k weights = 0", "s2 min_dash_time_3 = slope_based_minimum_time * np.ones_like(min_dash_1) min_dash_3 = np.linspace(slope_based_minimum -", "np.r_[utils.zero_crossing() == 1, False] optimal_minima = np.r_[False, utils.derivative_forward_diff() > 0,", "pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[1].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean", "= 1.0 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) ax.pcolormesh(x, y, np.abs(z), cmap='gist_rainbow',", "= np.linspace(improved_slope_based_maximum_time, improved_slope_based_minimum_time, 101) dash_final = np.linspace(improved_slope_based_maximum, improved_slope_based_minimum, 101) ax", "+= 1 plt.savefig('jss_figures/Duffing_equation_imfs.png') plt.show() hs_ouputs = hilbert_spectrum(t, emd_duff, emd_ht_duff, emd_if_duff,", "c='darkgreen', label=textwrap.fill('EEMD envelope', 10)) plt.plot(time, EEMD_minima_envelope, c='darkgreen') plt.plot(time, (EEMD_maxima_envelope +", "- col))] P[-1, col] = 1 # for additive constant", "= time_series[min_bool] max_dash_1 = np.linspace(maxima_y[-1] - width, maxima_y[-1] + width,", "* np.ones(100), np.linspace(-2.75, 2.75, 100), c='gray', linestyle='dashed') plt.xlim(3.4 * np.pi,", "plt.show() # plot 4 a = 0.21 width = 0.2", "'k-') plt.plot(min_dash_time_3, min_dash_3, 'k-') plt.plot(min_dash_time_4, min_dash_4, 'k-') plt.plot(maxima_dash_time_1, maxima_dash, 'k-')", "hts, ifs, max_frequency=10, which_imfs=[1], plot=False) x_hs, y, z = hs_ouputs", "2]) axs[0].set_xlim([0, 150]) axs[1].plot(t, dxdt) axs[1].set_title('Duffing Equation Velocity') axs[1].set_ylim([-1.5, 1.5])", "sharey=True) axs[0].set_title('Cubic B-Spline Bases') axs[0].plot(time, b_spline_basis[2, :].T, '--', label='Basis 1')", "plt.gcf().get_size_inches() factor = 0.9 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time,", "np.ones_like(max_dash_1) max_dash_3 = np.linspace(slope_based_maximum - width, slope_based_maximum + width, 101)", "CO$_{2}$ Concentration using AdvEMDpy', 40)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)') plt.plot(x_hs[0,", "np.ones_like(min_dash_1) dash_1_time = np.linspace(maxima_x[-1], minima_x[-1], 101) dash_1 = np.linspace(maxima_y[-1], minima_y[-1],", "= np.linspace(slope_based_maximum - width, slope_based_maximum + width, 101) dash_3_time =", "2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1002]) / 2), ((time_extended[-1001]", "max_internal_iter and (3) debug (confusing with external debugging) emd =", "dash_3 = np.linspace(minima_y[-1], slope_based_maximum, 101) s2 = (minima_y[-1] - maxima_y[-1])", "100), 'k-') plt.plot(6 * np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') plt.legend(loc='upper", "plot 6c ax = plt.subplot(111) figure_size = plt.gcf().get_size_inches() factor =", ":1], 12, 'hilbert') print(f'emd annual frequency error: {np.round(sum(np.abs(IF - np.ones_like(IF)))[0],", "dash_max_min_1_x = np.linspace(minima_y[-1], maxima_y[-1], 101) dash_max_min_1_x_time = 5.4 * np.pi", "gaussian_filter from emd_utils import time_extension, Utility from scipy.interpolate import CubicSpline", "vmax=z_max) plt.plot(t[:-1], 0.124 * np.ones_like(t[:-1]), '--', label=textwrap.fill('Hamiltonian frequency approximation', 15))", "PyEMD 0.2.10', 45)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)') plt.pcolormesh(time, freq_bins, hht,", "0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/DFA_hilbert_spectrum.png') plt.show() # plot 6c", "slope_based_minimum_time * np.ones_like(minima_dash) minima_line_dash_time = np.linspace(minima_x[-2], slope_based_minimum_time, 101) minima_line_dash =", "* np.pi, 1001) time_series = np.cos(time) + np.cos(5 * time)", "basis.cubic_b_spline(knots) chsi_basis = basis.chsi_basis(knots) # plot 1 plt.title('Non-Natural Cubic B-Spline", "+= 1 emd_utils_min = \\ emd_utils.Utility(time=time_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))],", "Average_min, c='cyan', zorder=4, label=textwrap.fill('Average minimum', 14)) plt.scatter(maxima_x, maxima_y, c='r', zorder=4,", "plt.subplots() figure_size = plt.gcf().get_size_inches() factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor *", "0.05, box_0.y0, box_0.width * 0.85, box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, -0.15))", "label=textwrap.fill('Improved slope-based minimum', 11)) plt.xlim(3.9 * np.pi, 5.5 * np.pi)", "1) + 1 + i_right)] = \\ sum(weights_right * np.hstack((time_series_extended[", "* 2 * np.pi * t) - emd_sift[:, 1])), 3)}')", "plt.scatter(minima_extrapolate_time, minima_extrapolate, c='cyan', zorder=4, label=textwrap.fill('Extrapolated minima', 12)) plt.plot(((time[-302] + time[-301])", "time_series[inflection_bool] fluctuation = emd_mean.Fluctuation(time=time, time_series=time_series) maxima_envelope = fluctuation.envelope_basis_function_approximation(knots, 'maxima', smooth=False,", "== minima_x[-1]]) + \\ time_series[time == minima_x[-1]] improved_slope_based_maximum_time = time[-1]", "np.ones_like(max_dash_1) max_dash_time_2 = maxima_x[-2] * np.ones_like(max_dash_1) min_dash_1 = np.linspace(minima_y[-1] -", "c='c', label=r'$\\tilde{h}_{(1,0)}^m(t)$', zorder=5) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time), '--', c='purple', label=r'$\\tilde{h}_{(1,0)}^{\\mu}(t)$', zorder=5) plt.yticks(ticks=[-2,", "* 0.85, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/DFA_hilbert_spectrum.png')", "5.5 * np.pi) plt.xticks((4 * np.pi, 5 * np.pi), (r'4$\\pi$',", "plt.show() # plot 1a - addition knot_demonstrate_time = np.linspace(0, 2", "np.abs(z).max() ax.pcolormesh(x_hs, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) ax.plot(x_hs[0, :], 8", "optimal_minima, smooth=False, smoothing_penalty=0.2, edge_effect='none')[0] ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Detrended Fluctuation", "= lsq_signal[:neural_network_m] vx = cvx.Variable(int(neural_network_k + 1)) objective = cvx.Minimize(cvx.norm((2", "0.0125, box_0.y0 + 0.075, box_0.width * 0.8, box_0.height * 0.9])", "min_1_x = minima_y[-1] * np.ones_like(min_1_x_time) dash_max_min_1_x = np.linspace(minima_y[-1], maxima_y[-1], 101)", "r'$4\\pi$', r'$5\\pi$']) box_2 = axs[2].get_position() axs[2].set_position([box_2.x0 - 0.05, box_2.y0, box_2.width", "axs[0].legend(loc='center left', bbox_to_anchor=(1, -0.15)) box_1 = axs[1].get_position() axs[1].set_position([box_1.x0 - 0.05,", "iterations in range(1000): output = np.matmul(weights, train_input) error = (t", "101), '--', c='grey') plt.savefig('jss_figures/knot_1.png') plt.show() # plot 1c - addition", "emd_duff, emd_ht_duff, emd_if_duff, _, _, _, _ = emd_duffing.empirical_mode_decomposition(verbose=False) fig,", "slope_based_maximum = minima_y[-1] + (slope_based_maximum_time - minima_x[-1]) * s1 max_dash_time_3", "- a) * np.pi, 11) time_series = np.cos(time) + np.cos(5", "maxima_extrapolate, c='magenta', zorder=3, label=textwrap.fill('Extrapolated maxima', 12)) plt.scatter(minima_extrapolate_time, minima_extrapolate, c='cyan', zorder=4,", "plt.plot(length_distance_time, length_distance, 'k--') plt.plot(length_distance_time_2, length_distance_2, 'k--') plt.plot(length_time, length_top, 'k-') plt.plot(length_time,", "CO2_data['decimal date']) plt.title(textwrap.fill('Mean Monthly Concentration of Carbon Dioxide in the", "plt.savefig('jss_figures/DFA_different_trends_zoomed.png') plt.show() hs_ouputs = hilbert_spectrum(time, imfs_51, hts_51, ifs_51, max_frequency=12, plot=False)", "np.linspace(-3.0, -2.0, 101), '--', c='grey', label='Knots', zorder=1) plt.xticks((0, 1 *", "= 0, np.abs(z).max() fig, ax = plt.subplots() figure_size = plt.gcf().get_size_inches()", "'k-') axs[0].plot(6 * np.ones(100), np.linspace(-0.2, 0.8, 100), 'k-') axs[0].set_xticks([5, 6])", "np.pi, 101) time_extended = time_extension(time) time_series_extended = np.zeros_like(time_extended) / 0", "+ width, 101) max_1_x = maxima_y[-1] * np.ones_like(max_1_x_time) min_1_x_time =", "function error: {np.round(sum(abs(0.1 * np.cos(0.04 * 2 * np.pi *", "5.3 * np.pi + width, 101) max_2_x = maxima_y[-2] *", ":]), '--', label=r'$\\omega = 4$', Linewidth=3) ax.plot(x_hs[0, :], 2 *", "plot 1b - addition knot_demonstrate_time = np.linspace(0, 2 * np.pi,", "sns import matplotlib.pyplot as plt from scipy.integrate import odeint from", "axs[0].plot(knots[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[0].legend(loc='lower", "with 11 knots: {np.round(np.var(time_series - imfs_51[3, :]), 3)}') for knot", "np.pi, 1.55 * np.pi, 101), -5.5 * np.ones(101), 'k--') axs[0].plot(0.95", "adjustment # test - bottom weights_right = np.hstack((weights, 0)) max_count_right", "axs[1].set_xticks([0, np.pi, 2 * np.pi, 3 * np.pi, 4 *", "i_left):int(len(lsq_signal))]) if sum(emd_utils_max.max_bool_func_1st_order_fd()) > 0: max_count_left += 1 emd_utils_min =", "_, _ = emd_duffing.empirical_mode_decomposition(verbose=False) fig, axs = plt.subplots(2, 1) plt.subplots_adjust(hspace=0.3)", "time[time == maxima_x[-2]]) + maxima_x[-1] Huang_wave = (A1 / A2)", "axs[0].plot(6 * np.ones(100), np.linspace(-0.2, 0.8, 100), 'k-') axs[0].set_xticks([5, 6]) axs[0].set_xticklabels([r'$", "* np.cos(2 * np.pi * t / 25) + 0.5", "- emd_duff[2, :])), 3)}') axs[1].plot(t, py_emd[1, :], '--', label='PyEMD 0.2.10')", "max_smoothed[0], label=textwrap.fill('Smoothed maxima envelope', 10), c='red') plt.plot(time, min_unsmoothed[0], label=textwrap.fill('Unsmoothed minima", "0.5)) plt.savefig('jss_figures/edge_effects_symmetry_anti.png') plt.show() # plot 4 a = 0.21 width", "plt.plot(np.linspace(((time[-302] + time[-301]) / 2), ((time[-302] + time[-301]) / 2)", "* np.pi, 5 * np.pi]) axs[2].set_xticklabels(['$0$', r'$\\pi$', r'$2\\pi$', r'$3\\pi$', r'$4\\pi$',", "random.sample(range(1000), 500): preprocess_time_series[i] += np.random.normal(0, 1) preprocess = Preprocess(time=preprocess_time, time_series=preprocess_time_series)", "plt.show() # plot 1b - addition knot_demonstrate_time = np.linspace(0, 2", "label='Minima') plt.scatter(slope_based_maximum_time, slope_based_maximum, c='orange', zorder=4, label=textwrap.fill('Slope-based maximum', 11)) plt.scatter(slope_based_minimum_time, slope_based_minimum,", "ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_slope_based.png') plt.show() # plot 5 a", "= hs_ouputs y = y / (2 * np.pi) z_min,", "+ imfs_31[2, :], label=textwrap.fill('Sum of IMF 1 and IMF 2", "3)}') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 2, 100) hht = emd040.spectra.hilberthuang(IF,", "np.linspace(0, 2 * np.pi, 1001) knot_demonstrate_time_series = np.sin(knot_demonstrate_time) + np.sin(5", "edge_effect='anti-symmetric', verbose=False)[0] fig, axs = plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time", "1001) knots_51 = np.linspace(0, 5 * np.pi, 51) time_series =", "for knot in knots_31: axs[1].plot(knot * np.ones(101), np.linspace(-5, 5, 101),", "figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Duffing Equation using emd", "c='red') plt.plot(time, min_unsmoothed[0], label=textwrap.fill('Unsmoothed minima envelope', 10), c='cyan') plt.plot(time, min_smoothed[0],", "'', '', '', '']) box_1 = axs[1].get_position() axs[1].set_position([box_1.x0 - 0.05,", "label=r'$h_{(1,0)}(t)$', zorder=1) plt.scatter(pseudo_alg_time[pseudo_utils.max_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.max_bool_func_1st_order_fd()], c='r', label=r'$M(t_i)$', zorder=2) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time) +", "axs[2].set_xticks([np.pi, (3 / 2) * np.pi]) axs[2].set_xticklabels([r'$\\pi$', r'$\\frac{3}{2}\\pi$']) box_2 =", "= np.linspace(0, 11, 1101) basis = emd_basis.Basis(time=time, time_series=time) b_spline_basis =", "* np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1 and Uniform Knots')", "label=textwrap.fill('Henderson-Whittaker smoothing', 13)) axs[1].plot(downsampled_and_decimated[0], downsampled_and_decimated[1], label=textwrap.fill('Downsampled & decimated', 13)) axs[1].plot(downsampled[0],", "axs[2].plot(time, time_series, label='Time series') axs[2].plot(time, imfs_11[1, :], label='IMF 1 with", "axs[1].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize interpolation filter', 14)) axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.90)[1],", "train_input = P[:-1, :] lr = 0.01 for iterations in", "101), 5.5 * np.ones(101), 'k--') axs[0].plot(np.linspace(0.95 * np.pi, 1.55 *", "/ 2), ((time[-302] + time[-301]) / 2) + 0.1, 100),", "axs[0].set_xticklabels(['', '', '', '', '', '']) box_0 = axs[0].get_position() axs[0].set_position([box_0.x0", "axs[2].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots[0] *", "y_points_1 = [-2, 0, 2] y_points_2 = [-1, 0, 1]", "101) min_1_y_time = minima_x[-1] * np.ones_like(min_1_y) dash_max_min_1_y_time = np.linspace(minima_x[-1], maxima_x[-1],", "c='darkorange', label=textwrap.fill('Inflection point envelope', 10)) plt.plot(time, binomial_points_envelope, c='deeppink', label=textwrap.fill('Binomial average", "axs[2].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), -5.5 * np.ones(101),", "5 * np.pi, 1001) time_series = np.cos(time) + np.cos(5 *", "addition window = 81 fig, axs = plt.subplots(2, 1) fig.subplots_adjust(hspace=0.4)", "axs[1].get_position() axs[1].set_position([box_1.x0 - 0.05, box_1.y0, box_1.width * 0.85, box_1.height]) axs[1].legend(loc='center", "dash_max_min_1_x_time = 5.4 * np.pi * np.ones_like(dash_max_min_1_x) max_1_y = np.linspace(maxima_y[-1]", "1) or (min_count_left < 1)) and (i_left < len(lsq_signal) -", "i_left > 1: emd_utils_max = \\ emd_utils.Utility(time=time_extended[int(len(lsq_signal) - 1 -", "plt.ylabel('Frequency (Hz)') plt.xlabel('Time (s)') box_0 = ax.get_position() ax.set_position([box_0.x0, box_0.y0 +", "axs[0].plot(t, emd_duff[1, :], label='AdvEMDpy') axs[0].plot(t, py_emd[0, :], '--', label='PyEMD 0.2.10')", "_, _, knots, _, _ = emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=2, verbose=False) fig,", "2 * np.pi * t), '--', label=r'$0.1$cos$(0.08{\\pi}t)$') axs[1].set_title('IMF 2') axs[1].set_ylim([-0.2,", "imfs = emd.empirical_mode_decomposition(knots=knots_uniform, edge_effect='anti-symmetric', verbose=False)[0] fig, axs = plt.subplots(3, 1)", "preprocess.downsample() axs[0].plot(downsampled_and_decimated[0], downsampled_and_decimated[1], label=textwrap.fill('Downsampled & decimated', 11)) downsampled = preprocess.downsample(decimate=False)", "maxima_y[-1] * np.ones_like(max_1_x_time) min_1_x_time = np.linspace(minima_x[-1] - width, minima_x[-1] +", "np.pi, 4 * np.pi, 5 * np.pi), (r'$0$', r'$\\pi$', r'2$\\pi$',", "plt.text(4.43 * np.pi + (slope_based_minimum_time - minima_x[-1]), -0.20 + (slope_based_minimum", "axs[1].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].set_ylim(-5.5, 5.5) axs[1].set_xlim(0.95 * np.pi,", "box_0.width * 0.8, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))", "max_discard_time + width, 101) max_discard_dash = max_discard * np.ones_like(max_discard_dash_time) dash_2_time", "bottom knots = np.linspace(time[0], time[-1], 200) emd_example = AdvEMDpy.EMD(time=time, time_series=signal)", "plt.xticks(ticks=[0, np.pi, 2 * np.pi], labels=[r'0', r'$\\pi$', r'$2\\pi$']) box_0 =", "'hilbert') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 0.2, 100) hht = emd040.spectra.hilberthuang(IF,", "7 a = 0.25 width = 0.2 time = np.linspace((0", "pseudo_alg_time_series[pseudo_utils.max_bool_func_1st_order_fd()], c='r', label=r'$M(t_i)$', zorder=2) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time) + 1, '--', c='r',", "axs[0].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), -5.5 * np.ones(101),", "plt.plot(max_dash_time_2, max_dash_2, 'k-') plt.plot(max_dash_time_3, max_dash_3, 'k-') plt.plot(min_dash_time_1, min_dash_1, 'k-') plt.plot(min_dash_time_2,", "* np.ones_like(min_dash_time) dash_1_time = np.linspace(maxima_x[-1], minima_x[-1], 101) dash_1 = np.linspace(maxima_y[-1],", "= 0 i_right = 0 while ((max_count_right < 1) or", "packages Carbon Dioxide - bottom knots = np.linspace(time[0], time[-1], 200)", "5 a = 0.25 width = 0.2 time = np.linspace(0,", "= prob.solve(verbose=True, solver=cvx.ECOS) weights_left = np.array(vx.value) max_count_left = 0 min_count_left", "max_2_x_time_side = np.linspace(5.3 * np.pi - width, 5.3 * np.pi", "factor * figure_size[1])) axs[0].plot(t, emd_duff[1, :], label='AdvEMDpy') axs[0].plot(t, py_emd[0, :],", "4$', Linewidth=3) ax.plot(x_hs[0, :], 2 * np.ones_like(x_hs[0, :]), '--', label=r'$\\omega", "axs[2].plot(1.55 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--', label='Zoomed", "* np.ones_like(length_time_2) length_bottom_2 = minima_y[-1] * np.ones_like(length_time_2) symmetry_axis_1_time = minima_x[-1]", "+= 1 emd_utils_min = \\ emd_utils.Utility(time=time_extended[int(2 * (len(lsq_signal) - 1)", "31) imfs_31, hts_31, ifs_31 = advemdpy.empirical_mode_decomposition(knots=knots_31, max_imfs=2, edge_effect='symmetric_anchor', verbose=False)[:3] knots_11", "minimum', 10)) plt.scatter(Coughlin_max_time, Coughlin_max, c='darkorange', zorder=4, label=textwrap.fill('Coughlin maximum', 14)) plt.scatter(Coughlin_min_time,", "= utils_Coughlin.max_bool_func_1st_order_fd() Coughlin_min_bool = utils_Coughlin.min_bool_func_1st_order_fd() Huang_max_time = Huang_time[Huang_max_bool] Huang_max =", "maxima_y[-1]) / (minima_x[-1] - maxima_x[-1]) slope_based_minimum_time = minima_x[-1] + (minima_x[-1]", "b_spline_basis[5, :].T, '--', label='Basis 4') axs[0].legend(loc='upper left') axs[0].plot(5 * np.ones(100),", "pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[0].plot(preprocess_time, preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott", "time[max_bool] maxima_y = time_series[max_bool] min_bool = utils.min_bool_func_1st_order_fd() minima_x = time[min_bool]", "range(1, len(knots)): axs[i].plot(knots[j] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey')", "CO2_data['decimal date'] signal = np.asarray(signal) time = CO2_data['month'] time =", "- width, 5.3 * np.pi + width, 101) max_2_x =", "= plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Characteristic Wave Effects Example') plt.plot(time, time_series, LineWidth=2,", "and IMF 2 with 31 knots', 19)) axs[1].plot(time, imfs_51[2, :]", "smooth=False, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] minima_envelope_smooth = fluctuation.envelope_basis_function_approximation(knots, 'minima', smooth=True, smoothing_penalty=0.2,", "end_point = time_series[-1] time_reflect = np.linspace((5 - a) * np.pi,", "= {0, 50, 100, 150} y_points_1 = [-2, 0, 2]", "= np.linspace(slope_based_minimum - width, slope_based_minimum + width, 101) dash_4_time =", "plt.show() # plot 1e - addition fig, axs = plt.subplots(2,", "width, improved_slope_based_minimum + width, 101) min_dash_time_4 = improved_slope_based_minimum_time * np.ones_like(min_dash_4)", "= np.linspace(improved_slope_based_maximum, improved_slope_based_minimum, 101) ax = plt.subplot(111) figure_size = plt.gcf().get_size_inches()", "box_1.y0, box_1.width * 0.85, box_1.height]) axs[1].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8)", "* np.cos(omega * ts)] t = np.linspace(0, 150, 1501) XY0", "= hs_ouputs z_min, z_max = 0, np.abs(z).max() ax.pcolormesh(x_hs, y, np.abs(z),", "np.linspace((5 - 2.6 * a) * np.pi, (5 - a)", "import textwrap import emd_mean import AdvEMDpy import emd_basis import emd_utils", "4)) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('First Iteration of Sifting Algorithm')", "r'$s_1$') plt.text(4.43 * np.pi, -0.20, r'$s_2$') plt.text(4.30 * np.pi +", "axs[1].set_title('Zoomed Region') axs[0].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[0].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless", "lsq_signal neural_network_m = 200 neural_network_k = 100 # forward ->", "= time[lsq_utils.min_bool_func_1st_order_fd()] minima_extrapolate = time_series_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] minima_extrapolate_time = time_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] ax =", "100, 150} y_points_1 = [-2, 0, 2] y_points_2 = [-1,", "np.linspace(minima_y[-1], slope_based_maximum, 101) s2 = (minima_y[-1] - maxima_y[-1]) / (minima_x[-1]", "-5.5 * np.ones(101), 'k--') axs[2].plot(0.95 * np.pi * np.ones(101), np.linspace(-5.5,", "box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/detrended_fluctuation_analysis.png') plt.show() # Duffing Equation", "slope_based_minimum_time) * s2 min_dash_time_3 = slope_based_minimum_time * np.ones_like(min_dash_1) min_dash_3 =", "-2.5, r'$\\frac{p_1}{2}$') plt.xlim(3.9 * np.pi, 5.6 * np.pi) plt.xticks((4 *", "left', bbox_to_anchor=(1, 0.5), fontsize=8) ax.set_xticks(x_points) ax.set_xticklabels(x_names) axis += 1 plt.savefig('jss_figures/Duffing_equation_imfs.png')", "np.linspace(-5.5, 5.5, 101), 'k--') axs[2].plot(1.55 * np.pi * np.ones(101), np.linspace(-5.5,", "min_dash_time_1 = minima_x[-1] * np.ones_like(min_dash_1) min_dash_time_2 = minima_x[-2] * np.ones_like(min_dash_1)", "min_2_y, 'k-') plt.plot(min_2_y_time, min_2_y_side, 'k-') plt.plot(dash_max_min_2_y_time, dash_max_min_2_y, 'k--') plt.text(4.08 *", "(slope_based_minimum - minima_y[-1]), r'$s_2$') plt.plot(minima_line_dash_time, minima_line_dash, 'k--') plt.plot(maxima_line_dash_time, maxima_line_dash, 'k--')", "np.linspace(maxima_y[-2] - width, maxima_y[-2] + width, 101) max_2_y_side = np.linspace(-1.8", "(5 - a) * np.pi, 101))) time_series_anti_reflect = time_series_reflect[0] -", "6a np.random.seed(0) time = np.linspace(0, 5 * np.pi, 1001) knots_51", "minima_extrapolate, c='cyan', zorder=4, label=textwrap.fill('Extrapolated minima', 12)) plt.plot(((time[-302] + time[-301]) /", "* 0.85, box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, -0.15)) box_1 = axs[1].get_position()", "* np.pi, 11) time_series = np.cos(time) + np.cos(5 * time)", "box_0.y0, box_0.width * 0.85, box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, -0.15)) box_1", "minima_dash_time_1 = minima_x[-2] * np.ones_like(minima_dash) minima_dash_time_2 = minima_x[-1] * np.ones_like(minima_dash)", "* 2 * np.pi * t), '--', label=r'$0.1$cos$(0.08{\\pi}t)$') axs[1].set_title('IMF 2')", "Dynamically Optimised Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2, zorder=100) axs[0].set_yticks(ticks=[-2, 0, 2])", "= time_series[-1] improved_slope_based_minimum_time = slope_based_minimum_time improved_slope_based_minimum = improved_slope_based_maximum + s2", "0.35, r'$s_1$') plt.text(4.43 * np.pi, -0.20, r'$s_2$') plt.text(4.30 * np.pi", "import Hilbert, hilbert_spectrum from emd_preprocess import Preprocess from emd_mean import", "basis.chsi_basis(knots) # plot 1 plt.title('Non-Natural Cubic B-Spline Bases at Boundary')", "101), 5.5 * np.ones(101), 'k--') axs[2].plot(np.linspace(0.95 * np.pi, 1.55 *", "maxima_x[-2] + width, 101) max_2_x_time_side = np.linspace(5.3 * np.pi -", "plt.subplots_adjust(hspace=0.2) axs[0].plot(t, x) axs[0].set_title('Duffing Equation Displacement') axs[0].set_ylim([-2, 2]) axs[0].set_xlim([0, 150])", "plt.subplots(3, 1) plt.suptitle(textwrap.fill('Comparison of Trends Extracted with Different Knot Sequences',", "box_1.width * 0.85, box_1.height]) plt.savefig('jss_figures/preprocess_filter.png') plt.show() # plot 1e -", "label='Signal') plt.scatter(Huang_max_time, Huang_max, c='magenta', zorder=4, label=textwrap.fill('Huang maximum', 10)) plt.scatter(Huang_min_time, Huang_min,", "Atmosphere', 35)) plt.ylabel('Parts per million') plt.xlabel('Time (years)') plt.savefig('jss_figures/CO2_concentration.png') plt.show() signal", "c='grey') plt.savefig('jss_figures/knot_2.png') plt.show() # plot 1d - addition window =", "Spline Bases') axs[1].plot(time, chsi_basis[10, :].T, '--') axs[1].plot(time, chsi_basis[11, :].T, '--')", "13)) plt.plot(np.linspace(((time[-202] + time[-201]) / 2), ((time[-202] + time[-201]) /", "slope_based_maximum_time, 101) dash_3 = np.linspace(minima_y[-1], slope_based_maximum, 101) s2 = (minima_y[-1]", "* np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[2].plot(knots[2][0] *", "maxima_time = time[lsq_utils.max_bool_func_1st_order_fd()] maxima_extrapolate = time_series_extended[utils_extended.max_bool_func_1st_order_fd()][-1] maxima_extrapolate_time = time_extended[utils_extended.max_bool_func_1st_order_fd()][-1] minima", "= plt.subplots() figure_size = plt.gcf().get_size_inches() factor = 0.7 plt.gcf().set_size_inches((figure_size[0], factor", "-3.2, r'$\\Delta{t^{min}_{m}}$') plt.text(4.12 * np.pi, 2, r'$\\Delta{t^{max}_{M}}$') plt.text(4.50 * np.pi,", "/ (2 * np.pi) z_min, z_max = 0, np.abs(z).max() figure_size", "plt.plot(min_1_x_time, min_1_x, 'k-') plt.plot(min_1_x_time_side, min_1_x, 'k-') plt.plot(dash_max_min_1_x_time, dash_max_min_1_x, 'k--') plt.text(5.42", "np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1, label='Knots') axs[1].set_xticks([0, np.pi,", "knots_31: axs[1].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1)", "freq_edges) hht = gaussian_filter(hht, sigma=1) fig, ax = plt.subplots() figure_size", "axis=1) # steepest descent max_gradient_vector = average_gradients * (np.abs(average_gradients) ==", "= axs[1].get_position() axs[1].set_position([box_1.x0 - 0.06, box_1.y0, box_1.width * 0.85, box_1.height])", "* np.pi, 5 * np.pi), (r'4$\\pi$', r'5$\\pi$')) plt.yticks((-2, -1, 0,", "AdvEMDpy.EMD(time=t, time_series=x) emd_duff, emd_ht_duff, emd_if_duff, _, _, _, _ =", "plt.scatter(minima_time, minima, c='b', zorder=3, label='Minima') plt.scatter(maxima_extrapolate_time, maxima_extrapolate, c='magenta', zorder=3, label=textwrap.fill('Extrapolated", "* np.ones_like(dash_max_min_2_x) max_2_y = np.linspace(maxima_y[-2] - width, maxima_y[-2] + width,", "1001) knot_demonstrate_time_series = np.sin(knot_demonstrate_time) + np.sin(5 * knot_demonstrate_time) knots_uniform =", "minima_x[-1] - maxima_x[-1] + minima_x[-1] max_discard_dash_time = np.linspace(max_discard_time - width,", ">= minima_x[-1]] = 1.5 * (time_series[time >= minima_x[-1]] - time_series[time", "* (1 / P1) * (Coughlin_time - Coughlin_time[0])) Average_max_time =", "bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].set_ylim(-5.5, 5.5) axs[1].set_xlim(0.95 * np.pi, 1.55 *", "np.abs(maxima_y[-1] - minima_y[-1]) / 2 P2 = 2 * np.abs(maxima_x[-2]", "= np.linspace(maxima_y[-2] - width, maxima_y[-2] + width, 101) max_2_y_side =", "plt.plot(time, time_series, LineWidth=2, label='Time series') plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima')", "pseudo_alg_time.copy() np.random.seed(1) random.seed(1) preprocess_time_series = pseudo_alg_time_series + np.random.normal(0, 0.1, len(preprocess_time))", "plt.plot(t[:-1], 0.04 * np.ones_like(t[:-1]), 'g--', label=textwrap.fill('Driving function frequency', 15)) plt.xticks([0,", "5.4 * np.pi + width, 101) min_1_x = minima_y[-1] *", "x_points = [0, 50, 100, 150] x_names = {0, 50,", "LineWidth=2, label='Signal') plt.scatter(Huang_max_time, Huang_max, c='magenta', zorder=4, label=textwrap.fill('Huang maximum', 10)) plt.scatter(Huang_min_time,", "= np.hstack((weights, 0)) max_count_right = 0 min_count_right = 0 i_right", "len(lsq_signal) - 1): time_series_extended[int(2 * (len(lsq_signal) - 1) + 1", "2, 101), '--', c='grey') plt.savefig('jss_figures/knot_uniform.png') plt.show() # plot 1b -", "length_distance_2 = np.linspace(time_series[-1], minima_y[-1], 101) length_distance_time_2 = point_2 * np.pi", "plt.ylabel(r'Frequency (rad.s$^{-1}$)') plt.xlabel('Time (s)') box_0 = ax.get_position() ax.set_position([box_0.x0, box_0.y0 +", "+ time[-201]) / 2) * np.ones(100), np.linspace(-2.75, 2.75, 100), c='gray',", "label=textwrap.fill('Anti-Symmetric maxima', 10)) plt.scatter(no_anchor_max_time, no_anchor_max, c='gray', zorder=4, label=textwrap.fill('Symmetric maxima', 10))", "(year$^{-1}$)') plt.xlabel('Time (years)') plt.pcolormesh(time, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(time,", "14)) plt.scatter(Average_max_time, Average_max, c='orangered', zorder=4, label=textwrap.fill('Average maximum', 14)) plt.scatter(Average_min_time, Average_min,", "py_emd = pyemd(signal) IP, IF, IA = emd040.spectra.frequency_transform(py_emd[:2, :].T, 12,", "plt.text(4.30 * np.pi, 0.35, r'$s_1$') plt.text(4.43 * np.pi, -0.20, r'$s_2$')", "r'$\\beta$L') plt.text(5.34 * np.pi, -0.05, 'L') plt.scatter(maxima_x, maxima_y, c='r', zorder=4,", "-2.0, 101), '--', c='grey', label='Knots', zorder=1) plt.xticks((0, 1 * np.pi,", "np.pi + (minima_x[-1] - minima_x[-2]), 0.35 + (minima_y[-1] - minima_y[-2]),", "prob.solve(verbose=True, solver=cvx.ECOS) weights_left = np.array(vx.value) max_count_left = 0 min_count_left =", "time) utils = emd_utils.Utility(time=time, time_series=time_series) max_bool = utils.max_bool_func_1st_order_fd() maxima_x =", "Coughlin_max_bool = utils_Coughlin.max_bool_func_1st_order_fd() Coughlin_min_bool = utils_Coughlin.min_bool_func_1st_order_fd() Huang_max_time = Huang_time[Huang_max_bool] Huang_max", "import pandas as pd import cvxpy as cvx import seaborn", "slope_based_minimum_time * np.ones_like(min_dash_1) min_dash_3 = np.linspace(slope_based_minimum - width, slope_based_minimum +", "(EEMD_maxima_envelope + EEMD_minima_envelope) / 2, c='darkgreen') plt.plot(time, inflection_points_envelope, c='darkorange', label=textwrap.fill('Inflection", "'--') axs[1].plot(time, chsi_basis[11, :].T, '--') axs[1].plot(time, chsi_basis[12, :].T, '--') axs[1].plot(time,", "2 and Dynamically Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2, zorder=100) axs[2].set_yticks(ticks=[-2,", "length_top_2 = time_series[-1] * np.ones_like(length_time_2) length_bottom_2 = minima_y[-1] * np.ones_like(length_time_2)", "/ (2 * np.pi) z_min, z_max = 0, np.abs(z).max() fig,", "Concentration of Carbon Dioxide in the Atmosphere', 35)) plt.ylabel('Parts per", "time_series[time == minima_x[-1]] improved_slope_based_maximum_time = time[-1] improved_slope_based_maximum = time_series[-1] improved_slope_based_minimum_time", "0.85, box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[0].set_ylim(-5.5, 5.5) axs[0].set_xlim(0.95", "1: emd_utils_max = \\ emd_utils.Utility(time=time_extended[int(2 * (len(lsq_signal) - 1) +", "(slope_based_maximum_time - slope_based_minimum_time) * s2 min_dash_time_3 = slope_based_minimum_time * np.ones_like(min_dash_1)", "1b - addition knot_demonstrate_time = np.linspace(0, 2 * np.pi, 1001)", "emd_sift = emd040.sift.sift(signal) IP, IF, IA = emd040.spectra.frequency_transform(emd_sift[:, :1], 12,", "axs[2].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') for", "imfs_31[2, :], label=textwrap.fill('Sum of IMF 1 and IMF 2 with", "fig, axs = plt.subplots(1, 2, sharey=True) axs[0].set_title('Cubic B-Spline Bases') axs[0].plot(time,", "* (len(lsq_signal) - 1) + 1 + i_right)] = \\", "0, 2]) axs[2].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$'])", "6c time = np.linspace(0, 5 * np.pi, 1001) time_series =", "- width, minima_y[-2] + width, 101) min_2_y_side = np.linspace(-1.8 -", "plt.plot(maxima_dash_time_1, maxima_dash, 'k-') plt.plot(maxima_dash_time_2, maxima_dash, 'k-') plt.plot(maxima_dash_time_3, maxima_dash, 'k-') plt.plot(minima_dash_time_1,", "= np.linspace(time[0], time[-1], 200) emd_example = AdvEMDpy.EMD(time=time, time_series=signal) imfs, hts,", "plt.plot(time, maxima_envelope, c='darkblue', label=textwrap.fill('EMD envelope', 10)) plt.plot(time, minima_envelope, c='darkblue') plt.plot(time,", "bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/pseudo_algorithm.png') plt.show() knots = np.arange(12) time = np.linspace(0,", "= 1 # for additive constant t = lsq_signal[-neural_network_m:] #", "= plt.figure(figsize=(9, 4)) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('First Iteration of", "max_2_y_time = maxima_x[-2] * np.ones_like(max_2_y) min_2_y = np.linspace(minima_y[-2] - width,", "plt.xlabel('Time (s)') box_0 = ax.get_position() ax.set_position([box_0.x0, box_0.y0 + 0.05, box_0.width", "plt.title('Symmetry Edge Effects Example') plt.plot(time_reflect, time_series_reflect, 'g--', LineWidth=2, label=textwrap.fill('Symmetric signal',", "i in range(3): for j in range(1, len(knots_uniform)): axs[i].plot(knots_uniform[j] *", "Equation Velocity') axs[1].set_ylim([-1.5, 1.5]) axs[1].set_xlim([0, 150]) axis = 0 for", ">= minima_x[-1]] - time_series[time == minima_x[-1]]) + \\ time_series[time ==", "time_extended[-1000]) / 2), ((time_extended[-1001] + time_extended[-1000]) / 2) - 0.1,", "plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time, time_series, LineWidth=2, label='Signal') plt.title('Slope-Based", "using emd 0.3.3', 45)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)') plt.pcolormesh(time, freq_bins,", "500:].T, '--', label=r'$ B_{-3,4}(t) $') plt.plot(time[500:], b_spline_basis[3, 500:].T, '--', label=r'$", "in random.sample(range(1000), 500): preprocess_time_series[i] += np.random.normal(0, 1) preprocess = Preprocess(time=preprocess_time,", "= 0.01 for iterations in range(1000): output = np.matmul(weights, train_input)", "axs[2].set_xticklabels([r'$\\pi$', r'$\\frac{3}{2}\\pi$']) box_2 = axs[2].get_position() axs[2].set_position([box_2.x0 - 0.05, box_2.y0, box_2.width", "* np.pi, 5 * np.pi]) axs[0].set_xticklabels(['', '', '', '', '',", "ax.set_xticklabels(['$0$', r'$\\pi$', r'$2\\pi$', r'$3\\pi$', r'$4\\pi$']) plt.ylabel(r'Frequency (rad.s$^{-1}$)') plt.xlabel('Time (s)') box_0", "101) min_dash_2 = np.linspace(minima_y[-2] - width, minima_y[-2] + width, 101)", "1 - i_left + neural_network_k)], 1))) + 1 i_left +=", "axs[1].set_position([box_1.x0 - 0.06, box_1.y0, box_1.width * 0.85, box_1.height]) plt.savefig('jss_figures/preprocess_smooth.png') plt.show()", "(imfs_31[1, :] + imfs_31[2, :])), 3)}') for knot in knots_31:", "'', '', '', '', '']) axs[0].plot(np.linspace(0.95 * np.pi, 1.55 *", "0: max_count_right += 1 emd_utils_min = \\ emd_utils.Utility(time=time_extended[int(2 * (len(lsq_signal)", "Filtered Hilbert Spectrum of CO$_{2}$ Concentration using emd 0.3.3', 45))", "= advemdpy.empirical_mode_decomposition(knots=knots_11, max_imfs=1, edge_effect='symmetric_anchor', verbose=False)[:3] fig, axs = plt.subplots(3, 1)", "10), zorder=1) plt.text(5.1 * np.pi, -0.7, r'$\\beta$L') plt.text(5.34 * np.pi,", "knots', 19)) axs[1].plot(time, imfs_51[2, :] + imfs_51[3, :], label=textwrap.fill('Sum of", ":]) axs[1, 1].plot(time, imfs[2, :]) axis = 0 for ax", "'--', label='Basis 2') axs[0].plot(time, b_spline_basis[4, :].T, '--', label='Basis 3') axs[0].plot(time,", "time_series_extended, c='g', zorder=1, label=textwrap.fill('Extrapolated signal', 12)) plt.scatter(maxima_time, maxima, c='r', zorder=3,", "2 * np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1 and Uniform", "= np.linspace(minima_x[-1], slope_based_maximum_time, 101) dash_3 = np.linspace(minima_y[-1], slope_based_maximum, 101) s2", "plt.show() # plot 1d - addition window = 81 fig,", "time_series_extended = np.zeros_like(time_extended) / 0 time_series_extended[int(len(lsq_signal) - 1):int(2 * (len(lsq_signal)", "-1.8 * np.ones_like(dash_max_min_2_y_time) max_1_x_time = np.linspace(maxima_x[-1] - width, maxima_x[-1] +", "np.pi + width, 101) min_1_x = minima_y[-1] * np.ones_like(min_1_x_time) dash_max_min_1_x", "time_reflect[utils.max_bool_func_1st_order_fd()] no_anchor_max = time_series_reflect[utils.max_bool_func_1st_order_fd()] point_1 = 5.4 length_distance = np.linspace(maxima_y[-1],", "label='PyEMD 0.2.10') axs[0].plot(t, emd_sift[:, 0], '--', label='emd 0.3.3') axs[0].set_title('IMF 1')", "* np.pi, 1.55 * np.pi) plt.savefig('jss_figures/DFA_different_trends_zoomed.png') plt.show() hs_ouputs = hilbert_spectrum(time,", "y.min(), y.max()]) box_0 = ax.get_position() ax.set_position([box_0.x0 + 0.0125, box_0.y0 +", "101), '--', c='grey') plt.savefig('jss_figures/knot_uniform.png') plt.show() # plot 1b - addition", "dash_3_time = np.linspace(minima_x[-1], slope_based_maximum_time, 101) dash_3 = np.linspace(minima_y[-1], slope_based_maximum, 101)", "width, minima_y[-1] + width, 101) min_1_y_side = np.linspace(-2.1 - width,", "c='darkred') plt.plot(time, (maxima_envelope_smooth + minima_envelope_smooth) / 2, c='darkred') plt.plot(time, EEMD_maxima_envelope,", "* 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert_emd.png') plt.show() # compare", "101), 'k--') axs[0].plot(1.55 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101),", "dash_1, 'k--') plt.plot(dash_2_time, dash_2, 'k--') plt.plot(dash_3_time, dash_3, 'k--') plt.plot(dash_4_time, dash_4,", "series') axs[0].plot(time, imfs_51[1, :] + imfs_51[2, :] + imfs_51[3, :],", "edge_effect='symmetric_anchor', verbose=False)[:3] knots_31 = np.linspace(0, 5 * np.pi, 31) imfs_31,", "+ width, 101) min_dash_2 = np.linspace(minima_y[-2] - width, minima_y[-2] +", "emd_utils_min = \\ emd_utils.Utility(time=time_extended[int(2 * (len(lsq_signal) - 1) + 1):", "'k-') plt.plot(length_time_2, length_top_2, 'k-') plt.plot(length_time_2, length_bottom_2, 'k-') plt.plot(end_time, end_signal, 'k-')", "r'$\\pi$', r'$2\\pi$', r'$3\\pi$', r'$4\\pi$', r'$5\\pi$']) box_2 = axs[2].get_position() axs[2].set_position([box_2.x0 -", "2, & IMF 3 with 51 knots', 21)) for knot", "label=textwrap.fill('Windsorize filter', 12)) axs[0].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize interpolation filter', 14))", "min_dash_2, 'k-') plt.plot(min_dash_time_3, min_dash_3, 'k-') plt.plot(min_dash_time_4, min_dash_4, 'k-') plt.plot(maxima_dash_time_1, maxima_dash,", "== 1: ax.set_ylabel(r'$ \\dfrac{dx(t)}{dt} $') ax.set(xlabel='t') ax.set_yticks(y_points_2) ax.set_xticks(x_points) ax.set_xticklabels(x_names) axis", "2.75, 100), c='gray', linestyle='dashed') plt.xlim(3.4 * np.pi, 5.6 * np.pi)", "Huang_min, c='lime', zorder=4, label=textwrap.fill('Huang minimum', 10)) plt.scatter(Coughlin_max_time, Coughlin_max, c='darkorange', zorder=4,", "edge_effect='none', spline_method='b_spline')[0] maxima_envelope_smooth = fluctuation.envelope_basis_function_approximation(knots, 'maxima', smooth=True, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0]", "5.5) axs[1].set_xlim(0.95 * np.pi, 1.55 * np.pi) axs[2].plot(time, time_series, label='Time", "improved_slope_based_minimum_time * np.ones_like(min_dash_4) dash_final_time = np.linspace(improved_slope_based_maximum_time, improved_slope_based_minimum_time, 101) dash_final =", "bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/DFA_hilbert_spectrum.png') plt.show() # plot 6c time = np.linspace(0,", "guess average gradients average_gradients = np.mean(gradients, axis=1) # steepest descent", "np.pi, 101), 5.5 * np.ones(101), 'k--') axs[1].plot(np.linspace(0.95 * np.pi, 1.55", "np.pi, (5 + a) * np.pi, 101) time_series_reflect = np.flip(np.cos(np.linspace((5", "np.pi - width, 5.4 * np.pi + width, 101) min_1_x", "* np.pi, 1.55 * np.pi) axs[1].plot(time, time_series, label='Time series') axs[1].plot(time,", "150} y_points_1 = [-2, 0, 2] y_points_2 = [-1, 0,", "axs[0].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), 5.5 * np.ones(101),", "if axis == 0: ax.set_ylabel(r'$\\gamma_1(t)$') ax.set_yticks([-2, 0, 2]) if axis", "(minima_y[-2] - maxima_y[-1]) / (minima_x[-2] - maxima_x[-1]) slope_based_maximum_time = maxima_x[-1]", "1e - addition fig, axs = plt.subplots(2, 1) fig.subplots_adjust(hspace=0.4) figure_size", "3 * np.pi, 4 * np.pi, 5 * np.pi), (r'$0$',", "np.ones_like(length_distance_2) length_time_2 = np.linspace(point_2 * np.pi - width, point_2 *", "c='grey', zorder=1, label='Knots') axs[0].set_xticks([0, np.pi, 2 * np.pi, 3 *", "minima_x[-1] + width, 101) min_1_x_time_side = np.linspace(5.4 * np.pi -", "31) # change (1) detrended_fluctuation_technique and (2) max_internal_iter and (3)", "= utils_Huang.min_bool_func_1st_order_fd() utils_Coughlin = emd_utils.Utility(time=time, time_series=Coughlin_wave) Coughlin_max_bool = utils_Coughlin.max_bool_func_1st_order_fd() Coughlin_min_bool", "max_bool = utils.max_bool_func_1st_order_fd() maxima_x = time[max_bool] maxima_y = time_series[max_bool] min_bool", "plt.plot(max_1_x_time, max_1_x, 'k-') plt.plot(max_1_x_time_side, max_1_x, 'k-') plt.plot(min_1_x_time, min_1_x, 'k-') plt.plot(min_1_x_time_side,", "'k-') plt.plot(dash_max_min_1_x_time, dash_max_min_1_x, 'k--') plt.text(5.42 * np.pi, -0.1, r'$2a_1$') plt.plot(max_1_y_time,", "fluctuation.envelope_basis_function_approximation(knots, 'maxima', smooth=False, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] maxima_envelope_smooth = fluctuation.envelope_basis_function_approximation(knots, 'maxima',", "minima', 12)) plt.plot(((time[-302] + time[-301]) / 2) * np.ones(100), np.linspace(-2.75,", "1 and Dynamically Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2, zorder=100) axs[1].set_yticks(ticks=[-2,", "np.pi, 2 * np.pi]) axs[1].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2 and", "axs[1].set_title('IMF 1 and Dynamically Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2, zorder=100)", "* np.pi * np.ones_like(dash_max_min_1_x) max_1_y = np.linspace(maxima_y[-1] - width, maxima_y[-1]", "np.linspace(-5, 5, 101), '--', c='grey', zorder=1) axs[2].plot(knot * np.ones(101), np.linspace(-5,", "fig, axs = plt.subplots(3, 1) plt.suptitle(textwrap.fill('Comparison of Trends Extracted with", "+ width, 101) length_top_2 = time_series[-1] * np.ones_like(length_time_2) length_bottom_2 =", "_ = emd_duffing.empirical_mode_decomposition(verbose=False) fig, axs = plt.subplots(2, 1) plt.subplots_adjust(hspace=0.3) figure_size", "zorder=1, label='Knots') axs[0].set_xticks([0, np.pi, 2 * np.pi, 3 * np.pi,", "= maxima_y[-1] max_discard_time = minima_x[-1] - maxima_x[-1] + minima_x[-1] max_discard_dash_time", "maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.scatter(max_discard_time,", "label=textwrap.fill('Symmetric signal', 10)) plt.plot(time_reflect[:51], time_series_anti_reflect[:51], '--', c='purple', LineWidth=2, label=textwrap.fill('Anti-symmetric signal',", "ax.set_xticks([0, np.pi, 2 * np.pi, 3 * np.pi, 4 *", "py_emd[0, :], '--', label='PyEMD 0.2.10') axs[0].plot(t, emd_sift[:, 0], '--', label='emd", "label=r'$\\omega = 2$', Linewidth=3) ax.set_xticks([0, np.pi, 2 * np.pi, 3", "0, 2]) axs[1].set_xticks(ticks=[np.pi]) axs[1].set_xticklabels(labels=[r'$\\pi$']) box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.06,", "* np.pi, 2 * np.pi, 3 * np.pi, 4 *", "= plt.subplots(2, 2) plt.subplots_adjust(hspace=0.5) axs[0, 0].plot(time, signal) axs[0, 1].plot(time, signal)", "* np.pi * t / 200) util_nn = emd_utils.Utility(time=t, time_series=signal_orig)", "ax.set_yticks(y_points_2) ax.set_xticks(x_points) ax.set_xticklabels(x_names) axis += 1 plt.savefig('jss_figures/Duffing_equation.png') plt.show() # compare", "zorder=4, label=textwrap.fill('Improved slope-based minimum', 11)) plt.xlim(3.9 * np.pi, 5.5 *", "plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time) - 1, '--', c='c', label=r'$\\tilde{h}_{(1,0)}^m(t)$', zorder=5) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time),", "+ width, 101) min_1_x_time_side = np.linspace(5.4 * np.pi - width,", "np.pi, 2 * np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1 and", "'--', label=r'$ B_{1,4}(t) $') plt.xticks([5, 6], [r'$ \\tau_0 $', r'$", "axs[1].plot(preprocess_time, preprocess.winsorize(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize filter', 12)) axs[1].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize", "2) * np.ones(100), np.linspace(-2.75, 2.75, 100), c='k', label=textwrap.fill('Neural network inputs',", "axs[1].set_xlim(0.85 * np.pi, 1.15 * np.pi) axs[1].set_ylim(-3, 3) axs[1].set_yticks(ticks=[-2, 0,", "plt.plot(minima_dash_time_2, minima_dash, 'k-') plt.plot(minima_dash_time_3, minima_dash, 'k-') plt.text(4.34 * np.pi, -3.2,", "q=0.90)[1], c='grey', label=textwrap.fill('Quantile window', 12)) axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.10)[1], c='grey') axs[1].set_xlim(0.85", "plt.plot(pseudo_alg_time, pseudo_alg_time_series, label=r'$h_{(1,0)}(t)$', zorder=1) plt.scatter(pseudo_alg_time[pseudo_utils.max_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.max_bool_func_1st_order_fd()], c='r', label=r'$M(t_i)$', zorder=2) plt.plot(pseudo_alg_time,", "* time) + np.cos(8 * time) noise = np.random.normal(0, 1,", "2$', Linewidth=3) ax.set_xticks([0, np.pi, 2 * np.pi, 3 * np.pi,", "0.2.10') axs[0].plot(t, emd_sift[:, 0], '--', label='emd 0.3.3') axs[0].set_title('IMF 1') axs[0].set_ylim([-2,", "constant t = lsq_signal[:neural_network_m] vx = cvx.Variable(int(neural_network_k + 1)) objective", "chsi_basis[13, :].T, '--') axs[1].plot(5 * np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-')", "emd040.spectra.frequency_transform(emd_sift[:, :1], 12, 'hilbert') print(f'emd annual frequency error: {np.round(sum(np.abs(IF -", "0.05, box_1.y0, box_1.width * 0.85, box_1.height]) plt.savefig('jss_figures/preprocess_filter.png') plt.show() # plot", "'k-') plt.plot(minima_dash_time_3, minima_dash, 'k-') plt.text(4.34 * np.pi, -3.2, r'$\\Delta{t^{min}_{m}}$') plt.text(4.74", "np.ones(100), np.linspace(-2.75, 2.75, 100), c='gray', linestyle='dashed') plt.xlim(3.4 * np.pi, 5.6", "ax.pcolormesh(x_hs, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) ax.set_title(textwrap.fill(r'Gaussian Filtered Hilbert Spectrum", "anti_max_bool = utils.max_bool_func_1st_order_fd() anti_max_point_time = time_reflect[anti_max_bool] anti_max_point = time_series_anti_reflect[anti_max_bool] utils", "= Coughlin_wave[Coughlin_max_bool] Coughlin_min_time = Coughlin_time[Coughlin_min_bool] Coughlin_min = Coughlin_wave[Coughlin_min_bool] max_2_x_time =", "inflection_points_envelope = fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True, smoothing_penalty=0.2, technique='inflection_points')[0] binomial_points_envelope = fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True,", "/ 2), ((time[-202] + time[-201]) / 2) + 0.1, 100),", "+ i_right): int(2 * (len(lsq_signal) - 1) + 1 +", "5, 101), '--', c='grey', zorder=1, label='Knots') axs[1].set_xticks([0, np.pi, 2 *", "plt.yticks((-2, -1, 0, 1, 2), ('-2', '-1', '0', '1', '2'))", "and IMF 3 with 51 knots', 19)) print(f'DFA fluctuation with", "c='grey') axs[0].plot(np.linspace(0.85 * np.pi, 1.15 * np.pi, 101), -3 *", "101) anti_symmetric_signal = time_series[-1] * np.ones_like(anti_symmetric_time) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10)", "6.6) plt.plot(5 * np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') plt.plot(6 *", "= maxima_x[-1] * np.ones_like(maxima_dash) maxima_dash_time_3 = slope_based_maximum_time * np.ones_like(maxima_dash) maxima_line_dash_time", "Huang_max_bool = utils_Huang.max_bool_func_1st_order_fd() Huang_min_bool = utils_Huang.min_bool_func_1st_order_fd() utils_Coughlin = emd_utils.Utility(time=time, time_series=Coughlin_wave)", "1)) and (i_left < len(lsq_signal) - 1): time_series_extended[int(len(lsq_signal) - 2", "5 * np.pi, 1001) lsq_signal = np.cos(time) + np.cos(5 *", "s1 = (minima_y[-2] - maxima_y[-1]) / (minima_x[-2] - maxima_x[-1]) slope_based_maximum_time", "< 1)) and (i_right < len(lsq_signal) - 1): time_series_extended[int(2 *", "'', '', '', '']) box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.05,", "19)) for knot in knots_31: axs[1].plot(knot * np.ones(101), np.linspace(-5, 5,", "> 0: max_count_right += 1 emd_utils_min = \\ emd_utils.Utility(time=time_extended[int(2 *", "Carbon Dioxide - top pyemd = pyemd0215() py_emd = pyemd(signal)", "False] & \\ np.r_[utils.zero_crossing() == 1, False] optimal_minima = np.r_[False,", "100), 2.75 * np.ones(100), c='k') plt.plot(((time_extended[-1001] + time_extended[-1002]) / 2)", "3') axs[0].plot(time, b_spline_basis[5, :].T, '--', label='Basis 4') axs[0].legend(loc='upper left') axs[0].plot(5", "a) * np.pi, 101)) + np.cos(5 * np.linspace((5 - 2.6", "label=textwrap.fill('Median filter', 13)) axs[0].plot(preprocess_time, preprocess.winsorize(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize filter', 12)) axs[0].plot(preprocess_time,", "utils = emd_utils.Utility(time=time[:-1], time_series=imf_1_of_derivative) optimal_maxima = np.r_[False, utils.derivative_forward_diff() < 0,", "axs[0].set_title('Duffing Equation Displacement') axs[0].set_ylim([-2, 2]) axs[0].set_xlim([0, 150]) axs[1].plot(t, dxdt) axs[1].set_title('Duffing", "time_series[min_bool] A2 = np.abs(maxima_y[-2] - minima_y[-2]) / 2 A1 =", "* np.pi, 0.35, r'$s_1$') plt.text(4.43 * np.pi, -0.20, r'$s_2$') plt.text(4.30", "c='b', zorder=4, label='Minima') plt.scatter(slope_based_maximum_time, slope_based_maximum, c='orange', zorder=4, label=textwrap.fill('Slope-based maximum', 11))", "np.linspace(-0.2, 0.8, 100), 'k-') axs[0].set_xticks([5, 6]) axs[0].set_xticklabels([r'$ \\tau_k $', r'$", "zorder=3, label=textwrap.fill('Extrapolated maxima', 12)) plt.scatter(minima_extrapolate_time, minima_extrapolate, c='cyan', zorder=4, label=textwrap.fill('Extrapolated minima',", "= utils.min_bool_func_1st_order_fd() minima_x = time[min_bool] minima_y = time_series[min_bool] inflection_bool =", "IMF 1, IMF 2, & IMF 3 with 51 knots',", "* figure_size[1])) ax.pcolormesh(x, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) plt.plot(t[:-1], 0.124", "of IMF 1, IMF 2, & IMF 3 with 51", "/ # \\/ import random import textwrap import emd_mean import", "* 0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/detrended_fluctuation_analysis.png') plt.show() #", "plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Dynamically Optimised Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2,", "1, IMF 2, & IMF 3 with 51 knots', 21))", "time_series[-1] * np.ones_like(end_time) anti_symmetric_time = np.linspace(time[-1] - 0.5, time[-1] +", "fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Statically Optimised Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series,", "= Utility(time=pseudo_alg_time, time_series=pseudo_alg_time_series) # plot 0 - addition fig =", "ax.set_xticks(x_points) ax.set_xticklabels(x_names) axis += 1 plt.savefig('jss_figures/Duffing_equation_imfs.png') plt.show() hs_ouputs = hilbert_spectrum(t,", "of Sifting Algorithm') plt.plot(pseudo_alg_time, pseudo_alg_time_series, label=r'$h_{(1,0)}(t)$', zorder=1) plt.scatter(pseudo_alg_time[pseudo_utils.max_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.max_bool_func_1st_order_fd()], c='r',", "c='k') plt.plot(((time_extended[-1001] + time_extended[-1002]) / 2) * np.ones(100), np.linspace(-2.75, 2.75,", "imfs, _, _, _, knots, _, _ = emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=2,", "Coughlin_wave[Coughlin_min_bool] max_2_x_time = np.linspace(maxima_x[-2] - width, maxima_x[-2] + width, 101)", "filter', 13)) axs[1].plot(preprocess_time, preprocess.winsorize(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize filter', 12)) axs[1].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window,", "np.ones_like(dash_max_min_1_y_time) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Characteristic Wave Effects Example') plt.plot(time,", "np.linspace(minima_y[-1] - width, minima_y[-1] + width, 101) min_dash_2 = np.linspace(minima_y[-2]", "min_dash_time_2 = minima_x[-2] * np.ones_like(min_dash_1) dash_1_time = np.linspace(maxima_x[-1], minima_x[-1], 101)", "= EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series) imfs, _, _, _, knots, _, _", "np.ones(100), np.linspace(-0.2, 0.8, 100), 'k-') axs[0].set_xticks([5, 6]) axs[0].set_xticklabels([r'$ \\tau_k $',", "descent max_gradient_vector = average_gradients * (np.abs(average_gradients) == max(np.abs(average_gradients))) adjustment =", "= 0, np.abs(z).max() ax.pcolormesh(x_hs, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) ax.plot(x_hs[0,", "+ 0.1, 100), -2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time[-302] + time[-301])", "width, -2.1 + width, 101) max_1_y_time = maxima_x[-1] * np.ones_like(max_1_y)", "'', '', '']) axs[0].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101),", "Average_min = (minima_y[-2] + minima_y[-1]) / 2 utils_Huang = emd_utils.Utility(time=time,", "(minima_x[-2] - maxima_x[-1]) slope_based_maximum_time = maxima_x[-1] + (maxima_x[-1] - maxima_x[-2])", "and Statically Optimised Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2, zorder=100) axs[2].set_yticks(ticks=[-2,", "0] dxdt = solution[:, 1] x_points = [0, 50, 100,", "time_series[max_bool] min_bool = utils.min_bool_func_1st_order_fd() minima_x = time[min_bool] minima_y = time_series[min_bool]", "/ 2 Average_min_time = minima_x[-1] + (minima_x[-1] - minima_x[-2]) Average_min", "time[min_bool] minima_y = time_series[min_bool] inflection_bool = utils.inflection_point() inflection_x = time[inflection_bool]", "utils.derivative_forward_diff() derivative_time = time[:-1] derivative_knots = np.linspace(knots[0], knots[-1], 31) #", "(np.abs(average_gradients) == max(np.abs(average_gradients))) adjustment = - lr * average_gradients #", "= np.linspace(minima_x[-1], max_discard_time, 101) dash_2 = np.linspace(minima_y[-1], max_discard, 101) end_point_time", "14)) plt.scatter(Average_min_time, Average_min, c='cyan', zorder=4, label=textwrap.fill('Average minimum', 14)) plt.scatter(maxima_x, maxima_y,", "\\tau_k $', r'$ \\tau_{k+1} $']) axs[0].set_xlim(4.5, 6.5) axs[1].set_title('Cubic Hermite Spline", "time_series, LineWidth=2, label='Signal') plt.title('Slope-Based Edge Effects Example') plt.plot(max_dash_time_1, max_dash_1, 'k-')", "width, 101) max_discard_dash = max_discard * np.ones_like(max_discard_dash_time) dash_2_time = np.linspace(minima_x[-1],", "+ width, 101) dash_4_time = np.linspace(slope_based_maximum_time, slope_based_minimum_time) dash_4 = np.linspace(slope_based_maximum,", "c='gray') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1000]) / 2), ((time_extended[-1001] + time_extended[-1000]) /", "knots', 21)) for knot in knots_51: axs[0].plot(knot * np.ones(101), np.linspace(-5,", "(5 - a) * np.pi, 1001) time_series = np.cos(time) +", "length_distance = np.linspace(maxima_y[-1], minima_y[-1], 101) length_distance_time = point_1 * np.pi", "/ 2) * np.pi]) axs[2].set_xticklabels([r'$\\pi$', r'$\\frac{3}{2}\\pi$']) box_2 = axs[2].get_position() axs[2].set_position([box_2.x0", "'--', c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2,", "12, 'hilbert') print(f'PyEMD annual frequency error: {np.round(sum(np.abs(IF[:, 0] - np.ones_like(IF[:,", "1) plt.suptitle(textwrap.fill('Comparison of Trends Extracted with Different Knot Sequences', 40))", "* time) knots = np.linspace(0, 5 * np.pi, 51) fluc", "plt.title(textwrap.fill('Plot Demonstrating Unsmoothed Extrema Envelopes if Schoenberg–Whitney Conditions are Not", "smoothing', 12)) axs[0].plot(preprocess_time, preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker smoothing', 13)) downsampled_and_decimated = preprocess.downsample()", "- bottom emd_duffing = AdvEMDpy.EMD(time=t, time_series=x) emd_duff, emd_ht_duff, emd_if_duff, _,", "label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2, 101), '--',", "CO$_2$ Concentration') axs[0, 1].set_title('Smoothed CO$_2$ Concentration') axs[1, 0].set_title('IMF 1') axs[1,", "minima_y, c='b', zorder=4, label='Minima') plt.scatter(max_discard_time, max_discard, c='purple', zorder=4, label=textwrap.fill('Symmetric Discard", "emd040.spectra.hilberthuang(IF, IA, freq_edges) hht = gaussian_filter(hht, sigma=1) fig, ax =", "2.75, 100), c='gray', linestyle='dashed', label=textwrap.fill('Neural network targets', 13)) plt.plot(np.linspace(((time[-202] +", "* np.pi * t) - emd_sift[:, 1])), 3)}') axs[1].plot(t, 0.1", "np.arange(12) time = np.linspace(0, 11, 1101) basis = emd_basis.Basis(time=time, time_series=time)", "500:].T, '--', label=r'$ B_{0,4}(t) $') plt.plot(time[500:], b_spline_basis[6, 500:].T, '--', label=r'$", "plt.scatter(pseudo_alg_time[pseudo_utils.min_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.min_bool_func_1st_order_fd()], c='c', label=r'$m(t_j)$', zorder=3) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time) - 1, '--',", "100) signal_orig = np.cos(2 * np.pi * t / 50)", "imfs[1, :]) axs[1, 1].plot(time, imfs[2, :]) axis = 0 for", "plt.xlim(-0.25 * np.pi, 5.25 * np.pi) box_0 = ax.get_position() ax.set_position([box_0.x0", "emd_duff[2, :])), 3)}') axs[1].plot(t, py_emd[1, :], '--', label='PyEMD 0.2.10') print(f'PyEMD", "width, 101) min_1_x_time_side = np.linspace(5.4 * np.pi - width, 5.4", "5, 101), '--', c='grey', zorder=1, label='Knots') axs[2].set_xticks([0, np.pi, 2 *", "<- P = np.zeros((int(neural_network_k + 1), neural_network_m)) for col in", "plt.plot(time_reflect, time_series_reflect, 'g--', LineWidth=2, label=textwrap.fill('Symmetric signal', 10)) plt.plot(time_reflect[:51], time_series_anti_reflect[:51], '--',", "plt.subplots(1, 2, sharey=True) axs[0].set_title('Cubic B-Spline Bases') axs[0].plot(time, b_spline_basis[2, :].T, '--',", "label=textwrap.fill('Optimal minima', 10)) plt.scatter(inflection_x, inflection_y, c='magenta', zorder=4, label=textwrap.fill('Inflection points', 10))", "0.75, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht_emd.png') plt.show()", "hts_31, ifs_31 = advemdpy.empirical_mode_decomposition(knots=knots_31, max_imfs=2, edge_effect='symmetric_anchor', verbose=False)[:3] knots_11 = np.linspace(0,", "+ time[-301]) / 2) + 0.1, 100), 2.75 * np.ones(100),", "c='darkorange') plt.plot(time, max_smoothed[0], label=textwrap.fill('Smoothed maxima envelope', 10), c='red') plt.plot(time, min_unsmoothed[0],", "figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess Filtering Demonstration') axs[1].set_title('Zoomed Region') preprocess_time = pseudo_alg_time.copy()", "label='Basis 4') axs[0].legend(loc='upper left') axs[0].plot(5 * np.ones(100), np.linspace(-0.2, 0.8, 100),", "box_0.width * 0.85, box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].plot(time,", "np.ones(100), np.linspace(-2.75, 2.75, 100), c='gray', linestyle='dashed', label=textwrap.fill('Neural network targets', 13))", "np.pi, 2, r'$\\Delta{t^{max}_{M}}$') plt.text(4.30 * np.pi, 0.35, r'$s_1$') plt.text(4.43 *", "1):int(col + neural_network_k + 1)] P[-1, col] = 1 #", "c='black', label=textwrap.fill('Zoomed region', 10)) axs[0].plot(np.linspace(0.85 * np.pi, 1.15 * np.pi,", "axs[0].set_xticks([0, np.pi, 2 * np.pi, 3 * np.pi, 4 *", "minima_x[-1]) Huang_time = (P1 / P2) * (time[time >= maxima_x[-2]]", "c='cyan') plt.plot(time, min_smoothed[0], label=textwrap.fill('Smoothed minima envelope', 10), c='blue') for knot", "box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Schoenberg_Whitney_Conditions.png') plt.show() # plot 7", "time = np.linspace(0, 5 * np.pi, 1001) lsq_signal = np.cos(time)", ":] + imfs_51[3, :], label=textwrap.fill('Sum of IMF 2 and IMF", "np.pi, 51) time_series = np.cos(2 * time) + np.cos(4 *", "plt.text(5.34 * np.pi, -0.05, 'L') plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima')", "* np.abs(maxima_x[-2] - minima_x[-2]) P1 = 2 * np.abs(maxima_x[-1] -", "plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) ax.pcolormesh(x_hs, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max)", "# slightly edit signal to make difference between slope-based method", ":]), 'k--', label=textwrap.fill('Annual cycle', 10)) ax.axis([x_hs.min(), x_hs.max(), y.min(), y.max()]) box_0", "0.1, 100), -2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1002]) /", "Bases at Boundary') plt.plot(time[500:], b_spline_basis[2, 500:].T, '--', label=r'$ B_{-3,4}(t) $')", "- addition window = 81 fig, axs = plt.subplots(2, 1)", "if axis == 1: ax.set_ylabel(r'$ \\dfrac{dx(t)}{dt} $') ax.set(xlabel='t') ax.set_yticks(y_points_2) ax.set_xticks(x_points)", "Hilbert Spectrum of Duffing Equation using emd 0.3.3', 40)) plt.pcolormesh(t,", "i_left):int(len(lsq_signal))]) if sum(emd_utils_min.min_bool_func_1st_order_fd()) > 0: min_count_left += 1 lsq_utils =", "plt.plot(max_2_y_time, max_2_y_side, 'k-') plt.plot(min_2_y_time, min_2_y, 'k-') plt.plot(min_2_y_time, min_2_y_side, 'k-') plt.plot(dash_max_min_2_y_time,", "ax.set_ylabel(r'$ \\dfrac{dx(t)}{dt} $') ax.set(xlabel='t') ax.set_yticks(y_points_2) ax.set_xticks(x_points) ax.set_xticklabels(x_names) axis += 1", "label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.scatter(max_discard_time, max_discard, c='purple', zorder=4,", "axs[0].set_title('Time Series and Statically Optimised Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2, zorder=100)", "= np.linspace(maxima_x[-2] - width, maxima_x[-2] + width, 101) max_2_x_time_side =", "c='deeppink', zorder=4, label=textwrap.fill('Improved slope-based maximum', 11)) plt.scatter(improved_slope_based_minimum_time, improved_slope_based_minimum, c='dodgerblue', zorder=4,", "axs[0].plot(0.85 * np.pi * np.ones(101), np.linspace(-3, 3, 101), '--', c='black')", "fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima', smooth=True) util = Utility(time=time, time_series=time_series) maxima = util.max_bool_func_1st_order_fd()", "axs[1].set_position([box_1.x0 - 0.05, box_1.y0, box_1.width * 0.85, box_1.height]) axs[1].legend(loc='center left',", "width, 101) end_signal = time_series[-1] * np.ones_like(end_time) anti_symmetric_time = np.linspace(time[-1]", "* np.ones_like(x_hs[0, :]), '--', label=r'$\\omega = 8$', Linewidth=3) ax.plot(x_hs[0, :],", "network inputs', 13)) plt.plot(np.linspace(((time[-302] + time[-301]) / 2), ((time[-302] +", "box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.06, box_0.y0, box_0.width * 0.85,", "r'$2\\pi$']) axs[1].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[1].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time", "# steepest descent max_gradient_vector = average_gradients * (np.abs(average_gradients) == max(np.abs(average_gradients)))", "z = hs_ouputs z_min, z_max = 0, np.abs(z).max() ax.pcolormesh(x_hs, y,", "a) * np.pi, 1001) knots = np.linspace((0 + a) *", "* (Coughlin_time - Coughlin_time[0])) Average_max_time = maxima_x[-1] + (maxima_x[-1] -", "np.ones(100), c='k') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1002]) / 2), ((time_extended[-1001] + time_extended[-1002])", "- i_left): int(len(lsq_signal) - 1 - i_left + neural_network_k)], 1)))", "* np.ones_like(max_dash_1) min_dash_1 = np.linspace(minima_y[-1] - width, minima_y[-1] + width,", "utils.min_bool_func_1st_order_fd() minima_x = time[min_bool] minima_y = time_series[min_bool] max_dash_1 = np.linspace(maxima_y[-1]", "box_2.width * 0.85, box_2.height]) axs[2].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[2].set_ylim(-5.5,", "= time_series[max_bool] min_bool = utils.min_bool_func_1st_order_fd() minima_x = time[min_bool] minima_y =", "plt.scatter(end_point_time, end_point, c='orange', zorder=4, label=textwrap.fill('Symmetric Anchor maxima', 10)) plt.scatter(anti_max_point_time, anti_max_point,", "0.2.10') print(f'PyEMD driving function error: {np.round(sum(abs(0.1 * np.cos(0.04 * 2", "min_dash_3 = np.linspace(slope_based_minimum - width, slope_based_minimum + width, 101) dash_4_time", "c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots[0] * np.ones(101), np.linspace(-2, 2, 101),", "_, _, knots, _, _ = emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=1, verbose=False) fig,", "while ((max_count_left < 1) or (min_count_left < 1)) and (i_left", "axs[0].plot(time, b_spline_basis[2, :].T, '--', label='Basis 1') axs[0].plot(time, b_spline_basis[3, :].T, '--',", "ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_symmetry_anti.png') plt.show() # plot 4 a", "3)}') fig, axs = plt.subplots(2, 2) plt.subplots_adjust(hspace=0.5) axs[0, 0].plot(time, signal)", "1)], time_series=time_series_extended[int(2 * (len(lsq_signal) - 1) + 1): int(2 *", "(maxima_x[-1] - maxima_x[-2]) Average_max = (maxima_y[-2] + maxima_y[-1]) / 2", "1):int(2 * (len(lsq_signal) - 1) + 1)] = lsq_signal neural_network_m", "np.linspace(-5, 5, 101), '--', c='grey', zorder=1) axs[0].plot(knot * np.ones(101), np.linspace(-5,", "plt.plot(max_2_x_time_side, max_2_x, 'k-') plt.plot(min_2_x_time, min_2_x, 'k-') plt.plot(min_2_x_time_side, min_2_x, 'k-') plt.plot(dash_max_min_2_x_time,", "from emd_mean import Fluctuation from AdvEMDpy import EMD # alternate", "* 0.95, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/pseudo_algorithm.png') plt.show() knots", "pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[1].plot(preprocess_time, preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott", "box_0.width * 0.85, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_symmetry_anti.png') plt.show()", "ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_characteristic_wave.png') plt.show() # plot 6 t", "10)) ax.axis([x_hs.min(), x_hs.max(), y.min(), y.max()]) box_0 = ax.get_position() ax.set_position([box_0.x0 +", "+ i_right)] = \\ sum(weights_right * np.hstack((time_series_extended[ int(2 * (len(lsq_signal)", "neural_network_m)) for col in range(neural_network_m): P[:-1, col] = lsq_signal[(-(neural_network_m +", "bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].plot(time, time_series, label='Time series') axs[1].plot(time, imfs_31[1, :]", "time[-201]) / 2), ((time[-202] + time[-201]) / 2) + 0.1,", "Example') plt.plot(time, lsq_signal, zorder=2, label='Signal') plt.plot(time_extended, time_series_extended, c='g', zorder=1, label=textwrap.fill('Extrapolated", "* np.pi - width, point_1 * np.pi + width, 101)", "101) min_2_x = minima_y[-2] * np.ones_like(min_2_x_time) dash_max_min_2_x = np.linspace(minima_y[-2], maxima_y[-2],", "np.ones_like(length_time) length_bottom = minima_y[-1] * np.ones_like(length_time) point_2 = 5.2 length_distance_2", "2), ((time[-302] + time[-301]) / 2) + 0.1, 100), -2.75", "axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.10)[1], c='grey') axs[1].set_xlim(0.85 * np.pi, 1.15 * np.pi)", "plt.plot(length_time_2, length_top_2, 'k-') plt.plot(length_time_2, length_bottom_2, 'k-') plt.plot(end_time, end_signal, 'k-') plt.plot(symmetry_axis_1_time,", "label=textwrap.fill('Median filter', 13)) axs[1].plot(preprocess_time, preprocess.winsorize(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize filter', 12)) axs[1].plot(preprocess_time,", "label='Maxima') plt.scatter(minima_time, minima, c='b', zorder=3, label='Minima') plt.scatter(maxima_extrapolate_time, maxima_extrapolate, c='magenta', zorder=3,", "+ width, 101) min_1_y_time = minima_x[-1] * np.ones_like(min_1_y) dash_max_min_1_y_time =", "max_imfs=1, edge_effect='symmetric_anchor', verbose=False)[:3] fig, axs = plt.subplots(3, 1) plt.suptitle(textwrap.fill('Comparison of", "in knots_51: axs[0].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey',", "knots') axs[2].plot(time, imfs_51[3, :], label='IMF 3 with 51 knots') print(f'DFA", "min_1_x_time = np.linspace(minima_x[-1] - width, minima_x[-1] + width, 101) min_1_x_time_side", "time_series[-1] time_reflect = np.linspace((5 - a) * np.pi, (5 +", "* np.pi, 4 * np.pi, 5 * np.pi]) axs[1].set_xticklabels(['', '',", "5 * np.pi), (r'$0$', r'$\\pi$', r'2$\\pi$', r'3$\\pi$', r'4$\\pi$', r'5$\\pi$')) plt.yticks((-2,", "np.linspace(0, 5 * np.pi, 11) imfs_11, hts_11, ifs_11 = advemdpy.empirical_mode_decomposition(knots=knots_11,", "((time[-302] + time[-301]) / 2) + 0.1, 100), -2.75 *", "max_1_y_side, 'k-') plt.plot(min_1_y_time, min_1_y, 'k-') plt.plot(min_1_y_time, min_1_y_side, 'k-') plt.plot(dash_max_min_1_y_time, dash_max_min_1_y,", "101), '--', c='grey', label='Knots') axs[2].plot(knots[2][0] * np.ones(101), np.linspace(-2, 2, 101),", "np.sin(pseudo_alg_time) + np.sin(5 * pseudo_alg_time) pseudo_utils = Utility(time=pseudo_alg_time, time_series=pseudo_alg_time_series) #", "time series', 12)) axs[1].plot(preprocess_time, preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott smoothing', 12)) axs[1].plot(preprocess_time, preprocess.hw(order=51)[1],", "- width, 5.4 * np.pi + width, 101) min_1_x =", "ax.set_position([box_0.x0, box_0.y0, box_0.width * 0.85, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5),", "P[-1, col] = 1 # for additive constant t =", "hs_ouputs = hilbert_spectrum(time, imfs, hts, ifs, max_frequency=10, which_imfs=[1], plot=False) x_hs,", "spline_method='b_spline')[0] maxima_envelope_smooth = fluctuation.envelope_basis_function_approximation(knots, 'maxima', smooth=True, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] minima_envelope", "- width, minima_y[-2] + width, 101) min_dash_time_1 = minima_x[-1] *", "0.5), fontsize=8) axs[1].set_ylim(-5.5, 5.5) axs[1].set_xlim(0.95 * np.pi, 1.55 * np.pi)", "= EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series) imfs = emd.empirical_mode_decomposition(knots=knots_uniform, edge_effect='anti-symmetric', verbose=False)[0] fig, axs", "(vx * P) + 1 - t), 2)) # linear", "time[min_bool] minima_y = time_series[min_bool] max_dash_1 = np.linspace(maxima_y[-1] - width, maxima_y[-1]", "$') plt.plot(time[500:], b_spline_basis[3, 500:].T, '--', label=r'$ B_{-2,4}(t) $') plt.plot(time[500:], b_spline_basis[4,", "P1) * (Coughlin_time - Coughlin_time[0])) Average_max_time = maxima_x[-1] + (maxima_x[-1]", "101) end_signal = time_series[-1] * np.ones_like(end_time) anti_symmetric_time = np.linspace(time[-1] -", "* np.pi) axs[1].set_ylim(-3, 3) axs[1].set_yticks(ticks=[-2, 0, 2]) axs[1].set_xticks(ticks=[np.pi]) axs[1].set_xticklabels(labels=[r'$\\pi$']) box_0", "-3 * np.ones(101), '--', c='black', label=textwrap.fill('Zoomed region', 10)) axs[0].plot(np.linspace(0.85 *", "plt.plot(((time_extended[-1001] + time_extended[-1000]) / 2) * np.ones(100), np.linspace(-2.75, 2.75, 100),", "verbose=False)[:3] knots_11 = np.linspace(0, 5 * np.pi, 11) imfs_11, hts_11,", "/ 2) - 0.1, 100), 2.75 * np.ones(100), c='k') plt.plot(((time_extended[-1001]", "100, 150] x_names = {0, 50, 100, 150} y_points_1 =", "50, 100, 150} y_points_1 = [-2, 0, 2] y_points_2 =", "symmetry_axis, 'r--', zorder=1) plt.plot(anti_symmetric_time, anti_symmetric_signal, 'r--', zorder=1) plt.plot(symmetry_axis_2_time, symmetry_axis, 'r--',", "length_distance_time = point_1 * np.pi * np.ones_like(length_distance) length_time = np.linspace(point_1", "100) hht = emd040.spectra.hilberthuang(IF, IA, freq_edges) hht = gaussian_filter(hht, sigma=1)", "seaborn as sns import matplotlib.pyplot as plt from scipy.integrate import", "101) length_distance_time_2 = point_2 * np.pi * np.ones_like(length_distance_2) length_time_2 =", "101), '--', c='grey', zorder=1, label='Knots') axs[0].set_xticks([0, np.pi, 2 * np.pi,", "left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht_pyemd.png') plt.show() plt.show() emd_sift = emd040.sift.sift(x) IP,", "np.ones_like(minima_dash) minima_line_dash_time = np.linspace(minima_x[-2], slope_based_minimum_time, 101) minima_line_dash = -3.4 *", "* a) * np.pi, (5 - a) * np.pi, 101))", "'--') axs[1].plot(time, chsi_basis[12, :].T, '--') axs[1].plot(time, chsi_basis[13, :].T, '--') axs[1].plot(5", "ax = plt.subplot(111) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Duffing Equation", "10)) plt.plot(time_reflect[:51], time_series_anti_reflect[:51], '--', c='purple', LineWidth=2, label=textwrap.fill('Anti-symmetric signal', 10)) plt.plot(max_dash_time,", ":] + imfs_31[2, :])), 3)}') for knot in knots_31: axs[1].plot(knot", "= time[max_bool] maxima_y = time_series[max_bool] min_bool = utils.min_bool_func_1st_order_fd() minima_x =", "knots: {np.round(np.var(time_series - (imfs_51[1, :] + imfs_51[2, :] + imfs_51[3,", "* np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots[0] * np.ones(101), np.linspace(-2, 2,", "np.linspace(-5.5, 5.5, 101), 'k--') axs[0].plot(1.55 * np.pi * np.ones(101), np.linspace(-5.5,", "vmin=z_min, vmax=z_max) ax.set_title(textwrap.fill(r'Gaussian Filtered Hilbert Spectrum of CO$_{2}$ Concentration using", "anti_symmetric_signal = time_series[-1] * np.ones_like(anti_symmetric_time) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time,", "= emd_utils.Utility(time=time, time_series=lsq_signal) utils_extended = emd_utils.Utility(time=time_extended, time_series=time_series_extended) maxima = lsq_signal[lsq_utils.max_bool_func_1st_order_fd()]", "plt.savefig('jss_figures/neural_network.png') plt.show() # plot 6a np.random.seed(0) time = np.linspace(0, 5", "51 knots', 21)) print(f'DFA fluctuation with 51 knots: {np.round(np.var(time_series -", "= np.linspace(maxima_y[-1], minima_y[-1], 101) dash_2_time = np.linspace(maxima_x[-1], minima_x[-2], 101) dash_2", "utils = emd_utils.Utility(time=time, time_series=time_series) max_bool = utils.max_bool_func_1st_order_fd() maxima_x = time[max_bool]", "+ 0.1, 100), -2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time[-202] + time[-201])", "c='c', label=r'$m(t_j)$', zorder=3) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time) - 1, '--', c='c', label=r'$\\tilde{h}_{(1,0)}^m(t)$',", "zorder=1) axs[0].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1,", "pd.read_csv('Data/co2_mm_mlo.csv', header=51) plt.plot(CO2_data['month'], CO2_data['decimal date']) plt.title(textwrap.fill('Mean Monthly Concentration of Carbon", "plt.text(5.16 * np.pi, 0.85, r'$2a_2$') plt.plot(max_2_y_time, max_2_y, 'k-') plt.plot(max_2_y_time, max_2_y_side,", "np.ones_like(minima_dash) minima_dash_time_2 = minima_x[-1] * np.ones_like(minima_dash) minima_dash_time_3 = slope_based_minimum_time *", "utils_extended = emd_utils.Utility(time=time_extended, time_series=time_series_extended) maxima = lsq_signal[lsq_utils.max_bool_func_1st_order_fd()] maxima_time = time[lsq_utils.max_bool_func_1st_order_fd()]", "label=textwrap.fill('Hodrick-Prescott smoothing', 12)) axs[0].plot(preprocess_time, preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker smoothing', 13)) downsampled_and_decimated =", "width, 5.3 * np.pi + width, 101) max_2_x = maxima_y[-2]", "(t - output) gradients = error * (- train_input) #", "axs[1].plot(time, chsi_basis[13, :].T, '--') axs[1].plot(5 * np.ones(100), np.linspace(-0.2, 1.2, 100),", "vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(t[:-1], 0.124 * np.ones_like(t[:-1]), '--', label=textwrap.fill('Hamiltonian frequency approximation',", "= 0 * seed_weights.copy() train_input = P[:-1, :] lr =", "0.1, 100), -2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1000]) /", "of Duffing Equation using emd 0.3.3', 40)) plt.pcolormesh(t, freq_bins, hht,", "neural_network_k)], 1))) + 1 i_left += 1 if i_left >", "14)) plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4,", "min_2_y = np.linspace(minima_y[-2] - width, minima_y[-2] + width, 101) min_2_y_side", "advemdpy.empirical_mode_decomposition(knots=knots_31, max_imfs=2, edge_effect='symmetric_anchor', verbose=False)[:3] knots_11 = np.linspace(0, 5 * np.pi,", "sum(weights_left * np.hstack((time_series_extended[int(len(lsq_signal) - 1 - i_left): int(len(lsq_signal) - 1", "plt.gcf().subplots_adjust(bottom=0.10) plt.title('Characteristic Wave Effects Example') plt.plot(time, time_series, LineWidth=2, label='Signal') plt.scatter(Huang_max_time,", "ax.pcolormesh(x_hs, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) ax.plot(x_hs[0, :], 8 *", "Region') preprocess_time = pseudo_alg_time.copy() np.random.seed(1) random.seed(1) preprocess_time_series = pseudo_alg_time_series +", "width, point_2 * np.pi + width, 101) length_top_2 = time_series[-1]", "axs = plt.subplots(2, 1) plt.subplots_adjust(hspace=0.3) figure_size = plt.gcf().get_size_inches() factor =", "LineWidth=2) plt.scatter(time[maxima], time_series[maxima], c='r', label='Maxima', zorder=10) plt.scatter(time[minima], time_series[minima], c='b', label='Minima',", "'--', label='emd 0.3.3') axs[0].set_title('IMF 1') axs[0].set_ylim([-2, 2]) axs[0].set_xlim([0, 150]) axs[1].plot(t,", "minima_extrapolate_time = time_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Single Neuron Neural", "Filtered Hilbert Spectrum of CO$_{2}$ Concentration using AdvEMDpy', 40)) plt.ylabel('Frequency", "from emd_hilbert import Hilbert, hilbert_spectrum from emd_preprocess import Preprocess from", "* t / 200) util_nn = emd_utils.Utility(time=t, time_series=signal_orig) maxima =", "smooth=True, smoothing_penalty=0.2, technique='binomial_average', order=21, increment=20)[0] derivative_of_lsq = utils.derivative_forward_diff() derivative_time =", "+ np.sin(5 * knot_demonstrate_time) emd = EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series) imfs, _,", "axs[1].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2 and Statically Optimised Knots') axs[2].plot(knot_demonstrate_time,", "label=textwrap.fill('Binomial average envelope', 10)) plt.plot(time, np.cos(time), c='black', label='True mean') plt.xticks((0,", "(1 / P1) * (Coughlin_time - Coughlin_time[0])) Average_max_time = maxima_x[-1]", "signal', 10)) plt.plot(max_dash_time, max_dash, 'k-') plt.plot(min_dash_time, min_dash, 'k-') plt.plot(dash_1_time, dash_1,", "* 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert_pyemd.png') plt.show() emd_sift =", "0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht.png') plt.show() # Carbon Dioxide", "= advemdpy.empirical_mode_decomposition(knots=knots_51, max_imfs=3, edge_effect='symmetric_anchor', verbose=False)[:3] knots_31 = np.linspace(0, 5 *", "i_left): int(len(lsq_signal) - 1 - i_left + neural_network_k)], 1))) +", "plt.plot(min_dash_time_1, min_dash_1, 'k-') plt.plot(min_dash_time_2, min_dash_2, 'k-') plt.plot(min_dash_time_3, min_dash_3, 'k-') plt.plot(min_dash_time_4,", "plt.xticks((4 * np.pi, 5 * np.pi), (r'4$\\pi$', r'5$\\pi$')) plt.yticks((-3, -2,", "min_count_right = 0 i_right = 0 while ((max_count_right < 1)", "xy[0] ** 3 + gamma * np.cos(omega * ts)] t", "'k-') plt.plot(max_dash_time_3, max_dash_3, 'k-') plt.plot(min_dash_time_1, min_dash_1, 'k-') plt.plot(min_dash_time_2, min_dash_2, 'k-')", "* figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess Smoothing Demonstration') axs[1].set_title('Zoomed Region') axs[0].plot(preprocess_time, preprocess_time_series,", "np.ones_like(min_dash_1) min_dash_3 = np.linspace(slope_based_minimum - width, slope_based_minimum + width, 101)", "- width, maxima_y[-2] + width, 101) max_2_y_side = np.linspace(-1.8 -", "2: ax.set(ylabel=R'C0$_2$ concentration') ax.set(xlabel='Time (years)') if axis == 3: ax.set(xlabel='Time", "axs[1].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean filter', 12)) axs[1].plot(preprocess_time, preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median filter', 13))", "'0', '1', '2')) box_0 = ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0,", "'maxima', smooth=True, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] minima_envelope = fluctuation.envelope_basis_function_approximation(knots, 'minima', smooth=False,", "plt.plot(max_1_x_time_side, max_1_x, 'k-') plt.plot(min_1_x_time, min_1_x, 'k-') plt.plot(min_1_x_time_side, min_1_x, 'k-') plt.plot(dash_max_min_1_x_time,", "* np.pi, -0.7, r'$\\beta$L') plt.text(5.34 * np.pi, -0.05, 'L') plt.scatter(maxima_x,", "+ (maxima_x[-1] - maxima_x[-2]) slope_based_maximum = minima_y[-1] + (slope_based_maximum_time -", "np.cos(2 * np.pi * (1 / P1) * (Coughlin_time -", "= np.linspace(maxima_x[-1] - width, maxima_x[-1] + width, 101) max_1_x_time_side =", "import AdvEMDpy import emd_basis import emd_utils import numpy as np", "Example') plt.plot(time, time_series, LineWidth=2, label='Signal') plt.scatter(Huang_max_time, Huang_max, c='magenta', zorder=4, label=textwrap.fill('Huang", "axs[0].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[0].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1],", "box_0.width * 0.95, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/pseudo_algorithm.png') plt.show()", "2) plt.subplots_adjust(hspace=0.5) axs[0, 0].plot(time, signal) axs[0, 1].plot(time, signal) axs[0, 1].plot(time,", "'k-') axs[1].plot(6 * np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') axs[1].set_xticks([5, 6])", "plt.plot(max_dash_time_3, max_dash_3, 'k-') plt.plot(min_dash_time_1, min_dash_1, 'k-') plt.plot(min_dash_time_2, min_dash_2, 'k-') plt.plot(min_dash_time_3,", "- minima_y[-1]) / 2 P2 = 2 * np.abs(maxima_x[-2] -", "# \\ / # \\ / # \\/ import random", "detrended_fluctuation_technique and (2) max_internal_iter and (3) debug (confusing with external", "minima_y[-1] * np.ones_like(length_time_2) symmetry_axis_1_time = minima_x[-1] * np.ones(101) symmetry_axis_2_time =", "IMF 2, & IMF 3 with 51 knots', 21)) print(f'DFA", "plt.savefig('jss_figures/CO2_concentration.png') plt.show() signal = CO2_data['decimal date'] signal = np.asarray(signal) time", "axs[1].set_ylim(-3, 3) axs[1].set_yticks(ticks=[-2, 0, 2]) axs[1].set_xticks(ticks=[np.pi]) axs[1].set_xticklabels(labels=[r'$\\pi$']) box_0 = axs[0].get_position()", "Statically Optimised Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2, zorder=100) axs[2].set_yticks(ticks=[-2, 0,", "'k--', label=textwrap.fill('Annual cycle', 10)) ax.axis([x_hs.min(), x_hs.max(), y.min(), y.max()]) box_0 =", "0.05, box_0.y0, box_0.width * 0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))", "axs[1].set_title('IMF 1 and Uniform Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2, zorder=100)", "plt.plot(dash_1_time, dash_1, 'k--') plt.plot(dash_2_time, dash_2, 'k--') plt.plot(length_distance_time, length_distance, 'k--') plt.plot(length_distance_time_2,", "= fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima', smooth=True) min_unsmoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima', smooth=False) min_smoothed", "Spectrum of Simple Sinusoidal Time Seres with Added Noise', 50))", "with Added Noise', 50)) x_hs, y, z = hs_ouputs z_min,", "left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[2].set_ylim(-5.5, 5.5) axs[2].set_xlim(0.95 * np.pi, 1.55", "fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'maxima', optimal_maxima, optimal_minima, smooth=False, smoothing_penalty=0.2, edge_effect='none')[0] EEMD_minima_envelope = fluctuation.envelope_basis_function_approximation_fixed_points(knots,", "-2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time[-302] + time[-301]) / 2), ((time[-302]", "= plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('First Iteration of Sifting Algorithm') plt.plot(pseudo_alg_time, pseudo_alg_time_series,", "= time[min_bool] minima_y = time_series[min_bool] max_dash_time = np.linspace(maxima_x[-1] - width,", "time[-301]) / 2) + 0.1, 100), 2.75 * np.ones(100), c='k')", "np.pi, -0.05, 'L') plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y,", "length_time = np.linspace(point_1 * np.pi - width, point_1 * np.pi", "= time_extended[utils_extended.max_bool_func_1st_order_fd()][-1] minima = lsq_signal[lsq_utils.min_bool_func_1st_order_fd()] minima_time = time[lsq_utils.min_bool_func_1st_order_fd()] minima_extrapolate =", "101) dash_max_min_2_x_time = 5.3 * np.pi * np.ones_like(dash_max_min_2_x) max_2_y =", "Seres with Added Noise', 50)) x_hs, y, z = hs_ouputs", "10, 'hilbert') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 0.2, 100) hht =", "Knot Sequences Zoomed Region', 40)) plt.subplots_adjust(hspace=0.1) axs[0].plot(time, time_series, label='Time series')", "minima_x[-1] + (minima_x[-1] - minima_x[-2]) Average_min = (minima_y[-2] + minima_y[-1])", "plt.plot(min_1_y_time, min_1_y_side, 'k-') plt.plot(dash_max_min_1_y_time, dash_max_min_1_y, 'k--') plt.text(4.48 * np.pi, -2.5,", "+ np.sin(5 * knot_demonstrate_time) knots_uniform = np.linspace(0, 2 * np.pi,", "test - bottom weights_right = np.hstack((weights, 0)) max_count_right = 0", "max_frequency=12, plot=False) # plot 6c ax = plt.subplot(111) figure_size =", "* np.pi * np.ones(101), np.linspace(-3, 3, 101), '--', c='black') axs[0].plot(1.15", "axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2, zorder=100) axs[0].set_yticks(ticks=[-2, 0, 2]) axs[0].set_xticks(ticks=[0, np.pi, 2", "Spectrum of Duffing Equation using PyEMD 0.2.10', 40)) plt.pcolormesh(t, freq_bins,", "smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] minima_envelope_smooth = fluctuation.envelope_basis_function_approximation(knots, 'minima', smooth=True, smoothing_penalty=0.2, edge_effect='none',", "print(f'emd driving function error: {np.round(sum(abs(0.1 * np.cos(0.04 * 2 *", "2), ((time[-202] + time[-201]) / 2) + 0.1, 100), 2.75", "minima = signal_orig[util_nn.min_bool_func_1st_order_fd()] cs_max = CubicSpline(t[util_nn.max_bool_func_1st_order_fd()], maxima) cs_min = CubicSpline(t[util_nn.min_bool_func_1st_order_fd()],", "101) max_2_y_side = np.linspace(-1.8 - width, -1.8 + width, 101)", "0.5)) plt.savefig('jss_figures/Duffing_equation_ht_pyemd.png') plt.show() plt.show() emd_sift = emd040.sift.sift(x) IP, IF, IA", "Huang_time Coughlin_wave = A1 * np.cos(2 * np.pi * (1", "plt.savefig('jss_figures/pseudo_algorithm.png') plt.show() knots = np.arange(12) time = np.linspace(0, 11, 1101)", "= lsq_signal[lsq_utils.min_bool_func_1st_order_fd()] minima_time = time[lsq_utils.min_bool_func_1st_order_fd()] minima_extrapolate = time_series_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] minima_extrapolate_time =", "101) dash_1 = np.linspace(maxima_y[-1], minima_y[-1], 101) dash_2_time = np.linspace(maxima_x[-1], minima_x[-2],", "bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101),", "if sum(emd_utils_max.max_bool_func_1st_order_fd()) > 0: max_count_right += 1 emd_utils_min = \\", "plt.scatter(Average_max_time, Average_max, c='orangered', zorder=4, label=textwrap.fill('Average maximum', 14)) plt.scatter(Average_min_time, Average_min, c='cyan',", "label=textwrap.fill('Symmetric maxima', 10)) plt.xlim(3.9 * np.pi, 5.5 * np.pi) plt.xticks((4", "and Statically Optimised Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2, zorder=100) axs[0].set_yticks(ticks=[-2, 0,", "improved_slope_based_minimum, 101) ax = plt.subplot(111) figure_size = plt.gcf().get_size_inches() factor =", "emd040.sift.sift(signal) IP, IF, IA = emd040.spectra.frequency_transform(emd_sift[:, :1], 12, 'hilbert') print(f'emd", "AdvEMDpy.EMD(time=time, time_series=signal) imfs, hts, ifs, _, _, _, _ =", "emd_utils.Utility(time=time[:-1], time_series=imf_1_of_derivative) optimal_maxima = np.r_[False, utils.derivative_forward_diff() < 0, False] &", "100), 'k-') axs[1].set_xticks([5, 6]) axs[1].set_xticklabels([r'$ \\tau_k $', r'$ \\tau_{k+1} $'])", "hts_51, ifs_51, max_frequency=12, plot=False) # plot 6c ax = plt.subplot(111)", "box_0.y0, box_0.width * 0.85, box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8)", "Edge Effects Example') plt.plot(max_dash_time_1, max_dash_1, 'k-') plt.plot(max_dash_time_2, max_dash_2, 'k-') plt.plot(max_dash_time_3,", "emd_mean.Fluctuation(time=time, time_series=time_series) maxima_envelope = fluctuation.envelope_basis_function_approximation(knots, 'maxima', smooth=False, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0]", "zorder=5) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time), '--', c='purple', label=r'$\\tilde{h}_{(1,0)}^{\\mu}(t)$', zorder=5) plt.yticks(ticks=[-2, -1, 0,", "np.pi) z_min, z_max = 0, np.abs(z).max() figure_size = plt.gcf().get_size_inches() factor", "150]) axs[1].plot(t, emd_duff[2, :], label='AdvEMDpy') print(f'AdvEMDpy driving function error: {np.round(sum(abs(0.1", "r'$s_2$') plt.text(4.50 * np.pi + (slope_based_minimum_time - minima_x[-1]), 1.20 +", "axs[1].set_ylim([-1.5, 1.5]) axs[1].set_xlim([0, 150]) axis = 0 for ax in", "'', '', '', '', '']) box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 -", "plot 2 fig, axs = plt.subplots(1, 2, sharey=True) axs[0].set_title('Cubic B-Spline", "10), c='blue') for knot in knots[:-1]: plt.plot(knot * np.ones(101), np.linspace(-3.0,", "np.pi, 4 * np.pi, 5 * np.pi]) axs[2].set_xticklabels(['$0$', r'$\\pi$', r'$2\\pi$',", "label='Basis 3') axs[0].plot(time, b_spline_basis[5, :].T, '--', label='Basis 4') axs[0].legend(loc='upper left')", "np.pi, 1.55 * np.pi) axs[2].plot(time, time_series, label='Time series') axs[2].plot(time, imfs_11[1,", "= P[:-1, :] lr = 0.01 for iterations in range(1000):", "np.ones(101), 'k--') axs[2].plot(0.95 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101),", ":])), 3)}') axs[1].plot(t, emd_sift[:, 1], '--', label='emd 0.3.3') print(f'emd driving", "np.pi) / 25) return [xy[1], xy[0] - epsilon * xy[0]", "np.linspace(-3.0, -2.0, 101), '--', c='grey', zorder=1) plt.plot(knots[-1] * np.ones(101), np.linspace(-3.0,", "np.pi, 2 * np.pi], labels=[r'0', r'$\\pi$', r'$2\\pi$']) box_0 = ax.get_position()", "= 2.5 * np.ones_like(maxima_line_dash_time) minima_dash = np.linspace(-3.4 - width, -3.4", "plt.title('Slope-Based Edge Effects Example') plt.plot(max_dash_time_1, max_dash_1, 'k-') plt.plot(max_dash_time_2, max_dash_2, 'k-')", "np.pi, 1.55 * np.pi, 101), -5.5 * np.ones(101), 'k--') axs[2].plot(0.95", "Utility(time=time, time_series=time_series) maxima = util.max_bool_func_1st_order_fd() minima = util.min_bool_func_1st_order_fd() ax =", "method and improved slope-based method more clear time_series[time >= minima_x[-1]]", "q=0.10)[1], c='grey') axs[1].set_xlim(0.85 * np.pi, 1.15 * np.pi) axs[1].set_ylim(-3, 3)", "- maxima_y[-1]) / (minima_x[-1] - maxima_x[-1]) slope_based_minimum_time = minima_x[-1] +", "0 for ax in axs.flat: ax.label_outer() if axis == 0:", "time_series=time) b_spline_basis = basis.cubic_b_spline(knots) chsi_basis = basis.chsi_basis(knots) # plot 1", "minima_time = time[lsq_utils.min_bool_func_1st_order_fd()] minima_extrapolate = time_series_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] minima_extrapolate_time = time_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] ax", "# guess average gradients average_gradients = np.mean(gradients, axis=1) # steepest", "* np.pi * t) - py_emd[1, :])), 3)}') axs[1].plot(t, emd_sift[:,", "downsampled = preprocess.downsample(decimate=False) axs[0].plot(downsampled[0], downsampled[1], label=textwrap.fill('Downsampled', 13)) axs[0].plot(np.linspace(0.85 * np.pi,", "* np.ones(100), np.linspace(-2.75, 2.75, 100), c='k', label=textwrap.fill('Neural network inputs', 13))", "axs[2].plot(0.95 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--') axs[2].plot(1.55", "'k--') plt.plot(dash_4_time, dash_4, 'k--') plt.plot(dash_final_time, dash_final, 'k--') plt.scatter(maxima_x, maxima_y, c='r',", "101) dash_final = np.linspace(improved_slope_based_maximum, improved_slope_based_minimum, 101) ax = plt.subplot(111) figure_size", "= np.linspace(maxima_x[-1], minima_x[-2], 101) dash_2 = np.linspace(maxima_y[-1], minima_y[-2], 101) s1", "import Fluctuation from AdvEMDpy import EMD # alternate packages from", "label='Minima') plt.scatter(time[optimal_maxima], time_series[optimal_maxima], c='darkred', zorder=4, label=textwrap.fill('Optimal maxima', 10)) plt.scatter(time[optimal_minima], time_series[optimal_minima],", "annual frequency error: {np.round(sum(np.abs(IF[:, 0] - np.ones_like(IF[:, 0]))), 3)}') freq_edges,", "sum(weights_right * np.hstack((time_series_extended[ int(2 * (len(lsq_signal) - 1) + 1", "+ 1 + i_right + 1)]) if sum(emd_utils_min.min_bool_func_1st_order_fd()) > 0:", "* np.cos(0.04 * 2 * np.pi * t) - emd_duff[2,", "- i_left):int(len(lsq_signal))]) if sum(emd_utils_min.min_bool_func_1st_order_fd()) > 0: min_count_left += 1 lsq_utils", "3 with 51 knots') print(f'DFA fluctuation with 11 knots: {np.round(np.var(time_series", "print(f'AdvEMDpy annual frequency error: {np.round(sum(np.abs(ifs[1, :] / (2 * np.pi)", "zorder=4, label='Minima') plt.scatter(slope_based_maximum_time, slope_based_maximum, c='orange', zorder=4, label=textwrap.fill('Slope-based maximum', 11)) plt.scatter(slope_based_minimum_time,", "r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1 and Uniform Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :],", "- minima_x[-1]), 1.20 + (slope_based_minimum - minima_y[-1]), r'$s_2$') plt.plot(minima_line_dash_time, minima_line_dash,", "min_count_left = 0 i_left = 0 while ((max_count_left < 1)", "box_0.width * 0.85, box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, -0.15)) box_1 =", "* np.ones_like(max_1_y) min_1_y = np.linspace(minima_y[-1] - width, minima_y[-1] + width,", "(len(lsq_signal) - 1) + 1 + i_right + 1)], time_series=time_series_extended[int(2", "constant t = lsq_signal[-neural_network_m:] # test - top seed_weights =", "(slope_based_maximum_time - minima_x[-1]) * s1 max_dash_time_3 = slope_based_maximum_time * np.ones_like(max_dash_1)", "2.75, 100), c='k', label=textwrap.fill('Neural network inputs', 13)) plt.plot(np.linspace(((time[-302] + time[-301])", "time series', 12)) axs[0].plot(preprocess_time, preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott smoothing', 12)) axs[0].plot(preprocess_time, preprocess.hw(order=51)[1],", "'k--') axs[2].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), -5.5 *", "0.5)) plt.savefig('jss_figures/edge_effects_slope_based.png') plt.show() # plot 5 a = 0.25 width", "plt.text(5.1 * np.pi, -0.7, r'$\\beta$L') plt.text(5.34 * np.pi, -0.05, 'L')", "4 * np.pi]) ax.set_xticklabels(['$0$', r'$\\pi$', r'$2\\pi$', r'$3\\pi$', r'$4\\pi$']) plt.ylabel(r'Frequency (rad.s$^{-1}$)')", "width, maxima_x[-1] + width, 101) max_dash = maxima_y[-1] * np.ones_like(max_dash_time)", "* np.pi, 101), -5.5 * np.ones(101), 'k--') axs[1].plot(0.95 * np.pi", "1001) lsq_signal = np.cos(time) + np.cos(5 * time) knots =", "max_discard, 101) end_point_time = time[-1] end_point = time_series[-1] time_reflect =", "zorder=2, LineWidth=2) plt.scatter(time[maxima], time_series[maxima], c='r', label='Maxima', zorder=10) plt.scatter(time[minima], time_series[minima], c='b',", "for knot in knots_11: axs[2].plot(knot * np.ones(101), np.linspace(-5, 5, 101),", "with 51 knots: {np.round(np.var(time_series - (imfs_51[1, :] + imfs_51[2, :]", "'k--') plt.plot(dash_2_time, dash_2, 'k--') plt.plot(dash_3_time, dash_3, 'k--') plt.plot(dash_4_time, dash_4, 'k--')", "plt.scatter(pseudo_alg_time[pseudo_utils.max_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.max_bool_func_1st_order_fd()], c='r', label=r'$M(t_i)$', zorder=2) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time) + 1, '--',", "axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[1].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple',", "knots: {np.round(np.var(time_series - imfs_51[3, :]), 3)}') for knot in knots_11:", "= (A1 / A2) * (time_series[time >= maxima_x[-2]] - time_series[time", "maxima_x[-1] + width, 101) max_1_x_time_side = np.linspace(5.4 * np.pi -", "plt.plot(time, minima_envelope, c='darkblue') plt.plot(time, (maxima_envelope + minima_envelope) / 2, c='darkblue')", "= [0, 50, 100, 150] x_names = {0, 50, 100,", "utils_Huang = emd_utils.Utility(time=time, time_series=Huang_wave) Huang_max_bool = utils_Huang.max_bool_func_1st_order_fd() Huang_min_bool = utils_Huang.min_bool_func_1st_order_fd()", "1.5]) axs[1].set_xlim([0, 150]) axis = 0 for ax in axs.flat:", "plt.plot(Coughlin_time, Coughlin_wave, '--', c='darkgreen', label=textwrap.fill('Coughlin Characteristic Wave', 14)) plt.plot(max_2_x_time, max_2_x,", "width, 101) min_1_y_time = minima_x[-1] * np.ones_like(min_1_y) dash_max_min_1_y_time = np.linspace(minima_x[-1],", "'']) box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.05, box_0.y0, box_0.width *", "label='Minima', zorder=10) plt.plot(time, max_unsmoothed[0], label=textwrap.fill('Unsmoothed maxima envelope', 10), c='darkorange') plt.plot(time,", "np.linspace(slope_based_maximum - width, slope_based_maximum + width, 101) dash_3_time = np.linspace(minima_x[-1],", "Linewidth=2, zorder=100) axs[1].set_yticks(ticks=[-2, 0, 2]) axs[1].set_xticks(ticks=[0, np.pi, 2 * np.pi])", "max_unsmoothed[0], label=textwrap.fill('Unsmoothed maxima envelope', 10), c='darkorange') plt.plot(time, max_smoothed[0], label=textwrap.fill('Smoothed maxima", "> 1: emd_utils_max = \\ emd_utils.Utility(time=time_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))],", "101), '--', c='grey', zorder=1) axs[2].plot(knot * np.ones(101), np.linspace(-5, 5, 101),", "* np.ones_like(length_time) length_bottom = minima_y[-1] * np.ones_like(length_time) point_2 = 5.2", "40)) x, y, z = hs_ouputs y = y /", "axs[0].set_title('Cubic B-Spline Bases') axs[0].plot(time, b_spline_basis[2, :].T, '--', label='Basis 1') axs[0].plot(time,", "= np.linspace(time[-1] - width, time[-1] + width, 101) end_signal =", "axs[0].plot(preprocess_time, preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker smoothing', 13)) downsampled_and_decimated = preprocess.downsample() axs[0].plot(downsampled_and_decimated[0], downsampled_and_decimated[1],", "emd_mean import AdvEMDpy import emd_basis import emd_utils import numpy as", "zorder=1) plt.scatter(pseudo_alg_time[pseudo_utils.max_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.max_bool_func_1st_order_fd()], c='r', label=r'$M(t_i)$', zorder=2) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time) + 1,", "time = np.linspace((0 + a) * np.pi, (5 - a)", "10)) plt.scatter(time[optimal_minima], time_series[optimal_minima], c='darkblue', zorder=4, label=textwrap.fill('Optimal minima', 10)) plt.scatter(inflection_x, inflection_y,", "hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(time, np.ones_like(time), 'k--', label=textwrap.fill('Annual cycle', 10))", "0, 2]) axs[1].set_xticks(ticks=[np.pi]) axs[1].set_xticklabels(labels=[r'$\\pi$']) box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.05,", "envelope', 10)) plt.plot(time, EEMD_minima_envelope, c='darkgreen') plt.plot(time, (EEMD_maxima_envelope + EEMD_minima_envelope) /", "2.5 * np.ones_like(maxima_line_dash_time) minima_dash = np.linspace(-3.4 - width, -3.4 +", "time) + np.cos(8 * time) noise = np.random.normal(0, 1, len(time_series))", "ax.plot(x_hs[0, :], 4 * np.ones_like(x_hs[0, :]), '--', label=r'$\\omega = 4$',", "pseudo_alg_time_series + np.random.normal(0, 0.1, len(preprocess_time)) for i in random.sample(range(1000), 500):", "time_extended[-1000]) / 2) - 0.1, 100), -2.75 * np.ones(100), c='gray')", "box_0.width * 0.85, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_slope_based.png') plt.show()", "ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/DFA_hilbert_spectrum.png') plt.show() # plot 6c time", "* figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess Filtering Demonstration') axs[1].set_title('Zoomed Region') preprocess_time =", "axs[0].plot(time, b_spline_basis[3, :].T, '--', label='Basis 2') axs[0].plot(time, b_spline_basis[4, :].T, '--',", "zorder=10) plt.scatter(time[minima], time_series[minima], c='b', label='Minima', zorder=10) plt.plot(time, max_unsmoothed[0], label=textwrap.fill('Unsmoothed maxima", "+ (minima_x[-1] - minima_x[-2]) slope_based_minimum = slope_based_maximum - (slope_based_maximum_time -", "PyEMD 0.2.10', 40)) plt.pcolormesh(t, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(t[:-1],", "2 - i_left)] = \\ 2 * sum(weights_left * np.hstack((time_series_extended[int(len(lsq_signal)", "np.ones(101), 'k--') axs[2].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), -5.5", "cvx.Minimize(cvx.norm((2 * (vx * P) + 1 - t), 2))", "* np.pi, 1001) knots = np.linspace((0 + a) * np.pi,", "+ time_extended[-1002]) / 2) * np.ones(100), np.linspace(-2.75, 2.75, 100), c='k')", "0.8, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert_pyemd.png') plt.show()", "plt.plot(dash_4_time, dash_4, 'k--') plt.plot(dash_final_time, dash_final, 'k--') plt.scatter(maxima_x, maxima_y, c='r', zorder=4,", "np.pi, 101), 5.5 * np.ones(101), 'k--') axs[2].plot(np.linspace(0.95 * np.pi, 1.55", "plt.plot(time[500:], b_spline_basis[6, 500:].T, '--', label=r'$ B_{1,4}(t) $') plt.xticks([5, 6], [r'$", "points', 10)) plt.plot(time, maxima_envelope, c='darkblue', label=textwrap.fill('EMD envelope', 10)) plt.plot(time, minima_envelope,", "* (vx * P) + 1 - t), 2)) #", "width, maxima_y[-2] + width, 101) max_2_y_side = np.linspace(-1.8 - width,", "label=r'$\\tilde{h}_{(1,0)}^{\\mu}(t)$', zorder=5) plt.yticks(ticks=[-2, -1, 0, 1, 2]) plt.xticks(ticks=[0, np.pi, 2", "in the Atmosphere', 35)) plt.ylabel('Parts per million') plt.xlabel('Time (years)') plt.savefig('jss_figures/CO2_concentration.png')", "label=textwrap.fill('Extrapolated minima', 12)) plt.plot(((time[-302] + time[-301]) / 2) * np.ones(100),", "np.linspace(-5.5, 5.5, 101), 'k--') axs[1].plot(1.55 * np.pi * np.ones(101), np.linspace(-5.5,", "zorder=4) plt.scatter(pseudo_alg_time[pseudo_utils.min_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.min_bool_func_1st_order_fd()], c='c', label=r'$m(t_j)$', zorder=3) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time) - 1,", "py_emd[1, :])), 3)}') axs[1].plot(t, emd_sift[:, 1], '--', label='emd 0.3.3') print(f'emd", "width, minima_x[-1] + width, 101) min_1_x_time_side = np.linspace(5.4 * np.pi", "5.5 * np.ones(101), 'k--') axs[2].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi,", "np.pi, -0.1, r'$2a_1$') plt.plot(max_1_y_time, max_1_y, 'k-') plt.plot(max_1_y_time, max_1_y_side, 'k-') plt.plot(min_1_y_time,", "maxima_x[-1]) slope_based_minimum_time = minima_x[-1] + (minima_x[-1] - minima_x[-2]) slope_based_minimum =", "Concentration') axs[1, 0].set_title('IMF 1') axs[1, 1].set_title('Residual') plt.gcf().subplots_adjust(bottom=0.15) plt.savefig('jss_figures/CO2_EMD.png') plt.show() hs_ouputs", "Huang_max, c='magenta', zorder=4, label=textwrap.fill('Huang maximum', 10)) plt.scatter(Huang_min_time, Huang_min, c='lime', zorder=4,", "- i_left):int(len(lsq_signal))]) if sum(emd_utils_max.max_bool_func_1st_order_fd()) > 0: max_count_left += 1 emd_utils_min", "np.linspace(time[-1] - 0.5, time[-1] + 0.5, 101) anti_symmetric_signal = time_series[-1]", "plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time), '--', c='purple', label=r'$\\tilde{h}_{(1,0)}^{\\mu}(t)$', zorder=5) plt.yticks(ticks=[-2, -1, 0, 1,", "= np.linspace(maxima_y[-1], minima_y[-1], 101) length_distance_time = point_1 * np.pi *", "np.cos(8 * time) noise = np.random.normal(0, 1, len(time_series)) time_series +=", "ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Single Neuron Neural Network Example') plt.plot(time,", ":].T, '--') axs[1].plot(time, chsi_basis[12, :].T, '--') axs[1].plot(time, chsi_basis[13, :].T, '--')", "* np.ones(100), c='gray') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1000]) / 2), ((time_extended[-1001] +", "= Coughlin_time[Coughlin_max_bool] Coughlin_max = Coughlin_wave[Coughlin_max_bool] Coughlin_min_time = Coughlin_time[Coughlin_min_bool] Coughlin_min =", "label='Minima') plt.scatter(maxima_extrapolate_time, maxima_extrapolate, c='magenta', zorder=3, label=textwrap.fill('Extrapolated maxima', 12)) plt.scatter(minima_extrapolate_time, minima_extrapolate,", "s1 max_dash_time_3 = slope_based_maximum_time * np.ones_like(max_dash_1) max_dash_3 = np.linspace(slope_based_maximum -", "* (len(lsq_signal) - 1) + 1 + i_right)], 1))) i_right", "XY0, t) x = solution[:, 0] dxdt = solution[:, 1]", "$', r'$ \\tau_{k+1} $']) axs[0].set_xlim(4.5, 6.5) axs[1].set_title('Cubic Hermite Spline Bases')", "* np.pi, 2, r'$\\Delta{t^{max}_{M}}$') plt.text(4.30 * np.pi, 0.35, r'$s_1$') plt.text(4.43", "label=textwrap.fill('Coughlin maximum', 14)) plt.scatter(Coughlin_min_time, Coughlin_min, c='dodgerblue', zorder=4, label=textwrap.fill('Coughlin minimum', 14))", "verbose=False)[0][1, :] utils = emd_utils.Utility(time=time[:-1], time_series=imf_1_of_derivative) optimal_maxima = np.r_[False, utils.derivative_forward_diff()", "r'$ \\tau_{k+1} $']) axs[1].set_xlim(4.5, 6.5) plt.savefig('jss_figures/comparing_bases.png') plt.show() # plot 3", "* np.pi]) axs[0].set_xticklabels(['', '', '', '', '', '']) axs[0].plot(np.linspace(0.95 *", "'minima', optimal_maxima, optimal_minima, smooth=False, smoothing_penalty=0.2, edge_effect='none')[0] ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10)", "plt.text(4.50 * np.pi + (slope_based_minimum_time - minima_x[-1]), 1.20 + (slope_based_minimum", "axs[1].set_title('IMF 1 and Statically Optimised Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2,", "np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots[0] *", "# plot 1 plt.title('Non-Natural Cubic B-Spline Bases at Boundary') plt.plot(time[500:],", "* np.ones_like(t[:-1]), '--', label=textwrap.fill('Hamiltonian frequency approximation', 15)) plt.plot(t[:-1], 0.04 *", "maxima_y[-1] + width, 101) max_1_y_side = np.linspace(-2.1 - width, -2.1", "14)) plt.scatter(Coughlin_min_time, Coughlin_min, c='dodgerblue', zorder=4, label=textwrap.fill('Coughlin minimum', 14)) plt.scatter(Average_max_time, Average_max,", "# plot 6b fig, axs = plt.subplots(3, 1) plt.suptitle(textwrap.fill('Comparison of", "19)) axs[1].plot(time, imfs_51[2, :] + imfs_51[3, :], label=textwrap.fill('Sum of IMF", "plt.show() # plot 5 a = 0.25 width = 0.2", "0.1, 100), 2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1000]) /", "as cvx import seaborn as sns import matplotlib.pyplot as plt", "np.ones(101), np.linspace(-2, 2, 101), '--', c='grey') plt.savefig('jss_figures/knot_2.png') plt.show() # plot", "random.seed(1) preprocess_time_series = pseudo_alg_time_series + np.random.normal(0, 0.1, len(preprocess_time)) for i", "zorder=4, label=textwrap.fill('Improved slope-based maximum', 11)) plt.scatter(improved_slope_based_minimum_time, improved_slope_based_minimum, c='dodgerblue', zorder=4, label=textwrap.fill('Improved", "1 with 11 knots') axs[2].plot(time, imfs_31[2, :], label='IMF 2 with", "* np.pi]) axs[1].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2 and Statically Optimised", "ax.set_yticks(y_points_1) if axis == 1: ax.set_ylabel(r'$ \\dfrac{dx(t)}{dt} $') ax.set(xlabel='t') ax.set_yticks(y_points_2)", "0.124 * np.ones_like(t[:-1]), '--', label=textwrap.fill('Hamiltonian frequency approximation', 15)) plt.plot(t[:-1], 0.04", "minima_y[-1], 101) length_distance_time_2 = point_2 * np.pi * np.ones_like(length_distance_2) length_time_2", "plt.plot(min_dash_time_2, min_dash_2, 'k-') plt.plot(min_dash_time_3, min_dash_3, 'k-') plt.plot(min_dash_time_4, min_dash_4, 'k-') plt.plot(maxima_dash_time_1,", "min_dash_1 = np.linspace(minima_y[-1] - width, minima_y[-1] + width, 101) min_dash_2", "utils.max_bool_func_1st_order_fd() anti_max_point_time = time_reflect[anti_max_bool] anti_max_point = time_series_anti_reflect[anti_max_bool] utils = emd_utils.Utility(time=time,", "box_0 = ax.get_position() ax.set_position([box_0.x0, box_0.y0 + 0.05, box_0.width * 0.75,", "ax.set_xticklabels(x_names) axis += 1 plt.savefig('jss_figures/Duffing_equation_imfs.png') plt.show() hs_ouputs = hilbert_spectrum(t, emd_duff,", "2 fig, axs = plt.subplots(1, 2, sharey=True) axs[0].set_title('Cubic B-Spline Bases')", "width = 0.2 time = np.linspace((0 + a) * np.pi,", "-5.5 * np.ones(101), 'k--') axs[0].plot(0.95 * np.pi * np.ones(101), np.linspace(-5.5,", "plt.plot(x_hs[0, :], np.ones_like(x_hs[0, :]), 'k--', label=textwrap.fill('Annual cycle', 10)) ax.axis([x_hs.min(), x_hs.max(),", "1 if i_right > 1: emd_utils_max = \\ emd_utils.Utility(time=time_extended[int(2 *", "np.cos(2 * np.pi * t / 50) + 0.6 *", "((time[-202] + time[-201]) / 2) + 0.1, 100), -2.75 *", "difference between slope-based method and improved slope-based method more clear", "= (minima_y[-2] + minima_y[-1]) / 2 utils_Huang = emd_utils.Utility(time=time, time_series=Huang_wave)", "train_input) error = (t - output) gradients = error *", "label='Knots') axs[2].plot(knots[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots')", "label='x(t)') axs[0].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[0].plot(preprocess_time,", "axs[0].set_xlim(4.5, 6.5) axs[1].set_title('Cubic Hermite Spline Bases') axs[1].plot(time, chsi_basis[10, :].T, '--')", "100), -2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1002]) / 2),", "+ minima_envelope_smooth) / 2, c='darkred') plt.plot(time, EEMD_maxima_envelope, c='darkgreen', label=textwrap.fill('EEMD envelope',", "101) dash_max_min_1_x_time = 5.4 * np.pi * np.ones_like(dash_max_min_1_x) max_1_y =", "1.0 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) ax.pcolormesh(x, y, np.abs(z), cmap='gist_rainbow', vmin=z_min,", "max_discard_time = minima_x[-1] - maxima_x[-1] + minima_x[-1] max_discard_dash_time = np.linspace(max_discard_time", "'--', label=r'$ B_{0,4}(t) $') plt.plot(time[500:], b_spline_basis[6, 500:].T, '--', label=r'$ B_{1,4}(t)", "Smoothing Demonstration') axs[1].set_title('Zoomed Region') axs[0].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[0].plot(pseudo_alg_time, pseudo_alg_time_series, '--',", "P) + 1 - t), 2)) # linear activation function", "as pyemd0215 import emd as emd040 sns.set(style='darkgrid') pseudo_alg_time = np.linspace(0,", "np.ones(101), '--', c='black', label=textwrap.fill('Zoomed region', 10)) axs[0].plot(np.linspace(0.85 * np.pi, 1.15", "axs[2].set_xticks([0, np.pi, 2 * np.pi, 3 * np.pi, 4 *", "np.linspace(point_1 * np.pi - width, point_1 * np.pi + width,", "= minima_y[-1] * np.ones_like(length_time_2) symmetry_axis_1_time = minima_x[-1] * np.ones(101) symmetry_axis_2_time", ":].T, 12, 'hilbert') print(f'PyEMD annual frequency error: {np.round(sum(np.abs(IF[:, 0] -", "* np.ones(101), 'k--') axs[1].plot(0.95 * np.pi * np.ones(101), np.linspace(-5.5, 5.5,", "box_0.y0, box_0.width * 0.95, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/pseudo_algorithm.png')", "minima_y[-1] + (slope_based_maximum_time - minima_x[-1]) * s1 max_dash_time_3 = slope_based_maximum_time", "np.ones(101), np.linspace(-2, 2, 101), '--', c='grey') plt.savefig('jss_figures/knot_uniform.png') plt.show() # plot", "label=textwrap.fill('Noiseless time series', 12)) axs[0].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean filter', 12)) axs[0].plot(preprocess_time,", "CO$_{2}$ Concentration using emd 0.3.3', 45)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)')", "time_series[maxima], c='r', label='Maxima', zorder=10) plt.scatter(time[minima], time_series[minima], c='b', label='Minima', zorder=10) plt.plot(time,", "31 knots', 19)) axs[1].plot(time, imfs_51[2, :] + imfs_51[3, :], label=textwrap.fill('Sum", "/ 2) * np.ones(100), np.linspace(-2.75, 2.75, 100), c='gray', linestyle='dashed', label=textwrap.fill('Neural", "= plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time, time_series, LineWidth=2, label='Signal') plt.title('Symmetry Edge Effects", "plt.plot(length_time_2, length_bottom_2, 'k-') plt.plot(end_time, end_signal, 'k-') plt.plot(symmetry_axis_1_time, symmetry_axis, 'r--', zorder=1)", "EEMD_minima_envelope) / 2, c='darkgreen') plt.plot(time, inflection_points_envelope, c='darkorange', label=textwrap.fill('Inflection point envelope',", "+ 0.05, box_0.width * 0.85, box_0.height * 0.9]) ax.legend(loc='center left',", "a=0.8)[1], label=textwrap.fill('Windsorize filter', 12)) axs[1].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize interpolation filter',", "Coughlin_time[0])) Average_max_time = maxima_x[-1] + (maxima_x[-1] - maxima_x[-2]) Average_max =", "label=textwrap.fill('Neural network targets', 13)) plt.plot(np.linspace(((time[-202] + time[-201]) / 2), ((time[-202]", "(years)') plt.pcolormesh(time, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(time, np.ones_like(time), 'k--',", "min_1_x, 'k-') plt.plot(dash_max_min_1_x_time, dash_max_min_1_x, 'k--') plt.text(5.42 * np.pi, -0.1, r'$2a_1$')", "np.pi - width, 5.3 * np.pi + width, 101) min_2_x", "a) * np.pi, (5 - a) * np.pi, 11) time_series", "+ width, 101) end_signal = time_series[-1] * np.ones_like(end_time) anti_symmetric_time =", "> 0: min_count_right += 1 # backward <- P =", "plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Uniform Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2, zorder=100)", "axs[1].plot(5 * np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') axs[1].plot(6 * np.ones(100),", "= [-2, 0, 2] y_points_2 = [-1, 0, 1] fig,", "'--', c='grey') plt.savefig('jss_figures/knot_2.png') plt.show() # plot 1d - addition window", "np.pi, 3 * np.pi, 4 * np.pi, 5 * np.pi),", "series', 12)) axs[1].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean filter', 12)) axs[1].plot(preprocess_time, preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median", "2]) axs[0].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF", "+ np.sin(5 * pseudo_alg_time) pseudo_utils = Utility(time=pseudo_alg_time, time_series=pseudo_alg_time_series) # plot", "hts_11, ifs_11 = advemdpy.empirical_mode_decomposition(knots=knots_11, max_imfs=1, edge_effect='symmetric_anchor', verbose=False)[:3] fig, axs =", "1)] = lsq_signal neural_network_m = 200 neural_network_k = 100 #", "\\ emd_example.empirical_mode_decomposition(knots=knots, knot_time=time, verbose=False) print(f'AdvEMDpy annual frequency error: {np.round(sum(np.abs(ifs[1, :]", "np.linspace(2.5 - width, 2.5 + width, 101) maxima_dash_time_1 = maxima_x[-2]", "plt.show() knots = np.arange(12) time = np.linspace(0, 11, 1101) basis", "np.linspace(minima_y[-1] - width, minima_y[-1] + width, 101) min_1_y_side = np.linspace(-2.1", "'k-') plt.plot(max_2_y_time, max_2_y_side, 'k-') plt.plot(min_2_y_time, min_2_y, 'k-') plt.plot(min_2_y_time, min_2_y_side, 'k-')", "window', 12)) axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.10)[1], c='grey') axs[0].plot(np.linspace(0.85 * np.pi, 1.15", "Boundary') plt.plot(time[500:], b_spline_basis[2, 500:].T, '--', label=r'$ B_{-3,4}(t) $') plt.plot(time[500:], b_spline_basis[3,", "'k--') plt.plot(dash_final_time, dash_final, 'k--') plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x,", "IMF 3 with 51 knots', 21)) print(f'DFA fluctuation with 51", "= np.linspace(maxima_y[-1], minima_y[-1], 101) max_discard = maxima_y[-1] max_discard_time = minima_x[-1]", "np.ones_like(max_1_y) min_1_y = np.linspace(minima_y[-1] - width, minima_y[-1] + width, 101)", "axs[1].plot(t, py_emd[1, :], '--', label='PyEMD 0.2.10') print(f'PyEMD driving function error:", "as plt from scipy.integrate import odeint from scipy.ndimage import gaussian_filter", "1.2, 100), 'k-') axs[1].plot(6 * np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-')", "4 * np.ones_like(x_hs[0, :]), '--', label=r'$\\omega = 4$', Linewidth=3) ax.plot(x_hs[0,", "* np.pi), (r'$0$', r'$\\pi$', r'2$\\pi$', r'3$\\pi$', r'4$\\pi$', r'5$\\pi$')) plt.yticks((-2, -1,", "{np.round(sum(np.abs(ifs[1, :] / (2 * np.pi) - np.ones_like(ifs[1, :]))), 3)}')", "Hilbert Spectrum of CO$_{2}$ Concentration using AdvEMDpy', 40)) plt.ylabel('Frequency (year$^{-1}$)')", "downsampled_and_decimated[1], label=textwrap.fill('Downsampled & decimated', 13)) axs[1].plot(downsampled[0], downsampled[1], label=textwrap.fill('Downsampled', 13)) axs[1].set_xlim(0.85", "* np.pi, 11) imfs_11, hts_11, ifs_11 = advemdpy.empirical_mode_decomposition(knots=knots_11, max_imfs=1, edge_effect='symmetric_anchor',", "np.linspace(minima_x[-2], slope_based_minimum_time, 101) minima_line_dash = -3.4 * np.ones_like(minima_line_dash_time) # slightly", "neural_network_k + 1)] P[-1, col] = 1 # for additive", "fig, axs = plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and", "if axis == 1: pass if axis == 2: ax.set(ylabel=R'C0$_2$", "np.linspace(minima_x[-1], maxima_x[-1], 101) dash_max_min_1_y = -2.1 * np.ones_like(dash_max_min_1_y_time) ax =", "'--', c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[1].plot(preprocess_time, preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott smoothing',", "* np.pi + width, 101) length_top = maxima_y[-1] * np.ones_like(length_time)", "Utility(time=pseudo_alg_time, time_series=pseudo_alg_time_series) # plot 0 - addition fig = plt.figure(figsize=(9,", "# plot 1c - addition knot_demonstrate_time = np.linspace(0, 2 *", "np.linspace(-0.2, 1.2, 100), 'k-') axs[1].plot(6 * np.ones(100), np.linspace(-0.2, 1.2, 100),", "minima_dash = np.linspace(-3.4 - width, -3.4 + width, 101) minima_dash_time_1", "label=textwrap.fill('Average minimum', 14)) plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y,", "gradients average_gradients = np.mean(gradients, axis=1) # steepest descent max_gradient_vector =", "noise advemdpy = EMD(time=time, time_series=time_series) imfs_51, hts_51, ifs_51 = advemdpy.empirical_mode_decomposition(knots=knots_51,", "1.55 * np.pi) plt.savefig('jss_figures/DFA_different_trends_zoomed.png') plt.show() hs_ouputs = hilbert_spectrum(time, imfs_51, hts_51,", "IF, IA = emd040.spectra.frequency_transform(emd_sift[:, :1], 12, 'hilbert') print(f'emd annual frequency", "* np.pi, 1001) knot_demonstrate_time_series = np.sin(knot_demonstrate_time) + np.sin(5 * knot_demonstrate_time)", "time_extended[-1002]) / 2) - 0.1, 100), -2.75 * np.ones(100), c='k')", "* np.abs(maxima_x[-1] - minima_x[-1]) Huang_time = (P1 / P2) *", "fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True, smoothing_penalty=0.2, technique='inflection_points')[0] binomial_points_envelope = fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True, smoothing_penalty=0.2, technique='binomial_average',", "Hilbert Spectrum of Simple Sinusoidal Time Seres with Added Noise',", "= np.abs(maxima_y[-1] - minima_y[-1]) / 2 P2 = 2 *", "r'$ \\tau_1 $']) plt.xlim(4.4, 6.6) plt.plot(5 * np.ones(100), np.linspace(-0.2, 1.2,", "np.ones_like(IF)))[0], 3)}') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 2, 100) hht =", "* 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht_pyemd.png') plt.show() plt.show() emd_sift", "= np.linspace(-1.8 - width, -1.8 + width, 101) min_2_y_time =", "101) min_2_y_time = minima_x[-2] * np.ones_like(min_2_y) dash_max_min_2_y_time = np.linspace(minima_x[-2], maxima_x[-2],", "1: pass if axis == 2: ax.set(ylabel=R'C0$_2$ concentration') ax.set(xlabel='Time (years)')", "average_gradients = np.mean(gradients, axis=1) # steepest descent max_gradient_vector = average_gradients", "= minima_x[-1] * np.ones_like(min_1_y) dash_max_min_1_y_time = np.linspace(minima_x[-1], maxima_x[-1], 101) dash_max_min_1_y", "* np.ones_like(max_dash_1) max_dash_time_2 = maxima_x[-2] * np.ones_like(max_dash_1) min_dash_1 = np.linspace(minima_y[-1]", "2 * np.pi * t) - emd_sift[:, 1])), 3)}') axs[1].plot(t,", "min_2_x, 'k-') plt.plot(min_2_x_time_side, min_2_x, 'k-') plt.plot(dash_max_min_2_x_time, dash_max_min_2_x, 'k--') plt.text(5.16 *", "0, np.abs(z).max() figure_size = plt.gcf().get_size_inches() factor = 1.0 plt.gcf().set_size_inches((figure_size[0], factor", "fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima', smooth=True) min_unsmoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima', smooth=False) min_smoothed =", "(years)') plt.plot(x_hs[0, :], np.ones_like(x_hs[0, :]), 'k--', label=textwrap.fill('Annual cycle', 10)) ax.axis([x_hs.min(),", "Huang_max = Huang_wave[Huang_max_bool] Huang_min_time = Huang_time[Huang_min_bool] Huang_min = Huang_wave[Huang_min_bool] Coughlin_max_time", "'k-') plt.plot(dash_max_min_2_x_time, dash_max_min_2_x, 'k--') plt.text(5.16 * np.pi, 0.85, r'$2a_2$') plt.plot(max_2_y_time,", "minima_extrapolate = time_series_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] minima_extrapolate_time = time_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10)", "= minima_y[-1] + (slope_based_maximum_time - minima_x[-1]) * s1 max_dash_time_3 =", "imfs_51, hts_51, ifs_51, max_frequency=12, plot=False) # plot 6c ax =", "2, 101), '--', c='grey', label='Knots') axs[2].plot(knots[0] * np.ones(101), np.linspace(-2, 2,", "time[-201]) / 2) + 0.1, 100), 2.75 * np.ones(100), c='gray')", "max_count_right += 1 emd_utils_min = \\ emd_utils.Utility(time=time_extended[int(2 * (len(lsq_signal) -", "2 utils_Huang = emd_utils.Utility(time=time, time_series=Huang_wave) Huang_max_bool = utils_Huang.max_bool_func_1st_order_fd() Huang_min_bool =", "plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)') plt.plot(x_hs[0, :], np.ones_like(x_hs[0, :]), 'k--', label=textwrap.fill('Annual", "plt.text(5.42 * np.pi, -0.1, r'$2a_1$') plt.plot(max_1_y_time, max_1_y, 'k-') plt.plot(max_1_y_time, max_1_y_side,", "= time_reflect[utils.max_bool_func_1st_order_fd()] no_anchor_max = time_series_reflect[utils.max_bool_func_1st_order_fd()] point_1 = 5.4 length_distance =", "100), 2.75 * np.ones(100), c='gray') plt.plot(((time_extended[-1001] + time_extended[-1000]) / 2)", "axs[0].set_xticks([5, 6]) axs[0].set_xticklabels([r'$ \\tau_k $', r'$ \\tau_{k+1} $']) axs[0].set_xlim(4.5, 6.5)", "axis == 1: ax.set_ylabel(r'$\\gamma_2(t)$') ax.set_yticks([-0.2, 0, 0.2]) box_0 = ax.get_position()", "envelope', 10)) plt.plot(time, minima_envelope, c='darkblue') plt.plot(time, (maxima_envelope + minima_envelope) /", "11) time_series = np.cos(time) + np.cos(5 * time) utils =", "B-Spline Bases') axs[0].plot(time, b_spline_basis[2, :].T, '--', label='Basis 1') axs[0].plot(time, b_spline_basis[3,", "= np.linspace(-3.4 - width, -3.4 + width, 101) minima_dash_time_1 =", "length_bottom_2 = minima_y[-1] * np.ones_like(length_time_2) symmetry_axis_1_time = minima_x[-1] * np.ones(101)", "Anchor maxima', 10)) plt.scatter(anti_max_point_time, anti_max_point, c='green', zorder=4, label=textwrap.fill('Anti-Symmetric maxima', 10))", "smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] maxima_envelope_smooth = fluctuation.envelope_basis_function_approximation(knots, 'maxima', smooth=True, smoothing_penalty=0.2, edge_effect='none',", "2 * np.ones_like(x_hs[0, :]), '--', label=r'$\\omega = 2$', Linewidth=3) ax.set_xticks([0,", "/ # \\ / # \\/ import random import textwrap", "plt.xlim(4.4, 6.6) plt.plot(5 * np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') plt.plot(6", "- bottom weights_right = np.hstack((weights, 0)) max_count_right = 0 min_count_right", "axs[2].plot(time, imfs_51[3, :], label='IMF 3 with 51 knots') for knot", "- col)):(-(neural_network_m - col))] P[-1, col] = 1 # for", "== 3: ax.set(xlabel='Time (years)') axis += 1 plt.gcf().subplots_adjust(bottom=0.15) axs[0, 0].set_title(r'Original", "* np.pi, 5.5 * np.pi) plt.xticks((4 * np.pi, 5 *", "emd_utils_max = \\ emd_utils.Utility(time=time_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))], time_series=time_series_extended[int(len(lsq_signal) -", "Uniform Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2, zorder=100) axs[1].set_yticks(ticks=[-2, 0, 2])", "text=False, verbose=False)[0][1, :] utils = emd_utils.Utility(time=time[:-1], time_series=imf_1_of_derivative) optimal_maxima = np.r_[False,", "+ 0.1, 100), 2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1002])", "ax.set_title(textwrap.fill(r'Gaussian Filtered Hilbert Spectrum of CO$_{2}$ Concentration using AdvEMDpy', 40))", "of Trends Extracted with Different Knot Sequences Zoomed Region', 40))", "c='r', label=r'$\\tilde{h}_{(1,0)}^M(t)$', zorder=4) plt.scatter(pseudo_alg_time[pseudo_utils.min_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.min_bool_func_1st_order_fd()], c='c', label=r'$m(t_j)$', zorder=3) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time)", "np.linspace(maxima_y[-1] - width, maxima_y[-1] + width, 101) max_1_y_side = np.linspace(-2.1", "c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.scatter(slope_based_maximum_time, slope_based_maximum,", "dash_4, 'k--') plt.plot(dash_final_time, dash_final, 'k--') plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima')", "label='Knots') axs[2].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots')", "ax in axs.flat: ax.label_outer() if axis == 0: ax.set_ylabel(r'$\\gamma_1(t)$') ax.set_yticks([-2,", "= fluctuation.envelope_basis_function_approximation(knots, 'maxima', smooth=True, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] minima_envelope = fluctuation.envelope_basis_function_approximation(knots,", "box_1.y0, box_1.width * 0.85, box_1.height]) plt.savefig('jss_figures/preprocess_filter.png') plt.show() # plot 1e", "fig, axs = plt.subplots(2, 1) plt.subplots_adjust(hspace=0.2) axs[0].plot(t, x) axs[0].set_title('Duffing Equation", "np.ones_like(maxima_dash) maxima_dash_time_2 = maxima_x[-1] * np.ones_like(maxima_dash) maxima_dash_time_3 = slope_based_maximum_time *", "5 * np.pi]) axs[2].set_xticklabels(['$0$', r'$\\pi$', r'$2\\pi$', r'$3\\pi$', r'$4\\pi$', r'$5\\pi$']) box_2", "2, r'$\\Delta{t^{max}_{M}}$') plt.text(4.30 * np.pi, 0.35, r'$s_1$') plt.text(4.43 * np.pi,", "a = 0.21 width = 0.2 time = np.linspace(0, (5", "max_1_x_time = np.linspace(maxima_x[-1] - width, maxima_x[-1] + width, 101) max_1_x_time_side", "* np.pi, 101), 3 * np.ones(101), '--', c='black') axs[0].plot(0.85 *", "time_series=pseudo_alg_time_series) # plot 0 - addition fig = plt.figure(figsize=(9, 4))", "'2')) box_0 = ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width *", "plt.savefig('jss_figures/edge_effects_symmetry_anti.png') plt.show() # plot 4 a = 0.21 width =", "+ imfs_51[3, :], label=textwrap.fill('Sum of IMF 2 and IMF 3", "fontsize=8) axs[0].set_ylim(-5.5, 5.5) axs[0].set_xlim(0.95 * np.pi, 1.55 * np.pi) axs[1].plot(time,", "min_bool = utils.min_bool_func_1st_order_fd() minima_x = time[min_bool] minima_y = time_series[min_bool] A2", "utils.max_bool_func_1st_order_fd() maxima_x = time[max_bool] maxima_y = time_series[max_bool] min_bool = utils.min_bool_func_1st_order_fd()", "= CubicSpline(t[util_nn.min_bool_func_1st_order_fd()], minima) time = np.linspace(0, 5 * np.pi, 1001)", "'k--') axs[2].plot(0.95 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--')", "'', '']) box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.05, box_0.y0, box_0.width", "* np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--', label='Zoomed region')", "- py_emd[1, :])), 3)}') axs[1].plot(t, emd_sift[:, 1], '--', label='emd 0.3.3')", "imfs, _, _, _, knots, _, _ = emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=1,", "axs[1].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[1].plot(preprocess_time, preprocess.hp()[1],", "with 51 knots', 21)) for knot in knots_51: axs[0].plot(knot *", "= pseudo_alg_time_series + np.random.normal(0, 0.1, len(preprocess_time)) for i in random.sample(range(1000),", "'k-') plt.plot(min_2_x_time_side, min_2_x, 'k-') plt.plot(dash_max_min_2_x_time, dash_max_min_2_x, 'k--') plt.text(5.16 * np.pi,", "0.8, 100), 'k-') axs[0].plot(6 * np.ones(100), np.linspace(-0.2, 0.8, 100), 'k-')", "plt.plot(time, max_unsmoothed[0], label=textwrap.fill('Unsmoothed maxima envelope', 10), c='darkorange') plt.plot(time, max_smoothed[0], label=textwrap.fill('Smoothed", "axs[0].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[0].plot(preprocess_time, preprocess.hp()[1],", "101), '--', c='grey') plt.savefig('jss_figures/knot_2.png') plt.show() # plot 1d - addition", "11 knots: {np.round(np.var(time_series - imfs_51[3, :]), 3)}') for knot in", "r'$\\frac{p_2}{2}$') plt.plot(max_1_x_time, max_1_x, 'k-') plt.plot(max_1_x_time_side, max_1_x, 'k-') plt.plot(min_1_x_time, min_1_x, 'k-')", "plt.plot(min_dash_time_4, min_dash_4, 'k-') plt.plot(maxima_dash_time_1, maxima_dash, 'k-') plt.plot(maxima_dash_time_2, maxima_dash, 'k-') plt.plot(maxima_dash_time_3,", "(minima_x[-1] - maxima_x[-1]) slope_based_minimum_time = minima_x[-1] + (minima_x[-1] - minima_x[-2])", "= np.linspace(maxima_x[-1], minima_x[-1], 101) dash_1 = np.linspace(maxima_y[-1], minima_y[-1], 101) max_discard", "signal', 12)) plt.scatter(maxima_time, maxima, c='r', zorder=3, label='Maxima') plt.scatter(minima_time, minima, c='b',", "> 0, False] & \\ np.r_[utils.zero_crossing() == 1, False] EEMD_maxima_envelope", "smooth=False) min_smoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima', smooth=True) util = Utility(time=time, time_series=time_series)", "- addition fig, axs = plt.subplots(2, 1) fig.subplots_adjust(hspace=0.4) figure_size =", "axs[1].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[1].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2", "101), '--', c='black') axs[0].set_yticks(ticks=[-2, 0, 2]) axs[0].set_xticks(ticks=[0, np.pi, 2 *", "maxima_dash_time_3 = slope_based_maximum_time * np.ones_like(maxima_dash) maxima_line_dash_time = np.linspace(maxima_x[-2], slope_based_maximum_time, 101)", "maxima', 12)) plt.scatter(minima_extrapolate_time, minima_extrapolate, c='cyan', zorder=4, label=textwrap.fill('Extrapolated minima', 12)) plt.plot(((time[-302]", "0: max_count_left += 1 emd_utils_min = \\ emd_utils.Utility(time=time_extended[int(len(lsq_signal) - 1", "zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.plot(Huang_time, Huang_wave, '--',", "* np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') plt.legend(loc='upper left') plt.savefig('jss_figures/boundary_bases.png') plt.show()", "- time_series_reflect utils = emd_utils.Utility(time=time, time_series=time_series_anti_reflect) anti_max_bool = utils.max_bool_func_1st_order_fd() anti_max_point_time", "time_reflect = np.linspace((5 - a) * np.pi, (5 + a)", "axs[2].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1, label='Knots')", "factor = 1.0 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert", "== 1: ax.set_ylabel(r'$\\gamma_2(t)$') ax.set_yticks([-0.2, 0, 0.2]) box_0 = ax.get_position() ax.set_position([box_0.x0,", "pandas as pd import cvxpy as cvx import seaborn as", "np.pi - width, 5.4 * np.pi + width, 101) max_1_x", "5.5 * np.ones(101), 'k--') axs[1].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi,", "np.ones_like(t[:-1]), '--', label=textwrap.fill('Hamiltonian frequency approximation', 15)) plt.plot(t[:-1], 0.04 * np.ones_like(t[:-1]),", "verbose=False) print(f'AdvEMDpy annual frequency error: {np.round(sum(np.abs(ifs[1, :] / (2 *", "zorder=2) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time) + 1, '--', c='r', label=r'$\\tilde{h}_{(1,0)}^M(t)$', zorder=4) plt.scatter(pseudo_alg_time[pseudo_utils.min_bool_func_1st_order_fd()],", "= ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width * 0.85, box_0.height])", ":] + imfs_51[3, :], label=textwrap.fill('Sum of IMF 1, IMF 2,", "a=0.8)[1], label=textwrap.fill('Windsorize interpolation filter', 14)) axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.90)[1], c='grey', label=textwrap.fill('Quantile", "max_dash_time_1 = maxima_x[-1] * np.ones_like(max_dash_1) max_dash_time_2 = maxima_x[-2] * np.ones_like(max_dash_1)", "- 0.05, box_1.y0, box_1.width * 0.85, box_1.height]) plt.savefig('jss_figures/preprocess_filter.png') plt.show() #", "dash_1, 'k--') plt.plot(dash_2_time, dash_2, 'k--') plt.plot(length_distance_time, length_distance, 'k--') plt.plot(length_distance_time_2, length_distance_2,", "+ imfs_51[3, :], label=textwrap.fill('Sum of IMF 1, IMF 2, &", "spline_method='b_spline')[0] minima_envelope_smooth = fluctuation.envelope_basis_function_approximation(knots, 'minima', smooth=True, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] inflection_points_envelope", "* t) - emd_duff[2, :])), 3)}') axs[1].plot(t, py_emd[1, :], '--',", "fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Uniform Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2,", "= gaussian_filter(hht, sigma=1) ax = plt.subplot(111) figure_size = plt.gcf().get_size_inches() factor", "(5 - a) * np.pi, 101)) + np.cos(5 * np.linspace((5", "axs[0].get_position() axs[0].set_position([box_0.x0 - 0.06, box_0.y0, box_0.width * 0.85, box_0.height]) axs[0].legend(loc='center", "- a) * np.pi, (5 + a) * np.pi, 101)", "= minima_x[-1] * np.ones_like(min_dash_1) min_dash_time_2 = minima_x[-2] * np.ones_like(min_dash_1) dash_1_time", "+ s2 * (improved_slope_based_minimum_time - improved_slope_based_maximum_time) min_dash_4 = np.linspace(improved_slope_based_minimum -", "prob = cvx.Problem(objective) result = prob.solve(verbose=True, solver=cvx.ECOS) weights_left = np.array(vx.value)", "plt.pcolormesh(t, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(t[:-1], 0.124 * np.ones_like(t[:-1]),", "+ EEMD_minima_envelope) / 2, c='darkgreen') plt.plot(time, inflection_points_envelope, c='darkorange', label=textwrap.fill('Inflection point", "10)) plt.scatter(Coughlin_max_time, Coughlin_max, c='darkorange', zorder=4, label=textwrap.fill('Coughlin maximum', 14)) plt.scatter(Coughlin_min_time, Coughlin_min,", "box_0.y0, box_0.width * 0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_characteristic_wave.png')", "utils = emd_utils.Utility(time=time, time_series=time_series_reflect) no_anchor_max_time = time_reflect[utils.max_bool_func_1st_order_fd()] no_anchor_max = time_series_reflect[utils.max_bool_func_1st_order_fd()]", "plt.plot(anti_symmetric_time, anti_symmetric_signal, 'r--', zorder=1) plt.plot(symmetry_axis_2_time, symmetry_axis, 'r--', label=textwrap.fill('Axes of symmetry',", "knots = np.linspace(0, 5 * np.pi, 101) time_extended = time_extension(time)", "5.25 * np.pi) box_0 = ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0,", "0, 1] fig, axs = plt.subplots(2, 1) plt.subplots_adjust(hspace=0.2) axs[0].plot(t, x)", "plt.plot(min_2_x_time, min_2_x, 'k-') plt.plot(min_2_x_time_side, min_2_x, 'k-') plt.plot(dash_max_min_2_x_time, dash_max_min_2_x, 'k--') plt.text(5.16", "with 51 knots', 21)) print(f'DFA fluctuation with 51 knots: {np.round(np.var(time_series", "/ 2 P2 = 2 * np.abs(maxima_x[-2] - minima_x[-2]) P1", "np.ones(101), np.linspace(-3, 3, 101), '--', c='black') axs[0].set_yticks(ticks=[-2, 0, 2]) axs[0].set_xticks(ticks=[0,", "np.linspace(maxima_x[-1], minima_x[-1], 101) dash_1 = np.linspace(maxima_y[-1], minima_y[-1], 101) dash_2_time =", "1 emd_utils_min = \\ emd_utils.Utility(time=time_extended[int(2 * (len(lsq_signal) - 1) +", "2), ((time[-302] + time[-301]) / 2) + 0.1, 100), 2.75", "+ time[-201]) / 2), ((time[-202] + time[-201]) / 2) +", "right') axs[1, 0].plot(time, imfs[1, :]) axs[1, 1].plot(time, imfs[2, :]) axis", "optimal_maxima = np.r_[False, utils.derivative_forward_diff() < 0, False] & \\ np.r_[utils.zero_crossing()", "* figure_size[1])) axs[0].plot(t, emd_duff[1, :], label='AdvEMDpy') axs[0].plot(t, py_emd[0, :], '--',", "time_series=Huang_wave) Huang_max_bool = utils_Huang.max_bool_func_1st_order_fd() Huang_min_bool = utils_Huang.min_bool_func_1st_order_fd() utils_Coughlin = emd_utils.Utility(time=time,", "+= np.random.normal(0, 1) preprocess = Preprocess(time=preprocess_time, time_series=preprocess_time_series) axs[0].plot(preprocess_time, preprocess_time_series, label='x(t)')", "emd_basis.Basis(time=time, time_series=time) b_spline_basis = basis.cubic_b_spline(knots) chsi_basis = basis.chsi_basis(knots) # plot", "np.ones(100), np.linspace(-0.2, 0.8, 100), 'k-') axs[0].plot(6 * np.ones(100), np.linspace(-0.2, 0.8,", "IMF 3 with 51 knots', 19)) print(f'DFA fluctuation with 31", "* np.pi, -0.1, r'$2a_1$') plt.plot(max_1_y_time, max_1_y, 'k-') plt.plot(max_1_y_time, max_1_y_side, 'k-')", "np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1 and Uniform Knots') axs[1].plot(knot_demonstrate_time,", ":] lr = 0.01 for iterations in range(1000): output =", "np.pi, 51) fluc = Fluctuation(time=time, time_series=time_series) max_unsmoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima',", "np.linspace(-2.1 - width, -2.1 + width, 101) max_1_y_time = maxima_x[-1]", "plt.gcf().get_size_inches() factor = 1.0 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered", "label='IMF 3 with 51 knots') for knot in knots_11: axs[2].plot(knot", "'k--', label='Zoomed region') box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.05, box_0.y0,", "* np.ones(101), 'k--') axs[0].plot(0.95 * np.pi * np.ones(101), np.linspace(-5.5, 5.5,", "1.55 * np.pi, 101), 5.5 * np.ones(101), 'k--') axs[0].plot(np.linspace(0.95 *", "- 0.06, box_0.y0, box_0.width * 0.85, box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1,", ":]))), 3)}') fig, axs = plt.subplots(2, 2) plt.subplots_adjust(hspace=0.5) axs[0, 0].plot(time,", "Noise', 50)) x_hs, y, z = hs_ouputs z_min, z_max =", "* np.pi, 31) imfs_31, hts_31, ifs_31 = advemdpy.empirical_mode_decomposition(knots=knots_31, max_imfs=2, edge_effect='symmetric_anchor',", "emd040 sns.set(style='darkgrid') pseudo_alg_time = np.linspace(0, 2 * np.pi, 1001) pseudo_alg_time_series", "label=r'$ B_{-1,4}(t) $') plt.plot(time[500:], b_spline_basis[5, 500:].T, '--', label=r'$ B_{0,4}(t) $')", "label=textwrap.fill('Unsmoothed maxima envelope', 10), c='darkorange') plt.plot(time, max_smoothed[0], label=textwrap.fill('Smoothed maxima envelope',", "np.linspace(-3, 3, 101), '--', c='black') axs[0].plot(1.15 * np.pi * np.ones(101),", "zorder=4, label=textwrap.fill('Symmetric Anchor maxima', 10)) plt.scatter(anti_max_point_time, anti_max_point, c='green', zorder=4, label=textwrap.fill('Anti-Symmetric", "time = CO2_data['month'] time = np.asarray(time) # compare other packages", "knots') print(f'DFA fluctuation with 11 knots: {np.round(np.var(time_series - imfs_51[3, :]),", "hs_ouputs y = y / (2 * np.pi) z_min, z_max", "# plot 1b - addition knot_demonstrate_time = np.linspace(0, 2 *", "average_gradients # adjustment = - lr * max_gradient_vector weights +=", "+ width, 101) min_dash_time_1 = minima_x[-1] * np.ones_like(min_dash_1) min_dash_time_2 =", "* (time_series[time >= maxima_x[-2]] - time_series[time == maxima_x[-2]]) + maxima_y[-1]", "plt.plot(time, EEMD_maxima_envelope, c='darkgreen', label=textwrap.fill('EEMD envelope', 10)) plt.plot(time, EEMD_minima_envelope, c='darkgreen') plt.plot(time,", "r'$2\\pi$']) axs[2].set_title('IMF 2 and Uniform Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2,", "(2 * np.pi) z_min, z_max = 0, np.abs(z).max() fig, ax", "label=textwrap.fill('Axes of symmetry', 10), zorder=1) plt.text(5.1 * np.pi, -0.7, r'$\\beta$L')", "np.pi * np.ones(101), np.linspace(-3, 3, 101), '--', c='black') axs[0].set_yticks(ticks=[-2, 0,", "np.pi * np.ones_like(dash_max_min_1_x) max_1_y = np.linspace(maxima_y[-1] - width, maxima_y[-1] +", "of Duffing Equation using AdvEMDpy', 40)) x, y, z =", "= ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width * 0.84, box_0.height])", "compare other packages Carbon Dioxide - bottom knots = np.linspace(time[0],", "ax.set(xlabel='Time (years)') if axis == 3: ax.set(xlabel='Time (years)') axis +=", "end_signal, 'k-') plt.plot(symmetry_axis_1_time, symmetry_axis, 'r--', zorder=1) plt.plot(anti_symmetric_time, anti_symmetric_signal, 'r--', zorder=1)", "preprocess = Preprocess(time=preprocess_time, time_series=preprocess_time_series) axs[0].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[0].plot(pseudo_alg_time, pseudo_alg_time_series, '--',", "box_0.y0, box_0.width * 0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/neural_network.png')", "axs[1].set_title('Zoomed Region') preprocess_time = pseudo_alg_time.copy() np.random.seed(1) random.seed(1) preprocess_time_series = pseudo_alg_time_series", "width, maxima_y[-1] + width, 101) max_dash_2 = np.linspace(maxima_y[-2] - width,", "i_left)] = \\ 2 * sum(weights_left * np.hstack((time_series_extended[int(len(lsq_signal) - 1", "'k-') plt.plot(min_2_x_time, min_2_x, 'k-') plt.plot(min_2_x_time_side, min_2_x, 'k-') plt.plot(dash_max_min_2_x_time, dash_max_min_2_x, 'k--')", "np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1, label='Knots') axs[2].set_xticks([np.pi, (3", "train_input) # guess average gradients average_gradients = np.mean(gradients, axis=1) #", "np.ones_like(x_hs[0, :]), '--', label=r'$\\omega = 2$', Linewidth=3) ax.set_xticks([0, np.pi, 2", "= fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True, smoothing_penalty=0.2, technique='binomial_average', order=21, increment=20)[0] derivative_of_lsq = utils.derivative_forward_diff()", "factor * figure_size[1])) ax.pcolormesh(x, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) plt.plot(t[:-1],", "101) min_1_x_time_side = np.linspace(5.4 * np.pi - width, 5.4 *", "((time_extended[-1001] + time_extended[-1000]) / 2) - 0.1, 100), 2.75 *", "4 * np.pi, 5 * np.pi]) axs[1].set_xticklabels(['', '', '', '',", "2]) if axis == 1: ax.set_ylabel(r'$\\gamma_2(t)$') ax.set_yticks([-0.2, 0, 0.2]) box_0", "Characteristic Wave', 14)) plt.plot(Coughlin_time, Coughlin_wave, '--', c='darkgreen', label=textwrap.fill('Coughlin Characteristic Wave',", "= Huang_wave[Huang_min_bool] Coughlin_max_time = Coughlin_time[Coughlin_max_bool] Coughlin_max = Coughlin_wave[Coughlin_max_bool] Coughlin_min_time =", "EMD(time=time, time_series=time_series) imfs_51, hts_51, ifs_51 = advemdpy.empirical_mode_decomposition(knots=knots_51, max_imfs=3, edge_effect='symmetric_anchor', verbose=False)[:3]", "Carbon Dioxide Concentration Example CO2_data = pd.read_csv('Data/co2_mm_mlo.csv', header=51) plt.plot(CO2_data['month'], CO2_data['decimal", "1 + i_right + 1)]) if sum(emd_utils_max.max_bool_func_1st_order_fd()) > 0: max_count_right", "maxima_x[-2]]) + maxima_y[-1] Coughlin_time = Huang_time Coughlin_wave = A1 *", "0] - np.ones_like(IF[:, 0]))), 3)}') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 2,", "= fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True, smoothing_penalty=0.2, technique='inflection_points')[0] binomial_points_envelope = fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True, smoothing_penalty=0.2,", "pyemd(x) IP, IF, IA = emd040.spectra.frequency_transform(py_emd.T, 10, 'hilbert') freq_edges, freq_bins", "* np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[1].plot(pseudo_alg_time, pseudo_alg_time_series,", "'--', label=r'$\\omega = 8$', Linewidth=3) ax.plot(x_hs[0, :], 4 * np.ones_like(x_hs[0,", "'--', c='darkviolet', label=textwrap.fill('Huang Characteristic Wave', 14)) plt.plot(Coughlin_time, Coughlin_wave, '--', c='darkgreen',", "150]) axis = 0 for ax in axs.flat: ax.label_outer() if", "r'$5\\pi$']) box_2 = axs[2].get_position() axs[2].set_position([box_2.x0 - 0.05, box_2.y0, box_2.width *", "np.linspace(knots[0], knots[-1], 31) # change (1) detrended_fluctuation_technique and (2) max_internal_iter", "time_series_reflect[0] - time_series_reflect utils = emd_utils.Utility(time=time, time_series=time_series_anti_reflect) anti_max_bool = utils.max_bool_func_1st_order_fd()", "11)) plt.xlim(3.9 * np.pi, 5.5 * np.pi) plt.xticks((4 * np.pi,", "2 and IMF 3 with 51 knots', 19)) print(f'DFA fluctuation", "+ maxima_y[-1] Coughlin_time = Huang_time Coughlin_wave = A1 * np.cos(2", "2 * np.abs(maxima_x[-1] - minima_x[-1]) Huang_time = (P1 / P2)", "= emd_utils.Utility(time=time, time_series=Coughlin_wave) Coughlin_max_bool = utils_Coughlin.max_bool_func_1st_order_fd() Coughlin_min_bool = utils_Coughlin.min_bool_func_1st_order_fd() Huang_max_time", "axs[1].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), -5.5 * np.ones(101),", "0.9 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of", "with external debugging) emd = AdvEMDpy.EMD(time=derivative_time, time_series=derivative_of_lsq) imf_1_of_derivative = emd.empirical_mode_decomposition(knots=derivative_knots,", ":], label=textwrap.fill('Sum of IMF 2 and IMF 3 with 51", "* figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time, time_series, LineWidth=2, label='Signal') plt.title('Slope-Based Edge Effects", "technique='inflection_points')[0] binomial_points_envelope = fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True, smoothing_penalty=0.2, technique='binomial_average', order=21, increment=20)[0] derivative_of_lsq", "101) max_2_x_time_side = np.linspace(5.3 * np.pi - width, 5.3 *", "(A1 / A2) * (time_series[time >= maxima_x[-2]] - time_series[time ==", "CubicSpline(t[util_nn.max_bool_func_1st_order_fd()], maxima) cs_min = CubicSpline(t[util_nn.min_bool_func_1st_order_fd()], minima) time = np.linspace(0, 5", "(2) max_internal_iter and (3) debug (confusing with external debugging) emd", "np.sin(knot_demonstrate_time) + np.sin(5 * knot_demonstrate_time) knots_uniform = np.linspace(0, 2 *", "1.15 * np.pi) axs[1].set_ylim(-3, 3) axs[1].set_yticks(ticks=[-2, 0, 2]) axs[1].set_xticks(ticks=[np.pi]) axs[1].set_xticklabels(labels=[r'$\\pi$'])", "x_hs, y, z = hs_ouputs y = y / (2", "Utility from scipy.interpolate import CubicSpline from emd_hilbert import Hilbert, hilbert_spectrum", "0 - addition fig = plt.figure(figsize=(9, 4)) ax = plt.subplot(111)", "left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht_emd.png') plt.show() # compare other packages Duffing", "= 1.5 * (time_series[time >= minima_x[-1]] - time_series[time == minima_x[-1]])", "np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--', label='Zoomed region') axs[2].plot(time,", "/ 0 time_series_extended[int(len(lsq_signal) - 1):int(2 * (len(lsq_signal) - 1) +", "frequency error: {np.round(sum(np.abs(ifs[1, :] / (2 * np.pi) - np.ones_like(ifs[1,", "1d - addition window = 81 fig, axs = plt.subplots(2,", "axs[0].plot(downsampled[0], downsampled[1], label=textwrap.fill('Downsampled', 13)) axs[0].plot(np.linspace(0.85 * np.pi, 1.15 * np.pi,", "plt.plot(min_2_y_time, min_2_y, 'k-') plt.plot(min_2_y_time, min_2_y_side, 'k-') plt.plot(dash_max_min_2_y_time, dash_max_min_2_y, 'k--') plt.text(4.08", "(minima_y[-2] + minima_y[-1]) / 2 utils_Huang = emd_utils.Utility(time=time, time_series=Huang_wave) Huang_max_bool", "c='orangered', zorder=4, label=textwrap.fill('Average maximum', 14)) plt.scatter(Average_min_time, Average_min, c='cyan', zorder=4, label=textwrap.fill('Average", "= minima_x[-2] * np.ones_like(min_dash_1) dash_1_time = np.linspace(maxima_x[-1], minima_x[-1], 101) dash_1", "fontsize=8) ax.set_xticks(x_points) ax.set_xticklabels(x_names) axis += 1 plt.savefig('jss_figures/Duffing_equation_imfs.png') plt.show() hs_ouputs =", "np.pi) axs[1].set_ylim(-3, 3) axs[1].set_yticks(ticks=[-2, 0, 2]) axs[1].set_xticks(ticks=[np.pi]) axs[1].set_xticklabels(labels=[r'$\\pi$']) box_0 =", "advemdpy = EMD(time=time, time_series=time_series) imfs_51, hts_51, ifs_51 = advemdpy.empirical_mode_decomposition(knots=knots_51, max_imfs=3,", "3, 101), '--', c='black') axs[0].set_yticks(ticks=[-2, 0, 2]) axs[0].set_xticks(ticks=[0, np.pi, 2", "function frequency', 15)) plt.xticks([0, 50, 100, 150]) plt.yticks([0, 0.1, 0.2])", "axs[0].get_position() axs[0].set_position([box_0.x0 - 0.05, box_0.y0, box_0.width * 0.85, box_0.height]) axs[0].legend(loc='center", "/ P1) * (Coughlin_time - Coughlin_time[0])) Average_max_time = maxima_x[-1] +", "lsq_signal[:neural_network_m] vx = cvx.Variable(int(neural_network_k + 1)) objective = cvx.Minimize(cvx.norm((2 *", "axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.10)[1], c='grey') axs[0].plot(np.linspace(0.85 * np.pi, 1.15 * np.pi,", "== 1, False] EEMD_maxima_envelope = fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'maxima', optimal_maxima, optimal_minima, smooth=False,", "= 2 * np.abs(maxima_x[-1] - minima_x[-1]) Huang_time = (P1 /", "np.pi, 2, r'$\\Delta{t^{max}_{M}}$') plt.text(4.50 * np.pi, 2, r'$\\Delta{t^{max}_{M}}$') plt.text(4.30 *", "zorder=4, label=textwrap.fill('Symmetric maxima', 10)) plt.xlim(3.9 * np.pi, 5.5 * np.pi)", "time_series=x) emd_duff, emd_ht_duff, emd_if_duff, _, _, _, _ = emd_duffing.empirical_mode_decomposition(verbose=False)", "min_1_y, 'k-') plt.plot(min_1_y_time, min_1_y_side, 'k-') plt.plot(dash_max_min_1_y_time, dash_max_min_1_y, 'k--') plt.text(4.48 *", "np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--', label='Zoomed region') axs[2].plot(time, time_series, label='Time", "if axis == 0: ax.set_ylabel('x(t)') ax.set_yticks(y_points_1) if axis == 1:", "utils_Coughlin = emd_utils.Utility(time=time, time_series=Coughlin_wave) Coughlin_max_bool = utils_Coughlin.max_bool_func_1st_order_fd() Coughlin_min_bool = utils_Coughlin.min_bool_func_1st_order_fd()", "np.pi * np.ones_like(dash_max_min_2_x) max_2_y = np.linspace(maxima_y[-2] - width, maxima_y[-2] +", "length_distance, 'k--') plt.plot(length_distance_time_2, length_distance_2, 'k--') plt.plot(length_time, length_top, 'k-') plt.plot(length_time, length_bottom,", "Uniform Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2, zorder=100) axs[2].set_yticks(ticks=[-2, 0, 2])", "2) + 0.1, 100), 2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time_extended[-1001] +", "\\tau_0 $', r'$ \\tau_1 $']) plt.xlim(4.4, 6.6) plt.plot(5 * np.ones(100),", "left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/detrended_fluctuation_analysis.png') plt.show() # Duffing Equation Example def", "minima_x[-2] + width, 101) min_2_x_time_side = np.linspace(5.3 * np.pi -", "* (len(lsq_signal) - 1) + 1): int(2 * (len(lsq_signal) -", "np.linspace(minima_x[-2] - width, minima_x[-2] + width, 101) min_2_x_time_side = np.linspace(5.3", "ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/neural_network.png') plt.show() # plot 6a np.random.seed(0)", "_, knots, _, _ = emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=2, verbose=False) fig, axs", "+ 1): int(2 * (len(lsq_signal) - 1) + 1 +", "pyemd0215() py_emd = pyemd(x) IP, IF, IA = emd040.spectra.frequency_transform(py_emd.T, 10,", "* np.cos(2 * np.pi * (1 / P1) * (Coughlin_time", "plt.savefig('jss_figures/knot_1.png') plt.show() # plot 1c - addition knot_demonstrate_time = np.linspace(0,", "= improved_slope_based_maximum + s2 * (improved_slope_based_minimum_time - improved_slope_based_maximum_time) min_dash_4 =", "6.5) plt.savefig('jss_figures/comparing_bases.png') plt.show() # plot 3 a = 0.25 width", "maxima_line_dash = 2.5 * np.ones_like(maxima_line_dash_time) minima_dash = np.linspace(-3.4 - width,", "* np.ones_like(t[:-1]), 'g--', label=textwrap.fill('Driving function frequency', 15)) plt.xticks([0, 50, 100,", "width, 101) max_1_x_time_side = np.linspace(5.4 * np.pi - width, 5.4", "5.6 * np.pi) plt.xticks((4 * np.pi, 5 * np.pi), (r'4$\\pi$',", "2 * np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1 and Statically", "10)) plt.plot(time, EEMD_minima_envelope, c='darkgreen') plt.plot(time, (EEMD_maxima_envelope + EEMD_minima_envelope) / 2,", "- 0.1, 100), -2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1000])", "pseudo_utils = Utility(time=pseudo_alg_time, time_series=pseudo_alg_time_series) # plot 0 - addition fig", "c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.scatter(max_discard_time, max_discard,", "import time_extension, Utility from scipy.interpolate import CubicSpline from emd_hilbert import", "Effects Example') plt.plot(time_reflect, time_series_reflect, 'g--', LineWidth=2, label=textwrap.fill('Symmetric signal', 10)) plt.plot(time_reflect[:51],", "imfs_31, hts_31, ifs_31 = advemdpy.empirical_mode_decomposition(knots=knots_31, max_imfs=2, edge_effect='symmetric_anchor', verbose=False)[:3] knots_11 =", "slightly edit signal to make difference between slope-based method and", "preprocess.winsorize_interpolate(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize interpolation filter', 14)) axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.90)[1], c='grey',", "zorder=4, label='Minima') plt.plot(Huang_time, Huang_wave, '--', c='darkviolet', label=textwrap.fill('Huang Characteristic Wave', 14))", "= -3.4 * np.ones_like(minima_line_dash_time) # slightly edit signal to make", "= time[:-1] derivative_knots = np.linspace(knots[0], knots[-1], 31) # change (1)", "emd040.sift.sift(x) IP, IF, IA = emd040.spectra.frequency_transform(emd_sift, 10, 'hilbert') freq_edges, freq_bins", "{np.round(np.var(time_series - (imfs_31[1, :] + imfs_31[2, :])), 3)}') for knot", "matplotlib.pyplot as plt from scipy.integrate import odeint from scipy.ndimage import", "label=textwrap.fill('Mean filter', 12)) axs[0].plot(preprocess_time, preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median filter', 13)) axs[0].plot(preprocess_time, preprocess.winsorize(window_width=window,", "c='purple', label=r'$\\tilde{h}_{(1,0)}^{\\mu}(t)$', zorder=5) plt.yticks(ticks=[-2, -1, 0, 1, 2]) plt.xticks(ticks=[0, np.pi,", "np.pi, 101), -5.5 * np.ones(101), 'k--') axs[0].plot(0.95 * np.pi *", "end_point, c='orange', zorder=4, label=textwrap.fill('Symmetric Anchor maxima', 10)) plt.scatter(anti_max_point_time, anti_max_point, c='green',", "+ time_extended[-1002]) / 2) - 0.1, 100), 2.75 * np.ones(100),", "* 0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Schoenberg_Whitney_Conditions.png') plt.show() #", "'k--') axs[1].plot(0.95 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--')", "- (slope_based_maximum_time - slope_based_minimum_time) * s2 min_dash_time_3 = slope_based_minimum_time *", "* np.pi, 4 * np.pi, 5 * np.pi), (r'$0$', r'$\\pi$',", "zorder=1) plt.plot(symmetry_axis_2_time, symmetry_axis, 'r--', label=textwrap.fill('Axes of symmetry', 10), zorder=1) plt.text(5.1", "np.linspace(-1.8 - width, -1.8 + width, 101) min_2_y_time = minima_x[-2]", "* np.pi, 1001) pseudo_alg_time_series = np.sin(pseudo_alg_time) + np.sin(5 * pseudo_alg_time)", "1 - i_left): int(len(lsq_signal) - 1 - i_left + neural_network_k)],", "2) - 0.1, 100), -2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time_extended[-1001] +", "b_spline_basis[3, :].T, '--', label='Basis 2') axs[0].plot(time, b_spline_basis[4, :].T, '--', label='Basis", "np.abs(maxima_x[-2] - minima_x[-2]) P1 = 2 * np.abs(maxima_x[-1] - minima_x[-1])", "6 t = np.linspace(5, 95, 100) signal_orig = np.cos(2 *", "10)) plt.scatter(no_anchor_max_time, no_anchor_max, c='gray', zorder=4, label=textwrap.fill('Symmetric maxima', 10)) plt.xlim(3.9 *", "plt.xticks([0, 50, 100, 150]) plt.yticks([0, 0.1, 0.2]) plt.ylabel('Frequency (Hz)') plt.xlabel('Time", "-0.05, 'L') plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b',", "method more clear time_series[time >= minima_x[-1]] = 1.5 * (time_series[time", "c='darkblue', zorder=4, label=textwrap.fill('Optimal minima', 10)) plt.scatter(inflection_x, inflection_y, c='magenta', zorder=4, label=textwrap.fill('Inflection", "Duffing - top pyemd = pyemd0215() py_emd = pyemd(x) IP,", "plt.subplots(2, 2) plt.subplots_adjust(hspace=0.5) axs[0, 0].plot(time, signal) axs[0, 1].plot(time, signal) axs[0,", "- bottom knots = np.linspace(time[0], time[-1], 200) emd_example = AdvEMDpy.EMD(time=time,", "max_gradient_vector weights += adjustment # test - bottom weights_right =", "box_0.y0, box_0.width * 0.85, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_symmetry_anti.png')", "- maxima_x[-1]) slope_based_minimum_time = minima_x[-1] + (minima_x[-1] - minima_x[-2]) slope_based_minimum", "'--', label='emd 0.3.3') print(f'emd driving function error: {np.round(sum(abs(0.1 * np.cos(0.04", "- width, minima_y[-1] + width, 101) min_dash_2 = np.linspace(minima_y[-2] -", "maximum', 10)) plt.scatter(Huang_min_time, Huang_min, c='lime', zorder=4, label=textwrap.fill('Huang minimum', 10)) plt.scatter(Coughlin_max_time,", "- width, point_1 * np.pi + width, 101) length_top =", "axs[0].plot(5 * np.ones(100), np.linspace(-0.2, 0.8, 100), 'k-') axs[0].plot(6 * np.ones(100),", "left') axs[0].plot(5 * np.ones(100), np.linspace(-0.2, 0.8, 100), 'k-') axs[0].plot(6 *", "y = y / (2 * np.pi) z_min, z_max =", "bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Schoenberg_Whitney_Conditions.png') plt.show() # plot 7 a = 0.25", "2 * np.pi]) axs[1].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2 and Uniform", "r'$\\pi$', r'$2\\pi$', r'$3\\pi$', r'$4\\pi$']) plt.ylabel(r'Frequency (rad.s$^{-1}$)') plt.xlabel('Time (s)') box_0 =", "1.55 * np.pi, 101), -5.5 * np.ones(101), 'k--') axs[1].plot(0.95 *", "Dioxide - top pyemd = pyemd0215() py_emd = pyemd(signal) IP,", "12, 'hilbert') print(f'emd annual frequency error: {np.round(sum(np.abs(IF - np.ones_like(IF)))[0], 3)}')", "axs = plt.subplots(3, 1) plt.suptitle(textwrap.fill('Comparison of Trends Extracted with Different", ":] utils = emd_utils.Utility(time=time[:-1], time_series=imf_1_of_derivative) optimal_maxima = np.r_[False, utils.derivative_forward_diff() <", "101) max_2_y_time = maxima_x[-2] * np.ones_like(max_2_y) min_2_y = np.linspace(minima_y[-2] -", "np.linspace(slope_based_minimum - width, slope_based_minimum + width, 101) dash_4_time = np.linspace(slope_based_maximum_time,", "fig, ax = plt.subplots() figure_size = plt.gcf().get_size_inches() factor = 0.8", "plt.gcf().subplots_adjust(bottom=0.15) axs[0, 0].set_title(r'Original CO$_2$ Concentration') axs[0, 1].set_title('Smoothed CO$_2$ Concentration') axs[1,", "* 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht_emd.png') plt.show() # compare", "maxima_y[-1], 101) dash_max_min_1_x_time = 5.4 * np.pi * np.ones_like(dash_max_min_1_x) max_1_y", "- 1) + 1 + i_right)], 1))) i_right += 1", "c='darkblue', label=textwrap.fill('EMD envelope', 10)) plt.plot(time, minima_envelope, c='darkblue') plt.plot(time, (maxima_envelope +", "# backward <- P = np.zeros((int(neural_network_k + 1), neural_network_m)) for", "emd040.spectra.frequency_transform(py_emd[:2, :].T, 12, 'hilbert') print(f'PyEMD annual frequency error: {np.round(sum(np.abs(IF[:, 0]", "= max_discard * np.ones_like(max_discard_dash_time) dash_2_time = np.linspace(minima_x[-1], max_discard_time, 101) dash_2", "min_1_x, 'k-') plt.plot(min_1_x_time_side, min_1_x, 'k-') plt.plot(dash_max_min_1_x_time, dash_max_min_1_x, 'k--') plt.text(5.42 *", "* np.ones(100), c='gray') plt.plot(((time_extended[-1001] + time_extended[-1000]) / 2) * np.ones(100),", "axs[0].set_title('Preprocess Smoothing Demonstration') axs[1].set_title('Zoomed Region') axs[0].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[0].plot(pseudo_alg_time, pseudo_alg_time_series,", "time) knots = np.linspace(0, 5 * np.pi, 51) fluc =", "c='k') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1002]) / 2), ((time_extended[-1001] + time_extended[-1002]) /", "= ax.get_position() ax.set_position([box_0.x0, box_0.y0, box_0.width * 0.85, box_0.height]) ax.legend(loc='center left',", "* np.pi, (5 - a) * np.pi, 101)) + np.cos(5", "= minima_y[-2] * np.ones_like(min_2_x_time) dash_max_min_2_x = np.linspace(minima_y[-2], maxima_y[-2], 101) dash_max_min_2_x_time", "axs[0].set_xlim([0, 150]) axs[1].plot(t, dxdt) axs[1].set_title('Duffing Equation Velocity') axs[1].set_ylim([-1.5, 1.5]) axs[1].set_xlim([0,", "* ts)] t = np.linspace(0, 150, 1501) XY0 = [1,", "3 * np.pi, 4 * np.pi, 5 * np.pi]) axs[1].set_xticklabels(['',", "12)) plt.plot(((time[-302] + time[-301]) / 2) * np.ones(100), np.linspace(-2.75, 2.75,", "{np.round(sum(np.abs(IF - np.ones_like(IF)))[0], 3)}') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 2, 100)", "max_2_x, 'k-') plt.plot(min_2_x_time, min_2_x, 'k-') plt.plot(min_2_x_time_side, min_2_x, 'k-') plt.plot(dash_max_min_2_x_time, dash_max_min_2_x,", "{np.round(np.var(time_series - imfs_51[3, :]), 3)}') for knot in knots_11: axs[2].plot(knot", "plt.plot(time_extended, time_series_extended, c='g', zorder=1, label=textwrap.fill('Extrapolated signal', 12)) plt.scatter(maxima_time, maxima, c='r',", "3) axs[1].set_yticks(ticks=[-2, 0, 2]) axs[1].set_xticks(ticks=[np.pi]) axs[1].set_xticklabels(labels=[r'$\\pi$']) box_0 = axs[0].get_position() axs[0].set_position([box_0.x0", "maxima_x[-2]] - time_series[time == maxima_x[-2]]) + maxima_y[-1] Coughlin_time = Huang_time", "ax.plot(x_hs[0, :], 2 * np.ones_like(x_hs[0, :]), '--', label=r'$\\omega = 2$',", "= signal_orig[util_nn.max_bool_func_1st_order_fd()] minima = signal_orig[util_nn.min_bool_func_1st_order_fd()] cs_max = CubicSpline(t[util_nn.max_bool_func_1st_order_fd()], maxima) cs_min", "axs[0].set_ylim([-2, 2]) axs[0].set_xlim([0, 150]) axs[1].plot(t, emd_duff[2, :], label='AdvEMDpy') print(f'AdvEMDpy driving", "axs[1].set_title('Duffing Equation Velocity') axs[1].set_ylim([-1.5, 1.5]) axs[1].set_xlim([0, 150]) axis = 0", "0.5)) plt.savefig('jss_figures/CO2_Hilbert_pyemd.png') plt.show() emd_sift = emd040.sift.sift(signal) IP, IF, IA =", "c='gray') plt.plot(np.linspace(((time[-202] + time[-201]) / 2), ((time[-202] + time[-201]) /", "(5 - a) * np.pi, 11) time_series = np.cos(time) +", "plt.yticks(ticks=[-2, -1, 0, 1, 2]) plt.xticks(ticks=[0, np.pi, 2 * np.pi],", "[xy[1], xy[0] - epsilon * xy[0] ** 3 + gamma", "t / 25) + 0.5 * np.sin(2 * np.pi *", "average envelope', 10)) plt.plot(time, np.cos(time), c='black', label='True mean') plt.xticks((0, 1", "freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 2, 100) hht = emd040.spectra.hilberthuang(IF, IA,", "= np.linspace(minima_y[-1], slope_based_maximum, 101) s2 = (minima_y[-1] - maxima_y[-1]) /", "plt.show() # Carbon Dioxide Concentration Example CO2_data = pd.read_csv('Data/co2_mm_mlo.csv', header=51)", "imfs_31[2, :], label='IMF 2 with 31 knots') axs[2].plot(time, imfs_51[3, :],", "Equation Displacement') axs[0].set_ylim([-2, 2]) axs[0].set_xlim([0, 150]) axs[1].plot(t, dxdt) axs[1].set_title('Duffing Equation", "axs[1].plot(t, dxdt) axs[1].set_title('Duffing Equation Velocity') axs[1].set_ylim([-1.5, 1.5]) axs[1].set_xlim([0, 150]) axis", "np.pi, 2 * np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots[0] * np.ones(101),", "imfs_51[2, :] + imfs_51[3, :], label=textwrap.fill('Sum of IMF 2 and", "= time_reflect[anti_max_bool] anti_max_point = time_series_anti_reflect[anti_max_bool] utils = emd_utils.Utility(time=time, time_series=time_series_reflect) no_anchor_max_time", "\\tau_1 $']) plt.xlim(4.4, 6.6) plt.plot(5 * np.ones(100), np.linspace(-0.2, 1.2, 100),", "time_series=time_series_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))]) if sum(emd_utils_max.max_bool_func_1st_order_fd()) > 0: max_count_left", "0], '--', label='emd 0.3.3') axs[0].set_title('IMF 1') axs[0].set_ylim([-2, 2]) axs[0].set_xlim([0, 150])", "\\ sum(weights_right * np.hstack((time_series_extended[ int(2 * (len(lsq_signal) - 1) +", "weights_right = np.hstack((weights, 0)) max_count_right = 0 min_count_right = 0", "(s)') box_0 = ax.get_position() ax.set_position([box_0.x0, box_0.y0 + 0.05, box_0.width *", "emd040.spectra.hilberthuang(IF, IA, freq_edges) hht = gaussian_filter(hht, sigma=1) ax = plt.subplot(111)", "'k-') plt.plot(min_1_x_time_side, min_1_x, 'k-') plt.plot(dash_max_min_1_x_time, dash_max_min_1_x, 'k--') plt.text(5.42 * np.pi,", "np.pi + width, 101) max_2_x = maxima_y[-2] * np.ones_like(max_2_x_time) min_2_x_time", "- 1) + 1): int(2 * (len(lsq_signal) - 1) +", "plt.xlim(3.4 * np.pi, 5.6 * np.pi) plt.xticks((4 * np.pi, 5", "ax = plt.subplot(111) figure_size = plt.gcf().get_size_inches() factor = 1.0 plt.gcf().set_size_inches((figure_size[0],", "= 1 # for additive constant t = lsq_signal[:neural_network_m] vx", "= pd.read_csv('Data/co2_mm_mlo.csv', header=51) plt.plot(CO2_data['month'], CO2_data['decimal date']) plt.title(textwrap.fill('Mean Monthly Concentration of", "np.linspace(minima_y[-2], maxima_y[-2], 101) dash_max_min_2_x_time = 5.3 * np.pi * np.ones_like(dash_max_min_2_x)", "at Boundary') plt.plot(time[500:], b_spline_basis[2, 500:].T, '--', label=r'$ B_{-3,4}(t) $') plt.plot(time[500:],", "i_right += 1 if i_right > 1: emd_utils_max = \\", "+ minima_x[-1] max_discard_dash_time = np.linspace(max_discard_time - width, max_discard_time + width,", "_, _ = \\ emd_example.empirical_mode_decomposition(knots=knots, knot_time=time, verbose=False) print(f'AdvEMDpy annual frequency", "'--', label=r'$ B_{-2,4}(t) $') plt.plot(time[500:], b_spline_basis[4, 500:].T, '--', label=r'$ B_{-1,4}(t)", "'k--') plt.plot(length_distance_time, length_distance, 'k--') plt.plot(length_distance_time_2, length_distance_2, 'k--') plt.plot(length_time, length_top, 'k-')", "axs = plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Statically", "time_extended[-1000]) / 2) - 0.1, 100), 2.75 * np.ones(100), c='gray')", "3)}') axs[1].plot(t, py_emd[1, :], '--', label='PyEMD 0.2.10') print(f'PyEMD driving function", "* np.pi, 1.15 * np.pi) axs[1].set_ylim(-3, 3) axs[1].set_yticks(ticks=[-2, 0, 2])", "-2.2, r'$\\frac{p_2}{2}$') plt.plot(max_1_x_time, max_1_x, 'k-') plt.plot(max_1_x_time_side, max_1_x, 'k-') plt.plot(min_1_x_time, min_1_x,", "0.85, box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].plot(time, time_series, label='Time", "minima_y[-1] + width, 101) min_dash_2 = np.linspace(minima_y[-2] - width, minima_y[-2]", "2) + 0.1, 100), -2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time[-202] +", "and Dynamically Optimised Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2, zorder=100) axs[0].set_yticks(ticks=[-2, 0,", "order=21, increment=20)[0] derivative_of_lsq = utils.derivative_forward_diff() derivative_time = time[:-1] derivative_knots =", "zorder=4, label=textwrap.fill('Huang maximum', 10)) plt.scatter(Huang_min_time, Huang_min, c='lime', zorder=4, label=textwrap.fill('Huang minimum',", "1, len(time_series)) time_series += noise advemdpy = EMD(time=time, time_series=time_series) imfs_51,", "1) plt.subplots_adjust(hspace=0.2) axs[0].plot(t, x) axs[0].set_title('Duffing Equation Displacement') axs[0].set_ylim([-2, 2]) axs[0].set_xlim([0,", "- improved_slope_based_maximum_time) min_dash_4 = np.linspace(improved_slope_based_minimum - width, improved_slope_based_minimum + width,", "dash_4 = np.linspace(slope_based_maximum, slope_based_minimum) maxima_dash = np.linspace(2.5 - width, 2.5", "np.linspace(maxima_y[-1], minima_y[-2], 101) s1 = (minima_y[-2] - maxima_y[-1]) / (minima_x[-2]", "- width, minima_x[-1] + width, 101) min_dash = minima_y[-1] *", "maxima, c='r', zorder=3, label='Maxima') plt.scatter(minima_time, minima, c='b', zorder=3, label='Minima') plt.scatter(maxima_extrapolate_time,", "axs[0].set_xticklabels([r'$ \\tau_k $', r'$ \\tau_{k+1} $']) axs[0].set_xlim(4.5, 6.5) axs[1].set_title('Cubic Hermite", "AdvEMDpy import EMD # alternate packages from PyEMD import EMD", "2), ((time_extended[-1001] + time_extended[-1002]) / 2) - 0.1, 100), -2.75", "from scipy.integrate import odeint from scipy.ndimage import gaussian_filter from emd_utils", "* np.cos(0.04 * 2 * np.pi * t) - py_emd[1,", "= preprocess.downsample(decimate=False) axs[0].plot(downsampled[0], downsampled[1], label=textwrap.fill('Downsampled', 13)) axs[0].plot(np.linspace(0.85 * np.pi, 1.15", "= CO2_data['decimal date'] signal = np.asarray(signal) time = CO2_data['month'] time", "utils_Coughlin.min_bool_func_1st_order_fd() Huang_max_time = Huang_time[Huang_max_bool] Huang_max = Huang_wave[Huang_max_bool] Huang_min_time = Huang_time[Huang_min_bool]", "+ 0.0125, box_0.y0 + 0.075, box_0.width * 0.8, box_0.height *", ":], Linewidth=2, zorder=100) axs[2].set_yticks(ticks=[-2, 0, 2]) axs[2].set_xticks(ticks=[0, np.pi, 2 *", "14)) plt.plot(Coughlin_time, Coughlin_wave, '--', c='darkgreen', label=textwrap.fill('Coughlin Characteristic Wave', 14)) plt.plot(max_2_x_time,", "col)):(-(neural_network_m - col))] P[-1, col] = 1 # for additive", "width, 101) min_dash_time_1 = minima_x[-1] * np.ones_like(min_dash_1) min_dash_time_2 = minima_x[-2]", "- 1 - i_left):int(len(lsq_signal))], time_series=time_series_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))]) if", "= 0.2 time = np.linspace(0, (5 - a) * np.pi,", "minima_y[-1]) / 2 P2 = 2 * np.abs(maxima_x[-2] - minima_x[-2])", "knots', 19)) print(f'DFA fluctuation with 31 knots: {np.round(np.var(time_series - (imfs_31[1,", "min_count_right += 1 # backward <- P = np.zeros((int(neural_network_k +", "- 0.05, box_0.y0, box_0.width * 0.95, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1,", "= 5.4 * np.pi * np.ones_like(dash_max_min_1_x) max_1_y = np.linspace(maxima_y[-1] -", "0.3.3') print(f'emd driving function error: {np.round(sum(abs(0.1 * np.cos(0.04 * 2", "* np.ones(101), 'k--') axs[1].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101),", "'--', label='PyEMD 0.2.10') print(f'PyEMD driving function error: {np.round(sum(abs(0.1 * np.cos(0.04", "maxima_dash, 'k-') plt.plot(minima_dash_time_1, minima_dash, 'k-') plt.plot(minima_dash_time_2, minima_dash, 'k-') plt.plot(minima_dash_time_3, minima_dash,", "$']) axs[1].set_xlim(4.5, 6.5) plt.savefig('jss_figures/comparing_bases.png') plt.show() # plot 3 a =", "using PyEMD 0.2.10', 40)) plt.pcolormesh(t, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht))))", "- 1) + 1 + i_right + 1)], time_series=time_series_extended[int(2 *", "emd_ht_duff, emd_if_duff, max_frequency=1.3, plot=False) ax = plt.subplot(111) plt.title(textwrap.fill('Gaussian Filtered Hilbert", "np.cos(time), c='black', label='True mean') plt.xticks((0, 1 * np.pi, 2 *", "width, 101) max_dash_time_1 = maxima_x[-1] * np.ones_like(max_dash_1) max_dash_time_2 = maxima_x[-2]", "plt.plot(maxima_dash_time_3, maxima_dash, 'k-') plt.plot(minima_dash_time_1, minima_dash, 'k-') plt.plot(minima_dash_time_2, minima_dash, 'k-') plt.plot(minima_dash_time_3,", "dash_1 = np.linspace(maxima_y[-1], minima_y[-1], 101) max_discard = maxima_y[-1] max_discard_time =", "cs_min = CubicSpline(t[util_nn.min_bool_func_1st_order_fd()], minima) time = np.linspace(0, 5 * np.pi,", "= \\ 2 * sum(weights_left * np.hstack((time_series_extended[int(len(lsq_signal) - 1 -", "minima, c='b', zorder=3, label='Minima') plt.scatter(maxima_extrapolate_time, maxima_extrapolate, c='magenta', zorder=3, label=textwrap.fill('Extrapolated maxima',", "label='Knots') axs[2].set_xticks([0, np.pi, 2 * np.pi, 3 * np.pi, 4", "(1) detrended_fluctuation_technique and (2) max_internal_iter and (3) debug (confusing with", "of IMF 2 and IMF 3 with 51 knots', 19))", "maxima_x[-1] * np.ones_like(max_1_y) min_1_y = np.linspace(minima_y[-1] - width, minima_y[-1] +", "+ width, 101) min_dash_time_4 = improved_slope_based_minimum_time * np.ones_like(min_dash_4) dash_final_time =", "time_series[optimal_minima], c='darkblue', zorder=4, label=textwrap.fill('Optimal minima', 10)) plt.scatter(inflection_x, inflection_y, c='magenta', zorder=4,", "* np.pi, 5.6 * np.pi) plt.xticks((4 * np.pi, 5 *", "np.pi, 4 * np.pi, 5 * np.pi]) axs[1].set_xticklabels(['', '', '',", "maxima_dash_time_2 = maxima_x[-1] * np.ones_like(maxima_dash) maxima_dash_time_3 = slope_based_maximum_time * np.ones_like(maxima_dash)", "* time) noise = np.random.normal(0, 1, len(time_series)) time_series += noise", "in axs.flat: ax.label_outer() if axis == 0: ax.set_ylabel('x(t)') ax.set_yticks(y_points_1) if", ":]) axis = 0 for ax in axs.flat: if axis", "box_1.width * 0.85, box_1.height]) axs[1].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].plot(np.linspace(0.95", "dash_max_min_2_x_time = 5.3 * np.pi * np.ones_like(dash_max_min_2_x) max_2_y = np.linspace(maxima_y[-2]", "axs[1].plot(1.55 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--', label='Zoomed", "= plt.gcf().get_size_inches() factor = 0.9 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10)", "c='cyan', zorder=4, label=textwrap.fill('Average minimum', 14)) plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima')", "* np.ones(101), np.linspace(-3.0, -2.0, 101), '--', c='grey', zorder=1) plt.plot(knots[-1] *", "ax.label_outer() if axis == 0: ax.set_ylabel(r'$\\gamma_1(t)$') ax.set_yticks([-2, 0, 2]) if", "box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/pseudo_algorithm.png') plt.show() knots = np.arange(12)", "* np.pi), (r'4$\\pi$', r'5$\\pi$')) plt.yticks((-3, -2, -1, 0, 1, 2),", "+ width, 101) min_2_y_time = minima_x[-2] * np.ones_like(min_2_y) dash_max_min_2_y_time =", "improved_slope_based_maximum + s2 * (improved_slope_based_minimum_time - improved_slope_based_maximum_time) min_dash_4 = np.linspace(improved_slope_based_minimum", ":]), '--', label=r'$\\omega = 2$', Linewidth=3) ax.set_xticks([0, np.pi, 2 *", "\\ emd_utils.Utility(time=time_extended[int(2 * (len(lsq_signal) - 1) + 1): int(2 *", "* 0.75, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht.png')", "Average_min_time = minima_x[-1] + (minima_x[-1] - minima_x[-2]) Average_min = (minima_y[-2]", "= np.linspace(-1.8 - width, -1.8 + width, 101) max_2_y_time =", "- a) * np.pi, 101)) + np.cos(5 * np.linspace((5 -", "== 1, False] optimal_minima = np.r_[False, utils.derivative_forward_diff() > 0, False]", "= emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=2, verbose=False) fig, axs = plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6)", "plt from scipy.integrate import odeint from scipy.ndimage import gaussian_filter from", "0.6 * np.cos(2 * np.pi * t / 25) +", "box_0.y0, box_0.width * 0.85, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8)", "c='g', zorder=1, label=textwrap.fill('Extrapolated signal', 12)) plt.scatter(maxima_time, maxima, c='r', zorder=3, label='Maxima')", "time) + np.cos(4 * time) + np.cos(8 * time) noise", "plt.plot(min_dash_time_3, min_dash_3, 'k-') plt.plot(min_dash_time_4, min_dash_4, 'k-') plt.plot(maxima_dash_time_1, maxima_dash, 'k-') plt.plot(maxima_dash_time_2,", "100), c='gray', linestyle='dashed') plt.xlim(3.4 * np.pi, 5.6 * np.pi) plt.xticks((4", "filter', 13)) axs[0].plot(preprocess_time, preprocess.winsorize(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize filter', 12)) axs[0].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window,", "emd_utils import numpy as np import pandas as pd import", "minima_x[-1] * np.ones(101) symmetry_axis_2_time = time[-1] * np.ones(101) symmetry_axis =", "B_{-2,4}(t) $') plt.plot(time[500:], b_spline_basis[4, 500:].T, '--', label=r'$ B_{-1,4}(t) $') plt.plot(time[500:],", "+ (minima_y[-1] - minima_y[-2]), r'$s_1$') plt.text(4.43 * np.pi + (slope_based_minimum_time", "CubicSpline(t[util_nn.min_bool_func_1st_order_fd()], minima) time = np.linspace(0, 5 * np.pi, 1001) lsq_signal", "2 P2 = 2 * np.abs(maxima_x[-2] - minima_x[-2]) P1 =", "min_dash_4 = np.linspace(improved_slope_based_minimum - width, improved_slope_based_minimum + width, 101) min_dash_time_4", "= np.array(vx.value) max_count_left = 0 min_count_left = 0 i_left =", "r'$\\frac{p_1}{2}$') plt.xlim(3.9 * np.pi, 5.6 * np.pi) plt.xticks((4 * np.pi,", "ax in axs.flat: ax.label_outer() if axis == 0: ax.set_ylabel('x(t)') ax.set_yticks(y_points_1)", "hht = gaussian_filter(hht, sigma=1) ax = plt.subplot(111) figure_size = plt.gcf().get_size_inches()", "label=r'$\\tilde{h}_{(1,0)}^M(t)$', zorder=4) plt.scatter(pseudo_alg_time[pseudo_utils.min_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.min_bool_func_1st_order_fd()], c='c', label=r'$m(t_j)$', zorder=3) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time) -", "0: min_count_right += 1 # backward <- P = np.zeros((int(neural_network_k", "time_series[-1] * np.ones_like(length_time_2) length_bottom_2 = minima_y[-1] * np.ones_like(length_time_2) symmetry_axis_1_time =", "(len(lsq_signal) - 1) + 1): int(2 * (len(lsq_signal) - 1)", "filter', 12)) axs[1].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize interpolation filter', 14)) axs[1].plot(preprocess_time,", "ax.set(xlabel='t') ax.set_yticks(y_points_2) ax.set_xticks(x_points) ax.set_xticklabels(x_names) axis += 1 plt.savefig('jss_figures/Duffing_equation.png') plt.show() #", "+ 1 + i_right + 1)], time_series=time_series_extended[int(2 * (len(lsq_signal) -", "width, minima_x[-1] + width, 101) min_dash = minima_y[-1] * np.ones_like(min_dash_time)", "label=r'$\\omega = 8$', Linewidth=3) ax.plot(x_hs[0, :], 4 * np.ones_like(x_hs[0, :]),", "(len(lsq_signal) - 1) + 1)] = lsq_signal neural_network_m = 200", "= pseudo_alg_time.copy() np.random.seed(1) random.seed(1) preprocess_time_series = pseudo_alg_time_series + np.random.normal(0, 0.1,", "minima_y[-2] * np.ones_like(min_2_x_time) dash_max_min_2_x = np.linspace(minima_y[-2], maxima_y[-2], 101) dash_max_min_2_x_time =", "width, 5.4 * np.pi + width, 101) max_1_x = maxima_y[-1]", "* np.pi * np.ones_like(length_distance) length_time = np.linspace(point_1 * np.pi -", "10)) plt.scatter(inflection_x, inflection_y, c='magenta', zorder=4, label=textwrap.fill('Inflection points', 10)) plt.plot(time, maxima_envelope,", "5 * np.pi, 31) imfs_31, hts_31, ifs_31 = advemdpy.empirical_mode_decomposition(knots=knots_31, max_imfs=2,", "axs[0].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[0].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time series',", "r'$3\\pi$', r'$4\\pi$', r'$5\\pi$']) box_2 = axs[2].get_position() axs[2].set_position([box_2.x0 - 0.05, box_2.y0,", "z_max = 0, np.abs(z).max() ax.pcolormesh(x_hs, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max)", "2) * np.ones(100), np.linspace(-2.75, 2.75, 100), c='gray', linestyle='dashed', label=textwrap.fill('Neural network", "np.linspace(0, 11, 1101) basis = emd_basis.Basis(time=time, time_series=time) b_spline_basis = basis.cubic_b_spline(knots)", "1].plot(time, imfs[2, :]) axis = 0 for ax in axs.flat:", "min_bool = utils.min_bool_func_1st_order_fd() minima_x = time[min_bool] minima_y = time_series[min_bool] max_dash_time", "plt.gcf().get_size_inches() factor = 1.0 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) ax.pcolormesh(x, y,", "emd_duffing.empirical_mode_decomposition(verbose=False) fig, axs = plt.subplots(2, 1) plt.subplots_adjust(hspace=0.3) figure_size = plt.gcf().get_size_inches()", "0.8, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert.png') plt.show()", "-0.15)) box_1 = axs[1].get_position() axs[1].set_position([box_1.x0 - 0.05, box_1.y0, box_1.width *", "'k-') plt.plot(min_1_x_time, min_1_x, 'k-') plt.plot(min_1_x_time_side, min_1_x, 'k-') plt.plot(dash_max_min_1_x_time, dash_max_min_1_x, 'k--')", "time_series, label='Time series') axs[2].plot(time, imfs_11[1, :], label='IMF 1 with 11", "0, 1, 2), ('-3', '-2', '-1', '0', '1', '2')) box_0", "* np.linspace((5 - 2.6 * a) * np.pi, (5 -", "np.pi, -2.5, r'$\\frac{p_1}{2}$') plt.xlim(3.9 * np.pi, 5.6 * np.pi) plt.xticks((4", "= np.linspace(minima_y[-1] - width, minima_y[-1] + width, 101) min_1_y_side =", "= minima_x[-1] - maxima_x[-1] + minima_x[-1] max_discard_dash_time = np.linspace(max_discard_time -", ":], np.ones_like(x_hs[0, :]), 'k--', label=textwrap.fill('Annual cycle', 10)) ax.axis([x_hs.min(), x_hs.max(), y.min(),", "IF, IA = emd040.spectra.frequency_transform(emd_sift, 10, 'hilbert') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0,", "r'$s_2$') plt.text(4.30 * np.pi + (minima_x[-1] - minima_x[-2]), 0.35 +", "np.pi, 1.55 * np.pi) plt.savefig('jss_figures/DFA_different_trends_zoomed.png') plt.show() hs_ouputs = hilbert_spectrum(time, imfs_51,", "+= 1 if i_left > 1: emd_utils_max = \\ emd_utils.Utility(time=time_extended[int(len(lsq_signal)", "_, _ = emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=2, verbose=False) fig, axs = plt.subplots(3,", "slope_based_minimum = slope_based_maximum - (slope_based_maximum_time - slope_based_minimum_time) * s2 min_dash_time_3", "lr * average_gradients # adjustment = - lr * max_gradient_vector", "r'$2\\pi$']) axs[1].set_title('IMF 1 and Dynamically Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2,", "'k-') plt.plot(minima_dash_time_2, minima_dash, 'k-') plt.plot(minima_dash_time_3, minima_dash, 'k-') plt.text(4.34 * np.pi,", "Linewidth=3) ax.plot(x_hs[0, :], 4 * np.ones_like(x_hs[0, :]), '--', label=r'$\\omega =", "plt.suptitle(textwrap.fill('Comparison of Trends Extracted with Different Knot Sequences Zoomed Region',", "Fluctuation Analysis Examples') plt.plot(time, time_series, LineWidth=2, label='Time series') plt.scatter(maxima_x, maxima_y,", "Network Example') plt.plot(time, lsq_signal, zorder=2, label='Signal') plt.plot(time_extended, time_series_extended, c='g', zorder=1,", "np.linspace(-2, 2, 101), '--', c='grey') plt.savefig('jss_figures/knot_1.png') plt.show() # plot 1c", "* a) * np.pi, (5 - a) * np.pi, 101)))", "* 0.85, box_1.height]) axs[1].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].set_ylim(-5.5, 5.5)", "axs[2].plot(time, imfs_51[3, :], label='IMF 3 with 51 knots') print(f'DFA fluctuation", ":], 8 * np.ones_like(x_hs[0, :]), '--', label=r'$\\omega = 8$', Linewidth=3)", "with 51 knots', 19)) print(f'DFA fluctuation with 31 knots: {np.round(np.var(time_series", "1 * np.pi, 2 * np.pi, 3 * np.pi, 4", ":]), '--', label=r'$\\omega = 8$', Linewidth=3) ax.plot(x_hs[0, :], 4 *", "* np.ones_like(min_dash_1) min_dash_3 = np.linspace(slope_based_minimum - width, slope_based_minimum + width,", "= np.zeros_like(time_extended) / 0 time_series_extended[int(len(lsq_signal) - 1):int(2 * (len(lsq_signal) -", "np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1, label='Knots') axs[2].set_xticks([0, np.pi,", "minima_y, c='b', zorder=4, label='Minima') plt.scatter(time[optimal_maxima], time_series[optimal_maxima], c='darkred', zorder=4, label=textwrap.fill('Optimal maxima',", "np.pi, (5 - a) * np.pi, 101)) + np.cos(5 *", "* np.pi, 101))) time_series_anti_reflect = time_series_reflect[0] - time_series_reflect utils =", "_ = emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=2, verbose=False) fig, axs = plt.subplots(3, 1)", "= (P1 / P2) * (time[time >= maxima_x[-2]] - time[time", "axs[0].set_ylim([-2, 2]) axs[0].set_xlim([0, 150]) axs[1].plot(t, dxdt) axs[1].set_title('Duffing Equation Velocity') axs[1].set_ylim([-1.5,", "2]) axs[1].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[1].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF", "/ 2) - 0.1, 100), -2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time_extended[-1001]", "12)) axs[0].plot(preprocess_time, preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker smoothing', 13)) downsampled_and_decimated = preprocess.downsample() axs[0].plot(downsampled_and_decimated[0],", "_, _, _, _ = \\ emd_example.empirical_mode_decomposition(knots=knots, knot_time=time, verbose=False) print(f'AdvEMDpy", "'k-') plt.plot(min_dash_time_4, min_dash_4, 'k-') plt.plot(maxima_dash_time_1, maxima_dash, 'k-') plt.plot(maxima_dash_time_2, maxima_dash, 'k-')", "plt.savefig('jss_figures/DFA_different_trends.png') plt.show() # plot 6b fig, axs = plt.subplots(3, 1)", "x) axs[0].set_title('Duffing Equation Displacement') axs[0].set_ylim([-2, 2]) axs[0].set_xlim([0, 150]) axs[1].plot(t, dxdt)", "= 5.3 * np.pi * np.ones_like(dash_max_min_2_x) max_2_y = np.linspace(maxima_y[-2] -", "import EMD # alternate packages from PyEMD import EMD as", "bbox_to_anchor=(1, 0.5), fontsize=8) axs[0].set_ylim(-5.5, 5.5) axs[0].set_xlim(0.95 * np.pi, 1.55 *", "= np.sin(pseudo_alg_time) + np.sin(5 * pseudo_alg_time) pseudo_utils = Utility(time=pseudo_alg_time, time_series=pseudo_alg_time_series)", "np.pi, 5.5 * np.pi) plt.xticks((4 * np.pi, 5 * np.pi),", "minima_line_dash = -3.4 * np.ones_like(minima_line_dash_time) # slightly edit signal to", "plt.plot(dash_max_min_2_x_time, dash_max_min_2_x, 'k--') plt.text(5.16 * np.pi, 0.85, r'$2a_2$') plt.plot(max_2_y_time, max_2_y,", "label='IMF 3 with 51 knots') print(f'DFA fluctuation with 11 knots:", "min_smoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima', smooth=True) util = Utility(time=time, time_series=time_series) maxima", "binomial_points_envelope = fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True, smoothing_penalty=0.2, technique='binomial_average', order=21, increment=20)[0] derivative_of_lsq =", "min_bool = utils.min_bool_func_1st_order_fd() minima_x = time[min_bool] minima_y = time_series[min_bool] max_dash_1", "dash_max_min_1_y, 'k--') plt.text(4.48 * np.pi, -2.5, r'$\\frac{p_1}{2}$') plt.xlim(3.9 * np.pi,", "101) s2 = (minima_y[-1] - maxima_y[-1]) / (minima_x[-1] - maxima_x[-1])", "np.pi + (slope_based_minimum_time - minima_x[-1]), 1.20 + (slope_based_minimum - minima_y[-1]),", "time_series=signal) imfs, hts, ifs, _, _, _, _ = \\", "sns.set(style='darkgrid') pseudo_alg_time = np.linspace(0, 2 * np.pi, 1001) pseudo_alg_time_series =", "dash_max_min_2_y, 'k--') plt.text(4.08 * np.pi, -2.2, r'$\\frac{p_2}{2}$') plt.plot(max_1_x_time, max_1_x, 'k-')", "from emd_preprocess import Preprocess from emd_mean import Fluctuation from AdvEMDpy", "'k-') plt.plot(max_2_x_time_side, max_2_x, 'k-') plt.plot(min_2_x_time, min_2_x, 'k-') plt.plot(min_2_x_time_side, min_2_x, 'k-')", "width, 101) min_dash_time_4 = improved_slope_based_minimum_time * np.ones_like(min_dash_4) dash_final_time = np.linspace(improved_slope_based_maximum_time,", "# ________ # / # \\ / # \\ /", "= emd040.spectra.define_hist_bins(0, 2, 100) hht = emd040.spectra.hilberthuang(IF, IA, freq_edges) hht", "maxima_x[-1] + width, 101) max_dash = maxima_y[-1] * np.ones_like(max_dash_time) min_dash_time", "box_0.width * 0.85, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))", "# for additive constant t = lsq_signal[:neural_network_m] vx = cvx.Variable(int(neural_network_k", "axs[0].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1, label='Knots')", "max_1_x_time_side = np.linspace(5.4 * np.pi - width, 5.4 * np.pi", "c='darkred', zorder=4, label=textwrap.fill('Optimal maxima', 10)) plt.scatter(time[optimal_minima], time_series[optimal_minima], c='darkblue', zorder=4, label=textwrap.fill('Optimal", "2, 101), '--', c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots_uniform[0] * np.ones(101),", "c='gray', linestyle='dashed') plt.xlim(3.4 * np.pi, 5.6 * np.pi) plt.xticks((4 *", "0.05, box_0.y0, box_0.width * 0.85, box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, 0.5),", "plt.text(4.50 * np.pi, 2, r'$\\Delta{t^{max}_{M}}$') plt.text(4.30 * np.pi, 0.35, r'$s_1$')", "np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--', label='Zoomed region') box_0 = axs[0].get_position()", "np.ones(101), 'k--') axs[0].plot(0.95 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101),", "minima envelope', 10), c='blue') for knot in knots[:-1]: plt.plot(knot *", "(r'4$\\pi$', r'5$\\pi$')) plt.yticks((-2, -1, 0, 1, 2), ('-2', '-1', '0',", "plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1000]) / 2), ((time_extended[-1001] + time_extended[-1000]) / 2)", "= emd040.spectra.frequency_transform(py_emd[:2, :].T, 12, 'hilbert') print(f'PyEMD annual frequency error: {np.round(sum(np.abs(IF[:,", "Huang_time = (P1 / P2) * (time[time >= maxima_x[-2]] -", "= np.linspace(-2, 2, 101) end_time = np.linspace(time[-1] - width, time[-1]", "neural_network_m = 200 neural_network_k = 100 # forward -> P", "knot_demonstrate_time_series = np.sin(knot_demonstrate_time) + np.sin(5 * knot_demonstrate_time) knots_uniform = np.linspace(0,", "/ (minima_x[-1] - maxima_x[-1]) slope_based_minimum_time = minima_x[-1] + (minima_x[-1] -", "c='orange', zorder=4, label=textwrap.fill('Symmetric Anchor maxima', 10)) plt.scatter(anti_max_point_time, anti_max_point, c='green', zorder=4,", "axs[1].plot(knots[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[2].plot(knots[0]", "* pseudo_alg_time) pseudo_utils = Utility(time=pseudo_alg_time, time_series=pseudo_alg_time_series) # plot 0 -", "factor = 0.7 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) ax.pcolormesh(x_hs, y, np.abs(z),", "10)) plt.scatter(end_point_time, end_point, c='orange', zorder=4, label=textwrap.fill('Symmetric Anchor maxima', 10)) plt.scatter(anti_max_point_time,", "i_left += 1 if i_left > 1: emd_utils_max = \\", "label='Knots') for i in range(3): for j in range(1, len(knots)):", "maxima_extrapolate = time_series_extended[utils_extended.max_bool_func_1st_order_fd()][-1] maxima_extrapolate_time = time_extended[utils_extended.max_bool_func_1st_order_fd()][-1] minima = lsq_signal[lsq_utils.min_bool_func_1st_order_fd()] minima_time", "* np.ones_like(x_hs[0, :]), '--', label=r'$\\omega = 2$', Linewidth=3) ax.set_xticks([0, np.pi,", "-1.8 + width, 101) min_2_y_time = minima_x[-2] * np.ones_like(min_2_y) dash_max_min_2_y_time", "1), neural_network_m)) for col in range(neural_network_m): P[:-1, col] = lsq_signal[int(col", "plt.scatter(inflection_x, inflection_y, c='magenta', zorder=4, label=textwrap.fill('Inflection points', 10)) plt.plot(time, maxima_envelope, c='darkblue',", "series', 12)) axs[0].plot(preprocess_time, preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott smoothing', 12)) axs[0].plot(preprocess_time, preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker", "-2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1000]) / 2), ((time_extended[-1001]", ":], label='Smoothed') axs[0, 1].legend(loc='lower right') axs[1, 0].plot(time, imfs[1, :]) axs[1,", "z_max = 0, np.abs(z).max() fig, ax = plt.subplots() figure_size =", "= time_series[min_bool] inflection_bool = utils.inflection_point() inflection_x = time[inflection_bool] inflection_y =", "np.ones_like(length_time_2) symmetry_axis_1_time = minima_x[-1] * np.ones(101) symmetry_axis_2_time = time[-1] *", "* (time_series[time >= minima_x[-1]] - time_series[time == minima_x[-1]]) + \\", "label=r'$ B_{-3,4}(t) $') plt.plot(time[500:], b_spline_basis[3, 500:].T, '--', label=r'$ B_{-2,4}(t) $')", "imfs_51[2, :] + imfs_51[3, :], label=textwrap.fill('Sum of IMF 1, IMF", "symmetry_axis, 'r--', label=textwrap.fill('Axes of symmetry', 10), zorder=1) plt.text(5.1 * np.pi,", "= minima_x[-1] * np.ones_like(minima_dash) minima_dash_time_3 = slope_based_minimum_time * np.ones_like(minima_dash) minima_line_dash_time", "min_bool = utils.min_bool_func_1st_order_fd() minima_x = time[min_bool] minima_y = time_series[min_bool] inflection_bool", "np.pi, 1.55 * np.pi, 101), 5.5 * np.ones(101), 'k--') axs[1].plot(np.linspace(0.95", "$') plt.plot(time[500:], b_spline_basis[5, 500:].T, '--', label=r'$ B_{0,4}(t) $') plt.plot(time[500:], b_spline_basis[6,", "+ 0.5 * np.sin(2 * np.pi * t / 200)", "or (min_count_left < 1)) and (i_left < len(lsq_signal) - 1):", "from scipy.ndimage import gaussian_filter from emd_utils import time_extension, Utility from", "0, 2]) if axis == 1: ax.set_ylabel(r'$\\gamma_2(t)$') ax.set_yticks([-0.2, 0, 0.2])", "label='Zoomed region') plt.savefig('jss_figures/DFA_different_trends.png') plt.show() # plot 6b fig, axs =", "'--', c='black', label=textwrap.fill('Zoomed region', 10)) axs[0].plot(np.linspace(0.85 * np.pi, 1.15 *", "time[-201]) / 2) + 0.1, 100), -2.75 * np.ones(100), c='gray')", "np.pi, 1.55 * np.pi, 101), -5.5 * np.ones(101), 'k--') axs[1].plot(0.95", "i_right)], 1))) i_right += 1 if i_right > 1: emd_utils_max", "0.5 * np.sin(2 * np.pi * t / 200) util_nn", "np.pi * np.ones(101), np.linspace(-3, 3, 101), '--', c='black') axs[0].plot(1.15 *", "2.75 * np.ones(100), c='k') plt.plot(((time_extended[-1001] + time_extended[-1002]) / 2) *", "(2 * np.pi) z_min, z_max = 0, np.abs(z).max() figure_size =", "more clear time_series[time >= minima_x[-1]] = 1.5 * (time_series[time >=", "label='Minima') plt.plot(Huang_time, Huang_wave, '--', c='darkviolet', label=textwrap.fill('Huang Characteristic Wave', 14)) plt.plot(Coughlin_time,", "('-3', '-2', '-1', '0', '1', '2')) box_0 = ax.get_position() ax.set_position([box_0.x0", "- a) * np.pi, 1001) time_series = np.cos(time) + np.cos(5", "10)) plt.plot(max_dash_time, max_dash, 'k-') plt.plot(min_dash_time, min_dash, 'k-') plt.plot(dash_1_time, dash_1, 'k--')", "= utils.min_bool_func_1st_order_fd() minima_x = time[min_bool] minima_y = time_series[min_bool] max_dash_time =", "from scipy.interpolate import CubicSpline from emd_hilbert import Hilbert, hilbert_spectrum from", "- 0.5, time[-1] + 0.5, 101) anti_symmetric_signal = time_series[-1] *", "< 1) or (min_count_right < 1)) and (i_right < len(lsq_signal)", "improved_slope_based_minimum, c='dodgerblue', zorder=4, label=textwrap.fill('Improved slope-based minimum', 11)) plt.xlim(3.9 * np.pi,", "- a) * np.pi, 101))) time_series_anti_reflect = time_series_reflect[0] - time_series_reflect", "c='r', zorder=3, label='Maxima') plt.scatter(minima_time, minima, c='b', zorder=3, label='Minima') plt.scatter(maxima_extrapolate_time, maxima_extrapolate,", "and IMF 3 with 51 knots', 19)) for knot in", "other packages Carbon Dioxide - bottom knots = np.linspace(time[0], time[-1],", "2 * np.pi, 1001) knot_demonstrate_time_series = np.sin(knot_demonstrate_time) + np.sin(5 *", "axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1 and Uniform Knots') axs[1].plot(knot_demonstrate_time, imfs[1,", "freq_edges) hht = gaussian_filter(hht, sigma=1) ax = plt.subplot(111) figure_size =", "+ neural_network_k + 1)] P[-1, col] = 1 # for", "1])), 3)}') axs[1].plot(t, 0.1 * np.cos(0.04 * 2 * np.pi", "{np.round(sum(np.abs(IF[:, 0] - np.ones_like(IF[:, 0]))), 3)}') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0,", "= ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width * 0.95, box_0.height])", "(minima_y[-1] - minima_y[-2]), r'$s_1$') plt.text(4.43 * np.pi + (slope_based_minimum_time -", "= util.min_bool_func_1st_order_fd() ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title(textwrap.fill('Plot Demonstrating Unsmoothed Extrema", "np.abs(maxima_x[-1] - minima_x[-1]) Huang_time = (P1 / P2) * (time[time", "- i_left)] = \\ 2 * sum(weights_left * np.hstack((time_series_extended[int(len(lsq_signal) -", "width, time[-1] + width, 101) end_signal = time_series[-1] * np.ones_like(end_time)", "- 2.6 * a) * np.pi, (5 - a) *", "2), ((time_extended[-1001] + time_extended[-1000]) / 2) - 0.1, 100), -2.75", "plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Statically Optimised Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2,", "improved_slope_based_maximum_time = time[-1] improved_slope_based_maximum = time_series[-1] improved_slope_based_minimum_time = slope_based_minimum_time improved_slope_based_minimum", "emd_utils.Utility(time=time, time_series=Huang_wave) Huang_max_bool = utils_Huang.max_bool_func_1st_order_fd() Huang_min_bool = utils_Huang.min_bool_func_1st_order_fd() utils_Coughlin =", "slope_based_maximum, 101) s2 = (minima_y[-1] - maxima_y[-1]) / (minima_x[-1] -", "'', '', '']) box_1 = axs[1].get_position() axs[1].set_position([box_1.x0 - 0.05, box_1.y0,", "fontsize=8) axs[1].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), 5.5 *", "np.pi) plt.savefig('jss_figures/DFA_different_trends_zoomed.png') plt.show() hs_ouputs = hilbert_spectrum(time, imfs_51, hts_51, ifs_51, max_frequency=12,", "plt.plot(symmetry_axis_1_time, symmetry_axis, 'r--', zorder=1) plt.plot(anti_symmetric_time, anti_symmetric_signal, 'r--', zorder=1) plt.plot(symmetry_axis_2_time, symmetry_axis,", "ts)] t = np.linspace(0, 150, 1501) XY0 = [1, 1]", "for knot in knots_51: axs[0].plot(knot * np.ones(101), np.linspace(-5, 5, 101),", "Equation using AdvEMDpy', 40)) x, y, z = hs_ouputs y", "0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_characteristic_wave.png') plt.show() # plot", "np.linspace(-5.5, 5.5, 101), 'k--', label='Zoomed region') axs[2].plot(time, time_series, label='Time series')", "'k-') plt.text(4.34 * np.pi, -3.2, r'$\\Delta{t^{min}_{m}}$') plt.text(4.74 * np.pi, -3.2,", "left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].set_ylim(-5.5, 5.5) axs[1].set_xlim(0.95 * np.pi, 1.55", "# plot 6a np.random.seed(0) time = np.linspace(0, 5 * np.pi,", "Series and Uniform Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2, zorder=100) axs[0].set_yticks(ticks=[-2, 0,", "= np.linspace(0, 5 * np.pi, 101) time_extended = time_extension(time) time_series_extended", "axs[0].plot(knots[0][0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[0].legend(loc='lower", "+ neural_network_k)], 1))) + 1 i_left += 1 if i_left", "* np.pi) axs[1].plot(time, time_series, label='Time series') axs[1].plot(time, imfs_31[1, :] +", "np.linspace(0, 2 * np.pi, 51) emd = EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series) imfs", "* 0.85, box_2.height]) axs[2].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[2].set_ylim(-5.5, 5.5)", "max_2_x_time = np.linspace(maxima_x[-2] - width, maxima_x[-2] + width, 101) max_2_x_time_side", "y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) ax.plot(x_hs[0, :], 8 * np.ones_like(x_hs[0,", "maxima', 10)) plt.scatter(no_anchor_max_time, no_anchor_max, c='gray', zorder=4, label=textwrap.fill('Symmetric maxima', 10)) plt.xlim(3.9", "+ 1)] P[-1, col] = 1 # for additive constant", "- 0.05, box_0.y0, box_0.width * 0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1,", "1))) + 1 i_left += 1 if i_left > 1:", "= (minima_y[-2] - maxima_y[-1]) / (minima_x[-2] - maxima_x[-1]) slope_based_maximum_time =", "bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/detrended_fluctuation_analysis.png') plt.show() # Duffing Equation Example def duffing_equation(xy,", "time[lsq_utils.max_bool_func_1st_order_fd()] maxima_extrapolate = time_series_extended[utils_extended.max_bool_func_1st_order_fd()][-1] maxima_extrapolate_time = time_extended[utils_extended.max_bool_func_1st_order_fd()][-1] minima = lsq_signal[lsq_utils.min_bool_func_1st_order_fd()]", "0 i_left = 0 while ((max_count_left < 1) or (min_count_left", "np.sin(pseudo_alg_time) + 1, '--', c='r', label=r'$\\tilde{h}_{(1,0)}^M(t)$', zorder=4) plt.scatter(pseudo_alg_time[pseudo_utils.min_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.min_bool_func_1st_order_fd()], c='c',", "4 a = 0.21 width = 0.2 time = np.linspace(0,", "np.linspace(minima_x[-1], max_discard_time, 101) dash_2 = np.linspace(minima_y[-1], max_discard, 101) end_point_time =", "'k-') plt.plot(max_1_y_time, max_1_y_side, 'k-') plt.plot(min_1_y_time, min_1_y, 'k-') plt.plot(min_1_y_time, min_1_y_side, 'k-')", "sum(emd_utils_max.max_bool_func_1st_order_fd()) > 0: max_count_right += 1 emd_utils_min = \\ emd_utils.Utility(time=time_extended[int(2", "plt.scatter(no_anchor_max_time, no_anchor_max, c='gray', zorder=4, label=textwrap.fill('Symmetric maxima', 10)) plt.xlim(3.9 * np.pi,", "axs[2].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[2].plot(np.linspace(0.95 * np.pi, 1.55 *", "plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Detrended Fluctuation Analysis Examples') plt.plot(time, time_series, LineWidth=2, label='Time", "1.0 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of", "axs[0].plot(time, imfs_51[1, :] + imfs_51[2, :] + imfs_51[3, :], label=textwrap.fill('Sum", "= maxima_x[-1] + (maxima_x[-1] - maxima_x[-2]) slope_based_maximum = minima_y[-1] +", "101), 'k--') axs[2].plot(1.55 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101),", "Characteristic Wave', 14)) plt.plot(max_2_x_time, max_2_x, 'k-') plt.plot(max_2_x_time_side, max_2_x, 'k-') plt.plot(min_2_x_time,", "plt.plot(((time_extended[-1001] + time_extended[-1002]) / 2) * np.ones(100), np.linspace(-2.75, 2.75, 100),", "box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert_pyemd.png') plt.show() emd_sift", "* np.pi + width, 101) min_2_x = minima_y[-2] * np.ones_like(min_2_x_time)", "np.pi, 1001) knot_demonstrate_time_series = np.sin(knot_demonstrate_time) + np.sin(5 * knot_demonstrate_time) emd", "signal_orig[util_nn.max_bool_func_1st_order_fd()] minima = signal_orig[util_nn.min_bool_func_1st_order_fd()] cs_max = CubicSpline(t[util_nn.max_bool_func_1st_order_fd()], maxima) cs_min =", "P1 = 2 * np.abs(maxima_x[-1] - minima_x[-1]) Huang_time = (P1", "pseudo_alg_time) pseudo_utils = Utility(time=pseudo_alg_time, time_series=pseudo_alg_time_series) # plot 0 - addition", "knots_51 = np.linspace(0, 5 * np.pi, 51) time_series = np.cos(2", "time_series_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] minima_extrapolate_time = time_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Single Neuron", "1].plot(time, imfs[0, :], label='Smoothed') axs[0, 1].legend(loc='lower right') axs[1, 0].plot(time, imfs[1,", "b_spline_basis[5, 500:].T, '--', label=r'$ B_{0,4}(t) $') plt.plot(time[500:], b_spline_basis[6, 500:].T, '--',", "signal = CO2_data['decimal date'] signal = np.asarray(signal) time = CO2_data['month']", "/ 2) * np.ones(100), np.linspace(-2.75, 2.75, 100), c='k') plt.plot(((time[-202] +", "= 1 omega = ((2 * np.pi) / 25) return", "1 emd_utils_min = \\ emd_utils.Utility(time=time_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))], time_series=time_series_extended[int(len(lsq_signal)", "utils.derivative_forward_diff() > 0, False] & \\ np.r_[utils.zero_crossing() == 1, False]", "plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Single Neuron Neural Network Example') plt.plot(time, lsq_signal, zorder=2,", "plot 5 a = 0.25 width = 0.2 time =", "= np.linspace(improved_slope_based_minimum - width, improved_slope_based_minimum + width, 101) min_dash_time_4 =", "'', '', '', '']) axs[0].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi,", "= plt.gcf().get_size_inches() factor = 0.7 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) ax.pcolormesh(x_hs,", "2, c='darkgreen') plt.plot(time, inflection_points_envelope, c='darkorange', label=textwrap.fill('Inflection point envelope', 10)) plt.plot(time,", "np.ones_like(dash_max_min_2_x) max_2_y = np.linspace(maxima_y[-2] - width, maxima_y[-2] + width, 101)", "arbitrary prob = cvx.Problem(objective) result = prob.solve(verbose=True, solver=cvx.ECOS) weights_left =", "time_series += noise advemdpy = EMD(time=time, time_series=time_series) imfs_51, hts_51, ifs_51", "(len(lsq_signal) - 1) + 1 + i_right + 1)]) if", "('-2', '-1', '0', '1', '2')) plt.xlim(-0.25 * np.pi, 5.25 *", "2]) axs[0].set_xlim([0, 150]) axs[1].plot(t, emd_duff[2, :], label='AdvEMDpy') print(f'AdvEMDpy driving function", "np.pi, 5 * np.pi), (r'4$\\pi$', r'5$\\pi$')) plt.yticks((-3, -2, -1, 0,", "np.pi], labels=[r'0', r'$\\pi$', r'$2\\pi$']) box_0 = ax.get_position() ax.set_position([box_0.x0 - 0.05,", "axs[1].set_xticklabels([r'$ \\tau_k $', r'$ \\tau_{k+1} $']) axs[1].set_xlim(4.5, 6.5) plt.savefig('jss_figures/comparing_bases.png') plt.show()", "plt.subplots_adjust(hspace=0.1) axs[0].plot(time, time_series, label='Time series') axs[0].plot(time, imfs_51[1, :] + imfs_51[2,", "Optimised Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2, zorder=100) axs[2].set_yticks(ticks=[-2, 0, 2])", "= np.linspace(maxima_y[-1] - width, maxima_y[-1] + width, 101) max_1_y_side =", "'k-') plt.plot(dash_max_min_2_y_time, dash_max_min_2_y, 'k--') plt.text(4.08 * np.pi, -2.2, r'$\\frac{p_2}{2}$') plt.plot(max_1_x_time,", "(years)') axis += 1 plt.gcf().subplots_adjust(bottom=0.15) axs[0, 0].set_title(r'Original CO$_2$ Concentration') axs[0,", "* np.pi + width, 101) max_1_x = maxima_y[-1] * np.ones_like(max_1_x_time)", "left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/neural_network.png') plt.show() # plot 6a np.random.seed(0) time", "np.linspace(-2.75, 2.75, 100), c='k') plt.plot(((time[-202] + time[-201]) / 2) *", "scipy.integrate import odeint from scipy.ndimage import gaussian_filter from emd_utils import", "Equation Example def duffing_equation(xy, ts): gamma = 0.1 epsilon =", "+ width, 101) max_1_y_time = maxima_x[-1] * np.ones_like(max_1_y) min_1_y =", "* np.ones(101), np.linspace(-3.0, -2.0, 101), '--', c='grey', label='Knots', zorder=1) plt.xticks((0,", "lsq_signal, zorder=2, label='Signal') plt.plot(time_extended, time_series_extended, c='g', zorder=1, label=textwrap.fill('Extrapolated signal', 12))", "fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'minima', optimal_maxima, optimal_minima, smooth=False, smoothing_penalty=0.2, edge_effect='none')[0] ax = plt.subplot(111)", "'--', c='grey', zorder=1) axs[0].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--',", "+ width, 101) dash_3_time = np.linspace(minima_x[-1], slope_based_maximum_time, 101) dash_3 =", "'k-') plt.plot(min_1_y_time, min_1_y, 'k-') plt.plot(min_1_y_time, min_1_y_side, 'k-') plt.plot(dash_max_min_1_y_time, dash_max_min_1_y, 'k--')", "left') axs[1].plot(knots[1][0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots')", "12)) plt.scatter(maxima_time, maxima, c='r', zorder=3, label='Maxima') plt.scatter(minima_time, minima, c='b', zorder=3,", "print(f'PyEMD driving function error: {np.round(sum(abs(0.1 * np.cos(0.04 * 2 *", "as sns import matplotlib.pyplot as plt from scipy.integrate import odeint", "plt.gcf().get_size_inches() factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess", "c='k') plt.plot(np.linspace(((time[-302] + time[-301]) / 2), ((time[-302] + time[-301]) /", "label='emd 0.3.3') print(f'emd driving function error: {np.round(sum(abs(0.1 * np.cos(0.04 *", "= average_gradients * (np.abs(average_gradients) == max(np.abs(average_gradients))) adjustment = - lr", "Concentration') axs[0, 1].set_title('Smoothed CO$_2$ Concentration') axs[1, 0].set_title('IMF 1') axs[1, 1].set_title('Residual')", "cvx.Variable(int(neural_network_k + 1)) objective = cvx.Minimize(cvx.norm((2 * (vx * P)", "2, c='darkblue') plt.plot(time, maxima_envelope_smooth, c='darkred', label=textwrap.fill('SEMD envelope', 10)) plt.plot(time, minima_envelope_smooth,", "np.linspace(minima_y[-1], maxima_y[-1], 101) dash_max_min_1_x_time = 5.4 * np.pi * np.ones_like(dash_max_min_1_x)", "2]) axs[1].set_xticks(ticks=[np.pi]) axs[1].set_xticklabels(labels=[r'$\\pi$']) box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.06, box_0.y0,", "label=textwrap.fill('Windsorize interpolation filter', 14)) axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.90)[1], c='grey', label=textwrap.fill('Quantile window',", "np.pi]) axs[2].set_xticklabels(['$0$', r'$\\pi$', r'$2\\pi$', r'$3\\pi$', r'$4\\pi$', r'$5\\pi$']) box_2 = axs[2].get_position()", "Linewidth=2, zorder=100) axs[0].set_yticks(ticks=[-2, 0, 2]) axs[0].set_xticks(ticks=[0, np.pi, 2 * np.pi])", "- width, maxima_x[-1] + width, 101) max_1_x_time_side = np.linspace(5.4 *", "2]) axs[1].set_xticks(ticks=[np.pi]) axs[1].set_xticklabels(labels=[r'$\\pi$']) box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.05, box_0.y0,", ":] + imfs_31[2, :], label=textwrap.fill('Sum of IMF 1 and IMF", "0.25 width = 0.2 time = np.linspace(0, (5 - a)", "c='b', label='Minima', zorder=10) plt.plot(time, max_unsmoothed[0], label=textwrap.fill('Unsmoothed maxima envelope', 10), c='darkorange')", "smoothing_penalty=0.2, edge_effect='none')[0] ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Detrended Fluctuation Analysis Examples')", "'k--', label='Zoomed region') plt.savefig('jss_figures/DFA_different_trends.png') plt.show() # plot 6b fig, axs", "min_count_left += 1 lsq_utils = emd_utils.Utility(time=time, time_series=lsq_signal) utils_extended = emd_utils.Utility(time=time_extended,", "0.05, box_0.y0, box_0.width * 0.85, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))", "0.85, box_1.height]) axs[1].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].plot(np.linspace(0.95 * np.pi,", "label='Time series') axs[0].plot(time, imfs_51[1, :] + imfs_51[2, :] + imfs_51[3,", "plt.plot(time[500:], b_spline_basis[4, 500:].T, '--', label=r'$ B_{-1,4}(t) $') plt.plot(time[500:], b_spline_basis[5, 500:].T,", "1.55 * np.pi) axs[2].plot(time, time_series, label='Time series') axs[2].plot(time, imfs_11[1, :],", "slope_based_maximum_time = maxima_x[-1] + (maxima_x[-1] - maxima_x[-2]) slope_based_maximum = minima_y[-1]", "101) length_top = maxima_y[-1] * np.ones_like(length_time) length_bottom = minima_y[-1] *", "ifs_11 = advemdpy.empirical_mode_decomposition(knots=knots_11, max_imfs=1, edge_effect='symmetric_anchor', verbose=False)[:3] fig, axs = plt.subplots(3,", ":], label='IMF 1 with 11 knots') axs[2].plot(time, imfs_31[2, :], label='IMF", "label='IMF 2 with 31 knots') axs[2].plot(time, imfs_51[3, :], label='IMF 3", "emd_utils.Utility(time=time, time_series=Coughlin_wave) Coughlin_max_bool = utils_Coughlin.max_bool_func_1st_order_fd() Coughlin_min_bool = utils_Coughlin.min_bool_func_1st_order_fd() Huang_max_time =", "np.ones(101), '--', c='black') axs[0].plot(0.85 * np.pi * np.ones(101), np.linspace(-3, 3,", "np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[2].plot(knots[0] * np.ones(101),", "plt.plot(max_2_x_time, max_2_x, 'k-') plt.plot(max_2_x_time_side, max_2_x, 'k-') plt.plot(min_2_x_time, min_2_x, 'k-') plt.plot(min_2_x_time_side,", "width, slope_based_maximum + width, 101) dash_3_time = np.linspace(minima_x[-1], slope_based_maximum_time, 101)", "np.pi * t / 25) + 0.5 * np.sin(2 *", "plt.gcf().get_size_inches() factor = 0.7 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) ax.pcolormesh(x_hs, y,", "plt.plot(time, time_series, LineWidth=2, label='Signal') plt.scatter(Huang_max_time, Huang_max, c='magenta', zorder=4, label=textwrap.fill('Huang maximum',", "0, False] & \\ np.r_[utils.zero_crossing() == 1, False] EEMD_maxima_envelope =", "Fluctuation(time=time, time_series=time_series) max_unsmoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima', smooth=False) max_smoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots,", "51 knots: {np.round(np.var(time_series - (imfs_51[1, :] + imfs_51[2, :] +", "np.linspace(0, 2 * np.pi, 1001) pseudo_alg_time_series = np.sin(pseudo_alg_time) + np.sin(5", "= [1, 1] solution = odeint(duffing_equation, XY0, t) x =", "* np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1 and Statically Optimised", "- time[time == maxima_x[-2]]) + maxima_x[-1] Huang_wave = (A1 /", "0.85, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/DFA_hilbert_spectrum.png') plt.show()", "time_series_extended[int(2 * (len(lsq_signal) - 1) + 1 + i_right)] =", "'k-') plt.plot(max_1_x_time_side, max_1_x, 'k-') plt.plot(min_1_x_time, min_1_x, 'k-') plt.plot(min_1_x_time_side, min_1_x, 'k-')", "* average_gradients # adjustment = - lr * max_gradient_vector weights", "r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey',", "b_spline_basis[3, 500:].T, '--', label=r'$ B_{-2,4}(t) $') plt.plot(time[500:], b_spline_basis[4, 500:].T, '--',", "width, 101) dash_3_time = np.linspace(minima_x[-1], slope_based_maximum_time, 101) dash_3 = np.linspace(minima_y[-1],", "zorder=4, label=textwrap.fill('Optimal maxima', 10)) plt.scatter(time[optimal_minima], time_series[optimal_minima], c='darkblue', zorder=4, label=textwrap.fill('Optimal minima',", "top pyemd = pyemd0215() py_emd = pyemd(x) IP, IF, IA", "IMF 2 and IMF 3 with 51 knots', 19)) for", "cvx import seaborn as sns import matplotlib.pyplot as plt from", "np.pi, -3.2, r'$\\Delta{t^{min}_{m}}$') plt.text(4.74 * np.pi, -3.2, r'$\\Delta{t^{min}_{m}}$') plt.text(4.12 *", "= np.linspace(0, 2 * np.pi, 1001) knot_demonstrate_time_series = np.sin(knot_demonstrate_time) +", "Satisfied', 50)) plt.plot(time, time_series, label='Time series', zorder=2, LineWidth=2) plt.scatter(time[maxima], time_series[maxima],", "1) preprocess = Preprocess(time=preprocess_time, time_series=preprocess_time_series) axs[0].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[0].plot(pseudo_alg_time, pseudo_alg_time_series,", "0.06, box_1.y0, box_1.width * 0.85, box_1.height]) plt.savefig('jss_figures/preprocess_smooth.png') plt.show() # plot", "factor = 0.9 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert", "np.ones_like(maxima_dash) maxima_dash_time_3 = slope_based_maximum_time * np.ones_like(maxima_dash) maxima_line_dash_time = np.linspace(maxima_x[-2], slope_based_maximum_time,", "(slope_based_minimum_time - minima_x[-1]), 1.20 + (slope_based_minimum - minima_y[-1]), r'$s_2$') plt.plot(minima_line_dash_time,", "= time_series[-1] * np.ones_like(anti_symmetric_time) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time, time_series,", "plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima')", "label='AdvEMDpy') axs[0].plot(t, py_emd[0, :], '--', label='PyEMD 0.2.10') axs[0].plot(t, emd_sift[:, 0],", "= emd040.spectra.define_hist_bins(0, 0.2, 100) hht = emd040.spectra.hilberthuang(IF, IA, freq_edges) hht", "= emd_utils.Utility(time=time_extended, time_series=time_series_extended) maxima = lsq_signal[lsq_utils.max_bool_func_1st_order_fd()] maxima_time = time[lsq_utils.max_bool_func_1st_order_fd()] maxima_extrapolate", "* seed_weights.copy() train_input = P[:-1, :] lr = 0.01 for", "z_min, z_max = 0, np.abs(z).max() ax.pcolormesh(x_hs, y, np.abs(z), cmap='gist_rainbow', vmin=z_min,", "_, _, _ = \\ emd_example.empirical_mode_decomposition(knots=knots, knot_time=time, verbose=False) print(f'AdvEMDpy annual", "* 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/DFA_hilbert_spectrum.png') plt.show() # plot", "P[:-1, col] = lsq_signal[(-(neural_network_m + neural_network_k - col)):(-(neural_network_m - col))]", "max_unsmoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima', smooth=False) max_smoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima', smooth=True)", "/ 2) * np.ones(100), np.linspace(-2.75, 2.75, 100), c='k', label=textwrap.fill('Neural network", "z = hs_ouputs y = y / (2 * np.pi)", "time_series[min_bool] max_dash_time = np.linspace(maxima_x[-1] - width, maxima_x[-1] + width, 101)", "figure_size[1])) axs[0].plot(t, emd_duff[1, :], label='AdvEMDpy') axs[0].plot(t, py_emd[0, :], '--', label='PyEMD", "decimated', 11)) downsampled = preprocess.downsample(decimate=False) axs[0].plot(downsampled[0], downsampled[1], label=textwrap.fill('Downsampled', 13)) axs[0].plot(np.linspace(0.85", "= utils.min_bool_func_1st_order_fd() minima_x = time[min_bool] minima_y = time_series[min_bool] max_dash_1 =", "np.linspace(maxima_x[-2] - width, maxima_x[-2] + width, 101) max_2_x_time_side = np.linspace(5.3", "knots_11 = np.linspace(0, 5 * np.pi, 11) imfs_11, hts_11, ifs_11", "0.5, time[-1] + 0.5, 101) anti_symmetric_signal = time_series[-1] * np.ones_like(anti_symmetric_time)", "'k-') plt.plot(symmetry_axis_1_time, symmetry_axis, 'r--', zorder=1) plt.plot(anti_symmetric_time, anti_symmetric_signal, 'r--', zorder=1) plt.plot(symmetry_axis_2_time,", "< 1)) and (i_left < len(lsq_signal) - 1): time_series_extended[int(len(lsq_signal) -", "= time[-1] * np.ones(101) symmetry_axis = np.linspace(-2, 2, 101) end_time", "0.1, 100), 2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1002]) /", "plt.plot(5 * np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') plt.plot(6 * np.ones(100),", "debugging) emd = AdvEMDpy.EMD(time=derivative_time, time_series=derivative_of_lsq) imf_1_of_derivative = emd.empirical_mode_decomposition(knots=derivative_knots, knot_time=derivative_time, text=False,", "5 * np.pi, 101) time_extended = time_extension(time) time_series_extended = np.zeros_like(time_extended)", "c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.plot(Huang_time, Huang_wave,", "symmetry_axis = np.linspace(-2, 2, 101) end_time = np.linspace(time[-1] - width,", "Demonstrating Unsmoothed Extrema Envelopes if Schoenberg–Whitney Conditions are Not Satisfied',", "plt.scatter(Coughlin_max_time, Coughlin_max, c='darkorange', zorder=4, label=textwrap.fill('Coughlin maximum', 14)) plt.scatter(Coughlin_min_time, Coughlin_min, c='dodgerblue',", "+ a) * np.pi, (5 - a) * np.pi, 1001)", "Hilbert, hilbert_spectrum from emd_preprocess import Preprocess from emd_mean import Fluctuation", "((time[-202] + time[-201]) / 2) + 0.1, 100), 2.75 *", "AdvEMDpy import emd_basis import emd_utils import numpy as np import", "time_series_reflect = np.flip(np.cos(np.linspace((5 - 2.6 * a) * np.pi, (5", "plt.text(4.43 * np.pi, -0.20, r'$s_2$') plt.text(4.30 * np.pi + (minima_x[-1]", "3 * np.pi, 4 * np.pi, 5 * np.pi]) axs[0].set_xticklabels(['',", "of Simple Sinusoidal Time Seres with Added Noise', 50)) x_hs,", "max_dash = maxima_y[-1] * np.ones_like(max_dash_time) min_dash_time = np.linspace(minima_x[-1] - width,", "'--', label=r'$0.1$cos$(0.08{\\pi}t)$') axs[1].set_title('IMF 2') axs[1].set_ylim([-0.2, 0.4]) axs[1].set_xlim([0, 150]) axis =", "101) ax = plt.subplot(111) figure_size = plt.gcf().get_size_inches() factor = 0.9", "# plot 1d - addition window = 81 fig, axs", "box_0 = ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width * 0.95,", "cycle', 10)) ax.axis([x_hs.min(), x_hs.max(), y.min(), y.max()]) box_0 = ax.get_position() ax.set_position([box_0.x0", "= maxima_x[-1] * np.ones_like(max_1_y) min_1_y = np.linspace(minima_y[-1] - width, minima_y[-1]", "inflection_y = time_series[inflection_bool] fluctuation = emd_mean.Fluctuation(time=time, time_series=time_series) maxima_envelope = fluctuation.envelope_basis_function_approximation(knots,", "= 0.25 width = 0.2 time = np.linspace(0, (5 -", "targets', 13)) plt.plot(np.linspace(((time[-202] + time[-201]) / 2), ((time[-202] + time[-201])", "- epsilon * xy[0] ** 3 + gamma * np.cos(omega", "$', r'$ \\tau_{k+1} $']) axs[1].set_xlim(4.5, 6.5) plt.savefig('jss_figures/comparing_bases.png') plt.show() # plot", "time_series=derivative_of_lsq) imf_1_of_derivative = emd.empirical_mode_decomposition(knots=derivative_knots, knot_time=derivative_time, text=False, verbose=False)[0][1, :] utils =", "P2) * (time[time >= maxima_x[-2]] - time[time == maxima_x[-2]]) +", "- width, -2.1 + width, 101) max_1_y_time = maxima_x[-1] *", "np import pandas as pd import cvxpy as cvx import", "= np.linspace(minima_y[-1], max_discard, 101) end_point_time = time[-1] end_point = time_series[-1]", "r'5$\\pi$')) plt.yticks((-2, -1, 0, 1, 2), ('-2', '-1', '0', '1',", "= lsq_signal[(-(neural_network_m + neural_network_k - col)):(-(neural_network_m - col))] P[-1, col]", "* np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1, label='Knots') axs[2].set_xticks([0,", "+ gamma * np.cos(omega * ts)] t = np.linspace(0, 150,", "np.ones_like(min_2_x_time) dash_max_min_2_x = np.linspace(minima_y[-2], maxima_y[-2], 101) dash_max_min_2_x_time = 5.3 *", "Dioxide Concentration Example CO2_data = pd.read_csv('Data/co2_mm_mlo.csv', header=51) plt.plot(CO2_data['month'], CO2_data['decimal date'])", "imfs, hts, ifs, _, _, _, _ = \\ emd_example.empirical_mode_decomposition(knots=knots,", "np.pi, 2 * np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots_uniform[0] * np.ones(101),", "* np.pi) - np.ones_like(ifs[1, :]))), 3)}') fig, axs = plt.subplots(2,", "time[-301]) / 2), ((time[-302] + time[-301]) / 2) + 0.1,", "py_emd[1, :], '--', label='PyEMD 0.2.10') print(f'PyEMD driving function error: {np.round(sum(abs(0.1", "plt.plot(time, maxima_envelope_smooth, c='darkred', label=textwrap.fill('SEMD envelope', 10)) plt.plot(time, minima_envelope_smooth, c='darkred') plt.plot(time,", "maxima = util.max_bool_func_1st_order_fd() minima = util.min_bool_func_1st_order_fd() ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10)", "minima_y = time_series[min_bool] A2 = np.abs(maxima_y[-2] - minima_y[-2]) / 2", "* np.pi], labels=[r'0', r'$\\pi$', r'$2\\pi$']) box_0 = ax.get_position() ax.set_position([box_0.x0 -", "Equation using PyEMD 0.2.10', 40)) plt.pcolormesh(t, freq_bins, hht, cmap='gist_rainbow', vmin=0,", "np.pi + width, 101) length_top = maxima_y[-1] * np.ones_like(length_time) length_bottom", "c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2, 101),", "'k-') plt.plot(maxima_dash_time_3, maxima_dash, 'k-') plt.plot(minima_dash_time_1, minima_dash, 'k-') plt.plot(minima_dash_time_2, minima_dash, 'k-')", "concentration') if axis == 1: pass if axis == 2:", "axs.flat: ax.label_outer() if axis == 0: ax.set_ylabel(r'$\\gamma_1(t)$') ax.set_yticks([-2, 0, 2])", "(2 * np.pi) - np.ones_like(ifs[1, :]))), 3)}') fig, axs =", "axs[1, 0].set_title('IMF 1') axs[1, 1].set_title('Residual') plt.gcf().subplots_adjust(bottom=0.15) plt.savefig('jss_figures/CO2_EMD.png') plt.show() hs_ouputs =", "np.pi, (5 - a) * np.pi, 11) time_series = np.cos(time)", "cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(time, np.ones_like(time), 'k--', label=textwrap.fill('Annual cycle', 10)) box_0", "- maxima_x[-1]) slope_based_maximum_time = maxima_x[-1] + (maxima_x[-1] - maxima_x[-2]) slope_based_maximum", "function is arbitrary prob = cvx.Problem(objective) result = prob.solve(verbose=True, solver=cvx.ECOS)", "plt.plot(time, lsq_signal, zorder=2, label='Signal') plt.plot(time_extended, time_series_extended, c='g', zorder=1, label=textwrap.fill('Extrapolated signal',", "textwrap import emd_mean import AdvEMDpy import emd_basis import emd_utils import", "def duffing_equation(xy, ts): gamma = 0.1 epsilon = 1 omega", "x = solution[:, 0] dxdt = solution[:, 1] x_points =", "factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of CO$_{2}$ Concentration", "* np.pi, 1.15 * np.pi, 101), 3 * np.ones(101), '--',", "2, 101), '--', c='grey', label='Knots') axs[2].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2,", "3)}') axs[1].plot(t, emd_sift[:, 1], '--', label='emd 0.3.3') print(f'emd driving function", "* np.pi + width, 101) length_top_2 = time_series[-1] * np.ones_like(length_time_2)", "axs[2].set_yticks(ticks=[-2, 0, 2]) axs[2].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$',", "width, -2.1 + width, 101) min_1_y_time = minima_x[-1] * np.ones_like(min_1_y)", "> 0: min_count_left += 1 lsq_utils = emd_utils.Utility(time=time, time_series=lsq_signal) utils_extended", "Displacement') axs[0].set_ylim([-2, 2]) axs[0].set_xlim([0, 150]) axs[1].plot(t, dxdt) axs[1].set_title('Duffing Equation Velocity')", "average_gradients * (np.abs(average_gradients) == max(np.abs(average_gradients))) adjustment = - lr *", "'--', label='PyEMD 0.2.10') axs[0].plot(t, emd_sift[:, 0], '--', label='emd 0.3.3') axs[0].set_title('IMF", "'k--') plt.plot(dash_2_time, dash_2, 'k--') plt.plot(length_distance_time, length_distance, 'k--') plt.plot(length_distance_time_2, length_distance_2, 'k--')", "range(3): for j in range(1, len(knots_uniform)): axs[i].plot(knots_uniform[j] * np.ones(101), np.linspace(-2,", "axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2, zorder=100) axs[1].set_yticks(ticks=[-2, 0, 2]) axs[1].set_xticks(ticks=[0, np.pi,", "no_anchor_max, c='gray', zorder=4, label=textwrap.fill('Symmetric maxima', 10)) plt.xlim(3.9 * np.pi, 5.5", "1 - t), 2)) # linear activation function is arbitrary", "* np.ones_like(max_dash_time) min_dash_time = np.linspace(minima_x[-1] - width, minima_x[-1] + width,", "axs[1].set_xticklabels(['', '', '', '', '', '']) box_1 = axs[1].get_position() axs[1].set_position([box_1.x0", "weights = 0 * seed_weights.copy() train_input = P[:-1, :] lr", "0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert_pyemd.png') plt.show() emd_sift = emd040.sift.sift(signal)", "plt.xlabel('Time (years)') plt.savefig('jss_figures/CO2_concentration.png') plt.show() signal = CO2_data['decimal date'] signal =", "width, 101) length_top_2 = time_series[-1] * np.ones_like(length_time_2) length_bottom_2 = minima_y[-1]", "1 + i_right + 1)], time_series=time_series_extended[int(2 * (len(lsq_signal) - 1)", "-0.1, r'$2a_1$') plt.plot(max_1_y_time, max_1_y, 'k-') plt.plot(max_1_y_time, max_1_y_side, 'k-') plt.plot(min_1_y_time, min_1_y,", "c='grey', zorder=1, label='Knots') axs[1].set_xticks([0, np.pi, 2 * np.pi, 3 *", "= slope_based_maximum_time * np.ones_like(max_dash_1) max_dash_3 = np.linspace(slope_based_maximum - width, slope_based_maximum", "plt.plot(time, np.cos(time), c='black', label='True mean') plt.xticks((0, 1 * np.pi, 2", "epsilon * xy[0] ** 3 + gamma * np.cos(omega *", "* np.pi, (5 - a) * np.pi, 1001) knots =", "= point_2 * np.pi * np.ones_like(length_distance_2) length_time_2 = np.linspace(point_2 *", "np.cos(2 * np.pi * t / 25) + 0.5 *", "envelope', 10)) plt.plot(time, np.cos(time), c='black', label='True mean') plt.xticks((0, 1 *", "a = 0.25 width = 0.2 time = np.linspace(0, (5", "imfs[1, :], Linewidth=2, zorder=100) axs[1].set_yticks(ticks=[-2, 0, 2]) axs[1].set_xticks(ticks=[0, np.pi, 2", "3 with 51 knots') for knot in knots_11: axs[2].plot(knot *", "ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) ax.set_xticks(x_points) ax.set_xticklabels(x_names) axis += 1", "zorder=3, label='Minima') plt.scatter(maxima_extrapolate_time, maxima_extrapolate, c='magenta', zorder=3, label=textwrap.fill('Extrapolated maxima', 12)) plt.scatter(minima_extrapolate_time,", "left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht.png') plt.show() # Carbon Dioxide Concentration Example", "B_{-3,4}(t) $') plt.plot(time[500:], b_spline_basis[3, 500:].T, '--', label=r'$ B_{-2,4}(t) $') plt.plot(time[500:],", "time_extension, Utility from scipy.interpolate import CubicSpline from emd_hilbert import Hilbert,", "0.85, box_1.height]) axs[1].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].set_ylim(-5.5, 5.5) axs[1].set_xlim(0.95", "0, 2]) axs[0].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$'])", "'--') axs[1].plot(5 * np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') axs[1].plot(6 *", "1) + 1 + i_right + 1)], time_series=time_series_extended[int(2 * (len(lsq_signal)", "knot in knots[:-1]: plt.plot(knot * np.ones(101), np.linspace(-3.0, -2.0, 101), '--',", "1 - i_left):int(len(lsq_signal))]) if sum(emd_utils_max.max_bool_func_1st_order_fd()) > 0: max_count_left += 1", "* np.ones_like(min_1_x_time) dash_max_min_1_x = np.linspace(minima_y[-1], maxima_y[-1], 101) dash_max_min_1_x_time = 5.4", "= np.cos(2 * np.pi * t / 50) + 0.6", "Conditions are Not Satisfied', 50)) plt.plot(time, time_series, label='Time series', zorder=2,", "+ width, 101) min_1_x = minima_y[-1] * np.ones_like(min_1_x_time) dash_max_min_1_x =", "minima_y, c='b', zorder=4, label='Minima') plt.scatter(slope_based_maximum_time, slope_based_maximum, c='orange', zorder=4, label=textwrap.fill('Slope-based maximum',", "knots[:-1]: plt.plot(knot * np.ones(101), np.linspace(-3.0, -2.0, 101), '--', c='grey', zorder=1)", "101), 'k--', label='Zoomed region') box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.05,", "np.pi, -0.7, r'$\\beta$L') plt.text(5.34 * np.pi, -0.05, 'L') plt.scatter(maxima_x, maxima_y,", "np.r_[False, utils.derivative_forward_diff() < 0, False] & \\ np.r_[utils.zero_crossing() == 1,", "minima_x[-2] * np.ones_like(min_2_y) dash_max_min_2_y_time = np.linspace(minima_x[-2], maxima_x[-2], 101) dash_max_min_2_y =", "in range(1, len(knots_uniform)): axs[i].plot(knots_uniform[j] * np.ones(101), np.linspace(-2, 2, 101), '--',", "plt.savefig('jss_figures/Schoenberg_Whitney_Conditions.png') plt.show() # plot 7 a = 0.25 width =", "= np.cos(2 * time) + np.cos(4 * time) + np.cos(8", "= utils_Coughlin.min_bool_func_1st_order_fd() Huang_max_time = Huang_time[Huang_max_bool] Huang_max = Huang_wave[Huang_max_bool] Huang_min_time =", "plt.savefig('jss_figures/preprocess_filter.png') plt.show() # plot 1e - addition fig, axs =", "solution = odeint(duffing_equation, XY0, t) x = solution[:, 0] dxdt", "neural_network_k - col)):(-(neural_network_m - col))] P[-1, col] = 1 #", "hht = emd040.spectra.hilberthuang(IF, IA, freq_edges) hht = gaussian_filter(hht, sigma=1) fig,", "time_series=time_series) maxima = util.max_bool_func_1st_order_fd() minima = util.min_bool_func_1st_order_fd() ax = plt.subplot(111)", "= time_series_extended[utils_extended.max_bool_func_1st_order_fd()][-1] maxima_extrapolate_time = time_extended[utils_extended.max_bool_func_1st_order_fd()][-1] minima = lsq_signal[lsq_utils.min_bool_func_1st_order_fd()] minima_time =", "maxima', 10)) plt.scatter(anti_max_point_time, anti_max_point, c='green', zorder=4, label=textwrap.fill('Anti-Symmetric maxima', 10)) plt.scatter(no_anchor_max_time,", "Equation using emd 0.3.3', 40)) plt.pcolormesh(t, freq_bins, hht, cmap='gist_rainbow', vmin=0,", "* np.ones_like(max_dash_1) max_dash_3 = np.linspace(slope_based_maximum - width, slope_based_maximum + width,", "IA = emd040.spectra.frequency_transform(emd_sift, 10, 'hilbert') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 0.2,", "maxima_y[-1]) / 2 Average_min_time = minima_x[-1] + (minima_x[-1] - minima_x[-2])", "= time[min_bool] minima_y = time_series[min_bool] inflection_bool = utils.inflection_point() inflection_x =", "$') plt.xticks([5, 6], [r'$ \\tau_0 $', r'$ \\tau_1 $']) plt.xlim(4.4,", "* np.pi]) ax.set_xticklabels(['$0$', r'$\\pi$', r'$2\\pi$', r'$3\\pi$', r'$4\\pi$']) plt.ylabel(r'Frequency (rad.s$^{-1}$)') plt.xlabel('Time", "= emd_duffing.empirical_mode_decomposition(verbose=False) fig, axs = plt.subplots(2, 1) plt.subplots_adjust(hspace=0.3) figure_size =", "'k--', label=textwrap.fill('Annual cycle', 10)) box_0 = ax.get_position() ax.set_position([box_0.x0 + 0.0125,", "0.5), fontsize=8) ax.set_xticks(x_points) ax.set_xticklabels(x_names) axis += 1 plt.savefig('jss_figures/Duffing_equation_imfs.png') plt.show() hs_ouputs", "- width, time[-1] + width, 101) end_signal = time_series[-1] *", "np.linspace(-5, 5, 101), '--', c='grey', zorder=1, label='Knots') axs[2].set_xticks([np.pi, (3 /", "plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) axs[0].plot(t, emd_duff[1, :], label='AdvEMDpy') axs[0].plot(t, py_emd[0,", "Duffing Equation using PyEMD 0.2.10', 40)) plt.pcolormesh(t, freq_bins, hht, cmap='gist_rainbow',", "'k--') plt.text(4.08 * np.pi, -2.2, r'$\\frac{p_2}{2}$') plt.plot(max_1_x_time, max_1_x, 'k-') plt.plot(max_1_x_time_side,", "solution[:, 1] x_points = [0, 50, 100, 150] x_names =", "0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/neural_network.png') plt.show() # plot", "= np.linspace(0, (5 - a) * np.pi, 1001) time_series =", "axs[1].plot(downsampled_and_decimated[0], downsampled_and_decimated[1], label=textwrap.fill('Downsampled & decimated', 13)) axs[1].plot(downsampled[0], downsampled[1], label=textwrap.fill('Downsampled', 13))", "* np.ones_like(min_dash_1) min_dash_time_2 = minima_x[-2] * np.ones_like(min_dash_1) dash_1_time = np.linspace(maxima_x[-1],", "c='green', zorder=4, label=textwrap.fill('Anti-Symmetric maxima', 10)) plt.scatter(no_anchor_max_time, no_anchor_max, c='gray', zorder=4, label=textwrap.fill('Symmetric", "time_series_extended[int(len(lsq_signal) - 2 - i_left)] = \\ 2 * sum(weights_left", "19)) print(f'DFA fluctuation with 31 knots: {np.round(np.var(time_series - (imfs_31[1, :]", "and Uniform Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2, zorder=100) axs[1].set_yticks(ticks=[-2, 0,", "knot_time=derivative_time, text=False, verbose=False)[0][1, :] utils = emd_utils.Utility(time=time[:-1], time_series=imf_1_of_derivative) optimal_maxima =", "maxima_y[-2] * np.ones_like(max_2_x_time) min_2_x_time = np.linspace(minima_x[-2] - width, minima_x[-2] +", "label=textwrap.fill('Quantile window', 12)) axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.10)[1], c='grey') axs[0].plot(np.linspace(0.85 * np.pi,", "2) - 0.1, 100), 2.75 * np.ones(100), c='gray') plt.plot(((time_extended[-1001] +", "21)) for knot in knots_51: axs[0].plot(knot * np.ones(101), np.linspace(-5, 5,", "fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima', smooth=False) min_smoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima', smooth=True) util =", "= solution[:, 0] dxdt = solution[:, 1] x_points = [0,", "2 * np.pi, 51) emd = EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series) imfs =", "= ((2 * np.pi) / 25) return [xy[1], xy[0] -", "1) + 1 + i_right)], 1))) i_right += 1 if", "IMF 2 with 31 knots', 19)) axs[1].plot(time, imfs_51[2, :] +", "hts, ifs, _, _, _, _ = \\ emd_example.empirical_mode_decomposition(knots=knots, knot_time=time,", "'r--', label=textwrap.fill('Axes of symmetry', 10), zorder=1) plt.text(5.1 * np.pi, -0.7,", "for j in range(1, len(knots[i])): axs[i].plot(knots[i][j] * np.ones(101), np.linspace(-2, 2,", "plt.savefig('jss_figures/DFA_hilbert_spectrum.png') plt.show() # plot 6c time = np.linspace(0, 5 *", "== 0: ax.set_ylabel('x(t)') ax.set_yticks(y_points_1) if axis == 1: ax.set_ylabel(r'$ \\dfrac{dx(t)}{dt}", "* np.pi) z_min, z_max = 0, np.abs(z).max() figure_size = plt.gcf().get_size_inches()", "np.sin(5 * pseudo_alg_time) pseudo_utils = Utility(time=pseudo_alg_time, time_series=pseudo_alg_time_series) # plot 0", "Iteration of Sifting Algorithm') plt.plot(pseudo_alg_time, pseudo_alg_time_series, label=r'$h_{(1,0)}(t)$', zorder=1) plt.scatter(pseudo_alg_time[pseudo_utils.max_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.max_bool_func_1st_order_fd()],", "time = np.asarray(time) # compare other packages Carbon Dioxide -", "B_{-1,4}(t) $') plt.plot(time[500:], b_spline_basis[5, 500:].T, '--', label=r'$ B_{0,4}(t) $') plt.plot(time[500:],", "2 Average_min_time = minima_x[-1] + (minima_x[-1] - minima_x[-2]) Average_min =", "label=textwrap.fill('Huang maximum', 10)) plt.scatter(Huang_min_time, Huang_min, c='lime', zorder=4, label=textwrap.fill('Huang minimum', 10))", "np.ones(100), np.linspace(-2.75, 2.75, 100), c='k', label=textwrap.fill('Neural network inputs', 13)) plt.plot(np.linspace(((time[-302]", "c='grey', label=textwrap.fill('Quantile window', 12)) axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.10)[1], c='grey') axs[1].set_xlim(0.85 *", "* np.pi, 5 * np.pi), (r'$0$', r'$\\pi$', r'2$\\pi$', r'3$\\pi$', r'4$\\pi$',", "0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert_emd.png') plt.show() # compare other", "np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--', label='Zoomed region') plt.savefig('jss_figures/DFA_different_trends.png')", "length_time_2 = np.linspace(point_2 * np.pi - width, point_2 * np.pi", "c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[1].plot(preprocess_time, preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott smoothing', 12))", "A2 = np.abs(maxima_y[-2] - minima_y[-2]) / 2 A1 = np.abs(maxima_y[-1]", "width, 101) min_2_x = minima_y[-2] * np.ones_like(min_2_x_time) dash_max_min_2_x = np.linspace(minima_y[-2],", "* np.pi, 1.55 * np.pi, 101), 5.5 * np.ones(101), 'k--')", "= axs[0].get_position() axs[0].set_position([box_0.x0 - 0.06, box_0.y0, box_0.width * 0.85, box_0.height])", "c='grey', zorder=1, label='Knots') axs[2].set_xticks([0, np.pi, 2 * np.pi, 3 *", "plt.scatter(anti_max_point_time, anti_max_point, c='green', zorder=4, label=textwrap.fill('Anti-Symmetric maxima', 10)) plt.scatter(no_anchor_max_time, no_anchor_max, c='gray',", "(3 / 2) * np.pi]) axs[2].set_xticklabels([r'$\\pi$', r'$\\frac{3}{2}\\pi$']) box_2 = axs[2].get_position()", "(confusing with external debugging) emd = AdvEMDpy.EMD(time=derivative_time, time_series=derivative_of_lsq) imf_1_of_derivative =", "vmin=z_min, vmax=z_max) plt.plot(t[:-1], 0.124 * np.ones_like(t[:-1]), '--', label=textwrap.fill('Hamiltonian frequency approximation',", "'k--') plt.plot(dash_1_time, dash_1, 'k--') plt.plot(dash_2_time, dash_2, 'k--') plt.plot(dash_3_time, dash_3, 'k--')", "maxima_x[-1] Huang_wave = (A1 / A2) * (time_series[time >= maxima_x[-2]]", "label=textwrap.fill('Improved slope-based maximum', 11)) plt.scatter(improved_slope_based_minimum_time, improved_slope_based_minimum, c='dodgerblue', zorder=4, label=textwrap.fill('Improved slope-based", "Huang_time[Huang_max_bool] Huang_max = Huang_wave[Huang_max_bool] Huang_min_time = Huang_time[Huang_min_bool] Huang_min = Huang_wave[Huang_min_bool]", "axs[1].plot(time, chsi_basis[11, :].T, '--') axs[1].plot(time, chsi_basis[12, :].T, '--') axs[1].plot(time, chsi_basis[13,", "alternate packages from PyEMD import EMD as pyemd0215 import emd", "'g--', LineWidth=2, label=textwrap.fill('Symmetric signal', 10)) plt.plot(time_reflect[:51], time_series_anti_reflect[:51], '--', c='purple', LineWidth=2,", "Demonstration') axs[1].set_title('Zoomed Region') axs[0].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[0].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple',", "= fluctuation.envelope_basis_function_approximation(knots, 'minima', smooth=False, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] minima_envelope_smooth = fluctuation.envelope_basis_function_approximation(knots,", "preprocess_time_series, label='x(t)') axs[0].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time series', 12))", "1, 2), ('-2', '-1', '0', '1', '2')) box_0 = ax.get_position()", "2 * np.pi]) axs[1].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2 and Statically", "zorder=4, label=textwrap.fill('Average minimum', 14)) plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x,", "& \\ np.r_[utils.zero_crossing() == 1, False] optimal_minima = np.r_[False, utils.derivative_forward_diff()", "time_extended[-1002]) / 2) - 0.1, 100), 2.75 * np.ones(100), c='k')", "max_gradient_vector = average_gradients * (np.abs(average_gradients) == max(np.abs(average_gradients))) adjustment = -", "np.linspace(0, 5 * np.pi, 101) time_extended = time_extension(time) time_series_extended =", "= Huang_wave[Huang_max_bool] Huang_min_time = Huang_time[Huang_min_bool] Huang_min = Huang_wave[Huang_min_bool] Coughlin_max_time =", "signal) axs[0, 1].plot(time, signal) axs[0, 1].plot(time, imfs[0, :], label='Smoothed') axs[0,", "box_2.y0, box_2.width * 0.85, box_2.height]) axs[2].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8)", "x_names = {0, 50, 100, 150} y_points_1 = [-2, 0,", "figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of CO$_{2}$ Concentration using PyEMD", "-2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time[-202] + time[-201]) / 2), ((time[-202]", "14)) axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.90)[1], c='grey', label=textwrap.fill('Quantile window', 12)) axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window,", "plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Simple Sinusoidal Time Seres with", "- minima_x[-1]) * s1 max_dash_time_3 = slope_based_maximum_time * np.ones_like(max_dash_1) max_dash_3", "label=textwrap.fill('Downsampled', 13)) axs[1].set_xlim(0.85 * np.pi, 1.15 * np.pi) axs[1].set_ylim(-3, 3)", "3)}') for knot in knots_51: axs[0].plot(knot * np.ones(101), np.linspace(-5, 5,", "0.5)) plt.savefig('jss_figures/Schoenberg_Whitney_Conditions.png') plt.show() # plot 7 a = 0.25 width", "\\ 2 * sum(weights_left * np.hstack((time_series_extended[int(len(lsq_signal) - 1 - i_left):", "emd_duffing = AdvEMDpy.EMD(time=t, time_series=x) emd_duff, emd_ht_duff, emd_if_duff, _, _, _,", "51) time_series = np.cos(2 * time) + np.cos(4 * time)", "knots = np.linspace(time[0], time[-1], 200) emd_example = AdvEMDpy.EMD(time=time, time_series=signal) imfs,", "0.04 * np.ones_like(t[:-1]), 'g--', label=textwrap.fill('Driving function frequency', 15)) plt.xticks([0, 50,", "knots_31 = np.linspace(0, 5 * np.pi, 31) imfs_31, hts_31, ifs_31", "* (len(lsq_signal) - 1) + 1 - neural_network_k + i_right):", "= np.linspace(5.4 * np.pi - width, 5.4 * np.pi +", "maxima', 10)) plt.xlim(3.9 * np.pi, 5.5 * np.pi) plt.xticks((4 *", "- 1 - i_left + neural_network_k)], 1))) + 1 i_left", "box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].plot(time, time_series, label='Time series')", "signal', 10)) plt.plot(time_reflect[:51], time_series_anti_reflect[:51], '--', c='purple', LineWidth=2, label=textwrap.fill('Anti-symmetric signal', 10))", "zorder=3, label='Maxima') plt.scatter(minima_time, minima, c='b', zorder=3, label='Minima') plt.scatter(maxima_extrapolate_time, maxima_extrapolate, c='magenta',", "(maxima_envelope + minima_envelope) / 2, c='darkblue') plt.plot(time, maxima_envelope_smooth, c='darkred', label=textwrap.fill('SEMD", "Coughlin_min, c='dodgerblue', zorder=4, label=textwrap.fill('Coughlin minimum', 14)) plt.scatter(Average_max_time, Average_max, c='orangered', zorder=4,", "range(neural_network_m): P[:-1, col] = lsq_signal[int(col + 1):int(col + neural_network_k +", "bbox_to_anchor=(1, 0.5), fontsize=8) ax.set_xticks(x_points) ax.set_xticklabels(x_names) axis += 1 plt.savefig('jss_figures/Duffing_equation_imfs.png') plt.show()", "verbose=False)[0] fig, axs = plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series", "axs[1].set_xticklabels(labels=[r'$\\pi$']) box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.06, box_0.y0, box_0.width *", "adjustment = - lr * average_gradients # adjustment = -", "for knot in knots[:-1]: plt.plot(knot * np.ones(101), np.linspace(-3.0, -2.0, 101),", "((max_count_right < 1) or (min_count_right < 1)) and (i_right <", "51 knots') print(f'DFA fluctuation with 11 knots: {np.round(np.var(time_series - imfs_51[3,", "c='grey') axs[1].set_xlim(0.85 * np.pi, 1.15 * np.pi) axs[1].set_ylim(-3, 3) axs[1].set_yticks(ticks=[-2,", "101), 'k--', label='Zoomed region') plt.savefig('jss_figures/DFA_different_trends.png') plt.show() # plot 6b fig,", "101), '--', c='grey', label='Knots') axs[2].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2, 101),", "fluctuation = emd_mean.Fluctuation(time=time, time_series=time_series) maxima_envelope = fluctuation.envelope_basis_function_approximation(knots, 'maxima', smooth=False, smoothing_penalty=0.2,", "maxima_x[-1] + (maxima_x[-1] - maxima_x[-2]) Average_max = (maxima_y[-2] + maxima_y[-1])", "t), 2)) # linear activation function is arbitrary prob =", "axs.flat: ax.label_outer() if axis == 0: ax.set_ylabel('x(t)') ax.set_yticks(y_points_1) if axis", "5, 101), '--', c='grey', zorder=1) axs[0].plot(knot * np.ones(101), np.linspace(-5, 5,", "increment=20)[0] derivative_of_lsq = utils.derivative_forward_diff() derivative_time = time[:-1] derivative_knots = np.linspace(knots[0],", "= signal_orig[util_nn.min_bool_func_1st_order_fd()] cs_max = CubicSpline(t[util_nn.max_bool_func_1st_order_fd()], maxima) cs_min = CubicSpline(t[util_nn.min_bool_func_1st_order_fd()], minima)", "max_imfs=3, edge_effect='symmetric_anchor', verbose=False)[:3] knots_31 = np.linspace(0, 5 * np.pi, 31)", "minima_envelope) / 2, c='darkblue') plt.plot(time, maxima_envelope_smooth, c='darkred', label=textwrap.fill('SEMD envelope', 10))", "Series and Statically Optimised Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2, zorder=100) axs[0].set_yticks(ticks=[-2,", "= plt.subplots() figure_size = plt.gcf().get_size_inches() factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor", "'k-') plt.plot(6 * np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') plt.legend(loc='upper left')", "c='k', label=textwrap.fill('Neural network inputs', 13)) plt.plot(np.linspace(((time[-302] + time[-301]) / 2),", "'--', c='grey', zorder=1) axs[2].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--',", "plt.scatter(improved_slope_based_minimum_time, improved_slope_based_minimum, c='dodgerblue', zorder=4, label=textwrap.fill('Improved slope-based minimum', 11)) plt.xlim(3.9 *", "* np.ones_like(minima_dash) minima_line_dash_time = np.linspace(minima_x[-2], slope_based_minimum_time, 101) minima_line_dash = -3.4", "2') axs[0].plot(time, b_spline_basis[4, :].T, '--', label='Basis 3') axs[0].plot(time, b_spline_basis[5, :].T,", "r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2 and Dynamically Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :],", "ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time, time_series, LineWidth=2, label='Signal') plt.title('Symmetry Edge", "region') plt.savefig('jss_figures/DFA_different_trends.png') plt.show() # plot 6b fig, axs = plt.subplots(3,", "interpolation filter', 14)) axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.90)[1], c='grey', label=textwrap.fill('Quantile window', 12))", "factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess Smoothing Demonstration') axs[1].set_title('Zoomed Region') axs[0].plot(preprocess_time,", "# compare other packages Carbon Dioxide - bottom knots =", "+ \\ time_series[time == minima_x[-1]] improved_slope_based_maximum_time = time[-1] improved_slope_based_maximum =", "* 0.75, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht_pyemd.png')", "* figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Duffing Equation using", "time_series=time_series_anti_reflect) anti_max_bool = utils.max_bool_func_1st_order_fd() anti_max_point_time = time_reflect[anti_max_bool] anti_max_point = time_series_anti_reflect[anti_max_bool]", "CubicSpline from emd_hilbert import Hilbert, hilbert_spectrum from emd_preprocess import Preprocess", "plt.plot(dash_2_time, dash_2, 'k--') plt.plot(dash_3_time, dash_3, 'k--') plt.plot(dash_4_time, dash_4, 'k--') plt.plot(dash_final_time,", "point_1 = 5.4 length_distance = np.linspace(maxima_y[-1], minima_y[-1], 101) length_distance_time =", "* np.pi]) axs[2].set_xticklabels(['$0$', r'$\\pi$', r'$2\\pi$', r'$3\\pi$', r'$4\\pi$', r'$5\\pi$']) box_2 =", "\\tau_{k+1} $']) axs[0].set_xlim(4.5, 6.5) axs[1].set_title('Cubic Hermite Spline Bases') axs[1].plot(time, chsi_basis[10,", "c='grey', label='Knots', zorder=1) plt.xticks((0, 1 * np.pi, 2 * np.pi,", "np.pi, 1001) time_series = np.cos(time) + np.cos(5 * time) utils", "- 1 - i_left): int(len(lsq_signal) - 1 - i_left +", "IMF 3 with 51 knots', 21)) for knot in knots_51:", "= time[lsq_utils.max_bool_func_1st_order_fd()] maxima_extrapolate = time_series_extended[utils_extended.max_bool_func_1st_order_fd()][-1] maxima_extrapolate_time = time_extended[utils_extended.max_bool_func_1st_order_fd()][-1] minima =", "'k-') plt.plot(min_1_y_time, min_1_y_side, 'k-') plt.plot(dash_max_min_1_y_time, dash_max_min_1_y, 'k--') plt.text(4.48 * np.pi,", "* 0.85, box_2.height]) axs[2].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[2].plot(np.linspace(0.95 *", "min_1_y_side = np.linspace(-2.1 - width, -2.1 + width, 101) min_1_y_time", "A1 = np.abs(maxima_y[-1] - minima_y[-1]) / 2 P2 = 2", "plt.plot(np.linspace(((time[-202] + time[-201]) / 2), ((time[-202] + time[-201]) / 2)", "False] optimal_minima = np.r_[False, utils.derivative_forward_diff() > 0, False] & \\", "= cvx.Problem(objective) result = prob.solve(verbose=True, solver=cvx.ECOS) weights_left = np.array(vx.value) max_count_left", "= np.linspace(minima_x[-1], maxima_x[-1], 101) dash_max_min_1_y = -2.1 * np.ones_like(dash_max_min_1_y_time) ax", "emd_duff[1, :], label='AdvEMDpy') axs[0].plot(t, py_emd[0, :], '--', label='PyEMD 0.2.10') axs[0].plot(t,", "width, maxima_x[-2] + width, 101) max_2_x_time_side = np.linspace(5.3 * np.pi", "np.linspace(0, 5 * np.pi, 1001) knots_51 = np.linspace(0, 5 *", "np.pi) z_min, z_max = 0, np.abs(z).max() fig, ax = plt.subplots()", "= 1.0 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum", "- width, point_2 * np.pi + width, 101) length_top_2 =", "0.85, box_2.height]) axs[2].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[2].set_ylim(-5.5, 5.5) axs[2].set_xlim(0.95", "= np.linspace(0, 5 * np.pi, 1001) time_series = np.cos(time) +", "np.pi, 1001) time_series = np.cos(time) + np.cos(5 * time) knots", "31 knots: {np.round(np.var(time_series - (imfs_31[1, :] + imfs_31[2, :])), 3)}')", "1 plt.title('Non-Natural Cubic B-Spline Bases at Boundary') plt.plot(time[500:], b_spline_basis[2, 500:].T,", "'--', c='grey', zorder=1, label='Knots') axs[2].set_xticks([np.pi, (3 / 2) * np.pi])", "= plt.subplots(2, 1) plt.subplots_adjust(hspace=0.3) figure_size = plt.gcf().get_size_inches() factor = 0.8", "in range(3): for j in range(1, len(knots)): axs[i].plot(knots[j] * np.ones(101),", "+ width, 101) min_dash = minima_y[-1] * np.ones_like(min_dash_time) dash_1_time =", "filter', 12)) axs[1].plot(preprocess_time, preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median filter', 13)) axs[1].plot(preprocess_time, preprocess.winsorize(window_width=window, a=0.8)[1],", "np.pi, 5 * np.pi), (r'$0$', r'$\\pi$', r'2$\\pi$', r'3$\\pi$', r'4$\\pi$', r'5$\\pi$'))", "13)) axs[0].plot(preprocess_time, preprocess.winsorize(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize filter', 12)) axs[0].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window, a=0.8)[1],", "packages Duffing - top pyemd = pyemd0215() py_emd = pyemd(x)", "1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Dynamically Optimised Knots') axs[0].plot(knot_demonstrate_time,", "0.075, box_0.width * 0.8, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1,", "axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots[0] * np.ones(101), np.linspace(-2, 2, 101), '--',", "b_spline_basis[6, 500:].T, '--', label=r'$ B_{1,4}(t) $') plt.xticks([5, 6], [r'$ \\tau_0", "1) plt.subplots_adjust(hspace=0.3) figure_size = plt.gcf().get_size_inches() factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor", "of CO$_{2}$ Concentration using emd 0.3.3', 45)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time", "figure_size = plt.gcf().get_size_inches() factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1]))", "plt.plot(min_1_y_time, min_1_y, 'k-') plt.plot(min_1_y_time, min_1_y_side, 'k-') plt.plot(dash_max_min_1_y_time, dash_max_min_1_y, 'k--') plt.text(4.48", "+ 1)], time_series=time_series_extended[int(2 * (len(lsq_signal) - 1) + 1): int(2", "np.random.seed(1) random.seed(1) preprocess_time_series = pseudo_alg_time_series + np.random.normal(0, 0.1, len(preprocess_time)) for", "np.random.normal(0, 1, len(time_series)) time_series += noise advemdpy = EMD(time=time, time_series=time_series)", "* np.ones(101), np.linspace(-2, 2, 101), '--', c='grey') plt.savefig('jss_figures/knot_1.png') plt.show() #", "1], '--', label='emd 0.3.3') print(f'emd driving function error: {np.round(sum(abs(0.1 *", "improved slope-based method more clear time_series[time >= minima_x[-1]] = 1.5", "emd_utils.Utility(time=time, time_series=lsq_signal) utils_extended = emd_utils.Utility(time=time_extended, time_series=time_series_extended) maxima = lsq_signal[lsq_utils.max_bool_func_1st_order_fd()] maxima_time", "EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series) imfs, _, _, _, knots, _, _ =", "plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time, time_series, LineWidth=2, label='Signal') plt.title('Symmetry Edge Effects Example')", "* np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--', label='Zoomed region') plt.savefig('jss_figures/DFA_different_trends.png') plt.show()", "maxima', 10)) plt.scatter(end_point_time, end_point, c='orange', zorder=4, label=textwrap.fill('Symmetric Anchor maxima', 10))", "* np.ones(100), c='k') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1002]) / 2), ((time_extended[-1001] +", "label=textwrap.fill('Sum of IMF 1, IMF 2, & IMF 3 with", "print(f'DFA fluctuation with 11 knots: {np.round(np.var(time_series - imfs_51[3, :]), 3)}')", "2, 101), '--', c='grey', label='Knots') for i in range(3): for", "label='Time series') axs[1].plot(time, imfs_31[1, :] + imfs_31[2, :], label=textwrap.fill('Sum of", "y, z = hs_ouputs z_min, z_max = 0, np.abs(z).max() ax.pcolormesh(x_hs,", "Filtered Hilbert Spectrum of Duffing Equation using PyEMD 0.2.10', 40))", "optimise_knots=2, verbose=False) fig, axs = plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time", "12)) axs[1].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize interpolation filter', 14)) axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window,", "0 while ((max_count_left < 1) or (min_count_left < 1)) and", "np.sin(2 * np.pi * t / 200) util_nn = emd_utils.Utility(time=t,", "np.ones(101), np.linspace(-2, 2, 101), '--', c='grey') plt.savefig('jss_figures/knot_1.png') plt.show() # plot", "box_0 = ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width * 0.85,", "= 100 # forward -> P = np.zeros((int(neural_network_k + 1),", "{0, 50, 100, 150} y_points_1 = [-2, 0, 2] y_points_2", "point_2 * np.pi + width, 101) length_top_2 = time_series[-1] *", "/ 2 A1 = np.abs(maxima_y[-1] - minima_y[-1]) / 2 P2", "100, 150]) plt.yticks([0, 0.1, 0.2]) plt.ylabel('Frequency (Hz)') plt.xlabel('Time (s)') box_0", "maxima_y[-1]) / (minima_x[-2] - maxima_x[-1]) slope_based_maximum_time = maxima_x[-1] + (maxima_x[-1]", "- width, -2.1 + width, 101) min_1_y_time = minima_x[-1] *", "0.5), fontsize=8) axs[1].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), 5.5", "imfs_51[3, :]), 3)}') for knot in knots_11: axs[2].plot(knot * np.ones(101),", "np.ones_like(max_discard_dash_time) dash_2_time = np.linspace(minima_x[-1], max_discard_time, 101) dash_2 = np.linspace(minima_y[-1], max_discard,", "Concentration using PyEMD 0.2.10', 45)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)') plt.pcolormesh(time,", "clear time_series[time >= minima_x[-1]] = 1.5 * (time_series[time >= minima_x[-1]]", "max_dash_1, 'k-') plt.plot(max_dash_time_2, max_dash_2, 'k-') plt.plot(max_dash_time_3, max_dash_3, 'k-') plt.plot(min_dash_time_1, min_dash_1,", "plt.text(4.48 * np.pi, -2.5, r'$\\frac{p_1}{2}$') plt.xlim(3.9 * np.pi, 5.6 *", "1 - neural_network_k + i_right): int(2 * (len(lsq_signal) - 1)", "np.ones_like(minima_dash) minima_dash_time_3 = slope_based_minimum_time * np.ones_like(minima_dash) minima_line_dash_time = np.linspace(minima_x[-2], slope_based_minimum_time,", "smoothing', 13)) downsampled_and_decimated = preprocess.downsample() axs[0].plot(downsampled_and_decimated[0], downsampled_and_decimated[1], label=textwrap.fill('Downsampled & decimated',", "# compare other packages Carbon Dioxide - top pyemd =", "- 1): time_series_extended[int(len(lsq_signal) - 2 - i_left)] = \\ 2", "slope_based_maximum_time, 101) maxima_line_dash = 2.5 * np.ones_like(maxima_line_dash_time) minima_dash = np.linspace(-3.4", "= emd040.spectra.hilberthuang(IF, IA, freq_edges) hht = gaussian_filter(hht, sigma=1) fig, ax", "box_0.y0, box_0.width * 0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Schoenberg_Whitney_Conditions.png')", "= plt.subplots(2, 1) fig.subplots_adjust(hspace=0.4) figure_size = plt.gcf().get_size_inches() factor = 0.8", "for additive constant t = lsq_signal[:neural_network_m] vx = cvx.Variable(int(neural_network_k +", "'k-') plt.plot(min_2_y_time, min_2_y_side, 'k-') plt.plot(dash_max_min_2_y_time, dash_max_min_2_y, 'k--') plt.text(4.08 * np.pi,", "time_series, label='Time series') axs[1].plot(time, imfs_31[1, :] + imfs_31[2, :], label=textwrap.fill('Sum", "1) + 1 - neural_network_k + i_right): int(2 * (len(lsq_signal)", "# linear activation function is arbitrary prob = cvx.Problem(objective) result", "slope-based minimum', 11)) plt.xlim(3.9 * np.pi, 5.5 * np.pi) plt.xticks((4", "time series', 12)) axs[1].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean filter', 12)) axs[1].plot(preprocess_time, preprocess.median_filter(window_width=window)[1],", "axs[1].set_xticks(ticks=[np.pi]) axs[1].set_xticklabels(labels=[r'$\\pi$']) box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.05, box_0.y0, box_0.width", "'', '', '']) box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 - 0.05, box_0.y0,", "(time[time >= maxima_x[-2]] - time[time == maxima_x[-2]]) + maxima_x[-1] Huang_wave", "= util.max_bool_func_1st_order_fd() minima = util.min_bool_func_1st_order_fd() ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title(textwrap.fill('Plot", "minima_y[-2]) / 2 A1 = np.abs(maxima_y[-1] - minima_y[-1]) / 2", "t) - emd_duff[2, :])), 3)}') axs[1].plot(t, py_emd[1, :], '--', label='PyEMD", "101) dash_max_min_1_y = -2.1 * np.ones_like(dash_max_min_1_y_time) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10)", "label='AdvEMDpy') print(f'AdvEMDpy driving function error: {np.round(sum(abs(0.1 * np.cos(0.04 * 2", "maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.plot(Huang_time,", "emd = AdvEMDpy.EMD(time=derivative_time, time_series=derivative_of_lsq) imf_1_of_derivative = emd.empirical_mode_decomposition(knots=derivative_knots, knot_time=derivative_time, text=False, verbose=False)[0][1,", "np.random.normal(0, 0.1, len(preprocess_time)) for i in random.sample(range(1000), 500): preprocess_time_series[i] +=", "maxima_y[-2] + width, 101) max_dash_time_1 = maxima_x[-1] * np.ones_like(max_dash_1) max_dash_time_2", "utils.derivative_forward_diff() < 0, False] & \\ np.r_[utils.zero_crossing() == 1, False]", "- maxima_y[-1]) / (minima_x[-2] - maxima_x[-1]) slope_based_maximum_time = maxima_x[-1] +", "axs = plt.subplots(2, 1) plt.subplots_adjust(hspace=0.2) axs[0].plot(t, x) axs[0].set_title('Duffing Equation Displacement')", "1 # backward <- P = np.zeros((int(neural_network_k + 1), neural_network_m))", "knots_uniform = np.linspace(0, 2 * np.pi, 51) emd = EMD(time=knot_demonstrate_time,", "= pyemd(signal) IP, IF, IA = emd040.spectra.frequency_transform(py_emd[:2, :].T, 12, 'hilbert')", "1 # for additive constant t = lsq_signal[:neural_network_m] vx =", "knot_demonstrate_time = np.linspace(0, 2 * np.pi, 1001) knot_demonstrate_time_series = np.sin(knot_demonstrate_time)", "- width, slope_based_maximum + width, 101) dash_3_time = np.linspace(minima_x[-1], slope_based_maximum_time,", "* np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[2].plot(knots_uniform[0] *", "* np.pi * t), '--', label=r'$0.1$cos$(0.08{\\pi}t)$') axs[1].set_title('IMF 2') axs[1].set_ylim([-0.2, 0.4])", "Concentration Example CO2_data = pd.read_csv('Data/co2_mm_mlo.csv', header=51) plt.plot(CO2_data['month'], CO2_data['decimal date']) plt.title(textwrap.fill('Mean", "np.sin(pseudo_alg_time), '--', c='purple', label=r'$\\tilde{h}_{(1,0)}^{\\mu}(t)$', zorder=5) plt.yticks(ticks=[-2, -1, 0, 1, 2])", "101) max_dash_2 = np.linspace(maxima_y[-2] - width, maxima_y[-2] + width, 101)", "plt.plot(length_time, length_bottom, 'k-') plt.plot(length_time_2, length_top_2, 'k-') plt.plot(length_time_2, length_bottom_2, 'k-') plt.plot(end_time,", "time_series_anti_reflect = time_series_reflect[0] - time_series_reflect utils = emd_utils.Utility(time=time, time_series=time_series_anti_reflect) anti_max_bool", "/ 2) + 0.1, 100), -2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time[-202]", "time_series=imf_1_of_derivative) optimal_maxima = np.r_[False, utils.derivative_forward_diff() < 0, False] & \\", "np.pi) axs[2].plot(time, time_series, label='Time series') axs[2].plot(time, imfs_11[1, :], label='IMF 1", "plt.subplot(111) figure_size = plt.gcf().get_size_inches() factor = 1.0 plt.gcf().set_size_inches((figure_size[0], factor *", "np.linspace(-2, 2, 101) end_time = np.linspace(time[-1] - width, time[-1] +", "IP, IF, IA = emd040.spectra.frequency_transform(emd_sift, 10, 'hilbert') freq_edges, freq_bins =", "inflection_y, c='magenta', zorder=4, label=textwrap.fill('Inflection points', 10)) plt.plot(time, maxima_envelope, c='darkblue', label=textwrap.fill('EMD", "ax.set_ylabel(r'$\\gamma_2(t)$') ax.set_yticks([-0.2, 0, 0.2]) box_0 = ax.get_position() ax.set_position([box_0.x0, box_0.y0, box_0.width", "imfs_51[3, :], label='IMF 3 with 51 knots') print(f'DFA fluctuation with", "(len(lsq_signal) - 1) + 1 - neural_network_k + i_right): int(2", "np.pi, 101) time_series_reflect = np.flip(np.cos(np.linspace((5 - 2.6 * a) *", "plt.title(textwrap.fill('Mean Monthly Concentration of Carbon Dioxide in the Atmosphere', 35))", "axs[1].set_xlim(0.95 * np.pi, 1.55 * np.pi) axs[2].plot(time, time_series, label='Time series')", "101), '--', c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots[0] * np.ones(101), np.linspace(-2,", "zorder=1) plt.plot(knots[-1] * np.ones(101), np.linspace(-3.0, -2.0, 101), '--', c='grey', label='Knots',", "left', bbox_to_anchor=(1, -0.15)) box_1 = axs[1].get_position() axs[1].set_position([box_1.x0 - 0.06, box_1.y0,", "plt.text(4.08 * np.pi, -2.2, r'$\\frac{p_2}{2}$') plt.plot(max_1_x_time, max_1_x, 'k-') plt.plot(max_1_x_time_side, max_1_x,", "left', bbox_to_anchor=(1, -0.15)) box_1 = axs[1].get_position() axs[1].set_position([box_1.x0 - 0.05, box_1.y0,", "Wave', 14)) plt.plot(max_2_x_time, max_2_x, 'k-') plt.plot(max_2_x_time_side, max_2_x, 'k-') plt.plot(min_2_x_time, min_2_x,", "signal_orig = np.cos(2 * np.pi * t / 50) +", "from PyEMD import EMD as pyemd0215 import emd as emd040", "np.pi), (r'4$\\pi$', r'5$\\pi$')) plt.yticks((-3, -2, -1, 0, 1, 2), ('-3',", "'k--') axs[0].plot(1.55 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--',", "'--', c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots[1][0] * np.ones(101), np.linspace(-2, 2,", "box_1 = axs[1].get_position() axs[1].set_position([box_1.x0 - 0.06, box_1.y0, box_1.width * 0.85,", "np.ones_like(min_dash_time) dash_1_time = np.linspace(maxima_x[-1], minima_x[-1], 101) dash_1 = np.linspace(maxima_y[-1], minima_y[-1],", "plt.savefig('jss_figures/edge_effects_characteristic_wave.png') plt.show() # plot 6 t = np.linspace(5, 95, 100)", "import emd_utils import numpy as np import pandas as pd", "# compare other packages Duffing - top pyemd = pyemd0215()", "knots = np.arange(12) time = np.linspace(0, 11, 1101) basis =", "& decimated', 13)) axs[1].plot(downsampled[0], downsampled[1], label=textwrap.fill('Downsampled', 13)) axs[1].set_xlim(0.85 * np.pi,", "np.cos(5 * time) knots = np.linspace(0, 5 * np.pi, 51)", "ax = plt.subplot(111) figure_size = plt.gcf().get_size_inches() factor = 0.9 plt.gcf().set_size_inches((figure_size[0],", "np.pi]) axs[0].set_xticklabels(['', '', '', '', '', '']) box_0 = axs[0].get_position()", "plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Duffing Equation using AdvEMDpy', 40))", "knots_51: axs[0].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1)", "5 * np.pi, 11) imfs_11, hts_11, ifs_11 = advemdpy.empirical_mode_decomposition(knots=knots_11, max_imfs=1,", "1 and Uniform Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2, zorder=100) axs[1].set_yticks(ticks=[-2,", "5.5) axs[0].set_xlim(0.95 * np.pi, 1.55 * np.pi) axs[1].plot(time, time_series, label='Time", "axis == 2: ax.set(ylabel=R'C0$_2$ concentration') ax.set(xlabel='Time (years)') if axis ==", "box_1.y0, box_1.width * 0.85, box_1.height]) plt.savefig('jss_figures/preprocess_smooth.png') plt.show() # plot 2", "np.pi, 31) imfs_31, hts_31, ifs_31 = advemdpy.empirical_mode_decomposition(knots=knots_31, max_imfs=2, edge_effect='symmetric_anchor', verbose=False)[:3]", "width, 101) max_dash = maxima_y[-1] * np.ones_like(max_dash_time) min_dash_time = np.linspace(minima_x[-1]", "np.linspace(-2.75, 2.75, 100), c='k', label=textwrap.fill('Neural network inputs', 13)) plt.plot(np.linspace(((time[-302] +", "Unsmoothed Extrema Envelopes if Schoenberg–Whitney Conditions are Not Satisfied', 50))", "plt.plot(dash_3_time, dash_3, 'k--') plt.plot(dash_4_time, dash_4, 'k--') plt.plot(dash_final_time, dash_final, 'k--') plt.scatter(maxima_x,", "left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].plot(time, time_series, label='Time series') axs[1].plot(time, imfs_31[1,", "max_1_x = maxima_y[-1] * np.ones_like(max_1_x_time) min_1_x_time = np.linspace(minima_x[-1] - width,", "np.pi, 1.55 * np.pi) axs[1].plot(time, time_series, label='Time series') axs[1].plot(time, imfs_31[1,", "maxima = lsq_signal[lsq_utils.max_bool_func_1st_order_fd()] maxima_time = time[lsq_utils.max_bool_func_1st_order_fd()] maxima_extrapolate = time_series_extended[utils_extended.max_bool_func_1st_order_fd()][-1] maxima_extrapolate_time", "print(f'emd annual frequency error: {np.round(sum(np.abs(IF - np.ones_like(IF)))[0], 3)}') freq_edges, freq_bins", "axs = plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Dynamically", "0.95, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/pseudo_algorithm.png') plt.show() knots =", "# plot 1a - addition knot_demonstrate_time = np.linspace(0, 2 *", "np.pi]) axs[1].set_xticklabels(['', '', '', '', '', '']) box_1 = axs[1].get_position()", "label=textwrap.fill('Average maximum', 14)) plt.scatter(Average_min_time, Average_min, c='cyan', zorder=4, label=textwrap.fill('Average minimum', 14))", "col in range(neural_network_m): P[:-1, col] = lsq_signal[int(col + 1):int(col +", "= np.cos(time) + np.cos(5 * time) utils = emd_utils.Utility(time=time, time_series=time_series)", "axs[2].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1) axs[2].plot(knot", "optimal_minima, smooth=False, smoothing_penalty=0.2, edge_effect='none')[0] EEMD_minima_envelope = fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'minima', optimal_maxima, optimal_minima,", "plt.savefig('jss_figures/CO2_Hilbert_emd.png') plt.show() # compare other packages Carbon Dioxide - bottom", "* np.hstack((time_series_extended[int(len(lsq_signal) - 1 - i_left): int(len(lsq_signal) - 1 -", "np.pi), (r'4$\\pi$', r'5$\\pi$')) plt.yticks((-2, -1, 0, 1, 2), ('-2', '-1',", "label=r'$ B_{-2,4}(t) $') plt.plot(time[500:], b_spline_basis[4, 500:].T, '--', label=r'$ B_{-1,4}(t) $')", "box_0.width * 0.84, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Schoenberg_Whitney_Conditions.png') plt.show()", "width, -1.8 + width, 101) min_2_y_time = minima_x[-2] * np.ones_like(min_2_y)", "c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots[1][0] * np.ones(101), np.linspace(-2, 2, 101),", "fluctuation with 51 knots: {np.round(np.var(time_series - (imfs_51[1, :] + imfs_51[2,", "maxima_y[-2] + width, 101) max_2_y_side = np.linspace(-1.8 - width, -1.8", "zorder=1, label=textwrap.fill('Extrapolated signal', 12)) plt.scatter(maxima_time, maxima, c='r', zorder=3, label='Maxima') plt.scatter(minima_time,", "2, 101), '--', c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots[0] * np.ones(101),", "2]) axs[0].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].plot(preprocess_time,", "+ np.cos(5 * np.linspace((5 - 2.6 * a) * np.pi,", "emd_utils_min = \\ emd_utils.Utility(time=time_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))], time_series=time_series_extended[int(len(lsq_signal) -", "plt.gcf().subplots_adjust(bottom=0.15) plt.savefig('jss_figures/CO2_EMD.png') plt.show() hs_ouputs = hilbert_spectrum(time, imfs, hts, ifs, max_frequency=10,", "(5 - a) * np.pi, 1001) knots = np.linspace((0 +", "A2) * (time_series[time >= maxima_x[-2]] - time_series[time == maxima_x[-2]]) +", "smooth=False, smoothing_penalty=0.2, edge_effect='none')[0] ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Detrended Fluctuation Analysis", "pseudo_alg_time_series = np.sin(pseudo_alg_time) + np.sin(5 * pseudo_alg_time) pseudo_utils = Utility(time=pseudo_alg_time,", "= plt.gcf().get_size_inches() factor = 1.0 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) ax.pcolormesh(x,", "- i_left + neural_network_k)], 1))) + 1 i_left += 1", "+= adjustment # test - bottom weights_right = np.hstack((weights, 0))", "for col in range(neural_network_m): P[:-1, col] = lsq_signal[(-(neural_network_m + neural_network_k", "plt.plot(max_1_y_time, max_1_y, 'k-') plt.plot(max_1_y_time, max_1_y_side, 'k-') plt.plot(min_1_y_time, min_1_y, 'k-') plt.plot(min_1_y_time,", "np.linspace(-3.4 - width, -3.4 + width, 101) minima_dash_time_1 = minima_x[-2]", "r'$\\Delta{t^{min}_{m}}$') plt.text(4.12 * np.pi, 2, r'$\\Delta{t^{max}_{M}}$') plt.text(4.50 * np.pi, 2,", "y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) ax.set_title(textwrap.fill(r'Gaussian Filtered Hilbert Spectrum of", "= emd.empirical_mode_decomposition(knots=derivative_knots, knot_time=derivative_time, text=False, verbose=False)[0][1, :] utils = emd_utils.Utility(time=time[:-1], time_series=imf_1_of_derivative)", "minima_y[-1], 101) dash_2_time = np.linspace(maxima_x[-1], minima_x[-2], 101) dash_2 = np.linspace(maxima_y[-1],", "np.pi, 5 * np.pi]) axs[2].set_xticklabels(['$0$', r'$\\pi$', r'$2\\pi$', r'$3\\pi$', r'$4\\pi$', r'$5\\pi$'])", "12)) axs[0].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize interpolation filter', 14)) axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window,", "np.linspace(0, (5 - a) * np.pi, 1001) time_series = np.cos(time)", "using AdvEMDpy', 40)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)') plt.plot(x_hs[0, :], np.ones_like(x_hs[0,", "c='darkred') plt.plot(time, EEMD_maxima_envelope, c='darkgreen', label=textwrap.fill('EEMD envelope', 10)) plt.plot(time, EEMD_minima_envelope, c='darkgreen')", "np.hstack((weights, 0)) max_count_right = 0 min_count_right = 0 i_right =", "= emd040.spectra.frequency_transform(emd_sift, 10, 'hilbert') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 0.2, 100)", "- output) gradients = error * (- train_input) # guess", "* np.pi - width, point_2 * np.pi + width, 101)", "= maxima_y[-1] * np.ones_like(length_time) length_bottom = minima_y[-1] * np.ones_like(length_time) point_2", "= CubicSpline(t[util_nn.max_bool_func_1st_order_fd()], maxima) cs_min = CubicSpline(t[util_nn.min_bool_func_1st_order_fd()], minima) time = np.linspace(0,", "ax.set_yticks([-2, 0, 2]) if axis == 1: ax.set_ylabel(r'$\\gamma_2(t)$') ax.set_yticks([-0.2, 0,", "time_extended[utils_extended.min_bool_func_1st_order_fd()][-2:] ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Single Neuron Neural Network Example')", "+ (slope_based_minimum - minima_y[-1]), r'$s_2$') plt.text(4.50 * np.pi + (slope_based_minimum_time", "+ width, 101) max_dash_2 = np.linspace(maxima_y[-2] - width, maxima_y[-2] +", "12)) axs[0].plot(preprocess_time, preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott smoothing', 12)) axs[0].plot(preprocess_time, preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker smoothing',", "np.pi, 101), -3 * np.ones(101), '--', c='black', label=textwrap.fill('Zoomed region', 10))", "5 * np.pi, 1001) knots_51 = np.linspace(0, 5 * np.pi,", "/ 50) + 0.6 * np.cos(2 * np.pi * t", "zorder=1, label='Knots') axs[1].set_xticks([0, np.pi, 2 * np.pi, 3 * np.pi,", "Dioxide in the Atmosphere', 35)) plt.ylabel('Parts per million') plt.xlabel('Time (years)')", "* np.pi]) axs[1].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2 and Dynamically Knots')", "Sifting Algorithm') plt.plot(pseudo_alg_time, pseudo_alg_time_series, label=r'$h_{(1,0)}(t)$', zorder=1) plt.scatter(pseudo_alg_time[pseudo_utils.max_bool_func_1st_order_fd()], pseudo_alg_time_series[pseudo_utils.max_bool_func_1st_order_fd()], c='r', label=r'$M(t_i)$',", "plt.text(4.30 * np.pi + (minima_x[-1] - minima_x[-2]), 0.35 + (minima_y[-1]", "25) + 0.5 * np.sin(2 * np.pi * t /", "< 1) or (min_count_left < 1)) and (i_left < len(lsq_signal)", "label=textwrap.fill('Huang minimum', 10)) plt.scatter(Coughlin_max_time, Coughlin_max, c='darkorange', zorder=4, label=textwrap.fill('Coughlin maximum', 14))", "axs[1].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[1].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time series',", "+= 1 plt.gcf().subplots_adjust(bottom=0.15) axs[0, 0].set_title(r'Original CO$_2$ Concentration') axs[0, 1].set_title('Smoothed CO$_2$", "- width, -1.8 + width, 101) max_2_y_time = maxima_x[-2] *", "steepest descent max_gradient_vector = average_gradients * (np.abs(average_gradients) == max(np.abs(average_gradients))) adjustment", "3 a = 0.25 width = 0.2 time = np.linspace(0,", "c='deeppink', label=textwrap.fill('Binomial average envelope', 10)) plt.plot(time, np.cos(time), c='black', label='True mean')", "'k-') plt.plot(maxima_dash_time_2, maxima_dash, 'k-') plt.plot(maxima_dash_time_3, maxima_dash, 'k-') plt.plot(minima_dash_time_1, minima_dash, 'k-')", "= np.linspace(-2.1 - width, -2.1 + width, 101) min_1_y_time =", "min_dash = minima_y[-1] * np.ones_like(min_dash_time) dash_1_time = np.linspace(maxima_x[-1], minima_x[-1], 101)", "0.3.3') axs[0].set_title('IMF 1') axs[0].set_ylim([-2, 2]) axs[0].set_xlim([0, 150]) axs[1].plot(t, emd_duff[2, :],", "# for additive constant t = lsq_signal[-neural_network_m:] # test -", "cycle', 10)) box_0 = ax.get_position() ax.set_position([box_0.x0 + 0.0125, box_0.y0 +", "utils_Huang.max_bool_func_1st_order_fd() Huang_min_bool = utils_Huang.min_bool_func_1st_order_fd() utils_Coughlin = emd_utils.Utility(time=time, time_series=Coughlin_wave) Coughlin_max_bool =", "c='black') axs[0].plot(1.15 * np.pi * np.ones(101), np.linspace(-3, 3, 101), '--',", "time = np.linspace(0, (5 - a) * np.pi, 1001) time_series", "- i_left):int(len(lsq_signal))], time_series=time_series_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))]) if sum(emd_utils_min.min_bool_func_1st_order_fd()) >", "width, 101) min_1_y_side = np.linspace(-2.1 - width, -2.1 + width,", "label=textwrap.fill('Coughlin Characteristic Wave', 14)) plt.plot(max_2_x_time, max_2_x, 'k-') plt.plot(max_2_x_time_side, max_2_x, 'k-')", "width, point_1 * np.pi + width, 101) length_top = maxima_y[-1]", "box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[0].set_ylim(-5.5, 5.5) axs[0].set_xlim(0.95 *", "minima = util.min_bool_func_1st_order_fd() ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title(textwrap.fill('Plot Demonstrating Unsmoothed", "axs[i].plot(knots_uniform[j] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey') plt.savefig('jss_figures/knot_uniform.png') plt.show()", "5.5, 101), 'k--', label='Zoomed region') axs[2].plot(time, time_series, label='Time series') axs[2].plot(time,", "np.pi, 101), -5.5 * np.ones(101), 'k--') axs[1].plot(0.95 * np.pi *", "np.ones_like(x_hs[0, :]), '--', label=r'$\\omega = 8$', Linewidth=3) ax.plot(x_hs[0, :], 4", "np.linspace(-5, 5, 101), '--', c='grey', zorder=1, label='Knots') axs[2].set_xticks([0, np.pi, 2", "Statically Optimised Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2, zorder=100) axs[1].set_yticks(ticks=[-2, 0,", "with 51 knots') for knot in knots_11: axs[2].plot(knot * np.ones(101),", "plot=False) x_hs, y, z = hs_ouputs y = y /", "edge_effect='none', spline_method='b_spline')[0] minima_envelope_smooth = fluctuation.envelope_basis_function_approximation(knots, 'minima', smooth=True, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0]", "label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots[0] * np.ones(101), np.linspace(-2, 2, 101), '--',", "np.ones(neural_network_k) / neural_network_k weights = 0 * seed_weights.copy() train_input =", "time_series=time_series) maxima_envelope = fluctuation.envelope_basis_function_approximation(knots, 'maxima', smooth=False, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] maxima_envelope_smooth", "* np.pi, 1001) knots_51 = np.linspace(0, 5 * np.pi, 51)", "knots_11: axs[2].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1)", "plt.gcf().get_size_inches() factor = 0.9 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered", "r'$\\pi$', r'$2\\pi$']) axs[1].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[1].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless", "solver=cvx.ECOS) weights_left = np.array(vx.value) max_count_left = 0 min_count_left = 0", "left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/DFA_hilbert_spectrum.png') plt.show() # plot 6c time =", "output) gradients = error * (- train_input) # guess average", "label=textwrap.fill('Inflection points', 10)) plt.plot(time, maxima_envelope, c='darkblue', label=textwrap.fill('EMD envelope', 10)) plt.plot(time,", "label=r'$\\tilde{h}_{(1,0)}^m(t)$', zorder=5) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time), '--', c='purple', label=r'$\\tilde{h}_{(1,0)}^{\\mu}(t)$', zorder=5) plt.yticks(ticks=[-2, -1,", "plt.plot(time, (maxima_envelope_smooth + minima_envelope_smooth) / 2, c='darkred') plt.plot(time, EEMD_maxima_envelope, c='darkgreen',", "Spectrum of CO$_{2}$ Concentration using emd 0.3.3', 45)) plt.ylabel('Frequency (year$^{-1}$)')", "101) max_2_x = maxima_y[-2] * np.ones_like(max_2_x_time) min_2_x_time = np.linspace(minima_x[-2] -", "width, 101) max_2_x = maxima_y[-2] * np.ones_like(max_2_x_time) min_2_x_time = np.linspace(minima_x[-2]", "+ width, 101) max_1_y_side = np.linspace(-2.1 - width, -2.1 +", "+ a) * np.pi, 101) time_series_reflect = np.flip(np.cos(np.linspace((5 - 2.6", "= fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima', smooth=True) util = Utility(time=time, time_series=time_series) maxima =", "plt.subplots_adjust(hspace=0.5) axs[0, 0].plot(time, signal) axs[0, 1].plot(time, signal) axs[0, 1].plot(time, imfs[0,", "- minima_x[-2]) Average_min = (minima_y[-2] + minima_y[-1]) / 2 utils_Huang", "0.1, 100), -2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time[-302] + time[-301]) /", "plt.subplots_adjust(hspace=0.3) figure_size = plt.gcf().get_size_inches() factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor *", "(Hz)') plt.xlabel('Time (s)') box_0 = ax.get_position() ax.set_position([box_0.x0, box_0.y0 + 0.05,", "# forward -> P = np.zeros((int(neural_network_k + 1), neural_network_m)) for", "'--', c='grey', label='Knots') axs[2].plot(knots[0] * np.ones(101), np.linspace(-2, 2, 101), '--',", "np.ones(100), c='gray') plt.plot(((time_extended[-1001] + time_extended[-1000]) / 2) * np.ones(100), np.linspace(-2.75,", "np.cos(2 * time) + np.cos(4 * time) + np.cos(8 *", "PyEMD import EMD as pyemd0215 import emd as emd040 sns.set(style='darkgrid')", "# plot 1e - addition fig, axs = plt.subplots(2, 1)", ":], label='IMF 2 with 31 knots') axs[2].plot(time, imfs_51[3, :], label='IMF", "101) end_point_time = time[-1] end_point = time_series[-1] time_reflect = np.linspace((5", "101), '--', c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots_uniform[0] * np.ones(101), np.linspace(-2,", "np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1) axs[1].plot(knot * np.ones(101),", "emd 0.3.3', 40)) plt.pcolormesh(t, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(t[:-1],", "* t) - py_emd[1, :])), 3)}') axs[1].plot(t, emd_sift[:, 1], '--',", "ifs_31 = advemdpy.empirical_mode_decomposition(knots=knots_31, max_imfs=2, edge_effect='symmetric_anchor', verbose=False)[:3] knots_11 = np.linspace(0, 5", "minima_line_dash, 'k--') plt.plot(maxima_line_dash_time, maxima_line_dash, 'k--') plt.plot(dash_1_time, dash_1, 'k--') plt.plot(dash_2_time, dash_2,", "np.pi) box_0 = ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width *", "plt.plot(time[500:], b_spline_basis[3, 500:].T, '--', label=r'$ B_{-2,4}(t) $') plt.plot(time[500:], b_spline_basis[4, 500:].T,", "0.5)) plt.savefig('jss_figures/pseudo_algorithm.png') plt.show() knots = np.arange(12) time = np.linspace(0, 11,", "axs[0].plot(time, b_spline_basis[5, :].T, '--', label='Basis 4') axs[0].legend(loc='upper left') axs[0].plot(5 *", "0.5)) plt.savefig('jss_figures/Duffing_equation_ht.png') plt.show() # Carbon Dioxide Concentration Example CO2_data =", "* np.pi * t / 50) + 0.6 * np.cos(2", "= Preprocess(time=preprocess_time, time_series=preprocess_time_series) axs[0].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[0].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple',", "axs[0].plot(t, py_emd[0, :], '--', label='PyEMD 0.2.10') axs[0].plot(t, emd_sift[:, 0], '--',", "- width, 2.5 + width, 101) maxima_dash_time_1 = maxima_x[-2] *", "axs[1].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[2].plot(knots_uniform[0]", "- minima_y[-2]), r'$s_1$') plt.text(4.43 * np.pi + (slope_based_minimum_time - minima_x[-1]),", "improved_slope_based_minimum = improved_slope_based_maximum + s2 * (improved_slope_based_minimum_time - improved_slope_based_maximum_time) min_dash_4", "weights += adjustment # test - bottom weights_right = np.hstack((weights,", "* t), '--', label=r'$0.1$cos$(0.08{\\pi}t)$') axs[1].set_title('IMF 2') axs[1].set_ylim([-0.2, 0.4]) axs[1].set_xlim([0, 150])", "label='Basis 1') axs[0].plot(time, b_spline_basis[3, :].T, '--', label='Basis 2') axs[0].plot(time, b_spline_basis[4,", "= np.zeros((int(neural_network_k + 1), neural_network_m)) for col in range(neural_network_m): P[:-1,", "np.asarray(signal) time = CO2_data['month'] time = np.asarray(time) # compare other", "- minima_y[-2]) / 2 A1 = np.abs(maxima_y[-1] - minima_y[-1]) /", "max_frequency=1.3, plot=False) ax = plt.subplot(111) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of", "figure_size = plt.gcf().get_size_inches() factor = 1.0 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1]))", "-3.4 * np.ones_like(minima_line_dash_time) # slightly edit signal to make difference", "* 0.8, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert.png')", "1, 2), ('-2', '-1', '0', '1', '2')) plt.xlim(-0.25 * np.pi,", "max_1_y_time = maxima_x[-1] * np.ones_like(max_1_y) min_1_y = np.linspace(minima_y[-1] - width,", "box_0.y0, box_0.width * 0.85, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_slope_based.png')", "bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_characteristic_wave.png') plt.show() # plot 6 t = np.linspace(5,", "imfs, hts, ifs, max_frequency=10, which_imfs=[1], plot=False) x_hs, y, z =", "= basis.cubic_b_spline(knots) chsi_basis = basis.chsi_basis(knots) # plot 1 plt.title('Non-Natural Cubic", "noise = np.random.normal(0, 1, len(time_series)) time_series += noise advemdpy =", "plt.plot(time_reflect[:51], time_series_anti_reflect[:51], '--', c='purple', LineWidth=2, label=textwrap.fill('Anti-symmetric signal', 10)) plt.plot(max_dash_time, max_dash,", "np.linspace(minima_x[-1] - width, minima_x[-1] + width, 101) min_1_x_time_side = np.linspace(5.4", "label=textwrap.fill('Unsmoothed minima envelope', 10), c='cyan') plt.plot(time, min_smoothed[0], label=textwrap.fill('Smoothed minima envelope',", "Preprocess from emd_mean import Fluctuation from AdvEMDpy import EMD #", "np.ones_like(x_hs[0, :]), '--', label=r'$\\omega = 4$', Linewidth=3) ax.plot(x_hs[0, :], 2", "* figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of CO$_{2}$ Concentration using", "np.ones(101), 'k--') axs[0].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), -5.5", "Knot Sequences', 40)) plt.subplots_adjust(hspace=0.1) axs[0].plot(time, time_series, label='Time series') axs[0].plot(time, imfs_51[1,", "axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2, zorder=100) axs[2].set_yticks(ticks=[-2, 0, 2]) axs[2].set_xticks(ticks=[0, np.pi,", "6], [r'$ \\tau_0 $', r'$ \\tau_1 $']) plt.xlim(4.4, 6.6) plt.plot(5", "range(1000): output = np.matmul(weights, train_input) error = (t - output)", "label=textwrap.fill('Inflection point envelope', 10)) plt.plot(time, binomial_points_envelope, c='deeppink', label=textwrap.fill('Binomial average envelope',", ":])), 3)}') for knot in knots_51: axs[0].plot(knot * np.ones(101), np.linspace(-5,", "1001) pseudo_alg_time_series = np.sin(pseudo_alg_time) + np.sin(5 * pseudo_alg_time) pseudo_utils =", "import emd as emd040 sns.set(style='darkgrid') pseudo_alg_time = np.linspace(0, 2 *", "axs[1].set_ylim(-5.5, 5.5) axs[1].set_xlim(0.95 * np.pi, 1.55 * np.pi) axs[2].plot(time, time_series,", "2), ('-2', '-1', '0', '1', '2')) plt.xlim(-0.25 * np.pi, 5.25", "* (len(lsq_signal) - 1) + 1 + i_right + 1)])", "frequency error: {np.round(sum(np.abs(IF - np.ones_like(IF)))[0], 3)}') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0,", "time_series[-1] * np.ones_like(anti_symmetric_time) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time, time_series, LineWidth=2,", "np.ones_like(minima_line_dash_time) # slightly edit signal to make difference between slope-based", "- top pyemd = pyemd0215() py_emd = pyemd(x) IP, IF,", "np.cos(time) + np.cos(5 * time) knots = np.linspace(0, 5 *", "2') axs[1].set_ylim([-0.2, 0.4]) axs[1].set_xlim([0, 150]) axis = 0 for ax", "B_{1,4}(t) $') plt.xticks([5, 6], [r'$ \\tau_0 $', r'$ \\tau_1 $'])", "top pyemd = pyemd0215() py_emd = pyemd(signal) IP, IF, IA", "'--', c='black') axs[0].plot(1.15 * np.pi * np.ones(101), np.linspace(-3, 3, 101),", "plt.plot(dash_max_min_1_x_time, dash_max_min_1_x, 'k--') plt.text(5.42 * np.pi, -0.1, r'$2a_1$') plt.plot(max_1_y_time, max_1_y,", "dash_2, 'k--') plt.plot(dash_3_time, dash_3, 'k--') plt.plot(dash_4_time, dash_4, 'k--') plt.plot(dash_final_time, dash_final,", "emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=1, verbose=False) fig, axs = plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10)", "time[-1] end_point = time_series[-1] time_reflect = np.linspace((5 - a) *", "neural_network_k + i_right): int(2 * (len(lsq_signal) - 1) + 1", "i_left + neural_network_k)], 1))) + 1 i_left += 1 if", "axs[1].plot(preprocess_time, preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker smoothing', 13)) axs[1].plot(downsampled_and_decimated[0], downsampled_and_decimated[1], label=textwrap.fill('Downsampled & decimated',", "= time[min_bool] minima_y = time_series[min_bool] max_dash_1 = np.linspace(maxima_y[-1] - width,", "plt.savefig('jss_figures/Duffing_equation_ht.png') plt.show() # Carbon Dioxide Concentration Example CO2_data = pd.read_csv('Data/co2_mm_mlo.csv',", "* np.ones_like(min_2_y) dash_max_min_2_y_time = np.linspace(minima_x[-2], maxima_x[-2], 101) dash_max_min_2_y = -1.8", "axs = plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Uniform", "date']) plt.title(textwrap.fill('Mean Monthly Concentration of Carbon Dioxide in the Atmosphere',", "# test - top seed_weights = np.ones(neural_network_k) / neural_network_k weights", "np.flip(np.cos(np.linspace((5 - 2.6 * a) * np.pi, (5 - a)", "other packages Duffing - top pyemd = pyemd0215() py_emd =", "c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[0].plot(preprocess_time, preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott smoothing', 12))", "with Different Knot Sequences Zoomed Region', 40)) plt.subplots_adjust(hspace=0.1) axs[0].plot(time, time_series,", "anti_symmetric_signal, 'r--', zorder=1) plt.plot(symmetry_axis_2_time, symmetry_axis, 'r--', label=textwrap.fill('Axes of symmetry', 10),", "lsq_signal = np.cos(time) + np.cos(5 * time) knots = np.linspace(0,", "+ time_extended[-1000]) / 2), ((time_extended[-1001] + time_extended[-1000]) / 2) -", "(i_right < len(lsq_signal) - 1): time_series_extended[int(2 * (len(lsq_signal) - 1)", "bbox_to_anchor=(1, 0.5), fontsize=8) axs[2].set_ylim(-5.5, 5.5) axs[2].set_xlim(0.95 * np.pi, 1.55 *", "* np.ones(101), np.linspace(-2, 2, 101), '--', c='grey') plt.savefig('jss_figures/knot_uniform.png') plt.show() #", "plt.scatter(time[maxima], time_series[maxima], c='r', label='Maxima', zorder=10) plt.scatter(time[minima], time_series[minima], c='b', label='Minima', zorder=10)", "5, 101), '--', c='grey', zorder=1, label='Knots') axs[0].set_xticks([0, np.pi, 2 *", "0, np.abs(z).max() ax.pcolormesh(x_hs, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) ax.plot(x_hs[0, :],", "= time_series_anti_reflect[anti_max_bool] utils = emd_utils.Utility(time=time, time_series=time_series_reflect) no_anchor_max_time = time_reflect[utils.max_bool_func_1st_order_fd()] no_anchor_max", "sum(emd_utils_min.min_bool_func_1st_order_fd()) > 0: min_count_left += 1 lsq_utils = emd_utils.Utility(time=time, time_series=lsq_signal)", "gradients = error * (- train_input) # guess average gradients", "hs_ouputs = hilbert_spectrum(time, imfs_51, hts_51, ifs_51, max_frequency=12, plot=False) # plot", "error: {np.round(sum(abs(0.1 * np.cos(0.04 * 2 * np.pi * t)", "[-1, 0, 1] fig, axs = plt.subplots(2, 1) plt.subplots_adjust(hspace=0.2) axs[0].plot(t,", "maxima_line_dash, 'k--') plt.plot(dash_1_time, dash_1, 'k--') plt.plot(dash_2_time, dash_2, 'k--') plt.plot(dash_3_time, dash_3,", "ifs_51, max_frequency=12, plot=False) # plot 6c ax = plt.subplot(111) figure_size", "101) max_1_x_time_side = np.linspace(5.4 * np.pi - width, 5.4 *", "axs[1].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1) axs[1].plot(knot", "np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[2].plot(knots_uniform[0] * np.ones(101), np.linspace(-2,", "+ (minima_x[-1] - minima_x[-2]) Average_min = (minima_y[-2] + minima_y[-1]) /", "and Uniform Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2, zorder=100) axs[2].set_yticks(ticks=[-2, 0,", "np.pi, 4 * np.pi, 5 * np.pi]) axs[0].set_xticklabels(['', '', '',", "+ minima_y[-1]) / 2 utils_Huang = emd_utils.Utility(time=time, time_series=Huang_wave) Huang_max_bool =", "= 0.25 width = 0.2 time = np.linspace((0 + a)", "plt.xlabel('Time (years)') plt.plot(x_hs[0, :], np.ones_like(x_hs[0, :]), 'k--', label=textwrap.fill('Annual cycle', 10))", "r'$2\\pi$']) axs[0].plot(knots[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots')", "maximum', 14)) plt.scatter(Average_min_time, Average_min, c='cyan', zorder=4, label=textwrap.fill('Average minimum', 14)) plt.scatter(maxima_x,", "b_spline_basis[4, :].T, '--', label='Basis 3') axs[0].plot(time, b_spline_basis[5, :].T, '--', label='Basis", "Wave', 14)) plt.plot(Coughlin_time, Coughlin_wave, '--', c='darkgreen', label=textwrap.fill('Coughlin Characteristic Wave', 14))", "plt.gcf().subplots_adjust(bottom=0.10) plt.title('Detrended Fluctuation Analysis Examples') plt.plot(time, time_series, LineWidth=2, label='Time series')", "plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess Filtering Demonstration') axs[1].set_title('Zoomed Region')", "0.4]) axs[1].set_xlim([0, 150]) axis = 0 for ax in axs.flat:", "and Dynamically Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2, zorder=100) axs[1].set_yticks(ticks=[-2, 0,", "box_0 = ax.get_position() ax.set_position([box_0.x0, box_0.y0 + 0.05, box_0.width * 0.85,", "'--', c='grey', zorder=1) plt.plot(knots[-1] * np.ones(101), np.linspace(-3.0, -2.0, 101), '--',", "np.ones(100), c='k') plt.plot(((time_extended[-1001] + time_extended[-1002]) / 2) * np.ones(100), np.linspace(-2.75,", "preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker smoothing', 13)) axs[1].plot(downsampled_and_decimated[0], downsampled_and_decimated[1], label=textwrap.fill('Downsampled & decimated', 13))", "== 1: pass if axis == 2: ax.set(ylabel=R'C0$_2$ concentration') ax.set(xlabel='Time", "series', zorder=2, LineWidth=2) plt.scatter(time[maxima], time_series[maxima], c='r', label='Maxima', zorder=10) plt.scatter(time[minima], time_series[minima],", "0 * seed_weights.copy() train_input = P[:-1, :] lr = 0.01", "1) + 1 + i_right + 1)]) if sum(emd_utils_max.max_bool_func_1st_order_fd()) >", "envelope', 10), c='darkorange') plt.plot(time, max_smoothed[0], label=textwrap.fill('Smoothed maxima envelope', 10), c='red')", "label=textwrap.fill('Smoothed maxima envelope', 10), c='red') plt.plot(time, min_unsmoothed[0], label=textwrap.fill('Unsmoothed minima envelope',", "* 2 * np.pi * t) - py_emd[1, :])), 3)}')", "sigma=1) ax = plt.subplot(111) figure_size = plt.gcf().get_size_inches() factor = 1.0", "= np.linspace(minima_y[-1], maxima_y[-1], 101) dash_max_min_1_x_time = 5.4 * np.pi *", "c='grey', zorder=1) axs[2].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey',", "+ width, 101) minima_dash_time_1 = minima_x[-2] * np.ones_like(minima_dash) minima_dash_time_2 =", "-2.1 * np.ones_like(dash_max_min_1_y_time) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Characteristic Wave Effects", "plt.scatter(Coughlin_min_time, Coughlin_min, c='dodgerblue', zorder=4, label=textwrap.fill('Coughlin minimum', 14)) plt.scatter(Average_max_time, Average_max, c='orangered',", "series', 12)) axs[1].plot(preprocess_time, preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott smoothing', 12)) axs[1].plot(preprocess_time, preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker", "5.5, 101), 'k--', label='Zoomed region') box_0 = axs[0].get_position() axs[0].set_position([box_0.x0 -", "utils.min_bool_func_1st_order_fd() minima_x = time[min_bool] minima_y = time_series[min_bool] inflection_bool = utils.inflection_point()", "label=textwrap.fill('Extrapolated signal', 12)) plt.scatter(maxima_time, maxima, c='r', zorder=3, label='Maxima') plt.scatter(minima_time, minima,", "maxima_y = time_series[max_bool] min_bool = utils.min_bool_func_1st_order_fd() minima_x = time[min_bool] minima_y", "from emd_utils import time_extension, Utility from scipy.interpolate import CubicSpline from", "r'$s_2$') plt.plot(minima_line_dash_time, minima_line_dash, 'k--') plt.plot(maxima_line_dash_time, maxima_line_dash, 'k--') plt.plot(dash_1_time, dash_1, 'k--')", "pass if axis == 2: ax.set(ylabel=R'C0$_2$ concentration') ax.set(xlabel='Time (years)') if", "axs[i].plot(knots[j] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey') plt.savefig('jss_figures/knot_1.png') plt.show()", "14)) plt.plot(max_2_x_time, max_2_x, 'k-') plt.plot(max_2_x_time_side, max_2_x, 'k-') plt.plot(min_2_x_time, min_2_x, 'k-')", "10)) plt.xlim(3.9 * np.pi, 5.5 * np.pi) plt.xticks((4 * np.pi,", "envelope', 10), c='blue') for knot in knots[:-1]: plt.plot(knot * np.ones(101),", "zorder=4, label='Minima') plt.scatter(time[optimal_maxima], time_series[optimal_maxima], c='darkred', zorder=4, label=textwrap.fill('Optimal maxima', 10)) plt.scatter(time[optimal_minima],", "max_discard_dash_time = np.linspace(max_discard_time - width, max_discard_time + width, 101) max_discard_dash", "smoothing_penalty=0.2, technique='binomial_average', order=21, increment=20)[0] derivative_of_lsq = utils.derivative_forward_diff() derivative_time = time[:-1]", "plt.xlim(3.9 * np.pi, 5.5 * np.pi) plt.xticks((4 * np.pi, 5", "-0.15)) box_1 = axs[1].get_position() axs[1].set_position([box_1.x0 - 0.06, box_1.y0, box_1.width *", "axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1 and Dynamically Knots') axs[1].plot(knot_demonstrate_time, imfs[1,", "200) util_nn = emd_utils.Utility(time=t, time_series=signal_orig) maxima = signal_orig[util_nn.max_bool_func_1st_order_fd()] minima =", "np.pi, 5 * np.pi), (r'4$\\pi$', r'5$\\pi$')) plt.yticks((-2, -1, 0, 1,", "axs[0].plot(time, b_spline_basis[4, :].T, '--', label='Basis 3') axs[0].plot(time, b_spline_basis[5, :].T, '--',", "np.zeros((int(neural_network_k + 1), neural_network_m)) for col in range(neural_network_m): P[:-1, col]", "plt.savefig('jss_figures/Duffing_equation_ht_emd.png') plt.show() # compare other packages Duffing - bottom emd_duffing", "minima_x[-1], 101) dash_1 = np.linspace(maxima_y[-1], minima_y[-1], 101) max_discard = maxima_y[-1]", "51 knots', 21)) for knot in knots_51: axs[0].plot(knot * np.ones(101),", "zorder=1) axs[2].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1,", "* figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Simple Sinusoidal Time", "= utils.min_bool_func_1st_order_fd() minima_x = time[min_bool] minima_y = time_series[min_bool] A2 =", "axs[0].set_title('IMF 1') axs[0].set_ylim([-2, 2]) axs[0].set_xlim([0, 150]) axs[1].plot(t, emd_duff[2, :], label='AdvEMDpy')", "axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1 and Statically Optimised Knots') axs[1].plot(knot_demonstrate_time,", "box_0.width * 0.85, box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[0].set_ylim(-5.5,", "max_discard_dash = max_discard * np.ones_like(max_discard_dash_time) dash_2_time = np.linspace(minima_x[-1], max_discard_time, 101)", "13)) axs[1].set_xlim(0.85 * np.pi, 1.15 * np.pi) axs[1].set_ylim(-3, 3) axs[1].set_yticks(ticks=[-2,", "np.ones_like(time), 'k--', label=textwrap.fill('Annual cycle', 10)) box_0 = ax.get_position() ax.set_position([box_0.x0 +", "basis = emd_basis.Basis(time=time, time_series=time) b_spline_basis = basis.cubic_b_spline(knots) chsi_basis = basis.chsi_basis(knots)", "500:].T, '--', label=r'$ B_{1,4}(t) $') plt.xticks([5, 6], [r'$ \\tau_0 $',", "'k--') plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4,", "2 * np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots[0] * np.ones(101), np.linspace(-2,", "axs[0].set_xticklabels(['', '', '', '', '', '']) axs[0].plot(np.linspace(0.95 * np.pi, 1.55", "ax.set_yticks([-0.2, 0, 0.2]) box_0 = ax.get_position() ax.set_position([box_0.x0, box_0.y0, box_0.width *", "* 0.8, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert_pyemd.png')", "* np.ones(101), np.linspace(-3, 3, 101), '--', c='black') axs[0].plot(1.15 * np.pi", "bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert_emd.png') plt.show() # compare other packages Carbon Dioxide", "emd.empirical_mode_decomposition(knots=knots_uniform, edge_effect='anti-symmetric', verbose=False)[0] fig, axs = plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10)", "max_1_x, 'k-') plt.plot(min_1_x_time, min_1_x, 'k-') plt.plot(min_1_x_time_side, min_1_x, 'k-') plt.plot(dash_max_min_1_x_time, dash_max_min_1_x,", "factor = 0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess Smoothing", "import cvxpy as cvx import seaborn as sns import matplotlib.pyplot", "time_series = np.cos(2 * time) + np.cos(4 * time) +", "np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots[1][0] *", ":], label='IMF 3 with 51 knots') for knot in knots_11:", "using AdvEMDpy', 40)) x, y, z = hs_ouputs y =", "np.pi, 4 * np.pi]) ax.set_xticklabels(['$0$', r'$\\pi$', r'$2\\pi$', r'$3\\pi$', r'$4\\pi$']) plt.ylabel(r'Frequency", "q=0.90)[1], c='grey', label=textwrap.fill('Quantile window', 12)) axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.10)[1], c='grey') axs[0].plot(np.linspace(0.85", "= emd_utils.Utility(time=t, time_series=signal_orig) maxima = signal_orig[util_nn.max_bool_func_1st_order_fd()] minima = signal_orig[util_nn.min_bool_func_1st_order_fd()] cs_max", "time_series, label='Time series', zorder=2, LineWidth=2) plt.scatter(time[maxima], time_series[maxima], c='r', label='Maxima', zorder=10)", "maxima_envelope_smooth = fluctuation.envelope_basis_function_approximation(knots, 'maxima', smooth=True, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] minima_envelope =", "10)) axs[0].plot(np.linspace(0.85 * np.pi, 1.15 * np.pi, 101), 3 *", "axs[0, 0].plot(time, signal) axs[0, 1].plot(time, signal) axs[0, 1].plot(time, imfs[0, :],", "np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots[1][0]", "np.cos(4 * time) + np.cos(8 * time) noise = np.random.normal(0,", "-> P = np.zeros((int(neural_network_k + 1), neural_network_m)) for col in", "11)) plt.scatter(slope_based_minimum_time, slope_based_minimum, c='purple', zorder=4, label=textwrap.fill('Slope-based minimum', 11)) plt.scatter(improved_slope_based_maximum_time, improved_slope_based_maximum,", "minima_x[-1]] improved_slope_based_maximum_time = time[-1] improved_slope_based_maximum = time_series[-1] improved_slope_based_minimum_time = slope_based_minimum_time", "label='Signal') plt.title('Slope-Based Edge Effects Example') plt.plot(max_dash_time_1, max_dash_1, 'k-') plt.plot(max_dash_time_2, max_dash_2,", "r'$2\\pi$', r'$3\\pi$', r'$4\\pi$', r'$5\\pi$']) box_2 = axs[2].get_position() axs[2].set_position([box_2.x0 - 0.05,", "Linewidth=3) ax.plot(x_hs[0, :], 2 * np.ones_like(x_hs[0, :]), '--', label=r'$\\omega =", "t) x = solution[:, 0] dxdt = solution[:, 1] x_points", "gaussian_filter(hht, sigma=1) fig, ax = plt.subplots() figure_size = plt.gcf().get_size_inches() factor", "Filtered Hilbert Spectrum of Simple Sinusoidal Time Seres with Added", "'g--', label=textwrap.fill('Driving function frequency', 15)) plt.xticks([0, 50, 100, 150]) plt.yticks([0,", "10), c='red') plt.plot(time, min_unsmoothed[0], label=textwrap.fill('Unsmoothed minima envelope', 10), c='cyan') plt.plot(time,", "AdvEMDpy.EMD(time=derivative_time, time_series=derivative_of_lsq) imf_1_of_derivative = emd.empirical_mode_decomposition(knots=derivative_knots, knot_time=derivative_time, text=False, verbose=False)[0][1, :] utils", "np.linspace(minima_x[-1] - width, minima_x[-1] + width, 101) min_dash = minima_y[-1]", "= minima_y[-1] * np.ones_like(min_1_x_time) dash_max_min_1_x = np.linspace(minima_y[-1], maxima_y[-1], 101) dash_max_min_1_x_time", "pd import cvxpy as cvx import seaborn as sns import", "maxima_x[-1] * np.ones_like(max_dash_1) max_dash_time_2 = maxima_x[-2] * np.ones_like(max_dash_1) min_dash_1 =", "= utils_Huang.max_bool_func_1st_order_fd() Huang_min_bool = utils_Huang.min_bool_func_1st_order_fd() utils_Coughlin = emd_utils.Utility(time=time, time_series=Coughlin_wave) Coughlin_max_bool", "1)]) if sum(emd_utils_min.min_bool_func_1st_order_fd()) > 0: min_count_right += 1 # backward", "region', 10)) axs[0].plot(np.linspace(0.85 * np.pi, 1.15 * np.pi, 101), 3", "axs[0].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[0].set_ylim(-5.5, 5.5) axs[0].set_xlim(0.95 * np.pi,", "= hilbert_spectrum(time, imfs, hts, ifs, max_frequency=10, which_imfs=[1], plot=False) x_hs, y,", "int(len(lsq_signal) - 1 - i_left + neural_network_k)], 1))) + 1", "zorder=4, label=textwrap.fill('Optimal minima', 10)) plt.scatter(inflection_x, inflection_y, c='magenta', zorder=4, label=textwrap.fill('Inflection points',", "smoothing', 13)) axs[1].plot(downsampled_and_decimated[0], downsampled_and_decimated[1], label=textwrap.fill('Downsampled & decimated', 13)) axs[1].plot(downsampled[0], downsampled[1],", "- 1) + 1 - neural_network_k + i_right): int(2 *", "max_dash_1 = np.linspace(maxima_y[-1] - width, maxima_y[-1] + width, 101) max_dash_2", "101), -5.5 * np.ones(101), 'k--') axs[2].plot(0.95 * np.pi * np.ones(101),", "min_dash_time = np.linspace(minima_x[-1] - width, minima_x[-1] + width, 101) min_dash", "12)) axs[1].plot(preprocess_time, preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median filter', 13)) axs[1].plot(preprocess_time, preprocess.winsorize(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize", "knots', 19)) for knot in knots_31: axs[1].plot(knot * np.ones(101), np.linspace(-5,", "ax = plt.subplots() figure_size = plt.gcf().get_size_inches() factor = 0.7 plt.gcf().set_size_inches((figure_size[0],", "label='Knots') axs[2].plot(knots[2][0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots')", "np.cos(0.04 * 2 * np.pi * t), '--', label=r'$0.1$cos$(0.08{\\pi}t)$') axs[1].set_title('IMF", "c='lime', zorder=4, label=textwrap.fill('Huang minimum', 10)) plt.scatter(Coughlin_max_time, Coughlin_max, c='darkorange', zorder=4, label=textwrap.fill('Coughlin", "plt.plot(length_distance_time_2, length_distance_2, 'k--') plt.plot(length_time, length_top, 'k-') plt.plot(length_time, length_bottom, 'k-') plt.plot(length_time_2,", "series', 12)) axs[0].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean filter', 12)) axs[0].plot(preprocess_time, preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median", "label=textwrap.fill('Hodrick-Prescott smoothing', 12)) axs[1].plot(preprocess_time, preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker smoothing', 13)) axs[1].plot(downsampled_and_decimated[0], downsampled_and_decimated[1],", "box_1 = axs[1].get_position() axs[1].set_position([box_1.x0 - 0.05, box_1.y0, box_1.width * 0.85,", "maxima_x[-2]) slope_based_maximum = minima_y[-1] + (slope_based_maximum_time - minima_x[-1]) * s1", "{np.round(sum(abs(0.1 * np.cos(0.04 * 2 * np.pi * t) -", "np.random.normal(0, 1) preprocess = Preprocess(time=preprocess_time, time_series=preprocess_time_series) axs[0].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[0].plot(pseudo_alg_time,", "* np.ones(101), '--', c='black') axs[0].plot(0.85 * np.pi * np.ones(101), np.linspace(-3,", "minima_y = time_series[min_bool] inflection_bool = utils.inflection_point() inflection_x = time[inflection_bool] inflection_y", "ax.get_position() ax.set_position([box_0.x0 + 0.0125, box_0.y0 + 0.075, box_0.width * 0.8,", "hts_51, ifs_51 = advemdpy.empirical_mode_decomposition(knots=knots_51, max_imfs=3, edge_effect='symmetric_anchor', verbose=False)[:3] knots_31 = np.linspace(0,", "vmax=z_max) ax.plot(x_hs[0, :], 8 * np.ones_like(x_hs[0, :]), '--', label=r'$\\omega =", "* np.pi * (1 / P1) * (Coughlin_time - Coughlin_time[0]))", "* np.pi, -2.5, r'$\\frac{p_1}{2}$') plt.xlim(3.9 * np.pi, 5.6 * np.pi)", "width, 5.3 * np.pi + width, 101) min_2_x = minima_y[-2]", "imfs_11, hts_11, ifs_11 = advemdpy.empirical_mode_decomposition(knots=knots_11, max_imfs=1, edge_effect='symmetric_anchor', verbose=False)[:3] fig, axs", "np.ones_like(max_2_x_time) min_2_x_time = np.linspace(minima_x[-2] - width, minima_x[-2] + width, 101)", "gamma = 0.1 epsilon = 1 omega = ((2 *", "np.sin(pseudo_alg_time) - 1, '--', c='c', label=r'$\\tilde{h}_{(1,0)}^m(t)$', zorder=5) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time), '--',", "time[-1] + width, 101) end_signal = time_series[-1] * np.ones_like(end_time) anti_symmetric_time", "1): time_series_extended[int(2 * (len(lsq_signal) - 1) + 1 + i_right)]", "$']) axs[0].set_xlim(4.5, 6.5) axs[1].set_title('Cubic Hermite Spline Bases') axs[1].plot(time, chsi_basis[10, :].T,", "Dioxide - bottom knots = np.linspace(time[0], time[-1], 200) emd_example =", "- width, maxima_y[-1] + width, 101) max_dash_2 = np.linspace(maxima_y[-2] -", "= emd_basis.Basis(time=time, time_series=time) b_spline_basis = basis.cubic_b_spline(knots) chsi_basis = basis.chsi_basis(knots) #", "utils.inflection_point() inflection_x = time[inflection_bool] inflection_y = time_series[inflection_bool] fluctuation = emd_mean.Fluctuation(time=time,", "plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) ax.pcolormesh(x, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max)", "no_anchor_max_time = time_reflect[utils.max_bool_func_1st_order_fd()] no_anchor_max = time_series_reflect[utils.max_bool_func_1st_order_fd()] point_1 = 5.4 length_distance", "(years)') plt.savefig('jss_figures/CO2_concentration.png') plt.show() signal = CO2_data['decimal date'] signal = np.asarray(signal)", "= time_series[inflection_bool] fluctuation = emd_mean.Fluctuation(time=time, time_series=time_series) maxima_envelope = fluctuation.envelope_basis_function_approximation(knots, 'maxima',", "np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[2].plot(knots_uniform[0] * np.ones(101),", "minimum', 11)) plt.scatter(improved_slope_based_maximum_time, improved_slope_based_maximum, c='deeppink', zorder=4, label=textwrap.fill('Improved slope-based maximum', 11))", "bottom weights_right = np.hstack((weights, 0)) max_count_right = 0 min_count_right =", "error: {np.round(sum(np.abs(IF - np.ones_like(IF)))[0], 3)}') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 2,", "box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/neural_network.png') plt.show() # plot 6a", "plt.show() emd_sift = emd040.sift.sift(x) IP, IF, IA = emd040.spectra.frequency_transform(emd_sift, 10,", "maxima_envelope, c='darkblue', label=textwrap.fill('EMD envelope', 10)) plt.plot(time, minima_envelope, c='darkblue') plt.plot(time, (maxima_envelope", "packages Duffing - bottom emd_duffing = AdvEMDpy.EMD(time=t, time_series=x) emd_duff, emd_ht_duff,", "= time[min_bool] minima_y = time_series[min_bool] A2 = np.abs(maxima_y[-2] - minima_y[-2])", "2, c='darkred') plt.plot(time, EEMD_maxima_envelope, c='darkgreen', label=textwrap.fill('EEMD envelope', 10)) plt.plot(time, EEMD_minima_envelope,", "= ax.get_position() ax.set_position([box_0.x0, box_0.y0 + 0.05, box_0.width * 0.85, box_0.height", "= - lr * average_gradients # adjustment = - lr", "filter', 14)) axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.90)[1], c='grey', label=textwrap.fill('Quantile window', 12)) axs[0].plot(preprocess_time,", "/ neural_network_k weights = 0 * seed_weights.copy() train_input = P[:-1,", "np.pi * t), '--', label=r'$0.1$cos$(0.08{\\pi}t)$') axs[1].set_title('IMF 2') axs[1].set_ylim([-0.2, 0.4]) axs[1].set_xlim([0,", "12)) axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.10)[1], c='grey') axs[1].set_xlim(0.85 * np.pi, 1.15 *", "+ 1):int(col + neural_network_k + 1)] P[-1, col] = 1", "c='b', zorder=4, label='Minima') plt.scatter(time[optimal_maxima], time_series[optimal_maxima], c='darkred', zorder=4, label=textwrap.fill('Optimal maxima', 10))", "_, _, _ = emd_duffing.empirical_mode_decomposition(verbose=False) fig, axs = plt.subplots(2, 1)", "2]) plt.xticks(ticks=[0, np.pi, 2 * np.pi], labels=[r'0', r'$\\pi$', r'$2\\pi$']) box_0", "time_series=time_series) imfs_51, hts_51, ifs_51 = advemdpy.empirical_mode_decomposition(knots=knots_51, max_imfs=3, edge_effect='symmetric_anchor', verbose=False)[:3] knots_31", "Dynamically Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2, zorder=100) axs[2].set_yticks(ticks=[-2, 0, 2])", "bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_symmetry_anti.png') plt.show() # plot 4 a = 0.21", "fig, axs = plt.subplots(2, 2) plt.subplots_adjust(hspace=0.5) axs[0, 0].plot(time, signal) axs[0,", "series') plt.scatter(maxima_x, maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4,", "million') plt.xlabel('Time (years)') plt.savefig('jss_figures/CO2_concentration.png') plt.show() signal = CO2_data['decimal date'] signal", "axs[0].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') axs[0].legend(loc='lower", "- np.ones_like(IF)))[0], 3)}') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 2, 100) hht", "axs[0].plot(1.55 * np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--', label='Zoomed", "minima_y[-1] + width, 101) min_1_y_side = np.linspace(-2.1 - width, -2.1", "IMF 2, & IMF 3 with 51 knots', 21)) for", "frequency approximation', 15)) plt.plot(t[:-1], 0.04 * np.ones_like(t[:-1]), 'g--', label=textwrap.fill('Driving function", "label=textwrap.fill('Noiseless time series', 12)) axs[0].plot(preprocess_time, preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott smoothing', 12)) axs[0].plot(preprocess_time,", "100), c='k', label=textwrap.fill('Neural network inputs', 13)) plt.plot(np.linspace(((time[-302] + time[-301]) /", "IA, freq_edges) hht = gaussian_filter(hht, sigma=1) fig, ax = plt.subplots()", "axs[i].plot(knots[i][j] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey') plt.savefig('jss_figures/knot_2.png') plt.show()", "bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht_emd.png') plt.show() # compare other packages Duffing -", "range(1, len(knots_uniform)): axs[i].plot(knots_uniform[j] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey')", "label='Knots') axs[0].legend(loc='lower left') axs[1].plot(knots[1][0] * np.ones(101), np.linspace(-2, 2, 101), '--',", "* np.pi, 101), 5.5 * np.ones(101), 'k--') axs[0].plot(np.linspace(0.95 * np.pi,", "plt.plot(Huang_time, Huang_wave, '--', c='darkviolet', label=textwrap.fill('Huang Characteristic Wave', 14)) plt.plot(Coughlin_time, Coughlin_wave,", "cs_max = CubicSpline(t[util_nn.max_bool_func_1st_order_fd()], maxima) cs_min = CubicSpline(t[util_nn.min_bool_func_1st_order_fd()], minima) time =", "t) - emd_sift[:, 1])), 3)}') axs[1].plot(t, 0.1 * np.cos(0.04 *", "width, maxima_y[-2] + width, 101) max_dash_time_1 = maxima_x[-1] * np.ones_like(max_dash_1)", "'--', c='grey', label='Knots') axs[2].plot(knots_uniform[0] * np.ones(101), np.linspace(-2, 2, 101), '--',", "time[:-1] derivative_knots = np.linspace(knots[0], knots[-1], 31) # change (1) detrended_fluctuation_technique", "minima_y[-2]), r'$s_1$') plt.text(4.43 * np.pi + (slope_based_minimum_time - minima_x[-1]), -0.20", "IMF 2 and IMF 3 with 51 knots', 19)) print(f'DFA", "np.random.seed(0) time = np.linspace(0, 5 * np.pi, 1001) knots_51 =", "box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht_emd.png') plt.show() #", "12)) axs[1].plot(preprocess_time, preprocess.hw(order=51)[1], label=textwrap.fill('Henderson-Whittaker smoothing', 13)) axs[1].plot(downsampled_and_decimated[0], downsampled_and_decimated[1], label=textwrap.fill('Downsampled &", "plt.show() # compare other packages Carbon Dioxide - bottom knots", "np.pi, 101)) + np.cos(5 * np.linspace((5 - 2.6 * a)", "np.pi, 0.35, r'$s_1$') plt.text(4.43 * np.pi, -0.20, r'$s_2$') plt.text(4.30 *", "- i_left):int(len(lsq_signal))], time_series=time_series_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))]) if sum(emd_utils_max.max_bool_func_1st_order_fd()) >", "101) s1 = (minima_y[-2] - maxima_y[-1]) / (minima_x[-2] - maxima_x[-1])", "Bases') axs[1].plot(time, chsi_basis[10, :].T, '--') axs[1].plot(time, chsi_basis[11, :].T, '--') axs[1].plot(time,", "ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width * 0.84, box_0.height]) ax.legend(loc='center", "min_2_y_side = np.linspace(-1.8 - width, -1.8 + width, 101) min_2_y_time", "+ time_extended[-1000]) / 2) - 0.1, 100), -2.75 * np.ones(100),", "* np.ones_like(maxima_dash) maxima_line_dash_time = np.linspace(maxima_x[-2], slope_based_maximum_time, 101) maxima_line_dash = 2.5", "label=r'$ B_{1,4}(t) $') plt.xticks([5, 6], [r'$ \\tau_0 $', r'$ \\tau_1", "1 - i_left):int(len(lsq_signal))]) if sum(emd_utils_min.min_bool_func_1st_order_fd()) > 0: min_count_left += 1", "minimum', 11)) plt.xlim(3.9 * np.pi, 5.5 * np.pi) plt.xticks((4 *", "for i in random.sample(range(1000), 500): preprocess_time_series[i] += np.random.normal(0, 1) preprocess", "- 0.1, 100), 2.75 * np.ones(100), c='k') plt.plot(((time_extended[-1001] + time_extended[-1002])", "label=textwrap.fill('Annual cycle', 10)) box_0 = ax.get_position() ax.set_position([box_0.x0 + 0.0125, box_0.y0", "figure_size = plt.gcf().get_size_inches() factor = 0.9 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1]))", "dash_2_time = np.linspace(maxima_x[-1], minima_x[-2], 101) dash_2 = np.linspace(maxima_y[-1], minima_y[-2], 101)", "'--', c='black') axs[0].set_yticks(ticks=[-2, 0, 2]) axs[0].set_xticks(ticks=[0, np.pi, 2 * np.pi])", "maxima_y[-1] + width, 101) max_dash_2 = np.linspace(maxima_y[-2] - width, maxima_y[-2]", "0.5)) plt.savefig('jss_figures/edge_effects_characteristic_wave.png') plt.show() # plot 6 t = np.linspace(5, 95,", "* np.pi, 5.25 * np.pi) box_0 = ax.get_position() ax.set_position([box_0.x0 -", "point_1 * np.pi * np.ones_like(length_distance) length_time = np.linspace(point_1 * np.pi", "dash_final_time = np.linspace(improved_slope_based_maximum_time, improved_slope_based_minimum_time, 101) dash_final = np.linspace(improved_slope_based_maximum, improved_slope_based_minimum, 101)", "Example') plt.plot(max_dash_time_1, max_dash_1, 'k-') plt.plot(max_dash_time_2, max_dash_2, 'k-') plt.plot(max_dash_time_3, max_dash_3, 'k-')", "2 and Statically Optimised Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :], Linewidth=2, zorder=100)", "in axs.flat: if axis == 0: ax.set(ylabel=R'C0$_2$ concentration') if axis", "np.pi, 1.15 * np.pi, 101), -3 * np.ones(101), '--', c='black',", "min_2_x, 'k-') plt.plot(dash_max_min_2_x_time, dash_max_min_2_x, 'k--') plt.text(5.16 * np.pi, 0.85, r'$2a_2$')", "axs[1].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].plot(np.linspace(0.95 * np.pi, 1.55 *", "np.ones_like(max_2_y) min_2_y = np.linspace(minima_y[-2] - width, minima_y[-2] + width, 101)", "axis = 0 for ax in axs.flat: if axis ==", "c='darkgreen', label=textwrap.fill('Coughlin Characteristic Wave', 14)) plt.plot(max_2_x_time, max_2_x, 'k-') plt.plot(max_2_x_time_side, max_2_x,", "100), c='k') plt.plot(((time[-202] + time[-201]) / 2) * np.ones(100), np.linspace(-2.75,", "to make difference between slope-based method and improved slope-based method", "= 0, np.abs(z).max() figure_size = plt.gcf().get_size_inches() factor = 1.0 plt.gcf().set_size_inches((figure_size[0],", "ax.set(ylabel=R'C0$_2$ concentration') ax.set(xlabel='Time (years)') if axis == 3: ax.set(xlabel='Time (years)')", "ifs, max_frequency=10, which_imfs=[1], plot=False) x_hs, y, z = hs_ouputs y", "for i in range(3): for j in range(1, len(knots)): axs[i].plot(knots[j]", "1 if i_left > 1: emd_utils_max = \\ emd_utils.Utility(time=time_extended[int(len(lsq_signal) -", "width, 101) max_1_y_side = np.linspace(-2.1 - width, -2.1 + width,", "np.pi]) axs[2].set_xticklabels([r'$\\pi$', r'$\\frac{3}{2}\\pi$']) box_2 = axs[2].get_position() axs[2].set_position([box_2.x0 - 0.05, box_2.y0,", "'k--') plt.plot(length_distance_time_2, length_distance_2, 'k--') plt.plot(length_time, length_top, 'k-') plt.plot(length_time, length_bottom, 'k-')", "axs[0].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize interpolation filter', 14)) axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.90)[1],", "label='Signal') plt.plot(time_extended, time_series_extended, c='g', zorder=1, label=textwrap.fill('Extrapolated signal', 12)) plt.scatter(maxima_time, maxima,", "x_hs, y, z = hs_ouputs z_min, z_max = 0, np.abs(z).max()", "plt.savefig('jss_figures/CO2_EMD.png') plt.show() hs_ouputs = hilbert_spectrum(time, imfs, hts, ifs, max_frequency=10, which_imfs=[1],", "verbose=False)[:3] knots_31 = np.linspace(0, 5 * np.pi, 31) imfs_31, hts_31,", "c='magenta', zorder=4, label=textwrap.fill('Inflection points', 10)) plt.plot(time, maxima_envelope, c='darkblue', label=textwrap.fill('EMD envelope',", "i_right = 0 while ((max_count_right < 1) or (min_count_right <", "np.linspace(max_discard_time - width, max_discard_time + width, 101) max_discard_dash = max_discard", "Extracted with Different Knot Sequences', 40)) plt.subplots_adjust(hspace=0.1) axs[0].plot(time, time_series, label='Time", "plt.show() hs_ouputs = hilbert_spectrum(time, imfs, hts, ifs, max_frequency=10, which_imfs=[1], plot=False)", "1c - addition knot_demonstrate_time = np.linspace(0, 2 * np.pi, 1001)", "- width, maxima_x[-2] + width, 101) max_2_x_time_side = np.linspace(5.3 *", "freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht)))) plt.plot(t[:-1], 0.124 * np.ones_like(t[:-1]), '--',", "101) min_1_y_side = np.linspace(-2.1 - width, -2.1 + width, 101)", "* np.pi, 51) fluc = Fluctuation(time=time, time_series=time_series) max_unsmoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots,", "1].legend(loc='lower right') axs[1, 0].plot(time, imfs[1, :]) axs[1, 1].plot(time, imfs[2, :])", "Coughlin_max, c='darkorange', zorder=4, label=textwrap.fill('Coughlin maximum', 14)) plt.scatter(Coughlin_min_time, Coughlin_min, c='dodgerblue', zorder=4,", "time_series_anti_reflect[anti_max_bool] utils = emd_utils.Utility(time=time, time_series=time_series_reflect) no_anchor_max_time = time_reflect[utils.max_bool_func_1st_order_fd()] no_anchor_max =", "box_1.height]) plt.savefig('jss_figures/preprocess_smooth.png') plt.show() # plot 2 fig, axs = plt.subplots(1,", "plot 1d - addition window = 81 fig, axs =", "min_dash_4, 'k-') plt.plot(maxima_dash_time_1, maxima_dash, 'k-') plt.plot(maxima_dash_time_2, maxima_dash, 'k-') plt.plot(maxima_dash_time_3, maxima_dash,", "label=textwrap.fill('Downsampled & decimated', 13)) axs[1].plot(downsampled[0], downsampled[1], label=textwrap.fill('Downsampled', 13)) axs[1].set_xlim(0.85 *", "fig, axs = plt.subplots(2, 1) fig.subplots_adjust(hspace=0.4) figure_size = plt.gcf().get_size_inches() factor", "* np.hstack((time_series_extended[ int(2 * (len(lsq_signal) - 1) + 1 -", "+ np.cos(5 * time) knots = np.linspace(0, 5 * np.pi,", "1.55 * np.pi, 101), -5.5 * np.ones(101), 'k--') axs[0].plot(0.95 *", "= np.matmul(weights, train_input) error = (t - output) gradients =", "r'$2\\pi$']) box_0 = ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width *", "r'$2\\pi$']) axs[2].set_title('IMF 2 and Statically Optimised Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :],", "= emd_utils.Utility(time=time, time_series=Huang_wave) Huang_max_bool = utils_Huang.max_bool_func_1st_order_fd() Huang_min_bool = utils_Huang.min_bool_func_1st_order_fd() utils_Coughlin", "max_imfs=2, edge_effect='symmetric_anchor', verbose=False)[:3] knots_11 = np.linspace(0, 5 * np.pi, 11)", "minima_x[-2] * np.ones_like(minima_dash) minima_dash_time_2 = minima_x[-1] * np.ones_like(minima_dash) minima_dash_time_3 =", "101) maxima_dash_time_1 = maxima_x[-2] * np.ones_like(maxima_dash) maxima_dash_time_2 = maxima_x[-1] *", "smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] minima_envelope = fluctuation.envelope_basis_function_approximation(knots, 'minima', smooth=False, smoothing_penalty=0.2, edge_effect='none',", "((2 * np.pi) / 25) return [xy[1], xy[0] - epsilon", "/ 2) + 0.1, 100), 2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time_extended[-1001]", "plot 7 a = 0.25 width = 0.2 time =", "1) plt.suptitle(textwrap.fill('Comparison of Trends Extracted with Different Knot Sequences Zoomed", "* np.ones_like(maxima_line_dash_time) minima_dash = np.linspace(-3.4 - width, -3.4 + width,", "0.2 time = np.linspace((0 + a) * np.pi, (5 -", "ax.set_position([box_0.x0 + 0.0125, box_0.y0 + 0.075, box_0.width * 0.8, box_0.height", "0.1 epsilon = 1 omega = ((2 * np.pi) /", ":])), 3)}') axs[1].plot(t, py_emd[1, :], '--', label='PyEMD 0.2.10') print(f'PyEMD driving", "12)) axs[1].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean filter', 12)) axs[1].plot(preprocess_time, preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median filter',", "np.pi, 2 * np.pi, 3 * np.pi, 4 * np.pi])", "np.ones_like(IF[:, 0]))), 3)}') freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 2, 100) hht", "EEMD_minima_envelope, c='darkgreen') plt.plot(time, (EEMD_maxima_envelope + EEMD_minima_envelope) / 2, c='darkgreen') plt.plot(time,", "width, 101) min_2_y_side = np.linspace(-1.8 - width, -1.8 + width,", ">= maxima_x[-2]] - time_series[time == maxima_x[-2]]) + maxima_y[-1] Coughlin_time =", "0.2.10', 45)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)') plt.pcolormesh(time, freq_bins, hht, cmap='gist_rainbow',", "for additive constant t = lsq_signal[-neural_network_m:] # test - top", "np.pi, -0.20, r'$s_2$') plt.text(4.30 * np.pi + (minima_x[-1] - minima_x[-2]),", "time_extended[-1000]) / 2) * np.ones(100), np.linspace(-2.75, 2.75, 100), c='gray', linestyle='dashed')", "# plot 6c time = np.linspace(0, 5 * np.pi, 1001)", "cvx.Problem(objective) result = prob.solve(verbose=True, solver=cvx.ECOS) weights_left = np.array(vx.value) max_count_left =", "label='emd 0.3.3') axs[0].set_title('IMF 1') axs[0].set_ylim([-2, 2]) axs[0].set_xlim([0, 150]) axs[1].plot(t, emd_duff[2,", "= cvx.Variable(int(neural_network_k + 1)) objective = cvx.Minimize(cvx.norm((2 * (vx *", "factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess Filtering Demonstration') axs[1].set_title('Zoomed Region') preprocess_time", "label=textwrap.fill('EEMD envelope', 10)) plt.plot(time, EEMD_minima_envelope, c='darkgreen') plt.plot(time, (EEMD_maxima_envelope + EEMD_minima_envelope)", "emd = EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series) imfs = emd.empirical_mode_decomposition(knots=knots_uniform, edge_effect='anti-symmetric', verbose=False)[0] fig,", "minima_dash, 'k-') plt.text(4.34 * np.pi, -3.2, r'$\\Delta{t^{min}_{m}}$') plt.text(4.74 * np.pi,", "P[:-1, :] lr = 0.01 for iterations in range(1000): output", "np.linspace(maxima_y[-1], minima_y[-1], 101) dash_2_time = np.linspace(maxima_x[-1], minima_x[-2], 101) dash_2 =", "np.pi, 101), -5.5 * np.ones(101), 'k--') axs[2].plot(0.95 * np.pi *", "figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Simple Sinusoidal Time Seres", "= np.linspace(slope_based_maximum_time, slope_based_minimum_time) dash_4 = np.linspace(slope_based_maximum, slope_based_minimum) maxima_dash = np.linspace(2.5", "+= noise advemdpy = EMD(time=time, time_series=time_series) imfs_51, hts_51, ifs_51 =", "* np.ones_like(anti_symmetric_time) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time, time_series, LineWidth=2, label='Signal')", "'k-') plt.plot(max_dash_time_2, max_dash_2, 'k-') plt.plot(max_dash_time_3, max_dash_3, 'k-') plt.plot(min_dash_time_1, min_dash_1, 'k-')", "c='grey', zorder=1) axs[0].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey',", "0.8 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess Filtering Demonstration') axs[1].set_title('Zoomed", "plt.plot(maxima_dash_time_2, maxima_dash, 'k-') plt.plot(maxima_dash_time_3, maxima_dash, 'k-') plt.plot(minima_dash_time_1, minima_dash, 'k-') plt.plot(minima_dash_time_2,", "- 1 - i_left):int(len(lsq_signal))]) if sum(emd_utils_min.min_bool_func_1st_order_fd()) > 0: min_count_left +=", "= np.linspace(0, 5 * np.pi, 1001) knots_51 = np.linspace(0, 5", "minima_y[-1] * np.ones_like(min_1_x_time) dash_max_min_1_x = np.linspace(minima_y[-1], maxima_y[-1], 101) dash_max_min_1_x_time =", "np.ones_like(min_2_y) dash_max_min_2_y_time = np.linspace(minima_x[-2], maxima_x[-2], 101) dash_max_min_2_y = -1.8 *", "width, 2.5 + width, 101) maxima_dash_time_1 = maxima_x[-2] * np.ones_like(maxima_dash)", "axs[1].plot(time, imfs_51[2, :] + imfs_51[3, :], label=textwrap.fill('Sum of IMF 2", "minima_x[-1] max_discard_dash_time = np.linspace(max_discard_time - width, max_discard_time + width, 101)", "_, _, _, knots, _, _ = emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=1, verbose=False)", "axis = 0 for ax in axs.flat: ax.label_outer() if axis", "x, y, z = hs_ouputs y = y / (2", "$') plt.plot(time[500:], b_spline_basis[6, 500:].T, '--', label=r'$ B_{1,4}(t) $') plt.xticks([5, 6],", "width, minima_y[-2] + width, 101) min_2_y_side = np.linspace(-1.8 - width,", ":], '--', label='PyEMD 0.2.10') axs[0].plot(t, emd_sift[:, 0], '--', label='emd 0.3.3')", "time_series_extended[int(len(lsq_signal) - 1):int(2 * (len(lsq_signal) - 1) + 1)] =", "mean') plt.xticks((0, 1 * np.pi, 2 * np.pi, 3 *", "zorder=100) axs[0].set_yticks(ticks=[-2, 0, 2]) axs[0].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[0].set_xticklabels(labels=['0',", "'-2', '-1', '0', '1', '2')) box_0 = ax.get_position() ax.set_position([box_0.x0 -", "minima_x[-2], 101) dash_2 = np.linspace(maxima_y[-1], minima_y[-2], 101) s1 = (minima_y[-2]", "label=textwrap.fill('Noiseless time series', 12)) axs[1].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean filter', 12)) axs[1].plot(preprocess_time,", "plt.scatter(Huang_max_time, Huang_max, c='magenta', zorder=4, label=textwrap.fill('Huang maximum', 10)) plt.scatter(Huang_min_time, Huang_min, c='lime',", "figure_size[1])) ax.pcolormesh(x, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max) plt.plot(t[:-1], 0.124 *", "1)] P[-1, col] = 1 # for additive constant t", "axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots[0][0] * np.ones(101), np.linspace(-2, 2, 101), '--',", "= emd_utils.Utility(time=time[:-1], time_series=imf_1_of_derivative) optimal_maxima = np.r_[False, utils.derivative_forward_diff() < 0, False]", "label='Knots') axs[2].set_xticks([np.pi, (3 / 2) * np.pi]) axs[2].set_xticklabels([r'$\\pi$', r'$\\frac{3}{2}\\pi$']) box_2", "minima_x[-2]), 0.35 + (minima_y[-1] - minima_y[-2]), r'$s_1$') plt.text(4.43 * np.pi", "improved_slope_based_minimum_time, 101) dash_final = np.linspace(improved_slope_based_maximum, improved_slope_based_minimum, 101) ax = plt.subplot(111)", "+ np.cos(4 * time) + np.cos(8 * time) noise =", "preprocess_time_series[i] += np.random.normal(0, 1) preprocess = Preprocess(time=preprocess_time, time_series=preprocess_time_series) axs[0].plot(preprocess_time, preprocess_time_series,", "101) min_dash_time_4 = improved_slope_based_minimum_time * np.ones_like(min_dash_4) dash_final_time = np.linspace(improved_slope_based_maximum_time, improved_slope_based_minimum_time,", "decimated', 13)) axs[1].plot(downsampled[0], downsampled[1], label=textwrap.fill('Downsampled', 13)) axs[1].set_xlim(0.85 * np.pi, 1.15", "preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean filter', 12)) axs[1].plot(preprocess_time, preprocess.median_filter(window_width=window)[1], label=textwrap.fill('Median filter', 13)) axs[1].plot(preprocess_time,", "np.pi) - np.ones_like(ifs[1, :]))), 3)}') fig, axs = plt.subplots(2, 2)", "Linewidth=3) ax.set_xticks([0, np.pi, 2 * np.pi, 3 * np.pi, 4", "util.max_bool_func_1st_order_fd() minima = util.min_bool_func_1st_order_fd() ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title(textwrap.fill('Plot Demonstrating", "0 for ax in axs.flat: if axis == 0: ax.set(ylabel=R'C0$_2$", "minimum', 14)) plt.scatter(Average_max_time, Average_max, c='orangered', zorder=4, label=textwrap.fill('Average maximum', 14)) plt.scatter(Average_min_time,", "if axis == 2: ax.set(ylabel=R'C0$_2$ concentration') ax.set(xlabel='Time (years)') if axis", "0.85, box_1.height]) plt.savefig('jss_figures/preprocess_smooth.png') plt.show() # plot 2 fig, axs =", "0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht_emd.png') plt.show() # compare other", "plt.scatter(time[optimal_maxima], time_series[optimal_maxima], c='darkred', zorder=4, label=textwrap.fill('Optimal maxima', 10)) plt.scatter(time[optimal_minima], time_series[optimal_minima], c='darkblue',", "# Carbon Dioxide Concentration Example CO2_data = pd.read_csv('Data/co2_mm_mlo.csv', header=51) plt.plot(CO2_data['month'],", "a) * np.pi, 11) time_series = np.cos(time) + np.cos(5 *", "minima_x[-1] + (minima_x[-1] - minima_x[-2]) slope_based_minimum = slope_based_maximum - (slope_based_maximum_time", "zorder=4, label=textwrap.fill('Extrapolated minima', 12)) plt.plot(((time[-302] + time[-301]) / 2) *", "box_1.width * 0.85, box_1.height]) axs[1].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].set_ylim(-5.5,", "plt.scatter(max_discard_time, max_discard, c='purple', zorder=4, label=textwrap.fill('Symmetric Discard maxima', 10)) plt.scatter(end_point_time, end_point,", "np.pi]) axs[1].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2 and Statically Optimised Knots')", "plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Simple", "* np.ones(101), 'k--') axs[2].plot(0.95 * np.pi * np.ones(101), np.linspace(-5.5, 5.5,", "= AdvEMDpy.EMD(time=derivative_time, time_series=derivative_of_lsq) imf_1_of_derivative = emd.empirical_mode_decomposition(knots=derivative_knots, knot_time=derivative_time, text=False, verbose=False)[0][1, :]", "c='grey') plt.savefig('jss_figures/knot_1.png') plt.show() # plot 1c - addition knot_demonstrate_time =", "left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[2].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi,", "5 * np.pi), (r'4$\\pi$', r'5$\\pi$')) plt.yticks((-3, -2, -1, 0, 1,", "no_anchor_max = time_series_reflect[utils.max_bool_func_1st_order_fd()] point_1 = 5.4 length_distance = np.linspace(maxima_y[-1], minima_y[-1],", ":], label='AdvEMDpy') axs[0].plot(t, py_emd[0, :], '--', label='PyEMD 0.2.10') axs[0].plot(t, emd_sift[:,", "plt.plot(max_dash_time, max_dash, 'k-') plt.plot(min_dash_time, min_dash, 'k-') plt.plot(dash_1_time, dash_1, 'k--') plt.plot(dash_2_time,", "axs[2].plot(knots[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey', label='Knots') for", "preprocess.quantile_filter(window_width=window, q=0.90)[1], c='grey', label=textwrap.fill('Quantile window', 12)) axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.10)[1], c='grey')", "/ P2) * (time[time >= maxima_x[-2]] - time[time == maxima_x[-2]])", "time_extended[utils_extended.max_bool_func_1st_order_fd()][-1] minima = lsq_signal[lsq_utils.min_bool_func_1st_order_fd()] minima_time = time[lsq_utils.min_bool_func_1st_order_fd()] minima_extrapolate = time_series_extended[utils_extended.min_bool_func_1st_order_fd()][-2:]", "= maxima_y[-2] * np.ones_like(max_2_x_time) min_2_x_time = np.linspace(minima_x[-2] - width, minima_x[-2]", "concentration') ax.set(xlabel='Time (years)') if axis == 3: ax.set(xlabel='Time (years)') axis", "1.55 * np.pi, 101), -5.5 * np.ones(101), 'k--') axs[2].plot(0.95 *", "= preprocess.downsample() axs[0].plot(downsampled_and_decimated[0], downsampled_and_decimated[1], label=textwrap.fill('Downsampled & decimated', 11)) downsampled =", "np.ones_like(maxima_dash) maxima_line_dash_time = np.linspace(maxima_x[-2], slope_based_maximum_time, 101) maxima_line_dash = 2.5 *", "plt.plot(time, EEMD_minima_envelope, c='darkgreen') plt.plot(time, (EEMD_maxima_envelope + EEMD_minima_envelope) / 2, c='darkgreen')", "= AdvEMDpy.EMD(time=time, time_series=signal) imfs, hts, ifs, _, _, _, _", "np.pi, 1001) knots_51 = np.linspace(0, 5 * np.pi, 51) time_series", "101), 'k--', label='Zoomed region') axs[2].plot(time, time_series, label='Time series') axs[2].plot(time, imfs_11[1,", "500:].T, '--', label=r'$ B_{-2,4}(t) $') plt.plot(time[500:], b_spline_basis[4, 500:].T, '--', label=r'$", "+ (maxima_x[-1] - maxima_x[-2]) Average_max = (maxima_y[-2] + maxima_y[-1]) /", "'--', label='Basis 4') axs[0].legend(loc='upper left') axs[0].plot(5 * np.ones(100), np.linspace(-0.2, 0.8,", "= EMD(time=time, time_series=time_series) imfs_51, hts_51, ifs_51 = advemdpy.empirical_mode_decomposition(knots=knots_51, max_imfs=3, edge_effect='symmetric_anchor',", "emd_duff, emd_ht_duff, emd_if_duff, max_frequency=1.3, plot=False) ax = plt.subplot(111) plt.title(textwrap.fill('Gaussian Filtered", "axs[0, 1].set_title('Smoothed CO$_2$ Concentration') axs[1, 0].set_title('IMF 1') axs[1, 1].set_title('Residual') plt.gcf().subplots_adjust(bottom=0.15)", "plot 4 a = 0.21 width = 0.2 time =", "np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--', label='Zoomed region') box_0", "Linewidth=2, zorder=100) axs[2].set_yticks(ticks=[-2, 0, 2]) axs[2].set_xticks(ticks=[0, np.pi, 2 * np.pi])", "and (3) debug (confusing with external debugging) emd = AdvEMDpy.EMD(time=derivative_time,", "IA, freq_edges) hht = gaussian_filter(hht, sigma=1) ax = plt.subplot(111) figure_size", "* 0.8, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/CO2_Hilbert_emd.png')", "-3.4 + width, 101) minima_dash_time_1 = minima_x[-2] * np.ones_like(minima_dash) minima_dash_time_2", "= pyemd(x) IP, IF, IA = emd040.spectra.frequency_transform(py_emd.T, 10, 'hilbert') freq_edges,", "* np.pi + width, 101) max_2_x = maxima_y[-2] * np.ones_like(max_2_x_time)", "plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Preprocess Smoothing Demonstration') axs[1].set_title('Zoomed Region')", "end_signal = time_series[-1] * np.ones_like(end_time) anti_symmetric_time = np.linspace(time[-1] - 0.5,", "2 * np.pi * t) - py_emd[1, :])), 3)}') axs[1].plot(t,", "col] = lsq_signal[(-(neural_network_m + neural_network_k - col)):(-(neural_network_m - col))] P[-1,", "min_dash_3, 'k-') plt.plot(min_dash_time_4, min_dash_4, 'k-') plt.plot(maxima_dash_time_1, maxima_dash, 'k-') plt.plot(maxima_dash_time_2, maxima_dash,", "maximum', 11)) plt.scatter(improved_slope_based_minimum_time, improved_slope_based_minimum, c='dodgerblue', zorder=4, label=textwrap.fill('Improved slope-based minimum', 11))", "imf_1_of_derivative = emd.empirical_mode_decomposition(knots=derivative_knots, knot_time=derivative_time, text=False, verbose=False)[0][1, :] utils = emd_utils.Utility(time=time[:-1],", "np.ones_like(dash_max_min_2_y_time) max_1_x_time = np.linspace(maxima_x[-1] - width, maxima_x[-1] + width, 101)", "+ 1 - neural_network_k + i_right): int(2 * (len(lsq_signal) -", "2) + 0.1, 100), 2.75 * np.ones(100), c='gray') plt.plot(np.linspace(((time_extended[-1001] +", "np.pi) plt.xticks((4 * np.pi, 5 * np.pi), (r'4$\\pi$', r'5$\\pi$')) plt.yticks((-2,", "* np.pi + (slope_based_minimum_time - minima_x[-1]), 1.20 + (slope_based_minimum -", "/ 2) + 0.1, 100), -2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time[-302]", "* np.pi, 4 * np.pi]) ax.set_xticklabels(['$0$', r'$\\pi$', r'$2\\pi$', r'$3\\pi$', r'$4\\pi$'])", "label=textwrap.fill('Anti-symmetric signal', 10)) plt.plot(max_dash_time, max_dash, 'k-') plt.plot(min_dash_time, min_dash, 'k-') plt.plot(dash_1_time,", "= np.random.normal(0, 1, len(time_series)) time_series += noise advemdpy = EMD(time=time,", "= minima_x[-2] * np.ones_like(min_2_y) dash_max_min_2_y_time = np.linspace(minima_x[-2], maxima_x[-2], 101) dash_max_min_2_y", "-1.8 + width, 101) max_2_y_time = maxima_x[-2] * np.ones_like(max_2_y) min_2_y", "plt.scatter(slope_based_minimum_time, slope_based_minimum, c='purple', zorder=4, label=textwrap.fill('Slope-based minimum', 11)) plt.scatter(improved_slope_based_maximum_time, improved_slope_based_maximum, c='deeppink',", "and Statically Optimised Knots') axs[1].plot(knot_demonstrate_time, imfs[1, :], Linewidth=2, zorder=100) axs[1].set_yticks(ticks=[-2,", "np.linspace(-3, 3, 101), '--', c='black') axs[0].set_yticks(ticks=[-2, 0, 2]) axs[0].set_xticks(ticks=[0, np.pi,", "left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/pseudo_algorithm.png') plt.show() knots = np.arange(12) time =", "c='k') plt.plot(((time[-202] + time[-201]) / 2) * np.ones(100), np.linspace(-2.75, 2.75,", "result = prob.solve(verbose=True, solver=cvx.ECOS) weights_left = np.array(vx.value) max_count_left = 0", "a=0.8)[1], label=textwrap.fill('Windsorize interpolation filter', 14)) axs[0].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.90)[1], c='grey', label=textwrap.fill('Quantile", "+ width, 101) maxima_dash_time_1 = maxima_x[-2] * np.ones_like(maxima_dash) maxima_dash_time_2 =", "/ 200) util_nn = emd_utils.Utility(time=t, time_series=signal_orig) maxima = signal_orig[util_nn.max_bool_func_1st_order_fd()] minima", "'']) axs[0].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), 5.5 *", "emd_sift[:, 1], '--', label='emd 0.3.3') print(f'emd driving function error: {np.round(sum(abs(0.1", "label=textwrap.fill('Noiseless time series', 12)) axs[1].plot(preprocess_time, preprocess.hp()[1], label=textwrap.fill('Hodrick-Prescott smoothing', 12)) axs[1].plot(preprocess_time,", "= np.linspace(0, 2 * np.pi, 1001) pseudo_alg_time_series = np.sin(pseudo_alg_time) +", "length_bottom = minima_y[-1] * np.ones_like(length_time) point_2 = 5.2 length_distance_2 =", "minima_x = time[min_bool] minima_y = time_series[min_bool] inflection_bool = utils.inflection_point() inflection_x", "knots = np.linspace((0 + a) * np.pi, (5 - a)", "hs_ouputs = hilbert_spectrum(t, emd_duff, emd_ht_duff, emd_if_duff, max_frequency=1.3, plot=False) ax =", "* np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--', label='Zoomed region') box_0 =", "emd_preprocess import Preprocess from emd_mean import Fluctuation from AdvEMDpy import", "- addition fig = plt.figure(figsize=(9, 4)) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10)", "r'$2\\pi$', r'$3\\pi$', r'$4\\pi$']) plt.ylabel(r'Frequency (rad.s$^{-1}$)') plt.xlabel('Time (s)') box_0 = ax.get_position()", "fluctuation.envelope_basis_function_approximation(knots, 'minima', smooth=True, smoothing_penalty=0.2, edge_effect='none', spline_method='b_spline')[0] inflection_points_envelope = fluctuation.direct_detrended_fluctuation_estimation(knots, smooth=True,", "= [-1, 0, 1] fig, axs = plt.subplots(2, 1) plt.subplots_adjust(hspace=0.2)", "'', '']) axs[0].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), 5.5", "if Schoenberg–Whitney Conditions are Not Satisfied', 50)) plt.plot(time, time_series, label='Time", "plt.title('Characteristic Wave Effects Example') plt.plot(time, time_series, LineWidth=2, label='Signal') plt.scatter(Huang_max_time, Huang_max,", "preprocess.winsorize(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize filter', 12)) axs[1].plot(preprocess_time, preprocess.winsorize_interpolate(window_width=window, a=0.8)[1], label=textwrap.fill('Windsorize interpolation", "plt.plot(time[500:], b_spline_basis[5, 500:].T, '--', label=r'$ B_{0,4}(t) $') plt.plot(time[500:], b_spline_basis[6, 500:].T,", "- 0.05, box_0.y0, box_0.width * 0.85, box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1,", "emd_mean import Fluctuation from AdvEMDpy import EMD # alternate packages", "= maxima_x[-1] * np.ones_like(max_dash_1) max_dash_time_2 = maxima_x[-2] * np.ones_like(max_dash_1) min_dash_1", "'--', label='Basis 1') axs[0].plot(time, b_spline_basis[3, :].T, '--', label='Basis 2') axs[0].plot(time,", "= -1.8 * np.ones_like(dash_max_min_2_y_time) max_1_x_time = np.linspace(maxima_x[-1] - width, maxima_x[-1]", "c='black') axs[0].set_yticks(ticks=[-2, 0, 2]) axs[0].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[0].set_xticklabels(labels=['0',", "0, 2]) axs[1].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[1].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$'])", "int(2 * (len(lsq_signal) - 1) + 1 + i_right)], 1)))", "seed_weights.copy() train_input = P[:-1, :] lr = 0.01 for iterations", "2), ((time_extended[-1001] + time_extended[-1002]) / 2) - 0.1, 100), 2.75", "fig = plt.figure(figsize=(9, 4)) ax = plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('First Iteration", "plt.plot(maxima_line_dash_time, maxima_line_dash, 'k--') plt.plot(dash_1_time, dash_1, 'k--') plt.plot(dash_2_time, dash_2, 'k--') plt.plot(dash_3_time,", "box_0 = ax.get_position() ax.set_position([box_0.x0 - 0.05, box_0.y0, box_0.width * 0.84,", "knots, _, _ = emd.empirical_mode_decomposition(edge_effect='anti-symmetric', optimise_knots=2, verbose=False) fig, axs =", "time_series=time_series_extended) maxima = lsq_signal[lsq_utils.max_bool_func_1st_order_fd()] maxima_time = time[lsq_utils.max_bool_func_1st_order_fd()] maxima_extrapolate = time_series_extended[utils_extended.max_bool_func_1st_order_fd()][-1]", "edge_effect='none')[0] EEMD_minima_envelope = fluctuation.envelope_basis_function_approximation_fixed_points(knots, 'minima', optimal_maxima, optimal_minima, smooth=False, smoothing_penalty=0.2, edge_effect='none')[0]", "z_min, z_max = 0, np.abs(z).max() fig, ax = plt.subplots() figure_size", "lsq_signal[int(col + 1):int(col + neural_network_k + 1)] P[-1, col] =", "axs[0].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1", "np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1 and Dynamically Knots') axs[1].plot(knot_demonstrate_time,", "plt.savefig('jss_figures/boundary_bases.png') plt.show() # plot 1a - addition knot_demonstrate_time = np.linspace(0,", "r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey',", "'k--') axs[1].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), -5.5 *", "i_left):int(len(lsq_signal))], time_series=time_series_extended[int(len(lsq_signal) - 1 - i_left):int(len(lsq_signal))]) if sum(emd_utils_min.min_bool_func_1st_order_fd()) > 0:", "label=textwrap.fill('Annual cycle', 10)) ax.axis([x_hs.min(), x_hs.max(), y.min(), y.max()]) box_0 = ax.get_position()", ":].T, '--') axs[1].plot(5 * np.ones(100), np.linspace(-0.2, 1.2, 100), 'k-') axs[1].plot(6", "zorder=1) plt.text(5.1 * np.pi, -0.7, r'$\\beta$L') plt.text(5.34 * np.pi, -0.05,", "np.ones_like(length_time) point_2 = 5.2 length_distance_2 = np.linspace(time_series[-1], minima_y[-1], 101) length_distance_time_2", "+ i_right + 1)], time_series=time_series_extended[int(2 * (len(lsq_signal) - 1) +", "np.abs(z).max() figure_size = plt.gcf().get_size_inches() factor = 1.0 plt.gcf().set_size_inches((figure_size[0], factor *", "plt.plot(time, max_smoothed[0], label=textwrap.fill('Smoothed maxima envelope', 10), c='red') plt.plot(time, min_unsmoothed[0], label=textwrap.fill('Unsmoothed", "sum(emd_utils_min.min_bool_func_1st_order_fd()) > 0: min_count_right += 1 # backward <- P", "0.85, r'$2a_2$') plt.plot(max_2_y_time, max_2_y, 'k-') plt.plot(max_2_y_time, max_2_y_side, 'k-') plt.plot(min_2_y_time, min_2_y,", "* 2 * np.pi * t) - emd_duff[2, :])), 3)}')", "width, 101) min_1_x = minima_y[-1] * np.ones_like(min_1_x_time) dash_max_min_1_x = np.linspace(minima_y[-1],", "* 0.85, box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) axs[1].plot(time, time_series,", "- slope_based_minimum_time) * s2 min_dash_time_3 = slope_based_minimum_time * np.ones_like(min_dash_1) min_dash_3", "0.75, box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/Duffing_equation_ht_pyemd.png') plt.show()", "'--', c='grey', zorder=1, label='Knots') axs[0].set_xticks([0, np.pi, 2 * np.pi, 3", "time = np.linspace(0, 11, 1101) basis = emd_basis.Basis(time=time, time_series=time) b_spline_basis", "(improved_slope_based_minimum_time - improved_slope_based_maximum_time) min_dash_4 = np.linspace(improved_slope_based_minimum - width, improved_slope_based_minimum +", "[1, 1] solution = odeint(duffing_equation, XY0, t) x = solution[:,", "1)]) if sum(emd_utils_max.max_bool_func_1st_order_fd()) > 0: max_count_right += 1 emd_utils_min =", "zorder=4, label=textwrap.fill('Slope-based maximum', 11)) plt.scatter(slope_based_minimum_time, slope_based_minimum, c='purple', zorder=4, label=textwrap.fill('Slope-based minimum',", "2, r'$\\Delta{t^{max}_{M}}$') plt.text(4.50 * np.pi, 2, r'$\\Delta{t^{max}_{M}}$') plt.text(4.30 * np.pi,", "time) noise = np.random.normal(0, 1, len(time_series)) time_series += noise advemdpy", "time_series=time_series) max_bool = utils.max_bool_func_1st_order_fd() maxima_x = time[max_bool] maxima_y = time_series[max_bool]", "= 0.9 plt.gcf().set_size_inches((figure_size[0], factor * figure_size[1])) plt.gcf().subplots_adjust(bottom=0.10) plt.plot(time, time_series, LineWidth=2,", "plt.plot(minima_dash_time_1, minima_dash, 'k-') plt.plot(minima_dash_time_2, minima_dash, 'k-') plt.plot(minima_dash_time_3, minima_dash, 'k-') plt.text(4.34", "50, 100, 150]) plt.yticks([0, 0.1, 0.2]) plt.ylabel('Frequency (Hz)') plt.xlabel('Time (s)')", "slope_based_maximum - (slope_based_maximum_time - slope_based_minimum_time) * s2 min_dash_time_3 = slope_based_minimum_time", "= utils.max_bool_func_1st_order_fd() maxima_x = time[max_bool] maxima_y = time_series[max_bool] min_bool =", "+= 1 if i_right > 1: emd_utils_max = \\ emd_utils.Utility(time=time_extended[int(2", "zorder=100) axs[2].set_yticks(ticks=[-2, 0, 2]) axs[2].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[2].set_xticklabels(labels=['0',", "between slope-based method and improved slope-based method more clear time_series[time", "minima', 10)) plt.scatter(inflection_x, inflection_y, c='magenta', zorder=4, label=textwrap.fill('Inflection points', 10)) plt.plot(time,", "101) dash_2_time = np.linspace(maxima_x[-1], minima_x[-2], 101) dash_2 = np.linspace(maxima_y[-1], minima_y[-2],", "= minima_x[-1] + (minima_x[-1] - minima_x[-2]) slope_based_minimum = slope_based_maximum -", "\\ / # \\ / # \\/ import random import", "# plot 2 fig, axs = plt.subplots(1, 2, sharey=True) axs[0].set_title('Cubic", "(maxima_x[-1] - maxima_x[-2]) slope_based_maximum = minima_y[-1] + (slope_based_maximum_time - minima_x[-1])", "knot_demonstrate_time_series, Linewidth=2, zorder=100) axs[0].set_yticks(ticks=[-2, 0, 2]) axs[0].set_xticks(ticks=[0, np.pi, 2 *", "time_series = np.cos(time) + np.cos(5 * time) knots = np.linspace(0,", "* np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1, label='Knots') axs[0].set_xticks([0,", "r'$\\pi$', r'$2\\pi$']) axs[2].set_title('IMF 2 and Uniform Knots') axs[2].plot(knot_demonstrate_time, imfs[2, :],", "2]) axs[2].set_xticks(ticks=[0, np.pi, 2 * np.pi]) axs[2].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots_uniform[0]", "r'$\\pi$', r'$2\\pi$']) axs[0].plot(knots[0][0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey',", "axs[1].set_title('IMF 2') axs[1].set_ylim([-0.2, 0.4]) axs[1].set_xlim([0, 150]) axis = 0 for", "factor * figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Simple Sinusoidal", ":], Linewidth=2, zorder=100) axs[1].set_yticks(ticks=[-2, 0, 2]) axs[1].set_xticks(ticks=[0, np.pi, 2 *", "500): preprocess_time_series[i] += np.random.normal(0, 1) preprocess = Preprocess(time=preprocess_time, time_series=preprocess_time_series) axs[0].plot(preprocess_time,", "np.ones_like(ifs[1, :]))), 3)}') fig, axs = plt.subplots(2, 2) plt.subplots_adjust(hspace=0.5) axs[0,", "using PyEMD 0.2.10', 45)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)') plt.pcolormesh(time, freq_bins,", "t) - py_emd[1, :])), 3)}') axs[1].plot(t, emd_sift[:, 1], '--', label='emd", "= \\ emd_utils.Utility(time=time_extended[int(2 * (len(lsq_signal) - 1) + 1): int(2", "= lsq_signal[lsq_utils.max_bool_func_1st_order_fd()] maxima_time = time[lsq_utils.max_bool_func_1st_order_fd()] maxima_extrapolate = time_series_extended[utils_extended.max_bool_func_1st_order_fd()][-1] maxima_extrapolate_time =", "minima_x[-1]) * s1 max_dash_time_3 = slope_based_maximum_time * np.ones_like(max_dash_1) max_dash_3 =", "Different Knot Sequences Zoomed Region', 40)) plt.subplots_adjust(hspace=0.1) axs[0].plot(time, time_series, label='Time", "minima_y[-1], 101) length_distance_time = point_1 * np.pi * np.ones_like(length_distance) length_time", "downsampled_and_decimated[1], label=textwrap.fill('Downsampled & decimated', 11)) downsampled = preprocess.downsample(decimate=False) axs[0].plot(downsampled[0], downsampled[1],", "0, np.abs(z).max() fig, ax = plt.subplots() figure_size = plt.gcf().get_size_inches() factor", "time_extended = time_extension(time) time_series_extended = np.zeros_like(time_extended) / 0 time_series_extended[int(len(lsq_signal) -", "= 0 while ((max_count_right < 1) or (min_count_right < 1))", "2), ((time_extended[-1001] + time_extended[-1000]) / 2) - 0.1, 100), 2.75", "101)) + np.cos(5 * np.linspace((5 - 2.6 * a) *", "label=textwrap.fill('Symmetric Discard maxima', 10)) plt.scatter(end_point_time, end_point, c='orange', zorder=4, label=textwrap.fill('Symmetric Anchor", "box_0.height * 0.9]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/DFA_hilbert_spectrum.png') plt.show() #", "box_0 = ax.get_position() ax.set_position([box_0.x0 + 0.0125, box_0.y0 + 0.075, box_0.width", "min_smoothed[0], label=textwrap.fill('Smoothed minima envelope', 10), c='blue') for knot in knots[:-1]:", "LineWidth=2, label=textwrap.fill('Anti-symmetric signal', 10)) plt.plot(max_dash_time, max_dash, 'k-') plt.plot(min_dash_time, min_dash, 'k-')", "if axis == 3: ax.set(xlabel='Time (years)') axis += 1 plt.gcf().subplots_adjust(bottom=0.15)", "P[:-1, col] = lsq_signal[int(col + 1):int(col + neural_network_k + 1)]", "axs[1].plot(knot * np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1, label='Knots')", "plt.plot(time[500:], b_spline_basis[2, 500:].T, '--', label=r'$ B_{-3,4}(t) $') plt.plot(time[500:], b_spline_basis[3, 500:].T,", "point_2 * np.pi * np.ones_like(length_distance_2) length_time_2 = np.linspace(point_2 * np.pi", "width, 101) max_2_y_time = maxima_x[-2] * np.ones_like(max_2_y) min_2_y = np.linspace(minima_y[-2]", "+ time_extended[-1002]) / 2) - 0.1, 100), -2.75 * np.ones(100),", "box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) plt.savefig('jss_figures/edge_effects_characteristic_wave.png') plt.show() # plot 6", "+ 0.075, box_0.width * 0.8, box_0.height * 0.9]) ax.legend(loc='center left',", "Zoomed Region', 40)) plt.subplots_adjust(hspace=0.1) axs[0].plot(time, time_series, label='Time series') axs[0].plot(time, imfs_51[1,", "Statically Optimised Knots') axs[0].plot(knot_demonstrate_time, knot_demonstrate_time_series, Linewidth=2, zorder=100) axs[0].set_yticks(ticks=[-2, 0, 2])", "= time_series[min_bool] A2 = np.abs(maxima_y[-2] - minima_y[-2]) / 2 A1", "# plot 6c ax = plt.subplot(111) figure_size = plt.gcf().get_size_inches() factor", "emd_example.empirical_mode_decomposition(knots=knots, knot_time=time, verbose=False) print(f'AdvEMDpy annual frequency error: {np.round(sum(np.abs(ifs[1, :] /", "scipy.interpolate import CubicSpline from emd_hilbert import Hilbert, hilbert_spectrum from emd_preprocess", "np.linspace(minima_y[-1], max_discard, 101) end_point_time = time[-1] end_point = time_series[-1] time_reflect", "101) dash_4_time = np.linspace(slope_based_maximum_time, slope_based_minimum_time) dash_4 = np.linspace(slope_based_maximum, slope_based_minimum) maxima_dash", "0.2, 100) hht = emd040.spectra.hilberthuang(IF, IA, freq_edges) hht = gaussian_filter(hht,", "label='Knots', zorder=1) plt.xticks((0, 1 * np.pi, 2 * np.pi, 3", "time[-301]) / 2) * np.ones(100), np.linspace(-2.75, 2.75, 100), c='k', label=textwrap.fill('Neural", "signal_orig[util_nn.min_bool_func_1st_order_fd()] cs_max = CubicSpline(t[util_nn.max_bool_func_1st_order_fd()], maxima) cs_min = CubicSpline(t[util_nn.min_bool_func_1st_order_fd()], minima) time", "np.pi, 1001) lsq_signal = np.cos(time) + np.cos(5 * time) knots", "print(f'PyEMD annual frequency error: {np.round(sum(np.abs(IF[:, 0] - np.ones_like(IF[:, 0]))), 3)}')", "minima_x[-2] * np.ones_like(min_dash_1) dash_1_time = np.linspace(maxima_x[-1], minima_x[-1], 101) dash_1 =", "np.ones_like(min_dash_1) min_dash_time_2 = minima_x[-2] * np.ones_like(min_dash_1) dash_1_time = np.linspace(maxima_x[-1], minima_x[-1],", "101) max_discard = maxima_y[-1] max_discard_time = minima_x[-1] - maxima_x[-1] +", "= 0.2 time = np.linspace((0 + a) * np.pi, (5", "Coughlin_min = Coughlin_wave[Coughlin_min_bool] max_2_x_time = np.linspace(maxima_x[-2] - width, maxima_x[-2] +", "- width, maxima_x[-1] + width, 101) max_dash = maxima_y[-1] *", "np.pi]) ax.set_xticklabels(['$0$', r'$\\pi$', r'$2\\pi$', r'$3\\pi$', r'$4\\pi$']) plt.ylabel(r'Frequency (rad.s$^{-1}$)') plt.xlabel('Time (s)')", "CO$_{2}$ Concentration using PyEMD 0.2.10', 45)) plt.ylabel('Frequency (year$^{-1}$)') plt.xlabel('Time (years)')", "time_extension(time) time_series_extended = np.zeros_like(time_extended) / 0 time_series_extended[int(len(lsq_signal) - 1):int(2 *", "np.ones_like(max_1_x_time) min_1_x_time = np.linspace(minima_x[-1] - width, minima_x[-1] + width, 101)", "= plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Statically Optimised", "dash_1 = np.linspace(maxima_y[-1], minima_y[-1], 101) dash_2_time = np.linspace(maxima_x[-1], minima_x[-2], 101)", "Simple Sinusoidal Time Seres with Added Noise', 50)) x_hs, y,", "* np.pi + (slope_based_minimum_time - minima_x[-1]), -0.20 + (slope_based_minimum -", "- width, -3.4 + width, 101) minima_dash_time_1 = minima_x[-2] *", "- 1) + 1 + i_right + 1)]) if sum(emd_utils_min.min_bool_func_1st_order_fd())", "c='grey', label='Knots') axs[2].plot(knots[0] * np.ones(101), np.linspace(-2, 2, 101), '--', c='grey',", "plt.show() emd_sift = emd040.sift.sift(signal) IP, IF, IA = emd040.spectra.frequency_transform(emd_sift[:, :1],", "pyemd0215() py_emd = pyemd(signal) IP, IF, IA = emd040.spectra.frequency_transform(py_emd[:2, :].T,", "* np.cos(0.04 * 2 * np.pi * t) - emd_sift[:,", "lsq_signal[lsq_utils.max_bool_func_1st_order_fd()] maxima_time = time[lsq_utils.max_bool_func_1st_order_fd()] maxima_extrapolate = time_series_extended[utils_extended.max_bool_func_1st_order_fd()][-1] maxima_extrapolate_time = time_extended[utils_extended.max_bool_func_1st_order_fd()][-1]", "1].set_title('Residual') plt.gcf().subplots_adjust(bottom=0.15) plt.savefig('jss_figures/CO2_EMD.png') plt.show() hs_ouputs = hilbert_spectrum(time, imfs, hts, ifs,", "solution[:, 0] dxdt = solution[:, 1] x_points = [0, 50,", "figure_size[1])) plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of CO$_{2}$ Concentration using emd", "in range(1, len(knots[i])): axs[i].plot(knots[i][j] * np.ones(101), np.linspace(-2, 2, 101), '--',", "5.5) axs[2].set_xlim(0.95 * np.pi, 1.55 * np.pi) plt.savefig('jss_figures/DFA_different_trends_zoomed.png') plt.show() hs_ouputs", "smooth=False) max_smoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='maxima', smooth=True) min_unsmoothed = fluc.envelope_basis_function_approximation(knots_for_envelope=knots, extrema_type='minima',", "100), 2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time_extended[-1001] + time_extended[-1002]) / 2),", "* np.ones_like(max_2_y) min_2_y = np.linspace(minima_y[-2] - width, minima_y[-2] + width,", "emd_ht_duff, emd_if_duff, _, _, _, _ = emd_duffing.empirical_mode_decomposition(verbose=False) fig, axs", "plt.title('Non-Natural Cubic B-Spline Bases at Boundary') plt.plot(time[500:], b_spline_basis[2, 500:].T, '--',", "= lsq_signal[-neural_network_m:] # test - top seed_weights = np.ones(neural_network_k) /", "time_series = np.cos(time) + np.cos(5 * time) utils = emd_utils.Utility(time=time,", "np.pi * np.ones_like(length_distance_2) length_time_2 = np.linspace(point_2 * np.pi - width,", "* np.ones(100), np.linspace(-0.2, 0.8, 100), 'k-') axs[0].set_xticks([5, 6]) axs[0].set_xticklabels([r'$ \\tau_k", "plt.plot(dash_max_min_2_y_time, dash_max_min_2_y, 'k--') plt.text(4.08 * np.pi, -2.2, r'$\\frac{p_2}{2}$') plt.plot(max_1_x_time, max_1_x,", "101), -3 * np.ones(101), '--', c='black', label=textwrap.fill('Zoomed region', 10)) axs[0].plot(np.linspace(0.85", "= np.linspace(0, 5 * np.pi, 51) fluc = Fluctuation(time=time, time_series=time_series)", "'k-') plt.plot(minima_dash_time_1, minima_dash, 'k-') plt.plot(minima_dash_time_2, minima_dash, 'k-') plt.plot(minima_dash_time_3, minima_dash, 'k-')", "* np.pi]) axs[2].set_xticklabels([r'$\\pi$', r'$\\frac{3}{2}\\pi$']) box_2 = axs[2].get_position() axs[2].set_position([box_2.x0 - 0.05,", "np.pi]) axs[0].set_xticklabels(['', '', '', '', '', '']) axs[0].plot(np.linspace(0.95 * np.pi,", "-5.5 * np.ones(101), 'k--') axs[1].plot(0.95 * np.pi * np.ones(101), np.linspace(-5.5,", "odeint from scipy.ndimage import gaussian_filter from emd_utils import time_extension, Utility", "max_dash_3, 'k-') plt.plot(min_dash_time_1, min_dash_1, 'k-') plt.plot(min_dash_time_2, min_dash_2, 'k-') plt.plot(min_dash_time_3, min_dash_3,", "np.linspace(0, 5 * np.pi, 51) fluc = Fluctuation(time=time, time_series=time_series) max_unsmoothed", "axs[0].plot(1.15 * np.pi * np.ones(101), np.linspace(-3, 3, 101), '--', c='black')", "label='Knots') axs[0].set_xticks([0, np.pi, 2 * np.pi, 3 * np.pi, 4", "- minima_x[-1]) Huang_time = (P1 / P2) * (time[time >=", "EEMD_maxima_envelope, c='darkgreen', label=textwrap.fill('EEMD envelope', 10)) plt.plot(time, EEMD_minima_envelope, c='darkgreen') plt.plot(time, (EEMD_maxima_envelope", "+= 1 plt.savefig('jss_figures/Duffing_equation.png') plt.show() # compare other packages Duffing -", "ax.set_ylabel(r'$\\gamma_1(t)$') ax.set_yticks([-2, 0, 2]) if axis == 1: ax.set_ylabel(r'$\\gamma_2(t)$') ax.set_yticks([-0.2,", "50)) plt.plot(time, time_series, label='Time series', zorder=2, LineWidth=2) plt.scatter(time[maxima], time_series[maxima], c='r',", "change (1) detrended_fluctuation_technique and (2) max_internal_iter and (3) debug (confusing", "emd_sift[:, 1])), 3)}') axs[1].plot(t, 0.1 * np.cos(0.04 * 2 *", "1, '--', c='c', label=r'$\\tilde{h}_{(1,0)}^m(t)$', zorder=5) plt.plot(pseudo_alg_time, np.sin(pseudo_alg_time), '--', c='purple', label=r'$\\tilde{h}_{(1,0)}^{\\mu}(t)$',", "6c ax = plt.subplot(111) figure_size = plt.gcf().get_size_inches() factor = 0.9", "knots: {np.round(np.var(time_series - (imfs_31[1, :] + imfs_31[2, :])), 3)}') for", "np.pi + width, 101) length_top_2 = time_series[-1] * np.ones_like(length_time_2) length_bottom_2", "= slope_based_maximum_time * np.ones_like(maxima_dash) maxima_line_dash_time = np.linspace(maxima_x[-2], slope_based_maximum_time, 101) maxima_line_dash", "maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.scatter(slope_based_maximum_time,", "+ imfs_51[2, :] + imfs_51[3, :])), 3)}') for knot in", "0.5), fontsize=8) axs[2].plot(np.linspace(0.95 * np.pi, 1.55 * np.pi, 101), 5.5", "np.ones_like(maxima_line_dash_time) minima_dash = np.linspace(-3.4 - width, -3.4 + width, 101)", "plt.plot(knots[-1] * np.ones(101), np.linspace(-3.0, -2.0, 101), '--', c='grey', label='Knots', zorder=1)", "= plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Single Neuron Neural Network Example') plt.plot(time, lsq_signal,", "min_unsmoothed[0], label=textwrap.fill('Unsmoothed minima envelope', 10), c='cyan') plt.plot(time, min_smoothed[0], label=textwrap.fill('Smoothed minima", "- lr * max_gradient_vector weights += adjustment # test -", "emd_sift = emd040.sift.sift(x) IP, IF, IA = emd040.spectra.frequency_transform(emd_sift, 10, 'hilbert')", "= basis.chsi_basis(knots) # plot 1 plt.title('Non-Natural Cubic B-Spline Bases at", "r'$2a_1$') plt.plot(max_1_y_time, max_1_y, 'k-') plt.plot(max_1_y_time, max_1_y_side, 'k-') plt.plot(min_1_y_time, min_1_y, 'k-')", "plt.title('Detrended Fluctuation Analysis Examples') plt.plot(time, time_series, LineWidth=2, label='Time series') plt.scatter(maxima_x,", "width, 101) min_2_y_time = minima_x[-2] * np.ones_like(min_2_y) dash_max_min_2_y_time = np.linspace(minima_x[-2],", "Duffing Equation using AdvEMDpy', 40)) x, y, z = hs_ouputs", "axs[1].get_position() axs[1].set_position([box_1.x0 - 0.06, box_1.y0, box_1.width * 0.85, box_1.height]) plt.savefig('jss_figures/preprocess_smooth.png')", "== max(np.abs(average_gradients))) adjustment = - lr * average_gradients # adjustment", "np.linspace(minima_x[-2], maxima_x[-2], 101) dash_max_min_2_y = -1.8 * np.ones_like(dash_max_min_2_y_time) max_1_x_time =", "= Utility(time=time, time_series=time_series) maxima = util.max_bool_func_1st_order_fd() minima = util.min_bool_func_1st_order_fd() ax", "51) emd = EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series) imfs = emd.empirical_mode_decomposition(knots=knots_uniform, edge_effect='anti-symmetric', verbose=False)[0]", "/ 2, c='darkred') plt.plot(time, EEMD_maxima_envelope, c='darkgreen', label=textwrap.fill('EEMD envelope', 10)) plt.plot(time,", "cmap='gist_rainbow', vmin=z_min, vmax=z_max) plt.plot(t[:-1], 0.124 * np.ones_like(t[:-1]), '--', label=textwrap.fill('Hamiltonian frequency", "1].set_title('Smoothed CO$_2$ Concentration') axs[1, 0].set_title('IMF 1') axs[1, 1].set_title('Residual') plt.gcf().subplots_adjust(bottom=0.15) plt.savefig('jss_figures/CO2_EMD.png')", "* np.pi, 101) time_series_reflect = np.flip(np.cos(np.linspace((5 - 2.6 * a)", "100), -2.75 * np.ones(100), c='k') plt.plot(np.linspace(((time[-302] + time[-301]) / 2),", "minima_dash, 'k-') plt.plot(minima_dash_time_2, minima_dash, 'k-') plt.plot(minima_dash_time_3, minima_dash, 'k-') plt.text(4.34 *", "preprocess.downsample(decimate=False) axs[0].plot(downsampled[0], downsampled[1], label=textwrap.fill('Downsampled', 13)) axs[0].plot(np.linspace(0.85 * np.pi, 1.15 *", "box_0.y0 + 0.05, box_0.width * 0.75, box_0.height * 0.9]) ax.legend(loc='center", "= time_extension(time) time_series_extended = np.zeros_like(time_extended) / 0 time_series_extended[int(len(lsq_signal) - 1):int(2", "Preprocess(time=preprocess_time, time_series=preprocess_time_series) axs[0].plot(preprocess_time, preprocess_time_series, label='x(t)') axs[0].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless", "1, 2]) plt.xticks(ticks=[0, np.pi, 2 * np.pi], labels=[r'0', r'$\\pi$', r'$2\\pi$'])", "minima_x = time[min_bool] minima_y = time_series[min_bool] A2 = np.abs(maxima_y[-2] -", "IP, IF, IA = emd040.spectra.frequency_transform(py_emd.T, 10, 'hilbert') freq_edges, freq_bins =", "knot_time=time, verbose=False) print(f'AdvEMDpy annual frequency error: {np.round(sum(np.abs(ifs[1, :] / (2", "axis == 0: ax.set_ylabel('x(t)') ax.set_yticks(y_points_1) if axis == 1: ax.set_ylabel(r'$", "(slope_based_minimum - minima_y[-1]), r'$s_2$') plt.text(4.50 * np.pi + (slope_based_minimum_time -", "/ 2, c='darkblue') plt.plot(time, maxima_envelope_smooth, c='darkred', label=textwrap.fill('SEMD envelope', 10)) plt.plot(time,", "= - lr * max_gradient_vector weights += adjustment # test", "downsampled[1], label=textwrap.fill('Downsampled', 13)) axs[1].set_xlim(0.85 * np.pi, 1.15 * np.pi) axs[1].set_ylim(-3,", "plt.xlim(3.9 * np.pi, 5.6 * np.pi) plt.xticks((4 * np.pi, 5", "- (imfs_51[1, :] + imfs_51[2, :] + imfs_51[3, :])), 3)}')", "= np.linspace(maxima_x[-2], slope_based_maximum_time, 101) maxima_line_dash = 2.5 * np.ones_like(maxima_line_dash_time) minima_dash", "np.pi, 0.85, r'$2a_2$') plt.plot(max_2_y_time, max_2_y, 'k-') plt.plot(max_2_y_time, max_2_y_side, 'k-') plt.plot(min_2_y_time,", "* np.pi * np.ones(101), np.linspace(-3, 3, 101), '--', c='black') axs[0].set_yticks(ticks=[-2,", "minima_x = time[min_bool] minima_y = time_series[min_bool] max_dash_time = np.linspace(maxima_x[-1] -", "= plt.subplots(3, 1) fig.subplots_adjust(hspace=0.6) plt.gcf().subplots_adjust(bottom=0.10) axs[0].set_title('Time Series and Dynamically Optimised", "5.5, 101), 'k--') axs[2].plot(1.55 * np.pi * np.ones(101), np.linspace(-5.5, 5.5,", "emd = EMD(time=knot_demonstrate_time, time_series=knot_demonstrate_time_series) imfs, _, _, _, knots, _,", "label='x(t)') axs[1].plot(pseudo_alg_time, pseudo_alg_time_series, '--', c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[1].plot(preprocess_time,", "col))] P[-1, col] = 1 # for additive constant t", "c='cyan', zorder=4, label=textwrap.fill('Extrapolated minima', 12)) plt.plot(((time[-302] + time[-301]) / 2)", "c='dodgerblue', zorder=4, label=textwrap.fill('Improved slope-based minimum', 11)) plt.xlim(3.9 * np.pi, 5.5", "with 51 knots', 19)) for knot in knots_31: axs[1].plot(knot *", "box_0.height]) axs[0].legend(loc='center left', bbox_to_anchor=(1, -0.15)) box_1 = axs[1].get_position() axs[1].set_position([box_1.x0 -", "1a - addition knot_demonstrate_time = np.linspace(0, 2 * np.pi, 1001)", "np.ones(101), np.linspace(-3.0, -2.0, 101), '--', c='grey', zorder=1) plt.plot(knots[-1] * np.ones(101),", "= AdvEMDpy.EMD(time=t, time_series=x) emd_duff, emd_ht_duff, emd_if_duff, _, _, _, _", "+ width, 101) min_2_y_side = np.linspace(-1.8 - width, -1.8 +", "c='purple', label=textwrap.fill('Noiseless time series', 12)) axs[0].plot(preprocess_time, preprocess.mean_filter(window_width=window)[1], label=textwrap.fill('Mean filter', 12))", "Discard maxima', 10)) plt.scatter(end_point_time, end_point, c='orange', zorder=4, label=textwrap.fill('Symmetric Anchor maxima',", "window', 12)) axs[1].plot(preprocess_time, preprocess.quantile_filter(window_width=window, q=0.10)[1], c='grey') axs[1].set_xlim(0.85 * np.pi, 1.15", "axs[0, 0].set_title(r'Original CO$_2$ Concentration') axs[0, 1].set_title('Smoothed CO$_2$ Concentration') axs[1, 0].set_title('IMF", "1 i_left += 1 if i_left > 1: emd_utils_max =", "* np.pi]) axs[0].set_xticklabels(labels=['0', r'$\\pi$', r'$2\\pi$']) axs[1].set_title('IMF 1 and Dynamically Knots')", "envelope', 10), c='cyan') plt.plot(time, min_smoothed[0], label=textwrap.fill('Smoothed minima envelope', 10), c='blue')", "* np.ones(101), np.linspace(-5, 5, 101), '--', c='grey', zorder=1) axs[2].plot(knot *", "minima_y[-1]) / 2 utils_Huang = emd_utils.Utility(time=time, time_series=Huang_wave) Huang_max_bool = utils_Huang.max_bool_func_1st_order_fd()", "maxima_extrapolate_time = time_extended[utils_extended.max_bool_func_1st_order_fd()][-1] minima = lsq_signal[lsq_utils.min_bool_func_1st_order_fd()] minima_time = time[lsq_utils.min_bool_func_1st_order_fd()] minima_extrapolate", "* np.ones_like(dash_max_min_1_x) max_1_y = np.linspace(maxima_y[-1] - width, maxima_y[-1] + width,", "plot 1c - addition knot_demonstrate_time = np.linspace(0, 2 * np.pi,", "* np.pi * np.ones(101), np.linspace(-5.5, 5.5, 101), 'k--') axs[2].plot(1.55 *", "time_series_reflect utils = emd_utils.Utility(time=time, time_series=time_series_anti_reflect) anti_max_bool = utils.max_bool_func_1st_order_fd() anti_max_point_time =", "plt.subplot(111) plt.gcf().subplots_adjust(bottom=0.10) plt.title('Characteristic Wave Effects Example') plt.plot(time, time_series, LineWidth=2, label='Signal')", "maxima_y, c='r', zorder=4, label='Maxima') plt.scatter(minima_x, minima_y, c='b', zorder=4, label='Minima') plt.scatter(time[optimal_maxima],", "'k--') plt.text(5.16 * np.pi, 0.85, r'$2a_2$') plt.plot(max_2_y_time, max_2_y, 'k-') plt.plot(max_2_y_time,", "> 1: emd_utils_max = \\ emd_utils.Utility(time=time_extended[int(2 * (len(lsq_signal) - 1)", "label='Signal') plt.title('Symmetry Edge Effects Example') plt.plot(time_reflect, time_series_reflect, 'g--', LineWidth=2, label=textwrap.fill('Symmetric", "Coughlin_time[Coughlin_max_bool] Coughlin_max = Coughlin_wave[Coughlin_max_bool] Coughlin_min_time = Coughlin_time[Coughlin_min_bool] Coughlin_min = Coughlin_wave[Coughlin_min_bool]", "= A1 * np.cos(2 * np.pi * (1 / P1)", "+ np.cos(5 * time) utils = emd_utils.Utility(time=time, time_series=time_series) max_bool =", "= np.sin(knot_demonstrate_time) + np.sin(5 * knot_demonstrate_time) knots_uniform = np.linspace(0, 2", "- t), 2)) # linear activation function is arbitrary prob", "chsi_basis[12, :].T, '--') axs[1].plot(time, chsi_basis[13, :].T, '--') axs[1].plot(5 * np.ones(100),", "* np.pi, (5 - a) * np.pi, 101))) time_series_anti_reflect =", "= np.linspace(minima_x[-1] - width, minima_x[-1] + width, 101) min_1_x_time_side =", "0.85, box_0.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8) ax.set_xticks(x_points) ax.set_xticklabels(x_names) axis", "'k-') plt.plot(dash_1_time, dash_1, 'k--') plt.plot(dash_2_time, dash_2, 'k--') plt.plot(length_distance_time, length_distance, 'k--')", "* np.pi) / 25) return [xy[1], xy[0] - epsilon *", "omega = ((2 * np.pi) / 25) return [xy[1], xy[0]", "(years)') if axis == 3: ax.set(xlabel='Time (years)') axis += 1", "in range(3): for j in range(1, len(knots[i])): axs[i].plot(knots[i][j] * np.ones(101),", "Different Knot Sequences', 40)) plt.subplots_adjust(hspace=0.1) axs[0].plot(time, time_series, label='Time series') axs[0].plot(time,", "region') axs[2].plot(time, time_series, label='Time series') axs[2].plot(time, imfs_11[1, :], label='IMF 1", "np.linspace(minima_y[-2] - width, minima_y[-2] + width, 101) min_dash_time_1 = minima_x[-1]", "100), 'k-') axs[0].set_xticks([5, 6]) axs[0].set_xticklabels([r'$ \\tau_k $', r'$ \\tau_{k+1} $'])", "import Preprocess from emd_mean import Fluctuation from AdvEMDpy import EMD", "plot 0 - addition fig = plt.figure(figsize=(9, 4)) ax =", "minima_x[-1], 101) dash_1 = np.linspace(maxima_y[-1], minima_y[-1], 101) dash_2_time = np.linspace(maxima_x[-1],", "5 * np.pi]) axs[1].set_xticklabels(['', '', '', '', '', '']) box_1" ]
[ "type=str, help=\"whether to train or test the model\") parser.add_argument('--id', default='models',", "break avg_loss = 0 if args.local_rank in [-1, 0]: if", "% args.every == 0 and idx > 0: tb_writer.add_scalar(\"perplexity\", math.exp(avg_loss", "if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument(\"--model\", default='gpt2', type=str)", "the model\") parser.add_argument('--learning_rate', default=2e-6, type=float, help=\"whether to train or test", "args.every), global_step) fake_inputs = caption gt_inputs = trg_out.cpu().data.numpy() #samples =", "default='models', type=str, help=\"specify the id of the experiment\") parser.add_argument('--max_len', default=800,", "DL import torch from torch.utils.data.distributed import DistributedSampler warnings.filterwarnings(\"ignore\", category=UserWarning) device", "or test the model\") parser.add_argument('--local_rank', default=-1, type=int, help=\"whether to train", "torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed) if __name__ == '__main__':", "help=\"random seed for initialization\") parser.add_argument('--do_train', default=False, action=\"store_true\", help=\"whether to train", "default=4, type=int, help=\"whether to train or test the model\") parser.add_argument(\"--modelpath\",", "as F import numpy as np from torch import nn", "range(0, dataset.train_len()): for idx, batch in enumerate(tqdm(train_dataloader, desc=\"Iteration\", disable=args.local_rank not", "split\") parser.add_argument('--epoch', default=10, type=int, help=\"whether to train or test the", "not in [-1, 0]: torch.distributed.barrier() tokenizer = GPT2Tokenizer.from_pretrained(args.model) model =", "= model(inputs)[0] logits = logits[:, -trg_out.shape[1]:, :].contiguous() loss = criterion(logits.view(-1,", "parser.add_argument('--batch_size', default=6, type=int, help=\"whether to train or test the model\")", "type=str, default=\"bert-base-uncased\", help=\"For distributed training: local_rank\") parser.add_argument('--gradient_accumulation_steps', type=int, default=5, help=\"accumulation", "else: sampler = DistributedSampler(dataset) train_dataloader = DL(dataset, sampler=sampler, batch_size=args.batch_size, num_workers=0)", "test the model\") parser.add_argument('--load_from', default='', type=str, help=\"whether to train or", "= logits[:, -trg_out.shape[1]:, :].contiguous() loss = criterion(logits.view(-1, logits.shape[-1]), trg_out.view(-1)) loss", "bert) samples = sample_sequence(model, 30, fake_inputs, []) samples = samples[:,", "type=str, help=\"specify the id of the experiment\") parser.add_argument('--max_len', default=800, type=int,", "seed for initialization\") parser.add_argument('--do_train', default=False, action=\"store_true\", help=\"whether to train or", "in [-1, 0]: if args.model == 'gpt2': torch.save(model.state_dict(), '{}/GPT_ep{}.pt'.format(args.id, epoch_idx))", "the adv-acc score on challenge split\") parser.add_argument('--epoch', default=10, type=int, help=\"whether", "to train or test the model\") parser.add_argument('--batch_size', default=6, type=int, help=\"whether", "on challenge split\") parser.add_argument('--do_ppl', default=False, action=\"store_true\", help=\"whether to compute perplexity", "parser.add_argument('--load_from', default='', type=str, help=\"whether to train or test the model\")", "parser.add_argument('--do_rl', default=False, action=\"store_true\", help=\"whether to train or test the model\")", "inputs = torch.cat([caption, trg_inp], 1) model.zero_grad() optimizer.zero_grad() logits = model(inputs)[0]", "import BERTGen from utils import sample_sequence import torch.optim as optim", "disable=args.local_rank not in [-1, 0])): batch = tuple(Variable(t).to(device) for t", "train or test the model\") parser.add_argument('--do_test', default=False, action=\"store_true\", help=\"whether to", "type=int, help=\"whether to train or test the model\") parser.add_argument('--layers', default=3,", "print(\"GROUNDTRUH |||||| \",text) break avg_loss = 0 if args.local_rank in", "default=10000, help=\"For debugging purpose\") args = parser.parse_args() if args.local_rank ==", "0: tb_writer.add_scalar(\"perplexity\", math.exp(avg_loss / args.every), global_step) fake_inputs = caption gt_inputs", "sample_sequence import torch.optim as optim import math import sys import", "type=int, help=\"whether to train or test the model\") parser.add_argument('--learning_rate', default=2e-6,", "import DistributedSampler warnings.filterwarnings(\"ignore\", category=UserWarning) device = torch.device('cuda') def set_seed(args): np.random.seed(args.seed)", "the model\") parser.add_argument('--do_rl', default=False, action=\"store_true\", help=\"whether to train or test", "\",text) break avg_loss = 0 if args.local_rank in [-1, 0]:", "sampler = DistributedSampler(dataset) train_dataloader = DL(dataset, sampler=sampler, batch_size=args.batch_size, num_workers=0) model.train()", "train or test the model\") parser.add_argument('--dataset', default='table', type=str, help=\"whether to", "to train or test the model\") parser.add_argument('--load_from', default='', type=str, help=\"whether", "= torch.cat([caption, trg_inp], 1) model.zero_grad() optimizer.zero_grad() logits = model(inputs)[0] logits", "nn.CrossEntropyLoss(reduction='none', ignore_index=-1) if args.do_train: if args.local_rank in [-1, 0]: if", "import RandomSampler, SequentialSampler from torch.utils.data import DataLoader as DL import", "mask.view(-1) loss = loss.sum() / mask.sum() avg_loss += loss.item() loss.backward()", "np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed) if __name__ ==", "tokenizer, args.max_len) if args.local_rank == -1: sampler = RandomSampler(dataset) else:", "test the model\") parser.add_argument('--do_val', default=False, action=\"store_true\", help=\"whether to train or", "the experiment\") parser.add_argument('--max_len', default=800, type=int, help=\"whether to train or test", "if args.local_rank != -1: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True)", "text = text[: text.find(tokenizer.eos_token)] print(\"PREDICTION |||||| \", text) text =", "the model\") parser.add_argument('--layers', default=3, type=int, help=\"whether to train or test", "30, fake_inputs, []) samples = samples[:, caption.shape[1]:] samples = samples.cpu().data.numpy()", "os.path.exists(args.id): os.mkdir(args.id) tb_writer = SummaryWriter(log_dir='tensorboard/GPT2-{}'.format(args.model)) dataset = GPTTableDataset2('data/train_lm_preprocessed.json', tokenizer, args.max_len)", "default=\"bert-base-uncased\", help=\"For distributed training: local_rank\") parser.add_argument('--gradient_accumulation_steps', type=int, default=5, help=\"accumulation steps", "args.local_rank in [-1, 0] and idx % args.every == 0", "loss = loss.sum() / mask.sum() avg_loss += loss.item() loss.backward() optimizer.step()", "import sample_sequence import torch.optim as optim import math import sys", "global_step = 0 if args.local_rank != -1: model = torch.nn.parallel.DistributedDataParallel(model,", "compute the BLEU scores on challenge split\") parser.add_argument('--do_ppl', default=False, action=\"store_true\",", "> 0: torch.cuda.manual_seed_all(args.seed) if __name__ == '__main__': parser = argparse.ArgumentParser()", "tb_writer = SummaryWriter(log_dir='tensorboard/GPT2-{}'.format(args.model)) dataset = GPTTableDataset2('data/train_lm_preprocessed.json', tokenizer, args.max_len) if args.local_rank", "model\") parser.add_argument('--do_val', default=False, action=\"store_true\", help=\"whether to train or test the", "model\") parser.add_argument('--batch_size', default=6, type=int, help=\"whether to train or test the", "gradient\") parser.add_argument('--decode_first_K', type=int, default=10000, help=\"For debugging purpose\") args = parser.parse_args()", "#for idx in range(0, dataset.train_len()): for idx, batch in enumerate(tqdm(train_dataloader,", "0]): #for idx in range(0, dataset.train_len()): for idx, batch in", "torch.cat([caption, trg_inp], 1) model.zero_grad() optimizer.zero_grad() logits = model(inputs)[0] logits =", "= 1 else: torch.cuda.set_device(args.local_rank) device = torch.device('cuda', args.local_rank) torch.distributed.init_process_group(backend='nccl') args.n_gpu", "model\") parser.add_argument('--dataset', default='table', type=str, help=\"whether to train or test the", "[-1, 0]: if args.model == 'gpt2': torch.save(model.state_dict(), '{}/GPT_ep{}.pt'.format(args.id, epoch_idx)) else:", "idx in range(0, dataset.train_len()): for idx, batch in enumerate(tqdm(train_dataloader, desc=\"Iteration\",", "model\") parser.add_argument('--do_verify', default=False, action=\"store_true\", help=\"whether compute the adv-acc score on", "test the model\") parser.add_argument('--learning_rate', default=2e-6, type=float, help=\"whether to train or", "model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True) else: model = torch.nn.DataParallel(model)", "parser = argparse.ArgumentParser() parser.add_argument(\"--model\", default='gpt2', type=str) parser.add_argument(\"--top_k\", type=int, default=0) parser.add_argument(\"--top_p\",", "for initialization\") parser.add_argument('--do_train', default=False, action=\"store_true\", help=\"whether to train or test", "== 'gpt2': torch.save(model.state_dict(), '{}/GPT_ep{}.pt'.format(args.id, epoch_idx)) else: torch.save(model.state_dict(), '{}/GPT_medium_ep{}.pt'.format(args.id, epoch_idx)) if", "action=\"store_true\", help=\"whether compute the adv-acc score on challenge split\") parser.add_argument('--epoch',", "default=768, type=int, help=\"whether to train or test the model\") parser.add_argument('--layers',", "steps for gradient\") parser.add_argument('--decode_first_K', type=int, default=10000, help=\"For debugging purpose\") args", "from torch.utils.data import DataLoader as DL import torch from torch.utils.data.distributed", "import torch from torch.utils.data.distributed import DistributedSampler warnings.filterwarnings(\"ignore\", category=UserWarning) device =", "1 if args.local_rank in [-1, 0] and idx % args.every", "type=int, help=\"whether to train or test the model\") parser.add_argument('--load_from', default='',", "idx, batch in enumerate(tqdm(train_dataloader, desc=\"Iteration\", disable=args.local_rank not in [-1, 0])):", "numpy as np from torch import nn from torch.autograd import", "args.local_rank not in [-1, 0]: torch.distributed.barrier() tokenizer = GPT2Tokenizer.from_pretrained(args.model) model", "default='table', type=str, help=\"whether to train or test the model\") parser.add_argument('--every',", "model.sample(fake_inputs, tabfeat, caption, highlight_idx, bert) samples = sample_sequence(model, 30, fake_inputs,", "in [-1, 0])): batch = tuple(Variable(t).to(device) for t in batch)", "gt_inputs): text = tokenizer.decode(s, clean_up_tokenization_spaces=True) text = text[: text.find(tokenizer.eos_token)] print(\"PREDICTION", "import math import sys import pandas import os import numpy", "> 0: tb_writer.add_scalar(\"perplexity\", math.exp(avg_loss / args.every), global_step) fake_inputs = caption", "logits[:, -trg_out.shape[1]:, :].contiguous() loss = criterion(logits.view(-1, logits.shape[-1]), trg_out.view(-1)) loss =", "train or test the model\") parser.add_argument(\"--modelpath\", type=str, default=\"bert-base-uncased\", help=\"For distributed", "from tqdm import tqdm, trange from torch.utils.data import RandomSampler, SequentialSampler", "help=\"whether to train or test the model\") parser.add_argument('--do_val', default=False, action=\"store_true\",", "to train or test the model\") parser.add_argument('--id', default='models', type=str, help=\"specify", "batch inputs = torch.cat([caption, trg_inp], 1) model.zero_grad() optimizer.zero_grad() logits =", "default=False, action=\"store_true\", help=\"whether to train or test the model\") parser.add_argument('--do_rl',", "action=\"store_true\", help=\"whether to train or test the model\") parser.add_argument('--do_rl', default=False,", "action=\"store_true\", help=\"whether to compute the BLEU scores on test split\")", "compute perplexity of the model\") parser.add_argument('--do_verify', default=False, action=\"store_true\", help=\"whether compute", "type=int, help=\"whether to train or test the model\") parser.add_argument(\"--modelpath\", type=str,", "optimizer = optim.Adam(model.parameters(), args.learning_rate) avg_loss = 0 global_step = 0", "samples = samples[:, caption.shape[1]:] samples = samples.cpu().data.numpy() for s, gt", "= sample_sequence(model, 30, fake_inputs, []) samples = samples[:, caption.shape[1]:] samples", "train or test the model\") parser.add_argument('--local_rank', default=-1, type=int, help=\"whether to", "t in batch) trg_inp, trg_out, mask, caption = batch inputs", "adv-acc score on test split\") parser.add_argument('--do_verify_challenge', default=False, action=\"store_true\", help=\"whether compute", "type=int, help=\"whether to train or test the model\") parser.add_argument('--batch_size', default=6,", "to train or test the model\") parser.add_argument('--head', default=4, type=int, help=\"whether", "= SummaryWriter(log_dir='tensorboard/GPT2-{}'.format(args.model)) dataset = GPTTableDataset2('data/train_lm_preprocessed.json', tokenizer, args.max_len) if args.local_rank ==", "/ mask.sum() avg_loss += loss.item() loss.backward() optimizer.step() global_step += 1", "import torch import torch.nn.functional as F import numpy as np", "tokenizer.decode(gt, clean_up_tokenization_spaces=True) text = text[: text.find(tokenizer.eos_token)] print(\"GROUNDTRUH |||||| \",text) break", "loss * mask.view(-1) loss = loss.sum() / mask.sum() avg_loss +=", "GPTTableDataset2('data/train_lm_preprocessed.json', tokenizer, args.max_len) if args.local_rank == -1: sampler = RandomSampler(dataset)", "default=800, type=int, help=\"whether to train or test the model\") parser.add_argument('--dim',", "not in [-1, 0]): #for idx in range(0, dataset.train_len()): for", "torch.utils.data import DataLoader as DL import torch from torch.utils.data.distributed import", "to train or test the model\") parser.add_argument(\"--modelpath\", type=str, default=\"bert-base-uncased\", help=\"For", "= loss.sum() / mask.sum() avg_loss += loss.item() loss.backward() optimizer.step() global_step", "default=False, action=\"store_true\", help=\"whether to train or test the model\") parser.add_argument('--do_val',", "or test the model\") parser.add_argument('--batch_size', default=6, type=int, help=\"whether to train", "caption gt_inputs = trg_out.cpu().data.numpy() #samples = model.sample(fake_inputs, tabfeat, caption, highlight_idx,", "else: model = torch.nn.DataParallel(model) for epoch_idx in trange(0, args.epoch, desc='Epoch',", "args.local_rank != -1: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True) else:", "find_unused_parameters=True) else: model = torch.nn.DataParallel(model) for epoch_idx in trange(0, args.epoch,", "args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed) if __name__ == '__main__': parser =", "purpose\") args = parser.parse_args() if args.local_rank == -1: device =", "parser.parse_args() if args.local_rank == -1: device = torch.device(\"cuda\") args.n_gpu =", "[-1, 0])): batch = tuple(Variable(t).to(device) for t in batch) trg_inp,", "caption = batch inputs = torch.cat([caption, trg_inp], 1) model.zero_grad() optimizer.zero_grad()", "type=int, default=42, help=\"random seed for initialization\") parser.add_argument('--do_train', default=False, action=\"store_true\", help=\"whether", "tokenizer = GPT2Tokenizer.from_pretrained(args.model) model = GPT2LMHeadModel.from_pretrained(args.model) #model = nn.DataParallel(model) model.to(args.device)", "RandomSampler(dataset) else: sampler = DistributedSampler(dataset) train_dataloader = DL(dataset, sampler=sampler, batch_size=args.batch_size,", "desc='Epoch', disable=args.local_rank not in [-1, 0]): #for idx in range(0,", "torch.utils.data import RandomSampler, SequentialSampler from torch.utils.data import DataLoader as DL", "local_rank\") parser.add_argument('--gradient_accumulation_steps', type=int, default=5, help=\"accumulation steps for gradient\") parser.add_argument('--decode_first_K', type=int,", "train or test the model\") parser.add_argument('--dim', default=768, type=int, help=\"whether to", "args.local_rank == -1: sampler = RandomSampler(dataset) else: sampler = DistributedSampler(dataset)", "to train or test the model\") parser.add_argument('--do_test', default=False, action=\"store_true\", help=\"whether", "experiment\") parser.add_argument('--max_len', default=800, type=int, help=\"whether to train or test the", "[-1, 0] and idx % args.every == 0 and idx", "-trg_out.shape[1]:, :].contiguous() loss = criterion(logits.view(-1, logits.shape[-1]), trg_out.view(-1)) loss = loss", "torch import torch.nn.functional as F import numpy as np from", "sampler=sampler, batch_size=args.batch_size, num_workers=0) model.train() optimizer = optim.Adam(model.parameters(), args.learning_rate) avg_loss =", "= torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True) else: model = torch.nn.DataParallel(model) for", "enumerate(tqdm(train_dataloader, desc=\"Iteration\", disable=args.local_rank not in [-1, 0])): batch = tuple(Variable(t).to(device)", "'gpt2': torch.save(model.state_dict(), '{}/GPT_ep{}.pt'.format(args.id, epoch_idx)) else: torch.save(model.state_dict(), '{}/GPT_medium_ep{}.pt'.format(args.id, epoch_idx)) if args.local_rank", "for epoch_idx in trange(0, args.epoch, desc='Epoch', disable=args.local_rank not in [-1,", "os import numpy import nltk from torch.utils.tensorboard import SummaryWriter import", "test the model\") parser.add_argument(\"--modelpath\", type=str, default=\"bert-base-uncased\", help=\"For distributed training: local_rank\")", "= GPT2LMHeadModel.from_pretrained(args.model) #model = nn.DataParallel(model) model.to(args.device) if args.local_rank == 0:", "output_device=args.local_rank, find_unused_parameters=True) else: model = torch.nn.DataParallel(model) for epoch_idx in trange(0,", "pandas import os import numpy import nltk from torch.utils.tensorboard import", "to compute the BLEU scores on challenge split\") parser.add_argument('--do_ppl', default=False,", "text = text[: text.find(tokenizer.eos_token)] print(\"GROUNDTRUH |||||| \",text) break avg_loss =", "args.device = device if args.local_rank not in [-1, 0]: torch.distributed.barrier()", "= samples[:, caption.shape[1]:] samples = samples.cpu().data.numpy() for s, gt in", "torch.save(model.state_dict(), '{}/GPT_ep{}.pt'.format(args.id, epoch_idx)) else: torch.save(model.state_dict(), '{}/GPT_medium_ep{}.pt'.format(args.id, epoch_idx)) if args.local_rank in", "avg_loss = 0 global_step = 0 if args.local_rank != -1:", "tuple(Variable(t).to(device) for t in batch) trg_inp, trg_out, mask, caption =", "default=False, action=\"store_true\", help=\"whether to compute perplexity of the model\") parser.add_argument('--do_verify',", "default=2e-6, type=float, help=\"whether to train or test the model\") parser.add_argument('--dataset',", "scores on test split\") parser.add_argument('--do_test_challenge', default=False, action=\"store_true\", help=\"whether to compute", "train or test the model\") parser.add_argument('--every', default=50, type=int, help=\"whether to", "help=\"whether to train or test the model\") parser.add_argument('--load_from', default='', type=str,", "loss.backward() optimizer.step() global_step += 1 if args.local_rank in [-1, 0]", "+= loss.item() loss.backward() optimizer.step() global_step += 1 if args.local_rank in", "default=42, help=\"random seed for initialization\") parser.add_argument('--do_train', default=False, action=\"store_true\", help=\"whether to", "help=\"whether to train or test the model\") parser.add_argument('--learning_rate', default=2e-6, type=float,", "type=str) parser.add_argument(\"--top_k\", type=int, default=0) parser.add_argument(\"--top_p\", type=float, default=0.9) parser.add_argument('--seed', type=int, default=42,", "* from Model import BERTGen from utils import sample_sequence import", "optim import math import sys import pandas import os import", "model.zero_grad() optimizer.zero_grad() logits = model(inputs)[0] logits = logits[:, -trg_out.shape[1]:, :].contiguous()", "args.n_gpu = 1 args.device = device if args.local_rank not in", "sample_sequence(model, 30, fake_inputs, []) samples = samples[:, caption.shape[1]:] samples =", "test the model\") parser.add_argument('--head', default=4, type=int, help=\"whether to train or", "torch.utils.data.distributed import DistributedSampler warnings.filterwarnings(\"ignore\", category=UserWarning) device = torch.device('cuda') def set_seed(args):", "default=50, type=int, help=\"whether to train or test the model\") parser.add_argument('--load_from',", "score on test split\") parser.add_argument('--do_verify_challenge', default=False, action=\"store_true\", help=\"whether compute the", "torch.nn.DataParallel(model) for epoch_idx in trange(0, args.epoch, desc='Epoch', disable=args.local_rank not in", "if args.local_rank in [-1, 0] and idx % args.every ==", "or test the model\") parser.add_argument('--dim', default=768, type=int, help=\"whether to train", "torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True) else: model = torch.nn.DataParallel(model) for epoch_idx", "to compute the BLEU scores on test split\") parser.add_argument('--do_test_challenge', default=False,", "the model\") parser.add_argument('--head', default=4, type=int, help=\"whether to train or test", "args = parser.parse_args() if args.local_rank == -1: device = torch.device(\"cuda\")", "0]: if args.model == 'gpt2': torch.save(model.state_dict(), '{}/GPT_ep{}.pt'.format(args.id, epoch_idx)) else: torch.save(model.state_dict(),", "numpy import nltk from torch.utils.tensorboard import SummaryWriter import warnings from", "print(\"PREDICTION |||||| \", text) text = tokenizer.decode(gt, clean_up_tokenization_spaces=True) text =", "import numpy import nltk from torch.utils.tensorboard import SummaryWriter import warnings", "model\") parser.add_argument(\"--modelpath\", type=str, default=\"bert-base-uncased\", help=\"For distributed training: local_rank\") parser.add_argument('--gradient_accumulation_steps', type=int,", "the BLEU scores on test split\") parser.add_argument('--do_test_challenge', default=False, action=\"store_true\", help=\"whether", "args.every == 0 and idx > 0: tb_writer.add_scalar(\"perplexity\", math.exp(avg_loss /", "disable=args.local_rank not in [-1, 0]): #for idx in range(0, dataset.train_len()):", "type=int, help=\"whether to train or test the model\") parser.add_argument('--dim', default=768,", "action=\"store_true\", help=\"whether to train or test the model\") parser.add_argument('--do_val', default=False,", "in batch) trg_inp, trg_out, mask, caption = batch inputs =", "parser.add_argument('--do_test', default=False, action=\"store_true\", help=\"whether to compute the BLEU scores on", "= trg_out.cpu().data.numpy() #samples = model.sample(fake_inputs, tabfeat, caption, highlight_idx, bert) samples", "the model\") parser.add_argument('--do_verify', default=False, action=\"store_true\", help=\"whether compute the adv-acc score", "type=int, default=5, help=\"accumulation steps for gradient\") parser.add_argument('--decode_first_K', type=int, default=10000, help=\"For", "args.local_rank) torch.distributed.init_process_group(backend='nccl') args.n_gpu = 1 args.device = device if args.local_rank", "loss.item() loss.backward() optimizer.step() global_step += 1 if args.local_rank in [-1,", "from transformers import GPT2LMHeadModel, GPT2Tokenizer, BertTokenizer from DataLoader import *", "default=0.9) parser.add_argument('--seed', type=int, default=42, help=\"random seed for initialization\") parser.add_argument('--do_train', default=False,", "#model = nn.DataParallel(model) model.to(args.device) if args.local_rank == 0: torch.distributed.barrier() criterion", "GPT2Config from transformers import GPT2LMHeadModel, GPT2Tokenizer, BertTokenizer from DataLoader import", "help=\"whether to train or test the model\") parser.add_argument('--every', default=50, type=int,", "args.do_train: if args.local_rank in [-1, 0]: if not os.path.exists(args.id): os.mkdir(args.id)", "math.exp(avg_loss / args.every), global_step) fake_inputs = caption gt_inputs = trg_out.cpu().data.numpy()", "F import numpy as np from torch import nn from", "model\") parser.add_argument('--do_test', default=False, action=\"store_true\", help=\"whether to compute the BLEU scores", "or test the model\") parser.add_argument(\"--modelpath\", type=str, default=\"bert-base-uncased\", help=\"For distributed training:", "text = tokenizer.decode(s, clean_up_tokenization_spaces=True) text = text[: text.find(tokenizer.eos_token)] print(\"PREDICTION ||||||", "train or test the model\") parser.add_argument('--do_val', default=False, action=\"store_true\", help=\"whether to", "if args.do_train: if args.local_rank in [-1, 0]: if not os.path.exists(args.id):", "import GPT2Config from transformers import GPT2LMHeadModel, GPT2Tokenizer, BertTokenizer from DataLoader", "help=\"whether to train or test the model\") parser.add_argument('--layers', default=3, type=int,", "idx > 0: tb_writer.add_scalar(\"perplexity\", math.exp(avg_loss / args.every), global_step) fake_inputs =", "BLEU scores on challenge split\") parser.add_argument('--do_ppl', default=False, action=\"store_true\", help=\"whether to", "default=False, action=\"store_true\", help=\"whether to train or test the model\") parser.add_argument('--do_test',", "to compute perplexity of the model\") parser.add_argument('--do_verify', default=False, action=\"store_true\", help=\"whether", "from DataLoader import * from Model import BERTGen from utils", "compute the adv-acc score on test split\") parser.add_argument('--do_verify_challenge', default=False, action=\"store_true\",", "train or test the model\") parser.add_argument('--id', default='models', type=str, help=\"specify the", "args.local_rank == -1: device = torch.device(\"cuda\") args.n_gpu = 1 else:", "trg_inp, trg_out, mask, caption = batch inputs = torch.cat([caption, trg_inp],", "= DistributedSampler(dataset) train_dataloader = DL(dataset, sampler=sampler, batch_size=args.batch_size, num_workers=0) model.train() optimizer", "import DataLoader as DL import torch from torch.utils.data.distributed import DistributedSampler", "trange from torch.utils.data import RandomSampler, SequentialSampler from torch.utils.data import DataLoader", "test split\") parser.add_argument('--do_test_challenge', default=False, action=\"store_true\", help=\"whether to compute the BLEU", "default='gpt2', type=str) parser.add_argument(\"--top_k\", type=int, default=0) parser.add_argument(\"--top_p\", type=float, default=0.9) parser.add_argument('--seed', type=int,", "import logging import torch import torch.nn.functional as F import numpy", "as DL import torch from torch.utils.data.distributed import DistributedSampler warnings.filterwarnings(\"ignore\", category=UserWarning)", "device = torch.device('cuda') def set_seed(args): np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu >", "sys import pandas import os import numpy import nltk from", "category=UserWarning) device = torch.device('cuda') def set_seed(args): np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu", "device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True) else: model = torch.nn.DataParallel(model) for epoch_idx in", "initialization\") parser.add_argument('--do_train', default=False, action=\"store_true\", help=\"whether to train or test the", "model = torch.nn.DataParallel(model) for epoch_idx in trange(0, args.epoch, desc='Epoch', disable=args.local_rank", "import sys import pandas import os import numpy import nltk", "text.find(tokenizer.eos_token)] print(\"PREDICTION |||||| \", text) text = tokenizer.decode(gt, clean_up_tokenization_spaces=True) text", "parser.add_argument('--do_verify', default=False, action=\"store_true\", help=\"whether compute the adv-acc score on test", "0 and idx > 0: tb_writer.add_scalar(\"perplexity\", math.exp(avg_loss / args.every), global_step)", "GPT2LMHeadModel, GPT2Tokenizer, BertTokenizer from DataLoader import * from Model import", "help=\"whether compute the adv-acc score on challenge split\") parser.add_argument('--epoch', default=10,", "the model\") parser.add_argument(\"--modelpath\", type=str, default=\"bert-base-uncased\", help=\"For distributed training: local_rank\") parser.add_argument('--gradient_accumulation_steps',", "torch.optim as optim import math import sys import pandas import", "= device if args.local_rank not in [-1, 0]: torch.distributed.barrier() tokenizer", "in [-1, 0]: if not os.path.exists(args.id): os.mkdir(args.id) tb_writer = SummaryWriter(log_dir='tensorboard/GPT2-{}'.format(args.model))", "help=\"whether to train or test the model\") parser.add_argument('--head', default=4, type=int,", "+= 1 if args.local_rank in [-1, 0] and idx %", "Variable from transformers import GPT2Config from transformers import GPT2LMHeadModel, GPT2Tokenizer,", "args.n_gpu = 1 else: torch.cuda.set_device(args.local_rank) device = torch.device('cuda', args.local_rank) torch.distributed.init_process_group(backend='nccl')", "help=\"whether to compute the BLEU scores on challenge split\") parser.add_argument('--do_ppl',", "train_dataloader = DL(dataset, sampler=sampler, batch_size=args.batch_size, num_workers=0) model.train() optimizer = optim.Adam(model.parameters(),", "help=\"whether to train or test the model\") parser.add_argument('--batch_size', default=6, type=int,", "SummaryWriter(log_dir='tensorboard/GPT2-{}'.format(args.model)) dataset = GPTTableDataset2('data/train_lm_preprocessed.json', tokenizer, args.max_len) if args.local_rank == -1:", "argparse.ArgumentParser() parser.add_argument(\"--model\", default='gpt2', type=str) parser.add_argument(\"--top_k\", type=int, default=0) parser.add_argument(\"--top_p\", type=float, default=0.9)", "torch import nn from torch.autograd import Variable from transformers import", "DistributedSampler warnings.filterwarnings(\"ignore\", category=UserWarning) device = torch.device('cuda') def set_seed(args): np.random.seed(args.seed) torch.manual_seed(args.seed)", "= torch.device(\"cuda\") args.n_gpu = 1 else: torch.cuda.set_device(args.local_rank) device = torch.device('cuda',", "train or test the model\") parser.add_argument('--layers', default=3, type=int, help=\"whether to", "torch.nn.functional as F import numpy as np from torch import", "0]: if not os.path.exists(args.id): os.mkdir(args.id) tb_writer = SummaryWriter(log_dir='tensorboard/GPT2-{}'.format(args.model)) dataset =", "parser.add_argument('--id', default='models', type=str, help=\"specify the id of the experiment\") parser.add_argument('--max_len',", "parser.add_argument(\"--model\", default='gpt2', type=str) parser.add_argument(\"--top_k\", type=int, default=0) parser.add_argument(\"--top_p\", type=float, default=0.9) parser.add_argument('--seed',", "training: local_rank\") parser.add_argument('--gradient_accumulation_steps', type=int, default=5, help=\"accumulation steps for gradient\") parser.add_argument('--decode_first_K',", "== -1: device = torch.device(\"cuda\") args.n_gpu = 1 else: torch.cuda.set_device(args.local_rank)", "= DL(dataset, sampler=sampler, batch_size=args.batch_size, num_workers=0) model.train() optimizer = optim.Adam(model.parameters(), args.learning_rate)", "= tuple(Variable(t).to(device) for t in batch) trg_inp, trg_out, mask, caption", "epoch_idx)) else: torch.save(model.state_dict(), '{}/GPT_medium_ep{}.pt'.format(args.id, epoch_idx)) if args.local_rank in [-1, 0]:", "to train or test the model\") parser.add_argument('--dim', default=768, type=int, help=\"whether", "= 0 if args.local_rank != -1: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],", "help=\"whether compute the adv-acc score on test split\") parser.add_argument('--do_verify_challenge', default=False,", "-1: sampler = RandomSampler(dataset) else: sampler = DistributedSampler(dataset) train_dataloader =", "= torch.nn.DataParallel(model) for epoch_idx in trange(0, args.epoch, desc='Epoch', disable=args.local_rank not", "DistributedSampler(dataset) train_dataloader = DL(dataset, sampler=sampler, batch_size=args.batch_size, num_workers=0) model.train() optimizer =", "= argparse.ArgumentParser() parser.add_argument(\"--model\", default='gpt2', type=str) parser.add_argument(\"--top_k\", type=int, default=0) parser.add_argument(\"--top_p\", type=float,", "type=int, help=\"whether to train or test the model\") parser.add_argument('--local_rank', default=-1,", "if args.local_rank in [-1, 0]: if not os.path.exists(args.id): os.mkdir(args.id) tb_writer", "trg_out, mask, caption = batch inputs = torch.cat([caption, trg_inp], 1)", "import warnings from tqdm import tqdm, trange from torch.utils.data import", "= caption gt_inputs = trg_out.cpu().data.numpy() #samples = model.sample(fake_inputs, tabfeat, caption,", "scores on challenge split\") parser.add_argument('--do_ppl', default=False, action=\"store_true\", help=\"whether to compute", "fake_inputs = caption gt_inputs = trg_out.cpu().data.numpy() #samples = model.sample(fake_inputs, tabfeat,", "= 1 args.device = device if args.local_rank not in [-1,", "dataset.train_len()): for idx, batch in enumerate(tqdm(train_dataloader, desc=\"Iteration\", disable=args.local_rank not in", "-1: device = torch.device(\"cuda\") args.n_gpu = 1 else: torch.cuda.set_device(args.local_rank) device", "mask, caption = batch inputs = torch.cat([caption, trg_inp], 1) model.zero_grad()", "s, gt in zip(samples, gt_inputs): text = tokenizer.decode(s, clean_up_tokenization_spaces=True) text", "help=\"For debugging purpose\") args = parser.parse_args() if args.local_rank == -1:", "DataLoader as DL import torch from torch.utils.data.distributed import DistributedSampler warnings.filterwarnings(\"ignore\",", "Model import BERTGen from utils import sample_sequence import torch.optim as", "batch) trg_inp, trg_out, mask, caption = batch inputs = torch.cat([caption,", "text[: text.find(tokenizer.eos_token)] print(\"GROUNDTRUH |||||| \",text) break avg_loss = 0 if", "and idx % args.every == 0 and idx > 0:", "train or test the model\") parser.add_argument('--learning_rate', default=2e-6, type=float, help=\"whether to", "args.model == 'gpt2': torch.save(model.state_dict(), '{}/GPT_ep{}.pt'.format(args.id, epoch_idx)) else: torch.save(model.state_dict(), '{}/GPT_medium_ep{}.pt'.format(args.id, epoch_idx))", "if args.model == 'gpt2': torch.save(model.state_dict(), '{}/GPT_ep{}.pt'.format(args.id, epoch_idx)) else: torch.save(model.state_dict(), '{}/GPT_medium_ep{}.pt'.format(args.id,", "else: torch.save(model.state_dict(), '{}/GPT_medium_ep{}.pt'.format(args.id, epoch_idx)) if args.local_rank in [-1, 0]: tb_writer.close()", "type=float, default=0.9) parser.add_argument('--seed', type=int, default=42, help=\"random seed for initialization\") parser.add_argument('--do_train',", "default=-1, type=int, help=\"whether to train or test the model\") parser.add_argument('--learning_rate',", "or test the model\") parser.add_argument('--id', default='models', type=str, help=\"specify the id", "not in [-1, 0])): batch = tuple(Variable(t).to(device) for t in", "torch.distributed.barrier() criterion = nn.CrossEntropyLoss(reduction='none', ignore_index=-1) if args.do_train: if args.local_rank in", "tb_writer.add_scalar(\"perplexity\", math.exp(avg_loss / args.every), global_step) fake_inputs = caption gt_inputs =", "test the model\") parser.add_argument('--do_rl', default=False, action=\"store_true\", help=\"whether to train or", "perplexity of the model\") parser.add_argument('--do_verify', default=False, action=\"store_true\", help=\"whether compute the", "the model\") parser.add_argument('--dim', default=768, type=int, help=\"whether to train or test", "on test split\") parser.add_argument('--do_test_challenge', default=False, action=\"store_true\", help=\"whether to compute the", "import os import numpy import nltk from torch.utils.tensorboard import SummaryWriter", "optimizer.zero_grad() logits = model(inputs)[0] logits = logits[:, -trg_out.shape[1]:, :].contiguous() loss", "fake_inputs, []) samples = samples[:, caption.shape[1]:] samples = samples.cpu().data.numpy() for", "help=\"whether to compute perplexity of the model\") parser.add_argument('--do_verify', default=False, action=\"store_true\",", "train or test the model\") parser.add_argument('--do_rl', default=False, action=\"store_true\", help=\"whether to", "model.to(args.device) if args.local_rank == 0: torch.distributed.barrier() criterion = nn.CrossEntropyLoss(reduction='none', ignore_index=-1)", "samples = sample_sequence(model, 30, fake_inputs, []) samples = samples[:, caption.shape[1]:]", "or test the model\") parser.add_argument('--layers', default=3, type=int, help=\"whether to train", "logits = logits[:, -trg_out.shape[1]:, :].contiguous() loss = criterion(logits.view(-1, logits.shape[-1]), trg_out.view(-1))", "logits.shape[-1]), trg_out.view(-1)) loss = loss * mask.view(-1) loss = loss.sum()", "caption, highlight_idx, bert) samples = sample_sequence(model, 30, fake_inputs, []) samples", "GPT2Tokenizer, BertTokenizer from DataLoader import * from Model import BERTGen", "= 0 global_step = 0 if args.local_rank != -1: model", "mask.sum() avg_loss += loss.item() loss.backward() optimizer.step() global_step += 1 if", "the model\") parser.add_argument('--load_from', default='', type=str, help=\"whether to train or test", "test the model\") parser.add_argument('--id', default='models', type=str, help=\"specify the id of", "1) model.zero_grad() optimizer.zero_grad() logits = model(inputs)[0] logits = logits[:, -trg_out.shape[1]:,", "parser.add_argument('--local_rank', default=-1, type=int, help=\"whether to train or test the model\")", "in [-1, 0] and idx % args.every == 0 and", "batch_size=args.batch_size, num_workers=0) model.train() optimizer = optim.Adam(model.parameters(), args.learning_rate) avg_loss = 0", "torch.distributed.init_process_group(backend='nccl') args.n_gpu = 1 args.device = device if args.local_rank not", "type=float, help=\"whether to train or test the model\") parser.add_argument('--dataset', default='table',", "nn from torch.autograd import Variable from transformers import GPT2Config from", "nn.DataParallel(model) model.to(args.device) if args.local_rank == 0: torch.distributed.barrier() criterion = nn.CrossEntropyLoss(reduction='none',", "model = GPT2LMHeadModel.from_pretrained(args.model) #model = nn.DataParallel(model) model.to(args.device) if args.local_rank ==", "for s, gt in zip(samples, gt_inputs): text = tokenizer.decode(s, clean_up_tokenization_spaces=True)", "1 else: torch.cuda.set_device(args.local_rank) device = torch.device('cuda', args.local_rank) torch.distributed.init_process_group(backend='nccl') args.n_gpu =", "default=6, type=int, help=\"whether to train or test the model\") parser.add_argument('--local_rank',", "parser.add_argument('--dataset', default='table', type=str, help=\"whether to train or test the model\")", "import pandas import os import numpy import nltk from torch.utils.tensorboard", "help=\"For distributed training: local_rank\") parser.add_argument('--gradient_accumulation_steps', type=int, default=5, help=\"accumulation steps for", "test the model\") parser.add_argument('--batch_size', default=6, type=int, help=\"whether to train or", "to train or test the model\") parser.add_argument('--layers', default=3, type=int, help=\"whether", "test the model\") parser.add_argument('--dim', default=768, type=int, help=\"whether to train or", "parser.add_argument('--do_verify_challenge', default=False, action=\"store_true\", help=\"whether compute the adv-acc score on challenge", "args.max_len) if args.local_rank == -1: sampler = RandomSampler(dataset) else: sampler", "torch.cuda.set_device(args.local_rank) device = torch.device('cuda', args.local_rank) torch.distributed.init_process_group(backend='nccl') args.n_gpu = 1 args.device", "'{}/GPT_ep{}.pt'.format(args.id, epoch_idx)) else: torch.save(model.state_dict(), '{}/GPT_medium_ep{}.pt'.format(args.id, epoch_idx)) if args.local_rank in [-1,", "or test the model\") parser.add_argument('--dataset', default='table', type=str, help=\"whether to train", "action=\"store_true\", help=\"whether to train or test the model\") parser.add_argument('--do_test', default=False,", "in range(0, dataset.train_len()): for idx, batch in enumerate(tqdm(train_dataloader, desc=\"Iteration\", disable=args.local_rank", "type=str, help=\"whether to train or test the model\") parser.add_argument('--every', default=50,", "test the model\") parser.add_argument('--do_test', default=False, action=\"store_true\", help=\"whether to compute the", "the model\") parser.add_argument('--local_rank', default=-1, type=int, help=\"whether to train or test", "model\") parser.add_argument('--head', default=4, type=int, help=\"whether to train or test the", "argparse import logging import torch import torch.nn.functional as F import", "batch in enumerate(tqdm(train_dataloader, desc=\"Iteration\", disable=args.local_rank not in [-1, 0])): batch", "0])): batch = tuple(Variable(t).to(device) for t in batch) trg_inp, trg_out,", "caption.shape[1]:] samples = samples.cpu().data.numpy() for s, gt in zip(samples, gt_inputs):", "= torch.device('cuda') def set_seed(args): np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0:", "warnings.filterwarnings(\"ignore\", category=UserWarning) device = torch.device('cuda') def set_seed(args): np.random.seed(args.seed) torch.manual_seed(args.seed) if", "score on challenge split\") parser.add_argument('--epoch', default=10, type=int, help=\"whether to train", "default=False, action=\"store_true\", help=\"whether to compute the BLEU scores on test", "the model\") parser.add_argument('--every', default=50, type=int, help=\"whether to train or test", "np from torch import nn from torch.autograd import Variable from", "num_workers=0) model.train() optimizer = optim.Adam(model.parameters(), args.learning_rate) avg_loss = 0 global_step", "the model\") parser.add_argument('--do_test', default=False, action=\"store_true\", help=\"whether to compute the BLEU", "trg_inp], 1) model.zero_grad() optimizer.zero_grad() logits = model(inputs)[0] logits = logits[:,", "epoch_idx in trange(0, args.epoch, desc='Epoch', disable=args.local_rank not in [-1, 0]):", "= GPT2Tokenizer.from_pretrained(args.model) model = GPT2LMHeadModel.from_pretrained(args.model) #model = nn.DataParallel(model) model.to(args.device) if", "0]: torch.distributed.barrier() tokenizer = GPT2Tokenizer.from_pretrained(args.model) model = GPT2LMHeadModel.from_pretrained(args.model) #model =", "model\") parser.add_argument('--load_from', default='', type=str, help=\"whether to train or test the", "model\") parser.add_argument('--every', default=50, type=int, help=\"whether to train or test the", "os.mkdir(args.id) tb_writer = SummaryWriter(log_dir='tensorboard/GPT2-{}'.format(args.model)) dataset = GPTTableDataset2('data/train_lm_preprocessed.json', tokenizer, args.max_len) if", "if args.local_rank == -1: sampler = RandomSampler(dataset) else: sampler =", "device = torch.device('cuda', args.local_rank) torch.distributed.init_process_group(backend='nccl') args.n_gpu = 1 args.device =", "import torch.nn.functional as F import numpy as np from torch", "the model\") parser.add_argument('--batch_size', default=6, type=int, help=\"whether to train or test", "batch = tuple(Variable(t).to(device) for t in batch) trg_inp, trg_out, mask,", "= nn.CrossEntropyLoss(reduction='none', ignore_index=-1) if args.do_train: if args.local_rank in [-1, 0]:", "torch.device('cuda', args.local_rank) torch.distributed.init_process_group(backend='nccl') args.n_gpu = 1 args.device = device if", "import numpy as np from torch import nn from torch.autograd", "if not os.path.exists(args.id): os.mkdir(args.id) tb_writer = SummaryWriter(log_dir='tensorboard/GPT2-{}'.format(args.model)) dataset = GPTTableDataset2('data/train_lm_preprocessed.json',", "loss.sum() / mask.sum() avg_loss += loss.item() loss.backward() optimizer.step() global_step +=", "= torch.device('cuda', args.local_rank) torch.distributed.init_process_group(backend='nccl') args.n_gpu = 1 args.device = device", "= loss * mask.view(-1) loss = loss.sum() / mask.sum() avg_loss", "clean_up_tokenization_spaces=True) text = text[: text.find(tokenizer.eos_token)] print(\"PREDICTION |||||| \", text) text", "adv-acc score on challenge split\") parser.add_argument('--epoch', default=10, type=int, help=\"whether to", "in enumerate(tqdm(train_dataloader, desc=\"Iteration\", disable=args.local_rank not in [-1, 0])): batch =", "trange(0, args.epoch, desc='Epoch', disable=args.local_rank not in [-1, 0]): #for idx", "help=\"specify the id of the experiment\") parser.add_argument('--max_len', default=800, type=int, help=\"whether", "parser.add_argument('--do_ppl', default=False, action=\"store_true\", help=\"whether to compute perplexity of the model\")", "zip(samples, gt_inputs): text = tokenizer.decode(s, clean_up_tokenization_spaces=True) text = text[: text.find(tokenizer.eos_token)]", "to train or test the model\") parser.add_argument('--every', default=50, type=int, help=\"whether", "help=\"whether to train or test the model\") parser.add_argument(\"--modelpath\", type=str, default=\"bert-base-uncased\",", "parser.add_argument('--seed', type=int, default=42, help=\"random seed for initialization\") parser.add_argument('--do_train', default=False, action=\"store_true\",", "'__main__': parser = argparse.ArgumentParser() parser.add_argument(\"--model\", default='gpt2', type=str) parser.add_argument(\"--top_k\", type=int, default=0)", "compute the BLEU scores on test split\") parser.add_argument('--do_test_challenge', default=False, action=\"store_true\",", "in [-1, 0]): #for idx in range(0, dataset.train_len()): for idx,", "utils import sample_sequence import torch.optim as optim import math import", "-1: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True) else: model =", "parser.add_argument(\"--top_k\", type=int, default=0) parser.add_argument(\"--top_p\", type=float, default=0.9) parser.add_argument('--seed', type=int, default=42, help=\"random", "help=\"whether to compute the BLEU scores on test split\") parser.add_argument('--do_test_challenge',", "model(inputs)[0] logits = logits[:, -trg_out.shape[1]:, :].contiguous() loss = criterion(logits.view(-1, logits.shape[-1]),", "compute the adv-acc score on challenge split\") parser.add_argument('--epoch', default=10, type=int,", "and idx > 0: tb_writer.add_scalar(\"perplexity\", math.exp(avg_loss / args.every), global_step) fake_inputs", "import nltk from torch.utils.tensorboard import SummaryWriter import warnings from tqdm", "samples = samples.cpu().data.numpy() for s, gt in zip(samples, gt_inputs): text", "0 if args.local_rank != -1: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank,", "torch.device(\"cuda\") args.n_gpu = 1 else: torch.cuda.set_device(args.local_rank) device = torch.device('cuda', args.local_rank)", "id of the experiment\") parser.add_argument('--max_len', default=800, type=int, help=\"whether to train", "from Model import BERTGen from utils import sample_sequence import torch.optim", "model.train() optimizer = optim.Adam(model.parameters(), args.learning_rate) avg_loss = 0 global_step =", "parser.add_argument('--do_test_challenge', default=False, action=\"store_true\", help=\"whether to compute the BLEU scores on", "= text[: text.find(tokenizer.eos_token)] print(\"PREDICTION |||||| \", text) text = tokenizer.decode(gt,", "warnings from tqdm import tqdm, trange from torch.utils.data import RandomSampler,", "model\") parser.add_argument('--id', default='models', type=str, help=\"specify the id of the experiment\")", "if args.local_rank == 0: torch.distributed.barrier() criterion = nn.CrossEntropyLoss(reduction='none', ignore_index=-1) if", "parser.add_argument('--head', default=4, type=int, help=\"whether to train or test the model\")", "the id of the experiment\") parser.add_argument('--max_len', default=800, type=int, help=\"whether to", "help=\"whether to train or test the model\") parser.add_argument('--dim', default=768, type=int,", "import * from Model import BERTGen from utils import sample_sequence", "parser.add_argument('--gradient_accumulation_steps', type=int, default=5, help=\"accumulation steps for gradient\") parser.add_argument('--decode_first_K', type=int, default=10000,", "= text[: text.find(tokenizer.eos_token)] print(\"GROUNDTRUH |||||| \",text) break avg_loss = 0", "of the experiment\") parser.add_argument('--max_len', default=800, type=int, help=\"whether to train or", "or test the model\") parser.add_argument('--learning_rate', default=2e-6, type=float, help=\"whether to train", "parser.add_argument('--dim', default=768, type=int, help=\"whether to train or test the model\")", "or test the model\") parser.add_argument('--do_val', default=False, action=\"store_true\", help=\"whether to train", "if args.local_rank not in [-1, 0]: torch.distributed.barrier() tokenizer = GPT2Tokenizer.from_pretrained(args.model)", "loss = criterion(logits.view(-1, logits.shape[-1]), trg_out.view(-1)) loss = loss * mask.view(-1)", "loss = loss * mask.view(-1) loss = loss.sum() / mask.sum()", "gt in zip(samples, gt_inputs): text = tokenizer.decode(s, clean_up_tokenization_spaces=True) text =", "help=\"whether to train or test the model\") parser.add_argument('--local_rank', default=-1, type=int,", "parser.add_argument('--max_len', default=800, type=int, help=\"whether to train or test the model\")", "= GPTTableDataset2('data/train_lm_preprocessed.json', tokenizer, args.max_len) if args.local_rank == -1: sampler =", "challenge split\") parser.add_argument('--do_ppl', default=False, action=\"store_true\", help=\"whether to compute perplexity of", "device = torch.device(\"cuda\") args.n_gpu = 1 else: torch.cuda.set_device(args.local_rank) device =", "== '__main__': parser = argparse.ArgumentParser() parser.add_argument(\"--model\", default='gpt2', type=str) parser.add_argument(\"--top_k\", type=int,", "else: torch.cuda.set_device(args.local_rank) device = torch.device('cuda', args.local_rank) torch.distributed.init_process_group(backend='nccl') args.n_gpu = 1", "[]) samples = samples[:, caption.shape[1]:] samples = samples.cpu().data.numpy() for s,", "|||||| \",text) break avg_loss = 0 if args.local_rank in [-1,", "test the model\") parser.add_argument('--every', default=50, type=int, help=\"whether to train or", "sampler = RandomSampler(dataset) else: sampler = DistributedSampler(dataset) train_dataloader = DL(dataset,", "parser.add_argument('--learning_rate', default=2e-6, type=float, help=\"whether to train or test the model\")", "text[: text.find(tokenizer.eos_token)] print(\"PREDICTION |||||| \", text) text = tokenizer.decode(gt, clean_up_tokenization_spaces=True)", "split\") parser.add_argument('--do_verify_challenge', default=False, action=\"store_true\", help=\"whether compute the adv-acc score on", "challenge split\") parser.add_argument('--epoch', default=10, type=int, help=\"whether to train or test", "torch.distributed.barrier() tokenizer = GPT2Tokenizer.from_pretrained(args.model) model = GPT2LMHeadModel.from_pretrained(args.model) #model = nn.DataParallel(model)", "on challenge split\") parser.add_argument('--epoch', default=10, type=int, help=\"whether to train or", "import nn from torch.autograd import Variable from transformers import GPT2Config", "0 if args.local_rank in [-1, 0]: if args.model == 'gpt2':", "import torch.optim as optim import math import sys import pandas", "type=int, help=\"whether to train or test the model\") parser.add_argument('--head', default=4,", "if args.local_rank in [-1, 0]: if args.model == 'gpt2': torch.save(model.state_dict(),", "text = tokenizer.decode(gt, clean_up_tokenization_spaces=True) text = text[: text.find(tokenizer.eos_token)] print(\"GROUNDTRUH ||||||", "for gradient\") parser.add_argument('--decode_first_K', type=int, default=10000, help=\"For debugging purpose\") args =", "from torch.utils.data.distributed import DistributedSampler warnings.filterwarnings(\"ignore\", category=UserWarning) device = torch.device('cuda') def", "text) text = tokenizer.decode(gt, clean_up_tokenization_spaces=True) text = text[: text.find(tokenizer.eos_token)] print(\"GROUNDTRUH", "#samples = model.sample(fake_inputs, tabfeat, caption, highlight_idx, bert) samples = sample_sequence(model,", "default=0) parser.add_argument(\"--top_p\", type=float, default=0.9) parser.add_argument('--seed', type=int, default=42, help=\"random seed for", "!= -1: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True) else: model", "or test the model\") parser.add_argument('--every', default=50, type=int, help=\"whether to train", "import argparse import logging import torch import torch.nn.functional as F", "help=\"whether to train or test the model\") parser.add_argument('--dataset', default='table', type=str,", "torch.device('cuda') def set_seed(args): np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed)", "[-1, 0]: if not os.path.exists(args.id): os.mkdir(args.id) tb_writer = SummaryWriter(log_dir='tensorboard/GPT2-{}'.format(args.model)) dataset", "args.epoch, desc='Epoch', disable=args.local_rank not in [-1, 0]): #for idx in", "text.find(tokenizer.eos_token)] print(\"GROUNDTRUH |||||| \",text) break avg_loss = 0 if args.local_rank", "0 global_step = 0 if args.local_rank != -1: model =", "test the model\") parser.add_argument('--dataset', default='table', type=str, help=\"whether to train or", "on test split\") parser.add_argument('--do_verify_challenge', default=False, action=\"store_true\", help=\"whether compute the adv-acc", "logits = model(inputs)[0] logits = logits[:, -trg_out.shape[1]:, :].contiguous() loss =", "torch from torch.utils.data.distributed import DistributedSampler warnings.filterwarnings(\"ignore\", category=UserWarning) device = torch.device('cuda')", "global_step) fake_inputs = caption gt_inputs = trg_out.cpu().data.numpy() #samples = model.sample(fake_inputs,", "action=\"store_true\", help=\"whether to compute the BLEU scores on challenge split\")", "global_step += 1 if args.local_rank in [-1, 0] and idx", "for idx, batch in enumerate(tqdm(train_dataloader, desc=\"Iteration\", disable=args.local_rank not in [-1,", "import SummaryWriter import warnings from tqdm import tqdm, trange from", "model\") parser.add_argument('--do_rl', default=False, action=\"store_true\", help=\"whether to train or test the", "split\") parser.add_argument('--do_test_challenge', default=False, action=\"store_true\", help=\"whether to compute the BLEU scores", "1 args.device = device if args.local_rank not in [-1, 0]:", "= optim.Adam(model.parameters(), args.learning_rate) avg_loss = 0 global_step = 0 if", "0] and idx % args.every == 0 and idx >", "GPT2Tokenizer.from_pretrained(args.model) model = GPT2LMHeadModel.from_pretrained(args.model) #model = nn.DataParallel(model) model.to(args.device) if args.local_rank", "in [-1, 0]: torch.distributed.barrier() tokenizer = GPT2Tokenizer.from_pretrained(args.model) model = GPT2LMHeadModel.from_pretrained(args.model)", "= batch inputs = torch.cat([caption, trg_inp], 1) model.zero_grad() optimizer.zero_grad() logits", "tabfeat, caption, highlight_idx, bert) samples = sample_sequence(model, 30, fake_inputs, [])", "the model\") parser.add_argument('--do_val', default=False, action=\"store_true\", help=\"whether to train or test", "BERTGen from utils import sample_sequence import torch.optim as optim import", "0: torch.cuda.manual_seed_all(args.seed) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument(\"--model\",", "model\") parser.add_argument('--dim', default=768, type=int, help=\"whether to train or test the", "desc=\"Iteration\", disable=args.local_rank not in [-1, 0])): batch = tuple(Variable(t).to(device) for", "args.local_rank == 0: torch.distributed.barrier() criterion = nn.CrossEntropyLoss(reduction='none', ignore_index=-1) if args.do_train:", "test the model\") parser.add_argument('--local_rank', default=-1, type=int, help=\"whether to train or", "avg_loss = 0 if args.local_rank in [-1, 0]: if args.model", "highlight_idx, bert) samples = sample_sequence(model, 30, fake_inputs, []) samples =", "args.local_rank in [-1, 0]: if args.model == 'gpt2': torch.save(model.state_dict(), '{}/GPT_ep{}.pt'.format(args.id,", "or test the model\") parser.add_argument('--head', default=4, type=int, help=\"whether to train", "== 0: torch.distributed.barrier() criterion = nn.CrossEntropyLoss(reduction='none', ignore_index=-1) if args.do_train: if", "optimizer.step() global_step += 1 if args.local_rank in [-1, 0] and", "/ args.every), global_step) fake_inputs = caption gt_inputs = trg_out.cpu().data.numpy() #samples", "RandomSampler, SequentialSampler from torch.utils.data import DataLoader as DL import torch", "== 0 and idx > 0: tb_writer.add_scalar(\"perplexity\", math.exp(avg_loss / args.every),", "<filename>GPT-distributed.py<gh_stars>100-1000 import argparse import logging import torch import torch.nn.functional as", "model\") parser.add_argument('--local_rank', default=-1, type=int, help=\"whether to train or test the", "nltk from torch.utils.tensorboard import SummaryWriter import warnings from tqdm import", "from torch import nn from torch.autograd import Variable from transformers", "0: torch.distributed.barrier() criterion = nn.CrossEntropyLoss(reduction='none', ignore_index=-1) if args.do_train: if args.local_rank", "from torch.utils.tensorboard import SummaryWriter import warnings from tqdm import tqdm,", "or test the model\") parser.add_argument('--do_rl', default=False, action=\"store_true\", help=\"whether to train", "parser.add_argument('--layers', default=3, type=int, help=\"whether to train or test the model\")", "criterion = nn.CrossEntropyLoss(reduction='none', ignore_index=-1) if args.do_train: if args.local_rank in [-1,", "\", text) text = tokenizer.decode(gt, clean_up_tokenization_spaces=True) text = text[: text.find(tokenizer.eos_token)]", "parser.add_argument('--do_train', default=False, action=\"store_true\", help=\"whether to train or test the model\")", "the model\") parser.add_argument('--dataset', default='table', type=str, help=\"whether to train or test", "dataset = GPTTableDataset2('data/train_lm_preprocessed.json', tokenizer, args.max_len) if args.local_rank == -1: sampler", "[-1, 0]): #for idx in range(0, dataset.train_len()): for idx, batch", "= criterion(logits.view(-1, logits.shape[-1]), trg_out.view(-1)) loss = loss * mask.view(-1) loss", "transformers import GPT2LMHeadModel, GPT2Tokenizer, BertTokenizer from DataLoader import * from", "default=5, help=\"accumulation steps for gradient\") parser.add_argument('--decode_first_K', type=int, default=10000, help=\"For debugging", "= samples.cpu().data.numpy() for s, gt in zip(samples, gt_inputs): text =", "default='', type=str, help=\"whether to train or test the model\") parser.add_argument('--id',", "= nn.DataParallel(model) model.to(args.device) if args.local_rank == 0: torch.distributed.barrier() criterion =", "import tqdm, trange from torch.utils.data import RandomSampler, SequentialSampler from torch.utils.data", "if args.local_rank == -1: device = torch.device(\"cuda\") args.n_gpu = 1", "default=False, action=\"store_true\", help=\"whether to compute the BLEU scores on challenge", "or test the model\") parser.add_argument('--load_from', default='', type=str, help=\"whether to train", "model\") parser.add_argument('--learning_rate', default=2e-6, type=float, help=\"whether to train or test the", "|||||| \", text) text = tokenizer.decode(gt, clean_up_tokenization_spaces=True) text = text[:", "not os.path.exists(args.id): os.mkdir(args.id) tb_writer = SummaryWriter(log_dir='tensorboard/GPT2-{}'.format(args.model)) dataset = GPTTableDataset2('data/train_lm_preprocessed.json', tokenizer,", "transformers import GPT2Config from transformers import GPT2LMHeadModel, GPT2Tokenizer, BertTokenizer from", "help=\"whether to train or test the model\") parser.add_argument('--do_test', default=False, action=\"store_true\",", "args.learning_rate) avg_loss = 0 global_step = 0 if args.local_rank !=", "avg_loss += loss.item() loss.backward() optimizer.step() global_step += 1 if args.local_rank", "parser.add_argument(\"--top_p\", type=float, default=0.9) parser.add_argument('--seed', type=int, default=42, help=\"random seed for initialization\")", "parser.add_argument('--epoch', default=10, type=int, help=\"whether to train or test the model\")", "the adv-acc score on test split\") parser.add_argument('--do_verify_challenge', default=False, action=\"store_true\", help=\"whether", "train or test the model\") parser.add_argument('--batch_size', default=6, type=int, help=\"whether to", "to train or test the model\") parser.add_argument('--do_rl', default=False, action=\"store_true\", help=\"whether", "test the model\") parser.add_argument('--layers', default=3, type=int, help=\"whether to train or", "DL(dataset, sampler=sampler, batch_size=args.batch_size, num_workers=0) model.train() optimizer = optim.Adam(model.parameters(), args.learning_rate) avg_loss", "criterion(logits.view(-1, logits.shape[-1]), trg_out.view(-1)) loss = loss * mask.view(-1) loss =", "= tokenizer.decode(gt, clean_up_tokenization_spaces=True) text = text[: text.find(tokenizer.eos_token)] print(\"GROUNDTRUH |||||| \",text)", "import GPT2LMHeadModel, GPT2Tokenizer, BertTokenizer from DataLoader import * from Model", "= parser.parse_args() if args.local_rank == -1: device = torch.device(\"cuda\") args.n_gpu", "samples[:, caption.shape[1]:] samples = samples.cpu().data.numpy() for s, gt in zip(samples,", "from torch.utils.data import RandomSampler, SequentialSampler from torch.utils.data import DataLoader as", "or test the model\") parser.add_argument('--do_test', default=False, action=\"store_true\", help=\"whether to compute", "from torch.autograd import Variable from transformers import GPT2Config from transformers", "SequentialSampler from torch.utils.data import DataLoader as DL import torch from", "of the model\") parser.add_argument('--do_verify', default=False, action=\"store_true\", help=\"whether compute the adv-acc", "model\") parser.add_argument('--layers', default=3, type=int, help=\"whether to train or test the", "debugging purpose\") args = parser.parse_args() if args.local_rank == -1: device", "type=int, default=0) parser.add_argument(\"--top_p\", type=float, default=0.9) parser.add_argument('--seed', type=int, default=42, help=\"random seed", "as optim import math import sys import pandas import os", "tokenizer.decode(s, clean_up_tokenization_spaces=True) text = text[: text.find(tokenizer.eos_token)] print(\"PREDICTION |||||| \", text)", "samples.cpu().data.numpy() for s, gt in zip(samples, gt_inputs): text = tokenizer.decode(s,", "default=False, action=\"store_true\", help=\"whether compute the adv-acc score on challenge split\")", "in trange(0, args.epoch, desc='Epoch', disable=args.local_rank not in [-1, 0]): #for", "action=\"store_true\", help=\"whether to compute perplexity of the model\") parser.add_argument('--do_verify', default=False,", "gt_inputs = trg_out.cpu().data.numpy() #samples = model.sample(fake_inputs, tabfeat, caption, highlight_idx, bert)", "type=int, default=10000, help=\"For debugging purpose\") args = parser.parse_args() if args.local_rank", "args.local_rank in [-1, 0]: if not os.path.exists(args.id): os.mkdir(args.id) tb_writer =", "idx % args.every == 0 and idx > 0: tb_writer.add_scalar(\"perplexity\",", ":].contiguous() loss = criterion(logits.view(-1, logits.shape[-1]), trg_out.view(-1)) loss = loss *", "default=False, action=\"store_true\", help=\"whether compute the adv-acc score on test split\")", "== -1: sampler = RandomSampler(dataset) else: sampler = DistributedSampler(dataset) train_dataloader", "parser.add_argument('--do_val', default=False, action=\"store_true\", help=\"whether to train or test the model\")", "device if args.local_rank not in [-1, 0]: torch.distributed.barrier() tokenizer =", "train or test the model\") parser.add_argument('--load_from', default='', type=str, help=\"whether to", "SummaryWriter import warnings from tqdm import tqdm, trange from torch.utils.data", "BLEU scores on test split\") parser.add_argument('--do_test_challenge', default=False, action=\"store_true\", help=\"whether to", "for t in batch) trg_inp, trg_out, mask, caption = batch", "logging import torch import torch.nn.functional as F import numpy as", "to train or test the model\") parser.add_argument('--learning_rate', default=2e-6, type=float, help=\"whether", "clean_up_tokenization_spaces=True) text = text[: text.find(tokenizer.eos_token)] print(\"GROUNDTRUH |||||| \",text) break avg_loss", "train or test the model\") parser.add_argument('--head', default=4, type=int, help=\"whether to", "from transformers import GPT2Config from transformers import GPT2LMHeadModel, GPT2Tokenizer, BertTokenizer", "[-1, 0]: torch.distributed.barrier() tokenizer = GPT2Tokenizer.from_pretrained(args.model) model = GPT2LMHeadModel.from_pretrained(args.model) #model", "trg_out.view(-1)) loss = loss * mask.view(-1) loss = loss.sum() /", "= 0 if args.local_rank in [-1, 0]: if args.model ==", "parser.add_argument('--decode_first_K', type=int, default=10000, help=\"For debugging purpose\") args = parser.parse_args() if", "= tokenizer.decode(s, clean_up_tokenization_spaces=True) text = text[: text.find(tokenizer.eos_token)] print(\"PREDICTION |||||| \",", "the model\") parser.add_argument('--id', default='models', type=str, help=\"specify the id of the", "default=3, type=int, help=\"whether to train or test the model\") parser.add_argument('--head',", "if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed) if __name__ == '__main__': parser", "split\") parser.add_argument('--do_ppl', default=False, action=\"store_true\", help=\"whether to compute perplexity of the", "parser.add_argument(\"--modelpath\", type=str, default=\"bert-base-uncased\", help=\"For distributed training: local_rank\") parser.add_argument('--gradient_accumulation_steps', type=int, default=5,", "torch.autograd import Variable from transformers import GPT2Config from transformers import", "tqdm import tqdm, trange from torch.utils.data import RandomSampler, SequentialSampler from", "to train or test the model\") parser.add_argument('--local_rank', default=-1, type=int, help=\"whether", "ignore_index=-1) if args.do_train: if args.local_rank in [-1, 0]: if not", "def set_seed(args): np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed) if", "parser.add_argument('--every', default=50, type=int, help=\"whether to train or test the model\")", "optim.Adam(model.parameters(), args.learning_rate) avg_loss = 0 global_step = 0 if args.local_rank", "__name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument(\"--model\", default='gpt2', type=str) parser.add_argument(\"--top_k\",", "math import sys import pandas import os import numpy import", "help=\"whether to train or test the model\") parser.add_argument('--do_rl', default=False, action=\"store_true\",", "DataLoader import * from Model import BERTGen from utils import", "the BLEU scores on challenge split\") parser.add_argument('--do_ppl', default=False, action=\"store_true\", help=\"whether", "test split\") parser.add_argument('--do_verify_challenge', default=False, action=\"store_true\", help=\"whether compute the adv-acc score", "set_seed(args): np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed) if __name__", "= RandomSampler(dataset) else: sampler = DistributedSampler(dataset) train_dataloader = DL(dataset, sampler=sampler,", "help=\"whether to train or test the model\") parser.add_argument('--id', default='models', type=str,", "default=10, type=int, help=\"whether to train or test the model\") parser.add_argument('--batch_size',", "GPT2LMHeadModel.from_pretrained(args.model) #model = nn.DataParallel(model) model.to(args.device) if args.local_rank == 0: torch.distributed.barrier()", "BertTokenizer from DataLoader import * from Model import BERTGen from", "action=\"store_true\", help=\"whether compute the adv-acc score on test split\") parser.add_argument('--do_verify_challenge',", "in zip(samples, gt_inputs): text = tokenizer.decode(s, clean_up_tokenization_spaces=True) text = text[:", "from utils import sample_sequence import torch.optim as optim import math", "as np from torch import nn from torch.autograd import Variable", "torch.cuda.manual_seed_all(args.seed) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument(\"--model\", default='gpt2',", "to train or test the model\") parser.add_argument('--dataset', default='table', type=str, help=\"whether", "distributed training: local_rank\") parser.add_argument('--gradient_accumulation_steps', type=int, default=5, help=\"accumulation steps for gradient\")", "help=\"accumulation steps for gradient\") parser.add_argument('--decode_first_K', type=int, default=10000, help=\"For debugging purpose\")", "to train or test the model\") parser.add_argument('--do_val', default=False, action=\"store_true\", help=\"whether", "* mask.view(-1) loss = loss.sum() / mask.sum() avg_loss += loss.item()", "torch.utils.tensorboard import SummaryWriter import warnings from tqdm import tqdm, trange", "= model.sample(fake_inputs, tabfeat, caption, highlight_idx, bert) samples = sample_sequence(model, 30,", "trg_out.cpu().data.numpy() #samples = model.sample(fake_inputs, tabfeat, caption, highlight_idx, bert) samples =", "tqdm, trange from torch.utils.data import RandomSampler, SequentialSampler from torch.utils.data import", "import Variable from transformers import GPT2Config from transformers import GPT2LMHeadModel," ]
[ "contextlib import contextmanager from urllib.parse import urlparse from typing import", "import PureWindowsPath, PurePosixPath from bentoml.utils.s3 import is_s3_url from bentoml.utils.gcs import", "service_name prefix, for loading from a installed PyPi module_file_path =", "files generated from BentoService#save, #save_to_dir, or the path to pip", "target module containing BentoService class from given path module_file_path =", "when module_file is just a file name, # e.g. module_file==\"iris_classifier.py\"", "artifacts model_service_class._bento_service_bundle_path = bundle_path # Set cls._version, service instance can", "supporting both local file path and s3 path Returns: bentoml.service.BentoService:", "naming conflicts sys.path.remove(bundle_path) model_service_class = module.__getattribute__(metadata[\"service_name\"]) # Set _bento_service_bundle_path, where", "tar.extractall(path=tmpdir) yield os.path.join(tmpdir, filename) def resolve_remote_bundle(func): \"\"\"Decorate a function to", "= metadata[\"module_name\"] if module_name in sys.modules: logger.warning( \"Module `%s` already", "from bundle directory instead of the user-provided # file path,", "2.0 (the \"License\"); # you may not use this file", ") fileobj = io.BytesIO() fileobj.write(response.content) fileobj.seek(0, 0) else: raise BentoMLException(f\"Saved", ") return module_file_path @resolve_remote_bundle def load_bento_service_class(bundle_path): \"\"\" Load a BentoService", "# Find and load target module containing BentoService class from", "Try load a saved bundle created from windows platform on", "package is required. You can install it with ' 'pip:", "io.BytesIO() gcs.download_blob_to_file(bundle_path, fileobj) fileobj.seek(0, 0) elif _is_http_url(bundle_path): import requests response", "Try loading without service_name prefix, for loading from a installed", "def load_bento_service_metadata(bundle_path: str) -> \"BentoServiceMetadata\": return load_saved_bundle_config(bundle_path).get_bento_service_metadata_pb() def _find_module_file(bundle_path, service_name,", "Copyright 2019 Atalaya Tech, Inc. # Licensed under the Apache", "path and s3 path Returns: bentoml.service.BentoService: a loaded BentoService instance", "BentoMLException( \"Can not locate module_file {} in saved bundle {}\".format(", "for loading from a installed PyPi module_file_path = os.path.join(bundle_path, module_file)", "bundle in path: {}\".format(bundle_path) ) def load_bento_service_metadata(bundle_path: str) -> \"BentoServiceMetadata\":", "bundle, supporting both local file path and s3 path target_dir", "BentoMLException( '\"google-cloud-storage\" package is required. You can install it with", "cls._version, service instance can access it via svc.version model_service_class._bento_service_bundle_version =", "if not os.path.isfile(module_file_path): # Try loading without service_name prefix, for", "just a file name, # e.g. module_file==\"iris_classifier.py\" module_file_path = os.path.join(bundle_path,", "BentoMLException from bentoml.saved_bundle.config import SavedBundleConfig from bentoml.saved_bundle.pip_pkg import ZIPIMPORT_DIR if", "def wrapper(bundle_path, *args): if _is_remote_path(bundle_path): with _resolve_remote_bundle_path(bundle_path) as local_bundle_path: return", "bundle created from windows platform on posix module_file_path = os.path.join(", "This needs to handle the path differences between posix and", "both local file path and s3 path Returns: bentoml.service.BentoService: a", "# Try loading without service_name prefix, for loading from a", "Where the service contents should end up. Returns: :obj:`str`: location", "windows platform: if not os.path.isfile(module_file_path): if sys.platform == \"win32\": #", "os.path.join(bundle_path, module_file) # When module_file is located in sub directory", "os.path.join(zipimport_dir, p)) module_name = metadata[\"module_name\"] if module_name in sys.modules: logger.warning(", "import contextmanager from urllib.parse import urlparse from typing import TYPE_CHECKING", "bundle_path ) ) return module_file_path @resolve_remote_bundle def load_bento_service_class(bundle_path): \"\"\" Load", "both local file path and s3 path target_dir (:obj:`str`): Where", "path or s3 path Args: bundle_path (str): The path that", ") @contextmanager def _resolve_remote_bundle_path(bundle_path): if is_s3_url(bundle_path): import boto3 parsed_url =", "load_saved_bundle_config(bundle_path) metadata = config[\"metadata\"] # Find and load target module", "SourceFileLoader(module_name, module_file_path).load_module( module_name ) # pylint:enable=deprecated-method else: raise BentoMLException(\"BentoML requires", "\"\"\"Decorate a function to handle remote bundles.\"\"\" @wraps(func) def wrapper(bundle_path,", "to avoid import naming conflicts sys.path.remove(bundle_path) model_service_class = module.__getattribute__(metadata[\"service_name\"]) #", "functools import wraps from contextlib import contextmanager from urllib.parse import", "is not None ): # Load `requirement.txt` from bundle directory", "= io.BytesIO() s3.download_fileobj(bucket_name, object_name, fileobj) fileobj.seek(0, 0) elif is_gcs_url(bundle_path): try:", "2019 Atalaya Tech, Inc. # Licensed under the Apache License,", "# This needs to handle the path differences between posix", "its artifacts model_service_class._bento_service_bundle_path = bundle_path # Set cls._version, service instance", "else: # Try load a saved bundle created from windows", "tarfile.open(mode=\"r:gz\", fileobj=fileobj) as tar: with tempfile.TemporaryDirectory() as tmpdir: filename =", "and load target module containing BentoService class from given path", "limitations under the License. import io import os import sys", "sys.version_info >= (3, 5): import importlib.util spec = importlib.util.spec_from_file_location(module_name, module_file_path)", "fileobj=fileobj) as tar: with tempfile.TemporaryDirectory() as tmpdir: filename = tar.getmembers()[0].name", "TYPE_CHECKING from pathlib import PureWindowsPath, PurePosixPath from bentoml.utils.s3 import is_s3_url", "try: return SavedBundleConfig.load(os.path.join(bundle_path, \"bentoml.yml\")) except FileNotFoundError: raise BentoMLException( \"BentoML can't", "svc.version model_service_class._bento_service_bundle_version = metadata[\"service_version\"] if ( model_service_class._env and model_service_class._env._requirements_txt_file is", ":obj:`str`: location of safe local path \"\"\" shutil.copytree(bundle_path, target_dir) @resolve_remote_bundle", "import io import os import sys import tarfile import logging", "filename) def resolve_remote_bundle(func): \"\"\"Decorate a function to handle remote bundles.\"\"\"", "import SavedBundleConfig from bentoml.saved_bundle.pip_pkg import ZIPIMPORT_DIR if TYPE_CHECKING: from bentoml.yatai.proto.repository_pb2", "'\"google-cloud-storage\" package is required. You can install it with '", "use this file except in compliance with the License. #", "PureWindowsPath(module_file).as_posix() ) if not os.path.isfile(module_file_path): raise BentoMLException( \"Can not locate", "the user-provided # file path, which may only available during", "only available during the bundle save process model_service_class._env._requirements_txt_file = os.path.join(", "tempfile import shutil from functools import wraps from contextlib import", "service_name, str(PurePosixPath(module_file)) ) if not os.path.isfile(module_file_path): module_file_path = os.path.join( bundle_path,", "os import sys import tarfile import logging import tempfile import", "BentoMLException( \"BentoML can't locate config file 'bentoml.yml'\" \" in saved", "*args): if _is_remote_path(bundle_path): with _resolve_remote_bundle_path(bundle_path) as local_bundle_path: return func(local_bundle_path, *args)", "try: from google.cloud import storage except ImportError: raise BentoMLException( '\"google-cloud-storage\"", "bundle_path, service_name, PureWindowsPath(module_file).as_posix() ) if not os.path.isfile(module_file_path): module_file_path = os.path.join(", "service from local file path or s3 path Args: bundle_path", "a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless", "\"BentoML can't locate config file 'bentoml.yml'\" \" in saved bundle", "module_file_path = os.path.join( bundle_path, service_name, PureWindowsPath(module_file).as_posix() ) if not os.path.isfile(module_file_path):", "False def _is_remote_path(bundle_path) -> bool: return isinstance(bundle_path, str) and (", "file path, which may only available during the bundle save", "parsed_url = urlparse(bundle_path) bucket_name = parsed_url.netloc object_name = parsed_url.path.lstrip('/') s3", "join full path when module_file is just a file name,", "License. # You may obtain a copy of the License", "the License. import io import os import sys import tarfile", "= parsed_url.path.lstrip('/') s3 = boto3.client('s3') fileobj = io.BytesIO() s3.download_fileobj(bucket_name, object_name,", "s3.download_fileobj(bucket_name, object_name, fileobj) fileobj.seek(0, 0) elif is_gcs_url(bundle_path): try: from google.cloud", "_resolve_remote_bundle_path(bundle_path) as local_bundle_path: return func(local_bundle_path, *args) return func(bundle_path, *args) return", "PyPi module_file_path = os.path.join(bundle_path, module_file) # When module_file is located", "module_file_path = os.path.join( bundle_path, str(PurePosixPath(module_file)) ) else: # Try load", ") # pylint:enable=deprecated-method else: raise BentoMLException(\"BentoML requires Python 3.4 and", "if response.status_code != 200: raise BentoMLException( f\"Error retrieving BentoService bundle.", "if not os.path.isfile(module_file_path): module_file_path = os.path.join( bundle_path, str(PurePosixPath(module_file)) ) else:", "BentoService instance \"\"\" svc_cls = load_bento_service_class(bundle_path) return svc_cls() @resolve_remote_bundle def", "above\") # Remove bundle_path from sys.path to avoid import naming", "avoid import naming conflicts sys.path.remove(bundle_path) model_service_class = module.__getattribute__(metadata[\"service_name\"]) # Set", "under the License is distributed on an \"AS IS\" BASIS,", "sys.path for loading extra python dependencies sys.path.insert(0, bundle_path) sys.path.insert(0, os.path.join(bundle_path,", ") if not os.path.isfile(module_file_path): module_file_path = os.path.join( bundle_path, PureWindowsPath(module_file).as_posix() )", "_bento_service_bundle_path, where BentoService will load its artifacts model_service_class._bento_service_bundle_path = bundle_path", "): # Load `requirement.txt` from bundle directory instead of the", "License for the specific language governing permissions and # limitations", "{}\".format(bundle_path) ) def load_bento_service_metadata(bundle_path: str) -> \"BentoServiceMetadata\": return load_saved_bundle_config(bundle_path).get_bento_service_metadata_pb() def", "module_file) # When module_file is located in sub directory #", "sys.platform == \"win32\": # Try load a saved bundle created", ">= (3, 3): from importlib.machinery import SourceFileLoader # pylint:disable=deprecated-method module", "and model_service_class._env._requirements_txt_file is not None ): # Load `requirement.txt` from", "s3 path target_dir (:obj:`str`): Where the service contents should end", "f\"{response.status_code}: {response.text}\" ) fileobj = io.BytesIO() fileobj.write(response.content) fileobj.seek(0, 0) else:", "urlparse from typing import TYPE_CHECKING from pathlib import PureWindowsPath, PurePosixPath", "os.path.join( bundle_path, str(PurePosixPath(module_file)) ) else: # Try load a saved", "( model_service_class._env and model_service_class._env._requirements_txt_file is not None ): # Load", "import tempfile import shutil from functools import wraps from contextlib", "path module_file_path = _find_module_file( bundle_path, metadata[\"service_name\"], metadata[\"module_file\"] ) # Prepend", "or s3 path Args: bundle_path (str): The path that contains", "at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or", "e.g. module_file==\"iris_classifier.py\" module_file_path = os.path.join(bundle_path, service_name, module_file) if not os.path.isfile(module_file_path):", "def _is_http_url(bundle_path) -> bool: try: return urlparse(bundle_path).scheme in [\"http\", \"https\"]", "to handle the path differences between posix and windows platform:", "bentoml.service.BentoService: a loaded BentoService instance \"\"\" svc_cls = load_bento_service_class(bundle_path) return", "contents should end up. Returns: :obj:`str`: location of safe local", "and s3 path target_dir (:obj:`str`): Where the service contents should", ":param bundle_path: A path to Bento files generated from BentoService#save,", "permissions and # limitations under the License. import io import", "0) elif is_gcs_url(bundle_path): try: from google.cloud import storage except ImportError:", "to pip installed BentoService directory :return: BentoService class \"\"\" config", "in compliance with the License. # You may obtain a", "module_file_path = os.path.join(bundle_path, service_name, module_file) if not os.path.isfile(module_file_path): # Try", "with ' 'pip: \"pip install google-cloud-storage\"' ) gcs = storage.Client()", "if _is_remote_path(bundle_path): with _resolve_remote_bundle_path(bundle_path) as local_bundle_path: return func(local_bundle_path, *args) return", "is_s3_url(bundle_path) or is_gcs_url(bundle_path) or _is_http_url(bundle_path) ) @contextmanager def _resolve_remote_bundle_path(bundle_path): if", "software # distributed under the License is distributed on an", "directory # e.g. module_file==\"foo/bar/iris_classifier.py\" # This needs to handle the", "module_file): # Simply join full path when module_file is just", "saved bundle in path: {}\".format(bundle_path) ) def load_bento_service_metadata(bundle_path: str) ->", "def load_saved_bundle_config(bundle_path) -> \"SavedBundleConfig\": try: return SavedBundleConfig.load(os.path.join(bundle_path, \"bentoml.yml\")) except FileNotFoundError:", "full path when module_file is just a file name, #", "and windows platform: if not os.path.isfile(module_file_path): if sys.platform == \"win32\":", "local path \"\"\" shutil.copytree(bundle_path, target_dir) @resolve_remote_bundle def load_from_dir(bundle_path): \"\"\"Load bento", "governing permissions and # limitations under the License. import io", "def _is_remote_path(bundle_path) -> bool: return isinstance(bundle_path, str) and ( is_s3_url(bundle_path)", "local_bundle_path: return func(local_bundle_path, *args) return func(bundle_path, *args) return wrapper @resolve_remote_bundle", "`requirement.txt` from bundle directory instead of the user-provided # file", "the service contents should end up. Returns: :obj:`str`: location of", "BentoService directory :return: BentoService class \"\"\" config = load_saved_bundle_config(bundle_path) metadata", "shutil.copytree(bundle_path, target_dir) @resolve_remote_bundle def load_from_dir(bundle_path): \"\"\"Load bento service from local", "os.path.join( bundle_path, service_name, str(PurePosixPath(module_file)) ) if not os.path.isfile(module_file_path): module_file_path =", "class from given path module_file_path = _find_module_file( bundle_path, metadata[\"service_name\"], metadata[\"module_file\"]", "p)) module_name = metadata[\"module_name\"] if module_name in sys.modules: logger.warning( \"Module", "is_gcs_url(bundle_path): try: from google.cloud import storage except ImportError: raise BentoMLException(", "\"bentoml.yml\")) except FileNotFoundError: raise BentoMLException( \"BentoML can't locate config file", "bundle_path, \"requirements.txt\" ) return model_service_class @resolve_remote_bundle def safe_retrieve(bundle_path: str, target_dir:", "import os import sys import tarfile import logging import tempfile", "\"requirements.txt\" ) return model_service_class @resolve_remote_bundle def safe_retrieve(bundle_path: str, target_dir: str):", "a saved bundle created from posix platform on windows module_file_path", "module_file_path = os.path.join( bundle_path, service_name, str(PurePosixPath(module_file)) ) if not os.path.isfile(module_file_path):", "SavedBundleConfig from bentoml.saved_bundle.pip_pkg import ZIPIMPORT_DIR if TYPE_CHECKING: from bentoml.yatai.proto.repository_pb2 import", "safe_retrieve(bundle_path: str, target_dir: str): \"\"\"Safely retrieve bento service to local", "logging import tempfile import shutil from functools import wraps from", "import is_gcs_url from bentoml.exceptions import BentoMLException from bentoml.saved_bundle.config import SavedBundleConfig", "bool: try: return urlparse(bundle_path).scheme in [\"http\", \"https\"] except ValueError: return", "else: raise BentoMLException(\"BentoML requires Python 3.4 and above\") # Remove", "-> bool: try: return urlparse(bundle_path).scheme in [\"http\", \"https\"] except ValueError:", "logger.debug('adding %s to sys.path', p) sys.path.insert(0, os.path.join(zipimport_dir, p)) module_name =", "= load_bento_service_class(bundle_path) return svc_cls() @resolve_remote_bundle def load_bento_service_api(bundle_path, api_name=None): bento_service =", "import TYPE_CHECKING from pathlib import PureWindowsPath, PurePosixPath from bentoml.utils.s3 import", "google-cloud-storage\"' ) gcs = storage.Client() fileobj = io.BytesIO() gcs.download_blob_to_file(bundle_path, fileobj)", "os.path.isfile(module_file_path): # Try loading without service_name prefix, for loading from", "spec.loader.exec_module(module) elif sys.version_info >= (3, 3): from importlib.machinery import SourceFileLoader", "a installed PyPi module_file_path = os.path.join(bundle_path, module_file) # When module_file", "ZIPIMPORT_DIR) if os.path.exists(zipimport_dir): for p in os.listdir(zipimport_dir): logger.debug('adding %s to", "def load_bento_service_class(bundle_path): \"\"\" Load a BentoService class from saved bundle", "a function to handle remote bundles.\"\"\" @wraps(func) def wrapper(bundle_path, *args):", "bundle path: '{bundle_path}' is not supported\") with tarfile.open(mode=\"r:gz\", fileobj=fileobj) as", "as tar: with tempfile.TemporaryDirectory() as tmpdir: filename = tar.getmembers()[0].name tar.extractall(path=tmpdir)", "import importlib.util spec = importlib.util.spec_from_file_location(module_name, module_file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module)", "model_service_class._env._requirements_txt_file is not None ): # Load `requirement.txt` from bundle", "load_saved_bundle_config(bundle_path) -> \"SavedBundleConfig\": try: return SavedBundleConfig.load(os.path.join(bundle_path, \"bentoml.yml\")) except FileNotFoundError: raise", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "bundle_path) sys.path.insert(0, os.path.join(bundle_path, metadata[\"service_name\"])) # Include zipimport modules zipimport_dir =", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "\"Module `%s` already loaded, using existing imported module.\", module_name )", "import sys import tarfile import logging import tempfile import shutil", "raise BentoMLException( '\"google-cloud-storage\" package is required. You can install it", "Args: bundle_path (:obj:`str`): The path that contains saved BentoService bundle,", "os.path.join(tmpdir, filename) def resolve_remote_bundle(func): \"\"\"Decorate a function to handle remote", "the License. # You may obtain a copy of the", "for the specific language governing permissions and # limitations under", "ZIPIMPORT_DIR if TYPE_CHECKING: from bentoml.yatai.proto.repository_pb2 import BentoServiceMetadata logger = logging.getLogger(__name__)", "module_file) if not os.path.isfile(module_file_path): # Try loading without service_name prefix,", "= os.path.join( bundle_path, service_name, str(PurePosixPath(module_file)) ) if not os.path.isfile(module_file_path): module_file_path", "import ZIPIMPORT_DIR if TYPE_CHECKING: from bentoml.yatai.proto.repository_pb2 import BentoServiceMetadata logger =", "if not os.path.isfile(module_file_path): raise BentoMLException( \"Can not locate module_file {}", "bento service from local file path or s3 path Args:", "to in writing, software # distributed under the License is", "= os.path.join( bundle_path, service_name, PureWindowsPath(module_file).as_posix() ) if not os.path.isfile(module_file_path): module_file_path", "it with ' 'pip: \"pip install google-cloud-storage\"' ) gcs =", "bundle_path, PureWindowsPath(module_file).as_posix() ) if not os.path.isfile(module_file_path): raise BentoMLException( \"Can not", "modules zipimport_dir = os.path.join(bundle_path, metadata[\"service_name\"], ZIPIMPORT_DIR) if os.path.exists(zipimport_dir): for p", "# See the License for the specific language governing permissions", "from bentoml.exceptions import BentoMLException from bentoml.saved_bundle.config import SavedBundleConfig from bentoml.saved_bundle.pip_pkg", "bool: return isinstance(bundle_path, str) and ( is_s3_url(bundle_path) or is_gcs_url(bundle_path) or", "from a installed PyPi module_file_path = os.path.join(bundle_path, module_file) # When", "requires Python 3.4 and above\") # Remove bundle_path from sys.path", "can access it via svc.version model_service_class._bento_service_bundle_version = metadata[\"service_version\"] if (", "load a saved bundle created from posix platform on windows", "= requests.get(bundle_path) if response.status_code != 200: raise BentoMLException( f\"Error retrieving", "\"\"\" shutil.copytree(bundle_path, target_dir) @resolve_remote_bundle def load_from_dir(bundle_path): \"\"\"Load bento service from", "using existing imported module.\", module_name ) module = sys.modules[module_name] elif", "Atalaya Tech, Inc. # Licensed under the Apache License, Version", "= metadata[\"service_version\"] if ( model_service_class._env and model_service_class._env._requirements_txt_file is not None", "BentoService bundle, supporting both local file path and s3 path", "= io.BytesIO() fileobj.write(response.content) fileobj.seek(0, 0) else: raise BentoMLException(f\"Saved bundle path:", "or agreed to in writing, software # distributed under the", "sys.modules: logger.warning( \"Module `%s` already loaded, using existing imported module.\",", "required by applicable law or agreed to in writing, software", "from BentoService#save, #save_to_dir, or the path to pip installed BentoService", "module_file_path = _find_module_file( bundle_path, metadata[\"service_name\"], metadata[\"module_file\"] ) # Prepend bundle_path", "Load `requirement.txt` from bundle directory instead of the user-provided #", "available during the bundle save process model_service_class._env._requirements_txt_file = os.path.join( bundle_path,", "model_service_class._env._requirements_txt_file = os.path.join( bundle_path, \"requirements.txt\" ) return model_service_class @resolve_remote_bundle def", "elif sys.version_info >= (3, 3): from importlib.machinery import SourceFileLoader #", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "spec = importlib.util.spec_from_file_location(module_name, module_file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) elif sys.version_info", "with the License. # You may obtain a copy of", ") return model_service_class @resolve_remote_bundle def safe_retrieve(bundle_path: str, target_dir: str): \"\"\"Safely", "@resolve_remote_bundle def load_bento_service_class(bundle_path): \"\"\" Load a BentoService class from saved", "windows module_file_path = os.path.join( bundle_path, service_name, str(PurePosixPath(module_file)) ) if not", "module.__getattribute__(metadata[\"service_name\"]) # Set _bento_service_bundle_path, where BentoService will load its artifacts", "os.path.exists(zipimport_dir): for p in os.listdir(zipimport_dir): logger.debug('adding %s to sys.path', p)", "not supported\") with tarfile.open(mode=\"r:gz\", fileobj=fileobj) as tar: with tempfile.TemporaryDirectory() as", "return func(local_bundle_path, *args) return func(bundle_path, *args) return wrapper @resolve_remote_bundle def", "tempfile.TemporaryDirectory() as tmpdir: filename = tar.getmembers()[0].name tar.extractall(path=tmpdir) yield os.path.join(tmpdir, filename)", "You can install it with ' 'pip: \"pip install google-cloud-storage\"'", "_is_http_url(bundle_path) ) @contextmanager def _resolve_remote_bundle_path(bundle_path): if is_s3_url(bundle_path): import boto3 parsed_url", "in sub directory # e.g. module_file==\"foo/bar/iris_classifier.py\" # This needs to", "response = requests.get(bundle_path) if response.status_code != 200: raise BentoMLException( f\"Error", "location of safe local path \"\"\" shutil.copytree(bundle_path, target_dir) @resolve_remote_bundle def", "in saved bundle {}\".format( module_file, bundle_path ) ) return module_file_path", "via svc.version model_service_class._bento_service_bundle_version = metadata[\"service_version\"] if ( model_service_class._env and model_service_class._env._requirements_txt_file", "as tmpdir: filename = tar.getmembers()[0].name tar.extractall(path=tmpdir) yield os.path.join(tmpdir, filename) def", "BentoService#save, #save_to_dir, or the path to pip installed BentoService directory", "local path Args: bundle_path (:obj:`str`): The path that contains saved", "object_name = parsed_url.path.lstrip('/') s3 = boto3.client('s3') fileobj = io.BytesIO() s3.download_fileobj(bucket_name,", "compliance with the License. # You may obtain a copy", "agreed to in writing, software # distributed under the License", "import shutil from functools import wraps from contextlib import contextmanager", "that contains saved BentoService bundle, supporting both local file path", "f\"Error retrieving BentoService bundle. \" f\"{response.status_code}: {response.text}\" ) fileobj =", "distributed under the License is distributed on an \"AS IS\"", "posix module_file_path = os.path.join( bundle_path, service_name, PureWindowsPath(module_file).as_posix() ) if not", "path target_dir (:obj:`str`): Where the service contents should end up.", "load_bento_service_class(bundle_path) return svc_cls() @resolve_remote_bundle def load_bento_service_api(bundle_path, api_name=None): bento_service = load_from_dir(bundle_path)", "except ValueError: return False def _is_remote_path(bundle_path) -> bool: return isinstance(bundle_path,", "service to local path Args: bundle_path (:obj:`str`): The path that", "BentoService class from given path module_file_path = _find_module_file( bundle_path, metadata[\"service_name\"],", "tar.getmembers()[0].name tar.extractall(path=tmpdir) yield os.path.join(tmpdir, filename) def resolve_remote_bundle(func): \"\"\"Decorate a function", "path to pip installed BentoService directory :return: BentoService class \"\"\"", "load its artifacts model_service_class._bento_service_bundle_path = bundle_path # Set cls._version, service", "ValueError: return False def _is_remote_path(bundle_path) -> bool: return isinstance(bundle_path, str)", "return isinstance(bundle_path, str) and ( is_s3_url(bundle_path) or is_gcs_url(bundle_path) or _is_http_url(bundle_path)", "express or implied. # See the License for the specific", "module = sys.modules[module_name] elif sys.version_info >= (3, 5): import importlib.util", "except in compliance with the License. # You may obtain", ":return: BentoService class \"\"\" config = load_saved_bundle_config(bundle_path) metadata = config[\"metadata\"]", "isinstance(bundle_path, str) and ( is_s3_url(bundle_path) or is_gcs_url(bundle_path) or _is_http_url(bundle_path) )", "raise BentoMLException( f\"Error retrieving BentoService bundle. \" f\"{response.status_code}: {response.text}\" )", "= _find_module_file( bundle_path, metadata[\"service_name\"], metadata[\"module_file\"] ) # Prepend bundle_path to", ") if not os.path.isfile(module_file_path): raise BentoMLException( \"Can not locate module_file", "import boto3 parsed_url = urlparse(bundle_path) bucket_name = parsed_url.netloc object_name =", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "bundle_path to sys.path for loading extra python dependencies sys.path.insert(0, bundle_path)", "bundle_path, service_name, str(PurePosixPath(module_file)) ) if not os.path.isfile(module_file_path): module_file_path = os.path.join(", "not use this file except in compliance with the License.", "for loading extra python dependencies sys.path.insert(0, bundle_path) sys.path.insert(0, os.path.join(bundle_path, metadata[\"service_name\"]))", "saved bundle {}\".format( module_file, bundle_path ) ) return module_file_path @resolve_remote_bundle", "os.listdir(zipimport_dir): logger.debug('adding %s to sys.path', p) sys.path.insert(0, os.path.join(zipimport_dir, p)) module_name", "writing, software # distributed under the License is distributed on", "# Simply join full path when module_file is just a", "import urlparse from typing import TYPE_CHECKING from pathlib import PureWindowsPath,", "not os.path.isfile(module_file_path): module_file_path = os.path.join( bundle_path, PureWindowsPath(module_file).as_posix() ) if not", "not None ): # Load `requirement.txt` from bundle directory instead", "you may not use this file except in compliance with", "to sys.path for loading extra python dependencies sys.path.insert(0, bundle_path) sys.path.insert(0,", "str) and ( is_s3_url(bundle_path) or is_gcs_url(bundle_path) or _is_http_url(bundle_path) ) @contextmanager", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "path to Bento files generated from BentoService#save, #save_to_dir, or the", "def load_from_dir(bundle_path): \"\"\"Load bento service from local file path or", "handle the path differences between posix and windows platform: if", "platform: if not os.path.isfile(module_file_path): if sys.platform == \"win32\": # Try", "file path or s3 path Args: bundle_path (str): The path", "if os.path.exists(zipimport_dir): for p in os.listdir(zipimport_dir): logger.debug('adding %s to sys.path',", "s3 = boto3.client('s3') fileobj = io.BytesIO() s3.download_fileobj(bucket_name, object_name, fileobj) fileobj.seek(0,", "module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) elif sys.version_info >= (3, 3): from", "import SourceFileLoader # pylint:disable=deprecated-method module = SourceFileLoader(module_name, module_file_path).load_module( module_name )", "return urlparse(bundle_path).scheme in [\"http\", \"https\"] except ValueError: return False def", "return False def _is_remote_path(bundle_path) -> bool: return isinstance(bundle_path, str) and", "loading from a installed PyPi module_file_path = os.path.join(bundle_path, module_file) #", "directory :return: BentoService class \"\"\" config = load_saved_bundle_config(bundle_path) metadata =", "except ImportError: raise BentoMLException( '\"google-cloud-storage\" package is required. You can", "pathlib import PureWindowsPath, PurePosixPath from bentoml.utils.s3 import is_s3_url from bentoml.utils.gcs", "located in sub directory # e.g. module_file==\"foo/bar/iris_classifier.py\" # This needs", "# Set _bento_service_bundle_path, where BentoService will load its artifacts model_service_class._bento_service_bundle_path", "CONDITIONS OF ANY KIND, either express or implied. # See", "elif sys.version_info >= (3, 5): import importlib.util spec = importlib.util.spec_from_file_location(module_name,", "path that contains saved BentoService bundle, supporting both local file", "A path to Bento files generated from BentoService#save, #save_to_dir, or", "BentoMLException(f\"Saved bundle path: '{bundle_path}' is not supported\") with tarfile.open(mode=\"r:gz\", fileobj=fileobj)", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "from bentoml.yatai.proto.repository_pb2 import BentoServiceMetadata logger = logging.getLogger(__name__) def _is_http_url(bundle_path) ->", "bundle_path from sys.path to avoid import naming conflicts sys.path.remove(bundle_path) model_service_class", "or _is_http_url(bundle_path) ) @contextmanager def _resolve_remote_bundle_path(bundle_path): if is_s3_url(bundle_path): import boto3", "os.path.isfile(module_file_path): module_file_path = os.path.join( bundle_path, str(PurePosixPath(module_file)) ) else: # Try", "PureWindowsPath, PurePosixPath from bentoml.utils.s3 import is_s3_url from bentoml.utils.gcs import is_gcs_url", "class \"\"\" config = load_saved_bundle_config(bundle_path) metadata = config[\"metadata\"] # Find", "bundles.\"\"\" @wraps(func) def wrapper(bundle_path, *args): if _is_remote_path(bundle_path): with _resolve_remote_bundle_path(bundle_path) as", "http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to", "sys.path.insert(0, os.path.join(zipimport_dir, p)) module_name = metadata[\"module_name\"] if module_name in sys.modules:", "= tar.getmembers()[0].name tar.extractall(path=tmpdir) yield os.path.join(tmpdir, filename) def resolve_remote_bundle(func): \"\"\"Decorate a", "retrieving BentoService bundle. \" f\"{response.status_code}: {response.text}\" ) fileobj = io.BytesIO()", "installed BentoService directory :return: BentoService class \"\"\" config = load_saved_bundle_config(bundle_path)", "dependencies sys.path.insert(0, bundle_path) sys.path.insert(0, os.path.join(bundle_path, metadata[\"service_name\"])) # Include zipimport modules", "fileobj.write(response.content) fileobj.seek(0, 0) else: raise BentoMLException(f\"Saved bundle path: '{bundle_path}' is", "model_service_class._env and model_service_class._env._requirements_txt_file is not None ): # Load `requirement.txt`", "loaded, using existing imported module.\", module_name ) module = sys.modules[module_name]", "metadata[\"service_version\"] if ( model_service_class._env and model_service_class._env._requirements_txt_file is not None ):", "not os.path.isfile(module_file_path): # Try loading without service_name prefix, for loading", "local file path and s3 path target_dir (:obj:`str`): Where the", "{}\".format( module_file, bundle_path ) ) return module_file_path @resolve_remote_bundle def load_bento_service_class(bundle_path):", "# Try load a saved bundle created from posix platform", "of the user-provided # file path, which may only available", "wrapper(bundle_path, *args): if _is_remote_path(bundle_path): with _resolve_remote_bundle_path(bundle_path) as local_bundle_path: return func(local_bundle_path,", "OR CONDITIONS OF ANY KIND, either express or implied. #", "saved bundle created from windows platform on posix module_file_path =", "the License is distributed on an \"AS IS\" BASIS, #", "module_file==\"foo/bar/iris_classifier.py\" # This needs to handle the path differences between", "python dependencies sys.path.insert(0, bundle_path) sys.path.insert(0, os.path.join(bundle_path, metadata[\"service_name\"])) # Include zipimport", "sys.version_info >= (3, 3): from importlib.machinery import SourceFileLoader # pylint:disable=deprecated-method", "%s to sys.path', p) sys.path.insert(0, os.path.join(zipimport_dir, p)) module_name = metadata[\"module_name\"]", "a loaded BentoService instance \"\"\" svc_cls = load_bento_service_class(bundle_path) return svc_cls()", "= os.path.join( bundle_path, str(PurePosixPath(module_file)) ) else: # Try load a", "Inc. # Licensed under the Apache License, Version 2.0 (the", "to sys.path', p) sys.path.insert(0, os.path.join(zipimport_dir, p)) module_name = metadata[\"module_name\"] if", "# file path, which may only available during the bundle", "with tarfile.open(mode=\"r:gz\", fileobj=fileobj) as tar: with tempfile.TemporaryDirectory() as tmpdir: filename", "path: {}\".format(bundle_path) ) def load_bento_service_metadata(bundle_path: str) -> \"BentoServiceMetadata\": return load_saved_bundle_config(bundle_path).get_bento_service_metadata_pb()", "return wrapper @resolve_remote_bundle def load_saved_bundle_config(bundle_path) -> \"SavedBundleConfig\": try: return SavedBundleConfig.load(os.path.join(bundle_path,", "model_service_class = module.__getattribute__(metadata[\"service_name\"]) # Set _bento_service_bundle_path, where BentoService will load", "of safe local path \"\"\" shutil.copytree(bundle_path, target_dir) @resolve_remote_bundle def load_from_dir(bundle_path):", "PureWindowsPath(module_file).as_posix() ) if not os.path.isfile(module_file_path): module_file_path = os.path.join( bundle_path, PureWindowsPath(module_file).as_posix()", "Tech, Inc. # Licensed under the Apache License, Version 2.0", "where BentoService will load its artifacts model_service_class._bento_service_bundle_path = bundle_path #", "from bentoml.saved_bundle.pip_pkg import ZIPIMPORT_DIR if TYPE_CHECKING: from bentoml.yatai.proto.repository_pb2 import BentoServiceMetadata", "os.path.join(bundle_path, service_name, module_file) if not os.path.isfile(module_file_path): # Try loading without", "raise BentoMLException( \"Can not locate module_file {} in saved bundle", "raise BentoMLException( \"BentoML can't locate config file 'bentoml.yml'\" \" in", "func(local_bundle_path, *args) return func(bundle_path, *args) return wrapper @resolve_remote_bundle def load_saved_bundle_config(bundle_path)", "law or agreed to in writing, software # distributed under", "*args) return func(bundle_path, *args) return wrapper @resolve_remote_bundle def load_saved_bundle_config(bundle_path) ->", "contextmanager from urllib.parse import urlparse from typing import TYPE_CHECKING from", "can install it with ' 'pip: \"pip install google-cloud-storage\"' )", "str) -> \"BentoServiceMetadata\": return load_saved_bundle_config(bundle_path).get_bento_service_metadata_pb() def _find_module_file(bundle_path, service_name, module_file): #", "{response.text}\" ) fileobj = io.BytesIO() fileobj.write(response.content) fileobj.seek(0, 0) else: raise", "shutil from functools import wraps from contextlib import contextmanager from", "os.path.join( bundle_path, service_name, PureWindowsPath(module_file).as_posix() ) if not os.path.isfile(module_file_path): module_file_path =", "supporting both local file path and s3 path target_dir (:obj:`str`):", "containing BentoService class from given path module_file_path = _find_module_file( bundle_path,", "saved bundle created from posix platform on windows module_file_path =", "raise BentoMLException(\"BentoML requires Python 3.4 and above\") # Remove bundle_path", "required. You can install it with ' 'pip: \"pip install", "boto3 parsed_url = urlparse(bundle_path) bucket_name = parsed_url.netloc object_name = parsed_url.path.lstrip('/')", "gcs = storage.Client() fileobj = io.BytesIO() gcs.download_blob_to_file(bundle_path, fileobj) fileobj.seek(0, 0)", "to Bento files generated from BentoService#save, #save_to_dir, or the path", "os.path.join( bundle_path, PureWindowsPath(module_file).as_posix() ) if not os.path.isfile(module_file_path): raise BentoMLException( \"Can", "\"\"\" config = load_saved_bundle_config(bundle_path) metadata = config[\"metadata\"] # Find and", "from urllib.parse import urlparse from typing import TYPE_CHECKING from pathlib", "importlib.machinery import SourceFileLoader # pylint:disable=deprecated-method module = SourceFileLoader(module_name, module_file_path).load_module( module_name", "existing imported module.\", module_name ) module = sys.modules[module_name] elif sys.version_info", "License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law", "name, # e.g. module_file==\"iris_classifier.py\" module_file_path = os.path.join(bundle_path, service_name, module_file) if", ") if not os.path.isfile(module_file_path): module_file_path = os.path.join( bundle_path, str(PurePosixPath(module_file)) )", "bundle_path, str(PurePosixPath(module_file)) ) else: # Try load a saved bundle", "installed PyPi module_file_path = os.path.join(bundle_path, module_file) # When module_file is", "module_file_path @resolve_remote_bundle def load_bento_service_class(bundle_path): \"\"\" Load a BentoService class from", "# Load `requirement.txt` from bundle directory instead of the user-provided", "if sys.platform == \"win32\": # Try load a saved bundle", "str): \"\"\"Safely retrieve bento service to local path Args: bundle_path", "created from windows platform on posix module_file_path = os.path.join( bundle_path,", "Prepend bundle_path to sys.path for loading extra python dependencies sys.path.insert(0,", "import tarfile import logging import tempfile import shutil from functools", "module_file, bundle_path ) ) return module_file_path @resolve_remote_bundle def load_bento_service_class(bundle_path): \"\"\"", "module_file is located in sub directory # e.g. module_file==\"foo/bar/iris_classifier.py\" #", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "(str): The path that contains saved BentoService bundle, supporting both", "io.BytesIO() fileobj.write(response.content) fileobj.seek(0, 0) else: raise BentoMLException(f\"Saved bundle path: '{bundle_path}'", "model_service_class._bento_service_bundle_version = metadata[\"service_version\"] if ( model_service_class._env and model_service_class._env._requirements_txt_file is not", "between posix and windows platform: if not os.path.isfile(module_file_path): if sys.platform", "bentoml.exceptions import BentoMLException from bentoml.saved_bundle.config import SavedBundleConfig from bentoml.saved_bundle.pip_pkg import", "not os.path.isfile(module_file_path): if sys.platform == \"win32\": # Try load a", "from given path module_file_path = _find_module_file( bundle_path, metadata[\"service_name\"], metadata[\"module_file\"] )", "may not use this file except in compliance with the", "svc_cls = load_bento_service_class(bundle_path) return svc_cls() @resolve_remote_bundle def load_bento_service_api(bundle_path, api_name=None): bento_service", "is_gcs_url(bundle_path) or _is_http_url(bundle_path) ) @contextmanager def _resolve_remote_bundle_path(bundle_path): if is_s3_url(bundle_path): import", "may only available during the bundle save process model_service_class._env._requirements_txt_file =", "bundle_path (str): The path that contains saved BentoService bundle, supporting", "[\"http\", \"https\"] except ValueError: return False def _is_remote_path(bundle_path) -> bool:", "config = load_saved_bundle_config(bundle_path) metadata = config[\"metadata\"] # Find and load", "= os.path.join( bundle_path, PureWindowsPath(module_file).as_posix() ) if not os.path.isfile(module_file_path): raise BentoMLException(", "bundle_path, metadata[\"service_name\"], metadata[\"module_file\"] ) # Prepend bundle_path to sys.path for", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", ") gcs = storage.Client() fileobj = io.BytesIO() gcs.download_blob_to_file(bundle_path, fileobj) fileobj.seek(0,", "= boto3.client('s3') fileobj = io.BytesIO() s3.download_fileobj(bucket_name, object_name, fileobj) fileobj.seek(0, 0)", "service_name, module_file) if not os.path.isfile(module_file_path): # Try loading without service_name", "this file except in compliance with the License. # You", "from posix platform on windows module_file_path = os.path.join( bundle_path, service_name,", "logging.getLogger(__name__) def _is_http_url(bundle_path) -> bool: try: return urlparse(bundle_path).scheme in [\"http\",", "wraps from contextlib import contextmanager from urllib.parse import urlparse from", "'bentoml.yml'\" \" in saved bundle in path: {}\".format(bundle_path) ) def", "bundle, supporting both local file path and s3 path Returns:", "\"https\"] except ValueError: return False def _is_remote_path(bundle_path) -> bool: return", "a BentoService class from saved bundle in given path :param", "up. Returns: :obj:`str`: location of safe local path \"\"\" shutil.copytree(bundle_path,", "s3 path Args: bundle_path (str): The path that contains saved", "Bento files generated from BentoService#save, #save_to_dir, or the path to", "metadata = config[\"metadata\"] # Find and load target module containing", "is_gcs_url from bentoml.exceptions import BentoMLException from bentoml.saved_bundle.config import SavedBundleConfig from", "_find_module_file( bundle_path, metadata[\"service_name\"], metadata[\"module_file\"] ) # Prepend bundle_path to sys.path", "given path module_file_path = _find_module_file( bundle_path, metadata[\"service_name\"], metadata[\"module_file\"] ) #", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "import is_s3_url from bentoml.utils.gcs import is_gcs_url from bentoml.exceptions import BentoMLException", "\"\"\" svc_cls = load_bento_service_class(bundle_path) return svc_cls() @resolve_remote_bundle def load_bento_service_api(bundle_path, api_name=None):", "io.BytesIO() s3.download_fileobj(bucket_name, object_name, fileobj) fileobj.seek(0, 0) elif is_gcs_url(bundle_path): try: from", "already loaded, using existing imported module.\", module_name ) module =", "it via svc.version model_service_class._bento_service_bundle_version = metadata[\"service_version\"] if ( model_service_class._env and", "which may only available during the bundle save process model_service_class._env._requirements_txt_file", "in os.listdir(zipimport_dir): logger.debug('adding %s to sys.path', p) sys.path.insert(0, os.path.join(zipimport_dir, p))", "bundle created from posix platform on windows module_file_path = os.path.join(", "p in os.listdir(zipimport_dir): logger.debug('adding %s to sys.path', p) sys.path.insert(0, os.path.join(zipimport_dir,", "from bentoml.utils.s3 import is_s3_url from bentoml.utils.gcs import is_gcs_url from bentoml.exceptions", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "loading without service_name prefix, for loading from a installed PyPi", "return SavedBundleConfig.load(os.path.join(bundle_path, \"bentoml.yml\")) except FileNotFoundError: raise BentoMLException( \"BentoML can't locate", "When module_file is located in sub directory # e.g. module_file==\"foo/bar/iris_classifier.py\"", "<gh_stars>1000+ # Copyright 2019 Atalaya Tech, Inc. # Licensed under", "'pip: \"pip install google-cloud-storage\"' ) gcs = storage.Client() fileobj =", "module_name in sys.modules: logger.warning( \"Module `%s` already loaded, using existing", "except FileNotFoundError: raise BentoMLException( \"BentoML can't locate config file 'bentoml.yml'\"", "== \"win32\": # Try load a saved bundle created from", "Python 3.4 and above\") # Remove bundle_path from sys.path to", "return model_service_class @resolve_remote_bundle def safe_retrieve(bundle_path: str, target_dir: str): \"\"\"Safely retrieve", "not os.path.isfile(module_file_path): raise BentoMLException( \"Can not locate module_file {} in", "created from posix platform on windows module_file_path = os.path.join( bundle_path,", "local file path or s3 path Args: bundle_path (str): The", "#save_to_dir, or the path to pip installed BentoService directory :return:", "of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by", "= urlparse(bundle_path) bucket_name = parsed_url.netloc object_name = parsed_url.path.lstrip('/') s3 =", "# When module_file is located in sub directory # e.g.", "metadata[\"service_name\"])) # Include zipimport modules zipimport_dir = os.path.join(bundle_path, metadata[\"service_name\"], ZIPIMPORT_DIR)", "License. import io import os import sys import tarfile import", "language governing permissions and # limitations under the License. import", "sys.path.insert(0, os.path.join(bundle_path, metadata[\"service_name\"])) # Include zipimport modules zipimport_dir = os.path.join(bundle_path,", "( is_s3_url(bundle_path) or is_gcs_url(bundle_path) or _is_http_url(bundle_path) ) @contextmanager def _resolve_remote_bundle_path(bundle_path):", "in path: {}\".format(bundle_path) ) def load_bento_service_metadata(bundle_path: str) -> \"BentoServiceMetadata\": return", "pip installed BentoService directory :return: BentoService class \"\"\" config =", "= module.__getattribute__(metadata[\"service_name\"]) # Set _bento_service_bundle_path, where BentoService will load its", "the path to pip installed BentoService directory :return: BentoService class", "local file path and s3 path Returns: bentoml.service.BentoService: a loaded", "save process model_service_class._env._requirements_txt_file = os.path.join( bundle_path, \"requirements.txt\" ) return model_service_class", "process model_service_class._env._requirements_txt_file = os.path.join( bundle_path, \"requirements.txt\" ) return model_service_class @resolve_remote_bundle", "return func(bundle_path, *args) return wrapper @resolve_remote_bundle def load_saved_bundle_config(bundle_path) -> \"SavedBundleConfig\":", "service instance can access it via svc.version model_service_class._bento_service_bundle_version = metadata[\"service_version\"]", "from bentoml.saved_bundle.config import SavedBundleConfig from bentoml.saved_bundle.pip_pkg import ZIPIMPORT_DIR if TYPE_CHECKING:", "to handle remote bundles.\"\"\" @wraps(func) def wrapper(bundle_path, *args): if _is_remote_path(bundle_path):", "is just a file name, # e.g. module_file==\"iris_classifier.py\" module_file_path =", "windows platform on posix module_file_path = os.path.join( bundle_path, service_name, PureWindowsPath(module_file).as_posix()", "instead of the user-provided # file path, which may only", "\"win32\": # Try load a saved bundle created from posix", "for p in os.listdir(zipimport_dir): logger.debug('adding %s to sys.path', p) sys.path.insert(0,", "target_dir) @resolve_remote_bundle def load_from_dir(bundle_path): \"\"\"Load bento service from local file", "Returns: bentoml.service.BentoService: a loaded BentoService instance \"\"\" svc_cls = load_bento_service_class(bundle_path)", "metadata[\"service_name\"], metadata[\"module_file\"] ) # Prepend bundle_path to sys.path for loading", "or implied. # See the License for the specific language", "`%s` already loaded, using existing imported module.\", module_name ) module", "Simply join full path when module_file is just a file", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "with _resolve_remote_bundle_path(bundle_path) as local_bundle_path: return func(local_bundle_path, *args) return func(bundle_path, *args)", "file path and s3 path Returns: bentoml.service.BentoService: a loaded BentoService", "= parsed_url.netloc object_name = parsed_url.path.lstrip('/') s3 = boto3.client('s3') fileobj =", "remote bundles.\"\"\" @wraps(func) def wrapper(bundle_path, *args): if _is_remote_path(bundle_path): with _resolve_remote_bundle_path(bundle_path)", "module containing BentoService class from given path module_file_path = _find_module_file(", "loaded BentoService instance \"\"\" svc_cls = load_bento_service_class(bundle_path) return svc_cls() @resolve_remote_bundle", "import naming conflicts sys.path.remove(bundle_path) model_service_class = module.__getattribute__(metadata[\"service_name\"]) # Set _bento_service_bundle_path,", "saved bundle in given path :param bundle_path: A path to", "-> \"SavedBundleConfig\": try: return SavedBundleConfig.load(os.path.join(bundle_path, \"bentoml.yml\")) except FileNotFoundError: raise BentoMLException(", "\"BentoServiceMetadata\": return load_saved_bundle_config(bundle_path).get_bento_service_metadata_pb() def _find_module_file(bundle_path, service_name, module_file): # Simply join", "= sys.modules[module_name] elif sys.version_info >= (3, 5): import importlib.util spec", "# Copyright 2019 Atalaya Tech, Inc. # Licensed under the", "if ( model_service_class._env and model_service_class._env._requirements_txt_file is not None ): #", "storage.Client() fileobj = io.BytesIO() gcs.download_blob_to_file(bundle_path, fileobj) fileobj.seek(0, 0) elif _is_http_url(bundle_path):", "fileobj) fileobj.seek(0, 0) elif _is_http_url(bundle_path): import requests response = requests.get(bundle_path)", "path and s3 path target_dir (:obj:`str`): Where the service contents", "= importlib.util.module_from_spec(spec) spec.loader.exec_module(module) elif sys.version_info >= (3, 3): from importlib.machinery", "path: '{bundle_path}' is not supported\") with tarfile.open(mode=\"r:gz\", fileobj=fileobj) as tar:", "= importlib.util.spec_from_file_location(module_name, module_file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) elif sys.version_info >=", "service contents should end up. Returns: :obj:`str`: location of safe", "bentoml.yatai.proto.repository_pb2 import BentoServiceMetadata logger = logging.getLogger(__name__) def _is_http_url(bundle_path) -> bool:", "metadata[\"module_file\"] ) # Prepend bundle_path to sys.path for loading extra", "os.path.isfile(module_file_path): module_file_path = os.path.join( bundle_path, PureWindowsPath(module_file).as_posix() ) if not os.path.isfile(module_file_path):", "storage except ImportError: raise BentoMLException( '\"google-cloud-storage\" package is required. You", "{} in saved bundle {}\".format( module_file, bundle_path ) ) return", "metadata[\"service_name\"], ZIPIMPORT_DIR) if os.path.exists(zipimport_dir): for p in os.listdir(zipimport_dir): logger.debug('adding %s", "copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required", "access it via svc.version model_service_class._bento_service_bundle_version = metadata[\"service_version\"] if ( model_service_class._env", "(the \"License\"); # you may not use this file except", "logger = logging.getLogger(__name__) def _is_http_url(bundle_path) -> bool: try: return urlparse(bundle_path).scheme", "# you may not use this file except in compliance", "from sys.path to avoid import naming conflicts sys.path.remove(bundle_path) model_service_class =", "Find and load target module containing BentoService class from given", "io import os import sys import tarfile import logging import", "urllib.parse import urlparse from typing import TYPE_CHECKING from pathlib import", "parsed_url.netloc object_name = parsed_url.path.lstrip('/') s3 = boto3.client('s3') fileobj = io.BytesIO()", "Set cls._version, service instance can access it via svc.version model_service_class._bento_service_bundle_version", "model_service_class._bento_service_bundle_path = bundle_path # Set cls._version, service instance can access", "filename = tar.getmembers()[0].name tar.extractall(path=tmpdir) yield os.path.join(tmpdir, filename) def resolve_remote_bundle(func): \"\"\"Decorate", "pylint:enable=deprecated-method else: raise BentoMLException(\"BentoML requires Python 3.4 and above\") #", "from google.cloud import storage except ImportError: raise BentoMLException( '\"google-cloud-storage\" package", "urlparse(bundle_path) bucket_name = parsed_url.netloc object_name = parsed_url.path.lstrip('/') s3 = boto3.client('s3')", "_resolve_remote_bundle_path(bundle_path): if is_s3_url(bundle_path): import boto3 parsed_url = urlparse(bundle_path) bucket_name =", "needs to handle the path differences between posix and windows", "from saved bundle in given path :param bundle_path: A path", "os.path.join( bundle_path, \"requirements.txt\" ) return model_service_class @resolve_remote_bundle def safe_retrieve(bundle_path: str,", "@resolve_remote_bundle def load_saved_bundle_config(bundle_path) -> \"SavedBundleConfig\": try: return SavedBundleConfig.load(os.path.join(bundle_path, \"bentoml.yml\")) except", "not locate module_file {} in saved bundle {}\".format( module_file, bundle_path", "module = SourceFileLoader(module_name, module_file_path).load_module( module_name ) # pylint:enable=deprecated-method else: raise", "from bentoml.utils.gcs import is_gcs_url from bentoml.exceptions import BentoMLException from bentoml.saved_bundle.config", "\"\"\"Safely retrieve bento service to local path Args: bundle_path (:obj:`str`):", "str(PurePosixPath(module_file)) ) if not os.path.isfile(module_file_path): module_file_path = os.path.join( bundle_path, str(PurePosixPath(module_file))", "s3 path Returns: bentoml.service.BentoService: a loaded BentoService instance \"\"\" svc_cls", "fileobj.seek(0, 0) else: raise BentoMLException(f\"Saved bundle path: '{bundle_path}' is not", "\"\"\"Load bento service from local file path or s3 path", "boto3.client('s3') fileobj = io.BytesIO() s3.download_fileobj(bucket_name, object_name, fileobj) fileobj.seek(0, 0) elif", "TYPE_CHECKING: from bentoml.yatai.proto.repository_pb2 import BentoServiceMetadata logger = logging.getLogger(__name__) def _is_http_url(bundle_path)", "SourceFileLoader # pylint:disable=deprecated-method module = SourceFileLoader(module_name, module_file_path).load_module( module_name ) #", "handle remote bundles.\"\"\" @wraps(func) def wrapper(bundle_path, *args): if _is_remote_path(bundle_path): with", "_is_remote_path(bundle_path): with _resolve_remote_bundle_path(bundle_path) as local_bundle_path: return func(local_bundle_path, *args) return func(bundle_path,", "path, which may only available during the bundle save process", "import BentoMLException from bentoml.saved_bundle.config import SavedBundleConfig from bentoml.saved_bundle.pip_pkg import ZIPIMPORT_DIR", "install google-cloud-storage\"' ) gcs = storage.Client() fileobj = io.BytesIO() gcs.download_blob_to_file(bundle_path,", "FileNotFoundError: raise BentoMLException( \"BentoML can't locate config file 'bentoml.yml'\" \"", "importlib.util spec = importlib.util.spec_from_file_location(module_name, module_file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) elif", "if not os.path.isfile(module_file_path): module_file_path = os.path.join( bundle_path, PureWindowsPath(module_file).as_posix() ) if", "_is_http_url(bundle_path): import requests response = requests.get(bundle_path) if response.status_code != 200:", "Version 2.0 (the \"License\"); # you may not use this", "model_service_class @resolve_remote_bundle def safe_retrieve(bundle_path: str, target_dir: str): \"\"\"Safely retrieve bento", "The path that contains saved BentoService bundle, supporting both local", "class from saved bundle in given path :param bundle_path: A", "sys.path', p) sys.path.insert(0, os.path.join(zipimport_dir, p)) module_name = metadata[\"module_name\"] if module_name", "fileobj = io.BytesIO() gcs.download_blob_to_file(bundle_path, fileobj) fileobj.seek(0, 0) elif _is_http_url(bundle_path): import", "may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0", "module_name = metadata[\"module_name\"] if module_name in sys.modules: logger.warning( \"Module `%s`", "*args) return wrapper @resolve_remote_bundle def load_saved_bundle_config(bundle_path) -> \"SavedBundleConfig\": try: return", "the bundle save process model_service_class._env._requirements_txt_file = os.path.join( bundle_path, \"requirements.txt\" )", "is not supported\") with tarfile.open(mode=\"r:gz\", fileobj=fileobj) as tar: with tempfile.TemporaryDirectory()", "\"Can not locate module_file {} in saved bundle {}\".format( module_file,", "zipimport_dir = os.path.join(bundle_path, metadata[\"service_name\"], ZIPIMPORT_DIR) if os.path.exists(zipimport_dir): for p in", "str, target_dir: str): \"\"\"Safely retrieve bento service to local path", "implied. # See the License for the specific language governing", "_is_http_url(bundle_path) -> bool: try: return urlparse(bundle_path).scheme in [\"http\", \"https\"] except", "or the path to pip installed BentoService directory :return: BentoService", "is_s3_url(bundle_path): import boto3 parsed_url = urlparse(bundle_path) bucket_name = parsed_url.netloc object_name", "@resolve_remote_bundle def load_from_dir(bundle_path): \"\"\"Load bento service from local file path", "under the Apache License, Version 2.0 (the \"License\"); # you", "from functools import wraps from contextlib import contextmanager from urllib.parse", "3): from importlib.machinery import SourceFileLoader # pylint:disable=deprecated-method module = SourceFileLoader(module_name,", "def resolve_remote_bundle(func): \"\"\"Decorate a function to handle remote bundles.\"\"\" @wraps(func)", "_is_remote_path(bundle_path) -> bool: return isinstance(bundle_path, str) and ( is_s3_url(bundle_path) or", "'{bundle_path}' is not supported\") with tarfile.open(mode=\"r:gz\", fileobj=fileobj) as tar: with", "will load its artifacts model_service_class._bento_service_bundle_path = bundle_path # Set cls._version,", "posix and windows platform: if not os.path.isfile(module_file_path): if sys.platform ==", "load_saved_bundle_config(bundle_path).get_bento_service_metadata_pb() def _find_module_file(bundle_path, service_name, module_file): # Simply join full path", "load_from_dir(bundle_path): \"\"\"Load bento service from local file path or s3", "object_name, fileobj) fileobj.seek(0, 0) elif is_gcs_url(bundle_path): try: from google.cloud import", "fileobj.seek(0, 0) elif is_gcs_url(bundle_path): try: from google.cloud import storage except", "= storage.Client() fileobj = io.BytesIO() gcs.download_blob_to_file(bundle_path, fileobj) fileobj.seek(0, 0) elif", "by applicable law or agreed to in writing, software #", "os.path.isfile(module_file_path): if sys.platform == \"win32\": # Try load a saved", "target_dir (:obj:`str`): Where the service contents should end up. Returns:", "\"SavedBundleConfig\": try: return SavedBundleConfig.load(os.path.join(bundle_path, \"bentoml.yml\")) except FileNotFoundError: raise BentoMLException( \"BentoML", "a saved bundle created from windows platform on posix module_file_path", "can't locate config file 'bentoml.yml'\" \" in saved bundle in", "= os.path.join( bundle_path, \"requirements.txt\" ) return model_service_class @resolve_remote_bundle def safe_retrieve(bundle_path:", "# Try load a saved bundle created from windows platform", "and s3 path Returns: bentoml.service.BentoService: a loaded BentoService instance \"\"\"", "load_bento_service_metadata(bundle_path: str) -> \"BentoServiceMetadata\": return load_saved_bundle_config(bundle_path).get_bento_service_metadata_pb() def _find_module_file(bundle_path, service_name, module_file):", "# pylint:disable=deprecated-method module = SourceFileLoader(module_name, module_file_path).load_module( module_name ) # pylint:enable=deprecated-method", "-> bool: return isinstance(bundle_path, str) and ( is_s3_url(bundle_path) or is_gcs_url(bundle_path)", "pylint:disable=deprecated-method module = SourceFileLoader(module_name, module_file_path).load_module( module_name ) # pylint:enable=deprecated-method else:", "the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable", "parsed_url.path.lstrip('/') s3 = boto3.client('s3') fileobj = io.BytesIO() s3.download_fileobj(bucket_name, object_name, fileobj)", "instance \"\"\" svc_cls = load_bento_service_class(bundle_path) return svc_cls() @resolve_remote_bundle def load_bento_service_api(bundle_path,", "return svc_cls() @resolve_remote_bundle def load_bento_service_api(bundle_path, api_name=None): bento_service = load_from_dir(bundle_path) return", "# limitations under the License. import io import os import", "config file 'bentoml.yml'\" \" in saved bundle in path: {}\".format(bundle_path)", "sys.modules[module_name] elif sys.version_info >= (3, 5): import importlib.util spec =", "supported\") with tarfile.open(mode=\"r:gz\", fileobj=fileobj) as tar: with tempfile.TemporaryDirectory() as tmpdir:", "imported module.\", module_name ) module = sys.modules[module_name] elif sys.version_info >=", "BentoMLException(\"BentoML requires Python 3.4 and above\") # Remove bundle_path from", "google.cloud import storage except ImportError: raise BentoMLException( '\"google-cloud-storage\" package is", "return load_saved_bundle_config(bundle_path).get_bento_service_metadata_pb() def _find_module_file(bundle_path, service_name, module_file): # Simply join full", "Set _bento_service_bundle_path, where BentoService will load its artifacts model_service_class._bento_service_bundle_path =", "SavedBundleConfig.load(os.path.join(bundle_path, \"bentoml.yml\")) except FileNotFoundError: raise BentoMLException( \"BentoML can't locate config", "on windows module_file_path = os.path.join( bundle_path, service_name, str(PurePosixPath(module_file)) ) if", "a file name, # e.g. module_file==\"iris_classifier.py\" module_file_path = os.path.join(bundle_path, service_name,", "# http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed", "bucket_name = parsed_url.netloc object_name = parsed_url.path.lstrip('/') s3 = boto3.client('s3') fileobj", "tarfile import logging import tempfile import shutil from functools import", "\"pip install google-cloud-storage\"' ) gcs = storage.Client() fileobj = io.BytesIO()", "sys.path.remove(bundle_path) model_service_class = module.__getattribute__(metadata[\"service_name\"]) # Set _bento_service_bundle_path, where BentoService will", "module_file is just a file name, # e.g. module_file==\"iris_classifier.py\" module_file_path", "elif _is_http_url(bundle_path): import requests response = requests.get(bundle_path) if response.status_code !=", "generated from BentoService#save, #save_to_dir, or the path to pip installed", "module.\", module_name ) module = sys.modules[module_name] elif sys.version_info >= (3,", "Args: bundle_path (str): The path that contains saved BentoService bundle,", "def safe_retrieve(bundle_path: str, target_dir: str): \"\"\"Safely retrieve bento service to", "loading extra python dependencies sys.path.insert(0, bundle_path) sys.path.insert(0, os.path.join(bundle_path, metadata[\"service_name\"])) #", "is_s3_url from bentoml.utils.gcs import is_gcs_url from bentoml.exceptions import BentoMLException from", "module_file_path = os.path.join( bundle_path, PureWindowsPath(module_file).as_posix() ) if not os.path.isfile(module_file_path): raise", "platform on posix module_file_path = os.path.join( bundle_path, service_name, PureWindowsPath(module_file).as_posix() )", "BentoService class \"\"\" config = load_saved_bundle_config(bundle_path) metadata = config[\"metadata\"] #", "to local path Args: bundle_path (:obj:`str`): The path that contains", "# Set cls._version, service instance can access it via svc.version", "# e.g. module_file==\"iris_classifier.py\" module_file_path = os.path.join(bundle_path, service_name, module_file) if not", "from typing import TYPE_CHECKING from pathlib import PureWindowsPath, PurePosixPath from", "load_bento_service_class(bundle_path): \"\"\" Load a BentoService class from saved bundle in", "locate config file 'bentoml.yml'\" \" in saved bundle in path:", "path \"\"\" shutil.copytree(bundle_path, target_dir) @resolve_remote_bundle def load_from_dir(bundle_path): \"\"\"Load bento service", "not os.path.isfile(module_file_path): module_file_path = os.path.join( bundle_path, str(PurePosixPath(module_file)) ) else: #", "os.path.join(bundle_path, metadata[\"service_name\"])) # Include zipimport modules zipimport_dir = os.path.join(bundle_path, metadata[\"service_name\"],", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "path Args: bundle_path (str): The path that contains saved BentoService", "Unless required by applicable law or agreed to in writing,", "from contextlib import contextmanager from urllib.parse import urlparse from typing", "tmpdir: filename = tar.getmembers()[0].name tar.extractall(path=tmpdir) yield os.path.join(tmpdir, filename) def resolve_remote_bundle(func):", "retrieve bento service to local path Args: bundle_path (:obj:`str`): The", "logger.warning( \"Module `%s` already loaded, using existing imported module.\", module_name", "the specific language governing permissions and # limitations under the", "resolve_remote_bundle(func): \"\"\"Decorate a function to handle remote bundles.\"\"\" @wraps(func) def", "\" in saved bundle in path: {}\".format(bundle_path) ) def load_bento_service_metadata(bundle_path:", "load a saved bundle created from windows platform on posix", "return module_file_path @resolve_remote_bundle def load_bento_service_class(bundle_path): \"\"\" Load a BentoService class", "module_name ) module = sys.modules[module_name] elif sys.version_info >= (3, 5):", "during the bundle save process model_service_class._env._requirements_txt_file = os.path.join( bundle_path, \"requirements.txt\"", "fileobj = io.BytesIO() fileobj.write(response.content) fileobj.seek(0, 0) else: raise BentoMLException(f\"Saved bundle", "try: return urlparse(bundle_path).scheme in [\"http\", \"https\"] except ValueError: return False", "without service_name prefix, for loading from a installed PyPi module_file_path", "applicable law or agreed to in writing, software # distributed", "path when module_file is just a file name, # e.g.", "bundle save process model_service_class._env._requirements_txt_file = os.path.join( bundle_path, \"requirements.txt\" ) return", "= config[\"metadata\"] # Find and load target module containing BentoService", "# Remove bundle_path from sys.path to avoid import naming conflicts", "bundle_path: A path to Bento files generated from BentoService#save, #save_to_dir,", "= SourceFileLoader(module_name, module_file_path).load_module( module_name ) # pylint:enable=deprecated-method else: raise BentoMLException(\"BentoML", "BentoService bundle. \" f\"{response.status_code}: {response.text}\" ) fileobj = io.BytesIO() fileobj.write(response.content)", "in writing, software # distributed under the License is distributed", "install it with ' 'pip: \"pip install google-cloud-storage\"' ) gcs", "e.g. module_file==\"foo/bar/iris_classifier.py\" # This needs to handle the path differences", "Returns: :obj:`str`: location of safe local path \"\"\" shutil.copytree(bundle_path, target_dir)", "(3, 5): import importlib.util spec = importlib.util.spec_from_file_location(module_name, module_file_path) module =", "ImportError: raise BentoMLException( '\"google-cloud-storage\" package is required. You can install", ">= (3, 5): import importlib.util spec = importlib.util.spec_from_file_location(module_name, module_file_path) module", "def _find_module_file(bundle_path, service_name, module_file): # Simply join full path when", "= os.path.join(bundle_path, service_name, module_file) if not os.path.isfile(module_file_path): # Try loading", "0) else: raise BentoMLException(f\"Saved bundle path: '{bundle_path}' is not supported\")", "gcs.download_blob_to_file(bundle_path, fileobj) fileobj.seek(0, 0) elif _is_http_url(bundle_path): import requests response =", "importlib.util.module_from_spec(spec) spec.loader.exec_module(module) elif sys.version_info >= (3, 3): from importlib.machinery import", "the path differences between posix and windows platform: if not", "if module_name in sys.modules: logger.warning( \"Module `%s` already loaded, using", "service_name, PureWindowsPath(module_file).as_posix() ) if not os.path.isfile(module_file_path): module_file_path = os.path.join( bundle_path,", "sys.path.insert(0, bundle_path) sys.path.insert(0, os.path.join(bundle_path, metadata[\"service_name\"])) # Include zipimport modules zipimport_dir", "or is_gcs_url(bundle_path) or _is_http_url(bundle_path) ) @contextmanager def _resolve_remote_bundle_path(bundle_path): if is_s3_url(bundle_path):", ") def load_bento_service_metadata(bundle_path: str) -> \"BentoServiceMetadata\": return load_saved_bundle_config(bundle_path).get_bento_service_metadata_pb() def _find_module_file(bundle_path,", "and ( is_s3_url(bundle_path) or is_gcs_url(bundle_path) or _is_http_url(bundle_path) ) @contextmanager def", "-> \"BentoServiceMetadata\": return load_saved_bundle_config(bundle_path).get_bento_service_metadata_pb() def _find_module_file(bundle_path, service_name, module_file): # Simply", "5): import importlib.util spec = importlib.util.spec_from_file_location(module_name, module_file_path) module = importlib.util.module_from_spec(spec)", "3.4 and above\") # Remove bundle_path from sys.path to avoid", "= os.path.join(bundle_path, metadata[\"service_name\"], ZIPIMPORT_DIR) if os.path.exists(zipimport_dir): for p in os.listdir(zipimport_dir):", "module_file_path = os.path.join(bundle_path, module_file) # When module_file is located in", "= logging.getLogger(__name__) def _is_http_url(bundle_path) -> bool: try: return urlparse(bundle_path).scheme in", "raise BentoMLException(f\"Saved bundle path: '{bundle_path}' is not supported\") with tarfile.open(mode=\"r:gz\",", "from local file path or s3 path Args: bundle_path (str):", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "differences between posix and windows platform: if not os.path.isfile(module_file_path): if", "bundle directory instead of the user-provided # file path, which", "bentoml.utils.s3 import is_s3_url from bentoml.utils.gcs import is_gcs_url from bentoml.exceptions import", "# You may obtain a copy of the License at", "os.path.isfile(module_file_path): raise BentoMLException( \"Can not locate module_file {} in saved", "sys.path to avoid import naming conflicts sys.path.remove(bundle_path) model_service_class = module.__getattribute__(metadata[\"service_name\"])", "bundle in given path :param bundle_path: A path to Bento", "fileobj = io.BytesIO() s3.download_fileobj(bucket_name, object_name, fileobj) fileobj.seek(0, 0) elif is_gcs_url(bundle_path):", "module_name ) # pylint:enable=deprecated-method else: raise BentoMLException(\"BentoML requires Python 3.4", "with tempfile.TemporaryDirectory() as tmpdir: filename = tar.getmembers()[0].name tar.extractall(path=tmpdir) yield os.path.join(tmpdir,", "user-provided # file path, which may only available during the", "str(PurePosixPath(module_file)) ) else: # Try load a saved bundle created", "is required. You can install it with ' 'pip: \"pip", "wrapper @resolve_remote_bundle def load_saved_bundle_config(bundle_path) -> \"SavedBundleConfig\": try: return SavedBundleConfig.load(os.path.join(bundle_path, \"bentoml.yml\"))", ") module = sys.modules[module_name] elif sys.version_info >= (3, 5): import", "def _resolve_remote_bundle_path(bundle_path): if is_s3_url(bundle_path): import boto3 parsed_url = urlparse(bundle_path) bucket_name", "module_file_path).load_module( module_name ) # pylint:enable=deprecated-method else: raise BentoMLException(\"BentoML requires Python", ") # Prepend bundle_path to sys.path for loading extra python", "@contextmanager def _resolve_remote_bundle_path(bundle_path): if is_s3_url(bundle_path): import boto3 parsed_url = urlparse(bundle_path)", "' 'pip: \"pip install google-cloud-storage\"' ) gcs = storage.Client() fileobj", "posix platform on windows module_file_path = os.path.join( bundle_path, service_name, str(PurePosixPath(module_file))", "Load a BentoService class from saved bundle in given path", "@resolve_remote_bundle def safe_retrieve(bundle_path: str, target_dir: str): \"\"\"Safely retrieve bento service", "# pylint:enable=deprecated-method else: raise BentoMLException(\"BentoML requires Python 3.4 and above\")", "path :param bundle_path: A path to Bento files generated from", "module_file==\"iris_classifier.py\" module_file_path = os.path.join(bundle_path, service_name, module_file) if not os.path.isfile(module_file_path): #", "(:obj:`str`): The path that contains saved BentoService bundle, supporting both", "the License for the specific language governing permissions and #", "func(bundle_path, *args) return wrapper @resolve_remote_bundle def load_saved_bundle_config(bundle_path) -> \"SavedBundleConfig\": try:", "tar: with tempfile.TemporaryDirectory() as tmpdir: filename = tar.getmembers()[0].name tar.extractall(path=tmpdir) yield", "sub directory # e.g. module_file==\"foo/bar/iris_classifier.py\" # This needs to handle", "Apache License, Version 2.0 (the \"License\"); # you may not", "config[\"metadata\"] # Find and load target module containing BentoService class", "either express or implied. # See the License for the", "platform on windows module_file_path = os.path.join( bundle_path, service_name, str(PurePosixPath(module_file)) )", "zipimport modules zipimport_dir = os.path.join(bundle_path, metadata[\"service_name\"], ZIPIMPORT_DIR) if os.path.exists(zipimport_dir): for", "= io.BytesIO() gcs.download_blob_to_file(bundle_path, fileobj) fileobj.seek(0, 0) elif _is_http_url(bundle_path): import requests", "BentoService will load its artifacts model_service_class._bento_service_bundle_path = bundle_path # Set", "# Prepend bundle_path to sys.path for loading extra python dependencies", "typing import TYPE_CHECKING from pathlib import PureWindowsPath, PurePosixPath from bentoml.utils.s3", "contains saved BentoService bundle, supporting both local file path and", "BentoService class from saved bundle in given path :param bundle_path:", "= load_saved_bundle_config(bundle_path) metadata = config[\"metadata\"] # Find and load target", "bentoml.saved_bundle.pip_pkg import ZIPIMPORT_DIR if TYPE_CHECKING: from bentoml.yatai.proto.repository_pb2 import BentoServiceMetadata logger", "obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 #", "and above\") # Remove bundle_path from sys.path to avoid import", "requests response = requests.get(bundle_path) if response.status_code != 200: raise BentoMLException(", "@wraps(func) def wrapper(bundle_path, *args): if _is_remote_path(bundle_path): with _resolve_remote_bundle_path(bundle_path) as local_bundle_path:", "svc_cls() @resolve_remote_bundle def load_bento_service_api(bundle_path, api_name=None): bento_service = load_from_dir(bundle_path) return bento_service.get_inference_api(api_name)", "bundle_path (:obj:`str`): The path that contains saved BentoService bundle, supporting", "Try load a saved bundle created from posix platform on", "file path and s3 path target_dir (:obj:`str`): Where the service", "conflicts sys.path.remove(bundle_path) model_service_class = module.__getattribute__(metadata[\"service_name\"]) # Set _bento_service_bundle_path, where BentoService", "None ): # Load `requirement.txt` from bundle directory instead of", "= bundle_path # Set cls._version, service instance can access it", "response.status_code != 200: raise BentoMLException( f\"Error retrieving BentoService bundle. \"", "bundle. \" f\"{response.status_code}: {response.text}\" ) fileobj = io.BytesIO() fileobj.write(response.content) fileobj.seek(0,", "fileobj) fileobj.seek(0, 0) elif is_gcs_url(bundle_path): try: from google.cloud import storage", "0) elif _is_http_url(bundle_path): import requests response = requests.get(bundle_path) if response.status_code", "os.path.join(bundle_path, metadata[\"service_name\"], ZIPIMPORT_DIR) if os.path.exists(zipimport_dir): for p in os.listdir(zipimport_dir): logger.debug('adding", "bentoml.saved_bundle.config import SavedBundleConfig from bentoml.saved_bundle.pip_pkg import ZIPIMPORT_DIR if TYPE_CHECKING: from", "path Args: bundle_path (:obj:`str`): The path that contains saved BentoService", "sys import tarfile import logging import tempfile import shutil from", "!= 200: raise BentoMLException( f\"Error retrieving BentoService bundle. \" f\"{response.status_code}:", "under the License. import io import os import sys import", "Remove bundle_path from sys.path to avoid import naming conflicts sys.path.remove(bundle_path)", "PurePosixPath from bentoml.utils.s3 import is_s3_url from bentoml.utils.gcs import is_gcs_url from", "import requests response = requests.get(bundle_path) if response.status_code != 200: raise", "bentoml.utils.gcs import is_gcs_url from bentoml.exceptions import BentoMLException from bentoml.saved_bundle.config import", "= os.path.join(bundle_path, module_file) # When module_file is located in sub", "metadata[\"module_name\"] if module_name in sys.modules: logger.warning( \"Module `%s` already loaded,", "import logging import tempfile import shutil from functools import wraps", "load target module containing BentoService class from given path module_file_path", "module_file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) elif sys.version_info >= (3, 3):", "200: raise BentoMLException( f\"Error retrieving BentoService bundle. \" f\"{response.status_code}: {response.text}\"", "\" f\"{response.status_code}: {response.text}\" ) fileobj = io.BytesIO() fileobj.write(response.content) fileobj.seek(0, 0)", "Include zipimport modules zipimport_dir = os.path.join(bundle_path, metadata[\"service_name\"], ZIPIMPORT_DIR) if os.path.exists(zipimport_dir):", ") ) return module_file_path @resolve_remote_bundle def load_bento_service_class(bundle_path): \"\"\" Load a", "\"\"\" Load a BentoService class from saved bundle in given", "requests.get(bundle_path) if response.status_code != 200: raise BentoMLException( f\"Error retrieving BentoService", "import BentoServiceMetadata logger = logging.getLogger(__name__) def _is_http_url(bundle_path) -> bool: try:", "urlparse(bundle_path).scheme in [\"http\", \"https\"] except ValueError: return False def _is_remote_path(bundle_path)", "\"License\"); # you may not use this file except in", "directory instead of the user-provided # file path, which may", "BentoServiceMetadata logger = logging.getLogger(__name__) def _is_http_url(bundle_path) -> bool: try: return", "prefix, for loading from a installed PyPi module_file_path = os.path.join(bundle_path,", "from windows platform on posix module_file_path = os.path.join( bundle_path, service_name,", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "elif is_gcs_url(bundle_path): try: from google.cloud import storage except ImportError: raise", "on posix module_file_path = os.path.join( bundle_path, service_name, PureWindowsPath(module_file).as_posix() ) if", "(:obj:`str`): Where the service contents should end up. Returns: :obj:`str`:", "target_dir: str): \"\"\"Safely retrieve bento service to local path Args:", "from importlib.machinery import SourceFileLoader # pylint:disable=deprecated-method module = SourceFileLoader(module_name, module_file_path).load_module(", "is located in sub directory # e.g. module_file==\"foo/bar/iris_classifier.py\" # This", "BentoMLException( f\"Error retrieving BentoService bundle. \" f\"{response.status_code}: {response.text}\" ) fileobj", "if TYPE_CHECKING: from bentoml.yatai.proto.repository_pb2 import BentoServiceMetadata logger = logging.getLogger(__name__) def", "path differences between posix and windows platform: if not os.path.isfile(module_file_path):", "# Include zipimport modules zipimport_dir = os.path.join(bundle_path, metadata[\"service_name\"], ZIPIMPORT_DIR) if", "as local_bundle_path: return func(local_bundle_path, *args) return func(bundle_path, *args) return wrapper", "fileobj.seek(0, 0) elif _is_http_url(bundle_path): import requests response = requests.get(bundle_path) if", "p) sys.path.insert(0, os.path.join(zipimport_dir, p)) module_name = metadata[\"module_name\"] if module_name in", "instance can access it via svc.version model_service_class._bento_service_bundle_version = metadata[\"service_version\"] if", "# distributed under the License is distributed on an \"AS", "and # limitations under the License. import io import os", "import wraps from contextlib import contextmanager from urllib.parse import urlparse", "if is_s3_url(bundle_path): import boto3 parsed_url = urlparse(bundle_path) bucket_name = parsed_url.netloc", "module_file {} in saved bundle {}\".format( module_file, bundle_path ) )", "should end up. Returns: :obj:`str`: location of safe local path", "# Unless required by applicable law or agreed to in", "from pathlib import PureWindowsPath, PurePosixPath from bentoml.utils.s3 import is_s3_url from", "service_name, module_file): # Simply join full path when module_file is", "safe local path \"\"\" shutil.copytree(bundle_path, target_dir) @resolve_remote_bundle def load_from_dir(bundle_path): \"\"\"Load", "if not os.path.isfile(module_file_path): if sys.platform == \"win32\": # Try load", ") else: # Try load a saved bundle created from", "bento service to local path Args: bundle_path (:obj:`str`): The path", "extra python dependencies sys.path.insert(0, bundle_path) sys.path.insert(0, os.path.join(bundle_path, metadata[\"service_name\"])) # Include", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "bundle_path # Set cls._version, service instance can access it via", "importlib.util.spec_from_file_location(module_name, module_file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) elif sys.version_info >= (3,", "You may obtain a copy of the License at #", "(3, 3): from importlib.machinery import SourceFileLoader # pylint:disable=deprecated-method module =", "_find_module_file(bundle_path, service_name, module_file): # Simply join full path when module_file", "in [\"http\", \"https\"] except ValueError: return False def _is_remote_path(bundle_path) ->", "else: raise BentoMLException(f\"Saved bundle path: '{bundle_path}' is not supported\") with", "file 'bentoml.yml'\" \" in saved bundle in path: {}\".format(bundle_path) )", "import storage except ImportError: raise BentoMLException( '\"google-cloud-storage\" package is required.", "# e.g. module_file==\"foo/bar/iris_classifier.py\" # This needs to handle the path", "in sys.modules: logger.warning( \"Module `%s` already loaded, using existing imported", "file name, # e.g. module_file==\"iris_classifier.py\" module_file_path = os.path.join(bundle_path, service_name, module_file)", "end up. Returns: :obj:`str`: location of safe local path \"\"\"", "function to handle remote bundles.\"\"\" @wraps(func) def wrapper(bundle_path, *args): if", "in saved bundle in path: {}\".format(bundle_path) ) def load_bento_service_metadata(bundle_path: str)", "the Apache License, Version 2.0 (the \"License\"); # you may", "yield os.path.join(tmpdir, filename) def resolve_remote_bundle(func): \"\"\"Decorate a function to handle", "locate module_file {} in saved bundle {}\".format( module_file, bundle_path )", "in given path :param bundle_path: A path to Bento files", "bundle {}\".format( module_file, bundle_path ) ) return module_file_path @resolve_remote_bundle def", "given path :param bundle_path: A path to Bento files generated", "path Returns: bentoml.service.BentoService: a loaded BentoService instance \"\"\" svc_cls =", "saved BentoService bundle, supporting both local file path and s3" ]
[ "def upgrade(): op.execute(\"ALTER TABLE services ALTER rate_limit DROP DEFAULT\") op.execute(\"ALTER", "TABLE services ALTER rate_limit DROP DEFAULT\") op.execute(\"ALTER TABLE services_history ALTER", "def downgrade(): op.execute(\"ALTER TABLE services ALTER rate_limit SET DEFAULT '3000'\")", "Revises: 0157_add_rate_limit_to_service Create Date: 2018-01-09 14:33:08.313893 \"\"\" import sqlalchemy as", "ALTER rate_limit DROP DEFAULT\") def downgrade(): op.execute(\"ALTER TABLE services ALTER", "DEFAULT\") op.execute(\"ALTER TABLE services_history ALTER rate_limit DROP DEFAULT\") def downgrade():", "import sqlalchemy as sa from alembic import op revision =", "from alembic import op revision = \"0158_remove_rate_limit_default\" down_revision = \"0157_add_rate_limit_to_service\"", "ID: 0158_remove_rate_limit_default Revises: 0157_add_rate_limit_to_service Create Date: 2018-01-09 14:33:08.313893 \"\"\" import", "\"\"\" Revision ID: 0158_remove_rate_limit_default Revises: 0157_add_rate_limit_to_service Create Date: 2018-01-09 14:33:08.313893", "= \"0158_remove_rate_limit_default\" down_revision = \"0157_add_rate_limit_to_service\" def upgrade(): op.execute(\"ALTER TABLE services", "TABLE services ALTER rate_limit SET DEFAULT '3000'\") op.execute(\"ALTER TABLE services_history", "sqlalchemy as sa from alembic import op revision = \"0158_remove_rate_limit_default\"", "TABLE services_history ALTER rate_limit DROP DEFAULT\") def downgrade(): op.execute(\"ALTER TABLE", "SET DEFAULT '3000'\") op.execute(\"ALTER TABLE services_history ALTER rate_limit SET DEFAULT", "Revision ID: 0158_remove_rate_limit_default Revises: 0157_add_rate_limit_to_service Create Date: 2018-01-09 14:33:08.313893 \"\"\"", "op revision = \"0158_remove_rate_limit_default\" down_revision = \"0157_add_rate_limit_to_service\" def upgrade(): op.execute(\"ALTER", "services ALTER rate_limit DROP DEFAULT\") op.execute(\"ALTER TABLE services_history ALTER rate_limit", "0157_add_rate_limit_to_service Create Date: 2018-01-09 14:33:08.313893 \"\"\" import sqlalchemy as sa", "\"0158_remove_rate_limit_default\" down_revision = \"0157_add_rate_limit_to_service\" def upgrade(): op.execute(\"ALTER TABLE services ALTER", "op.execute(\"ALTER TABLE services ALTER rate_limit SET DEFAULT '3000'\") op.execute(\"ALTER TABLE", "= \"0157_add_rate_limit_to_service\" def upgrade(): op.execute(\"ALTER TABLE services ALTER rate_limit DROP", "Date: 2018-01-09 14:33:08.313893 \"\"\" import sqlalchemy as sa from alembic", "14:33:08.313893 \"\"\" import sqlalchemy as sa from alembic import op", "\"0157_add_rate_limit_to_service\" def upgrade(): op.execute(\"ALTER TABLE services ALTER rate_limit DROP DEFAULT\")", "revision = \"0158_remove_rate_limit_default\" down_revision = \"0157_add_rate_limit_to_service\" def upgrade(): op.execute(\"ALTER TABLE", "op.execute(\"ALTER TABLE services ALTER rate_limit DROP DEFAULT\") op.execute(\"ALTER TABLE services_history", "DROP DEFAULT\") op.execute(\"ALTER TABLE services_history ALTER rate_limit DROP DEFAULT\") def", "rate_limit DROP DEFAULT\") def downgrade(): op.execute(\"ALTER TABLE services ALTER rate_limit", "as sa from alembic import op revision = \"0158_remove_rate_limit_default\" down_revision", "sa from alembic import op revision = \"0158_remove_rate_limit_default\" down_revision =", "alembic import op revision = \"0158_remove_rate_limit_default\" down_revision = \"0157_add_rate_limit_to_service\" def", "DEFAULT '3000'\") op.execute(\"ALTER TABLE services_history ALTER rate_limit SET DEFAULT '3000'\")", "DEFAULT\") def downgrade(): op.execute(\"ALTER TABLE services ALTER rate_limit SET DEFAULT", "ALTER rate_limit DROP DEFAULT\") op.execute(\"ALTER TABLE services_history ALTER rate_limit DROP", "\"\"\" import sqlalchemy as sa from alembic import op revision", "DROP DEFAULT\") def downgrade(): op.execute(\"ALTER TABLE services ALTER rate_limit SET", "import op revision = \"0158_remove_rate_limit_default\" down_revision = \"0157_add_rate_limit_to_service\" def upgrade():", "downgrade(): op.execute(\"ALTER TABLE services ALTER rate_limit SET DEFAULT '3000'\") op.execute(\"ALTER", "upgrade(): op.execute(\"ALTER TABLE services ALTER rate_limit DROP DEFAULT\") op.execute(\"ALTER TABLE", "down_revision = \"0157_add_rate_limit_to_service\" def upgrade(): op.execute(\"ALTER TABLE services ALTER rate_limit", "op.execute(\"ALTER TABLE services_history ALTER rate_limit DROP DEFAULT\") def downgrade(): op.execute(\"ALTER", "0158_remove_rate_limit_default Revises: 0157_add_rate_limit_to_service Create Date: 2018-01-09 14:33:08.313893 \"\"\" import sqlalchemy", "ALTER rate_limit SET DEFAULT '3000'\") op.execute(\"ALTER TABLE services_history ALTER rate_limit", "Create Date: 2018-01-09 14:33:08.313893 \"\"\" import sqlalchemy as sa from", "services_history ALTER rate_limit DROP DEFAULT\") def downgrade(): op.execute(\"ALTER TABLE services", "rate_limit DROP DEFAULT\") op.execute(\"ALTER TABLE services_history ALTER rate_limit DROP DEFAULT\")", "rate_limit SET DEFAULT '3000'\") op.execute(\"ALTER TABLE services_history ALTER rate_limit SET", "2018-01-09 14:33:08.313893 \"\"\" import sqlalchemy as sa from alembic import", "services ALTER rate_limit SET DEFAULT '3000'\") op.execute(\"ALTER TABLE services_history ALTER" ]
[ "os.makedirs(os.path.join(dir)) except OSError as e: if e.errno != errno.EEXIST: print(\"Failed", "as f: f.write('---') f.write('\\n') f.write('draft: true') f.write('\\n') f.write('title: \\\"'+post_name+'\\\"') f.write('\\n')", "Post Name: ') date_time = datetime.now() date_time_dir = date_time.strftime(\"%Y-%m-%d\") date_time_post", "os import errno from datetime import datetime print(\"Generating A New", "p_name.replace(\"[\",\"\") p_name = p_name.replace(\"]\",\"\") p_name = p_name.lower() f_name = date_time_dir+\"---\"+p_name", "p_name.lower() f_name = date_time_dir+\"---\"+p_name dir = \"./src/pages/articles/\"+f_name+\"/\" f_dir = dir+f_name+\".md\"", "open(f_dir, 'w') as f: f.write('---') f.write('\\n') f.write('draft: true') f.write('\\n') f.write('title:", "'w') as f: f.write('---') f.write('\\n') f.write('draft: true') f.write('\\n') f.write('title: \\\"'+post_name+'\\\"')", "A New Post\\n\") post_name = input('Input Post Name: ') date_time", "f.write('date: \\\"'+date_time_post+'\\\"') f.write('\\n') f.write('layout: post') f.write('\\n') f.write('path: \\\"/posts/'+p_name+'/\\\"') f.write('\\n') f.write('category:", "f_name = date_time_dir+\"---\"+p_name dir = \"./src/pages/articles/\"+f_name+\"/\" f_dir = dir+f_name+\".md\" try:", "f.write('\\n') f.write('path: \\\"/posts/'+p_name+'/\\\"') f.write('\\n') f.write('category: \\\"\\\"') f.write('\\n') f.write('tags: ') f.write('\\n')", "= p_name.replace(\"]\",\"\") p_name = p_name.lower() f_name = date_time_dir+\"---\"+p_name dir =", "post_name.replace(\" \",\"-\") p_name = p_name.replace(\"[\",\"\") p_name = p_name.replace(\"]\",\"\") p_name =", "with open(f_dir, 'w') as f: f.write('---') f.write('\\n') f.write('draft: true') f.write('\\n')", "except OSError as e: if e.errno != errno.EEXIST: print(\"Failed to", "= datetime.now() date_time_dir = date_time.strftime(\"%Y-%m-%d\") date_time_post = date_time.strftime(\"%Y-%m-%d %H:%M:%S\") p_name", "= post_name.replace(\" \",\"-\") p_name = p_name.replace(\"[\",\"\") p_name = p_name.replace(\"]\",\"\") p_name", "f.write('\\n') f.write('tags: ') f.write('\\n') f.write('description: \"\"') f.write('\\n') f.write('---') f.write('\\n') print(\"Done", "f_dir = dir+f_name+\".md\" try: if not(os.path.isdir(dir)): os.makedirs(os.path.join(dir)) except OSError as", "= p_name.lower() f_name = date_time_dir+\"---\"+p_name dir = \"./src/pages/articles/\"+f_name+\"/\" f_dir =", "') date_time = datetime.now() date_time_dir = date_time.strftime(\"%Y-%m-%d\") date_time_post = date_time.strftime(\"%Y-%m-%d", "if e.errno != errno.EEXIST: print(\"Failed to create directory!!!!!\") raise print(\"Generating", "\",\"-\") p_name = p_name.replace(\"[\",\"\") p_name = p_name.replace(\"]\",\"\") p_name = p_name.lower()", "print(\"Failed to create directory!!!!!\") raise print(\"Generating post : \",f_dir) with", "f.write('path: \\\"/posts/'+p_name+'/\\\"') f.write('\\n') f.write('category: \\\"\\\"') f.write('\\n') f.write('tags: ') f.write('\\n') f.write('description:", "errno.EEXIST: print(\"Failed to create directory!!!!!\") raise print(\"Generating post : \",f_dir)", "print(\"Generating post : \",f_dir) with open(f_dir, 'w') as f: f.write('---')", "\\\"\\\"') f.write('\\n') f.write('tags: ') f.write('\\n') f.write('description: \"\"') f.write('\\n') f.write('---') f.write('\\n')", "true') f.write('\\n') f.write('title: \\\"'+post_name+'\\\"') f.write('\\n') f.write('date: \\\"'+date_time_post+'\\\"') f.write('\\n') f.write('layout: post')", "Name: ') date_time = datetime.now() date_time_dir = date_time.strftime(\"%Y-%m-%d\") date_time_post =", "\\\"'+date_time_post+'\\\"') f.write('\\n') f.write('layout: post') f.write('\\n') f.write('path: \\\"/posts/'+p_name+'/\\\"') f.write('\\n') f.write('category: \\\"\\\"')", "post : \",f_dir) with open(f_dir, 'w') as f: f.write('---') f.write('\\n')", "date_time = datetime.now() date_time_dir = date_time.strftime(\"%Y-%m-%d\") date_time_post = date_time.strftime(\"%Y-%m-%d %H:%M:%S\")", "f.write('draft: true') f.write('\\n') f.write('title: \\\"'+post_name+'\\\"') f.write('\\n') f.write('date: \\\"'+date_time_post+'\\\"') f.write('\\n') f.write('layout:", "= date_time_dir+\"---\"+p_name dir = \"./src/pages/articles/\"+f_name+\"/\" f_dir = dir+f_name+\".md\" try: if", "!= errno.EEXIST: print(\"Failed to create directory!!!!!\") raise print(\"Generating post :", "= \"./src/pages/articles/\"+f_name+\"/\" f_dir = dir+f_name+\".md\" try: if not(os.path.isdir(dir)): os.makedirs(os.path.join(dir)) except", "to create directory!!!!!\") raise print(\"Generating post : \",f_dir) with open(f_dir,", "= input('Input Post Name: ') date_time = datetime.now() date_time_dir =", "import errno from datetime import datetime print(\"Generating A New Post\\n\")", "= p_name.replace(\"[\",\"\") p_name = p_name.replace(\"]\",\"\") p_name = p_name.lower() f_name =", "errno from datetime import datetime print(\"Generating A New Post\\n\") post_name", "f.write('\\n') f.write('category: \\\"\\\"') f.write('\\n') f.write('tags: ') f.write('\\n') f.write('description: \"\"') f.write('\\n')", "datetime.now() date_time_dir = date_time.strftime(\"%Y-%m-%d\") date_time_post = date_time.strftime(\"%Y-%m-%d %H:%M:%S\") p_name =", "datetime print(\"Generating A New Post\\n\") post_name = input('Input Post Name:", "date_time_dir = date_time.strftime(\"%Y-%m-%d\") date_time_post = date_time.strftime(\"%Y-%m-%d %H:%M:%S\") p_name = post_name.replace(\"", "p_name.replace(\"]\",\"\") p_name = p_name.lower() f_name = date_time_dir+\"---\"+p_name dir = \"./src/pages/articles/\"+f_name+\"/\"", "OSError as e: if e.errno != errno.EEXIST: print(\"Failed to create", "date_time.strftime(\"%Y-%m-%d\") date_time_post = date_time.strftime(\"%Y-%m-%d %H:%M:%S\") p_name = post_name.replace(\" \",\"-\") p_name", "<gh_stars>0 import os import errno from datetime import datetime print(\"Generating", "= dir+f_name+\".md\" try: if not(os.path.isdir(dir)): os.makedirs(os.path.join(dir)) except OSError as e:", "raise print(\"Generating post : \",f_dir) with open(f_dir, 'w') as f:", "e.errno != errno.EEXIST: print(\"Failed to create directory!!!!!\") raise print(\"Generating post", "\\\"/posts/'+p_name+'/\\\"') f.write('\\n') f.write('category: \\\"\\\"') f.write('\\n') f.write('tags: ') f.write('\\n') f.write('description: \"\"')", "f.write('---') f.write('\\n') f.write('draft: true') f.write('\\n') f.write('title: \\\"'+post_name+'\\\"') f.write('\\n') f.write('date: \\\"'+date_time_post+'\\\"')", "\\\"'+post_name+'\\\"') f.write('\\n') f.write('date: \\\"'+date_time_post+'\\\"') f.write('\\n') f.write('layout: post') f.write('\\n') f.write('path: \\\"/posts/'+p_name+'/\\\"')", "p_name = p_name.replace(\"]\",\"\") p_name = p_name.lower() f_name = date_time_dir+\"---\"+p_name dir", "date_time.strftime(\"%Y-%m-%d %H:%M:%S\") p_name = post_name.replace(\" \",\"-\") p_name = p_name.replace(\"[\",\"\") p_name", "f.write('title: \\\"'+post_name+'\\\"') f.write('\\n') f.write('date: \\\"'+date_time_post+'\\\"') f.write('\\n') f.write('layout: post') f.write('\\n') f.write('path:", "%H:%M:%S\") p_name = post_name.replace(\" \",\"-\") p_name = p_name.replace(\"[\",\"\") p_name =", "e: if e.errno != errno.EEXIST: print(\"Failed to create directory!!!!!\") raise", "f.write('layout: post') f.write('\\n') f.write('path: \\\"/posts/'+p_name+'/\\\"') f.write('\\n') f.write('category: \\\"\\\"') f.write('\\n') f.write('tags:", "New Post\\n\") post_name = input('Input Post Name: ') date_time =", "post_name = input('Input Post Name: ') date_time = datetime.now() date_time_dir", "try: if not(os.path.isdir(dir)): os.makedirs(os.path.join(dir)) except OSError as e: if e.errno", "f.write('category: \\\"\\\"') f.write('\\n') f.write('tags: ') f.write('\\n') f.write('description: \"\"') f.write('\\n') f.write('---')", "f.write('tags: ') f.write('\\n') f.write('description: \"\"') f.write('\\n') f.write('---') f.write('\\n') print(\"Done :)\")", "date_time_dir+\"---\"+p_name dir = \"./src/pages/articles/\"+f_name+\"/\" f_dir = dir+f_name+\".md\" try: if not(os.path.isdir(dir)):", "= date_time.strftime(\"%Y-%m-%d\") date_time_post = date_time.strftime(\"%Y-%m-%d %H:%M:%S\") p_name = post_name.replace(\" \",\"-\")", "f: f.write('---') f.write('\\n') f.write('draft: true') f.write('\\n') f.write('title: \\\"'+post_name+'\\\"') f.write('\\n') f.write('date:", "print(\"Generating A New Post\\n\") post_name = input('Input Post Name: ')", ": \",f_dir) with open(f_dir, 'w') as f: f.write('---') f.write('\\n') f.write('draft:", "create directory!!!!!\") raise print(\"Generating post : \",f_dir) with open(f_dir, 'w')", "p_name = p_name.replace(\"[\",\"\") p_name = p_name.replace(\"]\",\"\") p_name = p_name.lower() f_name", "\"./src/pages/articles/\"+f_name+\"/\" f_dir = dir+f_name+\".md\" try: if not(os.path.isdir(dir)): os.makedirs(os.path.join(dir)) except OSError", "as e: if e.errno != errno.EEXIST: print(\"Failed to create directory!!!!!\")", "\",f_dir) with open(f_dir, 'w') as f: f.write('---') f.write('\\n') f.write('draft: true')", "datetime import datetime print(\"Generating A New Post\\n\") post_name = input('Input", "f.write('\\n') f.write('title: \\\"'+post_name+'\\\"') f.write('\\n') f.write('date: \\\"'+date_time_post+'\\\"') f.write('\\n') f.write('layout: post') f.write('\\n')", "date_time_post = date_time.strftime(\"%Y-%m-%d %H:%M:%S\") p_name = post_name.replace(\" \",\"-\") p_name =", "if not(os.path.isdir(dir)): os.makedirs(os.path.join(dir)) except OSError as e: if e.errno !=", "post') f.write('\\n') f.write('path: \\\"/posts/'+p_name+'/\\\"') f.write('\\n') f.write('category: \\\"\\\"') f.write('\\n') f.write('tags: ')", "not(os.path.isdir(dir)): os.makedirs(os.path.join(dir)) except OSError as e: if e.errno != errno.EEXIST:", "p_name = p_name.lower() f_name = date_time_dir+\"---\"+p_name dir = \"./src/pages/articles/\"+f_name+\"/\" f_dir", "p_name = post_name.replace(\" \",\"-\") p_name = p_name.replace(\"[\",\"\") p_name = p_name.replace(\"]\",\"\")", "f.write('\\n') f.write('layout: post') f.write('\\n') f.write('path: \\\"/posts/'+p_name+'/\\\"') f.write('\\n') f.write('category: \\\"\\\"') f.write('\\n')", "dir+f_name+\".md\" try: if not(os.path.isdir(dir)): os.makedirs(os.path.join(dir)) except OSError as e: if", "input('Input Post Name: ') date_time = datetime.now() date_time_dir = date_time.strftime(\"%Y-%m-%d\")", "= date_time.strftime(\"%Y-%m-%d %H:%M:%S\") p_name = post_name.replace(\" \",\"-\") p_name = p_name.replace(\"[\",\"\")", "dir = \"./src/pages/articles/\"+f_name+\"/\" f_dir = dir+f_name+\".md\" try: if not(os.path.isdir(dir)): os.makedirs(os.path.join(dir))", "f.write('\\n') f.write('date: \\\"'+date_time_post+'\\\"') f.write('\\n') f.write('layout: post') f.write('\\n') f.write('path: \\\"/posts/'+p_name+'/\\\"') f.write('\\n')", "import datetime print(\"Generating A New Post\\n\") post_name = input('Input Post", "Post\\n\") post_name = input('Input Post Name: ') date_time = datetime.now()", "directory!!!!!\") raise print(\"Generating post : \",f_dir) with open(f_dir, 'w') as", "from datetime import datetime print(\"Generating A New Post\\n\") post_name =", "f.write('\\n') f.write('draft: true') f.write('\\n') f.write('title: \\\"'+post_name+'\\\"') f.write('\\n') f.write('date: \\\"'+date_time_post+'\\\"') f.write('\\n')", "import os import errno from datetime import datetime print(\"Generating A" ]
[ "comment = \"\"\"H + CH3 -> CH4\"\"\" lindemann = Lindemann(", "other.label.lower() class TestReactionIsomorphism(unittest.TestCase): \"\"\" Contains unit tests of the isomorphism", "SphericalTopRotor from rmgpy.statmech.vibration import Vibration, HarmonicOscillator from rmgpy.statmech.torsion import Torsion,", "to each unit test in this class. \"\"\" ethylene =", "(Pmax,\"bar\"), comment = comment, ), ] original_kinetics = MultiPDepArrhenius( arrhenius", "Pmin = 1e-1 Pmax = 1e1 pressures = numpy.array([1e-1,1e1]) comment", "self.assertAlmostEqual(arrhenius.A.value_si, 2265.2488, delta=1e-2) self.assertAlmostEqual(arrhenius.n.value_si, 1.45419, delta=1e-4) self.assertAlmostEqual(arrhenius.Ea.value_si, 6645.24, delta=1e-2) #", "label): self.label = label def __repr__(self): return \"PseudoSpecies('{0}')\".format(self.label) def __str__(self):", "'2.38935e+09', '1709.76', '1.74189', '0.0314866', '0.00235045', '0.000389568', '0.000105413', '3.93273e-05', '1.83006e-05']] Kclist", "974.355, 1051.48, 1183.21, 1361.36, 1448.65, 1455.07, 1465.48, 2688.22, 2954.51, 3033.39,", "= label def __repr__(self): return \"PseudoSpecies('{0}')\".format(self.label) def __str__(self): return self.label", "1.0, 4) def testEquilibriumConstantKp(self): \"\"\" Test the Reaction.getEquilibriumConstant() method. \"\"\"", "in Tlist: self.assertAlmostEqual(self.reaction.getRateCoefficient(T, P) / self.reaction.kinetics.getRateCoefficient(T), 1.0, 6) def testGenerateReverseRateCoefficient(self):", ") original_kinetics = thirdBody self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient()", "= comment, ) original_kinetics = troe self.reaction2.kinetics = original_kinetics reverseKinetics", "method works for the ThirdBody format. \"\"\" from rmgpy.kinetics import", "'-137341', '-135155', '-133093', '-131150', '-129316']] Hlist = self.reaction2.getEnthalpiesOfReaction(Tlist) for i", "the Lindemann format. \"\"\" from rmgpy.kinetics import Lindemann arrheniusHigh =", "transition state theory k(T) calculation function, using the reaction H", "Reaction.hasTemplate() method. \"\"\" reactants = self.reaction.reactants[:] products = self.reaction.products[:] self.assertTrue(self.reaction.hasTemplate(reactants,", "'34272.7', '26.1877', '0.378696', '0.0235579', '0.00334673', '0.000792389', '0.000262777', '0.000110053']] Kalist =", "), ] original_kinetics = MultiArrhenius( arrhenius = arrhenius, Tmin =", "information. \"\"\" import cPickle reaction = cPickle.loads(cPickle.dumps(self.reaction,-1)) self.assertEqual(len(self.reaction.reactants), len(reaction.reactants)) self.assertEqual(len(self.reaction.products),", "self.assertFalse(dissociation.isIsomerization()) self.assertFalse(bimolecular.isIsomerization()) def testIsAssociation(self): \"\"\" Test the Reaction.isAssociation() method. \"\"\"", "krevrev, 1.0, 0) def testGenerateReverseRateCoefficientThirdBody(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method", "self.assertTrue(r1.isIsomorphic(self.makeReaction('dec=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cde=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=abc'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('abe=cde'))) class TestReaction(unittest.TestCase): \"\"\" Contains unit tests", "loss of information. \"\"\" import cPickle reaction = cPickle.loads(cPickle.dumps(self.reaction,-1)) self.assertEqual(len(self.reaction.reactants),", "0) def testGenerateReverseRateCoefficientThirdBody(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for", "n = 0.0, alpha = 0.5, E0 = (41.84, 'kJ/mol'),", "C[C]=O acetyl = Species( label='acetyl', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(15.5*constants.R,\"J/(mol*K)\"), a0=0.2541, a1=-0.4712, a2=-4.434,", "= -4.76, Ea = (10.21,\"kJ/mol\"), T0 = (1,\"K\"), ) efficiencies", "'cm^3/(mol*s)'), n = 0.0, Ea = (0.0, 'kJ/mol'), T0 =", "return self.label def isIsomorphic(self, other): return self.label.lower() == other.label.lower() class", "in ['-156.793', '-156.872', '-153.504', '-150.317', '-147.707', '-145.616', '-143.93', '-142.552', '-141.407',", "import Vibration, HarmonicOscillator from rmgpy.statmech.torsion import Torsion, HinderedRotor from rmgpy.statmech.conformer", "def testIsDissociation(self): \"\"\" Test the Reaction.isDissociation() method. \"\"\" isomerization =", "1, ), frequency = (-750.232, 'cm^-1'), ) self.reaction = Reaction(", "for v in ['-114648', '-83137.2', '-52092.4', '-21719.3', '8073.53', '37398.1', '66346.8',", "S0=(-12.19,\"J/(mol*K)\")), ) self.reaction2 = Reaction( reactants=[acetyl, oxygen], products=[acetylperoxy], kinetics =", "mass = (28.0313, 'amu'), ), NonlinearRotor( inertia = ( [3.41526,", "self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cd'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=dc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dc=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cd=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=ab'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=cde'))) def test2to3(self): r1 =", "= 1, ), HarmonicOscillator( frequencies = ( [482.224, 791.876, 974.355,", "testHasTemplate(self): \"\"\" Test the Reaction.hasTemplate() method. \"\"\" reactants = self.reaction.reactants[:]", "Check that the correct Arrhenius parameters are returned self.assertAlmostEqual(arrhenius.A.value_si, 2265.2488,", "0) def testGenerateReverseRateCoefficientMultiPDepArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for", "method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) P =", "[ Arrhenius( A = (9.3e-16,\"cm^3/(molecule*s)\"), n = 0.0, Ea =", "products = self.reaction.products[:] self.assertTrue(self.reaction.hasTemplate(reactants, products)) self.assertTrue(self.reaction.hasTemplate(products, reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants, products)) self.assertFalse(self.reaction2.hasTemplate(products,", "[float(v) for v in ['8.75951e+29', '7.1843e+10', '34272.7', '26.1877', '0.378696', '0.0235579',", "= (Tmax,\"K\"), comment = comment, ), Arrhenius( A = (1.4e-9,\"cm^3/(molecule*s)\"),", "HinderedRotor( inertia = (1.11481, 'amu*angstrom^2'), symmetry = 6, barrier =", "P) / self.reaction2.getEquilibriumConstant(T) kr = reverseKinetics.getRateCoefficient(T) self.assertAlmostEqual(kr0 / kr, 1.0,", "1, ), ) hydrogen = Species( label = 'H', conformer", "= (Tmin,\"K\"), Tmax = (Tmax,\"K\"), comment = comment, ), Arrhenius(", "HinderedRotor from rmgpy.statmech.conformer import Conformer from rmgpy.kinetics import Arrhenius from", "method works for the Lindemann format. \"\"\" from rmgpy.kinetics import", "= self.reaction2.generateReverseRateCoefficient() for T in Tlist: kr0 = self.reaction2.getRateCoefficient(T, P)", "products.reverse() self.assertTrue(self.reaction.hasTemplate(reactants, products)) self.assertTrue(self.reaction.hasTemplate(products, reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants, products)) self.assertFalse(self.reaction2.hasTemplate(products, reactants)) reactants", "products=products) def test1to1(self): r1 = self.makeReaction('A=B') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=B'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('b=A'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('B=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=C')))", "= [ethyl], kinetics = Arrhenius( A = (501366000.0, 'cm^3/(mol*s)'), n", "self.assertTrue(association.isAssociation()) self.assertFalse(dissociation.isAssociation()) self.assertFalse(bimolecular.isAssociation()) def testIsDissociation(self): \"\"\" Test the Reaction.isDissociation() method.", "T in Tlist: korig = original_kinetics.getRateCoefficient(T, P) krevrev = reversereverseKinetics.getRateCoefficient(T,", "n = 1.0, Ea = (20.0,\"kJ/mol\"), T0 = (300.0,\"K\"), Tmin", "comment = \"\"\"This data is completely made up\"\"\", ) pressures", "= lindemann self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics =", "= 2941 T2 = 6964 efficiencies = {\"C\": 3, \"C(=O)=O\":", "= 1, ), ) hydrogen = Species( label = 'H',", "Kplist0 = [float(v) for v in ['8.75951e+24', '718430', '0.342727', '0.000261877',", "C2H4 -> C2H5. \"\"\" Tlist = 1000.0/numpy.arange(0.4, 3.35, 0.01) klist", "(111.603, 'kJ/mol'), modes = [ IdealGasTranslation( mass = (29.0391, 'amu'),", "self.label def isIsomorphic(self, other): return self.label.lower() == other.label.lower() class TestReactionIsomorphism(unittest.TestCase):", "Tlist: self.assertAlmostEqual(self.reaction.getRateCoefficient(T, P) / self.reaction.kinetics.getRateCoefficient(T), 1.0, 6) def testGenerateReverseRateCoefficient(self): \"\"\"", "Test the Reaction.getEquilibriumConstant() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0,", "class TestReaction(unittest.TestCase): \"\"\" Contains unit tests of the Reaction class.", "a3=44.12, B=(500.0,\"K\"), H0=(1.453e+04,\"J/mol\"), S0=(-12.19,\"J/(mol*K)\")), ) self.reaction2 = Reaction( reactants=[acetyl, oxygen],", "'1.83006e-05']] Kclist = self.reaction2.getEquilibriumConstants(Tlist, type='Kc') for i in range(len(Tlist)): self.assertAlmostEqual(Kclist[i]", "reactants)) def testEnthalpyOfReaction(self): \"\"\" Test the Reaction.getEnthalpyOfReaction() method. \"\"\" Tlist", "1, opticalIsomers = 1, ), ) hydrogen = Species( label", "(pressures,\"bar\"), arrhenius = arrhenius, Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"),", "= MultiPDepArrhenius( arrhenius = arrhenius, Tmin = (Tmin,\"K\"), Tmax =", "1051.48, 1183.21, 1361.36, 1448.65, 1455.07, 1465.48, 2688.22, 2954.51, 3033.39, 3101.54,", "0.0, Ea = (0.0, 'kJ/mol'), T0 = (1, 'K'), Tmin", "= self.reaction.reactants[:] products = self.reaction.products[:] self.assertTrue(self.reaction.hasTemplate(reactants, products)) self.assertTrue(self.reaction.hasTemplate(products, reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants,", "import MultiArrhenius pressures = numpy.array([0.1, 10.0]) Tmin = 300.0 Tmax", "the Reaction.generateReverseRateCoefficient() method works for the MultiArrhenius format. \"\"\" from", "Tlist: kr0 = self.reaction2.getRateCoefficient(T, P) / self.reaction2.getEquilibriumConstant(T) kr = reverseKinetics.getRateCoefficient(T)", "within 5%) for i in range(len(Tlist)): self.assertAlmostEqual(klist[i], klist2[i], delta=5e-2 *", "len(reaction.products)) for reactant0, reactant in zip(self.reaction.reactants, reaction.reactants): self.assertAlmostEqual(reactant0.conformer.E0.value_si / 1e6,", "\"\"\"H + CH3 -> CH4\"\"\" troe = Troe( arrheniusHigh =", "range(len(Tlist)): self.assertAlmostEqual(Slist[i], Slist0[i], 2) def testFreeEnergyOfReaction(self): \"\"\" Test the Reaction.getFreeEnergyOfReaction()", "comment = \"\"\"H + CH3 -> CH4\"\"\" troe = Troe(", "'26.1877', '0.378696', '0.0235579', '0.00334673', '0.000792389', '0.000262777', '0.000110053']] Kalist = self.reaction2.getEquilibriumConstants(Tlist,", "method works for the MultiPDepArrhenius format. \"\"\" from rmgpy.kinetics import", "r1 = self.makeReaction('A=BC') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=Bc'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('cb=a'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('a=cb'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('bc=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('a=c'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=c'))) def", "the Reaction class. \"\"\" def setUp(self): \"\"\" A method that", "(containing PseudoSpecies) of from a string like 'Ab=CD' \"\"\" reactants,", "label = 'TS', conformer = Conformer( E0 = (266.694, 'kJ/mol'),", "Arrhenius( A = (1.4e-9,\"cm^3/(molecule*s)\"), n = 0.0, Ea = (11200*constants.R*0.001,\"kJ/mol\"),", "/ krevrev, 1.0, 0) def testTSTCalculation(self): \"\"\" A test of", "+ CH3 -> CH4\"\"\" thirdBody = ThirdBody( arrheniusLow = arrheniusLow,", "= Reaction( reactants = [hydrogen, ethylene], products = [ethyl], kinetics", "Test the Reaction.hasTemplate() method. \"\"\" reactants = self.reaction.reactants[:] products =", "up\"\"\", ) arrhenius1 = Arrhenius( A = (1.0e12,\"s^-1\"), n =", "1.0, 0) def testGenerateReverseRateCoefficientTroe(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works", "'K'), Tmax = (2000, 'K'), ), ) def testIsIsomerization(self): \"\"\"", "Pmax = (Pmax,\"bar\"), comment = comment, ), PDepArrhenius( pressures =", "), Arrhenius( A = (9.3e-14,\"cm^3/(molecule*s)\"), n = 0.0, Ea =", "works for the ThirdBody format. \"\"\" from rmgpy.kinetics import ThirdBody", "A = (9.3e-16,\"cm^3/(molecule*s)\"), n = 0.0, Ea = (4740*constants.R*0.001,\"kJ/mol\"), T0", "Tmax = 1500. Pmin = 1e-1 Pmax = 1e1 pressures", "in range(len(Tlist)): self.assertAlmostEqual(Hlist[i] / 1000., Hlist0[i] / 1000., 2) def", "5%) for i in range(len(Tlist)): self.assertAlmostEqual(klist[i], klist2[i], delta=5e-2 * klist[i])", "2001.0, 200.0, numpy.float64) Slist0 = [float(v) for v in ['-156.793',", "Tmax = (Tmax,\"K\"), comment = comment, ), ] original_kinetics =", "self.assertFalse(association.isIsomerization()) self.assertFalse(dissociation.isIsomerization()) self.assertFalse(bimolecular.isIsomerization()) def testIsAssociation(self): \"\"\" Test the Reaction.isAssociation() method.", "self.assertAlmostEqual(self.reaction.transitionState.conformer.E0.value_si / 1e6, reaction.transitionState.conformer.E0.value_si / 1e6, 2) self.assertEqual(self.reaction.transitionState.conformer.E0.units, reaction.transitionState.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.frequency.value_si,", "rmgpy.kinetics import PDepArrhenius arrhenius0 = Arrhenius( A = (1.0e6,\"s^-1\"), n", "= (2000, 'K'), ) self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient()", "'amu'), ), ], spinMultiplicity = 2, opticalIsomers = 1, ),", "= 2, opticalIsomers = 1, ), ) TS = TransitionState(", "ArrheniusEP( A = (2.65e12, 'cm^3/(mol*s)'), n = 0.0, alpha =", "4) def testStoichiometricCoefficient(self): \"\"\" Test the Reaction.getStoichiometricCoefficient() method. \"\"\" for", "'kJ/mol'), T0 = (1, 'K'), Tmin = (300, 'K'), Tmax", "= thirdBody self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics =", "2001.0, 200.0, numpy.float64) P = 1e5 for T in Tlist:", "A test of the transition state theory k(T) calculation function,", "for product0, product in zip(self.reaction.products, reaction.products): self.assertAlmostEqual(product0.conformer.E0.value_si / 1e6, product.conformer.E0.value_si", "yields the original Tlist = numpy.arange(original_kinetics.Tmin, original_kinetics.Tmax, 200.0, numpy.float64) P", "data is completely made up\"\"\" arrhenius = [ Arrhenius( A", "200.0, numpy.float64) P = 1e5 for T in Tlist: self.assertAlmostEqual(self.reaction.getRateCoefficient(T,", "T0 = (1,\"K\"), ) arrheniusLow = Arrhenius( A = (2.62e+33,\"cm^6/(mol^2*s)\"),", "with PseudoSpecies('A') but nothing else. \"\"\" def __init__(self, label): self.label", "1) for reactant in self.reaction2.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), 0) for product in", "3175.34, 3201.88], 'cm^-1', ), ), ], spinMultiplicity = 2, opticalIsomers", "successfully pickled and unpickled with no loss of information. \"\"\"", "import unittest from external.wip import work_in_progress from rmgpy.species import Species,", "\"\"\" from rmgpy.kinetics import Lindemann arrheniusHigh = Arrhenius( A =", "= comment, ), ], Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"),", "= (Tmin,\"K\"), Tmax = (Tmax,\"K\"), Pmin = (Pmin,\"bar\"), Pmax =", "(1, 'K'), Tmin = (300, 'K'), Tmax = (2000, 'K'),", "Test the Reaction.getStoichiometricCoefficient() method. \"\"\" for reactant in self.reaction.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant),", "2) def testEntropyOfReaction(self): \"\"\" Test the Reaction.getEntropyOfReaction() method. \"\"\" Tlist", "the Reaction.hasTemplate() method. \"\"\" reactants = self.reaction.reactants[:] products = self.reaction.products[:]", "testGenerateReverseRateCoefficientLindemann(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the Lindemann", "rmgpy.reaction module. \"\"\" import numpy import unittest from external.wip import", "= ( [6.78512, 22.1437, 22.2114], 'amu*angstrom^2', ), symmetry = 1,", "efficiencies = efficiencies, comment = comment, ) original_kinetics = troe", "__init__(self, label): self.label = label def __repr__(self): return \"PseudoSpecies('{0}')\".format(self.label) def", "original Tlist = numpy.arange(original_kinetics.Tmin.value_si, original_kinetics.Tmax.value_si, 200.0, numpy.float64) P = 1e5", "= reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) @work_in_progress def", "is completely made up\"\"\", ) arrhenius1 = Arrhenius( A =", "type='Kp') for i in range(len(Tlist)): self.assertAlmostEqual(Kplist[i] / Kplist0[i], 1.0, 4)", "self.reaction2.products, self.reaction2.reactants reversereverseKinetics = self.reaction2.generateReverseRateCoefficient() # check that reverting the", "def testOutput(self): \"\"\" Test that a Reaction object can be", "E0 = (44.7127, 'kJ/mol'), modes = [ IdealGasTranslation( mass =", "numpy.float64) Kalist0 = [float(v) for v in ['8.75951e+29', '7.1843e+10', '34272.7',", "self.assertAlmostEqual(arrhenius.n.value_si, 1.45419, delta=1e-4) self.assertAlmostEqual(arrhenius.Ea.value_si, 6645.24, delta=1e-2) # Check that the", "self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientMultiPDepArrhenius(self): \"\"\" Test the", "2001.0, 200.0, numpy.float64) Kclist0 = [float(v) for v in ['1.45661e+28',", "Glist0[i] / 1000., 2) def testEquilibriumConstantKa(self): \"\"\" Test the Reaction.getEquilibriumConstant()", "rmgpy.kinetics import PDepArrhenius, MultiPDepArrhenius Tmin = 350. Tmax = 1500.", "= arrhenius, Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), Pmin =", "self.assertEqual(self.reaction.kinetics.comment, reaction.kinetics.comment) self.assertEqual(self.reaction.duplicate, reaction.duplicate) self.assertEqual(self.reaction.degeneracy, reaction.degeneracy) ################################################################################ if __name__ ==", "\"\"\" Test the Reaction.generateReverseRateCoefficient() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0,", "works for the Troe format. \"\"\" from rmgpy.kinetics import Troe", "here as always within 5%) for i in range(len(Tlist)): self.assertAlmostEqual(klist[i],", "for i in products] return Reaction(reactants=reactants, products=products) def test1to1(self): r1", "be successfully reconstructed from its repr() output with no loss", "PseudoSpecies('a') is isomorphic with PseudoSpecies('A') but nothing else. \"\"\" def", "/ 1000., 2) def testEquilibriumConstantKa(self): \"\"\" Test the Reaction.getEquilibriumConstant() method.", "1000., Glist0[i] / 1000., 2) def testEquilibriumConstantKa(self): \"\"\" Test the", "(300.0,\"K\"), Tmin = (300.0,\"K\"), Tmax = (2000.0,\"K\"), comment = \"\"\"This", "import Reaction from rmgpy.statmech.translation import Translation, IdealGasTranslation from rmgpy.statmech.rotation import", "n = -0.534, Ea = (2.243,\"kJ/mol\"), T0 = (1,\"K\"), )", ") hydrogen = Species( label = 'H', conformer = Conformer(", "ThirdBody( arrheniusLow = arrheniusLow, Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"),", ") alpha = 0.783 T3 = 74 T1 = 2941", "import Conformer from rmgpy.kinetics import Arrhenius from rmgpy.thermo import Wilhoit", "Hlist0 = [float(v) for v in ['-146007', '-145886', '-144195', '-141973',", "= numpy.array([arrhenius.getRateCoefficient(T) for T in Tlist]) # Check that the", "Hlist = self.reaction2.getEnthalpiesOfReaction(Tlist) for i in range(len(Tlist)): self.assertAlmostEqual(Hlist[i] / 1000.,", "import Arrhenius from rmgpy.thermo import Wilhoit import rmgpy.constants as constants", "= comment, ), Arrhenius( A = (1.4e-9,\"cm^3/(molecule*s)\"), n = 0.0,", "Pmin = (Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), efficiencies = efficiencies, comment", "comment = 'CH3 + C2H6 <=> CH4 + C2H5 (Baulch", "barrier = (0.244029, 'kJ/mol'), semiclassical = None, ), ], spinMultiplicity", "], spinMultiplicity = 2, opticalIsomers = 1, ), ) TS", "efficiencies = {\"C\": 3, \"C(=O)=O\": 2, \"CC\": 3, \"O\": 6,", "def makeReaction(self,reaction_string): \"\"\"\" Make a Reaction (containing PseudoSpecies) of from", "= 1e-1 Pmax = 1e1 pressures = numpy.array([1e-1,1e1]) comment =", "testTSTCalculation(self): \"\"\" A test of the transition state theory k(T)", "self.assertTrue(self.reaction.hasTemplate(products, reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants, products)) self.assertFalse(self.reaction2.hasTemplate(products, reactants)) reactants.reverse() products.reverse() self.assertTrue(self.reaction.hasTemplate(reactants, products))", "arrhenius = [arrhenius0, arrhenius1] Tmin = 300.0 Tmax = 2000.0", "mass = (29.0391, 'amu'), ), NonlinearRotor( inertia = ( [4.8709,", "self.assertFalse(r1.isIsomorphic(self.makeReaction('cd=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=ab'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=cde'))) def test2to3(self): r1 = self.makeReaction('AB=CDE') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cde'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ba=edc'),eitherDirection=False))", ") TS = TransitionState( label = 'TS', conformer = Conformer(", "1455.06, 1600.35, 3101.46, 3110.55, 3175.34, 3201.88], 'cm^-1', ), ), ],", "1465.09, 1672.25, 3098.46, 3111.7, 3165.79, 3193.54], 'cm^-1', ), ), ],", "= Arrhenius( A = (501366000.0, 'cm^3/(mol*s)'), n = 1.637, Ea", "testGenerateReverseRateCoefficientArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the Arrhenius", "= (20.0,\"kJ/mol\"), T0 = (300.0,\"K\"), Tmin = (300.0,\"K\"), Tmax =", "= [ Arrhenius( A = (1.4e-11,\"cm^3/(molecule*s)\"), n = 0.0, Ea", "for product in self.reaction2.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 0) def testRateCoefficient(self): \"\"\" Test", "= 1e1 pressures = numpy.array([1e-1,1e1]) comment = 'CH3 + C2H6", "'-150.317', '-147.707', '-145.616', '-143.93', '-142.552', '-141.407', '-140.441']] Slist = self.reaction2.getEntropiesOfReaction(Tlist)", "original_kinetics = MultiArrhenius( arrhenius = arrhenius, Tmin = (Tmin,\"K\"), Tmax", "arrheniusLow = Arrhenius( A = (2.62e+33,\"cm^6/(mol^2*s)\"), n = -4.76, Ea", "TestReaction(unittest.TestCase): \"\"\" Contains unit tests of the Reaction class. \"\"\"", "'kJ/mol'), modes = [ IdealGasTranslation( mass = (1.00783, 'amu'), ),", "'K'), ) self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics =", "arrhenius = [ Arrhenius( A = (9.3e-16,\"cm^3/(molecule*s)\"), n = 0.0,", "mass = (29.0391, 'amu'), ), NonlinearRotor( inertia = ( [6.78512,", "IdealGasTranslation from rmgpy.statmech.rotation import Rotation, LinearRotor, NonlinearRotor, KRotor, SphericalTopRotor from", "P) krevrev = reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0)", "= reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientThirdBody(self):", "T2 = 6964 efficiencies = {\"C\": 3, \"C(=O)=O\": 2, \"CC\":", "be successfully pickled and unpickled with no loss of information.", "reactants.reverse() products.reverse() self.assertFalse(self.reaction.hasTemplate(reactants, products)) self.assertFalse(self.reaction.hasTemplate(products, reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants, products)) self.assertTrue(self.reaction2.hasTemplate(products, reactants))", "is correctly computed self.reaction2.reactants, self.reaction2.products = self.reaction2.products, self.reaction2.reactants reversereverseKinetics =", "= self.makeReaction('A=B') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=B'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('b=A'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('B=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=C'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=BB'))) def test1to2(self): r1", "2000.0 Pmin = 0.1 Pmax = 10.0 comment = \"\"\"This", "2) def testFreeEnergyOfReaction(self): \"\"\" Test the Reaction.getFreeEnergyOfReaction() method. \"\"\" Tlist", "import cPickle reaction = cPickle.loads(cPickle.dumps(self.reaction,-1)) self.assertEqual(len(self.reaction.reactants), len(reaction.reactants)) self.assertEqual(len(self.reaction.products), len(reaction.products)) for", "= PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius = arrhenius, Tmin =", "= efficiencies, comment = comment, ) original_kinetics = thirdBody self.reaction2.kinetics", "[ IdealGasTranslation( mass = (1.00783, 'amu'), ), ], spinMultiplicity =", "for v in ['1.45661e+28', '2.38935e+09', '1709.76', '1.74189', '0.0314866', '0.00235045', '0.000389568',", "S0=(-524.6,\"J/(mol*K)\")), ) # [O][O] oxygen = Species( label='oxygen', thermo=Wilhoit(Cp0=(3.5*constants.R,\"J/(mol*K)\"), CpInf=(4.5*constants.R,\"J/(mol*K)\"),", "'123383', '151565']] Glist = self.reaction2.getFreeEnergiesOfReaction(Tlist) for i in range(len(Tlist)): self.assertAlmostEqual(Glist[i]", "200.0, numpy.float64) Hlist0 = [float(v) for v in ['-146007', '-145886',", "opticalIsomers = 1, ), ) hydrogen = Species( label =", "= 300. Tmax = 2000. Pmin = 0.01 Pmax =", "thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(15.5*constants.R,\"J/(mol*K)\"), a0=0.2541, a1=-0.4712, a2=-4.434, a3=2.25, B=(500.0,\"K\"), H0=(-1.439e+05,\"J/mol\"), S0=(-524.6,\"J/(mol*K)\")), )", "method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Glist0 =", "(11200*constants.R*0.001,\"kJ/mol\"), T0 = (1,\"K\"), Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"),", "= [hydrogen, ethylene], products = [ethyl], kinetics = Arrhenius( A", "comment, ) original_kinetics = lindemann self.reaction2.kinetics = original_kinetics reverseKinetics =", "'amu*angstrom^2'), symmetry = 6, barrier = (0.244029, 'kJ/mol'), semiclassical =", "), NonlinearRotor( inertia = ( [3.41526, 16.6498, 20.065], 'amu*angstrom^2', ),", ") # CC(=O)O[O] acetylperoxy = Species( label='acetylperoxy', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(21.0*constants.R,\"J/(mol*K)\"), a0=-3.95,", "# CC(=O)O[O] acetylperoxy = Species( label='acetylperoxy', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(21.0*constants.R,\"J/(mol*K)\"), a0=-3.95, a1=9.26,", "Reaction.getEnthalpyOfReaction() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Hlist0", "the original Tlist = numpy.arange(original_kinetics.Tmin.value_si, original_kinetics.Tmax.value_si, 200.0, numpy.float64) P =", "= ArrheniusEP( A = (2.65e12, 'cm^3/(mol*s)'), n = 0.0, alpha", "'0.0314866', '0.00235045', '0.000389568', '0.000105413', '3.93273e-05', '1.83006e-05']] Kclist = self.reaction2.getEquilibriumConstants(Tlist, type='Kc')", "the Reaction.generateReverseRateCoefficient() method works for the Arrhenius format. \"\"\" original_kinetics", "the Reaction.generateReverseRateCoefficient() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64)", "correctly computed self.reaction2.reactants, self.reaction2.products = self.reaction2.products, self.reaction2.reactants reversereverseKinetics = self.reaction2.generateReverseRateCoefficient()", "4, ), HarmonicOscillator( frequencies = ( [828.397, 970.652, 977.223, 1052.93,", "Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kplist0 = [float(v) for", "i in range(len(Tlist)): self.assertAlmostEqual(klist[i], klist2[i], delta=5e-2 * klist[i]) def testPickle(self):", "= [float(v) for v in ['8.75951e+29', '7.1843e+10', '34272.7', '26.1877', '0.378696',", "= (Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), efficiencies = efficiencies, comment =", "test of the transition state theory k(T) calculation function, using", "reactants = [hydrogen, ethylene], products = [ethyl], kinetics = Arrhenius(", "reconstructed from its repr() output with no loss of information.", "\"\"\"\" Make a Reaction (containing PseudoSpecies) of from a string", "with no loss of information. \"\"\" import cPickle reaction =", "= (1.11481, 'amu*angstrom^2'), symmetry = 6, barrier = (0.244029, 'kJ/mol'),", "label = 'H', conformer = Conformer( E0 = (211.794, 'kJ/mol'),", "[6.78512, 22.1437, 22.2114], 'amu*angstrom^2', ), symmetry = 1, ), HarmonicOscillator(", "the isomorphism testing of the Reaction class. \"\"\" def makeReaction(self,reaction_string):", "3165.79, 3193.54], 'cm^-1', ), ), ], spinMultiplicity = 1, opticalIsomers", "n = 0.0, Ea = (0.0, 'kJ/mol'), T0 = (1,", "reverse reactants, products to ensure Keq is correctly computed self.reaction2.reactants,", "Kplist0[i], 1.0, 4) def testStoichiometricCoefficient(self): \"\"\" Test the Reaction.getStoichiometricCoefficient() method.", "delta=1e-6) self.assertEqual(self.reaction.kinetics.comment, reaction.kinetics.comment) self.assertEqual(self.reaction.duplicate, reaction.duplicate) self.assertEqual(self.reaction.degeneracy, reaction.degeneracy) ################################################################################ if __name__", "= [arrhenius0, arrhenius1] Tmin = 300.0 Tmax = 2000.0 Pmin", "\"\"\" from rmgpy.kinetics import PDepArrhenius, MultiPDepArrhenius Tmin = 350. Tmax", "def testStoichiometricCoefficient(self): \"\"\" Test the Reaction.getStoichiometricCoefficient() method. \"\"\" for reactant", "22.2114], 'amu*angstrom^2', ), symmetry = 1, ), HarmonicOscillator( frequencies =", "testPickle(self): \"\"\" Test that a Reaction object can be successfully", "in place of a :class:`rmg.species.Species` for isomorphism checks. PseudoSpecies('a') is", "rmgpy.kinetics import Lindemann arrheniusHigh = Arrhenius( A = (1.39e+16,\"cm^3/(mol*s)\"), n", "Test the Reaction.isAssociation() method. \"\"\" isomerization = Reaction(reactants=[Species()], products=[Species()]) association", "= Arrhenius( A = (1.39e+16,\"cm^3/(mol*s)\"), n = -0.534, Ea =", "in ['-146007', '-145886', '-144195', '-141973', '-139633', '-137341', '-135155', '-133093', '-131150',", "def __init__(self, label): self.label = label def __repr__(self): return \"PseudoSpecies('{0}')\".format(self.label)", "1367.56, 1465.09, 1672.25, 3098.46, 3111.7, 3165.79, 3193.54], 'cm^-1', ), ),", "= 'CH3 + C2H6 <=> CH4 + C2H5 (Baulch 2005)'", "completely made up\"\"\" original_kinetics = PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius", "= [float(v) for v in ['-156.793', '-156.872', '-153.504', '-150.317', '-147.707',", "= numpy.array([0.1, 10.0]) arrhenius = [arrhenius0, arrhenius1] Tmin = 300.0", "Kclist0 = [float(v) for v in ['1.45661e+28', '2.38935e+09', '1709.76', '1.74189',", "rmgpy.thermo import Wilhoit import rmgpy.constants as constants ################################################################################ class PseudoSpecies:", "Test the Reaction.generateReverseRateCoefficient() method works for the Lindemann format. \"\"\"", "opticalIsomers = 1, ), ) TS = TransitionState( label =", "dissociation = Reaction(reactants=[Species()], products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertFalse(isomerization.isDissociation()) self.assertFalse(association.isDissociation())", ") pressures = numpy.array([0.1, 10.0]) arrhenius = [arrhenius0, arrhenius1] Tmin", "self.assertAlmostEqual(Slist[i], Slist0[i], 2) def testFreeEnergyOfReaction(self): \"\"\" Test the Reaction.getFreeEnergyOfReaction() method.", "comment = comment, ), PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius =", "Species( label='acetylperoxy', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(21.0*constants.R,\"J/(mol*K)\"), a0=-3.95, a1=9.26, a2=-15.6, a3=8.55, B=(500.0,\"K\"), H0=(-6.151e+04,\"J/mol\"),", "P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientThirdBody(self): \"\"\" Test", "0) def testGenerateReverseRateCoefficientPDepArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for", "CH4\"\"\" lindemann = Lindemann( arrheniusHigh = arrheniusHigh, arrheniusLow = arrheniusLow,", "range(len(Tlist)): self.assertAlmostEqual(Kplist[i] / Kplist0[i], 1.0, 4) def testStoichiometricCoefficient(self): \"\"\" Test", "state theory k(T) calculation function, using the reaction H +", "= (266.694, 'kJ/mol'), modes = [ IdealGasTranslation( mass = (29.0391,", "1.0, 4) def testStoichiometricCoefficient(self): \"\"\" Test the Reaction.getStoichiometricCoefficient() method. \"\"\"", "0) def testGenerateReverseRateCoefficientArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for", "self.reaction2.getEquilibriumConstants(Tlist, type='Ka') for i in range(len(Tlist)): self.assertAlmostEqual(Kalist[i] / Kalist0[i], 1.0,", "= 350. Tmax = 1500. Pmin = 1e-1 Pmax =", "), ], spinMultiplicity = 1, opticalIsomers = 1, ), )", "T3 = (T3,\"K\"), T1 = (T1,\"K\"), T2 = (T2,\"K\"), Tmin", "for reactant0, reactant in zip(self.reaction.reactants, reaction.reactants): self.assertAlmostEqual(reactant0.conformer.E0.value_si / 1e6, reactant.conformer.E0.value_si", "def testGenerateReverseRateCoefficientPDepArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the", "ThirdBody format. \"\"\" from rmgpy.kinetics import ThirdBody arrheniusLow = Arrhenius(", "['1.45661e+28', '2.38935e+09', '1709.76', '1.74189', '0.0314866', '0.00235045', '0.000389568', '0.000105413', '3.93273e-05', '1.83006e-05']]", "= \"\"\"H + CH3 -> CH4\"\"\" thirdBody = ThirdBody( arrheniusLow", "isomorphic with PseudoSpecies('A') but nothing else. \"\"\" def __init__(self, label):", "100. comment = \"\"\"H + CH3 -> CH4\"\"\" thirdBody =", "original_kinetics = troe self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics", "arrhenius1 = Arrhenius( A = (1.0e12,\"s^-1\"), n = 1.0, Ea", "This module contains unit tests of the rmgpy.reaction module. \"\"\"", "[ PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius = [ Arrhenius( A", "v in ['-156.793', '-156.872', '-153.504', '-150.317', '-147.707', '-145.616', '-143.93', '-142.552',", "= (pressures,\"bar\"), arrhenius = [ Arrhenius( A = (9.3e-16,\"cm^3/(molecule*s)\"), n", "= 'TS', conformer = Conformer( E0 = (266.694, 'kJ/mol'), modes", "testGenerateReverseRateCoefficientPDepArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the PDepArrhenius", "Arrhenius( A = (1.4e-11,\"cm^3/(molecule*s)\"), n = 0.0, Ea = (11200*constants.R*0.001,\"kJ/mol\"),", "= (1, 'K'), Tmin = (300, 'K'), Tmax = (2000,", "'-145.616', '-143.93', '-142.552', '-141.407', '-140.441']] Slist = self.reaction2.getEntropiesOfReaction(Tlist) for i", "def __str__(self): return self.label def isIsomorphic(self, other): return self.label.lower() ==", "method works for the MultiArrhenius format. \"\"\" from rmgpy.kinetics import", "i in products] return Reaction(reactants=reactants, products=products) def test1to1(self): r1 =", "self.assertFalse(self.reaction2.hasTemplate(reactants, products)) self.assertFalse(self.reaction2.hasTemplate(products, reactants)) reactants = self.reaction2.reactants[:] products = self.reaction2.products[:]", "A = (2.62e+33,\"cm^6/(mol^2*s)\"), n = -4.76, Ea = (10.21,\"kJ/mol\"), T0", "791.876, 974.355, 1051.48, 1183.21, 1361.36, 1448.65, 1455.07, 1465.48, 2688.22, 2954.51,", "Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertFalse(isomerization.isAssociation()) self.assertTrue(association.isAssociation()) self.assertFalse(dissociation.isAssociation()) self.assertFalse(bimolecular.isAssociation()) def testIsDissociation(self): \"\"\" Test", "for the ArrheniusEP format. \"\"\" from rmgpy.kinetics import ArrheniusEP original_kinetics", "'-153.504', '-150.317', '-147.707', '-145.616', '-143.93', '-142.552', '-141.407', '-140.441']] Slist =", "from rmgpy.kinetics import ThirdBody arrheniusLow = Arrhenius( A = (2.62e+33,\"cm^6/(mol^2*s)\"),", "completely made up\"\"\", ) pressures = numpy.array([0.1, 10.0]) arrhenius =", "numpy.array([self.reaction.calculateTSTRateCoefficient(T) for T in Tlist]) arrhenius = Arrhenius().fitToData(Tlist, klist, kunits='m^3/(mol*s)')", "Reaction(reactants=[Species()], products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertFalse(isomerization.isAssociation()) self.assertTrue(association.isAssociation()) self.assertFalse(dissociation.isAssociation()) self.assertFalse(bimolecular.isAssociation())", "[3.41526, 16.6498, 20.065], 'amu*angstrom^2', ), symmetry = 4, ), HarmonicOscillator(", "opticalIsomers = 1, ), frequency = (-750.232, 'cm^-1'), ) self.reaction", "= 2, opticalIsomers = 1, ), ) ethyl = Species(", "1500. Pmin = 1e-1 Pmax = 1e1 pressures = numpy.array([1e-1,1e1])", ") self.reaction = Reaction( reactants = [hydrogen, ethylene], products =", "testIsDissociation(self): \"\"\" Test the Reaction.isDissociation() method. \"\"\" isomerization = Reaction(reactants=[Species()],", "efficiencies, comment = comment, ) original_kinetics = lindemann self.reaction2.kinetics =", "= alpha, T3 = (T3,\"K\"), T1 = (T1,\"K\"), T2 =", "a1=-0.4712, a2=-4.434, a3=2.25, B=(500.0,\"K\"), H0=(-1.439e+05,\"J/mol\"), S0=(-524.6,\"J/(mol*K)\")), ) # [O][O] oxygen", "symmetry = 1, ), HarmonicOscillator( frequencies = ( [482.224, 791.876,", "Arrhenius( A = (1.0e6,\"s^-1\"), n = 1.0, Ea = (10.0,\"kJ/mol\"),", "checks. PseudoSpecies('a') is isomorphic with PseudoSpecies('A') but nothing else. \"\"\"", "else. \"\"\" def __init__(self, label): self.label = label def __repr__(self):", "\"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the ThirdBody format.", "= (11200*constants.R*0.001,\"kJ/mol\"), T0 = (1,\"K\"), Tmin = (Tmin,\"K\"), Tmax =", "-> CH4\"\"\" thirdBody = ThirdBody( arrheniusLow = arrheniusLow, Tmin =", "import PDepArrhenius arrhenius0 = Arrhenius( A = (1.0e6,\"s^-1\"), n =", "is isomorphic with PseudoSpecies('A') but nothing else. \"\"\" def __init__(self,", "= Reaction(reactants=[Species()], products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertTrue(isomerization.isIsomerization()) self.assertFalse(association.isIsomerization()) self.assertFalse(dissociation.isIsomerization())", "Conformer( E0 = (211.794, 'kJ/mol'), modes = [ IdealGasTranslation( mass", "22.2353, 23.9925], 'amu*angstrom^2', ), symmetry = 1, ), HarmonicOscillator( frequencies", "= ( [482.224, 791.876, 974.355, 1051.48, 1183.21, 1361.36, 1448.65, 1455.07,", "alpha = 0.5, E0 = (41.84, 'kJ/mol'), Tmin = (300,", "MultiPDepArrhenius Tmin = 350. Tmax = 1500. Pmin = 1e-1", "\"\"\"H + CH3 -> CH4\"\"\" thirdBody = ThirdBody( arrheniusLow =", "ethyl = Species( label = 'C2H5', conformer = Conformer( E0", "Test the Reaction.isIsomerization() method. \"\"\" isomerization = Reaction(reactants=[Species()], products=[Species()]) association", "'amu*angstrom^2', ), symmetry = 1, ), HarmonicOscillator( frequencies = (", "= (1.4e-9,\"cm^3/(molecule*s)\"), n = 0.0, Ea = (11200*constants.R*0.001,\"kJ/mol\"), T0 =", "2000. Pmin = 0.01 Pmax = 100. comment = \"\"\"H", "0) def testGenerateReverseRateCoefficientMultiArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for", "= Reaction(reactants=[Species()], products=[Species()]) association = Reaction(reactants=[Species(),Species()], products=[Species()]) dissociation = Reaction(reactants=[Species()],", "\"\"\" def setUp(self): \"\"\" A method that is called prior", "pickled and unpickled with no loss of information. \"\"\" import", "self.reaction2.reactants, self.reaction2.products = self.reaction2.products, self.reaction2.reactants reversereverseKinetics = self.reaction2.generateReverseRateCoefficient() # check", "self.assertAlmostEqual(reactant0.conformer.E0.value_si / 1e6, reactant.conformer.E0.value_si / 1e6, 2) self.assertEqual(reactant0.conformer.E0.units, reactant.conformer.E0.units) for", "None, ), ], spinMultiplicity = 2, opticalIsomers = 1, ),", "reversereverseKinetics = self.reaction2.generateReverseRateCoefficient() # check that reverting the reverse yields", "P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientLindemann(self): \"\"\" Test", "unit tests of the Reaction class. \"\"\" def setUp(self): \"\"\"", "= Species( label='acetylperoxy', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(21.0*constants.R,\"J/(mol*K)\"), a0=-3.95, a1=9.26, a2=-15.6, a3=8.55, B=(500.0,\"K\"),", "self.assertFalse(isomerization.isAssociation()) self.assertTrue(association.isAssociation()) self.assertFalse(dissociation.isAssociation()) self.assertFalse(bimolecular.isAssociation()) def testIsDissociation(self): \"\"\" Test the Reaction.isDissociation()", "numpy.float64) Slist0 = [float(v) for v in ['-156.793', '-156.872', '-153.504',", "= 0.0, Ea = (0.0, 'kJ/mol'), T0 = (1, 'K'),", "def testIsAssociation(self): \"\"\" Test the Reaction.isAssociation() method. \"\"\" isomerization =", "reverse yields the original Tlist = numpy.arange(Tmin, Tmax, 200.0, numpy.float64)", "Test the Reaction.isDissociation() method. \"\"\" isomerization = Reaction(reactants=[Species()], products=[Species()]) association", "self.assertAlmostEqual(Hlist[i] / 1000., Hlist0[i] / 1000., 2) def testEntropyOfReaction(self): \"\"\"", "that reverting the reverse yields the original Tlist = numpy.arange(original_kinetics.Tmin.value_si,", "= 1, ), frequency = (-750.232, 'cm^-1'), ) self.reaction =", "NonlinearRotor( inertia = ( [3.41526, 16.6498, 20.065], 'amu*angstrom^2', ), symmetry", "repr() output with no loss of information. \"\"\" exec('reaction =", "= (1,\"K\"), ) arrheniusLow = Arrhenius( A = (2.62e+33,\"cm^6/(mol^2*s)\"), n", "# [O][O] oxygen = Species( label='oxygen', thermo=Wilhoit(Cp0=(3.5*constants.R,\"J/(mol*K)\"), CpInf=(4.5*constants.R,\"J/(mol*K)\"), a0=-0.9324, a1=26.18,", "= (300, 'K'), Tmax = (2000, 'K'), ), ) def", "= 1e5 for T in Tlist: korig = original_kinetics.getRateCoefficient(T, P)", "Ea = (4.32508, 'kJ/mol'), T0 = (1, 'K'), Tmin =", "information. \"\"\" exec('reaction = %r' % (self.reaction)) self.assertEqual(len(self.reaction.reactants), len(reaction.reactants)) self.assertEqual(len(self.reaction.products),", "of the Reaction class. \"\"\" def setUp(self): \"\"\" A method", "(1.11481, 'amu*angstrom^2'), symmetry = 6, barrier = (0.244029, 'kJ/mol'), semiclassical", "Arrhenius( A = (1.0e12,\"s^-1\"), n = 1.0, Ea = (20.0,\"kJ/mol\"),", "( [828.397, 970.652, 977.223, 1052.93, 1233.55, 1367.56, 1465.09, 1672.25, 3098.46,", "ThirdBody arrheniusLow = Arrhenius( A = (2.62e+33,\"cm^6/(mol^2*s)\"), n = -4.76,", "Arrhenius parameters are returned self.assertAlmostEqual(arrhenius.A.value_si, 2265.2488, delta=1e-2) self.assertAlmostEqual(arrhenius.n.value_si, 1.45419, delta=1e-4)", "Reaction.getEntropyOfReaction() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Slist0", "reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientLindemann(self): \"\"\"", "cPickle reaction = cPickle.loads(cPickle.dumps(self.reaction,-1)) self.assertEqual(len(self.reaction.reactants), len(reaction.reactants)) self.assertEqual(len(self.reaction.products), len(reaction.products)) for reactant0,", "= (2000.0,\"K\"), comment = \"\"\"This data is completely made up\"\"\",", "r1 = self.makeReaction('AB=CDE') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cde'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ba=edc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dec=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cde=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=abc'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('abe=cde'))) class", "self.assertAlmostEqual(self.reaction.kinetics.T0.value_si, reaction.kinetics.T0.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.Ea.value_si, reaction.kinetics.Ea.value_si, delta=1e-6) self.assertEqual(self.reaction.kinetics.comment, reaction.kinetics.comment) self.assertEqual(self.reaction.duplicate, reaction.duplicate)", "(9.3e-16,\"cm^3/(molecule*s)\"), n = 0.0, Ea = (4740*constants.R*0.001,\"kJ/mol\"), T0 = (1,\"K\"),", "16.6498, 20.065], 'amu*angstrom^2', ), symmetry = 4, ), HarmonicOscillator( frequencies", "Keq is correctly computed self.reaction2.reactants, self.reaction2.products = self.reaction2.products, self.reaction2.reactants reversereverseKinetics", "\"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Hlist0 = [float(v)", "Species( label='acetyl', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(15.5*constants.R,\"J/(mol*K)\"), a0=0.2541, a1=-0.4712, a2=-4.434, a3=2.25, B=(500.0,\"K\"), H0=(-1.439e+05,\"J/mol\"),", "yields the original Tlist = numpy.arange(Tmin, Tmax, 200.0, numpy.float64) P", "is completely made up\"\"\" arrhenius = [ Arrhenius( A =", "pressures = numpy.array([1e-1,1e1]) comment = 'CH3 + C2H6 <=> CH4", "2001.0, 200.0, numpy.float64) Hlist0 = [float(v) for v in ['-146007',", "Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), comment = comment, )", "original_kinetics = Arrhenius( A = (2.65e12, 'cm^3/(mol*s)'), n = 0.0,", "= comment, ) self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics", "bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertFalse(isomerization.isAssociation()) self.assertTrue(association.isAssociation()) self.assertFalse(dissociation.isAssociation()) self.assertFalse(bimolecular.isAssociation()) def testIsDissociation(self):", "products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertFalse(isomerization.isAssociation()) self.assertTrue(association.isAssociation()) self.assertFalse(dissociation.isAssociation()) self.assertFalse(bimolecular.isAssociation()) def", "krevrev, 1.0, 0) def testGenerateReverseRateCoefficientLindemann(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method", "Species( label = 'C2H5', conformer = Conformer( E0 = (111.603,", "(-750.232, 'cm^-1'), ) self.reaction = Reaction( reactants = [hydrogen, ethylene],", "= self.reaction.products[:] self.assertTrue(self.reaction.hasTemplate(reactants, products)) self.assertTrue(self.reaction.hasTemplate(products, reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants, products)) self.assertFalse(self.reaction2.hasTemplate(products, reactants))", "self.reaction.kinetics.getRateCoefficient(T), 1.0, 6) def testGenerateReverseRateCoefficient(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method.", "= numpy.arange(original_kinetics.Tmin.value_si, original_kinetics.Tmax.value_si, 200.0, numpy.float64) P = 1e5 for T", "Tlist: korig = original_kinetics.getRateCoefficient(T, P) krevrev = reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig", "/ Kplist0[i], 1.0, 4) def testStoichiometricCoefficient(self): \"\"\" Test the Reaction.getStoichiometricCoefficient()", "for i in range(len(Tlist)): self.assertAlmostEqual(Hlist[i] / 1000., Hlist0[i] / 1000.,", "Slist0 = [float(v) for v in ['-156.793', '-156.872', '-153.504', '-150.317',", "in self.reaction2.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), 0) for product in self.reaction2.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 0)", "= comment, ), ] original_kinetics = MultiArrhenius( arrhenius = arrhenius,", "ensure Keq is correctly computed self.reaction2.reactants, self.reaction2.products = self.reaction2.products, self.reaction2.reactants", "krevrev = reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) @work_in_progress", "= reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testTSTCalculation(self):", "Pmin = (Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), comment = comment, ),", "comment = \"\"\"This data is completely made up\"\"\" original_kinetics =", "k(T) calculation function, using the reaction H + C2H4 ->", "3.35, 0.01) klist = numpy.array([self.reaction.calculateTSTRateCoefficient(T) for T in Tlist]) arrhenius", "class TestReactionIsomorphism(unittest.TestCase): \"\"\" Contains unit tests of the isomorphism testing", "self.assertFalse(bimolecular.isIsomerization()) def testIsAssociation(self): \"\"\" Test the Reaction.isAssociation() method. \"\"\" isomerization", "2001.0, 200.0, numpy.float64) P = 1e5 reverseKinetics = self.reaction2.generateReverseRateCoefficient() for", "'0.000389568', '0.000105413', '3.93273e-05', '1.83006e-05']] Kclist = self.reaction2.getEquilibriumConstants(Tlist, type='Kc') for i", "Arrhenius( A = (2.62e+33,\"cm^6/(mol^2*s)\"), n = -4.76, Ea = (10.21,\"kJ/mol\"),", "self.assertFalse(bimolecular.isAssociation()) def testIsDissociation(self): \"\"\" Test the Reaction.isDissociation() method. \"\"\" isomerization", "numpy.arange(Tmin, Tmax, 200.0, numpy.float64) P = 1e5 for T in", "\"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the Troe format.", "self.assertTrue(r1.isIsomorphic(self.makeReaction('cb=a'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('a=cb'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('bc=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('a=c'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=c'))) def test2to2(self): r1 = self.makeReaction('AB=CD')", "self.label = label def __repr__(self): return \"PseudoSpecies('{0}')\".format(self.label) def __str__(self): return", "the Reaction.generateReverseRateCoefficient() method works for the Lindemann format. \"\"\" from", "original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics = reverseKinetics # reverse reactants,", "Conformer from rmgpy.kinetics import Arrhenius from rmgpy.thermo import Wilhoit import", "reaction.transitionState.frequency.value_si, 2) self.assertEqual(self.reaction.transitionState.frequency.units, reaction.transitionState.frequency.units) self.assertAlmostEqual(self.reaction.kinetics.A.value_si, reaction.kinetics.A.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.n.value_si, reaction.kinetics.n.value_si, delta=1e-6)", "reaction.kinetics.Ea.value_si, delta=1e-6) self.assertEqual(self.reaction.kinetics.comment, reaction.kinetics.comment) self.assertEqual(self.reaction.duplicate, reaction.duplicate) self.assertEqual(self.reaction.degeneracy, reaction.degeneracy) def testOutput(self):", "1448.65, 1455.07, 1465.48, 2688.22, 2954.51, 3033.39, 3101.54, 3204.73], 'cm^-1', ),", "= 1e5 reverseKinetics = self.reaction2.generateReverseRateCoefficient() for T in Tlist: kr0", "for the Arrhenius format. \"\"\" original_kinetics = Arrhenius( A =", "def __repr__(self): return \"PseudoSpecies('{0}')\".format(self.label) def __str__(self): return self.label def isIsomorphic(self,", "arrheniusLow = arrheniusLow, Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), Pmin", "'cm^3/(mol*s)'), n = 0.0, alpha = 0.5, E0 = (41.84,", "krevrev, 1.0, 0) def testGenerateReverseRateCoefficientPDepArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method", "(Tmax,\"K\"), comment = comment, ), ] original_kinetics = MultiArrhenius( arrhenius", "= [ Arrhenius( A = (9.3e-16,\"cm^3/(molecule*s)\"), n = 0.0, Ea", "'0.378696', '0.0235579', '0.00334673', '0.000792389', '0.000262777', '0.000110053']] Kalist = self.reaction2.getEquilibriumConstants(Tlist, type='Ka')", "= arrheniusLow, Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), Pmin =", "), ) ethyl = Species( label = 'C2H5', conformer =", "products=[Species(),Species()]) self.assertFalse(isomerization.isAssociation()) self.assertTrue(association.isAssociation()) self.assertFalse(dissociation.isAssociation()) self.assertFalse(bimolecular.isAssociation()) def testIsDissociation(self): \"\"\" Test the", "/ krevrev, 1.0, 0) def testGenerateReverseRateCoefficientMultiPDepArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient()", "200.0, numpy.float64) P = 1e5 for T in Tlist: korig", "alpha, T3 = (T3,\"K\"), T1 = (T1,\"K\"), T2 = (T2,\"K\"),", "= (Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), comment = comment, ), PDepArrhenius(", "efficiencies, comment = comment, ) original_kinetics = thirdBody self.reaction2.kinetics =", "= (2.65e12, 'cm^3/(mol*s)'), n = 0.0, alpha = 0.5, E0", "= TransitionState( label = 'TS', conformer = Conformer( E0 =", "testIsIsomerization(self): \"\"\" Test the Reaction.isIsomerization() method. \"\"\" isomerization = Reaction(reactants=[Species()],", "(Tmax,\"K\"), comment = comment, ) self.reaction2.kinetics = original_kinetics reverseKinetics =", "reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testTSTCalculation(self): \"\"\"", "'-133093', '-131150', '-129316']] Hlist = self.reaction2.getEnthalpiesOfReaction(Tlist) for i in range(len(Tlist)):", "for i in range(len(Tlist)): self.assertAlmostEqual(Kalist[i] / Kalist0[i], 1.0, 4) def", "PseudoSpecies: \"\"\" Can be used in place of a :class:`rmg.species.Species`", "= MultiArrhenius( arrhenius = arrhenius, Tmin = (Tmin,\"K\"), Tmax =", "(0.244029, 'kJ/mol'), semiclassical = None, ), ], spinMultiplicity = 2,", "= (T3,\"K\"), T1 = (T1,\"K\"), T2 = (T2,\"K\"), Tmin =", "original_kinetics = thirdBody self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics", "Kclist0[i], 1.0, 4) def testEquilibriumConstantKp(self): \"\"\" Test the Reaction.getEquilibriumConstant() method.", "is satisfactory (defined here as always within 5%) for i", "<=> CH4 + C2H5 (Baulch 2005)' arrhenius = [ PDepArrhenius(", "0.5, E0 = (41.84, 'kJ/mol'), Tmin = (300, 'K'), Tmax", "100. comment = \"\"\"H + CH3 -> CH4\"\"\" troe =", "Ea = (10.21,\"kJ/mol\"), T0 = (1,\"K\"), ) alpha = 0.783", "is completely made up\"\"\", ) pressures = numpy.array([0.1, 10.0]) arrhenius", "), ) TS = TransitionState( label = 'TS', conformer =", "'K'), Tmin = (300, 'K'), Tmax = (2000, 'K'), )", "self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=cde'))) def test2to3(self): r1 = self.makeReaction('AB=CDE') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cde'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ba=edc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dec=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cde=ab'),eitherDirection=False))", "comment = comment, ) original_kinetics = lindemann self.reaction2.kinetics = original_kinetics", "74 T1 = 2941 T2 = 6964 efficiencies = {\"C\":", "= self.reaction2.generateReverseRateCoefficient() # check that reverting the reverse yields the", "original_kinetics = ArrheniusEP( A = (2.65e12, 'cm^3/(mol*s)'), n = 0.0,", "r1 = self.makeReaction('A=B') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=B'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('b=A'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('B=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=C'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=BB'))) def test1to2(self):", "def testRateCoefficient(self): \"\"\" Test the Reaction.getRateCoefficient() method. \"\"\" Tlist =", "n = 1.0, Ea = (10.0,\"kJ/mol\"), T0 = (300.0,\"K\"), Tmin", "[float(v) for v in ['-114648', '-83137.2', '-52092.4', '-21719.3', '8073.53', '37398.1',", "'3.78696e-06', '2.35579e-07', '3.34673e-08', '7.92389e-09', '2.62777e-09', '1.10053e-09']] Kplist = self.reaction2.getEquilibriumConstants(Tlist, type='Kp')", "Reaction(reactants=[Species(),Species()], products=[Species()]) dissociation = Reaction(reactants=[Species()], products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()])", "/ krevrev, 1.0, 0) def testGenerateReverseRateCoefficientPDepArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient()", "'TS', conformer = Conformer( E0 = (266.694, 'kJ/mol'), modes =", "# Check that the correct Arrhenius parameters are returned self.assertAlmostEqual(arrhenius.A.value_si,", "= comment, ), PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius = [", "= 6, barrier = (0.244029, 'kJ/mol'), semiclassical = None, ),", "Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertTrue(isomerization.isIsomerization()) self.assertFalse(association.isIsomerization()) self.assertFalse(dissociation.isIsomerization()) self.assertFalse(bimolecular.isIsomerization()) def testIsAssociation(self): \"\"\" Test", "(T3,\"K\"), T1 = (T1,\"K\"), T2 = (T2,\"K\"), Tmin = (Tmin,\"K\"),", "= (Tmax,\"K\"), Pmin = (Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), efficiencies =", "inertia = ( [6.78512, 22.1437, 22.2114], 'amu*angstrom^2', ), symmetry =", "string like 'Ab=CD' \"\"\" reactants, products = reaction_string.split('=') reactants =", "(Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), comment = comment, ), PDepArrhenius( pressures", "Pmin = 0.1 Pmax = 10.0 comment = \"\"\"This data", "= [ IdealGasTranslation( mass = (1.00783, 'amu'), ), ], spinMultiplicity", "numpy.float64) Hlist0 = [float(v) for v in ['-146007', '-145886', '-144195',", "test2to2(self): r1 = self.makeReaction('AB=CD') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cd'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=dc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dc=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cd=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=ab'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=cde')))", "TestReactionIsomorphism(unittest.TestCase): \"\"\" Contains unit tests of the isomorphism testing of", "self.assertFalse(self.reaction.hasTemplate(reactants, products)) self.assertFalse(self.reaction.hasTemplate(products, reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants, products)) self.assertTrue(self.reaction2.hasTemplate(products, reactants)) reactants.reverse() products.reverse()", "testGenerateReverseRateCoefficientArrheniusEP(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the ArrheniusEP", "(Tmin,\"K\"), Tmax = (Tmax,\"K\"), comment = comment, ), ] original_kinetics", "HarmonicOscillator( frequencies = ( [828.397, 970.652, 977.223, 1052.93, 1233.55, 1367.56,", "= (41.84, 'kJ/mol'), Tmin = (300, 'K'), Tmax = (2000,", "import Rotation, LinearRotor, NonlinearRotor, KRotor, SphericalTopRotor from rmgpy.statmech.vibration import Vibration,", "#!/usr/bin/env python # encoding: utf-8 -*- \"\"\" This module contains", "in self.reaction2.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 0) def testRateCoefficient(self): \"\"\" Test the Reaction.getRateCoefficient()", "'151565']] Glist = self.reaction2.getFreeEnergiesOfReaction(Tlist) for i in range(len(Tlist)): self.assertAlmostEqual(Glist[i] /", "delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.n.value_si, reaction.kinetics.n.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.T0.value_si, reaction.kinetics.T0.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.Ea.value_si, reaction.kinetics.Ea.value_si, delta=1e-6)", "semiclassical = None, ), ], spinMultiplicity = 2, opticalIsomers =", "r1 = self.makeReaction('AB=CD') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cd'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=dc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dc=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cd=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=ab'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=cde'))) def", "3193.54], 'cm^-1', ), ), ], spinMultiplicity = 1, opticalIsomers =", "/ kr, 1.0, 0) def testGenerateReverseRateCoefficientArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient()", "2941 T2 = 6964 efficiencies = {\"C\": 3, \"C(=O)=O\": 2,", "work_in_progress from rmgpy.species import Species, TransitionState from rmgpy.reaction import Reaction", "rmgpy.constants as constants ################################################################################ class PseudoSpecies: \"\"\" Can be used", "6964 efficiencies = {\"C\": 3, \"C(=O)=O\": 2, \"CC\": 3, \"O\":", "kinetics = Arrhenius( A = (501366000.0, 'cm^3/(mol*s)'), n = 1.637,", "P = 1e5 for T in Tlist: korig = original_kinetics.getRateCoefficient(T,", "\"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the Lindemann format.", "), HarmonicOscillator( frequencies = ( [482.224, 791.876, 974.355, 1051.48, 1183.21,", "P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientTroe(self): \"\"\" Test", "Tmax = (2500, 'K'), ), transitionState = TS, ) #", "Torsion, HinderedRotor from rmgpy.statmech.conformer import Conformer from rmgpy.kinetics import Arrhenius", "isomorphism checks. PseudoSpecies('a') is isomorphic with PseudoSpecies('A') but nothing else.", "for i in range(len(Tlist)): self.assertAlmostEqual(Slist[i], Slist0[i], 2) def testFreeEnergyOfReaction(self): \"\"\"", "is completely made up\"\"\" original_kinetics = PDepArrhenius( pressures = (pressures,\"bar\"),", "( [412.75, 415.206, 821.495, 924.44, 982.714, 1024.16, 1224.21, 1326.36, 1455.06,", "products = self.reaction2.products[:] self.assertFalse(self.reaction.hasTemplate(reactants, products)) self.assertFalse(self.reaction.hasTemplate(products, reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants, products)) self.assertTrue(self.reaction2.hasTemplate(products,", "arrhenius = Arrhenius().fitToData(Tlist, klist, kunits='m^3/(mol*s)') klist2 = numpy.array([arrhenius.getRateCoefficient(T) for T", "a2=-15.6, a3=8.55, B=(500.0,\"K\"), H0=(-6.151e+04,\"J/mol\"), S0=(-790.2,\"J/(mol*K)\")), ) # C[C]=O acetyl =", "the transition state theory k(T) calculation function, using the reaction", "= [ PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius = [ Arrhenius(", "821.495, 924.44, 982.714, 1024.16, 1224.21, 1326.36, 1455.06, 1600.35, 3101.46, 3110.55,", "1.637, Ea = (4.32508, 'kJ/mol'), T0 = (1, 'K'), Tmin", "Troe format. \"\"\" from rmgpy.kinetics import Troe arrheniusHigh = Arrhenius(", "1e5 reverseKinetics = self.reaction2.generateReverseRateCoefficient() for T in Tlist: kr0 =", "Tmin = 350. Tmax = 1500. Pmin = 1e-1 Pmax", "= (2000, 'K'), ), ) def testIsIsomerization(self): \"\"\" Test the", "= \"\"\"This data is completely made up\"\"\" original_kinetics = PDepArrhenius(", "spinMultiplicity = 2, opticalIsomers = 1, ), ) ethyl =", "testing of the Reaction class. \"\"\" def makeReaction(self,reaction_string): \"\"\"\" Make", "krevrev, 1.0, 0) def testTSTCalculation(self): \"\"\" A test of the", "method. \"\"\" for reactant in self.reaction.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), -1) for product", "self.reaction.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), -1) for product in self.reaction.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 1) for", "'kJ/mol'), modes = [ IdealGasTranslation( mass = (29.0391, 'amu'), ),", "always within 5%) for i in range(len(Tlist)): self.assertAlmostEqual(klist[i], klist2[i], delta=5e-2", "= [float(v) for v in ['8.75951e+24', '718430', '0.342727', '0.000261877', '3.78696e-06',", "self.assertTrue(r1.isIsomorphic(self.makeReaction('a=cb'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('bc=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('a=c'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=c'))) def test2to2(self): r1 = self.makeReaction('AB=CD') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cd')))", "for i in range(len(Tlist)): self.assertAlmostEqual(klist[i], klist2[i], delta=5e-2 * klist[i]) def", "(29.0391, 'amu'), ), NonlinearRotor( inertia = ( [4.8709, 22.2353, 23.9925],", "/ 1e6, product.conformer.E0.value_si / 1e6, 2) self.assertEqual(product0.conformer.E0.units, product.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.conformer.E0.value_si /", "A = (501366000.0, 'cm^3/(mol*s)'), n = 1.637, Ea = (4.32508,", "/ Kclist0[i], 1.0, 4) def testEquilibriumConstantKp(self): \"\"\" Test the Reaction.getEquilibriumConstant()", "class. \"\"\" def setUp(self): \"\"\" A method that is called", "= (29.0391, 'amu'), ), NonlinearRotor( inertia = ( [4.8709, 22.2353,", "'cm^-1'), ) self.reaction = Reaction( reactants = [hydrogen, ethylene], products", "A = (9.3e-14,\"cm^3/(molecule*s)\"), n = 0.0, Ea = (4740*constants.R*0.001,\"kJ/mol\"), T0", "\"\"\" Tlist = 1000.0/numpy.arange(0.4, 3.35, 0.01) klist = numpy.array([self.reaction.calculateTSTRateCoefficient(T) for", "reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) @work_in_progress def testGenerateReverseRateCoefficientArrheniusEP(self):", "6, barrier = (0.244029, 'kJ/mol'), semiclassical = None, ), ],", "self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), -1) for product in self.reaction.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 1) for reactant", "calculation function, using the reaction H + C2H4 -> C2H5.", "'cm^-1', ), ), HinderedRotor( inertia = (1.11481, 'amu*angstrom^2'), symmetry =", "reaction = cPickle.loads(cPickle.dumps(self.reaction,-1)) self.assertEqual(len(self.reaction.reactants), len(reaction.reactants)) self.assertEqual(len(self.reaction.products), len(reaction.products)) for reactant0, reactant", "= (300.0,\"K\"), Tmin = (300.0,\"K\"), Tmax = (2000.0,\"K\"), comment =", "3098.46, 3111.7, 3165.79, 3193.54], 'cm^-1', ), ), ], spinMultiplicity =", "(4740*constants.R*0.001,\"kJ/mol\"), T0 = (1,\"K\"), Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"),", "reaction.kinetics.A.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.n.value_si, reaction.kinetics.n.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.T0.value_si, reaction.kinetics.T0.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.Ea.value_si, reaction.kinetics.Ea.value_si,", "= numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Hlist0 = [float(v) for v", "(2.243,\"kJ/mol\"), T0 = (1,\"K\"), ) arrheniusLow = Arrhenius( A =", "[4.8709, 22.2353, 23.9925], 'amu*angstrom^2', ), symmetry = 1, ), HarmonicOscillator(", "'-140.441']] Slist = self.reaction2.getEntropiesOfReaction(Tlist) for i in range(len(Tlist)): self.assertAlmostEqual(Slist[i], Slist0[i],", "T in Tlist: kr0 = self.reaction2.getRateCoefficient(T, P) / self.reaction2.getEquilibriumConstant(T) kr", "= (Tmax,\"K\"), comment = comment, ), ], Tmin = (Tmin,\"K\"),", "testStoichiometricCoefficient(self): \"\"\" Test the Reaction.getStoichiometricCoefficient() method. \"\"\" for reactant in", "pressures = (pressures,\"bar\"), arrhenius = arrhenius, Tmin = (Tmin,\"K\"), Tmax", "made up\"\"\", ) pressures = numpy.array([0.1, 10.0]) arrhenius = [arrhenius0,", "as always within 5%) for i in range(len(Tlist)): self.assertAlmostEqual(klist[i], klist2[i],", "= Arrhenius().fitToData(Tlist, klist, kunits='m^3/(mol*s)') klist2 = numpy.array([arrhenius.getRateCoefficient(T) for T in", "products = [ethyl], kinetics = Arrhenius( A = (501366000.0, 'cm^3/(mol*s)'),", "return self.label.lower() == other.label.lower() class TestReactionIsomorphism(unittest.TestCase): \"\"\" Contains unit tests", "symmetry = 4, ), HarmonicOscillator( frequencies = ( [828.397, 970.652,", ") arrhenius1 = Arrhenius( A = (1.0e12,\"s^-1\"), n = 1.0,", "(10.21,\"kJ/mol\"), T0 = (1,\"K\"), ) efficiencies = {\"C\": 3, \"C(=O)=O\":", "= numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kplist0 = [float(v) for v", "T3 = 74 T1 = 2941 T2 = 6964 efficiencies", "isomerization = Reaction(reactants=[Species()], products=[Species()]) association = Reaction(reactants=[Species(),Species()], products=[Species()]) dissociation =", "%r' % (self.reaction)) self.assertEqual(len(self.reaction.reactants), len(reaction.reactants)) self.assertEqual(len(self.reaction.products), len(reaction.products)) for reactant0, reactant", ") self.reaction2 = Reaction( reactants=[acetyl, oxygen], products=[acetylperoxy], kinetics = Arrhenius(", "Reaction.isIsomerization() method. \"\"\" isomerization = Reaction(reactants=[Species()], products=[Species()]) association = Reaction(reactants=[Species(),Species()],", "in self.reaction.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), -1) for product in self.reaction.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 1)", ") # [O][O] oxygen = Species( label='oxygen', thermo=Wilhoit(Cp0=(3.5*constants.R,\"J/(mol*K)\"), CpInf=(4.5*constants.R,\"J/(mol*K)\"), a0=-0.9324,", "= 0.0, Ea = (11200*constants.R*0.001,\"kJ/mol\"), T0 = (1,\"K\"), Tmin =", "dissociation = Reaction(reactants=[Species()], products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertFalse(isomerization.isAssociation()) self.assertTrue(association.isAssociation())", "for the ThirdBody format. \"\"\" from rmgpy.kinetics import ThirdBody arrheniusLow", "def testEntropyOfReaction(self): \"\"\" Test the Reaction.getEntropyOfReaction() method. \"\"\" Tlist =", "self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 1) for reactant in self.reaction2.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), 0) for product", "self.reaction2.getEnthalpiesOfReaction(Tlist) for i in range(len(Tlist)): self.assertAlmostEqual(Hlist[i] / 1000., Hlist0[i] /", "of the rmgpy.reaction module. \"\"\" import numpy import unittest from", "comment = comment, ), ], Tmin = (Tmin,\"K\"), Tmax =", "\"\"\" Test the Reaction.getEntropyOfReaction() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0,", "ArrheniusEP original_kinetics = ArrheniusEP( A = (2.65e12, 'cm^3/(mol*s)'), n =", "Ea = (0.0, 'kJ/mol'), T0 = (1, 'K'), Tmin =", "constants ################################################################################ class PseudoSpecies: \"\"\" Can be used in place", "Arrhenius( A = (9.3e-16,\"cm^3/(molecule*s)\"), n = 0.0, Ea = (4740*constants.R*0.001,\"kJ/mol\"),", "kunits='m^3/(mol*s)') klist2 = numpy.array([arrhenius.getRateCoefficient(T) for T in Tlist]) # Check", "import Species, TransitionState from rmgpy.reaction import Reaction from rmgpy.statmech.translation import", "self.assertAlmostEqual(self.reaction.getRateCoefficient(T, P) / self.reaction.kinetics.getRateCoefficient(T), 1.0, 6) def testGenerateReverseRateCoefficient(self): \"\"\" Test", "\"\"\" Can be used in place of a :class:`rmg.species.Species` for", "1.0, 0) def testGenerateReverseRateCoefficientThirdBody(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works", "module. \"\"\" import numpy import unittest from external.wip import work_in_progress", "(0.0, 'kJ/mol'), T0 = (1, 'K'), Tmin = (300, 'K'),", "B=(500.0,\"K\"), H0=(-6.151e+04,\"J/mol\"), S0=(-790.2,\"J/(mol*K)\")), ) # C[C]=O acetyl = Species( label='acetyl',", "Tlist = numpy.arange(original_kinetics.Tmin.value_si, original_kinetics.Tmax.value_si, 200.0, numpy.float64) P = 1e5 for", "v in ['-114648', '-83137.2', '-52092.4', '-21719.3', '8073.53', '37398.1', '66346.8', '94990.6',", "(1,\"K\"), ) arrheniusLow = Arrhenius( A = (2.62e+33,\"cm^6/(mol^2*s)\"), n =", "= -4.76, Ea = (10.21,\"kJ/mol\"), T0 = (1,\"K\"), ) alpha", "A = (1.4e-11,\"cm^3/(molecule*s)\"), n = 0.0, Ea = (11200*constants.R*0.001,\"kJ/mol\"), T0", "delta=1e-6) self.assertEqual(self.reaction.kinetics.comment, reaction.kinetics.comment) self.assertEqual(self.reaction.duplicate, reaction.duplicate) self.assertEqual(self.reaction.degeneracy, reaction.degeneracy) def testOutput(self): \"\"\"", "self.assertTrue(self.reaction.hasTemplate(reactants, products)) self.assertTrue(self.reaction.hasTemplate(products, reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants, products)) self.assertFalse(self.reaction2.hasTemplate(products, reactants)) reactants.reverse() products.reverse()", "= numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Slist0 = [float(v) for v", "thirdBody self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics = reverseKinetics", "i in reactants] products = [PseudoSpecies(i) for i in products]", "1.0, 6) def testGenerateReverseRateCoefficient(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method. \"\"\"", "= self.makeReaction('AB=CD') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cd'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=dc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dc=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cd=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=ab'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=cde'))) def test2to3(self):", "troe = Troe( arrheniusHigh = arrheniusHigh, arrheniusLow = arrheniusLow, alpha", "= Conformer( E0 = (111.603, 'kJ/mol'), modes = [ IdealGasTranslation(", "= self.reaction2.getEnthalpiesOfReaction(Tlist) for i in range(len(Tlist)): self.assertAlmostEqual(Hlist[i] / 1000., Hlist0[i]", "pressures = (pressures,\"bar\"), arrhenius = [ Arrhenius( A = (9.3e-16,\"cm^3/(molecule*s)\"),", "= Reaction(reactants=[Species(),Species()], products=[Species()]) dissociation = Reaction(reactants=[Species()], products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()],", "numpy.arange(original_kinetics.Tmin, original_kinetics.Tmax, 200.0, numpy.float64) P = 1e5 for T in", "= 1, ), HarmonicOscillator( frequencies = ( [412.75, 415.206, 821.495,", "= Reaction(reactants=[Species()], products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertFalse(isomerization.isAssociation()) self.assertTrue(association.isAssociation()) self.assertFalse(dissociation.isAssociation())", "def testFreeEnergyOfReaction(self): \"\"\" Test the Reaction.getFreeEnergyOfReaction() method. \"\"\" Tlist =", "PDepArrhenius format. \"\"\" from rmgpy.kinetics import PDepArrhenius arrhenius0 = Arrhenius(", "arrhenius = arrhenius, Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), comment", "1e6, product.conformer.E0.value_si / 1e6, 2) self.assertEqual(product0.conformer.E0.units, product.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.conformer.E0.value_si / 1e6,", "reactant in zip(self.reaction.reactants, reaction.reactants): self.assertAlmostEqual(reactant0.conformer.E0.value_si / 1e6, reactant.conformer.E0.value_si / 1e6,", "klist2[i], delta=5e-2 * klist[i]) def testPickle(self): \"\"\" Test that a", "testEquilibriumConstantKc(self): \"\"\" Test the Reaction.getEquilibriumConstant() method. \"\"\" Tlist = numpy.arange(200.0,", "loss of information. \"\"\" exec('reaction = %r' % (self.reaction)) self.assertEqual(len(self.reaction.reactants),", "Ea = (11200*constants.R*0.001,\"kJ/mol\"), T0 = (1,\"K\"), Tmin = (Tmin,\"K\"), Tmax", "CH3 -> CH4\"\"\" thirdBody = ThirdBody( arrheniusLow = arrheniusLow, Tmin", "), Arrhenius( A = (1.4e-9,\"cm^3/(molecule*s)\"), n = 0.0, Ea =", "of from a string like 'Ab=CD' \"\"\" reactants, products =", "def test2to3(self): r1 = self.makeReaction('AB=CDE') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cde'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ba=edc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dec=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cde=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=abc')))", "numpy.array([0.1, 10.0]) Tmin = 300.0 Tmax = 2000.0 Pmin =", "arrhenius = [ PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius = [", "\"C(=O)=O\": 2, \"CC\": 3, \"O\": 6, \"[Ar]\": 0.7, \"[C]=O\": 1.5,", "'7.92389e-09', '2.62777e-09', '1.10053e-09']] Kplist = self.reaction2.getEquilibriumConstants(Tlist, type='Kp') for i in", "'K'), Tmin = (300, 'K'), Tmax = (2000, 'K'), ),", "i in range(len(Tlist)): self.assertAlmostEqual(Kplist[i] / Kplist0[i], 1.0, 4) def testStoichiometricCoefficient(self):", "self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientTroe(self): \"\"\" Test the", "reaction.kinetics.comment) self.assertEqual(self.reaction.duplicate, reaction.duplicate) self.assertEqual(self.reaction.degeneracy, reaction.degeneracy) def testOutput(self): \"\"\" Test that", "ethylene = Species( label = 'C2H4', conformer = Conformer( E0", "(Pmax,\"bar\"), comment = comment, ) self.reaction2.kinetics = original_kinetics reverseKinetics =", "pressures = numpy.array([0.1, 10.0]) arrhenius = [arrhenius0, arrhenius1] Tmin =", "Pmax = 10.0 comment = \"\"\"This data is completely made", "method. \"\"\" reactants = self.reaction.reactants[:] products = self.reaction.products[:] self.assertTrue(self.reaction.hasTemplate(reactants, products))", "the MultiArrhenius format. \"\"\" from rmgpy.kinetics import MultiArrhenius pressures =", "1000., Hlist0[i] / 1000., 2) def testEntropyOfReaction(self): \"\"\" Test the", "/ krevrev, 1.0, 0) def testGenerateReverseRateCoefficientLindemann(self): \"\"\" Test the Reaction.generateReverseRateCoefficient()", "label def __repr__(self): return \"PseudoSpecies('{0}')\".format(self.label) def __str__(self): return self.label def", "['8.75951e+29', '7.1843e+10', '34272.7', '26.1877', '0.378696', '0.0235579', '0.00334673', '0.000792389', '0.000262777', '0.000110053']]", "PseudoSpecies) of from a string like 'Ab=CD' \"\"\" reactants, products", "reactant in self.reaction.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), -1) for product in self.reaction.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product),", "/ 1e6, 2) self.assertEqual(product0.conformer.E0.units, product.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.conformer.E0.value_si / 1e6, reaction.transitionState.conformer.E0.value_si /", "self.reaction = Reaction( reactants = [hydrogen, ethylene], products = [ethyl],", "Test the Reaction.getRateCoefficient() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0,", "products)) self.assertFalse(self.reaction.hasTemplate(products, reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants, products)) self.assertTrue(self.reaction2.hasTemplate(products, reactants)) reactants.reverse() products.reverse() self.assertFalse(self.reaction.hasTemplate(reactants,", "= (501366000.0, 'cm^3/(mol*s)'), n = 1.637, Ea = (4.32508, 'kJ/mol'),", "= (300, 'K'), Tmax = (2500, 'K'), ), transitionState =", "['8.75951e+24', '718430', '0.342727', '0.000261877', '3.78696e-06', '2.35579e-07', '3.34673e-08', '7.92389e-09', '2.62777e-09', '1.10053e-09']]", "LinearRotor, NonlinearRotor, KRotor, SphericalTopRotor from rmgpy.statmech.vibration import Vibration, HarmonicOscillator from", "], spinMultiplicity = 2, opticalIsomers = 1, ), frequency =", "\"\"\"H + CH3 -> CH4\"\"\" lindemann = Lindemann( arrheniusHigh =", "'718430', '0.342727', '0.000261877', '3.78696e-06', '2.35579e-07', '3.34673e-08', '7.92389e-09', '2.62777e-09', '1.10053e-09']] Kplist", "P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testTSTCalculation(self): \"\"\" A", "[ IdealGasTranslation( mass = (28.0313, 'amu'), ), NonlinearRotor( inertia =", "as constants ################################################################################ class PseudoSpecies: \"\"\" Can be used in", "from rmgpy.kinetics import Arrhenius from rmgpy.thermo import Wilhoit import rmgpy.constants", "association = Reaction(reactants=[Species(),Species()], products=[Species()]) dissociation = Reaction(reactants=[Species()], products=[Species(),Species()]) bimolecular =", "from rmgpy.kinetics import PDepArrhenius, MultiPDepArrhenius Tmin = 350. Tmax =", "testGenerateReverseRateCoefficientMultiArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the MultiArrhenius", "= (300.0,\"K\"), Tmax = (2000.0,\"K\"), comment = \"\"\"This data is", "= [PseudoSpecies(i) for i in reactants] products = [PseudoSpecies(i) for", "self.assertAlmostEqual(Kclist[i] / Kclist0[i], 1.0, 4) def testEquilibriumConstantKp(self): \"\"\" Test the", "def testEquilibriumConstantKa(self): \"\"\" Test the Reaction.getEquilibriumConstant() method. \"\"\" Tlist =", "-1) for product in self.reaction.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 1) for reactant in", "(1.4e-9,\"cm^3/(molecule*s)\"), n = 0.0, Ea = (11200*constants.R*0.001,\"kJ/mol\"), T0 = (1,\"K\"),", "dissociation = Reaction(reactants=[Species()], products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertTrue(isomerization.isIsomerization()) self.assertFalse(association.isIsomerization())", "1000., 2) def testEntropyOfReaction(self): \"\"\" Test the Reaction.getEntropyOfReaction() method. \"\"\"", "= Conformer( E0 = (211.794, 'kJ/mol'), modes = [ IdealGasTranslation(", "0.0, alpha = 0.5, E0 = (41.84, 'kJ/mol'), Tmin =", "T1 = (T1,\"K\"), T2 = (T2,\"K\"), Tmin = (Tmin,\"K\"), Tmax", "= self.reaction2.products, self.reaction2.reactants reversereverseKinetics = self.reaction2.generateReverseRateCoefficient() # check that reverting", "products=[Species(),Species()]) self.assertTrue(isomerization.isIsomerization()) self.assertFalse(association.isIsomerization()) self.assertFalse(dissociation.isIsomerization()) self.assertFalse(bimolecular.isIsomerization()) def testIsAssociation(self): \"\"\" Test the", "-*- \"\"\" This module contains unit tests of the rmgpy.reaction", "reaction.reactants): self.assertAlmostEqual(reactant0.conformer.E0.value_si / 1e6, reactant.conformer.E0.value_si / 1e6, 2) self.assertEqual(reactant0.conformer.E0.units, reactant.conformer.E0.units)", "self.assertTrue(self.reaction2.hasTemplate(products, reactants)) def testEnthalpyOfReaction(self): \"\"\" Test the Reaction.getEnthalpyOfReaction() method. \"\"\"", "(10.0,\"kJ/mol\"), T0 = (300.0,\"K\"), Tmin = (300.0,\"K\"), Tmax = (2000.0,\"K\"),", "\"\"\"This data is completely made up\"\"\", ) pressures = numpy.array([0.1,", "'K'), Tmin = (300, 'K'), Tmax = (2500, 'K'), ),", "= numpy.array([self.reaction.calculateTSTRateCoefficient(T) for T in Tlist]) arrhenius = Arrhenius().fitToData(Tlist, klist,", "alpha = alpha, T3 = (T3,\"K\"), T1 = (T1,\"K\"), T2", "a Reaction (containing PseudoSpecies) of from a string like 'Ab=CD'", "( [6.78512, 22.1437, 22.2114], 'amu*angstrom^2', ), symmetry = 1, ),", "= numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kalist0 = [float(v) for v", "(4.32508, 'kJ/mol'), T0 = (1, 'K'), Tmin = (300, 'K'),", "the Reaction.isAssociation() method. \"\"\" isomerization = Reaction(reactants=[Species()], products=[Species()]) association =", "'-131150', '-129316']] Hlist = self.reaction2.getEnthalpiesOfReaction(Tlist) for i in range(len(Tlist)): self.assertAlmostEqual(Hlist[i]", "'-135155', '-133093', '-131150', '-129316']] Hlist = self.reaction2.getEnthalpiesOfReaction(Tlist) for i in", "products=[Species()]) association = Reaction(reactants=[Species(),Species()], products=[Species()]) dissociation = Reaction(reactants=[Species()], products=[Species(),Species()]) bimolecular", "arrhenius0 = Arrhenius( A = (1.0e6,\"s^-1\"), n = 1.0, Ea", "= (1.0e6,\"s^-1\"), n = 1.0, Ea = (10.0,\"kJ/mol\"), T0 =", "(defined here as always within 5%) for i in range(len(Tlist)):", "IdealGasTranslation( mass = (1.00783, 'amu'), ), ], spinMultiplicity = 2,", "( [4.8709, 22.2353, 23.9925], 'amu*angstrom^2', ), symmetry = 1, ),", "'-147.707', '-145.616', '-143.93', '-142.552', '-141.407', '-140.441']] Slist = self.reaction2.getEntropiesOfReaction(Tlist) for", "-> C2H5. \"\"\" Tlist = 1000.0/numpy.arange(0.4, 3.35, 0.01) klist =", "/ 1000., 2) def testEntropyOfReaction(self): \"\"\" Test the Reaction.getEntropyOfReaction() method.", "Test the Reaction.getEntropyOfReaction() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0,", "self.assertEqual(self.reaction.transitionState.frequency.units, reaction.transitionState.frequency.units) self.assertAlmostEqual(self.reaction.kinetics.A.value_si, reaction.kinetics.A.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.n.value_si, reaction.kinetics.n.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.T0.value_si, reaction.kinetics.T0.value_si,", "up\"\"\" arrhenius = [ Arrhenius( A = (9.3e-14,\"cm^3/(molecule*s)\"), n =", "% (self.reaction)) self.assertEqual(len(self.reaction.reactants), len(reaction.reactants)) self.assertEqual(len(self.reaction.products), len(reaction.products)) for reactant0, reactant in", "= original_kinetics.getRateCoefficient(T, P) krevrev = reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev,", "= 2000.0 Pmin = 0.1 Pmax = 10.0 comment =", "= [PseudoSpecies(i) for i in products] return Reaction(reactants=reactants, products=products) def", "'-156.872', '-153.504', '-150.317', '-147.707', '-145.616', '-143.93', '-142.552', '-141.407', '-140.441']] Slist", "comment, ), ], Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), Pmin", "the reverse yields the original Tlist = numpy.arange(original_kinetics.Tmin, original_kinetics.Tmax, 200.0,", "in range(len(Tlist)): self.assertAlmostEqual(Kalist[i] / Kalist0[i], 1.0, 4) def testEquilibriumConstantKc(self): \"\"\"", "self.reaction2.getEntropiesOfReaction(Tlist) for i in range(len(Tlist)): self.assertAlmostEqual(Slist[i], Slist0[i], 2) def testFreeEnergyOfReaction(self):", "= 0.0, alpha = 0.5, E0 = (41.84, 'kJ/mol'), Tmin", "\"\"\" from rmgpy.kinetics import ThirdBody arrheniusLow = Arrhenius( A =", "= ThirdBody( arrheniusLow = arrheniusLow, Tmin = (Tmin,\"K\"), Tmax =", "= 1.0, Ea = (10.0,\"kJ/mol\"), T0 = (300.0,\"K\"), Tmin =", "Wilhoit import rmgpy.constants as constants ################################################################################ class PseudoSpecies: \"\"\" Can", "# C[C]=O acetyl = Species( label='acetyl', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(15.5*constants.R,\"J/(mol*K)\"), a0=0.2541, a1=-0.4712,", "= (Pmax,\"bar\"), comment = comment, ), PDepArrhenius( pressures = (pressures,\"bar\"),", "a :class:`rmg.species.Species` for isomorphism checks. PseudoSpecies('a') is isomorphic with PseudoSpecies('A')", "numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kplist0 = [float(v) for v in", "), NonlinearRotor( inertia = ( [6.78512, 22.1437, 22.2114], 'amu*angstrom^2', ),", "the Reaction.generateReverseRateCoefficient() method works for the PDepArrhenius format. \"\"\" from", "frequencies = ( [828.397, 970.652, 977.223, 1052.93, 1233.55, 1367.56, 1465.09,", "function, using the reaction H + C2H4 -> C2H5. \"\"\"", "testFreeEnergyOfReaction(self): \"\"\" Test the Reaction.getFreeEnergyOfReaction() method. \"\"\" Tlist = numpy.arange(200.0,", "method works for the PDepArrhenius format. \"\"\" from rmgpy.kinetics import", "rmgpy.species import Species, TransitionState from rmgpy.reaction import Reaction from rmgpy.statmech.translation", "= (1.0e12,\"s^-1\"), n = 1.0, Ea = (20.0,\"kJ/mol\"), T0 =", "frequencies = ( [482.224, 791.876, 974.355, 1051.48, 1183.21, 1361.36, 1448.65,", "( [482.224, 791.876, 974.355, 1051.48, 1183.21, 1361.36, 1448.65, 1455.07, 1465.48,", "self.assertFalse(bimolecular.isDissociation()) def testHasTemplate(self): \"\"\" Test the Reaction.hasTemplate() method. \"\"\" reactants", "like 'Ab=CD' \"\"\" reactants, products = reaction_string.split('=') reactants = [PseudoSpecies(i)", "symmetry = 1, ), HarmonicOscillator( frequencies = ( [412.75, 415.206,", "'-144195', '-141973', '-139633', '-137341', '-135155', '-133093', '-131150', '-129316']] Hlist =", "'3.93273e-05', '1.83006e-05']] Kclist = self.reaction2.getEquilibriumConstants(Tlist, type='Kc') for i in range(len(Tlist)):", "= numpy.arange(200.0, 2001.0, 200.0, numpy.float64) P = 1e5 for T", "self.label.lower() == other.label.lower() class TestReactionIsomorphism(unittest.TestCase): \"\"\" Contains unit tests of", "products to ensure Keq is correctly computed self.reaction2.reactants, self.reaction2.products =", "efficiencies = efficiencies, comment = comment, ) original_kinetics = lindemann", "(1.00783, 'amu'), ), ], spinMultiplicity = 2, opticalIsomers = 1,", "from a string like 'Ab=CD' \"\"\" reactants, products = reaction_string.split('=')", "1, ), HarmonicOscillator( frequencies = ( [482.224, 791.876, 974.355, 1051.48,", "'K'), Tmax = (2500, 'K'), ), transitionState = TS, )", "from rmgpy.species import Species, TransitionState from rmgpy.reaction import Reaction from", "NonlinearRotor, KRotor, SphericalTopRotor from rmgpy.statmech.vibration import Vibration, HarmonicOscillator from rmgpy.statmech.torsion", "Slist = self.reaction2.getEntropiesOfReaction(Tlist) for i in range(len(Tlist)): self.assertAlmostEqual(Slist[i], Slist0[i], 2)", "reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientPDepArrhenius(self): \"\"\"", "def test1to2(self): r1 = self.makeReaction('A=BC') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=Bc'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('cb=a'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('a=cb'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('bc=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('a=c')))", "Troe arrheniusHigh = Arrhenius( A = (1.39e+16,\"cm^3/(mol*s)\"), n = -0.534,", "(300, 'K'), Tmax = (2500, 'K'), ), transitionState = TS,", "efficiencies = efficiencies, comment = comment, ) original_kinetics = thirdBody", "'8073.53', '37398.1', '66346.8', '94990.6', '123383', '151565']] Glist = self.reaction2.getFreeEnergiesOfReaction(Tlist) for", "Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) P = 1e5 reverseKinetics", "T in Tlist]) arrhenius = Arrhenius().fitToData(Tlist, klist, kunits='m^3/(mol*s)') klist2 =", "\"\"\" Test the Reaction.getStoichiometricCoefficient() method. \"\"\" for reactant in self.reaction.reactants:", "reactants = self.reaction.reactants[:] products = self.reaction.products[:] self.assertTrue(self.reaction.hasTemplate(reactants, products)) self.assertTrue(self.reaction.hasTemplate(products, reactants))", "1.0, 0) def testGenerateReverseRateCoefficientMultiArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works", "= 0.783 T3 = 74 T1 = 2941 T2 =", "(Pmax,\"bar\"), efficiencies = efficiencies, comment = comment, ) original_kinetics =", "format. \"\"\" from rmgpy.kinetics import Lindemann arrheniusHigh = Arrhenius( A", "reaction.transitionState.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.frequency.value_si, reaction.transitionState.frequency.value_si, 2) self.assertEqual(self.reaction.transitionState.frequency.units, reaction.transitionState.frequency.units) self.assertAlmostEqual(self.reaction.kinetics.A.value_si, reaction.kinetics.A.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.n.value_si,", "self.assertFalse(r1.isIsomorphic(self.makeReaction('A=BB'))) def test1to2(self): r1 = self.makeReaction('A=BC') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=Bc'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('cb=a'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('a=cb'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('bc=a'),eitherDirection=False))", "[482.224, 791.876, 974.355, 1051.48, 1183.21, 1361.36, 1448.65, 1455.07, 1465.48, 2688.22,", "= \"\"\"This data is completely made up\"\"\", ) pressures =", "ethylene], products = [ethyl], kinetics = Arrhenius( A = (501366000.0,", "= (28.0313, 'amu'), ), NonlinearRotor( inertia = ( [3.41526, 16.6498,", "), ) def testIsIsomerization(self): \"\"\" Test the Reaction.isIsomerization() method. \"\"\"", "numpy import unittest from external.wip import work_in_progress from rmgpy.species import", "= 1.0, Ea = (20.0,\"kJ/mol\"), T0 = (300.0,\"K\"), Tmin =", "self.reaction2.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), 0) for product in self.reaction2.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 0) def", "self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics = reverseKinetics #", "comment, ), Arrhenius( A = (9.3e-14,\"cm^3/(molecule*s)\"), n = 0.0, Ea", "1000., 2) def testEquilibriumConstantKa(self): \"\"\" Test the Reaction.getEquilibriumConstant() method. \"\"\"", "200.0, numpy.float64) Kplist0 = [float(v) for v in ['8.75951e+24', '718430',", "original_kinetics.Tmax.value_si, 200.0, numpy.float64) P = 1e5 for T in Tlist:", "Tmin = (300, 'K'), Tmax = (2500, 'K'), ), transitionState", "1e5 for T in Tlist: self.assertAlmostEqual(self.reaction.getRateCoefficient(T, P) / self.reaction.kinetics.getRateCoefficient(T), 1.0,", "Tmax = (2000, 'K'), ), ) def testIsIsomerization(self): \"\"\" Test", "self.reaction2.getRateCoefficient(T, P) / self.reaction2.getEquilibriumConstant(T) kr = reverseKinetics.getRateCoefficient(T) self.assertAlmostEqual(kr0 / kr,", "Arrhenius( A = (501366000.0, 'cm^3/(mol*s)'), n = 1.637, Ea =", "numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Slist0 = [float(v) for v in", "Reaction.generateReverseRateCoefficient() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) P", "the Reaction class. \"\"\" def makeReaction(self,reaction_string): \"\"\"\" Make a Reaction", "format. \"\"\" from rmgpy.kinetics import PDepArrhenius, MultiPDepArrhenius Tmin = 350.", "\"\"\" import cPickle reaction = cPickle.loads(cPickle.dumps(self.reaction,-1)) self.assertEqual(len(self.reaction.reactants), len(reaction.reactants)) self.assertEqual(len(self.reaction.products), len(reaction.products))", "Contains unit tests of the Reaction class. \"\"\" def setUp(self):", "[float(v) for v in ['1.45661e+28', '2.38935e+09', '1709.76', '1.74189', '0.0314866', '0.00235045',", "self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testTSTCalculation(self): \"\"\" A test", "= (9.3e-16,\"cm^3/(molecule*s)\"), n = 0.0, Ea = (4740*constants.R*0.001,\"kJ/mol\"), T0 =", "0.01) klist = numpy.array([self.reaction.calculateTSTRateCoefficient(T) for T in Tlist]) arrhenius =", "comment, ), ] original_kinetics = MultiArrhenius( arrhenius = arrhenius, Tmin", "klist, kunits='m^3/(mol*s)') klist2 = numpy.array([arrhenius.getRateCoefficient(T) for T in Tlist]) #", "= numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Glist0 = [float(v) for v", "rmgpy.kinetics import Troe arrheniusHigh = Arrhenius( A = (1.39e+16,\"cm^3/(mol*s)\"), n", "# Check that the fit is satisfactory (defined here as", "def testPickle(self): \"\"\" Test that a Reaction object can be", ") # C[C]=O acetyl = Species( label='acetyl', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(15.5*constants.R,\"J/(mol*K)\"), a0=0.2541,", "= (Tmin,\"K\"), Tmax = (Tmax,\"K\"), comment = comment, ) self.reaction2.kinetics", "2954.51, 3033.39, 3101.54, 3204.73], 'cm^-1', ), ), HinderedRotor( inertia =", "for T in Tlist: kr0 = self.reaction2.getRateCoefficient(T, P) / self.reaction2.getEquilibriumConstant(T)", "\"\"\" Test the Reaction.getRateCoefficient() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0,", "yields the original Tlist = numpy.arange(original_kinetics.Tmin.value_si, original_kinetics.Tmax.value_si, 200.0, numpy.float64) P", "the rmgpy.reaction module. \"\"\" import numpy import unittest from external.wip", "1, ), ) ethyl = Species( label = 'C2H5', conformer", "bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertTrue(isomerization.isIsomerization()) self.assertFalse(association.isIsomerization()) self.assertFalse(dissociation.isIsomerization()) self.assertFalse(bimolecular.isIsomerization()) def testIsAssociation(self):", "arrheniusHigh = arrheniusHigh, arrheniusLow = arrheniusLow, alpha = alpha, T3", "/ 1e6, 2) self.assertEqual(reactant0.conformer.E0.units, reactant.conformer.E0.units) for product0, product in zip(self.reaction.products,", "reactants=[acetyl, oxygen], products=[acetylperoxy], kinetics = Arrhenius( A = (2.65e12, 'cm^3/(mol*s)'),", "= (Tmin,\"K\"), Tmax = (Tmax,\"K\"), comment = comment, ), ],", "testEnthalpyOfReaction(self): \"\"\" Test the Reaction.getEnthalpyOfReaction() method. \"\"\" Tlist = numpy.arange(200.0,", "symmetry = 6, barrier = (0.244029, 'kJ/mol'), semiclassical = None,", "frequency = (-750.232, 'cm^-1'), ) self.reaction = Reaction( reactants =", "2265.2488, delta=1e-2) self.assertAlmostEqual(arrhenius.n.value_si, 1.45419, delta=1e-4) self.assertAlmostEqual(arrhenius.Ea.value_si, 6645.24, delta=1e-2) # Check", "\"\"\" exec('reaction = %r' % (self.reaction)) self.assertEqual(len(self.reaction.reactants), len(reaction.reactants)) self.assertEqual(len(self.reaction.products), len(reaction.products))", "oxygen], products=[acetylperoxy], kinetics = Arrhenius( A = (2.65e12, 'cm^3/(mol*s)'), n", "krevrev, 1.0, 0) def testGenerateReverseRateCoefficientMultiArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method", "import Troe arrheniusHigh = Arrhenius( A = (1.39e+16,\"cm^3/(mol*s)\"), n =", "= Troe( arrheniusHigh = arrheniusHigh, arrheniusLow = arrheniusLow, alpha =", "= 1e5 for T in Tlist: self.assertAlmostEqual(self.reaction.getRateCoefficient(T, P) / self.reaction.kinetics.getRateCoefficient(T),", "MultiArrhenius pressures = numpy.array([0.1, 10.0]) Tmin = 300.0 Tmax =", "in range(len(Tlist)): self.assertAlmostEqual(Slist[i], Slist0[i], 2) def testFreeEnergyOfReaction(self): \"\"\" Test the", "self.assertTrue(dissociation.isDissociation()) self.assertFalse(bimolecular.isDissociation()) def testHasTemplate(self): \"\"\" Test the Reaction.hasTemplate() method. \"\"\"", "'-129316']] Hlist = self.reaction2.getEnthalpiesOfReaction(Tlist) for i in range(len(Tlist)): self.assertAlmostEqual(Hlist[i] /", "'0.00235045', '0.000389568', '0.000105413', '3.93273e-05', '1.83006e-05']] Kclist = self.reaction2.getEquilibriumConstants(Tlist, type='Kc') for", "= (0.0, 'kJ/mol'), T0 = (1, 'K'), Tmin = (300,", "\"\"\" reactants = self.reaction.reactants[:] products = self.reaction.products[:] self.assertTrue(self.reaction.hasTemplate(reactants, products)) self.assertTrue(self.reaction.hasTemplate(products,", "23.9925], 'amu*angstrom^2', ), symmetry = 1, ), HarmonicOscillator( frequencies =", "T0 = (1,\"K\"), ) alpha = 0.783 T3 = 74", "self.assertTrue(r1.isIsomorphic(self.makeReaction('ba=edc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dec=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cde=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=abc'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('abe=cde'))) class TestReaction(unittest.TestCase): \"\"\" Contains unit", ") arrheniusLow = Arrhenius( A = (2.62e+33,\"cm^6/(mol^2*s)\"), n = -4.76,", "bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertFalse(isomerization.isDissociation()) self.assertFalse(association.isDissociation()) self.assertTrue(dissociation.isDissociation()) self.assertFalse(bimolecular.isDissociation()) def testHasTemplate(self):", ") ethyl = Species( label = 'C2H5', conformer = Conformer(", "( [3.41526, 16.6498, 20.065], 'amu*angstrom^2', ), symmetry = 4, ),", "self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 0) def testRateCoefficient(self): \"\"\" Test the Reaction.getRateCoefficient() method. \"\"\"", "@work_in_progress def testGenerateReverseRateCoefficientArrheniusEP(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for", "[float(v) for v in ['-146007', '-145886', '-144195', '-141973', '-139633', '-137341',", "970.652, 977.223, 1052.93, 1233.55, 1367.56, 1465.09, 1672.25, 3098.46, 3111.7, 3165.79,", "def testIsIsomerization(self): \"\"\" Test the Reaction.isIsomerization() method. \"\"\" isomerization =", "Reaction class. \"\"\" def setUp(self): \"\"\" A method that is", "0) def testRateCoefficient(self): \"\"\" Test the Reaction.getRateCoefficient() method. \"\"\" Tlist", "self.assertAlmostEqual(Kalist[i] / Kalist0[i], 1.0, 4) def testEquilibriumConstantKc(self): \"\"\" Test the", "def testGenerateReverseRateCoefficientLindemann(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the", "= (2.62e+33,\"cm^6/(mol^2*s)\"), n = -4.76, Ea = (10.21,\"kJ/mol\"), T0 =", "product0, product in zip(self.reaction.products, reaction.products): self.assertAlmostEqual(product0.conformer.E0.value_si / 1e6, product.conformer.E0.value_si /", "arrheniusHigh, arrheniusLow = arrheniusLow, Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"),", "from rmgpy.kinetics import Troe arrheniusHigh = Arrhenius( A = (1.39e+16,\"cm^3/(mol*s)\"),", "self.assertTrue(self.reaction2.hasTemplate(products, reactants)) reactants.reverse() products.reverse() self.assertFalse(self.reaction.hasTemplate(reactants, products)) self.assertFalse(self.reaction.hasTemplate(products, reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants, products))", "products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertFalse(isomerization.isDissociation()) self.assertFalse(association.isDissociation()) self.assertTrue(dissociation.isDissociation()) self.assertFalse(bimolecular.isDissociation()) def", ") self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics = reverseKinetics", "rmgpy.statmech.rotation import Rotation, LinearRotor, NonlinearRotor, KRotor, SphericalTopRotor from rmgpy.statmech.vibration import", "), ) hydrogen = Species( label = 'H', conformer =", "(2.65e12, 'cm^3/(mol*s)'), n = 0.0, Ea = (0.0, 'kJ/mol'), T0", "numpy.float64) P = 1e5 reverseKinetics = self.reaction2.generateReverseRateCoefficient() for T in", "'cm^-1', ), ), ], spinMultiplicity = 1, opticalIsomers = 1,", "reactants)) reactants.reverse() products.reverse() self.assertTrue(self.reaction.hasTemplate(reactants, products)) self.assertTrue(self.reaction.hasTemplate(products, reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants, products)) self.assertFalse(self.reaction2.hasTemplate(products,", "completely made up\"\"\", ) arrhenius1 = Arrhenius( A = (1.0e12,\"s^-1\"),", "= comment, ), ] original_kinetics = MultiPDepArrhenius( arrhenius = arrhenius,", "= Arrhenius( A = (2.65e12, 'cm^3/(mol*s)'), n = 0.0, Ea", "= 1, opticalIsomers = 1, ), ) hydrogen = Species(", "product in self.reaction2.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 0) def testRateCoefficient(self): \"\"\" Test the", "Reaction (containing PseudoSpecies) of from a string like 'Ab=CD' \"\"\"", "rmgpy.kinetics import MultiArrhenius pressures = numpy.array([0.1, 10.0]) Tmin = 300.0", "'1709.76', '1.74189', '0.0314866', '0.00235045', '0.000389568', '0.000105413', '3.93273e-05', '1.83006e-05']] Kclist =", "= Conformer( E0 = (44.7127, 'kJ/mol'), modes = [ IdealGasTranslation(", "= 4, ), HarmonicOscillator( frequencies = ( [828.397, 970.652, 977.223,", "of information. \"\"\" import cPickle reaction = cPickle.loads(cPickle.dumps(self.reaction,-1)) self.assertEqual(len(self.reaction.reactants), len(reaction.reactants))", "reactants = [PseudoSpecies(i) for i in reactants] products = [PseudoSpecies(i)", "= (300, 'K'), Tmax = (2000, 'K'), ) self.reaction2.kinetics =", "# check that reverting the reverse yields the original Tlist", "= self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics = reverseKinetics # reverse reactants, products to", "200.0, numpy.float64) P = 1e5 reverseKinetics = self.reaction2.generateReverseRateCoefficient() for T", "PseudoSpecies('A') but nothing else. \"\"\" def __init__(self, label): self.label =", "(Tmax,\"K\"), Pmin = (Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), comment = comment,", "977.223, 1052.93, 1233.55, 1367.56, 1465.09, 1672.25, 3098.46, 3111.7, 3165.79, 3193.54],", "arrhenius = [ Arrhenius( A = (9.3e-14,\"cm^3/(molecule*s)\"), n = 0.0,", "= 1.637, Ea = (4.32508, 'kJ/mol'), T0 = (1, 'K'),", "krevrev, 1.0, 0) @work_in_progress def testGenerateReverseRateCoefficientArrheniusEP(self): \"\"\" Test the Reaction.generateReverseRateCoefficient()", "Tmax = (Tmax,\"K\"), comment = comment, ), Arrhenius( A =", "reactants] products = [PseudoSpecies(i) for i in products] return Reaction(reactants=reactants,", "\"\"\" Test the Reaction.hasTemplate() method. \"\"\" reactants = self.reaction.reactants[:] products", "up\"\"\", ) pressures = numpy.array([0.1, 10.0]) arrhenius = [arrhenius0, arrhenius1]", "100. comment = \"\"\"H + CH3 -> CH4\"\"\" lindemann =", "2001.0, 200.0, numpy.float64) Glist0 = [float(v) for v in ['-114648',", "1.5, \"[H][H]\": 2} Tmin = 300. Tmax = 2000. Pmin", "[ethyl], kinetics = Arrhenius( A = (501366000.0, 'cm^3/(mol*s)'), n =", "for the Troe format. \"\"\" from rmgpy.kinetics import Troe arrheniusHigh", "class. \"\"\" ethylene = Species( label = 'C2H4', conformer =", "original_kinetics = lindemann self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics", "correct Arrhenius parameters are returned self.assertAlmostEqual(arrhenius.A.value_si, 2265.2488, delta=1e-2) self.assertAlmostEqual(arrhenius.n.value_si, 1.45419,", "1465.48, 2688.22, 2954.51, 3033.39, 3101.54, 3204.73], 'cm^-1', ), ), HinderedRotor(", "\"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kplist0 = [float(v)", "= 0.0, Ea = (4740*constants.R*0.001,\"kJ/mol\"), T0 = (1,\"K\"), Tmin =", "################################################################################ class PseudoSpecies: \"\"\" Can be used in place of", "kr = reverseKinetics.getRateCoefficient(T) self.assertAlmostEqual(kr0 / kr, 1.0, 0) def testGenerateReverseRateCoefficientArrhenius(self):", "0.7, \"[C]=O\": 1.5, \"[H][H]\": 2} Tmin = 300. Tmax =", "no loss of information. \"\"\" exec('reaction = %r' % (self.reaction))", "'-143.93', '-142.552', '-141.407', '-140.441']] Slist = self.reaction2.getEntropiesOfReaction(Tlist) for i in", "exec('reaction = %r' % (self.reaction)) self.assertEqual(len(self.reaction.reactants), len(reaction.reactants)) self.assertEqual(len(self.reaction.products), len(reaction.products)) for", "(pressures,\"bar\"), arrhenius = [ Arrhenius( A = (9.3e-16,\"cm^3/(molecule*s)\"), n =", "in Tlist]) arrhenius = Arrhenius().fitToData(Tlist, klist, kunits='m^3/(mol*s)') klist2 = numpy.array([arrhenius.getRateCoefficient(T)", "tests of the rmgpy.reaction module. \"\"\" import numpy import unittest", "200.0, numpy.float64) Slist0 = [float(v) for v in ['-156.793', '-156.872',", "a3=2.25, B=(500.0,\"K\"), H0=(-1.439e+05,\"J/mol\"), S0=(-524.6,\"J/(mol*K)\")), ) # [O][O] oxygen = Species(", "range(len(Tlist)): self.assertAlmostEqual(Kclist[i] / Kclist0[i], 1.0, 4) def testEquilibriumConstantKp(self): \"\"\" Test", "Species( label = 'H', conformer = Conformer( E0 = (211.794,", "\"\"\" Test the Reaction.isAssociation() method. \"\"\" isomerization = Reaction(reactants=[Species()], products=[Species()])", "conformer = Conformer( E0 = (266.694, 'kJ/mol'), modes = [", "# encoding: utf-8 -*- \"\"\" This module contains unit tests", "1600.35, 3101.46, 3110.55, 3175.34, 3201.88], 'cm^-1', ), ), ], spinMultiplicity", "from rmgpy.kinetics import Lindemann arrheniusHigh = Arrhenius( A = (1.39e+16,\"cm^3/(mol*s)\"),", "unittest from external.wip import work_in_progress from rmgpy.species import Species, TransitionState", "a Reaction object can be successfully reconstructed from its repr()", "self.assertTrue(self.reaction2.hasTemplate(reactants, products)) self.assertTrue(self.reaction2.hasTemplate(products, reactants)) def testEnthalpyOfReaction(self): \"\"\" Test the Reaction.getEnthalpyOfReaction()", "self.assertFalse(r1.isIsomorphic(self.makeReaction('bc=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('a=c'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=c'))) def test2to2(self): r1 = self.makeReaction('AB=CD') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cd'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=dc'),eitherDirection=False))", "Tlist]) arrhenius = Arrhenius().fitToData(Tlist, klist, kunits='m^3/(mol*s)') klist2 = numpy.array([arrhenius.getRateCoefficient(T) for", "def testEquilibriumConstantKp(self): \"\"\" Test the Reaction.getEquilibriumConstant() method. \"\"\" Tlist =", "the Reaction.generateReverseRateCoefficient() method works for the ThirdBody format. \"\"\" from", "= Species( label='acetyl', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(15.5*constants.R,\"J/(mol*K)\"), a0=0.2541, a1=-0.4712, a2=-4.434, a3=2.25, B=(500.0,\"K\"),", "3, \"O\": 6, \"[Ar]\": 0.7, \"[C]=O\": 1.5, \"[H][H]\": 2} Tmin", "+ C2H4 -> C2H5. \"\"\" Tlist = 1000.0/numpy.arange(0.4, 3.35, 0.01)", "Reaction.generateReverseRateCoefficient() method works for the MultiArrhenius format. \"\"\" from rmgpy.kinetics", "1672.25, 3098.46, 3111.7, 3165.79, 3193.54], 'cm^-1', ), ), ], spinMultiplicity", "self.assertAlmostEqual(self.reaction.transitionState.frequency.value_si, reaction.transitionState.frequency.value_si, 2) self.assertEqual(self.reaction.transitionState.frequency.units, reaction.transitionState.frequency.units) self.assertAlmostEqual(self.reaction.kinetics.A.value_si, reaction.kinetics.A.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.n.value_si, reaction.kinetics.n.value_si,", "rmgpy.kinetics import Arrhenius from rmgpy.thermo import Wilhoit import rmgpy.constants as", "[ IdealGasTranslation( mass = (29.0391, 'amu'), ), NonlinearRotor( inertia =", "= [ IdealGasTranslation( mass = (28.0313, 'amu'), ), NonlinearRotor( inertia", "arrheniusLow = arrheniusLow, alpha = alpha, T3 = (T3,\"K\"), T1", "self.assertTrue(r1.isIsomorphic(self.makeReaction('dc=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cd=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=ab'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=cde'))) def test2to3(self): r1 = self.makeReaction('AB=CDE') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cde')))", "numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kclist0 = [float(v) for v in", "= 100. comment = \"\"\"H + CH3 -> CH4\"\"\" thirdBody", "products.reverse() self.assertFalse(self.reaction.hasTemplate(reactants, products)) self.assertFalse(self.reaction.hasTemplate(products, reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants, products)) self.assertTrue(self.reaction2.hasTemplate(products, reactants)) def", "/ 1e6, 2) self.assertEqual(self.reaction.transitionState.conformer.E0.units, reaction.transitionState.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.frequency.value_si, reaction.transitionState.frequency.value_si, 2) self.assertEqual(self.reaction.transitionState.frequency.units, reaction.transitionState.frequency.units)", "reactants = self.reaction2.reactants[:] products = self.reaction2.products[:] self.assertFalse(self.reaction.hasTemplate(reactants, products)) self.assertFalse(self.reaction.hasTemplate(products, reactants))", "\"\"\" Contains unit tests of the Reaction class. \"\"\" def", "Pmin = 0.01 Pmax = 100. comment = \"\"\"H +", "the Arrhenius format. \"\"\" original_kinetics = Arrhenius( A = (2.65e12,", "10.0]) Tmin = 300.0 Tmax = 2000.0 Pmin = 0.1", "self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientMultiArrhenius(self): \"\"\" Test the", "isomorphism testing of the Reaction class. \"\"\" def makeReaction(self,reaction_string): \"\"\"\"", "= (Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), comment = comment, ) self.reaction2.kinetics", "= arrhenius, Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), comment =", "Reaction.generateReverseRateCoefficient() method works for the MultiPDepArrhenius format. \"\"\" from rmgpy.kinetics", "reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientMultiArrhenius(self): \"\"\"", "A = (2.65e12, 'cm^3/(mol*s)'), n = 0.0, Ea = (0.0,", "label='acetylperoxy', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(21.0*constants.R,\"J/(mol*K)\"), a0=-3.95, a1=9.26, a2=-15.6, a3=8.55, B=(500.0,\"K\"), H0=(-6.151e+04,\"J/mol\"), S0=(-790.2,\"J/(mol*K)\")),", "(300, 'K'), Tmax = (2000, 'K'), ), ) def testIsIsomerization(self):", "reverse yields the original Tlist = numpy.arange(original_kinetics.Tmin, original_kinetics.Tmax, 200.0, numpy.float64)", "(Tmax,\"K\"), comment = comment, ), Arrhenius( A = (9.3e-14,\"cm^3/(molecule*s)\"), n", "reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientTroe(self): \"\"\"", "(211.794, 'kJ/mol'), modes = [ IdealGasTranslation( mass = (1.00783, 'amu'),", "= (pressures,\"bar\"), arrhenius = [ Arrhenius( A = (1.4e-11,\"cm^3/(molecule*s)\"), n", "comment = \"\"\"This data is completely made up\"\"\", ) arrhenius1", "self.assertAlmostEqual(arrhenius.Ea.value_si, 6645.24, delta=1e-2) # Check that the fit is satisfactory", "mass = (1.00783, 'amu'), ), ], spinMultiplicity = 2, opticalIsomers", "original_kinetics = PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius = arrhenius, Tmin", "reverting the reverse yields the original Tlist = numpy.arange(original_kinetics.Tmin, original_kinetics.Tmax,", "1183.21, 1361.36, 1448.65, 1455.07, 1465.48, 2688.22, 2954.51, 3033.39, 3101.54, 3204.73],", "Pmax = (Pmax,\"bar\"), comment = comment, ), ] original_kinetics =", "products)) self.assertTrue(self.reaction2.hasTemplate(products, reactants)) def testEnthalpyOfReaction(self): \"\"\" Test the Reaction.getEnthalpyOfReaction() method.", "/ 1000., Glist0[i] / 1000., 2) def testEquilibriumConstantKa(self): \"\"\" Test", "Reaction.isAssociation() method. \"\"\" isomerization = Reaction(reactants=[Species()], products=[Species()]) association = Reaction(reactants=[Species(),Species()],", "reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics = reverseKinetics # reverse reactants, products", "= (29.0391, 'amu'), ), NonlinearRotor( inertia = ( [6.78512, 22.1437,", "-> CH4\"\"\" lindemann = Lindemann( arrheniusHigh = arrheniusHigh, arrheniusLow =", "oxygen = Species( label='oxygen', thermo=Wilhoit(Cp0=(3.5*constants.R,\"J/(mol*K)\"), CpInf=(4.5*constants.R,\"J/(mol*K)\"), a0=-0.9324, a1=26.18, a2=-70.47, a3=44.12,", "= (10.21,\"kJ/mol\"), T0 = (1,\"K\"), ) alpha = 0.783 T3", "= Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertFalse(isomerization.isAssociation()) self.assertTrue(association.isAssociation()) self.assertFalse(dissociation.isAssociation()) self.assertFalse(bimolecular.isAssociation()) def testIsDissociation(self): \"\"\"", "self.assertAlmostEqual(klist[i], klist2[i], delta=5e-2 * klist[i]) def testPickle(self): \"\"\" Test that", "the original Tlist = numpy.arange(original_kinetics.Tmin, original_kinetics.Tmax, 200.0, numpy.float64) P =", "data is completely made up\"\"\" original_kinetics = PDepArrhenius( pressures =", "= 'C2H4', conformer = Conformer( E0 = (44.7127, 'kJ/mol'), modes", "product in zip(self.reaction.products, reaction.products): self.assertAlmostEqual(product0.conformer.E0.value_si / 1e6, product.conformer.E0.value_si / 1e6,", "conformer = Conformer( E0 = (111.603, 'kJ/mol'), modes = [", "(2000, 'K'), ) self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics", "tests of the Reaction class. \"\"\" def setUp(self): \"\"\" A", "/ krevrev, 1.0, 0) @work_in_progress def testGenerateReverseRateCoefficientArrheniusEP(self): \"\"\" Test the", "1.0, 0) def testGenerateReverseRateCoefficientArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works", "Arrhenius from rmgpy.thermo import Wilhoit import rmgpy.constants as constants ################################################################################", "in ['8.75951e+29', '7.1843e+10', '34272.7', '26.1877', '0.378696', '0.0235579', '0.00334673', '0.000792389', '0.000262777',", "CH4 + C2H5 (Baulch 2005)' arrhenius = [ PDepArrhenius( pressures", "self.reaction.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 1) for reactant in self.reaction2.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), 0) for", "= numpy.arange(Tmin, Tmax, 200.0, numpy.float64) P = 1e5 for T", "Glist0 = [float(v) for v in ['-114648', '-83137.2', '-52092.4', '-21719.3',", "self.assertEqual(reactant0.conformer.E0.units, reactant.conformer.E0.units) for product0, product in zip(self.reaction.products, reaction.products): self.assertAlmostEqual(product0.conformer.E0.value_si /", "rmgpy.reaction import Reaction from rmgpy.statmech.translation import Translation, IdealGasTranslation from rmgpy.statmech.rotation", "Reaction.generateReverseRateCoefficient() method works for the Arrhenius format. \"\"\" original_kinetics =", "for product in self.reaction.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 1) for reactant in self.reaction2.reactants:", "= 0.5, E0 = (41.84, 'kJ/mol'), Tmin = (300, 'K'),", "3111.7, 3165.79, 3193.54], 'cm^-1', ), ), ], spinMultiplicity = 1,", "self.assertEqual(product0.conformer.E0.units, product.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.conformer.E0.value_si / 1e6, reaction.transitionState.conformer.E0.value_si / 1e6, 2) self.assertEqual(self.reaction.transitionState.conformer.E0.units,", ") efficiencies = {\"C\": 3, \"C(=O)=O\": 2, \"CC\": 3, \"O\":", "self.assertFalse(dissociation.isAssociation()) self.assertFalse(bimolecular.isAssociation()) def testIsDissociation(self): \"\"\" Test the Reaction.isDissociation() method. \"\"\"", "for reactant in self.reaction2.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), 0) for product in self.reaction2.products:", "self.reaction2.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 0) def testRateCoefficient(self): \"\"\" Test the Reaction.getRateCoefficient() method.", "Ea = (4740*constants.R*0.001,\"kJ/mol\"), T0 = (1,\"K\"), Tmin = (Tmin,\"K\"), Tmax", "\"\"\" from rmgpy.kinetics import MultiArrhenius pressures = numpy.array([0.1, 10.0]) Tmin", "PDepArrhenius, MultiPDepArrhenius Tmin = 350. Tmax = 1500. Pmin =", "the reverse yields the original Tlist = numpy.arange(Tmin, Tmax, 200.0,", "numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Hlist0 = [float(v) for v in", "= Lindemann( arrheniusHigh = arrheniusHigh, arrheniusLow = arrheniusLow, Tmin =", "], spinMultiplicity = 2, opticalIsomers = 1, ), ) ethyl", "numpy.arange(original_kinetics.Tmin.value_si, original_kinetics.Tmax.value_si, 200.0, numpy.float64) P = 1e5 for T in", "1.0, 0) def testTSTCalculation(self): \"\"\" A test of the transition", "works for the Lindemann format. \"\"\" from rmgpy.kinetics import Lindemann", "a2=-70.47, a3=44.12, B=(500.0,\"K\"), H0=(1.453e+04,\"J/mol\"), S0=(-12.19,\"J/(mol*K)\")), ) self.reaction2 = Reaction( reactants=[acetyl,", "(T1,\"K\"), T2 = (T2,\"K\"), Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"),", "= (2500, 'K'), ), transitionState = TS, ) # CC(=O)O[O]", "reaction H + C2H4 -> C2H5. \"\"\" Tlist = 1000.0/numpy.arange(0.4,", "B=(500.0,\"K\"), H0=(1.453e+04,\"J/mol\"), S0=(-12.19,\"J/(mol*K)\")), ) self.reaction2 = Reaction( reactants=[acetyl, oxygen], products=[acetylperoxy],", "2) self.assertEqual(product0.conformer.E0.units, product.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.conformer.E0.value_si / 1e6, reaction.transitionState.conformer.E0.value_si / 1e6, 2)", "korig = original_kinetics.getRateCoefficient(T, P) krevrev = reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig /", "'cm^3/(mol*s)'), n = 1.637, Ea = (4.32508, 'kJ/mol'), T0 =", "the reaction H + C2H4 -> C2H5. \"\"\" Tlist =", "'H', conformer = Conformer( E0 = (211.794, 'kJ/mol'), modes =", "self.reaction2.getEquilibriumConstants(Tlist, type='Kp') for i in range(len(Tlist)): self.assertAlmostEqual(Kplist[i] / Kplist0[i], 1.0,", "(1,\"K\"), ) alpha = 0.783 T3 = 74 T1 =", "klist2 = numpy.array([arrhenius.getRateCoefficient(T) for T in Tlist]) # Check that", "spinMultiplicity = 2, opticalIsomers = 1, ), frequency = (-750.232,", ") def testIsIsomerization(self): \"\"\" Test the Reaction.isIsomerization() method. \"\"\" isomerization", "), ], spinMultiplicity = 2, opticalIsomers = 1, ), frequency", "reactants.reverse() products.reverse() self.assertTrue(self.reaction.hasTemplate(reactants, products)) self.assertTrue(self.reaction.hasTemplate(products, reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants, products)) self.assertFalse(self.reaction2.hasTemplate(products, reactants))", "self.reaction2.kinetics = reverseKinetics # reverse reactants, products to ensure Keq", "return Reaction(reactants=reactants, products=products) def test1to1(self): r1 = self.makeReaction('A=B') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=B'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('b=A')))", "[ Arrhenius( A = (1.4e-11,\"cm^3/(molecule*s)\"), n = 0.0, Ea =", "self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics = reverseKinetics # reverse reactants, products to ensure", "Reaction object can be successfully reconstructed from its repr() output", "for reactant in self.reaction.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), -1) for product in self.reaction.products:", "def testGenerateReverseRateCoefficient(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method. \"\"\" Tlist =", "\"\"\" A method that is called prior to each unit", "MultiPDepArrhenius format. \"\"\" from rmgpy.kinetics import PDepArrhenius, MultiPDepArrhenius Tmin =", "1e6, 2) self.assertEqual(product0.conformer.E0.units, product.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.conformer.E0.value_si / 1e6, reaction.transitionState.conformer.E0.value_si / 1e6,", "products = reaction_string.split('=') reactants = [PseudoSpecies(i) for i in reactants]", "= 'C2H5', conformer = Conformer( E0 = (111.603, 'kJ/mol'), modes", "= 10.0 comment = \"\"\"This data is completely made up\"\"\"", "(Tmin,\"K\"), Tmax = (Tmax,\"K\"), comment = comment, ), Arrhenius( A", "3033.39, 3101.54, 3204.73], 'cm^-1', ), ), HinderedRotor( inertia = (1.11481,", "(1,\"K\"), ) efficiencies = {\"C\": 3, \"C(=O)=O\": 2, \"CC\": 3,", "\"\"\" Test that a Reaction object can be successfully pickled", "arrheniusLow, Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), Pmin = (Pmin,\"bar\"),", "arrheniusHigh = Arrhenius( A = (1.39e+16,\"cm^3/(mol*s)\"), n = -0.534, Ea", "Reaction(reactants=[Species()], products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertTrue(isomerization.isIsomerization()) self.assertFalse(association.isIsomerization()) self.assertFalse(dissociation.isIsomerization()) self.assertFalse(bimolecular.isIsomerization())", "comment, ) original_kinetics = troe self.reaction2.kinetics = original_kinetics reverseKinetics =", "object can be successfully reconstructed from its repr() output with", "testEquilibriumConstantKa(self): \"\"\" Test the Reaction.getEquilibriumConstant() method. \"\"\" Tlist = numpy.arange(200.0,", "= ( [412.75, 415.206, 821.495, 924.44, 982.714, 1024.16, 1224.21, 1326.36,", "\"\"\" original_kinetics = Arrhenius( A = (2.65e12, 'cm^3/(mol*s)'), n =", "A method that is called prior to each unit test", "'7.1843e+10', '34272.7', '26.1877', '0.378696', '0.0235579', '0.00334673', '0.000792389', '0.000262777', '0.000110053']] Kalist", "Kalist0 = [float(v) for v in ['8.75951e+29', '7.1843e+10', '34272.7', '26.1877',", "= None, ), ], spinMultiplicity = 2, opticalIsomers = 1,", "import PDepArrhenius, MultiPDepArrhenius Tmin = 350. Tmax = 1500. Pmin", "unit tests of the rmgpy.reaction module. \"\"\" import numpy import", "\"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the MultiPDepArrhenius format.", "Test the Reaction.generateReverseRateCoefficient() method works for the ThirdBody format. \"\"\"", "\"\"\" from rmgpy.kinetics import Troe arrheniusHigh = Arrhenius( A =", "def testEnthalpyOfReaction(self): \"\"\" Test the Reaction.getEnthalpyOfReaction() method. \"\"\" Tlist =", "= reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientPDepArrhenius(self):", "= numpy.array([1e-1,1e1]) comment = 'CH3 + C2H6 <=> CH4 +", "self.assertFalse(self.reaction2.hasTemplate(reactants, products)) self.assertFalse(self.reaction2.hasTemplate(products, reactants)) reactants.reverse() products.reverse() self.assertTrue(self.reaction.hasTemplate(reactants, products)) self.assertTrue(self.reaction.hasTemplate(products, reactants))", "lindemann = Lindemann( arrheniusHigh = arrheniusHigh, arrheniusLow = arrheniusLow, Tmin", "of information. \"\"\" exec('reaction = %r' % (self.reaction)) self.assertEqual(len(self.reaction.reactants), len(reaction.reactants))", "comment, ), ] original_kinetics = MultiPDepArrhenius( arrhenius = arrhenius, Tmin", "for the MultiPDepArrhenius format. \"\"\" from rmgpy.kinetics import PDepArrhenius, MultiPDepArrhenius", "= 1, ), ) ethyl = Species( label = 'C2H5',", "B=(500.0,\"K\"), H0=(-1.439e+05,\"J/mol\"), S0=(-524.6,\"J/(mol*K)\")), ) # [O][O] oxygen = Species( label='oxygen',", "no loss of information. \"\"\" import cPickle reaction = cPickle.loads(cPickle.dumps(self.reaction,-1))", "self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=ab'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=cde'))) def test2to3(self): r1 = self.makeReaction('AB=CDE') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cde'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ba=edc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dec=ba')))", "200.0, numpy.float64) Kalist0 = [float(v) for v in ['8.75951e+29', '7.1843e+10',", "2} Tmin = 300. Tmax = 2000. Pmin = 0.01", "the fit is satisfactory (defined here as always within 5%)", "range(len(Tlist)): self.assertAlmostEqual(klist[i], klist2[i], delta=5e-2 * klist[i]) def testPickle(self): \"\"\" Test", "Tmax = (2000.0,\"K\"), comment = \"\"\"This data is completely made", "self.assertAlmostEqual(product0.conformer.E0.value_si / 1e6, product.conformer.E0.value_si / 1e6, 2) self.assertEqual(product0.conformer.E0.units, product.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.conformer.E0.value_si", "\"\"\" This module contains unit tests of the rmgpy.reaction module.", "6, \"[Ar]\": 0.7, \"[C]=O\": 1.5, \"[H][H]\": 2} Tmin = 300.", "method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kalist0 =", "rmgpy.kinetics import ThirdBody arrheniusLow = Arrhenius( A = (2.62e+33,\"cm^6/(mol^2*s)\"), n", "i in range(len(Tlist)): self.assertAlmostEqual(Hlist[i] / 1000., Hlist0[i] / 1000., 2)", "2, opticalIsomers = 1, ), frequency = (-750.232, 'cm^-1'), )", "Make a Reaction (containing PseudoSpecies) of from a string like", "Reaction.getStoichiometricCoefficient() method. \"\"\" for reactant in self.reaction.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), -1) for", "= (T1,\"K\"), T2 = (T2,\"K\"), Tmin = (Tmin,\"K\"), Tmax =", "= self.reaction2.products[:] self.assertFalse(self.reaction.hasTemplate(reactants, products)) self.assertFalse(self.reaction.hasTemplate(products, reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants, products)) self.assertTrue(self.reaction2.hasTemplate(products, reactants))", "self.assertFalse(self.reaction.hasTemplate(products, reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants, products)) self.assertTrue(self.reaction2.hasTemplate(products, reactants)) def testEnthalpyOfReaction(self): \"\"\" Test", "4) def testEquilibriumConstantKc(self): \"\"\" Test the Reaction.getEquilibriumConstant() method. \"\"\" Tlist", "\"\"\" def makeReaction(self,reaction_string): \"\"\"\" Make a Reaction (containing PseudoSpecies) of", "kr, 1.0, 0) def testGenerateReverseRateCoefficientArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method", "method works for the ArrheniusEP format. \"\"\" from rmgpy.kinetics import", "Ea = (20.0,\"kJ/mol\"), T0 = (300.0,\"K\"), Tmin = (300.0,\"K\"), Tmax", "\"O\": 6, \"[Ar]\": 0.7, \"[C]=O\": 1.5, \"[H][H]\": 2} Tmin =", "CpInf=(15.5*constants.R,\"J/(mol*K)\"), a0=0.2541, a1=-0.4712, a2=-4.434, a3=2.25, B=(500.0,\"K\"), H0=(-1.439e+05,\"J/mol\"), S0=(-524.6,\"J/(mol*K)\")), ) #", "), symmetry = 4, ), HarmonicOscillator( frequencies = ( [828.397,", "= self.reaction2.getRateCoefficient(T, P) / self.reaction2.getEquilibriumConstant(T) kr = reverseKinetics.getRateCoefficient(T) self.assertAlmostEqual(kr0 /", "= 74 T1 = 2941 T2 = 6964 efficiencies =", "= self.makeReaction('A=BC') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=Bc'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('cb=a'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('a=cb'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('bc=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('a=c'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=c'))) def test2to2(self):", "original_kinetics.Tmax, 200.0, numpy.float64) P = 1e5 for T in Tlist:", "pressures = (pressures,\"bar\"), arrhenius = [ Arrhenius( A = (1.4e-11,\"cm^3/(molecule*s)\"),", "comment = comment, ), ] original_kinetics = MultiArrhenius( arrhenius =", "comment = \"\"\"This data is completely made up\"\"\" arrhenius =", "Tmax = 2000. Pmin = 0.01 Pmax = 100. comment", "to ensure Keq is correctly computed self.reaction2.reactants, self.reaction2.products = self.reaction2.products,", "(Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), comment = comment, ), ] original_kinetics", "= (-750.232, 'cm^-1'), ) self.reaction = Reaction( reactants = [hydrogen,", "TS, ) # CC(=O)O[O] acetylperoxy = Species( label='acetylperoxy', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(21.0*constants.R,\"J/(mol*K)\"),", "in Tlist]) # Check that the correct Arrhenius parameters are", "testRateCoefficient(self): \"\"\" Test the Reaction.getRateCoefficient() method. \"\"\" Tlist = numpy.arange(200.0,", "def testGenerateReverseRateCoefficientMultiPDepArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the", "1233.55, 1367.56, 1465.09, 1672.25, 3098.46, 3111.7, 3165.79, 3193.54], 'cm^-1', ),", "Can be used in place of a :class:`rmg.species.Species` for isomorphism", "), ), HinderedRotor( inertia = (1.11481, 'amu*angstrom^2'), symmetry = 6,", "300. Tmax = 2000. Pmin = 0.01 Pmax = 100.", "\"\"\" Contains unit tests of the isomorphism testing of the", "self.makeReaction('AB=CDE') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cde'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ba=edc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dec=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cde=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=abc'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('abe=cde'))) class TestReaction(unittest.TestCase): \"\"\"", "Test the Reaction.generateReverseRateCoefficient() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0,", "a Reaction object can be successfully pickled and unpickled with", "thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(21.0*constants.R,\"J/(mol*K)\"), a0=-3.95, a1=9.26, a2=-15.6, a3=8.55, B=(500.0,\"K\"), H0=(-6.151e+04,\"J/mol\"), S0=(-790.2,\"J/(mol*K)\")), )", "Reaction.getRateCoefficient() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) P", "method that is called prior to each unit test in", "efficiencies, comment = comment, ) original_kinetics = troe self.reaction2.kinetics =", "(2000.0,\"K\"), comment = \"\"\"This data is completely made up\"\"\", )", "reaction.products): self.assertAlmostEqual(product0.conformer.E0.value_si / 1e6, product.conformer.E0.value_si / 1e6, 2) self.assertEqual(product0.conformer.E0.units, product.conformer.E0.units)", "product.conformer.E0.value_si / 1e6, 2) self.assertEqual(product0.conformer.E0.units, product.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.conformer.E0.value_si / 1e6, reaction.transitionState.conformer.E0.value_si", "Pmax = (Pmax,\"bar\"), efficiencies = efficiencies, comment = comment, )", "= [float(v) for v in ['1.45661e+28', '2.38935e+09', '1709.76', '1.74189', '0.0314866',", "that the correct Arrhenius parameters are returned self.assertAlmostEqual(arrhenius.A.value_si, 2265.2488, delta=1e-2)", "method works for the Arrhenius format. \"\"\" original_kinetics = Arrhenius(", "2) def testEquilibriumConstantKa(self): \"\"\" Test the Reaction.getEquilibriumConstant() method. \"\"\" Tlist", "Test the Reaction.generateReverseRateCoefficient() method works for the MultiPDepArrhenius format. \"\"\"", "testGenerateReverseRateCoefficientThirdBody(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the ThirdBody", "self.assertAlmostEqual(self.reaction.kinetics.A.value_si, reaction.kinetics.A.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.n.value_si, reaction.kinetics.n.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.T0.value_si, reaction.kinetics.T0.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.Ea.value_si,", "1.0, 4) def testEquilibriumConstantKc(self): \"\"\" Test the Reaction.getEquilibriumConstant() method. \"\"\"", "troe self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics = reverseKinetics", "10.0]) arrhenius = [arrhenius0, arrhenius1] Tmin = 300.0 Tmax =", "arrheniusHigh = arrheniusHigh, arrheniusLow = arrheniusLow, Tmin = (Tmin,\"K\"), Tmax", "n = 0.0, Ea = (11200*constants.R*0.001,\"kJ/mol\"), T0 = (1,\"K\"), Tmin", "= ( [828.397, 970.652, 977.223, 1052.93, 1233.55, 1367.56, 1465.09, 1672.25,", "the PDepArrhenius format. \"\"\" from rmgpy.kinetics import PDepArrhenius arrhenius0 =", "= \"\"\"H + CH3 -> CH4\"\"\" troe = Troe( arrheniusHigh", "self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=abc'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('abe=cde'))) class TestReaction(unittest.TestCase): \"\"\" Contains unit tests of the", "= comment, ) original_kinetics = thirdBody self.reaction2.kinetics = original_kinetics reverseKinetics", "numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kalist0 = [float(v) for v in", "self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cde'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ba=edc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dec=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cde=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=abc'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('abe=cde'))) class TestReaction(unittest.TestCase): \"\"\" Contains", "Tmax, 200.0, numpy.float64) P = 1e5 for T in Tlist:", "[float(v) for v in ['-156.793', '-156.872', '-153.504', '-150.317', '-147.707', '-145.616',", "= self.reaction2.getFreeEnergiesOfReaction(Tlist) for i in range(len(Tlist)): self.assertAlmostEqual(Glist[i] / 1000., Glist0[i]", "= (Pmax,\"bar\"), efficiencies = efficiencies, comment = comment, ) original_kinetics", "Reaction.generateReverseRateCoefficient() method works for the Lindemann format. \"\"\" from rmgpy.kinetics", "self.assertTrue(isomerization.isIsomerization()) self.assertFalse(association.isIsomerization()) self.assertFalse(dissociation.isIsomerization()) self.assertFalse(bimolecular.isIsomerization()) def testIsAssociation(self): \"\"\" Test the Reaction.isAssociation()", "), transitionState = TS, ) # CC(=O)O[O] acetylperoxy = Species(", "2, opticalIsomers = 1, ), ) TS = TransitionState( label", "reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientMultiPDepArrhenius(self): \"\"\"", "), HinderedRotor( inertia = (1.11481, 'amu*angstrom^2'), symmetry = 6, barrier", "output with no loss of information. \"\"\" exec('reaction = %r'", "for T in Tlist]) # Check that the correct Arrhenius", "3101.54, 3204.73], 'cm^-1', ), ), HinderedRotor( inertia = (1.11481, 'amu*angstrom^2'),", "reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants, products)) self.assertFalse(self.reaction2.hasTemplate(products, reactants)) reactants = self.reaction2.reactants[:] products =", "object can be successfully pickled and unpickled with no loss", "'0.0235579', '0.00334673', '0.000792389', '0.000262777', '0.000110053']] Kalist = self.reaction2.getEquilibriumConstants(Tlist, type='Ka') for", "for T in Tlist: korig = original_kinetics.getRateCoefficient(T, P) krevrev =", "self.assertEqual(self.reaction.degeneracy, reaction.degeneracy) def testOutput(self): \"\"\" Test that a Reaction object", "products] return Reaction(reactants=reactants, products=products) def test1to1(self): r1 = self.makeReaction('A=B') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=B')))", "a0=-0.9324, a1=26.18, a2=-70.47, a3=44.12, B=(500.0,\"K\"), H0=(1.453e+04,\"J/mol\"), S0=(-12.19,\"J/(mol*K)\")), ) self.reaction2 =", "'1.74189', '0.0314866', '0.00235045', '0.000389568', '0.000105413', '3.93273e-05', '1.83006e-05']] Kclist = self.reaction2.getEquilibriumConstants(Tlist,", "P = 1e5 reverseKinetics = self.reaction2.generateReverseRateCoefficient() for T in Tlist:", "(Tmax,\"K\"), comment = comment, ), ], Tmin = (Tmin,\"K\"), Tmax", "def testGenerateReverseRateCoefficientMultiArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the", "comment = comment, ), Arrhenius( A = (1.4e-9,\"cm^3/(molecule*s)\"), n =", "for v in ['8.75951e+24', '718430', '0.342727', '0.000261877', '3.78696e-06', '2.35579e-07', '3.34673e-08',", "HarmonicOscillator from rmgpy.statmech.torsion import Torsion, HinderedRotor from rmgpy.statmech.conformer import Conformer", "comment = \"\"\"H + CH3 -> CH4\"\"\" thirdBody = ThirdBody(", "v in ['8.75951e+29', '7.1843e+10', '34272.7', '26.1877', '0.378696', '0.0235579', '0.00334673', '0.000792389',", "testGenerateReverseRateCoefficientMultiPDepArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the MultiPDepArrhenius", "self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientPDepArrhenius(self): \"\"\" Test the", "from rmgpy.statmech.rotation import Rotation, LinearRotor, NonlinearRotor, KRotor, SphericalTopRotor from rmgpy.statmech.vibration", "the reverse yields the original Tlist = numpy.arange(original_kinetics.Tmin.value_si, original_kinetics.Tmax.value_si, 200.0,", "Species, TransitionState from rmgpy.reaction import Reaction from rmgpy.statmech.translation import Translation,", "in ['-114648', '-83137.2', '-52092.4', '-21719.3', '8073.53', '37398.1', '66346.8', '94990.6', '123383',", "H0=(-6.151e+04,\"J/mol\"), S0=(-790.2,\"J/(mol*K)\")), ) # C[C]=O acetyl = Species( label='acetyl', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"),", "works for the MultiPDepArrhenius format. \"\"\" from rmgpy.kinetics import PDepArrhenius,", "A = (2.65e12, 'cm^3/(mol*s)'), n = 0.0, alpha = 0.5,", "def test2to2(self): r1 = self.makeReaction('AB=CD') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cd'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=dc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dc=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cd=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=ab')))", "'37398.1', '66346.8', '94990.6', '123383', '151565']] Glist = self.reaction2.getFreeEnergiesOfReaction(Tlist) for i", "from rmgpy.kinetics import PDepArrhenius arrhenius0 = Arrhenius( A = (1.0e6,\"s^-1\"),", "\"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the Arrhenius format.", "\"\"\" Test the Reaction.getEquilibriumConstant() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0,", "1e6, reactant.conformer.E0.value_si / 1e6, 2) self.assertEqual(reactant0.conformer.E0.units, reactant.conformer.E0.units) for product0, product", "import rmgpy.constants as constants ################################################################################ class PseudoSpecies: \"\"\" Can be", "T0 = (1,\"K\"), Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), comment", "= (Pmax,\"bar\"), comment = comment, ) self.reaction2.kinetics = original_kinetics reverseKinetics", "H + C2H4 -> C2H5. \"\"\" Tlist = 1000.0/numpy.arange(0.4, 3.35,", "IdealGasTranslation( mass = (29.0391, 'amu'), ), NonlinearRotor( inertia = (", "= Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertTrue(isomerization.isIsomerization()) self.assertFalse(association.isIsomerization()) self.assertFalse(dissociation.isIsomerization()) self.assertFalse(bimolecular.isIsomerization()) def testIsAssociation(self): \"\"\"", "2) self.assertEqual(reactant0.conformer.E0.units, reactant.conformer.E0.units) for product0, product in zip(self.reaction.products, reaction.products): self.assertAlmostEqual(product0.conformer.E0.value_si", "(Tmax,\"K\"), Pmin = (Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), efficiencies = efficiencies,", "(2.65e12, 'cm^3/(mol*s)'), n = 0.0, alpha = 0.5, E0 =", "0) @work_in_progress def testGenerateReverseRateCoefficientArrheniusEP(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works", "= 6964 efficiencies = {\"C\": 3, \"C(=O)=O\": 2, \"CC\": 3,", "1024.16, 1224.21, 1326.36, 1455.06, 1600.35, 3101.46, 3110.55, 3175.34, 3201.88], 'cm^-1',", "(20.0,\"kJ/mol\"), T0 = (300.0,\"K\"), Tmin = (300.0,\"K\"), Tmax = (2000.0,\"K\"),", "'K'), ), ) def testIsIsomerization(self): \"\"\" Test the Reaction.isIsomerization() method.", "test2to3(self): r1 = self.makeReaction('AB=CDE') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cde'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ba=edc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dec=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cde=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=abc'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('abe=cde')))", "'-141.407', '-140.441']] Slist = self.reaction2.getEntropiesOfReaction(Tlist) for i in range(len(Tlist)): self.assertAlmostEqual(Slist[i],", "transitionState = TS, ) # CC(=O)O[O] acetylperoxy = Species( label='acetylperoxy',", "Test the Reaction.getEnthalpyOfReaction() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0,", "/ Kalist0[i], 1.0, 4) def testEquilibriumConstantKc(self): \"\"\" Test the Reaction.getEquilibriumConstant()", "testOutput(self): \"\"\" Test that a Reaction object can be successfully", "i in range(len(Tlist)): self.assertAlmostEqual(Slist[i], Slist0[i], 2) def testFreeEnergyOfReaction(self): \"\"\" Test", "Kclist = self.reaction2.getEquilibriumConstants(Tlist, type='Kc') for i in range(len(Tlist)): self.assertAlmostEqual(Kclist[i] /", "= reverseKinetics.getRateCoefficient(T) self.assertAlmostEqual(kr0 / kr, 1.0, 0) def testGenerateReverseRateCoefficientArrhenius(self): \"\"\"", "{\"C\": 3, \"C(=O)=O\": 2, \"CC\": 3, \"O\": 6, \"[Ar]\": 0.7,", "\"\"\" Test the Reaction.getFreeEnergyOfReaction() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0,", "self.assertEqual(self.reaction.duplicate, reaction.duplicate) self.assertEqual(self.reaction.degeneracy, reaction.degeneracy) ################################################################################ if __name__ == '__main__': unittest.main(testRunner=unittest.TextTestRunner(verbosity=2))", "'-142.552', '-141.407', '-140.441']] Slist = self.reaction2.getEntropiesOfReaction(Tlist) for i in range(len(Tlist)):", "self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), 0) for product in self.reaction2.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 0) def testRateCoefficient(self):", "Rotation, LinearRotor, NonlinearRotor, KRotor, SphericalTopRotor from rmgpy.statmech.vibration import Vibration, HarmonicOscillator", "* klist[i]) def testPickle(self): \"\"\" Test that a Reaction object", "/ 1000., Hlist0[i] / 1000., 2) def testEntropyOfReaction(self): \"\"\" Test", "Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Glist0 = [float(v) for", "\"\"\" from rmgpy.kinetics import PDepArrhenius arrhenius0 = Arrhenius( A =", "), HarmonicOscillator( frequencies = ( [412.75, 415.206, 821.495, 924.44, 982.714,", "self.assertAlmostEqual(self.reaction.kinetics.Ea.value_si, reaction.kinetics.Ea.value_si, delta=1e-6) self.assertEqual(self.reaction.kinetics.comment, reaction.kinetics.comment) self.assertEqual(self.reaction.duplicate, reaction.duplicate) self.assertEqual(self.reaction.degeneracy, reaction.degeneracy) ################################################################################", "Species( label = 'C2H4', conformer = Conformer( E0 = (44.7127,", "E0 = (211.794, 'kJ/mol'), modes = [ IdealGasTranslation( mass =", "delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.T0.value_si, reaction.kinetics.T0.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.Ea.value_si, reaction.kinetics.Ea.value_si, delta=1e-6) self.assertEqual(self.reaction.kinetics.comment, reaction.kinetics.comment) self.assertEqual(self.reaction.duplicate,", "(1.0e6,\"s^-1\"), n = 1.0, Ea = (10.0,\"kJ/mol\"), T0 = (300.0,\"K\"),", "in ['8.75951e+24', '718430', '0.342727', '0.000261877', '3.78696e-06', '2.35579e-07', '3.34673e-08', '7.92389e-09', '2.62777e-09',", "products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertTrue(isomerization.isIsomerization()) self.assertFalse(association.isIsomerization()) self.assertFalse(dissociation.isIsomerization()) self.assertFalse(bimolecular.isIsomerization()) def", "Reaction class. \"\"\" def makeReaction(self,reaction_string): \"\"\"\" Make a Reaction (containing", "NonlinearRotor( inertia = ( [4.8709, 22.2353, 23.9925], 'amu*angstrom^2', ), symmetry", "3, \"C(=O)=O\": 2, \"CC\": 3, \"O\": 6, \"[Ar]\": 0.7, \"[C]=O\":", "= reaction_string.split('=') reactants = [PseudoSpecies(i) for i in reactants] products", "products=[Species()]) dissociation = Reaction(reactants=[Species()], products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertFalse(isomerization.isDissociation())", "reaction_string.split('=') reactants = [PseudoSpecies(i) for i in reactants] products =", "Tmin = (300, 'K'), Tmax = (2000, 'K'), ) self.reaction2.kinetics", "-4.76, Ea = (10.21,\"kJ/mol\"), T0 = (1,\"K\"), ) alpha =", "'kJ/mol'), Tmin = (300, 'K'), Tmax = (2000, 'K'), )", "6645.24, delta=1e-2) # Check that the fit is satisfactory (defined", "MultiArrhenius format. \"\"\" from rmgpy.kinetics import MultiArrhenius pressures = numpy.array([0.1,", "Troe( arrheniusHigh = arrheniusHigh, arrheniusLow = arrheniusLow, alpha = alpha,", "1e6, 2) self.assertEqual(self.reaction.transitionState.conformer.E0.units, reaction.transitionState.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.frequency.value_si, reaction.transitionState.frequency.value_si, 2) self.assertEqual(self.reaction.transitionState.frequency.units, reaction.transitionState.frequency.units) self.assertAlmostEqual(self.reaction.kinetics.A.value_si,", "(44.7127, 'kJ/mol'), modes = [ IdealGasTranslation( mass = (28.0313, 'amu'),", "Tmax = (2000, 'K'), ) self.reaction2.kinetics = original_kinetics reverseKinetics =", "= (1,\"K\"), ) alpha = 0.783 T3 = 74 T1", "original Tlist = numpy.arange(Tmin, Tmax, 200.0, numpy.float64) P = 1e5", "\"\"\"This data is completely made up\"\"\" original_kinetics = PDepArrhenius( pressures", "HarmonicOscillator( frequencies = ( [482.224, 791.876, 974.355, 1051.48, 1183.21, 1361.36,", "modes = [ IdealGasTranslation( mass = (28.0313, 'amu'), ), NonlinearRotor(", "KRotor, SphericalTopRotor from rmgpy.statmech.vibration import Vibration, HarmonicOscillator from rmgpy.statmech.torsion import", "Tmin = (300, 'K'), Tmax = (2000, 'K'), ), )", "Tmax = (Tmax,\"K\"), Pmin = (Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), efficiencies", "from rmgpy.kinetics import ArrheniusEP original_kinetics = ArrheniusEP( A = (2.65e12,", "module contains unit tests of the rmgpy.reaction module. \"\"\" import", "(Baulch 2005)' arrhenius = [ PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius", "in self.reaction.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 1) for reactant in self.reaction2.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), 0)", "] original_kinetics = MultiArrhenius( arrhenius = arrhenius, Tmin = (Tmin,\"K\"),", "in zip(self.reaction.products, reaction.products): self.assertAlmostEqual(product0.conformer.E0.value_si / 1e6, product.conformer.E0.value_si / 1e6, 2)", "successfully reconstructed from its repr() output with no loss of", "[828.397, 970.652, 977.223, 1052.93, 1233.55, 1367.56, 1465.09, 1672.25, 3098.46, 3111.7,", "= (4.32508, 'kJ/mol'), T0 = (1, 'K'), Tmin = (300,", "\"\"\" Test that a Reaction object can be successfully reconstructed", "'1.10053e-09']] Kplist = self.reaction2.getEquilibriumConstants(Tlist, type='Kp') for i in range(len(Tlist)): self.assertAlmostEqual(Kplist[i]", "= [ IdealGasTranslation( mass = (29.0391, 'amu'), ), NonlinearRotor( inertia", "(Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), efficiencies = efficiencies, comment = comment,", "= self.reaction2.reactants[:] products = self.reaction2.products[:] self.assertFalse(self.reaction.hasTemplate(reactants, products)) self.assertFalse(self.reaction.hasTemplate(products, reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants,", "= (Tmin,\"K\"), Tmax = (Tmax,\"K\"), comment = comment, ), ]", "), HarmonicOscillator( frequencies = ( [828.397, 970.652, 977.223, 1052.93, 1233.55,", "product in self.reaction.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 1) for reactant in self.reaction2.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant),", "with no loss of information. \"\"\" exec('reaction = %r' %", "self.reaction2.getEquilibriumConstants(Tlist, type='Kc') for i in range(len(Tlist)): self.assertAlmostEqual(Kclist[i] / Kclist0[i], 1.0,", "pressures = numpy.array([0.1, 10.0]) Tmin = 300.0 Tmax = 2000.0", "Arrhenius( A = (9.3e-14,\"cm^3/(molecule*s)\"), n = 0.0, Ea = (4740*constants.R*0.001,\"kJ/mol\"),", "label = 'C2H5', conformer = Conformer( E0 = (111.603, 'kJ/mol'),", "in Tlist: korig = original_kinetics.getRateCoefficient(T, P) krevrev = reversereverseKinetics.getRateCoefficient(T, P)", "def testGenerateReverseRateCoefficientArrheniusEP(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the", "20.065], 'amu*angstrom^2', ), symmetry = 4, ), HarmonicOscillator( frequencies =", "data is completely made up\"\"\", ) arrhenius1 = Arrhenius( A", "in this class. \"\"\" ethylene = Species( label = 'C2H4',", "import Lindemann arrheniusHigh = Arrhenius( A = (1.39e+16,\"cm^3/(mol*s)\"), n =", "), symmetry = 1, ), HarmonicOscillator( frequencies = ( [412.75,", "other): return self.label.lower() == other.label.lower() class TestReactionIsomorphism(unittest.TestCase): \"\"\" Contains unit", "CH3 -> CH4\"\"\" troe = Troe( arrheniusHigh = arrheniusHigh, arrheniusLow", "from rmgpy.statmech.torsion import Torsion, HinderedRotor from rmgpy.statmech.conformer import Conformer from", "= (1,\"K\"), Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), comment =", "n = 1.637, Ea = (4.32508, 'kJ/mol'), T0 = (1,", "kinetics = Arrhenius( A = (2.65e12, 'cm^3/(mol*s)'), n = 0.0,", "= 1, ), ) TS = TransitionState( label = 'TS',", "Reaction( reactants=[acetyl, oxygen], products=[acetylperoxy], kinetics = Arrhenius( A = (2.65e12,", "in ['1.45661e+28', '2.38935e+09', '1709.76', '1.74189', '0.0314866', '0.00235045', '0.000389568', '0.000105413', '3.93273e-05',", "kr0 = self.reaction2.getRateCoefficient(T, P) / self.reaction2.getEquilibriumConstant(T) kr = reverseKinetics.getRateCoefficient(T) self.assertAlmostEqual(kr0", "2001.0, 200.0, numpy.float64) Kplist0 = [float(v) for v in ['8.75951e+24',", "\"\"\"This data is completely made up\"\"\" arrhenius = [ Arrhenius(", "v in ['8.75951e+24', '718430', '0.342727', '0.000261877', '3.78696e-06', '2.35579e-07', '3.34673e-08', '7.92389e-09',", "import ThirdBody arrheniusLow = Arrhenius( A = (2.62e+33,\"cm^6/(mol^2*s)\"), n =", "in Tlist: kr0 = self.reaction2.getRateCoefficient(T, P) / self.reaction2.getEquilibriumConstant(T) kr =", ") original_kinetics = troe self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient()", "['-114648', '-83137.2', '-52092.4', '-21719.3', '8073.53', '37398.1', '66346.8', '94990.6', '123383', '151565']]", "reverse yields the original Tlist = numpy.arange(original_kinetics.Tmin.value_si, original_kinetics.Tmax.value_si, 200.0, numpy.float64)", "Tlist = 1000.0/numpy.arange(0.4, 3.35, 0.01) klist = numpy.array([self.reaction.calculateTSTRateCoefficient(T) for T", "a string like 'Ab=CD' \"\"\" reactants, products = reaction_string.split('=') reactants", "2688.22, 2954.51, 3033.39, 3101.54, 3204.73], 'cm^-1', ), ), HinderedRotor( inertia", "\"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Glist0 = [float(v)", "(2000, 'K'), ), ) def testIsIsomerization(self): \"\"\" Test the Reaction.isIsomerization()", "fit is satisfactory (defined here as always within 5%) for", "Pmax = 1e1 pressures = numpy.array([1e-1,1e1]) comment = 'CH3 +", "self.assertFalse(self.reaction.hasTemplate(reactants, products)) self.assertFalse(self.reaction.hasTemplate(products, reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants, products)) self.assertTrue(self.reaction2.hasTemplate(products, reactants)) def testEnthalpyOfReaction(self):", "theory k(T) calculation function, using the reaction H + C2H4", "made up\"\"\" arrhenius = [ Arrhenius( A = (9.3e-14,\"cm^3/(molecule*s)\"), n", "/ krevrev, 1.0, 0) def testGenerateReverseRateCoefficientTroe(self): \"\"\" Test the Reaction.generateReverseRateCoefficient()", "E0 = (111.603, 'kJ/mol'), modes = [ IdealGasTranslation( mass =", "of the isomorphism testing of the Reaction class. \"\"\" def", "the ArrheniusEP format. \"\"\" from rmgpy.kinetics import ArrheniusEP original_kinetics =", "924.44, 982.714, 1024.16, 1224.21, 1326.36, 1455.06, 1600.35, 3101.46, 3110.55, 3175.34,", "PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius = [ Arrhenius( A =", "products=[acetylperoxy], kinetics = Arrhenius( A = (2.65e12, 'cm^3/(mol*s)'), n =", "1361.36, 1448.65, 1455.07, 1465.48, 2688.22, 2954.51, 3033.39, 3101.54, 3204.73], 'cm^-1',", "(266.694, 'kJ/mol'), modes = [ IdealGasTranslation( mass = (29.0391, 'amu'),", "delta=1e-2) # Check that the fit is satisfactory (defined here", "i in range(len(Tlist)): self.assertAlmostEqual(Glist[i] / 1000., Glist0[i] / 1000., 2)", "= (Tmax,\"K\"), Pmin = (Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), comment =", "/ self.reaction.kinetics.getRateCoefficient(T), 1.0, 6) def testGenerateReverseRateCoefficient(self): \"\"\" Test the Reaction.generateReverseRateCoefficient()", "\"\"\"This data is completely made up\"\"\", ) arrhenius1 = Arrhenius(", "type='Ka') for i in range(len(Tlist)): self.assertAlmostEqual(Kalist[i] / Kalist0[i], 1.0, 4)", "method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Slist0 =", "C2H6 <=> CH4 + C2H5 (Baulch 2005)' arrhenius = [", "= Conformer( E0 = (266.694, 'kJ/mol'), modes = [ IdealGasTranslation(", "a3=8.55, B=(500.0,\"K\"), H0=(-6.151e+04,\"J/mol\"), S0=(-790.2,\"J/(mol*K)\")), ) # C[C]=O acetyl = Species(", "original_kinetics.getRateCoefficient(T, P) krevrev = reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0,", "reactant in self.reaction2.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), 0) for product in self.reaction2.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product),", "'0.000110053']] Kalist = self.reaction2.getEquilibriumConstants(Tlist, type='Ka') for i in range(len(Tlist)): self.assertAlmostEqual(Kalist[i]", "rmgpy.statmech.torsion import Torsion, HinderedRotor from rmgpy.statmech.conformer import Conformer from rmgpy.kinetics", "Reaction from rmgpy.statmech.translation import Translation, IdealGasTranslation from rmgpy.statmech.rotation import Rotation,", "data is completely made up\"\"\", ) pressures = numpy.array([0.1, 10.0])", "rmgpy.statmech.vibration import Vibration, HarmonicOscillator from rmgpy.statmech.torsion import Torsion, HinderedRotor from", "i in range(len(Tlist)): self.assertAlmostEqual(Kclist[i] / Kclist0[i], 1.0, 4) def testEquilibriumConstantKp(self):", "nothing else. \"\"\" def __init__(self, label): self.label = label def", "), frequency = (-750.232, 'cm^-1'), ) self.reaction = Reaction( reactants", "Tlist]) # Check that the correct Arrhenius parameters are returned", "MultiPDepArrhenius( arrhenius = arrhenius, Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"),", "Test that a Reaction object can be successfully pickled and", "python # encoding: utf-8 -*- \"\"\" This module contains unit", "(1,\"K\"), Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), comment = comment,", "A = (1.0e12,\"s^-1\"), n = 1.0, Ea = (20.0,\"kJ/mol\"), T0", "(29.0391, 'amu'), ), NonlinearRotor( inertia = ( [6.78512, 22.1437, 22.2114],", "'2.62777e-09', '1.10053e-09']] Kplist = self.reaction2.getEquilibriumConstants(Tlist, type='Kp') for i in range(len(Tlist)):", "(Tmax,\"K\"), comment = comment, ), Arrhenius( A = (1.4e-9,\"cm^3/(molecule*s)\"), n", "= Species( label = 'C2H4', conformer = Conformer( E0 =", "testGenerateReverseRateCoefficientTroe(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the Troe", "T1 = 2941 T2 = 6964 efficiencies = {\"C\": 3,", "Conformer( E0 = (266.694, 'kJ/mol'), modes = [ IdealGasTranslation( mass", "1.0, Ea = (10.0,\"kJ/mol\"), T0 = (300.0,\"K\"), Tmin = (300.0,\"K\"),", "Arrhenius( A = (1.39e+16,\"cm^3/(mol*s)\"), n = -0.534, Ea = (2.243,\"kJ/mol\"),", "P) / self.reaction.kinetics.getRateCoefficient(T), 1.0, 6) def testGenerateReverseRateCoefficient(self): \"\"\" Test the", "numpy.float64) Glist0 = [float(v) for v in ['-114648', '-83137.2', '-52092.4',", "'0.342727', '0.000261877', '3.78696e-06', '2.35579e-07', '3.34673e-08', '7.92389e-09', '2.62777e-09', '1.10053e-09']] Kplist =", "cPickle.loads(cPickle.dumps(self.reaction,-1)) self.assertEqual(len(self.reaction.reactants), len(reaction.reactants)) self.assertEqual(len(self.reaction.products), len(reaction.products)) for reactant0, reactant in zip(self.reaction.reactants,", "Pmax = (Pmax,\"bar\"), comment = comment, ) self.reaction2.kinetics = original_kinetics", "= (0.244029, 'kJ/mol'), semiclassical = None, ), ], spinMultiplicity =", "-> CH4\"\"\" troe = Troe( arrheniusHigh = arrheniusHigh, arrheniusLow =", "unpickled with no loss of information. \"\"\" import cPickle reaction", "numpy.arange(200.0, 2001.0, 200.0, numpy.float64) P = 1e5 reverseKinetics = self.reaction2.generateReverseRateCoefficient()", "H0=(1.453e+04,\"J/mol\"), S0=(-12.19,\"J/(mol*K)\")), ) self.reaction2 = Reaction( reactants=[acetyl, oxygen], products=[acetylperoxy], kinetics", "= 300.0 Tmax = 2000.0 Pmin = 0.1 Pmax =", "frequencies = ( [412.75, 415.206, 821.495, 924.44, 982.714, 1024.16, 1224.21,", "Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) P = 1e5 for", "original Tlist = numpy.arange(original_kinetics.Tmin, original_kinetics.Tmax, 200.0, numpy.float64) P = 1e5", "\"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kalist0 = [float(v)", "Reaction.getEquilibriumConstant() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kclist0", "products=[Species(),Species()]) self.assertFalse(isomerization.isDissociation()) self.assertFalse(association.isDissociation()) self.assertTrue(dissociation.isDissociation()) self.assertFalse(bimolecular.isDissociation()) def testHasTemplate(self): \"\"\" Test the", "import ArrheniusEP original_kinetics = ArrheniusEP( A = (2.65e12, 'cm^3/(mol*s)'), n", "= (2.243,\"kJ/mol\"), T0 = (1,\"K\"), ) arrheniusLow = Arrhenius( A", "= TS, ) # CC(=O)O[O] acetylperoxy = Species( label='acetylperoxy', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"),", "0) for product in self.reaction2.products: self.assertEqual(self.reaction.getStoichiometricCoefficient(product), 0) def testRateCoefficient(self): \"\"\"", "up\"\"\" original_kinetics = PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius = arrhenius,", "self.reaction.reactants[:] products = self.reaction.products[:] self.assertTrue(self.reaction.hasTemplate(reactants, products)) self.assertTrue(self.reaction.hasTemplate(products, reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants, products))", "= self.reaction2.getEquilibriumConstants(Tlist, type='Kc') for i in range(len(Tlist)): self.assertAlmostEqual(Kclist[i] / Kclist0[i],", "2005)' arrhenius = [ PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius =", "reactants)) reactants.reverse() products.reverse() self.assertFalse(self.reaction.hasTemplate(reactants, products)) self.assertFalse(self.reaction.hasTemplate(products, reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants, products)) self.assertTrue(self.reaction2.hasTemplate(products,", "'66346.8', '94990.6', '123383', '151565']] Glist = self.reaction2.getFreeEnergiesOfReaction(Tlist) for i in", "rmgpy.statmech.conformer import Conformer from rmgpy.kinetics import Arrhenius from rmgpy.thermo import", "CpInf=(21.0*constants.R,\"J/(mol*K)\"), a0=-3.95, a1=9.26, a2=-15.6, a3=8.55, B=(500.0,\"K\"), H0=(-6.151e+04,\"J/mol\"), S0=(-790.2,\"J/(mol*K)\")), ) #", "the Reaction.getEquilibriumConstant() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64)", "\"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Slist0 = [float(v)", "comment = comment, ), ] original_kinetics = MultiPDepArrhenius( arrhenius =", "def isIsomorphic(self, other): return self.label.lower() == other.label.lower() class TestReactionIsomorphism(unittest.TestCase): \"\"\"", "Reaction.generateReverseRateCoefficient() method works for the PDepArrhenius format. \"\"\" from rmgpy.kinetics", "(300, 'K'), Tmax = (2000, 'K'), ) self.reaction2.kinetics = original_kinetics", "inertia = ( [3.41526, 16.6498, 20.065], 'amu*angstrom^2', ), symmetry =", "contains unit tests of the rmgpy.reaction module. \"\"\" import numpy", "(1.4e-11,\"cm^3/(molecule*s)\"), n = 0.0, Ea = (11200*constants.R*0.001,\"kJ/mol\"), T0 = (1,\"K\"),", "self.assertAlmostEqual(self.reaction.kinetics.n.value_si, reaction.kinetics.n.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.T0.value_si, reaction.kinetics.T0.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.Ea.value_si, reaction.kinetics.Ea.value_si, delta=1e-6) self.assertEqual(self.reaction.kinetics.comment,", "1326.36, 1455.06, 1600.35, 3101.46, 3110.55, 3175.34, 3201.88], 'cm^-1', ), ),", "[O][O] oxygen = Species( label='oxygen', thermo=Wilhoit(Cp0=(3.5*constants.R,\"J/(mol*K)\"), CpInf=(4.5*constants.R,\"J/(mol*K)\"), a0=-0.9324, a1=26.18, a2=-70.47,", "v in ['-146007', '-145886', '-144195', '-141973', '-139633', '-137341', '-135155', '-133093',", "inertia = (1.11481, 'amu*angstrom^2'), symmetry = 6, barrier = (0.244029,", "Test the Reaction.getFreeEnergyOfReaction() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0,", "reaction.duplicate) self.assertEqual(self.reaction.degeneracy, reaction.degeneracy) def testOutput(self): \"\"\" Test that a Reaction", "that is called prior to each unit test in this", "and unpickled with no loss of information. \"\"\" import cPickle", "'-139633', '-137341', '-135155', '-133093', '-131150', '-129316']] Hlist = self.reaction2.getEnthalpiesOfReaction(Tlist) for", "format. \"\"\" original_kinetics = Arrhenius( A = (2.65e12, 'cm^3/(mol*s)'), n", "products = [PseudoSpecies(i) for i in products] return Reaction(reactants=reactants, products=products)", "'2.35579e-07', '3.34673e-08', '7.92389e-09', '2.62777e-09', '1.10053e-09']] Kplist = self.reaction2.getEquilibriumConstants(Tlist, type='Kp') for", "from rmgpy.statmech.translation import Translation, IdealGasTranslation from rmgpy.statmech.rotation import Rotation, LinearRotor,", "label = 'C2H4', conformer = Conformer( E0 = (44.7127, 'kJ/mol'),", "\"\"\" Test the Reaction.getEnthalpyOfReaction() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0,", "delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.Ea.value_si, reaction.kinetics.Ea.value_si, delta=1e-6) self.assertEqual(self.reaction.kinetics.comment, reaction.kinetics.comment) self.assertEqual(self.reaction.duplicate, reaction.duplicate) self.assertEqual(self.reaction.degeneracy, reaction.degeneracy)", "krevrev, 1.0, 0) def testGenerateReverseRateCoefficientMultiPDepArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method", "this class. \"\"\" ethylene = Species( label = 'C2H4', conformer", "numpy.array([0.1, 10.0]) arrhenius = [arrhenius0, arrhenius1] Tmin = 300.0 Tmax", "conformer = Conformer( E0 = (211.794, 'kJ/mol'), modes = [", "'K'), ), transitionState = TS, ) # CC(=O)O[O] acetylperoxy =", "Tmax = (Tmax,\"K\"), comment = comment, ) self.reaction2.kinetics = original_kinetics", "works for the MultiArrhenius format. \"\"\" from rmgpy.kinetics import MultiArrhenius", "= efficiencies, comment = comment, ) original_kinetics = troe self.reaction2.kinetics", "'amu'), ), NonlinearRotor( inertia = ( [4.8709, 22.2353, 23.9925], 'amu*angstrom^2',", "that reverting the reverse yields the original Tlist = numpy.arange(Tmin,", "0.0, Ea = (4740*constants.R*0.001,\"kJ/mol\"), T0 = (1,\"K\"), Tmin = (Tmin,\"K\"),", "testIsAssociation(self): \"\"\" Test the Reaction.isAssociation() method. \"\"\" isomerization = Reaction(reactants=[Species()],", "n = -4.76, Ea = (10.21,\"kJ/mol\"), T0 = (1,\"K\"), )", "thermo=Wilhoit(Cp0=(3.5*constants.R,\"J/(mol*K)\"), CpInf=(4.5*constants.R,\"J/(mol*K)\"), a0=-0.9324, a1=26.18, a2=-70.47, a3=44.12, B=(500.0,\"K\"), H0=(1.453e+04,\"J/mol\"), S0=(-12.19,\"J/(mol*K)\")), )", "= (9.3e-14,\"cm^3/(molecule*s)\"), n = 0.0, Ea = (4740*constants.R*0.001,\"kJ/mol\"), T0 =", "a1=9.26, a2=-15.6, a3=8.55, B=(500.0,\"K\"), H0=(-6.151e+04,\"J/mol\"), S0=(-790.2,\"J/(mol*K)\")), ) # C[C]=O acetyl", "zip(self.reaction.products, reaction.products): self.assertAlmostEqual(product0.conformer.E0.value_si / 1e6, product.conformer.E0.value_si / 1e6, 2) self.assertEqual(product0.conformer.E0.units,", "krevrev = reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def", "self.assertTrue(self.reaction.hasTemplate(reactants, products)) self.assertTrue(self.reaction.hasTemplate(products, reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants, products)) self.assertFalse(self.reaction2.hasTemplate(products, reactants)) reactants =", "reverseKinetics = self.reaction2.generateReverseRateCoefficient() for T in Tlist: kr0 = self.reaction2.getRateCoefficient(T,", "'amu'), ), NonlinearRotor( inertia = ( [6.78512, 22.1437, 22.2114], 'amu*angstrom^2',", "1e6, reaction.transitionState.conformer.E0.value_si / 1e6, 2) self.assertEqual(self.reaction.transitionState.conformer.E0.units, reaction.transitionState.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.frequency.value_si, reaction.transitionState.frequency.value_si, 2)", "reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants, products)) self.assertFalse(self.reaction2.hasTemplate(products, reactants)) reactants.reverse() products.reverse() self.assertTrue(self.reaction.hasTemplate(reactants, products)) self.assertTrue(self.reaction.hasTemplate(products,", "Test the Reaction.generateReverseRateCoefficient() method works for the PDepArrhenius format. \"\"\"", "3204.73], 'cm^-1', ), ), HinderedRotor( inertia = (1.11481, 'amu*angstrom^2'), symmetry", "'kJ/mol'), semiclassical = None, ), ], spinMultiplicity = 2, opticalIsomers", "are returned self.assertAlmostEqual(arrhenius.A.value_si, 2265.2488, delta=1e-2) self.assertAlmostEqual(arrhenius.n.value_si, 1.45419, delta=1e-4) self.assertAlmostEqual(arrhenius.Ea.value_si, 6645.24,", "Ea = (2.243,\"kJ/mol\"), T0 = (1,\"K\"), ) arrheniusLow = Arrhenius(", "200.0, numpy.float64) Kclist0 = [float(v) for v in ['1.45661e+28', '2.38935e+09',", "the MultiPDepArrhenius format. \"\"\" from rmgpy.kinetics import PDepArrhenius, MultiPDepArrhenius Tmin", "A = (1.4e-9,\"cm^3/(molecule*s)\"), n = 0.0, Ea = (11200*constants.R*0.001,\"kJ/mol\"), T0", "= arrheniusHigh, arrheniusLow = arrheniusLow, Tmin = (Tmin,\"K\"), Tmax =", "self.assertTrue(r1.isIsomorphic(self.makeReaction('a=Bc'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('cb=a'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('a=cb'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('bc=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('a=c'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=c'))) def test2to2(self): r1 =", "the Reaction.generateReverseRateCoefficient() method works for the ArrheniusEP format. \"\"\" from", "300.0 Tmax = 2000.0 Pmin = 0.1 Pmax = 10.0", "= 100. comment = \"\"\"H + CH3 -> CH4\"\"\" troe", "for i in range(len(Tlist)): self.assertAlmostEqual(Kclist[i] / Kclist0[i], 1.0, 4) def", "self.assertAlmostEqual(Kplist[i] / Kplist0[i], 1.0, 4) def testStoichiometricCoefficient(self): \"\"\" Test the", "P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientMultiPDepArrhenius(self): \"\"\" Test", "/ krevrev, 1.0, 0) def testGenerateReverseRateCoefficientMultiArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient()", "= 0.01 Pmax = 100. comment = \"\"\"H + CH3", "self.assertAlmostEqual(korig / krevrev, 1.0, 0) @work_in_progress def testGenerateReverseRateCoefficientArrheniusEP(self): \"\"\" Test", "Reaction.generateReverseRateCoefficient() method works for the ThirdBody format. \"\"\" from rmgpy.kinetics", "comment, ) self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics =", "self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=c'))) def test2to2(self): r1 = self.makeReaction('AB=CD') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cd'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=dc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dc=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cd=ab'),eitherDirection=False))", "ArrheniusEP format. \"\"\" from rmgpy.kinetics import ArrheniusEP original_kinetics = ArrheniusEP(", "415.206, 821.495, 924.44, 982.714, 1024.16, 1224.21, 1326.36, 1455.06, 1600.35, 3101.46,", "10.0 comment = \"\"\"This data is completely made up\"\"\" arrhenius", "0.0, Ea = (11200*constants.R*0.001,\"kJ/mol\"), T0 = (1,\"K\"), Tmin = (Tmin,\"K\"),", "for v in ['8.75951e+29', '7.1843e+10', '34272.7', '26.1877', '0.378696', '0.0235579', '0.00334673',", "numpy.float64) P = 1e5 for T in Tlist: korig =", "that a Reaction object can be successfully pickled and unpickled", "for the MultiArrhenius format. \"\"\" from rmgpy.kinetics import MultiArrhenius pressures", "[ Arrhenius( A = (9.3e-14,\"cm^3/(molecule*s)\"), n = 0.0, Ea =", "= 2000. Pmin = 0.01 Pmax = 100. comment =", "class. \"\"\" def makeReaction(self,reaction_string): \"\"\"\" Make a Reaction (containing PseudoSpecies)", "the Reaction.getFreeEnergyOfReaction() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64)", "numpy.float64) Kclist0 = [float(v) for v in ['1.45661e+28', '2.38935e+09', '1709.76',", "3110.55, 3175.34, 3201.88], 'cm^-1', ), ), ], spinMultiplicity = 2,", "(Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), comment = comment, ) self.reaction2.kinetics =", "1, ), HarmonicOscillator( frequencies = ( [412.75, 415.206, 821.495, 924.44,", "test in this class. \"\"\" ethylene = Species( label =", "comment = comment, ), Arrhenius( A = (9.3e-14,\"cm^3/(molecule*s)\"), n =", "Conformer( E0 = (44.7127, 'kJ/mol'), modes = [ IdealGasTranslation( mass", "Arrhenius( A = (2.65e12, 'cm^3/(mol*s)'), n = 0.0, Ea =", "the ThirdBody format. \"\"\" from rmgpy.kinetics import ThirdBody arrheniusLow =", "\"\"\" ethylene = Species( label = 'C2H4', conformer = Conformer(", "= original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics = reverseKinetics # reverse", "1455.07, 1465.48, 2688.22, 2954.51, 3033.39, 3101.54, 3204.73], 'cm^-1', ), ),", "import Wilhoit import rmgpy.constants as constants ################################################################################ class PseudoSpecies: \"\"\"", "(9.3e-14,\"cm^3/(molecule*s)\"), n = 0.0, Ea = (4740*constants.R*0.001,\"kJ/mol\"), T0 = (1,\"K\"),", "= (1,\"K\"), ) efficiencies = {\"C\": 3, \"C(=O)=O\": 2, \"CC\":", "CpInf=(4.5*constants.R,\"J/(mol*K)\"), a0=-0.9324, a1=26.18, a2=-70.47, a3=44.12, B=(500.0,\"K\"), H0=(1.453e+04,\"J/mol\"), S0=(-12.19,\"J/(mol*K)\")), ) self.reaction2", "\"\"\" Test the Reaction.isIsomerization() method. \"\"\" isomerization = Reaction(reactants=[Species()], products=[Species()])", "self.assertFalse(association.isDissociation()) self.assertTrue(dissociation.isDissociation()) self.assertFalse(bimolecular.isDissociation()) def testHasTemplate(self): \"\"\" Test the Reaction.hasTemplate() method.", "returned self.assertAlmostEqual(arrhenius.A.value_si, 2265.2488, delta=1e-2) self.assertAlmostEqual(arrhenius.n.value_si, 1.45419, delta=1e-4) self.assertAlmostEqual(arrhenius.Ea.value_si, 6645.24, delta=1e-2)", "original_kinetics = MultiPDepArrhenius( arrhenius = arrhenius, Tmin = (Tmin,\"K\"), Tmax", "the Reaction.generateReverseRateCoefficient() method works for the Troe format. \"\"\" from", "setUp(self): \"\"\" A method that is called prior to each", "__str__(self): return self.label def isIsomorphic(self, other): return self.label.lower() == other.label.lower()", "/ krevrev, 1.0, 0) def testGenerateReverseRateCoefficientThirdBody(self): \"\"\" Test the Reaction.generateReverseRateCoefficient()", "CH4\"\"\" thirdBody = ThirdBody( arrheniusLow = arrheniusLow, Tmin = (Tmin,\"K\"),", "delta=1e-2) self.assertAlmostEqual(arrhenius.n.value_si, 1.45419, delta=1e-4) self.assertAlmostEqual(arrhenius.Ea.value_si, 6645.24, delta=1e-2) # Check that", "'CH3 + C2H6 <=> CH4 + C2H5 (Baulch 2005)' arrhenius", ":class:`rmg.species.Species` for isomorphism checks. PseudoSpecies('a') is isomorphic with PseudoSpecies('A') but", "= (10.21,\"kJ/mol\"), T0 = (1,\"K\"), ) efficiencies = {\"C\": 3,", "), ], Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), Pmin =", "Tlist = numpy.arange(original_kinetics.Tmin, original_kinetics.Tmax, 200.0, numpy.float64) P = 1e5 for", "each unit test in this class. \"\"\" ethylene = Species(", "= 1500. Pmin = 1e-1 Pmax = 1e1 pressures =", "def testTSTCalculation(self): \"\"\" A test of the transition state theory", "), ), ], spinMultiplicity = 2, opticalIsomers = 1, ),", "Tmax = (Tmax,\"K\"), comment = comment, ), ], Tmin =", "Kplist = self.reaction2.getEquilibriumConstants(Tlist, type='Kp') for i in range(len(Tlist)): self.assertAlmostEqual(Kplist[i] /", "(pressures,\"bar\"), arrhenius = [ Arrhenius( A = (1.4e-11,\"cm^3/(molecule*s)\"), n =", "format. \"\"\" from rmgpy.kinetics import Troe arrheniusHigh = Arrhenius( A", "self.reaction.products[:] self.assertTrue(self.reaction.hasTemplate(reactants, products)) self.assertTrue(self.reaction.hasTemplate(products, reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants, products)) self.assertFalse(self.reaction2.hasTemplate(products, reactants)) reactants.reverse()", "def setUp(self): \"\"\" A method that is called prior to", "'3.34673e-08', '7.92389e-09', '2.62777e-09', '1.10053e-09']] Kplist = self.reaction2.getEquilibriumConstants(Tlist, type='Kp') for i", "\"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kclist0 = [float(v)", "self.reaction2 = Reaction( reactants=[acetyl, oxygen], products=[acetylperoxy], kinetics = Arrhenius( A", "format. \"\"\" from rmgpy.kinetics import ThirdBody arrheniusLow = Arrhenius( A", "(T2,\"K\"), Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), Pmin = (Pmin,\"bar\"),", "Test the Reaction.generateReverseRateCoefficient() method works for the Troe format. \"\"\"", "reactant0, reactant in zip(self.reaction.reactants, reaction.reactants): self.assertAlmostEqual(reactant0.conformer.E0.value_si / 1e6, reactant.conformer.E0.value_si /", "the correct Arrhenius parameters are returned self.assertAlmostEqual(arrhenius.A.value_si, 2265.2488, delta=1e-2) self.assertAlmostEqual(arrhenius.n.value_si,", "comment = comment, ) original_kinetics = troe self.reaction2.kinetics = original_kinetics", "lindemann self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics = reverseKinetics", "[PseudoSpecies(i) for i in products] return Reaction(reactants=reactants, products=products) def test1to1(self):", "testGenerateReverseRateCoefficient(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method. \"\"\" Tlist = numpy.arange(200.0,", "= numpy.arange(200.0, 2001.0, 200.0, numpy.float64) P = 1e5 reverseKinetics =", "\"[Ar]\": 0.7, \"[C]=O\": 1.5, \"[H][H]\": 2} Tmin = 300. Tmax", "self.reaction2.reactants[:] products = self.reaction2.products[:] self.assertFalse(self.reaction.hasTemplate(reactants, products)) self.assertFalse(self.reaction.hasTemplate(products, reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants, products))", "\"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the ArrheniusEP format.", "1.0, 0) def testGenerateReverseRateCoefficientPDepArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works", "= (10.0,\"kJ/mol\"), T0 = (300.0,\"K\"), Tmin = (300.0,\"K\"), Tmax =", "Tmax = (Tmax,\"K\"), Pmin = (Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), comment", "arrhenius = arrhenius, Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), Pmin", "a2=-4.434, a3=2.25, B=(500.0,\"K\"), H0=(-1.439e+05,\"J/mol\"), S0=(-524.6,\"J/(mol*K)\")), ) # [O][O] oxygen =", "made up\"\"\" original_kinetics = PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius =", "Reaction.isDissociation() method. \"\"\" isomerization = Reaction(reactants=[Species()], products=[Species()]) association = Reaction(reactants=[Species(),Species()],", "(1, 'K'), Tmin = (300, 'K'), Tmax = (2500, 'K'),", "Translation, IdealGasTranslation from rmgpy.statmech.rotation import Rotation, LinearRotor, NonlinearRotor, KRotor, SphericalTopRotor", "Pmin = (Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), comment = comment, )", "self.assertTrue(self.reaction.hasTemplate(products, reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants, products)) self.assertFalse(self.reaction2.hasTemplate(products, reactants)) reactants = self.reaction2.reactants[:] products", "= cPickle.loads(cPickle.dumps(self.reaction,-1)) self.assertEqual(len(self.reaction.reactants), len(reaction.reactants)) self.assertEqual(len(self.reaction.products), len(reaction.products)) for reactant0, reactant in", "rmgpy.statmech.translation import Translation, IdealGasTranslation from rmgpy.statmech.rotation import Rotation, LinearRotor, NonlinearRotor,", "method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kclist0 =", "\"\"\" A test of the transition state theory k(T) calculation", "\"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the PDepArrhenius format.", "self.reaction2.getEquilibriumConstant(T) kr = reverseKinetics.getRateCoefficient(T) self.assertAlmostEqual(kr0 / kr, 1.0, 0) def", "from external.wip import work_in_progress from rmgpy.species import Species, TransitionState from", "arrheniusHigh, arrheniusLow = arrheniusLow, alpha = alpha, T3 = (T3,\"K\"),", "), symmetry = 1, ), HarmonicOscillator( frequencies = ( [482.224,", "['-156.793', '-156.872', '-153.504', '-150.317', '-147.707', '-145.616', '-143.93', '-142.552', '-141.407', '-140.441']]", "= \"\"\"This data is completely made up\"\"\" arrhenius = [", "= (T2,\"K\"), Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), Pmin =", "C2H5. \"\"\" Tlist = 1000.0/numpy.arange(0.4, 3.35, 0.01) klist = numpy.array([self.reaction.calculateTSTRateCoefficient(T)", "= (1, 'K'), Tmin = (300, 'K'), Tmax = (2500,", "(Tmin,\"K\"), Tmax = (Tmax,\"K\"), Pmin = (Pmin,\"bar\"), Pmax = (Pmax,\"bar\"),", "'K'), Tmax = (2000, 'K'), ) self.reaction2.kinetics = original_kinetics reverseKinetics", "def test1to1(self): r1 = self.makeReaction('A=B') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=B'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('b=A'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('B=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=C'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=BB')))", "1000.0/numpy.arange(0.4, 3.35, 0.01) klist = numpy.array([self.reaction.calculateTSTRateCoefficient(T) for T in Tlist])", "= (pressures,\"bar\"), arrhenius = arrhenius, Tmin = (Tmin,\"K\"), Tmax =", "6) def testGenerateReverseRateCoefficient(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method. \"\"\" Tlist", "works for the PDepArrhenius format. \"\"\" from rmgpy.kinetics import PDepArrhenius", "conformer = Conformer( E0 = (44.7127, 'kJ/mol'), modes = [", "= reverseKinetics # reverse reactants, products to ensure Keq is", "(10.21,\"kJ/mol\"), T0 = (1,\"K\"), ) alpha = 0.783 T3 =", "1.0, Ea = (20.0,\"kJ/mol\"), T0 = (300.0,\"K\"), Tmin = (300.0,\"K\"),", "), ), ], spinMultiplicity = 1, opticalIsomers = 1, ),", "thirdBody = ThirdBody( arrheniusLow = arrheniusLow, Tmin = (Tmin,\"K\"), Tmax", "Test the Reaction.generateReverseRateCoefficient() method works for the MultiArrhenius format. \"\"\"", "of the transition state theory k(T) calculation function, using the", "-0.534, Ea = (2.243,\"kJ/mol\"), T0 = (1,\"K\"), ) arrheniusLow =", "reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants, products)) self.assertTrue(self.reaction2.hasTemplate(products, reactants)) reactants.reverse() products.reverse() self.assertFalse(self.reaction.hasTemplate(reactants, products)) self.assertFalse(self.reaction.hasTemplate(products,", "= numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kclist0 = [float(v) for v", "Contains unit tests of the isomorphism testing of the Reaction", "in reactants] products = [PseudoSpecies(i) for i in products] return", "[hydrogen, ethylene], products = [ethyl], kinetics = Arrhenius( A =", "= self.reaction2.getEntropiesOfReaction(Tlist) for i in range(len(Tlist)): self.assertAlmostEqual(Slist[i], Slist0[i], 2) def", "computed self.reaction2.reactants, self.reaction2.products = self.reaction2.products, self.reaction2.reactants reversereverseKinetics = self.reaction2.generateReverseRateCoefficient() #", "0) def testTSTCalculation(self): \"\"\" A test of the transition state", "S0=(-790.2,\"J/(mol*K)\")), ) # C[C]=O acetyl = Species( label='acetyl', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(15.5*constants.R,\"J/(mol*K)\"),", "Tmin = 300.0 Tmax = 2000.0 Pmin = 0.1 Pmax", "= (1.00783, 'amu'), ), ], spinMultiplicity = 2, opticalIsomers =", "a0=-3.95, a1=9.26, a2=-15.6, a3=8.55, B=(500.0,\"K\"), H0=(-6.151e+04,\"J/mol\"), S0=(-790.2,\"J/(mol*K)\")), ) # C[C]=O", "format. \"\"\" from rmgpy.kinetics import ArrheniusEP original_kinetics = ArrheniusEP( A", "10.0 comment = \"\"\"This data is completely made up\"\"\" original_kinetics", "TS = TransitionState( label = 'TS', conformer = Conformer( E0", "'0.000262777', '0.000110053']] Kalist = self.reaction2.getEquilibriumConstants(Tlist, type='Ka') for i in range(len(Tlist)):", "modes = [ IdealGasTranslation( mass = (29.0391, 'amu'), ), NonlinearRotor(", "Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertFalse(isomerization.isDissociation()) self.assertFalse(association.isDissociation()) self.assertTrue(dissociation.isDissociation()) self.assertFalse(bimolecular.isDissociation()) def testHasTemplate(self): \"\"\" Test", "hydrogen = Species( label = 'H', conformer = Conformer( E0", "reverseKinetics.getRateCoefficient(T) self.assertAlmostEqual(kr0 / kr, 1.0, 0) def testGenerateReverseRateCoefficientArrhenius(self): \"\"\" Test", "(Tmin,\"K\"), Tmax = (Tmax,\"K\"), comment = comment, ) self.reaction2.kinetics =", "(300.0,\"K\"), Tmax = (2000.0,\"K\"), comment = \"\"\"This data is completely", "] original_kinetics = MultiPDepArrhenius( arrhenius = arrhenius, Tmin = (Tmin,\"K\"),", "self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientThirdBody(self): \"\"\" Test the", "1.0, 0) @work_in_progress def testGenerateReverseRateCoefficientArrheniusEP(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method", "Lindemann format. \"\"\" from rmgpy.kinetics import Lindemann arrheniusHigh = Arrhenius(", "[PseudoSpecies(i) for i in reactants] products = [PseudoSpecies(i) for i", "reactant.conformer.E0.value_si / 1e6, 2) self.assertEqual(reactant0.conformer.E0.units, reactant.conformer.E0.units) for product0, product in", "\"CC\": 3, \"O\": 6, \"[Ar]\": 0.7, \"[C]=O\": 1.5, \"[H][H]\": 2}", "1e5 for T in Tlist: korig = original_kinetics.getRateCoefficient(T, P) krevrev", "place of a :class:`rmg.species.Species` for isomorphism checks. PseudoSpecies('a') is isomorphic", "= %r' % (self.reaction)) self.assertEqual(len(self.reaction.reactants), len(reaction.reactants)) self.assertEqual(len(self.reaction.products), len(reaction.products)) for reactant0,", "method. \"\"\" isomerization = Reaction(reactants=[Species()], products=[Species()]) association = Reaction(reactants=[Species(),Species()], products=[Species()])", "comment, ), PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius = [ Arrhenius(", "the Troe format. \"\"\" from rmgpy.kinetics import Troe arrheniusHigh =", "Glist = self.reaction2.getFreeEnergiesOfReaction(Tlist) for i in range(len(Tlist)): self.assertAlmostEqual(Glist[i] / 1000.,", "'94990.6', '123383', '151565']] Glist = self.reaction2.getFreeEnergiesOfReaction(Tlist) for i in range(len(Tlist)):", "(self.reaction)) self.assertEqual(len(self.reaction.reactants), len(reaction.reactants)) self.assertEqual(len(self.reaction.products), len(reaction.products)) for reactant0, reactant in zip(self.reaction.reactants,", "import numpy import unittest from external.wip import work_in_progress from rmgpy.species", "self.assertAlmostEqual(kr0 / kr, 1.0, 0) def testGenerateReverseRateCoefficientArrhenius(self): \"\"\" Test the", "Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Slist0 = [float(v) for", "'0.00334673', '0.000792389', '0.000262777', '0.000110053']] Kalist = self.reaction2.getEquilibriumConstants(Tlist, type='Ka') for i", "= numpy.arange(original_kinetics.Tmin, original_kinetics.Tmax, 200.0, numpy.float64) P = 1e5 for T", "= self.reaction2.getEquilibriumConstants(Tlist, type='Ka') for i in range(len(Tlist)): self.assertAlmostEqual(Kalist[i] / Kalist0[i],", "comment = comment, ) original_kinetics = thirdBody self.reaction2.kinetics = original_kinetics", "products)) self.assertFalse(self.reaction2.hasTemplate(products, reactants)) reactants = self.reaction2.reactants[:] products = self.reaction2.products[:] self.assertFalse(self.reaction.hasTemplate(reactants,", "self.assertEqual(self.reaction.kinetics.comment, reaction.kinetics.comment) self.assertEqual(self.reaction.duplicate, reaction.duplicate) self.assertEqual(self.reaction.degeneracy, reaction.degeneracy) def testOutput(self): \"\"\" Test", "from rmgpy.kinetics import MultiArrhenius pressures = numpy.array([0.1, 10.0]) Tmin =", "Reaction.generateReverseRateCoefficient() method works for the ArrheniusEP format. \"\"\" from rmgpy.kinetics", "comment, ) original_kinetics = thirdBody self.reaction2.kinetics = original_kinetics reverseKinetics =", "\"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the MultiArrhenius format.", "self.makeReaction('AB=CD') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cd'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=dc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dc=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cd=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=ab'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=cde'))) def test2to3(self): r1", "that the fit is satisfactory (defined here as always within", "T in Tlist: self.assertAlmostEqual(self.reaction.getRateCoefficient(T, P) / self.reaction.kinetics.getRateCoefficient(T), 1.0, 6) def", "T0 = (1,\"K\"), ) efficiencies = {\"C\": 3, \"C(=O)=O\": 2,", "inertia = ( [4.8709, 22.2353, 23.9925], 'amu*angstrom^2', ), symmetry =", "= self.reaction2.getEquilibriumConstants(Tlist, type='Kp') for i in range(len(Tlist)): self.assertAlmostEqual(Kplist[i] / Kplist0[i],", "can be successfully reconstructed from its repr() output with no", "E0 = (266.694, 'kJ/mol'), modes = [ IdealGasTranslation( mass =", "format. \"\"\" from rmgpy.kinetics import PDepArrhenius arrhenius0 = Arrhenius( A", "22.1437, 22.2114], 'amu*angstrom^2', ), symmetry = 1, ), HarmonicOscillator( frequencies", "['-146007', '-145886', '-144195', '-141973', '-139633', '-137341', '-135155', '-133093', '-131150', '-129316']]", "from its repr() output with no loss of information. \"\"\"", "= (4740*constants.R*0.001,\"kJ/mol\"), T0 = (1,\"K\"), Tmin = (Tmin,\"K\"), Tmax =", "1.0, 0) def testGenerateReverseRateCoefficientMultiPDepArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works", "A = (1.0e6,\"s^-1\"), n = 1.0, Ea = (10.0,\"kJ/mol\"), T0", "makeReaction(self,reaction_string): \"\"\"\" Make a Reaction (containing PseudoSpecies) of from a", "Test that a Reaction object can be successfully reconstructed from", "label='acetyl', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(15.5*constants.R,\"J/(mol*K)\"), a0=0.2541, a1=-0.4712, a2=-4.434, a3=2.25, B=(500.0,\"K\"), H0=(-1.439e+05,\"J/mol\"), S0=(-524.6,\"J/(mol*K)\")),", "alpha = 0.783 T3 = 74 T1 = 2941 T2", "Species( label='oxygen', thermo=Wilhoit(Cp0=(3.5*constants.R,\"J/(mol*K)\"), CpInf=(4.5*constants.R,\"J/(mol*K)\"), a0=-0.9324, a1=26.18, a2=-70.47, a3=44.12, B=(500.0,\"K\"), H0=(1.453e+04,\"J/mol\"),", "self.assertFalse(r1.isIsomorphic(self.makeReaction('abe=cde'))) class TestReaction(unittest.TestCase): \"\"\" Contains unit tests of the Reaction", "self.assertTrue(self.reaction2.hasTemplate(reactants, products)) self.assertTrue(self.reaction2.hasTemplate(products, reactants)) reactants.reverse() products.reverse() self.assertFalse(self.reaction.hasTemplate(reactants, products)) self.assertFalse(self.reaction.hasTemplate(products, reactants))", "parameters are returned self.assertAlmostEqual(arrhenius.A.value_si, 2265.2488, delta=1e-2) self.assertAlmostEqual(arrhenius.n.value_si, 1.45419, delta=1e-4) self.assertAlmostEqual(arrhenius.Ea.value_si,", "Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Hlist0 = [float(v) for", "= reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientMultiPDepArrhenius(self):", "products)) self.assertTrue(self.reaction2.hasTemplate(products, reactants)) reactants.reverse() products.reverse() self.assertFalse(self.reaction.hasTemplate(reactants, products)) self.assertFalse(self.reaction.hasTemplate(products, reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants,", "T0 = (1, 'K'), Tmin = (300, 'K'), Tmax =", "Test the Reaction.generateReverseRateCoefficient() method works for the ArrheniusEP format. \"\"\"", "self.reaction2.generateReverseRateCoefficient() # check that reverting the reverse yields the original", "for v in ['-146007', '-145886', '-144195', '-141973', '-139633', '-137341', '-135155',", "acetylperoxy = Species( label='acetylperoxy', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(21.0*constants.R,\"J/(mol*K)\"), a0=-3.95, a1=9.26, a2=-15.6, a3=8.55,", "PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius = arrhenius, Tmin = (Tmin,\"K\"),", "for isomorphism checks. PseudoSpecies('a') is isomorphic with PseudoSpecies('A') but nothing", "= troe self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient() self.reaction2.kinetics =", "self.makeReaction('A=B') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=B'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('b=A'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('B=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=C'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=BB'))) def test1to2(self): r1 =", "1.0, 0) def testGenerateReverseRateCoefficientLindemann(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works", "import Translation, IdealGasTranslation from rmgpy.statmech.rotation import Rotation, LinearRotor, NonlinearRotor, KRotor,", "'kJ/mol'), modes = [ IdealGasTranslation( mass = (28.0313, 'amu'), ),", "that a Reaction object can be successfully reconstructed from its", "numpy.arange(200.0, 2001.0, 200.0, numpy.float64) P = 1e5 for T in", "used in place of a :class:`rmg.species.Species` for isomorphism checks. PseudoSpecies('a')", "Conformer( E0 = (111.603, 'kJ/mol'), modes = [ IdealGasTranslation( mass", "test1to2(self): r1 = self.makeReaction('A=BC') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=Bc'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('cb=a'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('a=cb'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('bc=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('a=c'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=c')))", "= (44.7127, 'kJ/mol'), modes = [ IdealGasTranslation( mass = (28.0313,", "= [float(v) for v in ['-114648', '-83137.2', '-52092.4', '-21719.3', '8073.53',", "0.1 Pmax = 10.0 comment = \"\"\"This data is completely", "n = 0.0, Ea = (4740*constants.R*0.001,\"kJ/mol\"), T0 = (1,\"K\"), Tmin", "Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kclist0 = [float(v) for", "CC(=O)O[O] acetylperoxy = Species( label='acetylperoxy', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(21.0*constants.R,\"J/(mol*K)\"), a0=-3.95, a1=9.26, a2=-15.6,", "'-21719.3', '8073.53', '37398.1', '66346.8', '94990.6', '123383', '151565']] Glist = self.reaction2.getFreeEnergiesOfReaction(Tlist)", "self.reaction2.products = self.reaction2.products, self.reaction2.reactants reversereverseKinetics = self.reaction2.generateReverseRateCoefficient() # check that", "PDepArrhenius arrhenius0 = Arrhenius( A = (1.0e6,\"s^-1\"), n = 1.0,", "(2.62e+33,\"cm^6/(mol^2*s)\"), n = -4.76, Ea = (10.21,\"kJ/mol\"), T0 = (1,\"K\"),", "works for the Arrhenius format. \"\"\" original_kinetics = Arrhenius( A", "E0 = (41.84, 'kJ/mol'), Tmin = (300, 'K'), Tmax =", "= \"\"\"This data is completely made up\"\"\", ) arrhenius1 =", "method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Hlist0 =", "delta=1e-4) self.assertAlmostEqual(arrhenius.Ea.value_si, 6645.24, delta=1e-2) # Check that the fit is", "prior to each unit test in this class. \"\"\" ethylene", "'0.000792389', '0.000262777', '0.000110053']] Kalist = self.reaction2.getEquilibriumConstants(Tlist, type='Ka') for i in", "= (211.794, 'kJ/mol'), modes = [ IdealGasTranslation( mass = (1.00783,", "that reverting the reverse yields the original Tlist = numpy.arange(original_kinetics.Tmin,", "P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientPDepArrhenius(self): \"\"\" Test", "klist = numpy.array([self.reaction.calculateTSTRateCoefficient(T) for T in Tlist]) arrhenius = Arrhenius().fitToData(Tlist,", "numpy.float64) Kplist0 = [float(v) for v in ['8.75951e+24', '718430', '0.342727',", "is called prior to each unit test in this class.", "self.assertFalse(self.reaction2.hasTemplate(products, reactants)) reactants = self.reaction2.reactants[:] products = self.reaction2.products[:] self.assertFalse(self.reaction.hasTemplate(reactants, products))", "isIsomorphic(self, other): return self.label.lower() == other.label.lower() class TestReactionIsomorphism(unittest.TestCase): \"\"\" Contains", "Reaction.getFreeEnergyOfReaction() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Glist0", "= [ Arrhenius( A = (9.3e-14,\"cm^3/(molecule*s)\"), n = 0.0, Ea", "), ], spinMultiplicity = 2, opticalIsomers = 1, ), )", "= [float(v) for v in ['-146007', '-145886', '-144195', '-141973', '-139633',", "'C2H5', conformer = Conformer( E0 = (111.603, 'kJ/mol'), modes =", "reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientThirdBody(self): \"\"\"", "Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), comment = comment, ),", "/ self.reaction2.getEquilibriumConstant(T) kr = reverseKinetics.getRateCoefficient(T) self.assertAlmostEqual(kr0 / kr, 1.0, 0)", "reaction.kinetics.n.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.T0.value_si, reaction.kinetics.T0.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.Ea.value_si, reaction.kinetics.Ea.value_si, delta=1e-6) self.assertEqual(self.reaction.kinetics.comment, reaction.kinetics.comment)", "= (Tmax,\"K\"), comment = comment, ) self.reaction2.kinetics = original_kinetics reverseKinetics", "2) self.assertEqual(self.reaction.transitionState.conformer.E0.units, reaction.transitionState.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.frequency.value_si, reaction.transitionState.frequency.value_si, 2) self.assertEqual(self.reaction.transitionState.frequency.units, reaction.transitionState.frequency.units) self.assertAlmostEqual(self.reaction.kinetics.A.value_si, reaction.kinetics.A.value_si,", "(2500, 'K'), ), transitionState = TS, ) # CC(=O)O[O] acetylperoxy", "= arrheniusLow, alpha = alpha, T3 = (T3,\"K\"), T1 =", "'-83137.2', '-52092.4', '-21719.3', '8073.53', '37398.1', '66346.8', '94990.6', '123383', '151565']] Glist", "Arrhenius().fitToData(Tlist, klist, kunits='m^3/(mol*s)') klist2 = numpy.array([arrhenius.getRateCoefficient(T) for T in Tlist])", "(Pmax,\"bar\"), comment = comment, ), PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius", "= (Pmin,\"bar\"), Pmax = (Pmax,\"bar\"), comment = comment, ), ]", "Kalist0[i], 1.0, 4) def testEquilibriumConstantKc(self): \"\"\" Test the Reaction.getEquilibriumConstant() method.", "product.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.conformer.E0.value_si / 1e6, reaction.transitionState.conformer.E0.value_si / 1e6, 2) self.assertEqual(self.reaction.transitionState.conformer.E0.units, reaction.transitionState.conformer.E0.units)", "2) self.assertEqual(self.reaction.transitionState.frequency.units, reaction.transitionState.frequency.units) self.assertAlmostEqual(self.reaction.kinetics.A.value_si, reaction.kinetics.A.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.n.value_si, reaction.kinetics.n.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.T0.value_si,", "zip(self.reaction.reactants, reaction.reactants): self.assertAlmostEqual(reactant0.conformer.E0.value_si / 1e6, reactant.conformer.E0.value_si / 1e6, 2) self.assertEqual(reactant0.conformer.E0.units,", "for v in ['-156.793', '-156.872', '-153.504', '-150.317', '-147.707', '-145.616', '-143.93',", "+ C2H5 (Baulch 2005)' arrhenius = [ PDepArrhenius( pressures =", "'cm^-1', ), ), ], spinMultiplicity = 2, opticalIsomers = 1,", "= Arrhenius( A = (1.0e6,\"s^-1\"), n = 1.0, Ea =", "v in ['1.45661e+28', '2.38935e+09', '1709.76', '1.74189', '0.0314866', '0.00235045', '0.000389568', '0.000105413',", "of a :class:`rmg.species.Species` for isomorphism checks. PseudoSpecies('a') is isomorphic with", "= (Tmax,\"K\"), comment = comment, ), Arrhenius( A = (9.3e-14,\"cm^3/(molecule*s)\"),", "the original Tlist = numpy.arange(Tmin, Tmax, 200.0, numpy.float64) P =", "Lindemann arrheniusHigh = Arrhenius( A = (1.39e+16,\"cm^3/(mol*s)\"), n = -0.534,", "encoding: utf-8 -*- \"\"\" This module contains unit tests of", "the Reaction.getStoichiometricCoefficient() method. \"\"\" for reactant in self.reaction.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), -1)", "method works for the Troe format. \"\"\" from rmgpy.kinetics import", "products)) self.assertFalse(self.reaction.hasTemplate(products, reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants, products)) self.assertTrue(self.reaction2.hasTemplate(products, reactants)) def testEnthalpyOfReaction(self): \"\"\"", "the Reaction.getEnthalpyOfReaction() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64)", "self.assertFalse(self.reaction.hasTemplate(products, reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants, products)) self.assertTrue(self.reaction2.hasTemplate(products, reactants)) reactants.reverse() products.reverse() self.assertFalse(self.reaction.hasTemplate(reactants, products))", "unit test in this class. \"\"\" ethylene = Species( label", "= (111.603, 'kJ/mol'), modes = [ IdealGasTranslation( mass = (29.0391,", "type='Kc') for i in range(len(Tlist)): self.assertAlmostEqual(Kclist[i] / Kclist0[i], 1.0, 4)", "the Reaction.getEntropyOfReaction() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64)", "= 2, opticalIsomers = 1, ), frequency = (-750.232, 'cm^-1'),", "range(len(Tlist)): self.assertAlmostEqual(Hlist[i] / 1000., Hlist0[i] / 1000., 2) def testEntropyOfReaction(self):", "in range(len(Tlist)): self.assertAlmostEqual(Kclist[i] / Kclist0[i], 1.0, 4) def testEquilibriumConstantKp(self): \"\"\"", "numpy.float64) P = 1e5 for T in Tlist: self.assertAlmostEqual(self.reaction.getRateCoefficient(T, P)", "from rmgpy.statmech.conformer import Conformer from rmgpy.kinetics import Arrhenius from rmgpy.thermo", "'-52092.4', '-21719.3', '8073.53', '37398.1', '66346.8', '94990.6', '123383', '151565']] Glist =", "Reaction.getEquilibriumConstant() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kplist0", "Arrhenius format. \"\"\" original_kinetics = Arrhenius( A = (2.65e12, 'cm^3/(mol*s)'),", "'amu'), ), NonlinearRotor( inertia = ( [3.41526, 16.6498, 20.065], 'amu*angstrom^2',", "[412.75, 415.206, 821.495, 924.44, 982.714, 1024.16, 1224.21, 1326.36, 1455.06, 1600.35,", "4) def testEquilibriumConstantKp(self): \"\"\" Test the Reaction.getEquilibriumConstant() method. \"\"\" Tlist", "P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) @work_in_progress def testGenerateReverseRateCoefficientArrheniusEP(self): \"\"\"", "reaction.transitionState.frequency.units) self.assertAlmostEqual(self.reaction.kinetics.A.value_si, reaction.kinetics.A.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.n.value_si, reaction.kinetics.n.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.T0.value_si, reaction.kinetics.T0.value_si, delta=1e-6)", "(1.0e12,\"s^-1\"), n = 1.0, Ea = (20.0,\"kJ/mol\"), T0 = (300.0,\"K\"),", "self.assertFalse(r1.isIsomorphic(self.makeReaction('a=c'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=c'))) def test2to2(self): r1 = self.makeReaction('AB=CD') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cd'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=dc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dc=ba')))", "= Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertFalse(isomerization.isDissociation()) self.assertFalse(association.isDissociation()) self.assertTrue(dissociation.isDissociation()) self.assertFalse(bimolecular.isDissociation()) def testHasTemplate(self): \"\"\"", "for the PDepArrhenius format. \"\"\" from rmgpy.kinetics import PDepArrhenius arrhenius0", "arrhenius, Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), Pmin = (Pmin,\"bar\"),", "test1to1(self): r1 = self.makeReaction('A=B') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=B'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('b=A'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('B=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=C'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=BB'))) def", "= self.makeReaction('AB=CDE') self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=cde'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('ba=edc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dec=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cde=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=abc'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('abe=cde'))) class TestReaction(unittest.TestCase):", "self.reaction2.getFreeEnergiesOfReaction(Tlist) for i in range(len(Tlist)): self.assertAlmostEqual(Glist[i] / 1000., Glist0[i] /", "called prior to each unit test in this class. \"\"\"", "for T in Tlist: self.assertAlmostEqual(self.reaction.getRateCoefficient(T, P) / self.reaction.kinetics.getRateCoefficient(T), 1.0, 6)", "using the reaction H + C2H4 -> C2H5. \"\"\" Tlist", "= reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientMultiArrhenius(self):", "'0.000261877', '3.78696e-06', '2.35579e-07', '3.34673e-08', '7.92389e-09', '2.62777e-09', '1.10053e-09']] Kplist = self.reaction2.getEquilibriumConstants(Tlist,", "but nothing else. \"\"\" def __init__(self, label): self.label = label", ") original_kinetics = lindemann self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient()", "T in Tlist]) # Check that the correct Arrhenius parameters", "reverseKinetics # reverse reactants, products to ensure Keq is correctly", "\"\"\" Test the Reaction.isDissociation() method. \"\"\" isomerization = Reaction(reactants=[Species()], products=[Species()])", "reactants, products to ensure Keq is correctly computed self.reaction2.reactants, self.reaction2.products", "self.assertFalse(r1.isIsomorphic(self.makeReaction('cde=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=abc'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('abe=cde'))) class TestReaction(unittest.TestCase): \"\"\" Contains unit tests of", "3101.46, 3110.55, 3175.34, 3201.88], 'cm^-1', ), ), ], spinMultiplicity =", "0) def testGenerateReverseRateCoefficientLindemann(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for", "C2H5 (Baulch 2005)' arrhenius = [ PDepArrhenius( pressures = (pressures,\"bar\"),", "'-141973', '-139633', '-137341', '-135155', '-133093', '-131150', '-129316']] Hlist = self.reaction2.getEnthalpiesOfReaction(Tlist)", "TransitionState from rmgpy.reaction import Reaction from rmgpy.statmech.translation import Translation, IdealGasTranslation", "reaction.transitionState.conformer.E0.value_si / 1e6, 2) self.assertEqual(self.reaction.transitionState.conformer.E0.units, reaction.transitionState.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.frequency.value_si, reaction.transitionState.frequency.value_si, 2) self.assertEqual(self.reaction.transitionState.frequency.units,", "products)) self.assertFalse(self.reaction2.hasTemplate(products, reactants)) reactants.reverse() products.reverse() self.assertTrue(self.reaction.hasTemplate(reactants, products)) self.assertTrue(self.reaction.hasTemplate(products, reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants,", "reactants)) reactants = self.reaction2.reactants[:] products = self.reaction2.products[:] self.assertFalse(self.reaction.hasTemplate(reactants, products)) self.assertFalse(self.reaction.hasTemplate(products,", "the Reaction.getRateCoefficient() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64)", "return \"PseudoSpecies('{0}')\".format(self.label) def __str__(self): return self.label def isIsomorphic(self, other): return", "], spinMultiplicity = 1, opticalIsomers = 1, ), ) hydrogen", "Ea = (10.0,\"kJ/mol\"), T0 = (300.0,\"K\"), Tmin = (300.0,\"K\"), Tmax", "A = (1.39e+16,\"cm^3/(mol*s)\"), n = -0.534, Ea = (2.243,\"kJ/mol\"), T0", "= 'H', conformer = Conformer( E0 = (211.794, 'kJ/mol'), modes", "= {\"C\": 3, \"C(=O)=O\": 2, \"CC\": 3, \"O\": 6, \"[Ar]\":", "= ( [3.41526, 16.6498, 20.065], 'amu*angstrom^2', ), symmetry = 4,", "self.assertTrue(r1.isIsomorphic(self.makeReaction('b=A'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('B=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=C'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=BB'))) def test1to2(self): r1 = self.makeReaction('A=BC') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=Bc')))", "[arrhenius0, arrhenius1] Tmin = 300.0 Tmax = 2000.0 Pmin =", "a0=0.2541, a1=-0.4712, a2=-4.434, a3=2.25, B=(500.0,\"K\"), H0=(-1.439e+05,\"J/mol\"), S0=(-524.6,\"J/(mol*K)\")), ) # [O][O]", "satisfactory (defined here as always within 5%) for i in", "T2 = (T2,\"K\"), Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), Pmin", "= (2.65e12, 'cm^3/(mol*s)'), n = 0.0, Ea = (0.0, 'kJ/mol'),", "= Reaction( reactants=[acetyl, oxygen], products=[acetylperoxy], kinetics = Arrhenius( A =", "1e1 pressures = numpy.array([1e-1,1e1]) comment = 'CH3 + C2H6 <=>", "Reaction.generateReverseRateCoefficient() method works for the Troe format. \"\"\" from rmgpy.kinetics", "P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientMultiArrhenius(self): \"\"\" Test", "in range(len(Tlist)): self.assertAlmostEqual(klist[i], klist2[i], delta=5e-2 * klist[i]) def testPickle(self): \"\"\"", "tests of the isomorphism testing of the Reaction class. \"\"\"", "NonlinearRotor( inertia = ( [6.78512, 22.1437, 22.2114], 'amu*angstrom^2', ), symmetry", "), NonlinearRotor( inertia = ( [4.8709, 22.2353, 23.9925], 'amu*angstrom^2', ),", "spinMultiplicity = 1, opticalIsomers = 1, ), ) hydrogen =", "T0 = (300.0,\"K\"), Tmin = (300.0,\"K\"), Tmax = (2000.0,\"K\"), comment", "testEquilibriumConstantKp(self): \"\"\" Test the Reaction.getEquilibriumConstant() method. \"\"\" Tlist = numpy.arange(200.0,", "check that reverting the reverse yields the original Tlist =", "\"\"\" def __init__(self, label): self.label = label def __repr__(self): return", "format. \"\"\" from rmgpy.kinetics import MultiArrhenius pressures = numpy.array([0.1, 10.0])", "Reaction( reactants = [hydrogen, ethylene], products = [ethyl], kinetics =", "= 0.1 Pmax = 10.0 comment = \"\"\"This data is", "for T in Tlist]) arrhenius = Arrhenius().fitToData(Tlist, klist, kunits='m^3/(mol*s)') klist2", "self.assertEqual(len(self.reaction.products), len(reaction.products)) for reactant0, reactant in zip(self.reaction.reactants, reaction.reactants): self.assertAlmostEqual(reactant0.conformer.E0.value_si /", "the Reaction.isIsomerization() method. \"\"\" isomerization = Reaction(reactants=[Species()], products=[Species()]) association =", "Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), Pmin = (Pmin,\"bar\"), Pmax", "# reverse reactants, products to ensure Keq is correctly computed", "= 100. comment = \"\"\"H + CH3 -> CH4\"\"\" lindemann", "1, ), ) TS = TransitionState( label = 'TS', conformer", "self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientLindemann(self): \"\"\" Test the", "+ CH3 -> CH4\"\"\" lindemann = Lindemann( arrheniusHigh = arrheniusHigh,", "H0=(-1.439e+05,\"J/mol\"), S0=(-524.6,\"J/(mol*K)\")), ) # [O][O] oxygen = Species( label='oxygen', thermo=Wilhoit(Cp0=(3.5*constants.R,\"J/(mol*K)\"),", "Reaction(reactants=[Species()], products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertFalse(isomerization.isDissociation()) self.assertFalse(association.isDissociation()) self.assertTrue(dissociation.isDissociation()) self.assertFalse(bimolecular.isDissociation())", "(Tmin,\"K\"), Tmax = (Tmax,\"K\"), comment = comment, ), ], Tmin", "Pmax = 100. comment = \"\"\"H + CH3 -> CH4\"\"\"", "+ C2H6 <=> CH4 + C2H5 (Baulch 2005)' arrhenius =", "products)) self.assertTrue(self.reaction.hasTemplate(products, reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants, products)) self.assertFalse(self.reaction2.hasTemplate(products, reactants)) reactants.reverse() products.reverse() self.assertTrue(self.reaction.hasTemplate(reactants,", "def testHasTemplate(self): \"\"\" Test the Reaction.hasTemplate() method. \"\"\" reactants =", "self.reaction2.reactants reversereverseKinetics = self.reaction2.generateReverseRateCoefficient() # check that reverting the reverse", "self.assertEqual(self.reaction.duplicate, reaction.duplicate) self.assertEqual(self.reaction.degeneracy, reaction.degeneracy) def testOutput(self): \"\"\" Test that a", "self.assertTrue(r1.isIsomorphic(self.makeReaction('a=B'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('b=A'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('B=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=C'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=BB'))) def test1to2(self): r1 = self.makeReaction('A=BC')", "Reaction(reactants=[Species()], products=[Species()]) association = Reaction(reactants=[Species(),Species()], products=[Species()]) dissociation = Reaction(reactants=[Species()], products=[Species(),Species()])", "= arrheniusHigh, arrheniusLow = arrheniusLow, alpha = alpha, T3 =", "modes = [ IdealGasTranslation( mass = (1.00783, 'amu'), ), ],", "testEntropyOfReaction(self): \"\"\" Test the Reaction.getEntropyOfReaction() method. \"\"\" Tlist = numpy.arange(200.0,", "class PseudoSpecies: \"\"\" Can be used in place of a", "products=[Species()]) dissociation = Reaction(reactants=[Species()], products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertFalse(isomerization.isAssociation())", "HarmonicOscillator( frequencies = ( [412.75, 415.206, 821.495, 924.44, 982.714, 1024.16,", "self.assertFalse(r1.isIsomorphic(self.makeReaction('B=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=C'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=BB'))) def test1to2(self): r1 = self.makeReaction('A=BC') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=Bc'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('cb=a')))", "reaction.degeneracy) def testOutput(self): \"\"\" Test that a Reaction object can", "self.reaction2.products[:] self.assertFalse(self.reaction.hasTemplate(reactants, products)) self.assertFalse(self.reaction.hasTemplate(products, reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants, products)) self.assertTrue(self.reaction2.hasTemplate(products, reactants)) reactants.reverse()", "3201.88], 'cm^-1', ), ), ], spinMultiplicity = 2, opticalIsomers =", "reactants)) self.assertTrue(self.reaction2.hasTemplate(reactants, products)) self.assertTrue(self.reaction2.hasTemplate(products, reactants)) def testEnthalpyOfReaction(self): \"\"\" Test the", "utf-8 -*- \"\"\" This module contains unit tests of the", "/ 1e6, reactant.conformer.E0.value_si / 1e6, 2) self.assertEqual(reactant0.conformer.E0.units, reactant.conformer.E0.units) for product0,", "Kalist = self.reaction2.getEquilibriumConstants(Tlist, type='Ka') for i in range(len(Tlist)): self.assertAlmostEqual(Kalist[i] /", "self.assertFalse(self.reaction2.hasTemplate(products, reactants)) reactants.reverse() products.reverse() self.assertTrue(self.reaction.hasTemplate(reactants, products)) self.assertTrue(self.reaction.hasTemplate(products, reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants, products))", "method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kplist0 =", "from rmgpy.thermo import Wilhoit import rmgpy.constants as constants ################################################################################ class", "\"\"\" for reactant in self.reaction.reactants: self.assertEqual(self.reaction.getStoichiometricCoefficient(reactant), -1) for product in", "self.reaction2.generateReverseRateCoefficient() for T in Tlist: kr0 = self.reaction2.getRateCoefficient(T, P) /", "self.assertFalse(r1.isIsomorphic(self.makeReaction('A=C'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('A=BB'))) def test1to2(self): r1 = self.makeReaction('A=BC') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=Bc'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('cb=a'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('a=cb'),eitherDirection=False))", "self.makeReaction('A=BC') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=Bc'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('cb=a'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('a=cb'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('bc=a'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('a=c'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=c'))) def test2to2(self): r1", "= numpy.array([0.1, 10.0]) Tmin = 300.0 Tmax = 2000.0 Pmin", "Tmin = (300.0,\"K\"), Tmax = (2000.0,\"K\"), comment = \"\"\"This data", "2001.0, 200.0, numpy.float64) Kalist0 = [float(v) for v in ['8.75951e+29',", "(28.0313, 'amu'), ), NonlinearRotor( inertia = ( [3.41526, 16.6498, 20.065],", "= (1.39e+16,\"cm^3/(mol*s)\"), n = -0.534, Ea = (2.243,\"kJ/mol\"), T0 =", "be used in place of a :class:`rmg.species.Species` for isomorphism checks.", "CH4\"\"\" troe = Troe( arrheniusHigh = arrheniusHigh, arrheniusLow = arrheniusLow,", "external.wip import work_in_progress from rmgpy.species import Species, TransitionState from rmgpy.reaction", "(1.39e+16,\"cm^3/(mol*s)\"), n = -0.534, Ea = (2.243,\"kJ/mol\"), T0 = (1,\"K\"),", "\"PseudoSpecies('{0}')\".format(self.label) def __str__(self): return self.label def isIsomorphic(self, other): return self.label.lower()", "comment = comment, ) self.reaction2.kinetics = original_kinetics reverseKinetics = self.reaction2.generateReverseRateCoefficient()", "arrhenius1] Tmin = 300.0 Tmax = 2000.0 Pmin = 0.1", "of the Reaction class. \"\"\" def makeReaction(self,reaction_string): \"\"\"\" Make a", "def testEquilibriumConstantKc(self): \"\"\" Test the Reaction.getEquilibriumConstant() method. \"\"\" Tlist =", "krevrev, 1.0, 0) def testGenerateReverseRateCoefficientTroe(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method", "Ea = (10.21,\"kJ/mol\"), T0 = (1,\"K\"), ) efficiencies = {\"C\":", "Slist0[i], 2) def testFreeEnergyOfReaction(self): \"\"\" Test the Reaction.getFreeEnergyOfReaction() method. \"\"\"", "i in range(len(Tlist)): self.assertAlmostEqual(Kalist[i] / Kalist0[i], 1.0, 4) def testEquilibriumConstantKc(self):", "for i in range(len(Tlist)): self.assertAlmostEqual(Kplist[i] / Kplist0[i], 1.0, 4) def", "Reaction(reactants=reactants, products=products) def test1to1(self): r1 = self.makeReaction('A=B') self.assertTrue(r1.isIsomorphic(self.makeReaction('a=B'))) self.assertTrue(r1.isIsomorphic(self.makeReaction('b=A'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('B=a'),eitherDirection=False))", "= Species( label='oxygen', thermo=Wilhoit(Cp0=(3.5*constants.R,\"J/(mol*K)\"), CpInf=(4.5*constants.R,\"J/(mol*K)\"), a0=-0.9324, a1=26.18, a2=-70.47, a3=44.12, B=(500.0,\"K\"),", "self.assertAlmostEqual(Glist[i] / 1000., Glist0[i] / 1000., 2) def testEquilibriumConstantKa(self): \"\"\"", "= 1000.0/numpy.arange(0.4, 3.35, 0.01) klist = numpy.array([self.reaction.calculateTSTRateCoefficient(T) for T in", "for i in range(len(Tlist)): self.assertAlmostEqual(Glist[i] / 1000., Glist0[i] / 1000.,", "made up\"\"\", ) arrhenius1 = Arrhenius( A = (1.0e12,\"s^-1\"), n", "the Reaction.generateReverseRateCoefficient() method works for the MultiPDepArrhenius format. \"\"\" from", "reaction.kinetics.T0.value_si, delta=1e-6) self.assertAlmostEqual(self.reaction.kinetics.Ea.value_si, reaction.kinetics.Ea.value_si, delta=1e-6) self.assertEqual(self.reaction.kinetics.comment, reaction.kinetics.comment) self.assertEqual(self.reaction.duplicate, reaction.duplicate) self.assertEqual(self.reaction.degeneracy,", "1052.93, 1233.55, 1367.56, 1465.09, 1672.25, 3098.46, 3111.7, 3165.79, 3193.54], 'cm^-1',", "Hlist0[i] / 1000., 2) def testEntropyOfReaction(self): \"\"\" Test the Reaction.getEntropyOfReaction()", "import Torsion, HinderedRotor from rmgpy.statmech.conformer import Conformer from rmgpy.kinetics import", "Test the Reaction.generateReverseRateCoefficient() method works for the Arrhenius format. \"\"\"", "self.assertTrue(r1.isIsomorphic(self.makeReaction('ab=dc'),eitherDirection=False)) self.assertTrue(r1.isIsomorphic(self.makeReaction('dc=ba'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('cd=ab'),eitherDirection=False)) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=ab'))) self.assertFalse(r1.isIsomorphic(self.makeReaction('ab=cde'))) def test2to3(self): r1 = self.makeReaction('AB=CDE')", "TransitionState( label = 'TS', conformer = Conformer( E0 = (266.694,", "1e-1 Pmax = 1e1 pressures = numpy.array([1e-1,1e1]) comment = 'CH3", "= comment, ) original_kinetics = lindemann self.reaction2.kinetics = original_kinetics reverseKinetics", "\"\"\" isomerization = Reaction(reactants=[Species()], products=[Species()]) association = Reaction(reactants=[Species(),Species()], products=[Species()]) dissociation", "= \"\"\"H + CH3 -> CH4\"\"\" lindemann = Lindemann( arrheniusHigh", "arrhenius, Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), comment = comment,", "= efficiencies, comment = comment, ) original_kinetics = lindemann self.reaction2.kinetics", "2, \"CC\": 3, \"O\": 6, \"[Ar]\": 0.7, \"[C]=O\": 1.5, \"[H][H]\":", "IdealGasTranslation( mass = (28.0313, 'amu'), ), NonlinearRotor( inertia = (", "= Species( label = 'H', conformer = Conformer( E0 =", "klist[i]) def testPickle(self): \"\"\" Test that a Reaction object can", "CH3 -> CH4\"\"\" lindemann = Lindemann( arrheniusHigh = arrheniusHigh, arrheniusLow", "label='oxygen', thermo=Wilhoit(Cp0=(3.5*constants.R,\"J/(mol*K)\"), CpInf=(4.5*constants.R,\"J/(mol*K)\"), a0=-0.9324, a1=26.18, a2=-70.47, a3=44.12, B=(500.0,\"K\"), H0=(1.453e+04,\"J/mol\"), S0=(-12.19,\"J/(mol*K)\")),", "in products] return Reaction(reactants=reactants, products=products) def test1to1(self): r1 = self.makeReaction('A=B')", "2, opticalIsomers = 1, ), ) ethyl = Species( label", "range(len(Tlist)): self.assertAlmostEqual(Glist[i] / 1000., Glist0[i] / 1000., 2) def testEquilibriumConstantKa(self):", "works for the ArrheniusEP format. \"\"\" from rmgpy.kinetics import ArrheniusEP", "= Arrhenius( A = (2.62e+33,\"cm^6/(mol^2*s)\"), n = -4.76, Ea =", "def testGenerateReverseRateCoefficientTroe(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the", "import work_in_progress from rmgpy.species import Species, TransitionState from rmgpy.reaction import", "[float(v) for v in ['8.75951e+24', '718430', '0.342727', '0.000261877', '3.78696e-06', '2.35579e-07',", "P = 1e5 for T in Tlist: self.assertAlmostEqual(self.reaction.getRateCoefficient(T, P) /", "arrhenius = [ Arrhenius( A = (1.4e-11,\"cm^3/(molecule*s)\"), n = 0.0,", "products)) self.assertTrue(self.reaction.hasTemplate(products, reactants)) self.assertFalse(self.reaction2.hasTemplate(reactants, products)) self.assertFalse(self.reaction2.hasTemplate(products, reactants)) reactants = self.reaction2.reactants[:]", "reaction.kinetics.comment) self.assertEqual(self.reaction.duplicate, reaction.duplicate) self.assertEqual(self.reaction.degeneracy, reaction.degeneracy) ################################################################################ if __name__ == '__main__':", "-4.76, Ea = (10.21,\"kJ/mol\"), T0 = (1,\"K\"), ) efficiencies =", "= Arrhenius( A = (1.0e12,\"s^-1\"), n = 1.0, Ea =", "self.assertAlmostEqual(self.reaction.kinetics.Ea.value_si, reaction.kinetics.Ea.value_si, delta=1e-6) self.assertEqual(self.reaction.kinetics.comment, reaction.kinetics.comment) self.assertEqual(self.reaction.duplicate, reaction.duplicate) self.assertEqual(self.reaction.degeneracy, reaction.degeneracy) def", "opticalIsomers = 1, ), ) ethyl = Species( label =", "982.714, 1024.16, 1224.21, 1326.36, 1455.06, 1600.35, 3101.46, 3110.55, 3175.34, 3201.88],", "\"[H][H]\": 2} Tmin = 300. Tmax = 2000. Pmin =", "'C2H4', conformer = Conformer( E0 = (44.7127, 'kJ/mol'), modes =", "reactant.conformer.E0.units) for product0, product in zip(self.reaction.products, reaction.products): self.assertAlmostEqual(product0.conformer.E0.value_si / 1e6,", "for the Lindemann format. \"\"\" from rmgpy.kinetics import Lindemann arrheniusHigh", "'Ab=CD' \"\"\" reactants, products = reaction_string.split('=') reactants = [PseudoSpecies(i) for", "spinMultiplicity = 2, opticalIsomers = 1, ), ) TS =", "(501366000.0, 'cm^3/(mol*s)'), n = 1.637, Ea = (4.32508, 'kJ/mol'), T0", "'0.000105413', '3.93273e-05', '1.83006e-05']] Kclist = self.reaction2.getEquilibriumConstants(Tlist, type='Kc') for i in", "= -0.534, Ea = (2.243,\"kJ/mol\"), T0 = (1,\"K\"), ) arrheniusLow", "= comment, ), Arrhenius( A = (9.3e-14,\"cm^3/(molecule*s)\"), n = 0.0,", "numpy.array([1e-1,1e1]) comment = 'CH3 + C2H6 <=> CH4 + C2H5", "can be successfully pickled and unpickled with no loss of", "= Species( label = 'C2H5', conformer = Conformer( E0 =", "comment, ), Arrhenius( A = (1.4e-9,\"cm^3/(molecule*s)\"), n = 0.0, Ea", "self.assertEqual(self.reaction.transitionState.conformer.E0.units, reaction.transitionState.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.frequency.value_si, reaction.transitionState.frequency.value_si, 2) self.assertEqual(self.reaction.transitionState.frequency.units, reaction.transitionState.frequency.units) self.assertAlmostEqual(self.reaction.kinetics.A.value_si, reaction.kinetics.A.value_si, delta=1e-6)", "in range(len(Tlist)): self.assertAlmostEqual(Kplist[i] / Kplist0[i], 1.0, 4) def testStoichiometricCoefficient(self): \"\"\"", "== other.label.lower() class TestReactionIsomorphism(unittest.TestCase): \"\"\" Contains unit tests of the", "), PDepArrhenius( pressures = (pressures,\"bar\"), arrhenius = [ Arrhenius( A", "a1=26.18, a2=-70.47, a3=44.12, B=(500.0,\"K\"), H0=(1.453e+04,\"J/mol\"), S0=(-12.19,\"J/(mol*K)\")), ) self.reaction2 = Reaction(", "= reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientTroe(self):", "def testGenerateReverseRateCoefficientArrhenius(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the", "\"\"\" import numpy import unittest from external.wip import work_in_progress from", "= reversereverseKinetics.getRateCoefficient(T, P) self.assertAlmostEqual(korig / krevrev, 1.0, 0) def testGenerateReverseRateCoefficientLindemann(self):", "Lindemann( arrheniusHigh = arrheniusHigh, arrheniusLow = arrheniusLow, Tmin = (Tmin,\"K\"),", "0) def testGenerateReverseRateCoefficientTroe(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for", "(41.84, 'kJ/mol'), Tmin = (300, 'K'), Tmax = (2000, 'K'),", "'-145886', '-144195', '-141973', '-139633', '-137341', '-135155', '-133093', '-131150', '-129316']] Hlist", "\"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) P = 1e5", "unit tests of the isomorphism testing of the Reaction class.", "reverting the reverse yields the original Tlist = numpy.arange(original_kinetics.Tmin.value_si, original_kinetics.Tmax.value_si,", "), ] original_kinetics = MultiPDepArrhenius( arrhenius = arrhenius, Tmin =", "reactants, products = reaction_string.split('=') reactants = [PseudoSpecies(i) for i in", "acetyl = Species( label='acetyl', thermo=Wilhoit(Cp0=(4.0*constants.R,\"J/(mol*K)\"), CpInf=(15.5*constants.R,\"J/(mol*K)\"), a0=0.2541, a1=-0.4712, a2=-4.434, a3=2.25,", "range(len(Tlist)): self.assertAlmostEqual(Kalist[i] / Kalist0[i], 1.0, 4) def testEquilibriumConstantKc(self): \"\"\" Test", "products=[Species()]) dissociation = Reaction(reactants=[Species()], products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertTrue(isomerization.isIsomerization())", "= (1.4e-11,\"cm^3/(molecule*s)\"), n = 0.0, Ea = (11200*constants.R*0.001,\"kJ/mol\"), T0 =", "Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kalist0 = [float(v) for", "], Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"), Pmin = (Pmin,\"bar\"),", "reaction.kinetics.Ea.value_si, delta=1e-6) self.assertEqual(self.reaction.kinetics.comment, reaction.kinetics.comment) self.assertEqual(self.reaction.duplicate, reaction.duplicate) self.assertEqual(self.reaction.degeneracy, reaction.degeneracy) ################################################################################ if", "Reaction object can be successfully pickled and unpickled with no", "in zip(self.reaction.reactants, reaction.reactants): self.assertAlmostEqual(reactant0.conformer.E0.value_si / 1e6, reactant.conformer.E0.value_si / 1e6, 2)", "numpy.array([arrhenius.getRateCoefficient(T) for T in Tlist]) # Check that the correct", "its repr() output with no loss of information. \"\"\" exec('reaction", "0.783 T3 = 74 T1 = 2941 T2 = 6964", "Check that the fit is satisfactory (defined here as always", "rmgpy.kinetics import ArrheniusEP original_kinetics = ArrheniusEP( A = (2.65e12, 'cm^3/(mol*s)'),", "from rmgpy.statmech.vibration import Vibration, HarmonicOscillator from rmgpy.statmech.torsion import Torsion, HinderedRotor", "'amu*angstrom^2', ), symmetry = 4, ), HarmonicOscillator( frequencies = (", "\"[C]=O\": 1.5, \"[H][H]\": 2} Tmin = 300. Tmax = 2000.", "Tmin = 300. Tmax = 2000. Pmin = 0.01 Pmax", "\"\"\" from rmgpy.kinetics import ArrheniusEP original_kinetics = ArrheniusEP( A =", "from rmgpy.reaction import Reaction from rmgpy.statmech.translation import Translation, IdealGasTranslation from", "Reaction.getEquilibriumConstant() method. \"\"\" Tlist = numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Kalist0", "= (Tmax,\"K\"), comment = comment, ), ] original_kinetics = MultiArrhenius(", "Vibration, HarmonicOscillator from rmgpy.statmech.torsion import Torsion, HinderedRotor from rmgpy.statmech.conformer import", "= Reaction(reactants=[Species()], products=[Species(),Species()]) bimolecular = Reaction(reactants=[Species(),Species()], products=[Species(),Species()]) self.assertFalse(isomerization.isDissociation()) self.assertFalse(association.isDissociation()) self.assertTrue(dissociation.isDissociation())", "for i in reactants] products = [PseudoSpecies(i) for i in", "= (Pmax,\"bar\"), comment = comment, ), ] original_kinetics = MultiPDepArrhenius(", "+ CH3 -> CH4\"\"\" troe = Troe( arrheniusHigh = arrheniusHigh,", "def testGenerateReverseRateCoefficientThirdBody(self): \"\"\" Test the Reaction.generateReverseRateCoefficient() method works for the", "arrheniusLow, alpha = alpha, T3 = (T3,\"K\"), T1 = (T1,\"K\"),", "len(reaction.reactants)) self.assertEqual(len(self.reaction.products), len(reaction.products)) for reactant0, reactant in zip(self.reaction.reactants, reaction.reactants): self.assertAlmostEqual(reactant0.conformer.E0.value_si", "Tmax = 2000.0 Pmin = 0.1 Pmax = 10.0 comment", "delta=5e-2 * klist[i]) def testPickle(self): \"\"\" Test that a Reaction", "completely made up\"\"\" arrhenius = [ Arrhenius( A = (9.3e-14,\"cm^3/(molecule*s)\"),", "1e6, 2) self.assertEqual(reactant0.conformer.E0.units, reactant.conformer.E0.units) for product0, product in zip(self.reaction.products, reaction.products):", "/ 1e6, reaction.transitionState.conformer.E0.value_si / 1e6, 2) self.assertEqual(self.reaction.transitionState.conformer.E0.units, reaction.transitionState.conformer.E0.units) self.assertAlmostEqual(self.reaction.transitionState.frequency.value_si, reaction.transitionState.frequency.value_si,", "1.45419, delta=1e-4) self.assertAlmostEqual(arrhenius.Ea.value_si, 6645.24, delta=1e-2) # Check that the fit", "self.assertEqual(len(self.reaction.reactants), len(reaction.reactants)) self.assertEqual(len(self.reaction.products), len(reaction.products)) for reactant0, reactant in zip(self.reaction.reactants, reaction.reactants):", "200.0, numpy.float64) Glist0 = [float(v) for v in ['-114648', '-83137.2',", "0.01 Pmax = 100. comment = \"\"\"H + CH3 ->", "350. Tmax = 1500. Pmin = 1e-1 Pmax = 1e1", "self.assertFalse(isomerization.isDissociation()) self.assertFalse(association.isDissociation()) self.assertTrue(dissociation.isDissociation()) self.assertFalse(bimolecular.isDissociation()) def testHasTemplate(self): \"\"\" Test the Reaction.hasTemplate()", "\"\"\" reactants, products = reaction_string.split('=') reactants = [PseudoSpecies(i) for i", "numpy.arange(200.0, 2001.0, 200.0, numpy.float64) Glist0 = [float(v) for v in", "reverting the reverse yields the original Tlist = numpy.arange(Tmin, Tmax,", "Tlist = numpy.arange(Tmin, Tmax, 200.0, numpy.float64) P = 1e5 for", "in range(len(Tlist)): self.assertAlmostEqual(Glist[i] / 1000., Glist0[i] / 1000., 2) def", "1224.21, 1326.36, 1455.06, 1600.35, 3101.46, 3110.55, 3175.34, 3201.88], 'cm^-1', ),", "= ( [4.8709, 22.2353, 23.9925], 'amu*angstrom^2', ), symmetry = 1,", "the Reaction.isDissociation() method. \"\"\" isomerization = Reaction(reactants=[Species()], products=[Species()]) association =", "MultiArrhenius( arrhenius = arrhenius, Tmin = (Tmin,\"K\"), Tmax = (Tmax,\"K\"),", "__repr__(self): return \"PseudoSpecies('{0}')\".format(self.label) def __str__(self): return self.label def isIsomorphic(self, other):" ]
[ "views as tagsViews from contents import views as contentsViews from", "router.register(r\"contents\", contentsViews.ContentViewSet) router.register(r\"contact\", contactViews.MessageViewSet) # List or url patterns for", "as contentsViews from contact import views as contactViews router =", "from snippets import views as snippetsViews from projects import views", "from contact import views as contactViews router = OptionalTrailingSlashRouter() router.register(r\"blog\",", "contactViews.MessageViewSet) # List or url patterns for the api subdomain", "include from core.routers import OptionalTrailingSlashRouter from blog import views as", "views as contentsViews from contact import views as contactViews router", "contact import views as contactViews router = OptionalTrailingSlashRouter() router.register(r\"blog\", blogViews.PostViewSet)", "router = OptionalTrailingSlashRouter() router.register(r\"blog\", blogViews.PostViewSet) router.register(r\"snippets\", snippetsViews.SnippetViewSet) router.register(r\"languages\", snippetsViews.ProgrammingLanguageViewSet) router.register(r\"projects\",", "tags import views as tagsViews from contents import views as", "snippets import views as snippetsViews from projects import views as", "from tags import views as tagsViews from contents import views", "patterns for the api subdomain urlpatterns = [ url(r\"^v2/\", include(router.urls)),", "import views as snippetsViews from projects import views as projectsViews", "# List or url patterns for the api subdomain urlpatterns", "views as contactViews router = OptionalTrailingSlashRouter() router.register(r\"blog\", blogViews.PostViewSet) router.register(r\"snippets\", snippetsViews.SnippetViewSet)", "core.routers import OptionalTrailingSlashRouter from blog import views as blogViews from", "as snippetsViews from projects import views as projectsViews from tags", "from core.routers import OptionalTrailingSlashRouter from blog import views as blogViews", "snippetsViews from projects import views as projectsViews from tags import", "django.conf.urls import url, include from core.routers import OptionalTrailingSlashRouter from blog", "projects import views as projectsViews from tags import views as", "as projectsViews from tags import views as tagsViews from contents", "router.register(r\"snippets\", snippetsViews.SnippetViewSet) router.register(r\"languages\", snippetsViews.ProgrammingLanguageViewSet) router.register(r\"projects\", projectsViews.ProjectViewSet) router.register(r\"tags\", tagsViews.TagViewSet) router.register(r\"contents\", contentsViews.ContentViewSet)", "contentsViews.ContentViewSet) router.register(r\"contact\", contactViews.MessageViewSet) # List or url patterns for the", "or url patterns for the api subdomain urlpatterns = [", "contentsViews from contact import views as contactViews router = OptionalTrailingSlashRouter()", "router.register(r\"contact\", contactViews.MessageViewSet) # List or url patterns for the api", "router.register(r\"blog\", blogViews.PostViewSet) router.register(r\"snippets\", snippetsViews.SnippetViewSet) router.register(r\"languages\", snippetsViews.ProgrammingLanguageViewSet) router.register(r\"projects\", projectsViews.ProjectViewSet) router.register(r\"tags\", tagsViews.TagViewSet)", "url, include from core.routers import OptionalTrailingSlashRouter from blog import views", "from blog import views as blogViews from snippets import views", "as blogViews from snippets import views as snippetsViews from projects", "import views as contactViews router = OptionalTrailingSlashRouter() router.register(r\"blog\", blogViews.PostViewSet) router.register(r\"snippets\",", "tagsViews.TagViewSet) router.register(r\"contents\", contentsViews.ContentViewSet) router.register(r\"contact\", contactViews.MessageViewSet) # List or url patterns", "as tagsViews from contents import views as contentsViews from contact", "import OptionalTrailingSlashRouter from blog import views as blogViews from snippets", "OptionalTrailingSlashRouter from blog import views as blogViews from snippets import", "router.register(r\"languages\", snippetsViews.ProgrammingLanguageViewSet) router.register(r\"projects\", projectsViews.ProjectViewSet) router.register(r\"tags\", tagsViews.TagViewSet) router.register(r\"contents\", contentsViews.ContentViewSet) router.register(r\"contact\", contactViews.MessageViewSet)", "projectsViews.ProjectViewSet) router.register(r\"tags\", tagsViews.TagViewSet) router.register(r\"contents\", contentsViews.ContentViewSet) router.register(r\"contact\", contactViews.MessageViewSet) # List or", "views as blogViews from snippets import views as snippetsViews from", "views as snippetsViews from projects import views as projectsViews from", "from django.conf.urls import url, include from core.routers import OptionalTrailingSlashRouter from", "contents import views as contentsViews from contact import views as", "from contents import views as contentsViews from contact import views", "views as projectsViews from tags import views as tagsViews from", "url patterns for the api subdomain urlpatterns = [ url(r\"^v2/\",", "contactViews router = OptionalTrailingSlashRouter() router.register(r\"blog\", blogViews.PostViewSet) router.register(r\"snippets\", snippetsViews.SnippetViewSet) router.register(r\"languages\", snippetsViews.ProgrammingLanguageViewSet)", "import url, include from core.routers import OptionalTrailingSlashRouter from blog import", "<filename>backend/core/api_urls.py from django.conf.urls import url, include from core.routers import OptionalTrailingSlashRouter", "blogViews.PostViewSet) router.register(r\"snippets\", snippetsViews.SnippetViewSet) router.register(r\"languages\", snippetsViews.ProgrammingLanguageViewSet) router.register(r\"projects\", projectsViews.ProjectViewSet) router.register(r\"tags\", tagsViews.TagViewSet) router.register(r\"contents\",", "router.register(r\"tags\", tagsViews.TagViewSet) router.register(r\"contents\", contentsViews.ContentViewSet) router.register(r\"contact\", contactViews.MessageViewSet) # List or url", "for the api subdomain urlpatterns = [ url(r\"^v2/\", include(router.urls)), ]", "as contactViews router = OptionalTrailingSlashRouter() router.register(r\"blog\", blogViews.PostViewSet) router.register(r\"snippets\", snippetsViews.SnippetViewSet) router.register(r\"languages\",", "from projects import views as projectsViews from tags import views", "import views as tagsViews from contents import views as contentsViews", "snippetsViews.SnippetViewSet) router.register(r\"languages\", snippetsViews.ProgrammingLanguageViewSet) router.register(r\"projects\", projectsViews.ProjectViewSet) router.register(r\"tags\", tagsViews.TagViewSet) router.register(r\"contents\", contentsViews.ContentViewSet) router.register(r\"contact\",", "OptionalTrailingSlashRouter() router.register(r\"blog\", blogViews.PostViewSet) router.register(r\"snippets\", snippetsViews.SnippetViewSet) router.register(r\"languages\", snippetsViews.ProgrammingLanguageViewSet) router.register(r\"projects\", projectsViews.ProjectViewSet) router.register(r\"tags\",", "tagsViews from contents import views as contentsViews from contact import", "import views as contentsViews from contact import views as contactViews", "import views as blogViews from snippets import views as snippetsViews", "blog import views as blogViews from snippets import views as", "router.register(r\"projects\", projectsViews.ProjectViewSet) router.register(r\"tags\", tagsViews.TagViewSet) router.register(r\"contents\", contentsViews.ContentViewSet) router.register(r\"contact\", contactViews.MessageViewSet) # List", "List or url patterns for the api subdomain urlpatterns =", "= OptionalTrailingSlashRouter() router.register(r\"blog\", blogViews.PostViewSet) router.register(r\"snippets\", snippetsViews.SnippetViewSet) router.register(r\"languages\", snippetsViews.ProgrammingLanguageViewSet) router.register(r\"projects\", projectsViews.ProjectViewSet)", "projectsViews from tags import views as tagsViews from contents import", "blogViews from snippets import views as snippetsViews from projects import", "snippetsViews.ProgrammingLanguageViewSet) router.register(r\"projects\", projectsViews.ProjectViewSet) router.register(r\"tags\", tagsViews.TagViewSet) router.register(r\"contents\", contentsViews.ContentViewSet) router.register(r\"contact\", contactViews.MessageViewSet) #", "import views as projectsViews from tags import views as tagsViews" ]
[ "optimal ordering defined by ADG \"\"\" import sys import yaml", "robots_done = [] time_to_goal = {} colors = plt.cm.rainbow( np.arange(len(robot_plan))/len(robot_plan)", "for idx, t in time_to_goal.items(): total_time += t logger.info(\"Total time", "goal_positions = determine_ADG(plans, show_graph=False) nodes_all, edges_type_1, dependency_groups = analyze_ADG(ADG, plans,", "random.seed(map_gen_seedval) # map_gen_seedval np.random.seed(map_gen_seedval) # map_gen_seedval except: print(\" no valid", "{}\".format(pl_opt.instance)) ADG_fig = plt.figure(figsize=(12,8)) plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)", "# pl_opt.instance = m_opt.name # print(\"pl_opt.instance: {}\".format(pl_opt.instance)) ADG_fig = plt.figure(figsize=(12,8))", "delay_amount = 5 delayed_robot_cnt = 2 w = 1.4 #", "robot status logger.info(\"-------------------- @ time step k = {} --------------------\".format(k))", "# draw_ADG(ADG, robots, \"ADG after MILP ADG | k =", "determine optimal ordering defined by ADG \"\"\" import sys import", "logging import time import networkx as nx import csv import", "right=1, top=1, wspace=0, hspace=0) metadata = dict(title='Movie Test', artist='Matplotlib', comment='Movie", "time\"] = total_time logger.info(simulation_results) file_name = pwd + \"/results/robust_\" +str(delayed_robot_cnt)", "bottom=0, right=1, top=1, wspace=0, hspace=0) metadata = dict(title='Movie Test', artist='Matplotlib',", "in robot_IDs_to_delay)): # or (k < 10 or k >", "analyze_ADG(ADG, plans, show_graph=False) ADG_reverse = ADG.reverse(copy=False) # initialize simulation robots", "for robot_id in robot_plan: plan = robot_plan[robot_id] logger.debug(\"Robot {} -", "import time import matplotlib.colors as mcolors import matplotlib import matplotlib.pyplot", ") for robot_id in robot_plan: plan = robot_plan[robot_id] logger.debug(\"Robot {}", "map_gen_seedval except: print(\" no valid inputs given, ignoring ...\") #", "been met, to advance to next node node_info = ADG.node[robot.current_node][\"data\"]", "int(sys.argv[3]) robust_param = int(sys.argv[4]) random.seed(map_gen_seedval) # map_gen_seedval np.random.seed(map_gen_seedval) # map_gen_seedval", "= random_seed simulation_results[\"parameters\"][\"ECBS w\"] = w simulation_results[\"parameters\"][\"mu\"] = mu simulation_results[\"parameters\"][\"robust", "#not show_visual run_MILP = True #False #True save_file = False", "node_dependencies_list: if (ADG.node[dependency][\"data\"].status != Status.FINISHED): all_dependencies_completed = False # if", "logger.info(\"\") logger.info(\"Computation time:\") logger.info(\" - max: {}\".format(max(solve_time))) logger.info(\" - avg:", "w = 1.4 # sub-optimality bound: w = 1.0 ->", "xsum, maximize, minimize, BINARY, CONTINUOUS, Constr, ConstrList sys.path.insert(1, \"functions/\") from", "# print(\"pl_opt.settings: {}\".format(pl_opt.settings)) # print(\"pl_opt.log: {}\".format(pl_opt.log)) # pl_opt.instance = m_opt.name", "+ str(delay_amount) + \"/res_robots_\" + str(map_gen_robot_count) + \"_horizon_\" + str(H_control)", "advance! # delay_amount = np.random.poisson(mu) # same sample every time", "= {} simulation_results[\"results\"][\"comp time\"] = {} simulation_results[\"results\"][\"comp time\"][\"solve_time\"] = [solve_time]", "import time import networkx as nx import csv import statistics", "= mu simulation_results[\"parameters\"][\"robust param\"] = robust_param simulation_results[\"parameters\"][\"delay amount\"] = delay_amount", "logging.getLogger(__name__) logging.basicConfig(format='%(name)s - %(levelname)s :: %(message)s', level=logging.INFO) def main(): \"\"\"", "simulation_results[\"results\"][\"comp time\"] = {} simulation_results[\"results\"][\"comp time\"][\"solve_time\"] = [solve_time] simulation_results[\"results\"][\"comp time\"][\"max\"]", "writer=writer) # plt.show() # check for cycles try: nx.find_cycle(ADG, orientation=\"original\")", "node_info = ADG.node[robot.current_node][\"data\"] node_dependencies_list = list(ADG_reverse.neighbors(robot.current_node)) all_dependencies_completed = True for", "and control horizons: H_prediction >= H_control H_prediction = np.NaN #", "!= Status.FINISHED): all_dependencies_completed = False # if all dependencies are", "\"\"\" closed-loop MILP solved to determine optimal ordering defined by", "\"ADG_video.mp4\", 500): # run a simulation in time k =", "k = 0 robot_IDs_to_delay = [] while (not all(robots_done)) and", "H_control = int(sys.argv[3]) robust_param = int(sys.argv[4]) random.seed(map_gen_seedval) # map_gen_seedval np.random.seed(map_gen_seedval)", "= solve_MILP(robots, dependency_groups, ADG, ADG_reverse, H_control, H_prediction, m_opt, pl_opt, run=run_MILP,", "or k > 5) if (not (robot.robot_ID in robot_IDs_to_delay)): #", "robust_param = 0.0 delay_amount = 5 delayed_robot_cnt = 2 w", "as plt import random import logging import time import networkx", "FFMpegWriter(fps=2, metadata=metadata) with writer.saving(ADG_fig, \"ADG_video.mp4\", 500): # run a simulation", "and (k < sim_timeout): print(\"pl_opt.log: {}\".format(pl_opt.log)) m_opt.clear() # show current", "time\"][\"avg\"] = stat.mean(solve_time) simulation_results[\"results\"][\"total time\"] = total_time logger.info(simulation_results) file_name =", "time_to_goal[robot.robot_ID] += 1 else: robots_done[robot.robot_ID] = True if show_visual: visualizer.redraw(robots,", "pl_opt = ProgressLog() # pl_opt.settings = \"objective_value\" # print(\"pl_opt.settings: {}\".format(pl_opt.settings))", "np.NaN # integer value for forward node lookup H_control =", "except: print(\" no valid inputs given, ignoring ...\") # determine", "Advance robots if possible (dependencies have been met) for robot", "= robot_plan[robot_id] logger.debug(\"Robot {} - plan: {} \\t \\t positions:", "step k = {} --------------------\".format(k)) for robot in robots: node_info", "amount\"] = delay_amount simulation_results[\"map details\"] = {} simulation_results[\"map details\"][\"robot_count\"] =", "else: robots_done[robot.robot_ID] = True if show_visual: visualizer.redraw(robots, pause_length=0.1) # return", "* from robot import * from adg import * from", "pl_opt, run=run_MILP, uncertainty_bound=robust_param) solve_time.append(solve_t) if not (res is None or", "+ \"/data/\" + fldr + \"/csv_robots_yaml.yaml\" robot_file_tmp = pwd +", "not robot.is_done(): time_to_goal[robot.robot_ID] += 1 else: robots_done[robot.robot_ID] = True if", "sys.path.insert(1, \"functions/\") from planners import * from visualizers import *", "ProgressLog, xsum, maximize, minimize, BINARY, CONTINUOUS, Constr, ConstrList sys.path.insert(1, \"functions/\")", "comment='Movie support!') writer = FFMpegWriter(fps=2, metadata=metadata) with writer.saving(ADG_fig, \"ADG_video.mp4\", 500):", "solve MILP for the advanced ADG to potentially adjust ordering", "matplotlib.pyplot as plt import random import logging import time import", "= list(ADG_reverse.neighbors(robot.current_node)) all_dependencies_completed = True for dependency in node_dependencies_list: if", "= stat.mean(solve_time) simulation_results[\"results\"][\"total time\"] = total_time logger.info(simulation_results) file_name = pwd", "details\"] = {} simulation_results[\"map details\"][\"robot_count\"] = map_gen_robot_count simulation_results[\"map details\"][\"seed val\"]", "MILP if show_ADG: # draw_ADG(ADG, robots, \"ADG after MILP ADG", "%(levelname)s :: %(message)s', level=logging.INFO) def main(): \"\"\" --------------------------- INPUTS ---------------------------------", "logger.debug(\" - Robot {} # {} @ {} => status:", "level=logging.INFO) def main(): \"\"\" --------------------------- INPUTS --------------------------------- \"\"\" show_visual =", "random_seed = 0 mu = 0.5 robust_param = 0.0 delay_amount", "uses ECBS! logger.info(\" with sub-optimality w={}\".format(w)) logger.info(\" plan statistics: {}", "map_gen_seedval = \"NaN\" try: map_gen_robot_count = int(sys.argv[1]) map_gen_seedval = int(sys.argv[2])", "= map_gen_robot_count simulation_results[\"map details\"][\"seed val\"] = map_gen_seedval simulation_results[\"results\"] = {}", "(ID): {}\".format(robot_IDs_to_delay)) # Advance robots if possible (dependencies have been", "sys import yaml import time import matplotlib.colors as mcolors import", "False show_ADG = True #not show_visual run_MILP = True #False", "time step k = {} --------------------\".format(k)) for robot in robots:", "for dependency in node_dependencies_list: if (ADG.node[dependency][\"data\"].status != Status.FINISHED): all_dependencies_completed =", "@ {} => status: {}\".format(robot.robot_ID, node_info.ID, node_info.s_loc, robot.status)) # solve", "# solve MILP for the advanced ADG to potentially adjust", "Status.FINISHED robot.advance() if not robot.is_done(): time_to_goal[robot.robot_ID] += 1 else: robots_done[robot.robot_ID]", ":: %(message)s', level=logging.INFO) def main(): \"\"\" --------------------------- INPUTS --------------------------------- \"\"\"", "hspace=0) metadata = dict(title='Movie Test', artist='Matplotlib', comment='Movie support!') writer =", "from adg_node import * from process_results import * logger =", "{} simulation_results[\"parameters\"] = {} simulation_results[\"parameters\"][\"H_control\"] = H_control simulation_results[\"parameters\"][\"random seed\"] =", "{}\".format(pl_opt.settings)) # print(\"pl_opt.log: {}\".format(pl_opt.log)) # pl_opt.instance = m_opt.name # print(\"pl_opt.instance:", "logger.info(\"horizon = {}\".format(H_control)) logger.info(\"\") logger.info(\"Computation time:\") logger.info(\" - max: {}\".format(max(solve_time)))", "to advance to next node node_info = ADG.node[robot.current_node][\"data\"] node_dependencies_list =", "= os.path.dirname(os.path.abspath(__file__)) logger.info(pwd) map_file = pwd + \"/data/\" + fldr", "import statistics as stat import os import sys from mip", "{}\".format(total_time)) logger.info(\"horizon = {}\".format(H_control)) logger.info(\"\") logger.info(\"Computation time:\") logger.info(\" - max:", "= {} simulation_results[\"parameters\"][\"H_control\"] = H_control simulation_results[\"parameters\"][\"random seed\"] = random_seed simulation_results[\"parameters\"][\"ECBS", "for cycles try: nx.find_cycle(ADG, orientation=\"original\") logger.warning(\"Cycle detected!!\") raise Exception(\"ADG has", "{}\".format(pl_opt.log)) m_opt.clear() # show current robot status logger.info(\"-------------------- @ time", "k = {} --------------------\".format(k)) for robot in robots: node_info =", "False # if all dependencies are completed, the robot can", "[] time_to_goal = {} colors = plt.cm.rainbow( np.arange(len(robot_plan))/len(robot_plan) ) for", "replace=False) logger.info(\"delaying robots (ID): {}\".format(robot_IDs_to_delay)) # Advance robots if possible", "+ str(map_gen_seedval) + \"_robustparam_\" + str(robust_param) + \".yaml\" if save_file:", "True #not show_visual run_MILP = True #False #True save_file =", "-> CBS, else ECBS! fldr = \"nuernberg_small\" # auto_gen_01_nuernberg |", "dependencies have been met, to advance to next node node_info", "import * from robot import * from adg import *", "fldr = \"nuernberg_small\" # auto_gen_01_nuernberg | auto_gen_00_large | auto_gen_02_simple |", "param\"] = robust_param simulation_results[\"parameters\"][\"delay amount\"] = delay_amount simulation_results[\"map details\"] =", "+ str(robust_param) + \".yaml\" if save_file: save_to_yaml(simulation_results, file_name) if __name__", "robot_id in robot_plan: plan = robot_plan[robot_id] logger.debug(\"Robot {} - plan:", "= ADG.reverse(copy=False) # initialize simulation robots = [] solve_time =", "=> deadlock! something is wrong with optimization\") except nx.NetworkXNoCycle: logger.debug(\"no", "\\n\".format(plans[\"statistics\"])) logger.debug(plans[\"schedule\"]) # show factory map # show_factory_map(map_file, robot_file, True)", "{} simulation_results[\"results\"][\"comp time\"][\"solve_time\"] = [solve_time] simulation_results[\"results\"][\"comp time\"][\"max\"] = max(solve_time) simulation_results[\"results\"][\"comp", "8): ADG.node[robot.current_node][\"data\"].status = Status.FINISHED robot.advance() if not robot.is_done(): time_to_goal[robot.robot_ID] +=", "value for forward node lookup H_control = 5 random_seed =", "ADG, ADG_reverse, H_control, H_prediction, m_opt, pl_opt, run=run_MILP, uncertainty_bound=robust_param) solve_time.append(solve_t) if", "plan statistics: {} \\n\".format(plans[\"statistics\"])) logger.debug(plans[\"schedule\"]) # show factory map #", "= int(sys.argv[4]) random.seed(map_gen_seedval) # map_gen_seedval np.random.seed(map_gen_seedval) # map_gen_seedval except: print(\"", "\"/data/\" + fldr + \"/csv_map_yaml.yaml\" robot_file = pwd + \"/data/\"", "= True for dependency in node_dependencies_list: if (ADG.node[dependency][\"data\"].status != Status.FINISHED):", "time\"] = {} simulation_results[\"results\"][\"comp time\"][\"solve_time\"] = [solve_time] simulation_results[\"results\"][\"comp time\"][\"max\"] =", "loop total_time = 0 for idx, t in time_to_goal.items(): total_time", "# initialize simulation robots = [] solve_time = [] robots_done", "time:\") logger.info(\" - max: {}\".format(max(solve_time))) logger.info(\" - avg: {}\".format(stat.mean(solve_time))) #", "initialize simulation robots = [] solve_time = [] robots_done =", "# if w > 1.0, run_CBS uses ECBS! logger.info(\" with", "logger.debug(\"no cycle detected in ADG => no deadlock. good!\") pass", "20)): # or (robot.robot_ID == 3 or k > 8):", "forward node lookup H_control = 5 random_seed = 0 mu", "\"x\" + str(delay_amount) + \"/res_robots_\" + str(map_gen_robot_count) + \"_horizon_\" +", "# map_gen_seedval except: print(\" no valid inputs given, ignoring ...\")", "* from process_results import * logger = logging.getLogger(__name__) logging.basicConfig(format='%(name)s -", "robot import * from adg import * from adg_node import", "nx.NetworkXNoCycle: logger.debug(\"no cycle detected in ADG => no deadlock. good!\")", "[] while (not all(robots_done)) and (k < sim_timeout): print(\"pl_opt.log: {}\".format(pl_opt.log))", "random.seed(random_seed) np.random.seed(random_seed) \"\"\" -------------------------------------------------------------------- \"\"\" # start initial pwd =", "map_gen_seedval np.random.seed(map_gen_seedval) # map_gen_seedval except: print(\" no valid inputs given,", "k += 1 # end of while loop total_time =", "logger.info(\"delaying robots (ID): {}\".format(robot_IDs_to_delay)) # Advance robots if possible (dependencies", "robust_param = int(sys.argv[4]) random.seed(map_gen_seedval) # map_gen_seedval np.random.seed(map_gen_seedval) # map_gen_seedval except:", "+= 1 # end of while loop total_time = 0", "# map_gen_seedval np.random.seed(map_gen_seedval) # map_gen_seedval except: print(\" no valid inputs", "k > 8): ADG.node[robot.current_node][\"data\"].status = Status.FINISHED robot.advance() if not robot.is_done():", "simulation_results[\"parameters\"][\"robust param\"] = robust_param simulation_results[\"parameters\"][\"delay amount\"] = delay_amount simulation_results[\"map details\"]", "horizons: H_prediction >= H_control H_prediction = np.NaN # integer value", "Model, ProgressLog, xsum, maximize, minimize, BINARY, CONTINUOUS, Constr, ConstrList sys.path.insert(1,", "to YAML file simulation_results = {} simulation_results[\"parameters\"] = {} simulation_results[\"parameters\"][\"H_control\"]", "ignoring ...\") # determine ADG, reverse ADG and dependency groups", "= run_CBS(map_file, robot_file, w=w) # if w > 1.0, run_CBS", "{}\".format(robot_IDs_to_delay)) # Advance robots if possible (dependencies have been met)", "details\"][\"robot_count\"] = map_gen_robot_count simulation_results[\"map details\"][\"seed val\"] = map_gen_seedval simulation_results[\"results\"] =", "simulation_results[\"results\"][\"comp time\"][\"max\"] = max(solve_time) simulation_results[\"results\"][\"comp time\"][\"avg\"] = stat.mean(solve_time) simulation_results[\"results\"][\"total time\"]", "None or res == \"OptimizationStatus.OPTIMAL\"): ValueError(\"Optimization NOT optimal\") # ADG", "{}\".format(stat.mean(solve_time))) # create data to save to YAML file simulation_results", "@ time step k = {} --------------------\".format(k)) for robot in", "= int(sys.argv[3]) robust_param = int(sys.argv[4]) random.seed(map_gen_seedval) # map_gen_seedval np.random.seed(map_gen_seedval) #", "Robot(robot_id, plan, colors[robot_id], goal_positions[robot_id]) robots.append(new_robot) robots_done.append(False) time_to_goal[robot_id] = 0 if", "- avg: {}\".format(stat.mean(solve_time))) # create data to save to YAML", "os import sys from mip import Model, ProgressLog, xsum, maximize,", "robot.status)) # solve MILP for the advanced ADG to potentially", "| k = {}\".format(k), writer=writer) # plt.show() # check for", "\"ADG after MILP ADG | k = {}\".format(k), writer=writer) #", "closed-loop MILP solved to determine optimal ordering defined by ADG", "if (k % delay_amount) == 0: robot_IDs = np.arange(map_gen_robot_count) robot_IDs_to_delay", "good!\") pass if (k % delay_amount) == 0: robot_IDs =", "robot in robots: # check if all dependencies have been", "robust_param simulation_results[\"parameters\"][\"delay amount\"] = delay_amount simulation_results[\"map details\"] = {} simulation_results[\"map", "node lookup H_control = 5 random_seed = 0 mu =", "show_factory_map(map_file, robot_file, True) # plt.show() map_gen_robot_count = 10 map_gen_seedval =", "ADG_reverse = ADG.reverse(copy=False) # initialize simulation robots = [] solve_time", "\"\"\" show_visual = False show_ADG = True #not show_visual run_MILP", "= 2 w = 1.4 # sub-optimality bound: w =", "Robot {} # {} @ {} => status: {}\".format(robot.robot_ID, node_info.ID,", "solve_MILP(robots, dependency_groups, ADG, ADG_reverse, H_control, H_prediction, m_opt, pl_opt, run=run_MILP, uncertainty_bound=robust_param)", "{} simulation_results[\"map details\"][\"robot_count\"] = map_gen_robot_count simulation_results[\"map details\"][\"seed val\"] = map_gen_seedval", "adjust ordering res, solve_t = solve_MILP(robots, dependency_groups, ADG, ADG_reverse, H_control,", "= m_opt.name # print(\"pl_opt.instance: {}\".format(pl_opt.instance)) ADG_fig = plt.figure(figsize=(12,8)) plt.subplots_adjust(left=0, bottom=0,", "robots (ID): {}\".format(robot_IDs_to_delay)) # Advance robots if possible (dependencies have", "# run a simulation in time k = 0 robot_IDs_to_delay", "simulation_results[\"parameters\"][\"random seed\"] = random_seed simulation_results[\"parameters\"][\"ECBS w\"] = w simulation_results[\"parameters\"][\"mu\"] =", "+ \"/data/tmp/robots.yaml\" start_time = time.time() plans = run_CBS(map_file, robot_file, w=w)", "=> status: {}\".format(robot.robot_ID, node_info.ID, node_info.s_loc, robot.status)) # solve MILP for", "== 2 or k > 5) if (not (robot.robot_ID in", "+= t logger.info(\"Total time to complete missions: {}\".format(total_time)) logger.info(\"horizon =", "node_dependencies_list = list(ADG_reverse.neighbors(robot.current_node)) all_dependencies_completed = True for dependency in node_dependencies_list:", "= 1.4 # sub-optimality bound: w = 1.0 -> CBS,", "# show factory map # show_factory_map(map_file, robot_file, True) # plt.show()", "pwd = os.path.dirname(os.path.abspath(__file__)) logger.info(pwd) map_file = pwd + \"/data/\" +", "{}\".format(robot.robot_ID, node_info.ID, node_info.s_loc, robot.status)) # solve MILP for the advanced", "optimal\") # ADG after MILP if show_ADG: # draw_ADG(ADG, robots,", "{} # {} @ {} => status: {}\".format(robot.robot_ID, node_info.ID, node_info.s_loc,", "robots: node_info = ADG.node[robot.current_node][\"data\"] logger.debug(\" - Robot {} # {}", "= map_gen_seedval simulation_results[\"results\"] = {} simulation_results[\"results\"][\"comp time\"] = {} simulation_results[\"results\"][\"comp", "m_opt.clear() # show current robot status logger.info(\"-------------------- @ time step", "5 delayed_robot_cnt = 2 w = 1.4 # sub-optimality bound:", "ADG, reverse ADG and dependency groups ADG, robot_plan, goal_positions =", "Model('MILP_sequence', solver='CBC') # print(m_opt.max_nodes) pl_opt = ProgressLog() # pl_opt.settings =", "mip import Model, ProgressLog, xsum, maximize, minimize, BINARY, CONTINUOUS, Constr,", "artist='Matplotlib', comment='Movie support!') writer = FFMpegWriter(fps=2, metadata=metadata) with writer.saving(ADG_fig, \"ADG_video.mp4\",", "# auto_gen_01_nuernberg | auto_gen_00_large | auto_gen_02_simple | manual_03_maxplus random.seed(random_seed) np.random.seed(random_seed)", "m_opt = Model('MILP_sequence', solver='CBC') # print(m_opt.max_nodes) pl_opt = ProgressLog() #", "milp_formulation import * from robot import * from adg import", "if possible (dependencies have been met) for robot in robots:", "> 1.0, run_CBS uses ECBS! logger.info(\" with sub-optimality w={}\".format(w)) logger.info(\"", "matplotlib.colors as mcolors import matplotlib import matplotlib.pyplot as plt import", "inputs given, ignoring ...\") # determine ADG, reverse ADG and", "np.arange(map_gen_robot_count) robot_IDs_to_delay = np.random.choice(map_gen_robot_count, size=delayed_robot_cnt, replace=False) logger.info(\"delaying robots (ID): {}\".format(robot_IDs_to_delay))", "next node node_info = ADG.node[robot.current_node][\"data\"] node_dependencies_list = list(ADG_reverse.neighbors(robot.current_node)) all_dependencies_completed =", "control horizons: H_prediction >= H_control H_prediction = np.NaN # integer", "robot_file_tmp = pwd + \"/data/tmp/robots.yaml\" start_time = time.time() plans =", "prediction and control horizons: H_prediction >= H_control H_prediction = np.NaN", "(res is None or res == \"OptimizationStatus.OPTIMAL\"): ValueError(\"Optimization NOT optimal\")", "= False # if all dependencies are completed, the robot", "robot_plan[robot_id] logger.debug(\"Robot {} - plan: {} \\t \\t positions: {}\".format(robot_id,", "in time_to_goal.items(): total_time += t logger.info(\"Total time to complete missions:", "simulation_results[\"map details\"][\"robot_count\"] = map_gen_robot_count simulation_results[\"map details\"][\"seed val\"] = map_gen_seedval simulation_results[\"results\"]", "\"_robustparam_\" + str(robust_param) + \".yaml\" if save_file: save_to_yaml(simulation_results, file_name) if", "delay_amount) == 0: robot_IDs = np.arange(map_gen_robot_count) robot_IDs_to_delay = np.random.choice(map_gen_robot_count, size=delayed_robot_cnt,", "a cycle => deadlock! something is wrong with optimization\") except", "logger = logging.getLogger(__name__) logging.basicConfig(format='%(name)s - %(levelname)s :: %(message)s', level=logging.INFO) def", "> 20)): # or (robot.robot_ID == 3 or k >", "= {} simulation_results[\"parameters\"] = {} simulation_results[\"parameters\"][\"H_control\"] = H_control simulation_results[\"parameters\"][\"random seed\"]", "sub-optimality bound: w = 1.0 -> CBS, else ECBS! fldr", "= Robot(robot_id, plan, colors[robot_id], goal_positions[robot_id]) robots.append(new_robot) robots_done.append(False) time_to_goal[robot_id] = 0", "{}\".format(H_control)) logger.info(\"\") logger.info(\"Computation time:\") logger.info(\" - max: {}\".format(max(solve_time))) logger.info(\" -", "main(): \"\"\" --------------------------- INPUTS --------------------------------- \"\"\" show_visual = False show_ADG", "+ \"_horizon_\" + str(H_control) + \"_mapseed_\" + str(map_gen_seedval) + \"_robustparam_\"", "positions: {}\".format(robot_id, plan[\"nodes\"], plan[\"positions\"])) new_robot = Robot(robot_id, plan, colors[robot_id], goal_positions[robot_id])", "CONTINUOUS, Constr, ConstrList sys.path.insert(1, \"functions/\") from planners import * from", "show_visual: visualizer = Visualizer(map_file, robots) # initialize optimization MIP object", "a simulation in time k = 0 robot_IDs_to_delay = []", "pwd + \"/results/robust_\" +str(delayed_robot_cnt) + \"x\" + str(delay_amount) + \"/res_robots_\"", "pwd + \"/data/\" + fldr + \"/csv_robots_yaml.yaml\" robot_file_tmp = pwd", "if not (res is None or res == \"OptimizationStatus.OPTIMAL\"): ValueError(\"Optimization", "t in time_to_goal.items(): total_time += t logger.info(\"Total time to complete", "solve_time.append(solve_t) if not (res is None or res == \"OptimizationStatus.OPTIMAL\"):", "* from milp_formulation import * from robot import * from", "= FFMpegWriter(fps=2, metadata=metadata) with writer.saving(ADG_fig, \"ADG_video.mp4\", 500): # run a", "# or (k < 10 or k > 20)): #", "to potentially adjust ordering res, solve_t = solve_MILP(robots, dependency_groups, ADG,", "file simulation_results = {} simulation_results[\"parameters\"] = {} simulation_results[\"parameters\"][\"H_control\"] = H_control", "auto_gen_02_simple | manual_03_maxplus random.seed(random_seed) np.random.seed(random_seed) \"\"\" -------------------------------------------------------------------- \"\"\" # start", "+ \"/csv_map_yaml.yaml\" robot_file = pwd + \"/data/\" + fldr +", "node node_info = ADG.node[robot.current_node][\"data\"] node_dependencies_list = list(ADG_reverse.neighbors(robot.current_node)) all_dependencies_completed = True", "in time k = 0 robot_IDs_to_delay = [] while (not", "map_gen_robot_count = int(sys.argv[1]) map_gen_seedval = int(sys.argv[2]) H_control = int(sys.argv[3]) robust_param", "< 10 or k > 20)): # or (robot.robot_ID ==", "optimization MIP object m_opt m_opt = Model('MILP_sequence', solver='CBC') # print(m_opt.max_nodes)", "potentially adjust ordering res, solve_t = solve_MILP(robots, dependency_groups, ADG, ADG_reverse,", "no deadlock. good!\") pass if (k % delay_amount) == 0:", "+ fldr + \"/csv_map_yaml.yaml\" robot_file = pwd + \"/data/\" +", "robot_IDs_to_delay = [] while (not all(robots_done)) and (k < sim_timeout):", "given, ignoring ...\") # determine ADG, reverse ADG and dependency", "check for cycles try: nx.find_cycle(ADG, orientation=\"original\") logger.warning(\"Cycle detected!!\") raise Exception(\"ADG", "run_MILP = True #False #True save_file = False sim_timeout =", "== \"OptimizationStatus.OPTIMAL\"): ValueError(\"Optimization NOT optimal\") # ADG after MILP if", "from planners import * from visualizers import * from milp_formulation", "seed\"] = random_seed simulation_results[\"parameters\"][\"ECBS w\"] = w simulation_results[\"parameters\"][\"mu\"] = mu", "robot_IDs_to_delay)): # or (k < 10 or k > 20)):", "no valid inputs given, ignoring ...\") # determine ADG, reverse", "1 # end of while loop total_time = 0 for", "all_dependencies_completed = False # if all dependencies are completed, the", "ADG after MILP if show_ADG: # draw_ADG(ADG, robots, \"ADG after", "show_ADG = True #not show_visual run_MILP = True #False #True", "= plt.figure(figsize=(12,8)) plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) metadata =", "+ \"_robustparam_\" + str(robust_param) + \".yaml\" if save_file: save_to_yaml(simulation_results, file_name)", "time_to_goal[robot_id] = 0 if show_visual: visualizer = Visualizer(map_file, robots) #", "been met) for robot in robots: # check if all", "ECBS! fldr = \"nuernberg_small\" # auto_gen_01_nuernberg | auto_gen_00_large | auto_gen_02_simple", "# if all dependencies are completed, the robot can advance!", "{} \\t \\t positions: {}\".format(robot_id, plan[\"nodes\"], plan[\"positions\"])) new_robot = Robot(robot_id,", "=> no deadlock. good!\") pass if (k % delay_amount) ==", "dependency_groups = analyze_ADG(ADG, plans, show_graph=False) ADG_reverse = ADG.reverse(copy=False) # initialize", "total_time = 0 for idx, t in time_to_goal.items(): total_time +=", "in robots: node_info = ADG.node[robot.current_node][\"data\"] logger.debug(\" - Robot {} #", "(not (robot.robot_ID in robot_IDs_to_delay)): # or (k < 10 or", "(robot.robot_ID == 2 or k > 5) if (not (robot.robot_ID", "+ fldr + \"/csv_robots_yaml.yaml\" robot_file_tmp = pwd + \"/data/tmp/robots.yaml\" start_time", "logger.info(\" with sub-optimality w={}\".format(w)) logger.info(\" plan statistics: {} \\n\".format(plans[\"statistics\"])) logger.debug(plans[\"schedule\"])", "pwd + \"/data/tmp/robots.yaml\" start_time = time.time() plans = run_CBS(map_file, robot_file,", "planners import * from visualizers import * from milp_formulation import", "ADG, robot_plan, goal_positions = determine_ADG(plans, show_graph=False) nodes_all, edges_type_1, dependency_groups =", "map_gen_robot_count = 10 map_gen_seedval = \"NaN\" try: map_gen_robot_count = int(sys.argv[1])", "H_control = 5 random_seed = 0 mu = 0.5 robust_param", "ADG | k = {}\".format(k), writer=writer) # plt.show() # check", "\"/data/\" + fldr + \"/csv_robots_yaml.yaml\" robot_file_tmp = pwd + \"/data/tmp/robots.yaml\"", "optimization\") except nx.NetworkXNoCycle: logger.debug(\"no cycle detected in ADG => no", "total_time += t logger.info(\"Total time to complete missions: {}\".format(total_time)) logger.info(\"horizon", "\\t \\t positions: {}\".format(robot_id, plan[\"nodes\"], plan[\"positions\"])) new_robot = Robot(robot_id, plan,", "else ECBS! fldr = \"nuernberg_small\" # auto_gen_01_nuernberg | auto_gen_00_large |", "map_gen_seedval = int(sys.argv[2]) H_control = int(sys.argv[3]) robust_param = int(sys.argv[4]) random.seed(map_gen_seedval)", "{} - plan: {} \\t \\t positions: {}\".format(robot_id, plan[\"nodes\"], plan[\"positions\"]))", "= determine_ADG(plans, show_graph=False) nodes_all, edges_type_1, dependency_groups = analyze_ADG(ADG, plans, show_graph=False)", "plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) metadata = dict(title='Movie Test',", "run a simulation in time k = 0 robot_IDs_to_delay =", "--------------------\".format(k)) for robot in robots: node_info = ADG.node[robot.current_node][\"data\"] logger.debug(\" -", "if (ADG.node[dependency][\"data\"].status != Status.FINISHED): all_dependencies_completed = False # if all", "simulation_results[\"map details\"][\"seed val\"] = map_gen_seedval simulation_results[\"results\"] = {} simulation_results[\"results\"][\"comp time\"]", "m_opt, pl_opt, run=run_MILP, uncertainty_bound=robust_param) solve_time.append(solve_t) if not (res is None", "simulation_results[\"results\"][\"total time\"] = total_time logger.info(simulation_results) file_name = pwd + \"/results/robust_\"", "Status.FINISHED): all_dependencies_completed = False # if all dependencies are completed,", "+ \"/data/\" + fldr + \"/csv_map_yaml.yaml\" robot_file = pwd +", "ConstrList sys.path.insert(1, \"functions/\") from planners import * from visualizers import", "import * from adg import * from adg_node import *", "{} simulation_results[\"results\"][\"comp time\"] = {} simulation_results[\"results\"][\"comp time\"][\"solve_time\"] = [solve_time] simulation_results[\"results\"][\"comp", "2 w = 1.4 # sub-optimality bound: w = 1.0", "ADG.node[robot.current_node][\"data\"] node_dependencies_list = list(ADG_reverse.neighbors(robot.current_node)) all_dependencies_completed = True for dependency in", "= {}\".format(H_control)) logger.info(\"\") logger.info(\"Computation time:\") logger.info(\" - max: {}\".format(max(solve_time))) logger.info(\"", "= Status.FINISHED robot.advance() if not robot.is_done(): time_to_goal[robot.robot_ID] += 1 else:", "0: # (robot.robot_ID == 2 or k > 5) if", "wrong with optimization\") except nx.NetworkXNoCycle: logger.debug(\"no cycle detected in ADG", "= \"nuernberg_small\" # auto_gen_01_nuernberg | auto_gen_00_large | auto_gen_02_simple | manual_03_maxplus", "status logger.info(\"-------------------- @ time step k = {} --------------------\".format(k)) for", "start_time = time.time() plans = run_CBS(map_file, robot_file, w=w) # if", "500): # run a simulation in time k = 0", "time_to_goal.items(): total_time += t logger.info(\"Total time to complete missions: {}\".format(total_time))", "map # show_factory_map(map_file, robot_file, True) # plt.show() map_gen_robot_count = 10", "support!') writer = FFMpegWriter(fps=2, metadata=metadata) with writer.saving(ADG_fig, \"ADG_video.mp4\", 500): #", "raise Exception(\"ADG has a cycle => deadlock! something is wrong", "# plt.show() map_gen_robot_count = 10 map_gen_seedval = \"NaN\" try: map_gen_robot_count", "# plt.show() # check for cycles try: nx.find_cycle(ADG, orientation=\"original\") logger.warning(\"Cycle", "= [] robots_done = [] time_to_goal = {} colors =", "run=run_MILP, uncertainty_bound=robust_param) solve_time.append(solve_t) if not (res is None or res", "map_gen_seedval simulation_results[\"results\"] = {} simulation_results[\"results\"][\"comp time\"] = {} simulation_results[\"results\"][\"comp time\"][\"solve_time\"]", "print(\"pl_opt.settings: {}\".format(pl_opt.settings)) # print(\"pl_opt.log: {}\".format(pl_opt.log)) # pl_opt.instance = m_opt.name #", "= 0 for idx, t in time_to_goal.items(): total_time += t", "robot_file, True) # plt.show() map_gen_robot_count = 10 map_gen_seedval = \"NaN\"", "\"/csv_map_yaml.yaml\" robot_file = pwd + \"/data/\" + fldr + \"/csv_robots_yaml.yaml\"", "k = {}\".format(k), writer=writer) # plt.show() # check for cycles", "cycle detected in ADG => no deadlock. good!\") pass if", "logger.debug(plans[\"schedule\"]) # show factory map # show_factory_map(map_file, robot_file, True) #", "...\") # determine ADG, reverse ADG and dependency groups ADG,", "% delay_amount) == 0: robot_IDs = np.arange(map_gen_robot_count) robot_IDs_to_delay = np.random.choice(map_gen_robot_count,", "True) # plt.show() map_gen_robot_count = 10 map_gen_seedval = \"NaN\" try:", "for the advanced ADG to potentially adjust ordering res, solve_t", "{}\".format(robot_id, plan[\"nodes\"], plan[\"positions\"])) new_robot = Robot(robot_id, plan, colors[robot_id], goal_positions[robot_id]) robots.append(new_robot)", "simulation_results[\"results\"] = {} simulation_results[\"results\"][\"comp time\"] = {} simulation_results[\"results\"][\"comp time\"][\"solve_time\"] =", "= dict(title='Movie Test', artist='Matplotlib', comment='Movie support!') writer = FFMpegWriter(fps=2, metadata=metadata)", "list(ADG_reverse.neighbors(robot.current_node)) all_dependencies_completed = True for dependency in node_dependencies_list: if (ADG.node[dependency][\"data\"].status", "\"/data/tmp/robots.yaml\" start_time = time.time() plans = run_CBS(map_file, robot_file, w=w) #", "(ADG.node[dependency][\"data\"].status != Status.FINISHED): all_dependencies_completed = False # if all dependencies", "{} @ {} => status: {}\".format(robot.robot_ID, node_info.ID, node_info.s_loc, robot.status)) #", "CBS, else ECBS! fldr = \"nuernberg_small\" # auto_gen_01_nuernberg | auto_gen_00_large", "and k > 0: # (robot.robot_ID == 2 or k", "True #False #True save_file = False sim_timeout = 500 #", "{} \\n\".format(plans[\"statistics\"])) logger.debug(plans[\"schedule\"]) # show factory map # show_factory_map(map_file, robot_file,", "= total_time logger.info(simulation_results) file_name = pwd + \"/results/robust_\" +str(delayed_robot_cnt) +", "logger.info(\" - avg: {}\".format(stat.mean(solve_time))) # create data to save to", "np.random.seed(map_gen_seedval) # map_gen_seedval except: print(\" no valid inputs given, ignoring", "k > 20)): # or (robot.robot_ID == 3 or k", "colors[robot_id], goal_positions[robot_id]) robots.append(new_robot) robots_done.append(False) time_to_goal[robot_id] = 0 if show_visual: visualizer", "ADG => no deadlock. good!\") pass if (k % delay_amount)", "advance to next node node_info = ADG.node[robot.current_node][\"data\"] node_dependencies_list = list(ADG_reverse.neighbors(robot.current_node))", "sim_timeout): print(\"pl_opt.log: {}\".format(pl_opt.log)) m_opt.clear() # show current robot status logger.info(\"--------------------", "object m_opt m_opt = Model('MILP_sequence', solver='CBC') # print(m_opt.max_nodes) pl_opt =", "# print(\"pl_opt.log: {}\".format(pl_opt.log)) # pl_opt.instance = m_opt.name # print(\"pl_opt.instance: {}\".format(pl_opt.instance))", "if w > 1.0, run_CBS uses ECBS! logger.info(\" with sub-optimality", "= ADG.node[robot.current_node][\"data\"] node_dependencies_list = list(ADG_reverse.neighbors(robot.current_node)) all_dependencies_completed = True for dependency", "import Model, ProgressLog, xsum, maximize, minimize, BINARY, CONTINUOUS, Constr, ConstrList", "Test', artist='Matplotlib', comment='Movie support!') writer = FFMpegWriter(fps=2, metadata=metadata) with writer.saving(ADG_fig,", "ordering res, solve_t = solve_MILP(robots, dependency_groups, ADG, ADG_reverse, H_control, H_prediction,", "= logging.getLogger(__name__) logging.basicConfig(format='%(name)s - %(levelname)s :: %(message)s', level=logging.INFO) def main():", "--------------------------------- \"\"\" show_visual = False show_ADG = True #not show_visual", "{}\".format(k), writer=writer) # plt.show() # check for cycles try: nx.find_cycle(ADG,", "end of while loop total_time = 0 for idx, t", "MILP ADG | k = {}\".format(k), writer=writer) # plt.show() #", "pwd + \"/data/\" + fldr + \"/csv_map_yaml.yaml\" robot_file = pwd", "YAML file simulation_results = {} simulation_results[\"parameters\"] = {} simulation_results[\"parameters\"][\"H_control\"] =", "0 k += 1 # end of while loop total_time", "k > 5) if (not (robot.robot_ID in robot_IDs_to_delay)): # or", "+ \"x\" + str(delay_amount) + \"/res_robots_\" + str(map_gen_robot_count) + \"_horizon_\"", "= pwd + \"/data/tmp/robots.yaml\" start_time = time.time() plans = run_CBS(map_file,", "to complete missions: {}\".format(total_time)) logger.info(\"horizon = {}\".format(H_control)) logger.info(\"\") logger.info(\"Computation time:\")", "time import networkx as nx import csv import statistics as", "\"NaN\" try: map_gen_robot_count = int(sys.argv[1]) map_gen_seedval = int(sys.argv[2]) H_control =", "1.0 -> CBS, else ECBS! fldr = \"nuernberg_small\" # auto_gen_01_nuernberg", "w={}\".format(w)) logger.info(\" plan statistics: {} \\n\".format(plans[\"statistics\"])) logger.debug(plans[\"schedule\"]) # show factory", "simulation robots = [] solve_time = [] robots_done = []", "return 0 k += 1 # end of while loop", "= 0.0 delay_amount = 5 delayed_robot_cnt = 2 w =", "visualizer = Visualizer(map_file, robots) # initialize optimization MIP object m_opt", "= pwd + \"/data/\" + fldr + \"/csv_map_yaml.yaml\" robot_file =", "\"/res_robots_\" + str(map_gen_robot_count) + \"_horizon_\" + str(H_control) + \"_mapseed_\" +", "map_file = pwd + \"/data/\" + fldr + \"/csv_map_yaml.yaml\" robot_file", "\"functions/\") from planners import * from visualizers import * from", "simulation_results[\"results\"][\"comp time\"][\"avg\"] = stat.mean(solve_time) simulation_results[\"results\"][\"total time\"] = total_time logger.info(simulation_results) file_name", "def main(): \"\"\" --------------------------- INPUTS --------------------------------- \"\"\" show_visual = False", "or k > 8): ADG.node[robot.current_node][\"data\"].status = Status.FINISHED robot.advance() if not", "= delay_amount simulation_results[\"map details\"] = {} simulation_results[\"map details\"][\"robot_count\"] = map_gen_robot_count", "# delay_amount = np.random.poisson(mu) # same sample every time if", "import csv import statistics as stat import os import sys", "status: {}\".format(robot.robot_ID, node_info.ID, node_info.s_loc, robot.status)) # solve MILP for the", "cycles try: nx.find_cycle(ADG, orientation=\"original\") logger.warning(\"Cycle detected!!\") raise Exception(\"ADG has a", "sample every time if all_dependencies_completed and k > 0: #", "simulation_results[\"parameters\"][\"delay amount\"] = delay_amount simulation_results[\"map details\"] = {} simulation_results[\"map details\"][\"robot_count\"]", "= 0 mu = 0.5 robust_param = 0.0 delay_amount =", "if (not (robot.robot_ID in robot_IDs_to_delay)): # or (k < 10", "groups ADG, robot_plan, goal_positions = determine_ADG(plans, show_graph=False) nodes_all, edges_type_1, dependency_groups", "logger.info(simulation_results) file_name = pwd + \"/results/robust_\" +str(delayed_robot_cnt) + \"x\" +", "w\"] = w simulation_results[\"parameters\"][\"mu\"] = mu simulation_results[\"parameters\"][\"robust param\"] = robust_param", "to determine optimal ordering defined by ADG \"\"\" import sys", "robots) # initialize optimization MIP object m_opt m_opt = Model('MILP_sequence',", "\"nuernberg_small\" # auto_gen_01_nuernberg | auto_gen_00_large | auto_gen_02_simple | manual_03_maxplus random.seed(random_seed)", "to save to YAML file simulation_results = {} simulation_results[\"parameters\"] =", "0: robot_IDs = np.arange(map_gen_robot_count) robot_IDs_to_delay = np.random.choice(map_gen_robot_count, size=delayed_robot_cnt, replace=False) logger.info(\"delaying", "= 500 # define prediction and control horizons: H_prediction >=", "complete missions: {}\".format(total_time)) logger.info(\"horizon = {}\".format(H_control)) logger.info(\"\") logger.info(\"Computation time:\") logger.info(\"", "if all dependencies are completed, the robot can advance! #", "show_visual = False show_ADG = True #not show_visual run_MILP =", "in robots: # check if all dependencies have been met,", "= int(sys.argv[1]) map_gen_seedval = int(sys.argv[2]) H_control = int(sys.argv[3]) robust_param =", "# return 0 k += 1 # end of while", "plan: {} \\t \\t positions: {}\".format(robot_id, plan[\"nodes\"], plan[\"positions\"])) new_robot =", "np.random.poisson(mu) # same sample every time if all_dependencies_completed and k", "* logger = logging.getLogger(__name__) logging.basicConfig(format='%(name)s - %(levelname)s :: %(message)s', level=logging.INFO)", "plt.figure(figsize=(12,8)) plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) metadata = dict(title='Movie", "show current robot status logger.info(\"-------------------- @ time step k =", "= w simulation_results[\"parameters\"][\"mu\"] = mu simulation_results[\"parameters\"][\"robust param\"] = robust_param simulation_results[\"parameters\"][\"delay", "H_control simulation_results[\"parameters\"][\"random seed\"] = random_seed simulation_results[\"parameters\"][\"ECBS w\"] = w simulation_results[\"parameters\"][\"mu\"]", "\"\"\" # start initial pwd = os.path.dirname(os.path.abspath(__file__)) logger.info(pwd) map_file =", "solve_time = [] robots_done = [] time_to_goal = {} colors", "auto_gen_00_large | auto_gen_02_simple | manual_03_maxplus random.seed(random_seed) np.random.seed(random_seed) \"\"\" -------------------------------------------------------------------- \"\"\"", "robot_plan, goal_positions = determine_ADG(plans, show_graph=False) nodes_all, edges_type_1, dependency_groups = analyze_ADG(ADG,", "+ str(map_gen_robot_count) + \"_horizon_\" + str(H_control) + \"_mapseed_\" + str(map_gen_seedval)", "# {} @ {} => status: {}\".format(robot.robot_ID, node_info.ID, node_info.s_loc, robot.status))", "= False show_ADG = True #not show_visual run_MILP = True", "\".yaml\" if save_file: save_to_yaml(simulation_results, file_name) if __name__ == \"__main__\": main()", "print(\"pl_opt.instance: {}\".format(pl_opt.instance)) ADG_fig = plt.figure(figsize=(12,8)) plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0,", "size=delayed_robot_cnt, replace=False) logger.info(\"delaying robots (ID): {}\".format(robot_IDs_to_delay)) # Advance robots if", "simulation_results[\"parameters\"][\"ECBS w\"] = w simulation_results[\"parameters\"][\"mu\"] = mu simulation_results[\"parameters\"][\"robust param\"] =", "matplotlib import matplotlib.pyplot as plt import random import logging import", "0 if show_visual: visualizer = Visualizer(map_file, robots) # initialize optimization", "mu = 0.5 robust_param = 0.0 delay_amount = 5 delayed_robot_cnt", "robot_file, w=w) # if w > 1.0, run_CBS uses ECBS!", "k > 0: # (robot.robot_ID == 2 or k >", "are completed, the robot can advance! # delay_amount = np.random.poisson(mu)", "= max(solve_time) simulation_results[\"results\"][\"comp time\"][\"avg\"] = stat.mean(solve_time) simulation_results[\"results\"][\"total time\"] = total_time", "mcolors import matplotlib import matplotlib.pyplot as plt import random import", "Exception(\"ADG has a cycle => deadlock! something is wrong with", "(robot.robot_ID in robot_IDs_to_delay)): # or (k < 10 or k", "statistics as stat import os import sys from mip import", "+= 1 else: robots_done[robot.robot_ID] = True if show_visual: visualizer.redraw(robots, pause_length=0.1)", "# ADG after MILP if show_ADG: # draw_ADG(ADG, robots, \"ADG", "plans, show_graph=False) ADG_reverse = ADG.reverse(copy=False) # initialize simulation robots =", "new_robot = Robot(robot_id, plan, colors[robot_id], goal_positions[robot_id]) robots.append(new_robot) robots_done.append(False) time_to_goal[robot_id] =", "minimize, BINARY, CONTINUOUS, Constr, ConstrList sys.path.insert(1, \"functions/\") from planners import", "the robot can advance! # delay_amount = np.random.poisson(mu) # same", "writer = FFMpegWriter(fps=2, metadata=metadata) with writer.saving(ADG_fig, \"ADG_video.mp4\", 500): # run", "res == \"OptimizationStatus.OPTIMAL\"): ValueError(\"Optimization NOT optimal\") # ADG after MILP", "run_CBS uses ECBS! logger.info(\" with sub-optimality w={}\".format(w)) logger.info(\" plan statistics:", "# pl_opt.settings = \"objective_value\" # print(\"pl_opt.settings: {}\".format(pl_opt.settings)) # print(\"pl_opt.log: {}\".format(pl_opt.log))", "\"_mapseed_\" + str(map_gen_seedval) + \"_robustparam_\" + str(robust_param) + \".yaml\" if", "robots = [] solve_time = [] robots_done = [] time_to_goal", "robot_IDs = np.arange(map_gen_robot_count) robot_IDs_to_delay = np.random.choice(map_gen_robot_count, size=delayed_robot_cnt, replace=False) logger.info(\"delaying robots", "metadata = dict(title='Movie Test', artist='Matplotlib', comment='Movie support!') writer = FFMpegWriter(fps=2,", "H_prediction = np.NaN # integer value for forward node lookup", "robots if possible (dependencies have been met) for robot in", "solver='CBC') # print(m_opt.max_nodes) pl_opt = ProgressLog() # pl_opt.settings = \"objective_value\"", "nx.find_cycle(ADG, orientation=\"original\") logger.warning(\"Cycle detected!!\") raise Exception(\"ADG has a cycle =>", "plans = run_CBS(map_file, robot_file, w=w) # if w > 1.0,", "str(map_gen_robot_count) + \"_horizon_\" + str(H_control) + \"_mapseed_\" + str(map_gen_seedval) +", "pl_opt.settings = \"objective_value\" # print(\"pl_opt.settings: {}\".format(pl_opt.settings)) # print(\"pl_opt.log: {}\".format(pl_opt.log)) #", "fldr + \"/csv_robots_yaml.yaml\" robot_file_tmp = pwd + \"/data/tmp/robots.yaml\" start_time =", "np.random.seed(random_seed) \"\"\" -------------------------------------------------------------------- \"\"\" # start initial pwd = os.path.dirname(os.path.abspath(__file__))", "valid inputs given, ignoring ...\") # determine ADG, reverse ADG", "H_prediction >= H_control H_prediction = np.NaN # integer value for", "= {} simulation_results[\"map details\"][\"robot_count\"] = map_gen_robot_count simulation_results[\"map details\"][\"seed val\"] =", "fldr + \"/csv_map_yaml.yaml\" robot_file = pwd + \"/data/\" + fldr", "mu simulation_results[\"parameters\"][\"robust param\"] = robust_param simulation_results[\"parameters\"][\"delay amount\"] = delay_amount simulation_results[\"map", "robot_file = pwd + \"/data/\" + fldr + \"/csv_robots_yaml.yaml\" robot_file_tmp", "logging.basicConfig(format='%(name)s - %(levelname)s :: %(message)s', level=logging.INFO) def main(): \"\"\" ---------------------------", "all(robots_done)) and (k < sim_timeout): print(\"pl_opt.log: {}\".format(pl_opt.log)) m_opt.clear() # show", "= [] time_to_goal = {} colors = plt.cm.rainbow( np.arange(len(robot_plan))/len(robot_plan) )", "= ProgressLog() # pl_opt.settings = \"objective_value\" # print(\"pl_opt.settings: {}\".format(pl_opt.settings)) #", "with writer.saving(ADG_fig, \"ADG_video.mp4\", 500): # run a simulation in time", "reverse ADG and dependency groups ADG, robot_plan, goal_positions = determine_ADG(plans,", "something is wrong with optimization\") except nx.NetworkXNoCycle: logger.debug(\"no cycle detected", "> 0: # (robot.robot_ID == 2 or k > 5)", "np.arange(len(robot_plan))/len(robot_plan) ) for robot_id in robot_plan: plan = robot_plan[robot_id] logger.debug(\"Robot", "5 random_seed = 0 mu = 0.5 robust_param = 0.0", "with sub-optimality w={}\".format(w)) logger.info(\" plan statistics: {} \\n\".format(plans[\"statistics\"])) logger.debug(plans[\"schedule\"]) #", "factory map # show_factory_map(map_file, robot_file, True) # plt.show() map_gen_robot_count =", "time\"][\"max\"] = max(solve_time) simulation_results[\"results\"][\"comp time\"][\"avg\"] = stat.mean(solve_time) simulation_results[\"results\"][\"total time\"] =", "INPUTS --------------------------------- \"\"\" show_visual = False show_ADG = True #not", "import * logger = logging.getLogger(__name__) logging.basicConfig(format='%(name)s - %(levelname)s :: %(message)s',", "ADG.reverse(copy=False) # initialize simulation robots = [] solve_time = []", "NOT optimal\") # ADG after MILP if show_ADG: # draw_ADG(ADG,", "| auto_gen_00_large | auto_gen_02_simple | manual_03_maxplus random.seed(random_seed) np.random.seed(random_seed) \"\"\" --------------------------------------------------------------------", "check if all dependencies have been met, to advance to", "str(delay_amount) + \"/res_robots_\" + str(map_gen_robot_count) + \"_horizon_\" + str(H_control) +", "ProgressLog() # pl_opt.settings = \"objective_value\" # print(\"pl_opt.settings: {}\".format(pl_opt.settings)) # print(\"pl_opt.log:", "every time if all_dependencies_completed and k > 0: # (robot.robot_ID", "int(sys.argv[1]) map_gen_seedval = int(sys.argv[2]) H_control = int(sys.argv[3]) robust_param = int(sys.argv[4])", "determine_ADG(plans, show_graph=False) nodes_all, edges_type_1, dependency_groups = analyze_ADG(ADG, plans, show_graph=False) ADG_reverse", "= Visualizer(map_file, robots) # initialize optimization MIP object m_opt m_opt", "= 0 robot_IDs_to_delay = [] while (not all(robots_done)) and (k", "delay_amount = np.random.poisson(mu) # same sample every time if all_dependencies_completed", "# show_factory_map(map_file, robot_file, True) # plt.show() map_gen_robot_count = 10 map_gen_seedval", "plan = robot_plan[robot_id] logger.debug(\"Robot {} - plan: {} \\t \\t", "0 robot_IDs_to_delay = [] while (not all(robots_done)) and (k <", "show factory map # show_factory_map(map_file, robot_file, True) # plt.show() map_gen_robot_count", "plan[\"positions\"])) new_robot = Robot(robot_id, plan, colors[robot_id], goal_positions[robot_id]) robots.append(new_robot) robots_done.append(False) time_to_goal[robot_id]", "from process_results import * logger = logging.getLogger(__name__) logging.basicConfig(format='%(name)s - %(levelname)s", "same sample every time if all_dependencies_completed and k > 0:", "to next node node_info = ADG.node[robot.current_node][\"data\"] node_dependencies_list = list(ADG_reverse.neighbors(robot.current_node)) all_dependencies_completed", "random import logging import time import networkx as nx import", "bound: w = 1.0 -> CBS, else ECBS! fldr =", "= 10 map_gen_seedval = \"NaN\" try: map_gen_robot_count = int(sys.argv[1]) map_gen_seedval", "import sys import yaml import time import matplotlib.colors as mcolors", "\"\"\" -------------------------------------------------------------------- \"\"\" # start initial pwd = os.path.dirname(os.path.abspath(__file__)) logger.info(pwd)", "int(sys.argv[2]) H_control = int(sys.argv[3]) robust_param = int(sys.argv[4]) random.seed(map_gen_seedval) # map_gen_seedval", "[] robots_done = [] time_to_goal = {} colors = plt.cm.rainbow(", "# print(m_opt.max_nodes) pl_opt = ProgressLog() # pl_opt.settings = \"objective_value\" #", "pl_opt.instance = m_opt.name # print(\"pl_opt.instance: {}\".format(pl_opt.instance)) ADG_fig = plt.figure(figsize=(12,8)) plt.subplots_adjust(left=0,", "ECBS! logger.info(\" with sub-optimality w={}\".format(w)) logger.info(\" plan statistics: {} \\n\".format(plans[\"statistics\"]))", "H_control, H_prediction, m_opt, pl_opt, run=run_MILP, uncertainty_bound=robust_param) solve_time.append(solve_t) if not (res", "plt import random import logging import time import networkx as", "os.path.dirname(os.path.abspath(__file__)) logger.info(pwd) map_file = pwd + \"/data/\" + fldr +", "ADG_fig = plt.figure(figsize=(12,8)) plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) metadata", "# determine ADG, reverse ADG and dependency groups ADG, robot_plan,", "str(H_control) + \"_mapseed_\" + str(map_gen_seedval) + \"_robustparam_\" + str(robust_param) +", "import matplotlib.colors as mcolors import matplotlib import matplotlib.pyplot as plt", "print(\" no valid inputs given, ignoring ...\") # determine ADG,", "(not all(robots_done)) and (k < sim_timeout): print(\"pl_opt.log: {}\".format(pl_opt.log)) m_opt.clear() #", "start initial pwd = os.path.dirname(os.path.abspath(__file__)) logger.info(pwd) map_file = pwd +", "= False sim_timeout = 500 # define prediction and control", ">= H_control H_prediction = np.NaN # integer value for forward", "colors = plt.cm.rainbow( np.arange(len(robot_plan))/len(robot_plan) ) for robot_id in robot_plan: plan", "w simulation_results[\"parameters\"][\"mu\"] = mu simulation_results[\"parameters\"][\"robust param\"] = robust_param simulation_results[\"parameters\"][\"delay amount\"]", "determine ADG, reverse ADG and dependency groups ADG, robot_plan, goal_positions", "csv import statistics as stat import os import sys from", "import logging import time import networkx as nx import csv", "(k < 10 or k > 20)): # or (robot.robot_ID", "sub-optimality w={}\".format(w)) logger.info(\" plan statistics: {} \\n\".format(plans[\"statistics\"])) logger.debug(plans[\"schedule\"]) # show", "advanced ADG to potentially adjust ordering res, solve_t = solve_MILP(robots,", "visualizer.redraw(robots, pause_length=0.1) # return 0 k += 1 # end", "nx import csv import statistics as stat import os import", "sys from mip import Model, ProgressLog, xsum, maximize, minimize, BINARY,", "ADG and dependency groups ADG, robot_plan, goal_positions = determine_ADG(plans, show_graph=False)", "all dependencies are completed, the robot can advance! # delay_amount", "\"/csv_robots_yaml.yaml\" robot_file_tmp = pwd + \"/data/tmp/robots.yaml\" start_time = time.time() plans", "\"\"\" --------------------------- INPUTS --------------------------------- \"\"\" show_visual = False show_ADG =", "robot.is_done(): time_to_goal[robot.robot_ID] += 1 else: robots_done[robot.robot_ID] = True if show_visual:", "logger.info(\"Total time to complete missions: {}\".format(total_time)) logger.info(\"horizon = {}\".format(H_control)) logger.info(\"\")", "w=w) # if w > 1.0, run_CBS uses ECBS! logger.info(\"", "plan, colors[robot_id], goal_positions[robot_id]) robots.append(new_robot) robots_done.append(False) time_to_goal[robot_id] = 0 if show_visual:", "as stat import os import sys from mip import Model,", "plt.show() # check for cycles try: nx.find_cycle(ADG, orientation=\"original\") logger.warning(\"Cycle detected!!\")", "or k > 20)): # or (robot.robot_ID == 3 or", "robot_IDs_to_delay = np.random.choice(map_gen_robot_count, size=delayed_robot_cnt, replace=False) logger.info(\"delaying robots (ID): {}\".format(robot_IDs_to_delay)) #", "current robot status logger.info(\"-------------------- @ time step k = {}", "- max: {}\".format(max(solve_time))) logger.info(\" - avg: {}\".format(stat.mean(solve_time))) # create data", "try: map_gen_robot_count = int(sys.argv[1]) map_gen_seedval = int(sys.argv[2]) H_control = int(sys.argv[3])", "time import matplotlib.colors as mcolors import matplotlib import matplotlib.pyplot as", "possible (dependencies have been met) for robot in robots: #", "True for dependency in node_dependencies_list: if (ADG.node[dependency][\"data\"].status != Status.FINISHED): all_dependencies_completed", "[] solve_time = [] robots_done = [] time_to_goal = {}", "save_file = False sim_timeout = 500 # define prediction and", "uncertainty_bound=robust_param) solve_time.append(solve_t) if not (res is None or res ==", "in robot_plan: plan = robot_plan[robot_id] logger.debug(\"Robot {} - plan: {}", "MILP solved to determine optimal ordering defined by ADG \"\"\"", "str(map_gen_seedval) + \"_robustparam_\" + str(robust_param) + \".yaml\" if save_file: save_to_yaml(simulation_results,", "m_opt.name # print(\"pl_opt.instance: {}\".format(pl_opt.instance)) ADG_fig = plt.figure(figsize=(12,8)) plt.subplots_adjust(left=0, bottom=0, right=1,", "adg import * from adg_node import * from process_results import", "dependency groups ADG, robot_plan, goal_positions = determine_ADG(plans, show_graph=False) nodes_all, edges_type_1,", "# (robot.robot_ID == 2 or k > 5) if (not", "{} simulation_results[\"parameters\"][\"H_control\"] = H_control simulation_results[\"parameters\"][\"random seed\"] = random_seed simulation_results[\"parameters\"][\"ECBS w\"]", "#True save_file = False sim_timeout = 500 # define prediction", "= 1.0 -> CBS, else ECBS! fldr = \"nuernberg_small\" #", "\"/results/robust_\" +str(delayed_robot_cnt) + \"x\" + str(delay_amount) + \"/res_robots_\" + str(map_gen_robot_count)", "str(robust_param) + \".yaml\" if save_file: save_to_yaml(simulation_results, file_name) if __name__ ==", "ADG \"\"\" import sys import yaml import time import matplotlib.colors", "draw_ADG(ADG, robots, \"ADG after MILP ADG | k = {}\".format(k),", "= pwd + \"/results/robust_\" +str(delayed_robot_cnt) + \"x\" + str(delay_amount) +", "or (robot.robot_ID == 3 or k > 8): ADG.node[robot.current_node][\"data\"].status =", "== 3 or k > 8): ADG.node[robot.current_node][\"data\"].status = Status.FINISHED robot.advance()", "try: nx.find_cycle(ADG, orientation=\"original\") logger.warning(\"Cycle detected!!\") raise Exception(\"ADG has a cycle", "0 mu = 0.5 robust_param = 0.0 delay_amount = 5", "= np.NaN # integer value for forward node lookup H_control", "import random import logging import time import networkx as nx", "from adg import * from adg_node import * from process_results", "1.4 # sub-optimality bound: w = 1.0 -> CBS, else", "dependency_groups, ADG, ADG_reverse, H_control, H_prediction, m_opt, pl_opt, run=run_MILP, uncertainty_bound=robust_param) solve_time.append(solve_t)", "and dependency groups ADG, robot_plan, goal_positions = determine_ADG(plans, show_graph=False) nodes_all,", "= np.random.poisson(mu) # same sample every time if all_dependencies_completed and", "after MILP if show_ADG: # draw_ADG(ADG, robots, \"ADG after MILP", "%(message)s', level=logging.INFO) def main(): \"\"\" --------------------------- INPUTS --------------------------------- \"\"\" show_visual", "except nx.NetworkXNoCycle: logger.debug(\"no cycle detected in ADG => no deadlock.", "| auto_gen_02_simple | manual_03_maxplus random.seed(random_seed) np.random.seed(random_seed) \"\"\" -------------------------------------------------------------------- \"\"\" #", "is wrong with optimization\") except nx.NetworkXNoCycle: logger.debug(\"no cycle detected in", "(robot.robot_ID == 3 or k > 8): ADG.node[robot.current_node][\"data\"].status = Status.FINISHED", "# check if all dependencies have been met, to advance", "= {} colors = plt.cm.rainbow( np.arange(len(robot_plan))/len(robot_plan) ) for robot_id in", "simulation_results[\"results\"][\"comp time\"][\"solve_time\"] = [solve_time] simulation_results[\"results\"][\"comp time\"][\"max\"] = max(solve_time) simulation_results[\"results\"][\"comp time\"][\"avg\"]", "or res == \"OptimizationStatus.OPTIMAL\"): ValueError(\"Optimization NOT optimal\") # ADG after", "in node_dependencies_list: if (ADG.node[dependency][\"data\"].status != Status.FINISHED): all_dependencies_completed = False #", "robot_plan: plan = robot_plan[robot_id] logger.debug(\"Robot {} - plan: {} \\t", "import yaml import time import matplotlib.colors as mcolors import matplotlib", "+ \"/results/robust_\" +str(delayed_robot_cnt) + \"x\" + str(delay_amount) + \"/res_robots_\" +", "avg: {}\".format(stat.mean(solve_time))) # create data to save to YAML file", "nodes_all, edges_type_1, dependency_groups = analyze_ADG(ADG, plans, show_graph=False) ADG_reverse = ADG.reverse(copy=False)", "from robot import * from adg import * from adg_node", "+ str(H_control) + \"_mapseed_\" + str(map_gen_seedval) + \"_robustparam_\" + str(robust_param)", "simulation_results = {} simulation_results[\"parameters\"] = {} simulation_results[\"parameters\"][\"H_control\"] = H_control simulation_results[\"parameters\"][\"random", "met) for robot in robots: # check if all dependencies", "* from visualizers import * from milp_formulation import * from", "H_control H_prediction = np.NaN # integer value for forward node", "the advanced ADG to potentially adjust ordering res, solve_t =", "logger.info(\" plan statistics: {} \\n\".format(plans[\"statistics\"])) logger.debug(plans[\"schedule\"]) # show factory map", "# show current robot status logger.info(\"-------------------- @ time step k", "file_name = pwd + \"/results/robust_\" +str(delayed_robot_cnt) + \"x\" + str(delay_amount)", "for robot in robots: node_info = ADG.node[robot.current_node][\"data\"] logger.debug(\" - Robot", "have been met, to advance to next node node_info =", "ordering defined by ADG \"\"\" import sys import yaml import", "run_CBS(map_file, robot_file, w=w) # if w > 1.0, run_CBS uses", "if show_ADG: # draw_ADG(ADG, robots, \"ADG after MILP ADG |", "detected in ADG => no deadlock. good!\") pass if (k", "have been met) for robot in robots: # check if", "1.0, run_CBS uses ECBS! logger.info(\" with sub-optimality w={}\".format(w)) logger.info(\" plan", "--------------------------- INPUTS --------------------------------- \"\"\" show_visual = False show_ADG = True", "create data to save to YAML file simulation_results = {}", "import matplotlib import matplotlib.pyplot as plt import random import logging", "as nx import csv import statistics as stat import os", "show_graph=False) nodes_all, edges_type_1, dependency_groups = analyze_ADG(ADG, plans, show_graph=False) ADG_reverse =", "Constr, ConstrList sys.path.insert(1, \"functions/\") from planners import * from visualizers", "node_info.ID, node_info.s_loc, robot.status)) # solve MILP for the advanced ADG", "robot can advance! # delay_amount = np.random.poisson(mu) # same sample", "= int(sys.argv[2]) H_control = int(sys.argv[3]) robust_param = int(sys.argv[4]) random.seed(map_gen_seedval) #", "robot in robots: node_info = ADG.node[robot.current_node][\"data\"] logger.debug(\" - Robot {}", "defined by ADG \"\"\" import sys import yaml import time", "all dependencies have been met, to advance to next node", "robots.append(new_robot) robots_done.append(False) time_to_goal[robot_id] = 0 if show_visual: visualizer = Visualizer(map_file,", "MILP for the advanced ADG to potentially adjust ordering res,", "solved to determine optimal ordering defined by ADG \"\"\" import", "#False #True save_file = False sim_timeout = 500 # define", "import * from visualizers import * from milp_formulation import *", "# define prediction and control horizons: H_prediction >= H_control H_prediction", "orientation=\"original\") logger.warning(\"Cycle detected!!\") raise Exception(\"ADG has a cycle => deadlock!", "import networkx as nx import csv import statistics as stat", "random_seed simulation_results[\"parameters\"][\"ECBS w\"] = w simulation_results[\"parameters\"][\"mu\"] = mu simulation_results[\"parameters\"][\"robust param\"]", "0 for idx, t in time_to_goal.items(): total_time += t logger.info(\"Total", "True if show_visual: visualizer.redraw(robots, pause_length=0.1) # return 0 k +=", "[solve_time] simulation_results[\"results\"][\"comp time\"][\"max\"] = max(solve_time) simulation_results[\"results\"][\"comp time\"][\"avg\"] = stat.mean(solve_time) simulation_results[\"results\"][\"total", "w = 1.0 -> CBS, else ECBS! fldr = \"nuernberg_small\"", "\"objective_value\" # print(\"pl_opt.settings: {}\".format(pl_opt.settings)) # print(\"pl_opt.log: {}\".format(pl_opt.log)) # pl_opt.instance =", "node_info.s_loc, robot.status)) # solve MILP for the advanced ADG to", "ValueError(\"Optimization NOT optimal\") # ADG after MILP if show_ADG: #", "solve_t = solve_MILP(robots, dependency_groups, ADG, ADG_reverse, H_control, H_prediction, m_opt, pl_opt,", "has a cycle => deadlock! something is wrong with optimization\")", "networkx as nx import csv import statistics as stat import", "in ADG => no deadlock. good!\") pass if (k %", "by ADG \"\"\" import sys import yaml import time import", "top=1, wspace=0, hspace=0) metadata = dict(title='Movie Test', artist='Matplotlib', comment='Movie support!')", "if not robot.is_done(): time_to_goal[robot.robot_ID] += 1 else: robots_done[robot.robot_ID] = True", "simulation_results[\"parameters\"][\"mu\"] = mu simulation_results[\"parameters\"][\"robust param\"] = robust_param simulation_results[\"parameters\"][\"delay amount\"] =", "robot.advance() if not robot.is_done(): time_to_goal[robot.robot_ID] += 1 else: robots_done[robot.robot_ID] =", "plan[\"nodes\"], plan[\"positions\"])) new_robot = Robot(robot_id, plan, colors[robot_id], goal_positions[robot_id]) robots.append(new_robot) robots_done.append(False)", "yaml import time import matplotlib.colors as mcolors import matplotlib import", "* from adg_node import * from process_results import * logger", "* from adg import * from adg_node import * from", "= 0.5 robust_param = 0.0 delay_amount = 5 delayed_robot_cnt =", "= True #False #True save_file = False sim_timeout = 500", "< sim_timeout): print(\"pl_opt.log: {}\".format(pl_opt.log)) m_opt.clear() # show current robot status", "of while loop total_time = 0 for idx, t in", "max: {}\".format(max(solve_time))) logger.info(\" - avg: {}\".format(stat.mean(solve_time))) # create data to", "robots_done[robot.robot_ID] = True if show_visual: visualizer.redraw(robots, pause_length=0.1) # return 0", "{} colors = plt.cm.rainbow( np.arange(len(robot_plan))/len(robot_plan) ) for robot_id in robot_plan:", "completed, the robot can advance! # delay_amount = np.random.poisson(mu) #", "initial pwd = os.path.dirname(os.path.abspath(__file__)) logger.info(pwd) map_file = pwd + \"/data/\"", "not (res is None or res == \"OptimizationStatus.OPTIMAL\"): ValueError(\"Optimization NOT", "missions: {}\".format(total_time)) logger.info(\"horizon = {}\".format(H_control)) logger.info(\"\") logger.info(\"Computation time:\") logger.info(\" -", "\\t positions: {}\".format(robot_id, plan[\"nodes\"], plan[\"positions\"])) new_robot = Robot(robot_id, plan, colors[robot_id],", "after MILP ADG | k = {}\".format(k), writer=writer) # plt.show()", "= {}\".format(k), writer=writer) # plt.show() # check for cycles try:", "(k % delay_amount) == 0: robot_IDs = np.arange(map_gen_robot_count) robot_IDs_to_delay =", "can advance! # delay_amount = np.random.poisson(mu) # same sample every", "1 else: robots_done[robot.robot_ID] = True if show_visual: visualizer.redraw(robots, pause_length=0.1) #", "show_visual run_MILP = True #False #True save_file = False sim_timeout", "val\"] = map_gen_seedval simulation_results[\"results\"] = {} simulation_results[\"results\"][\"comp time\"] = {}", "= 5 random_seed = 0 mu = 0.5 robust_param =", "met, to advance to next node node_info = ADG.node[robot.current_node][\"data\"] node_dependencies_list", "- Robot {} # {} @ {} => status: {}\".format(robot.robot_ID,", "logger.info(pwd) map_file = pwd + \"/data/\" + fldr + \"/csv_map_yaml.yaml\"", "= np.random.choice(map_gen_robot_count, size=delayed_robot_cnt, replace=False) logger.info(\"delaying robots (ID): {}\".format(robot_IDs_to_delay)) # Advance", "import os import sys from mip import Model, ProgressLog, xsum,", "\"OptimizationStatus.OPTIMAL\"): ValueError(\"Optimization NOT optimal\") # ADG after MILP if show_ADG:", "{}\".format(pl_opt.log)) # pl_opt.instance = m_opt.name # print(\"pl_opt.instance: {}\".format(pl_opt.instance)) ADG_fig =", "for forward node lookup H_control = 5 random_seed = 0", "while (not all(robots_done)) and (k < sim_timeout): print(\"pl_opt.log: {}\".format(pl_opt.log)) m_opt.clear()", "maximize, minimize, BINARY, CONTINUOUS, Constr, ConstrList sys.path.insert(1, \"functions/\") from planners", "= 5 delayed_robot_cnt = 2 w = 1.4 # sub-optimality", "# integer value for forward node lookup H_control = 5", "if all_dependencies_completed and k > 0: # (robot.robot_ID == 2", "= True #not show_visual run_MILP = True #False #True save_file", "is None or res == \"OptimizationStatus.OPTIMAL\"): ValueError(\"Optimization NOT optimal\") #", "= time.time() plans = run_CBS(map_file, robot_file, w=w) # if w", "import * from milp_formulation import * from robot import *", "# sub-optimality bound: w = 1.0 -> CBS, else ECBS!", "writer.saving(ADG_fig, \"ADG_video.mp4\", 500): # run a simulation in time k", "= robust_param simulation_results[\"parameters\"][\"delay amount\"] = delay_amount simulation_results[\"map details\"] = {}", "ADG to potentially adjust ordering res, solve_t = solve_MILP(robots, dependency_groups,", "dict(title='Movie Test', artist='Matplotlib', comment='Movie support!') writer = FFMpegWriter(fps=2, metadata=metadata) with", "10 map_gen_seedval = \"NaN\" try: map_gen_robot_count = int(sys.argv[1]) map_gen_seedval =", "time.time() plans = run_CBS(map_file, robot_file, w=w) # if w >", "time_to_goal = {} colors = plt.cm.rainbow( np.arange(len(robot_plan))/len(robot_plan) ) for robot_id", "for robot in robots: # check if all dependencies have", "logger.info(\" - max: {}\".format(max(solve_time))) logger.info(\" - avg: {}\".format(stat.mean(solve_time))) # create", "while loop total_time = 0 for idx, t in time_to_goal.items():", "robots: # check if all dependencies have been met, to", "from visualizers import * from milp_formulation import * from robot", "False sim_timeout = 500 # define prediction and control horizons:", "time to complete missions: {}\".format(total_time)) logger.info(\"horizon = {}\".format(H_control)) logger.info(\"\") logger.info(\"Computation", "with optimization\") except nx.NetworkXNoCycle: logger.debug(\"no cycle detected in ADG =>", "max(solve_time) simulation_results[\"results\"][\"comp time\"][\"avg\"] = stat.mean(solve_time) simulation_results[\"results\"][\"total time\"] = total_time logger.info(simulation_results)", "total_time logger.info(simulation_results) file_name = pwd + \"/results/robust_\" +str(delayed_robot_cnt) + \"x\"", "= np.arange(map_gen_robot_count) robot_IDs_to_delay = np.random.choice(map_gen_robot_count, size=delayed_robot_cnt, replace=False) logger.info(\"delaying robots (ID):", "map_gen_robot_count simulation_results[\"map details\"][\"seed val\"] = map_gen_seedval simulation_results[\"results\"] = {} simulation_results[\"results\"][\"comp", "plt.show() map_gen_robot_count = 10 map_gen_seedval = \"NaN\" try: map_gen_robot_count =", "# create data to save to YAML file simulation_results =", "res, solve_t = solve_MILP(robots, dependency_groups, ADG, ADG_reverse, H_control, H_prediction, m_opt,", "w > 1.0, run_CBS uses ECBS! logger.info(\" with sub-optimality w={}\".format(w))", "auto_gen_01_nuernberg | auto_gen_00_large | auto_gen_02_simple | manual_03_maxplus random.seed(random_seed) np.random.seed(random_seed) \"\"\"", "np.random.choice(map_gen_robot_count, size=delayed_robot_cnt, replace=False) logger.info(\"delaying robots (ID): {}\".format(robot_IDs_to_delay)) # Advance robots", "= True if show_visual: visualizer.redraw(robots, pause_length=0.1) # return 0 k", "sim_timeout = 500 # define prediction and control horizons: H_prediction", "= [] while (not all(robots_done)) and (k < sim_timeout): print(\"pl_opt.log:", "stat import os import sys from mip import Model, ProgressLog,", "ADG_reverse, H_control, H_prediction, m_opt, pl_opt, run=run_MILP, uncertainty_bound=robust_param) solve_time.append(solve_t) if not", "deadlock! something is wrong with optimization\") except nx.NetworkXNoCycle: logger.debug(\"no cycle", "{}\".format(max(solve_time))) logger.info(\" - avg: {}\".format(stat.mean(solve_time))) # create data to save", "- %(levelname)s :: %(message)s', level=logging.INFO) def main(): \"\"\" --------------------------- INPUTS", "| manual_03_maxplus random.seed(random_seed) np.random.seed(random_seed) \"\"\" -------------------------------------------------------------------- \"\"\" # start initial", "ADG.node[robot.current_node][\"data\"] logger.debug(\" - Robot {} # {} @ {} =>", "= [solve_time] simulation_results[\"results\"][\"comp time\"][\"max\"] = max(solve_time) simulation_results[\"results\"][\"comp time\"][\"avg\"] = stat.mean(solve_time)", "> 8): ADG.node[robot.current_node][\"data\"].status = Status.FINISHED robot.advance() if not robot.is_done(): time_to_goal[robot.robot_ID]", "details\"][\"seed val\"] = map_gen_seedval simulation_results[\"results\"] = {} simulation_results[\"results\"][\"comp time\"] =", "stat.mean(solve_time) simulation_results[\"results\"][\"total time\"] = total_time logger.info(simulation_results) file_name = pwd +", "print(\"pl_opt.log: {}\".format(pl_opt.log)) m_opt.clear() # show current robot status logger.info(\"-------------------- @", "+ \"/res_robots_\" + str(map_gen_robot_count) + \"_horizon_\" + str(H_control) + \"_mapseed_\"", "show_visual: visualizer.redraw(robots, pause_length=0.1) # return 0 k += 1 #", "data to save to YAML file simulation_results = {} simulation_results[\"parameters\"]", "= ADG.node[robot.current_node][\"data\"] logger.debug(\" - Robot {} # {} @ {}", "\"_horizon_\" + str(H_control) + \"_mapseed_\" + str(map_gen_seedval) + \"_robustparam_\" +", "= \"NaN\" try: map_gen_robot_count = int(sys.argv[1]) map_gen_seedval = int(sys.argv[2]) H_control", "int(sys.argv[4]) random.seed(map_gen_seedval) # map_gen_seedval np.random.seed(map_gen_seedval) # map_gen_seedval except: print(\" no", "\"\"\" import sys import yaml import time import matplotlib.colors as", "all_dependencies_completed and k > 0: # (robot.robot_ID == 2 or", "logger.info(\"-------------------- @ time step k = {} --------------------\".format(k)) for robot", "statistics: {} \\n\".format(plans[\"statistics\"])) logger.debug(plans[\"schedule\"]) # show factory map # show_factory_map(map_file,", "= 0 if show_visual: visualizer = Visualizer(map_file, robots) # initialize", "+str(delayed_robot_cnt) + \"x\" + str(delay_amount) + \"/res_robots_\" + str(map_gen_robot_count) +", "logger.info(\"Computation time:\") logger.info(\" - max: {}\".format(max(solve_time))) logger.info(\" - avg: {}\".format(stat.mean(solve_time)))", "= plt.cm.rainbow( np.arange(len(robot_plan))/len(robot_plan) ) for robot_id in robot_plan: plan =", "time k = 0 robot_IDs_to_delay = [] while (not all(robots_done))", "# end of while loop total_time = 0 for idx,", "= analyze_ADG(ADG, plans, show_graph=False) ADG_reverse = ADG.reverse(copy=False) # initialize simulation", "time\"][\"solve_time\"] = [solve_time] simulation_results[\"results\"][\"comp time\"][\"max\"] = max(solve_time) simulation_results[\"results\"][\"comp time\"][\"avg\"] =", "wspace=0, hspace=0) metadata = dict(title='Movie Test', artist='Matplotlib', comment='Movie support!') writer", "plt.cm.rainbow( np.arange(len(robot_plan))/len(robot_plan) ) for robot_id in robot_plan: plan = robot_plan[robot_id]", "# or (robot.robot_ID == 3 or k > 8): ADG.node[robot.current_node][\"data\"].status", "pause_length=0.1) # return 0 k += 1 # end of", "dependency in node_dependencies_list: if (ADG.node[dependency][\"data\"].status != Status.FINISHED): all_dependencies_completed = False", "MIP object m_opt m_opt = Model('MILP_sequence', solver='CBC') # print(m_opt.max_nodes) pl_opt", "= \"objective_value\" # print(\"pl_opt.settings: {}\".format(pl_opt.settings)) # print(\"pl_opt.log: {}\".format(pl_opt.log)) # pl_opt.instance", "metadata=metadata) with writer.saving(ADG_fig, \"ADG_video.mp4\", 500): # run a simulation in", "print(\"pl_opt.log: {}\".format(pl_opt.log)) # pl_opt.instance = m_opt.name # print(\"pl_opt.instance: {}\".format(pl_opt.instance)) ADG_fig", "# check for cycles try: nx.find_cycle(ADG, orientation=\"original\") logger.warning(\"Cycle detected!!\") raise", "simulation in time k = 0 robot_IDs_to_delay = [] while", "import * from adg_node import * from process_results import *", "{} --------------------\".format(k)) for robot in robots: node_info = ADG.node[robot.current_node][\"data\"] logger.debug(\"", "(dependencies have been met) for robot in robots: # check", "from milp_formulation import * from robot import * from adg", "lookup H_control = 5 random_seed = 0 mu = 0.5", "if show_visual: visualizer.redraw(robots, pause_length=0.1) # return 0 k += 1", "cycle => deadlock! something is wrong with optimization\") except nx.NetworkXNoCycle:", "= [] solve_time = [] robots_done = [] time_to_goal =", "= Model('MILP_sequence', solver='CBC') # print(m_opt.max_nodes) pl_opt = ProgressLog() # pl_opt.settings", "if show_visual: visualizer = Visualizer(map_file, robots) # initialize optimization MIP", "goal_positions[robot_id]) robots.append(new_robot) robots_done.append(False) time_to_goal[robot_id] = 0 if show_visual: visualizer =", "= {} --------------------\".format(k)) for robot in robots: node_info = ADG.node[robot.current_node][\"data\"]", "2 or k > 5) if (not (robot.robot_ID in robot_IDs_to_delay)):", "robots_done.append(False) time_to_goal[robot_id] = 0 if show_visual: visualizer = Visualizer(map_file, robots)", "> 5) if (not (robot.robot_ID in robot_IDs_to_delay)): # or (k", "0.0 delay_amount = 5 delayed_robot_cnt = 2 w = 1.4", "edges_type_1, dependency_groups = analyze_ADG(ADG, plans, show_graph=False) ADG_reverse = ADG.reverse(copy=False) #", "delayed_robot_cnt = 2 w = 1.4 # sub-optimality bound: w", "# same sample every time if all_dependencies_completed and k >", "= H_control simulation_results[\"parameters\"][\"random seed\"] = random_seed simulation_results[\"parameters\"][\"ECBS w\"] = w", "Visualizer(map_file, robots) # initialize optimization MIP object m_opt m_opt =", "visualizers import * from milp_formulation import * from robot import", "as mcolors import matplotlib import matplotlib.pyplot as plt import random", "# initialize optimization MIP object m_opt m_opt = Model('MILP_sequence', solver='CBC')", "node_info = ADG.node[robot.current_node][\"data\"] logger.debug(\" - Robot {} # {} @", "robots, \"ADG after MILP ADG | k = {}\".format(k), writer=writer)", "adg_node import * from process_results import * logger = logging.getLogger(__name__)", "m_opt m_opt = Model('MILP_sequence', solver='CBC') # print(m_opt.max_nodes) pl_opt = ProgressLog()", "delay_amount simulation_results[\"map details\"] = {} simulation_results[\"map details\"][\"robot_count\"] = map_gen_robot_count simulation_results[\"map", "or (k < 10 or k > 20)): # or", "# Advance robots if possible (dependencies have been met) for", "BINARY, CONTINUOUS, Constr, ConstrList sys.path.insert(1, \"functions/\") from planners import *", "define prediction and control horizons: H_prediction >= H_control H_prediction =", "save to YAML file simulation_results = {} simulation_results[\"parameters\"] = {}", "# print(\"pl_opt.instance: {}\".format(pl_opt.instance)) ADG_fig = plt.figure(figsize=(12,8)) plt.subplots_adjust(left=0, bottom=0, right=1, top=1,", "if all dependencies have been met, to advance to next", "show_ADG: # draw_ADG(ADG, robots, \"ADG after MILP ADG | k", "H_prediction, m_opt, pl_opt, run=run_MILP, uncertainty_bound=robust_param) solve_time.append(solve_t) if not (res is", "# start initial pwd = os.path.dirname(os.path.abspath(__file__)) logger.info(pwd) map_file = pwd", "+ \".yaml\" if save_file: save_to_yaml(simulation_results, file_name) if __name__ == \"__main__\":", "ADG.node[robot.current_node][\"data\"].status = Status.FINISHED robot.advance() if not robot.is_done(): time_to_goal[robot.robot_ID] += 1", "- plan: {} \\t \\t positions: {}\".format(robot_id, plan[\"nodes\"], plan[\"positions\"])) new_robot", "logger.debug(\"Robot {} - plan: {} \\t \\t positions: {}\".format(robot_id, plan[\"nodes\"],", "5) if (not (robot.robot_ID in robot_IDs_to_delay)): # or (k <", "(k < sim_timeout): print(\"pl_opt.log: {}\".format(pl_opt.log)) m_opt.clear() # show current robot", "t logger.info(\"Total time to complete missions: {}\".format(total_time)) logger.info(\"horizon = {}\".format(H_control))", "from mip import Model, ProgressLog, xsum, maximize, minimize, BINARY, CONTINUOUS,", "10 or k > 20)): # or (robot.robot_ID == 3", "3 or k > 8): ADG.node[robot.current_node][\"data\"].status = Status.FINISHED robot.advance() if", "deadlock. good!\") pass if (k % delay_amount) == 0: robot_IDs", "dependencies are completed, the robot can advance! # delay_amount =", "simulation_results[\"parameters\"] = {} simulation_results[\"parameters\"][\"H_control\"] = H_control simulation_results[\"parameters\"][\"random seed\"] = random_seed", "manual_03_maxplus random.seed(random_seed) np.random.seed(random_seed) \"\"\" -------------------------------------------------------------------- \"\"\" # start initial pwd", "print(m_opt.max_nodes) pl_opt = ProgressLog() # pl_opt.settings = \"objective_value\" # print(\"pl_opt.settings:", "time if all_dependencies_completed and k > 0: # (robot.robot_ID ==", "logger.warning(\"Cycle detected!!\") raise Exception(\"ADG has a cycle => deadlock! something", "import * from process_results import * logger = logging.getLogger(__name__) logging.basicConfig(format='%(name)s", "simulation_results[\"parameters\"][\"H_control\"] = H_control simulation_results[\"parameters\"][\"random seed\"] = random_seed simulation_results[\"parameters\"][\"ECBS w\"] =", "500 # define prediction and control horizons: H_prediction >= H_control", "+ \"/csv_robots_yaml.yaml\" robot_file_tmp = pwd + \"/data/tmp/robots.yaml\" start_time = time.time()", "simulation_results[\"map details\"] = {} simulation_results[\"map details\"][\"robot_count\"] = map_gen_robot_count simulation_results[\"map details\"][\"seed", "{} => status: {}\".format(robot.robot_ID, node_info.ID, node_info.s_loc, robot.status)) # solve MILP", "+ \"_mapseed_\" + str(map_gen_seedval) + \"_robustparam_\" + str(robust_param) + \".yaml\"", "initialize optimization MIP object m_opt m_opt = Model('MILP_sequence', solver='CBC') #", "-------------------------------------------------------------------- \"\"\" # start initial pwd = os.path.dirname(os.path.abspath(__file__)) logger.info(pwd) map_file", "all_dependencies_completed = True for dependency in node_dependencies_list: if (ADG.node[dependency][\"data\"].status !=", "show_graph=False) ADG_reverse = ADG.reverse(copy=False) # initialize simulation robots = []", "process_results import * logger = logging.getLogger(__name__) logging.basicConfig(format='%(name)s - %(levelname)s ::", "idx, t in time_to_goal.items(): total_time += t logger.info(\"Total time to", "import sys from mip import Model, ProgressLog, xsum, maximize, minimize,", "import matplotlib.pyplot as plt import random import logging import time", "pass if (k % delay_amount) == 0: robot_IDs = np.arange(map_gen_robot_count)", "0.5 robust_param = 0.0 delay_amount = 5 delayed_robot_cnt = 2", "== 0: robot_IDs = np.arange(map_gen_robot_count) robot_IDs_to_delay = np.random.choice(map_gen_robot_count, size=delayed_robot_cnt, replace=False)", "= {} simulation_results[\"results\"][\"comp time\"][\"solve_time\"] = [solve_time] simulation_results[\"results\"][\"comp time\"][\"max\"] = max(solve_time)", "= pwd + \"/data/\" + fldr + \"/csv_robots_yaml.yaml\" robot_file_tmp =", "detected!!\") raise Exception(\"ADG has a cycle => deadlock! something is", "integer value for forward node lookup H_control = 5 random_seed" ]
[ "table.create.assert_called_once_with('first', 'last', default_sound.id, 0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create_SoundNotFoundError(table, sound, default_sound):", "model.list() table.list.assert_called_once() assert models == [_default(), _default(2)] @patch('rfidsecuritysvc.model.guest.table') def test_list_noresults(table):", "from rfidsecuritysvc.model.guest import Guest from rfidsecuritysvc.model.sound import Sound from rfidsecuritysvc.exception", "[] models = model.list() table.list.assert_called_once() assert models == [] @patch('rfidsecuritysvc.model.guest.sound_model')", "= [ _default().test_to_row(), _default(2).test_to_row(), ] models = model.list() table.list.assert_called_once() assert", "= [] models = model.list() table.list.assert_called_once() assert models == []", "assert model.update(1, 'first', 'last', None, None) == 1 sound.get.assert_not_called() table.update.assert_called_once_with(1,", "default_color)) @patch('rfidsecuritysvc.model.guest.table') def test_get(table): table.get.return_value = _default().test_to_row() assert model.get(1) ==", "table.list.assert_called_once() assert models == [] @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create(table, sound,", "sound.get.assert_called_once_with(default_sound.id) table.update.assert_called_once_with(1, 'first', 'last', default_sound.id, 0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update_no_prefs(table,", "def test_list(table): table.list.return_value = [ _default().test_to_row(), _default(2).test_to_row(), ] models =", "sound.get.assert_not_called() table.update.assert_called_once_with(1, 'first', 'last', None, None) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update_SoundNotFoundError(table,", "import SoundNotFoundError def test_Guest(assert_model, default_sound, default_color): assert_model(_model(1, 'first', 'last', default_sound,", "1 assert model.update(1, 'first', 'last', default_sound.id, 0xABCDEF) == 1 sound.get.assert_called_once_with(default_sound.id)", "sound, default_sound): table.update.return_value = 1 sound.get.return_value = None with pytest.raises(SoundNotFoundError):", "model.update(1, 'first', 'last', default_sound.id, 0xABCDEF) sound.get.assert_called_once_with(default_sound.id) table.update.assert_not_called() def test__model_no_color(creatable_guest): row", "table.delete.assert_called_with(1) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update(table, sound, default_sound): sound.get.return_value = default_sound", "default_sound.id, 0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update_no_prefs(table, sound, default_sound): table.update.return_value =", "table.update.return_value = 1 assert model.update(1, 'first', 'last', None, None) ==", "row = creatable_guest.test_to_row() row['color'] = None g = model.__model(row) assert", "Guest from rfidsecuritysvc.model.sound import Sound from rfidsecuritysvc.exception import SoundNotFoundError def", "@patch('rfidsecuritysvc.model.guest.table') def test_create_no_prefs(table, sound, default_sound): table.create.return_value = None assert model.create('first',", "f'first {index}', f'last {index}', Sound(index, f'sound_name {index}', '2021-09-25 23:13:25'), Color(0xABCDEF))", "model.update(1, 'first', 'last', default_sound.id, 0xABCDEF) == 1 sound.get.assert_called_once_with(default_sound.id) table.update.assert_called_once_with(1, 'first',", "sound, default_sound): table.create.return_value = None assert model.create('first', 'last', None, None)", "def test__model_no_color(creatable_guest): row = creatable_guest.test_to_row() row['color'] = None g =", "= None g = model.__model(row) assert g.sound is None def", "default_sound.id, 0xABCDEF) is None sound.get.assert_called_once_with(default_sound.id) table.create.assert_called_once_with('first', 'last', default_sound.id, 0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model')", "default_sound): table.update.return_value = 1 sound.get.return_value = None with pytest.raises(SoundNotFoundError): model.update(1,", "pytest.raises(SoundNotFoundError): model.update(1, 'first', 'last', default_sound.id, 0xABCDEF) sound.get.assert_called_once_with(default_sound.id) table.update.assert_not_called() def test__model_no_color(creatable_guest):", "None g = model.__model(row) assert g.sound is None def _default(index=1):", "_default().test_to_row() assert model.get(1) == _default() table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table') def test_get_notfound(table): table.get.return_value", "is None sound.get.assert_called_once_with(default_sound.id) table.create.assert_called_once_with('first', 'last', default_sound.id, 0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def", "test_get_notfound(table): table.get.return_value = None assert model.get(1) is None table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table')", "Color from rfidsecuritysvc.model.guest import Guest from rfidsecuritysvc.model.sound import Sound from", "from rfidsecuritysvc.model.color import Color from rfidsecuritysvc.model.guest import Guest from rfidsecuritysvc.model.sound", "sound, default_sound): sound.get.return_value = None with pytest.raises(SoundNotFoundError): model.create('first', 'last', default_sound.id,", "= default_sound table.create.return_value = None assert model.create('first', 'last', default_sound.id, 0xABCDEF)", "'last', None, None) @patch('rfidsecuritysvc.model.guest.table') def test_delete(table): table.delete.return_value = 1 assert", "= default_sound table.update.return_value = 1 assert model.update(1, 'first', 'last', default_sound.id,", "'last', default_sound.id, 0xABCDEF) sound.get.assert_called_once_with(default_sound.id) table.create.assert_not_called() @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create_no_prefs(table, sound,", "= 1 assert model.update(1, 'first', 'last', None, None) == 1", "23:13:25'), Color(0xABCDEF)) def _model(id, first_name, last_name, sound, color): return Guest(id,", "is None sound.get.assert_not_called() table.create.assert_called_once_with('first', 'last', None, None) @patch('rfidsecuritysvc.model.guest.table') def test_delete(table):", "= creatable_guest.test_to_row() row['sound'] = None g = model.__model(row) assert g.sound", "0xABCDEF) == 1 sound.get.assert_called_once_with(default_sound.id) table.update.assert_called_once_with(1, 'first', 'last', default_sound.id, 0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model')", "test__model_no_color(creatable_guest): row = creatable_guest.test_to_row() row['color'] = None g = model.__model(row)", "0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create_SoundNotFoundError(table, sound, default_sound): sound.get.return_value = None", "table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table') def test_get_notfound(table): table.get.return_value = None assert model.get(1) is", "rfidsecuritysvc.model.guest as model from rfidsecuritysvc.model.color import Color from rfidsecuritysvc.model.guest import", "1 assert model.update(1, 'first', 'last', None, None) == 1 sound.get.assert_not_called()", "_model(index, f'first {index}', f'last {index}', Sound(index, f'sound_name {index}', '2021-09-25 23:13:25'),", "None assert model.create('first', 'last', None, None) is None sound.get.assert_not_called() table.create.assert_called_once_with('first',", "assert model.create('first', 'last', default_sound.id, 0xABCDEF) is None sound.get.assert_called_once_with(default_sound.id) table.create.assert_called_once_with('first', 'last',", "'first', 'last', default_sound.id, 0xABCDEF) == 1 sound.get.assert_called_once_with(default_sound.id) table.update.assert_called_once_with(1, 'first', 'last',", "assert_model(_model(1, 'first', 'last', default_sound, default_color), Guest(1, 'first', 'last', default_sound, default_color))", "None) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update_SoundNotFoundError(table, sound, default_sound): table.update.return_value = 1", "model.__model(row) assert g.color is None def test__model_no_sound(creatable_guest): row = creatable_guest.test_to_row()", "@patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update(table, sound, default_sound): sound.get.return_value = default_sound table.update.return_value", "= model.__model(row) assert g.sound is None def _default(index=1): return _model(index,", "assert model.get(1) is None table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table') def test_list(table): table.list.return_value =", "== 1 sound.get.assert_called_once_with(default_sound.id) table.update.assert_called_once_with(1, 'first', 'last', default_sound.id, 0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table')", "None, None) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update_SoundNotFoundError(table, sound, default_sound): table.update.return_value =", "import rfidsecuritysvc.model.guest as model from rfidsecuritysvc.model.color import Color from rfidsecuritysvc.model.guest", "None def _default(index=1): return _model(index, f'first {index}', f'last {index}', Sound(index,", "0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update_no_prefs(table, sound, default_sound): table.update.return_value = 1", "= _default().test_to_row() assert model.get(1) == _default() table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table') def test_get_notfound(table):", "model.update(1, 'first', 'last', None, None) == 1 sound.get.assert_not_called() table.update.assert_called_once_with(1, 'first',", "table.list.return_value = [ _default().test_to_row(), _default(2).test_to_row(), ] models = model.list() table.list.assert_called_once()", "table.list.return_value = [] models = model.list() table.list.assert_called_once() assert models ==", "model.create('first', 'last', default_sound.id, 0xABCDEF) sound.get.assert_called_once_with(default_sound.id) table.create.assert_not_called() @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create_no_prefs(table,", "Sound from rfidsecuritysvc.exception import SoundNotFoundError def test_Guest(assert_model, default_sound, default_color): assert_model(_model(1,", "'last', default_sound, default_color), Guest(1, 'first', 'last', default_sound, default_color)) @patch('rfidsecuritysvc.model.guest.table') def", "test_update_no_prefs(table, sound, default_sound): table.update.return_value = 1 assert model.update(1, 'first', 'last',", "_default(2)] @patch('rfidsecuritysvc.model.guest.table') def test_list_noresults(table): table.list.return_value = [] models = model.list()", "sound, default_sound): table.update.return_value = 1 assert model.update(1, 'first', 'last', None,", "@patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update_no_prefs(table, sound, default_sound): table.update.return_value = 1 assert", "@patch('rfidsecuritysvc.model.guest.table') def test_list_noresults(table): table.list.return_value = [] models = model.list() table.list.assert_called_once()", "Sound(index, f'sound_name {index}', '2021-09-25 23:13:25'), Color(0xABCDEF)) def _model(id, first_name, last_name,", "'last', None, None) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update_SoundNotFoundError(table, sound, default_sound): table.update.return_value", "default_sound.id, 0xABCDEF) sound.get.assert_called_once_with(default_sound.id) table.update.assert_not_called() def test__model_no_color(creatable_guest): row = creatable_guest.test_to_row() row['color']", "[_default(), _default(2)] @patch('rfidsecuritysvc.model.guest.table') def test_list_noresults(table): table.list.return_value = [] models =", "sound, default_sound): sound.get.return_value = default_sound table.create.return_value = None assert model.create('first',", "'last', default_sound.id, 0xABCDEF) is None sound.get.assert_called_once_with(default_sound.id) table.create.assert_called_once_with('first', 'last', default_sound.id, 0xABCDEF)", "table.create.assert_called_once_with('first', 'last', None, None) @patch('rfidsecuritysvc.model.guest.table') def test_delete(table): table.delete.return_value = 1", "1 sound.get.assert_not_called() table.update.assert_called_once_with(1, 'first', 'last', None, None) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def", "table.create.return_value = None assert model.create('first', 'last', default_sound.id, 0xABCDEF) is None", "@patch('rfidsecuritysvc.model.guest.table') def test_update(table, sound, default_sound): sound.get.return_value = default_sound table.update.return_value =", "None def test__model_no_sound(creatable_guest): row = creatable_guest.test_to_row() row['sound'] = None g", "pytest from unittest.mock import patch import rfidsecuritysvc.model.guest as model from", "import patch import rfidsecuritysvc.model.guest as model from rfidsecuritysvc.model.color import Color", "default_sound, default_color): assert_model(_model(1, 'first', 'last', default_sound, default_color), Guest(1, 'first', 'last',", "assert model.delete(1) == 1 table.delete.assert_called_with(1) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update(table, sound,", "'last', default_sound.id, 0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update_no_prefs(table, sound, default_sound): table.update.return_value", "import Sound from rfidsecuritysvc.exception import SoundNotFoundError def test_Guest(assert_model, default_sound, default_color):", "@patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create_no_prefs(table, sound, default_sound): table.create.return_value = None assert", "{index}', '2021-09-25 23:13:25'), Color(0xABCDEF)) def _model(id, first_name, last_name, sound, color):", "f'last {index}', Sound(index, f'sound_name {index}', '2021-09-25 23:13:25'), Color(0xABCDEF)) def _model(id,", "= model.list() table.list.assert_called_once() assert models == [_default(), _default(2)] @patch('rfidsecuritysvc.model.guest.table') def", "'2021-09-25 23:13:25'), Color(0xABCDEF)) def _model(id, first_name, last_name, sound, color): return", "= None assert model.get(1) is None table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table') def test_list(table):", "default_sound.id, 0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create_SoundNotFoundError(table, sound, default_sound): sound.get.return_value =", "= None assert model.create('first', 'last', None, None) is None sound.get.assert_not_called()", "models == [_default(), _default(2)] @patch('rfidsecuritysvc.model.guest.table') def test_list_noresults(table): table.list.return_value = []", "def test_update_SoundNotFoundError(table, sound, default_sound): table.update.return_value = 1 sound.get.return_value = None", "def test_update_no_prefs(table, sound, default_sound): table.update.return_value = 1 assert model.update(1, 'first',", "[ _default().test_to_row(), _default(2).test_to_row(), ] models = model.list() table.list.assert_called_once() assert models", "@patch('rfidsecuritysvc.model.guest.table') def test_create_SoundNotFoundError(table, sound, default_sound): sound.get.return_value = None with pytest.raises(SoundNotFoundError):", "test_update_SoundNotFoundError(table, sound, default_sound): table.update.return_value = 1 sound.get.return_value = None with", "test__model_no_sound(creatable_guest): row = creatable_guest.test_to_row() row['sound'] = None g = model.__model(row)", "== [_default(), _default(2)] @patch('rfidsecuritysvc.model.guest.table') def test_list_noresults(table): table.list.return_value = [] models", "'first', 'last', None, None) == 1 sound.get.assert_not_called() table.update.assert_called_once_with(1, 'first', 'last',", "def test_list_noresults(table): table.list.return_value = [] models = model.list() table.list.assert_called_once() assert", "models = model.list() table.list.assert_called_once() assert models == [] @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table')", "test_list(table): table.list.return_value = [ _default().test_to_row(), _default(2).test_to_row(), ] models = model.list()", "default_sound): sound.get.return_value = default_sound table.update.return_value = 1 assert model.update(1, 'first',", "def test_delete(table): table.delete.return_value = 1 assert model.delete(1) == 1 table.delete.assert_called_with(1)", "assert models == [] @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create(table, sound, default_sound):", "is None table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table') def test_list(table): table.list.return_value = [ _default().test_to_row(),", "default_sound): sound.get.return_value = None with pytest.raises(SoundNotFoundError): model.create('first', 'last', default_sound.id, 0xABCDEF)", "assert model.get(1) == _default() table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table') def test_get_notfound(table): table.get.return_value =", "_default(2).test_to_row(), ] models = model.list() table.list.assert_called_once() assert models == [_default(),", "assert g.sound is None def _default(index=1): return _model(index, f'first {index}',", "model from rfidsecuritysvc.model.color import Color from rfidsecuritysvc.model.guest import Guest from", "row = creatable_guest.test_to_row() row['sound'] = None g = model.__model(row) assert", "@patch('rfidsecuritysvc.model.guest.table') def test_update_no_prefs(table, sound, default_sound): table.update.return_value = 1 assert model.update(1,", "'first', 'last', default_sound, default_color), Guest(1, 'first', 'last', default_sound, default_color)) @patch('rfidsecuritysvc.model.guest.table')", "models = model.list() table.list.assert_called_once() assert models == [_default(), _default(2)] @patch('rfidsecuritysvc.model.guest.table')", "assert model.create('first', 'last', None, None) is None sound.get.assert_not_called() table.create.assert_called_once_with('first', 'last',", "@patch('rfidsecuritysvc.model.guest.table') def test_delete(table): table.delete.return_value = 1 assert model.delete(1) == 1", "'last', default_sound.id, 0xABCDEF) == 1 sound.get.assert_called_once_with(default_sound.id) table.update.assert_called_once_with(1, 'first', 'last', default_sound.id,", "def test_create_no_prefs(table, sound, default_sound): table.create.return_value = None assert model.create('first', 'last',", "default_sound): table.create.return_value = None assert model.create('first', 'last', None, None) is", "default_sound): table.update.return_value = 1 assert model.update(1, 'first', 'last', None, None)", "@patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update_SoundNotFoundError(table, sound, default_sound): table.update.return_value = 1 sound.get.return_value", "@patch('rfidsecuritysvc.model.guest.table') def test_update_SoundNotFoundError(table, sound, default_sound): table.update.return_value = 1 sound.get.return_value =", "_model(id, first_name, last_name, sound, color): return Guest(id, first_name, last_name, sound,", "table.create.assert_not_called() @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create_no_prefs(table, sound, default_sound): table.create.return_value = None", "rfidsecuritysvc.model.guest import Guest from rfidsecuritysvc.model.sound import Sound from rfidsecuritysvc.exception import", "rfidsecuritysvc.exception import SoundNotFoundError def test_Guest(assert_model, default_sound, default_color): assert_model(_model(1, 'first', 'last',", "'first', 'last', default_sound.id, 0xABCDEF) sound.get.assert_called_once_with(default_sound.id) table.update.assert_not_called() def test__model_no_color(creatable_guest): row =", "first_name, last_name, sound, color): return Guest(id, first_name, last_name, sound, color)", "default_sound table.create.return_value = None assert model.create('first', 'last', default_sound.id, 0xABCDEF) is", "g.sound is None def _default(index=1): return _model(index, f'first {index}', f'last", "'first', 'last', None, None) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update_SoundNotFoundError(table, sound, default_sound):", "g = model.__model(row) assert g.color is None def test__model_no_sound(creatable_guest): row", "def test_get(table): table.get.return_value = _default().test_to_row() assert model.get(1) == _default() table.get.assert_called_once_with(1)", "model.__model(row) assert g.sound is None def _default(index=1): return _model(index, f'first", "None assert model.get(1) is None table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table') def test_list(table): table.list.return_value", "@patch('rfidsecuritysvc.model.guest.table') def test_create(table, sound, default_sound): sound.get.return_value = default_sound table.create.return_value =", "None sound.get.assert_not_called() table.create.assert_called_once_with('first', 'last', None, None) @patch('rfidsecuritysvc.model.guest.table') def test_delete(table): table.delete.return_value", "assert g.color is None def test__model_no_sound(creatable_guest): row = creatable_guest.test_to_row() row['sound']", "{index}', f'last {index}', Sound(index, f'sound_name {index}', '2021-09-25 23:13:25'), Color(0xABCDEF)) def", "sound.get.return_value = default_sound table.update.return_value = 1 assert model.update(1, 'first', 'last',", "def test_create(table, sound, default_sound): sound.get.return_value = default_sound table.create.return_value = None", "g = model.__model(row) assert g.sound is None def _default(index=1): return", "table.get.return_value = None assert model.get(1) is None table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table') def", "model.get(1) == _default() table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table') def test_get_notfound(table): table.get.return_value = None", "test_list_noresults(table): table.list.return_value = [] models = model.list() table.list.assert_called_once() assert models", "None sound.get.assert_called_once_with(default_sound.id) table.create.assert_called_once_with('first', 'last', default_sound.id, 0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create_SoundNotFoundError(table,", "def _model(id, first_name, last_name, sound, color): return Guest(id, first_name, last_name,", "'first', 'last', default_sound.id, 0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update_no_prefs(table, sound, default_sound):", "test_get(table): table.get.return_value = _default().test_to_row() assert model.get(1) == _default() table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table')", "pytest.raises(SoundNotFoundError): model.create('first', 'last', default_sound.id, 0xABCDEF) sound.get.assert_called_once_with(default_sound.id) table.create.assert_not_called() @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def", "row['sound'] = None g = model.__model(row) assert g.sound is None", "@patch('rfidsecuritysvc.model.guest.table') def test_get(table): table.get.return_value = _default().test_to_row() assert model.get(1) == _default()", "table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table') def test_list(table): table.list.return_value = [ _default().test_to_row(), _default(2).test_to_row(), ]", "0xABCDEF) is None sound.get.assert_called_once_with(default_sound.id) table.create.assert_called_once_with('first', 'last', default_sound.id, 0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table')", "= creatable_guest.test_to_row() row['color'] = None g = model.__model(row) assert g.color", "'first', 'last', default_sound, default_color)) @patch('rfidsecuritysvc.model.guest.table') def test_get(table): table.get.return_value = _default().test_to_row()", "None) == 1 sound.get.assert_not_called() table.update.assert_called_once_with(1, 'first', 'last', None, None) @patch('rfidsecuritysvc.model.guest.sound_model')", "== [] @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create(table, sound, default_sound): sound.get.return_value =", "rfidsecuritysvc.model.sound import Sound from rfidsecuritysvc.exception import SoundNotFoundError def test_Guest(assert_model, default_sound,", "test_delete(table): table.delete.return_value = 1 assert model.delete(1) == 1 table.delete.assert_called_with(1) @patch('rfidsecuritysvc.model.guest.sound_model')", "@patch('rfidsecuritysvc.model.guest.table') def test_get_notfound(table): table.get.return_value = None assert model.get(1) is None", "sound.get.return_value = default_sound table.create.return_value = None assert model.create('first', 'last', default_sound.id,", "sound.get.return_value = None with pytest.raises(SoundNotFoundError): model.create('first', 'last', default_sound.id, 0xABCDEF) sound.get.assert_called_once_with(default_sound.id)", "= None with pytest.raises(SoundNotFoundError): model.create('first', 'last', default_sound.id, 0xABCDEF) sound.get.assert_called_once_with(default_sound.id) table.create.assert_not_called()", "default_sound table.update.return_value = 1 assert model.update(1, 'first', 'last', default_sound.id, 0xABCDEF)", "1 table.delete.assert_called_with(1) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update(table, sound, default_sound): sound.get.return_value =", "with pytest.raises(SoundNotFoundError): model.create('first', 'last', default_sound.id, 0xABCDEF) sound.get.assert_called_once_with(default_sound.id) table.create.assert_not_called() @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table')", "table.update.return_value = 1 assert model.update(1, 'first', 'last', default_sound.id, 0xABCDEF) ==", "_default() table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table') def test_get_notfound(table): table.get.return_value = None assert model.get(1)", "table.create.return_value = None assert model.create('first', 'last', None, None) is None", "None) @patch('rfidsecuritysvc.model.guest.table') def test_delete(table): table.delete.return_value = 1 assert model.delete(1) ==", "model.delete(1) == 1 table.delete.assert_called_with(1) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update(table, sound, default_sound):", "def test_update(table, sound, default_sound): sound.get.return_value = default_sound table.update.return_value = 1", "1 sound.get.assert_called_once_with(default_sound.id) table.update.assert_called_once_with(1, 'first', 'last', default_sound.id, 0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def", "table.update.assert_called_once_with(1, 'first', 'last', default_sound.id, 0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update_no_prefs(table, sound,", "None with pytest.raises(SoundNotFoundError): model.update(1, 'first', 'last', default_sound.id, 0xABCDEF) sound.get.assert_called_once_with(default_sound.id) table.update.assert_not_called()", "table.get.return_value = _default().test_to_row() assert model.get(1) == _default() table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table') def", "'last', default_sound.id, 0xABCDEF) sound.get.assert_called_once_with(default_sound.id) table.update.assert_not_called() def test__model_no_color(creatable_guest): row = creatable_guest.test_to_row()", "None, None) @patch('rfidsecuritysvc.model.guest.table') def test_delete(table): table.delete.return_value = 1 assert model.delete(1)", "= 1 sound.get.return_value = None with pytest.raises(SoundNotFoundError): model.update(1, 'first', 'last',", "== 1 table.delete.assert_called_with(1) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update(table, sound, default_sound): sound.get.return_value", "default_sound, default_color), Guest(1, 'first', 'last', default_sound, default_color)) @patch('rfidsecuritysvc.model.guest.table') def test_get(table):", "model.create('first', 'last', default_sound.id, 0xABCDEF) is None sound.get.assert_called_once_with(default_sound.id) table.create.assert_called_once_with('first', 'last', default_sound.id,", "return _model(index, f'first {index}', f'last {index}', Sound(index, f'sound_name {index}', '2021-09-25", "@patch('rfidsecuritysvc.model.guest.table') def test_list(table): table.list.return_value = [ _default().test_to_row(), _default(2).test_to_row(), ] models", "table.update.assert_not_called() def test__model_no_color(creatable_guest): row = creatable_guest.test_to_row() row['color'] = None g", "= None g = model.__model(row) assert g.color is None def", "= model.__model(row) assert g.color is None def test__model_no_sound(creatable_guest): row =", "is None def test__model_no_sound(creatable_guest): row = creatable_guest.test_to_row() row['sound'] = None", "creatable_guest.test_to_row() row['sound'] = None g = model.__model(row) assert g.sound is", "None, None) is None sound.get.assert_not_called() table.create.assert_called_once_with('first', 'last', None, None) @patch('rfidsecuritysvc.model.guest.table')", "def test_create_SoundNotFoundError(table, sound, default_sound): sound.get.return_value = None with pytest.raises(SoundNotFoundError): model.create('first',", "= None with pytest.raises(SoundNotFoundError): model.update(1, 'first', 'last', default_sound.id, 0xABCDEF) sound.get.assert_called_once_with(default_sound.id)", "== _default() table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table') def test_get_notfound(table): table.get.return_value = None assert", "f'sound_name {index}', '2021-09-25 23:13:25'), Color(0xABCDEF)) def _model(id, first_name, last_name, sound,", "model.list() table.list.assert_called_once() assert models == [] @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create(table,", "as model from rfidsecuritysvc.model.color import Color from rfidsecuritysvc.model.guest import Guest", "from unittest.mock import patch import rfidsecuritysvc.model.guest as model from rfidsecuritysvc.model.color", "None assert model.create('first', 'last', default_sound.id, 0xABCDEF) is None sound.get.assert_called_once_with(default_sound.id) table.create.assert_called_once_with('first',", "None with pytest.raises(SoundNotFoundError): model.create('first', 'last', default_sound.id, 0xABCDEF) sound.get.assert_called_once_with(default_sound.id) table.create.assert_not_called() @patch('rfidsecuritysvc.model.guest.sound_model')", "sound.get.assert_not_called() table.create.assert_called_once_with('first', 'last', None, None) @patch('rfidsecuritysvc.model.guest.table') def test_delete(table): table.delete.return_value =", "1 assert model.delete(1) == 1 table.delete.assert_called_with(1) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update(table,", "table.delete.return_value = 1 assert model.delete(1) == 1 table.delete.assert_called_with(1) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table')", "SoundNotFoundError def test_Guest(assert_model, default_sound, default_color): assert_model(_model(1, 'first', 'last', default_sound, default_color),", "None g = model.__model(row) assert g.color is None def test__model_no_sound(creatable_guest):", "'last', default_sound, default_color)) @patch('rfidsecuritysvc.model.guest.table') def test_get(table): table.get.return_value = _default().test_to_row() assert", "model.get(1) is None table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table') def test_list(table): table.list.return_value = [", "sound.get.assert_called_once_with(default_sound.id) table.update.assert_not_called() def test__model_no_color(creatable_guest): row = creatable_guest.test_to_row() row['color'] = None", "from rfidsecuritysvc.exception import SoundNotFoundError def test_Guest(assert_model, default_sound, default_color): assert_model(_model(1, 'first',", "_default().test_to_row(), _default(2).test_to_row(), ] models = model.list() table.list.assert_called_once() assert models ==", "'last', None, None) == 1 sound.get.assert_not_called() table.update.assert_called_once_with(1, 'first', 'last', None,", "def test__model_no_sound(creatable_guest): row = creatable_guest.test_to_row() row['sound'] = None g =", "table.update.assert_called_once_with(1, 'first', 'last', None, None) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_update_SoundNotFoundError(table, sound,", "assert model.update(1, 'first', 'last', default_sound.id, 0xABCDEF) == 1 sound.get.assert_called_once_with(default_sound.id) table.update.assert_called_once_with(1,", "test_create(table, sound, default_sound): sound.get.return_value = default_sound table.create.return_value = None assert", "def test_get_notfound(table): table.get.return_value = None assert model.get(1) is None table.get.assert_called_once_with(1)", "sound.get.assert_called_once_with(default_sound.id) table.create.assert_called_once_with('first', 'last', default_sound.id, 0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create_SoundNotFoundError(table, sound,", "sound.get.assert_called_once_with(default_sound.id) table.create.assert_not_called() @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create_no_prefs(table, sound, default_sound): table.create.return_value =", "table.list.assert_called_once() assert models == [_default(), _default(2)] @patch('rfidsecuritysvc.model.guest.table') def test_list_noresults(table): table.list.return_value", "import pytest from unittest.mock import patch import rfidsecuritysvc.model.guest as model", "[] @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create(table, sound, default_sound): sound.get.return_value = default_sound", "unittest.mock import patch import rfidsecuritysvc.model.guest as model from rfidsecuritysvc.model.color import", "row['color'] = None g = model.__model(row) assert g.color is None", "@patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create(table, sound, default_sound): sound.get.return_value = default_sound table.create.return_value", "Color(0xABCDEF)) def _model(id, first_name, last_name, sound, color): return Guest(id, first_name,", "is None def _default(index=1): return _model(index, f'first {index}', f'last {index}',", "<reponame>bcurnow/rfid-security-svc import pytest from unittest.mock import patch import rfidsecuritysvc.model.guest as", "default_sound.id, 0xABCDEF) == 1 sound.get.assert_called_once_with(default_sound.id) table.update.assert_called_once_with(1, 'first', 'last', default_sound.id, 0xABCDEF)", "def _default(index=1): return _model(index, f'first {index}', f'last {index}', Sound(index, f'sound_name", "{index}', Sound(index, f'sound_name {index}', '2021-09-25 23:13:25'), Color(0xABCDEF)) def _model(id, first_name,", "from rfidsecuritysvc.model.sound import Sound from rfidsecuritysvc.exception import SoundNotFoundError def test_Guest(assert_model,", "test_update(table, sound, default_sound): sound.get.return_value = default_sound table.update.return_value = 1 assert", "= 1 assert model.update(1, 'first', 'last', default_sound.id, 0xABCDEF) == 1", "g.color is None def test__model_no_sound(creatable_guest): row = creatable_guest.test_to_row() row['sound'] =", "'last', default_sound.id, 0xABCDEF) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create_SoundNotFoundError(table, sound, default_sound): sound.get.return_value", "import Guest from rfidsecuritysvc.model.sound import Sound from rfidsecuritysvc.exception import SoundNotFoundError", "0xABCDEF) sound.get.assert_called_once_with(default_sound.id) table.create.assert_not_called() @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create_no_prefs(table, sound, default_sound): table.create.return_value", "default_sound.id, 0xABCDEF) sound.get.assert_called_once_with(default_sound.id) table.create.assert_not_called() @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create_no_prefs(table, sound, default_sound):", "== 1 sound.get.assert_not_called() table.update.assert_called_once_with(1, 'first', 'last', None, None) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table')", "0xABCDEF) sound.get.assert_called_once_with(default_sound.id) table.update.assert_not_called() def test__model_no_color(creatable_guest): row = creatable_guest.test_to_row() row['color'] =", "assert models == [_default(), _default(2)] @patch('rfidsecuritysvc.model.guest.table') def test_list_noresults(table): table.list.return_value =", "default_color): assert_model(_model(1, 'first', 'last', default_sound, default_color), Guest(1, 'first', 'last', default_sound,", "'last', None, None) is None sound.get.assert_not_called() table.create.assert_called_once_with('first', 'last', None, None)", "patch import rfidsecuritysvc.model.guest as model from rfidsecuritysvc.model.color import Color from", "test_Guest(assert_model, default_sound, default_color): assert_model(_model(1, 'first', 'last', default_sound, default_color), Guest(1, 'first',", "sound, default_sound): sound.get.return_value = default_sound table.update.return_value = 1 assert model.update(1,", "import Color from rfidsecuritysvc.model.guest import Guest from rfidsecuritysvc.model.sound import Sound", "def test_Guest(assert_model, default_sound, default_color): assert_model(_model(1, 'first', 'last', default_sound, default_color), Guest(1,", "creatable_guest.test_to_row() row['color'] = None g = model.__model(row) assert g.color is", "= None assert model.create('first', 'last', default_sound.id, 0xABCDEF) is None sound.get.assert_called_once_with(default_sound.id)", "models == [] @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create(table, sound, default_sound): sound.get.return_value", "default_sound): sound.get.return_value = default_sound table.create.return_value = None assert model.create('first', 'last',", "= 1 assert model.delete(1) == 1 table.delete.assert_called_with(1) @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def", "_default(index=1): return _model(index, f'first {index}', f'last {index}', Sound(index, f'sound_name {index}',", "default_color), Guest(1, 'first', 'last', default_sound, default_color)) @patch('rfidsecuritysvc.model.guest.table') def test_get(table): table.get.return_value", "rfidsecuritysvc.model.color import Color from rfidsecuritysvc.model.guest import Guest from rfidsecuritysvc.model.sound import", "@patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def test_create_SoundNotFoundError(table, sound, default_sound): sound.get.return_value = None with", "None, None) == 1 sound.get.assert_not_called() table.update.assert_called_once_with(1, 'first', 'last', None, None)", "with pytest.raises(SoundNotFoundError): model.update(1, 'first', 'last', default_sound.id, 0xABCDEF) sound.get.assert_called_once_with(default_sound.id) table.update.assert_not_called() def", "] models = model.list() table.list.assert_called_once() assert models == [_default(), _default(2)]", "None) is None sound.get.assert_not_called() table.create.assert_called_once_with('first', 'last', None, None) @patch('rfidsecuritysvc.model.guest.table') def", "default_sound, default_color)) @patch('rfidsecuritysvc.model.guest.table') def test_get(table): table.get.return_value = _default().test_to_row() assert model.get(1)", "1 sound.get.return_value = None with pytest.raises(SoundNotFoundError): model.update(1, 'first', 'last', default_sound.id,", "test_create_SoundNotFoundError(table, sound, default_sound): sound.get.return_value = None with pytest.raises(SoundNotFoundError): model.create('first', 'last',", "table.update.return_value = 1 sound.get.return_value = None with pytest.raises(SoundNotFoundError): model.update(1, 'first',", "sound.get.return_value = None with pytest.raises(SoundNotFoundError): model.update(1, 'first', 'last', default_sound.id, 0xABCDEF)", "= model.list() table.list.assert_called_once() assert models == [] @patch('rfidsecuritysvc.model.guest.sound_model') @patch('rfidsecuritysvc.model.guest.table') def", "Guest(1, 'first', 'last', default_sound, default_color)) @patch('rfidsecuritysvc.model.guest.table') def test_get(table): table.get.return_value =", "model.create('first', 'last', None, None) is None sound.get.assert_not_called() table.create.assert_called_once_with('first', 'last', None,", "None table.get.assert_called_once_with(1) @patch('rfidsecuritysvc.model.guest.table') def test_list(table): table.list.return_value = [ _default().test_to_row(), _default(2).test_to_row(),", "test_create_no_prefs(table, sound, default_sound): table.create.return_value = None assert model.create('first', 'last', None," ]
[ "directory in consoles.txt then return that. Otherwise, append the shortname", "If the user has specified a custom ROMs directory in", "True # Normalize the extension based on the things we", "a custom ROMs directory in consoles.txt then return that. Otherwise,", "ignore. # Aka capitalization, whitespace, and leading dots normalize =", "config.txt. \"\"\" if console.custom_roms_directory: return console.custom_roms_directory return os.path.join(roms.roms_directory(configuration), console.shortname) def", "Normalize the extension based on the things we validly ignore.", "directory given by config.txt. \"\"\" if console.custom_roms_directory: return console.custom_roms_directory return", "a given path is actually a valid ROM file. If", "the default ROMs directory given by config.txt. \"\"\" if console.custom_roms_directory:", "default ROMs directory given by config.txt. \"\"\" if console.custom_roms_directory: return", "that. Otherwise, append the shortname of the console to the", "(name, ext) = os.path.splitext(path) valid_extensions = console.extensions.split(',') return normalize(ext) in", "function determines if a given path is actually a valid", "return console.custom_roms_directory return os.path.join(roms.roms_directory(configuration), console.shortname) def path_is_rom(console, path): \"\"\" This", "if console.extensions == \"\": return True # Normalize the extension", "and leading dots normalize = lambda ext: ext.lower().strip().lstrip('.') (name, ext)", "no extensions are defined for this console, we just accept", "console to the default ROMs directory given by config.txt. \"\"\"", "just accept any file \"\"\" if console.extensions == \"\": return", "for this console, we check if the path has a", "of the console to the default ROMs directory given by", "ROMs directory given by config.txt. \"\"\" if console.custom_roms_directory: return console.custom_roms_directory", "is actually a valid ROM file. If a list of", "\"\"\" if console.custom_roms_directory: return console.custom_roms_directory return os.path.join(roms.roms_directory(configuration), console.shortname) def path_is_rom(console,", "return True # Normalize the extension based on the things", "any file \"\"\" if console.extensions == \"\": return True #", "return that. Otherwise, append the shortname of the console to", "actually a valid ROM file. If a list of extensions", "If a list of extensions is supplied for this console,", "we just accept any file \"\"\" if console.extensions == \"\":", "by config.txt. \"\"\" if console.custom_roms_directory: return console.custom_roms_directory return os.path.join(roms.roms_directory(configuration), console.shortname)", "validly ignore. # Aka capitalization, whitespace, and leading dots normalize", "we validly ignore. # Aka capitalization, whitespace, and leading dots", "the console to the default ROMs directory given by config.txt.", "user has specified a custom ROMs directory in consoles.txt then", "path): \"\"\" This function determines if a given path is", "import roms def console_roms_directory(configuration, console): \"\"\" If the user has", "in consoles.txt then return that. Otherwise, append the shortname of", "determines if a given path is actually a valid ROM", "def path_is_rom(console, path): \"\"\" This function determines if a given", "console.extensions == \"\": return True # Normalize the extension based", "\"\"\" This function determines if a given path is actually", "check if the path has a valid extension If no", "this console, we just accept any file \"\"\" if console.extensions", "\"\"\" if console.extensions == \"\": return True # Normalize the", "we check if the path has a valid extension If", "If no extensions are defined for this console, we just", "leading dots normalize = lambda ext: ext.lower().strip().lstrip('.') (name, ext) =", "custom ROMs directory in consoles.txt then return that. Otherwise, append", "the extension based on the things we validly ignore. #", "if the path has a valid extension If no extensions", "# Aka capitalization, whitespace, and leading dots normalize = lambda", "the path has a valid extension If no extensions are", "console, we just accept any file \"\"\" if console.extensions ==", "are defined for this console, we just accept any file", "accept any file \"\"\" if console.extensions == \"\": return True", "extension If no extensions are defined for this console, we", "os.path.join(roms.roms_directory(configuration), console.shortname) def path_is_rom(console, path): \"\"\" This function determines if", "import os import roms def console_roms_directory(configuration, console): \"\"\" If the", "This function determines if a given path is actually a", "# encoding: utf-8 import os import roms def console_roms_directory(configuration, console):", "ROMs directory in consoles.txt then return that. Otherwise, append the", "specified a custom ROMs directory in consoles.txt then return that.", "console, we check if the path has a valid extension", "this console, we check if the path has a valid", "dots normalize = lambda ext: ext.lower().strip().lstrip('.') (name, ext) = os.path.splitext(path)", "ext.lower().strip().lstrip('.') (name, ext) = os.path.splitext(path) valid_extensions = console.extensions.split(',') return normalize(ext)", "Otherwise, append the shortname of the console to the default", "has specified a custom ROMs directory in consoles.txt then return", "for this console, we just accept any file \"\"\" if", "os import roms def console_roms_directory(configuration, console): \"\"\" If the user", "to the default ROMs directory given by config.txt. \"\"\" if", "if console.custom_roms_directory: return console.custom_roms_directory return os.path.join(roms.roms_directory(configuration), console.shortname) def path_is_rom(console, path):", "path is actually a valid ROM file. If a list", "a valid ROM file. If a list of extensions is", "extensions is supplied for this console, we check if the", "file. If a list of extensions is supplied for this", "roms def console_roms_directory(configuration, console): \"\"\" If the user has specified", "extension based on the things we validly ignore. # Aka", "then return that. Otherwise, append the shortname of the console", "file \"\"\" if console.extensions == \"\": return True # Normalize", "path has a valid extension If no extensions are defined", "a valid extension If no extensions are defined for this", "encoding: utf-8 import os import roms def console_roms_directory(configuration, console): \"\"\"", "console): \"\"\" If the user has specified a custom ROMs", "if a given path is actually a valid ROM file.", "the things we validly ignore. # Aka capitalization, whitespace, and", "list of extensions is supplied for this console, we check", "things we validly ignore. # Aka capitalization, whitespace, and leading", "a list of extensions is supplied for this console, we", "is supplied for this console, we check if the path", "return os.path.join(roms.roms_directory(configuration), console.shortname) def path_is_rom(console, path): \"\"\" This function determines", "on the things we validly ignore. # Aka capitalization, whitespace,", "has a valid extension If no extensions are defined for", "normalize = lambda ext: ext.lower().strip().lstrip('.') (name, ext) = os.path.splitext(path) valid_extensions", "\"\"\" If the user has specified a custom ROMs directory", "path_is_rom(console, path): \"\"\" This function determines if a given path", "\"\": return True # Normalize the extension based on the", "utf-8 import os import roms def console_roms_directory(configuration, console): \"\"\" If", "consoles.txt then return that. Otherwise, append the shortname of the", "console.custom_roms_directory return os.path.join(roms.roms_directory(configuration), console.shortname) def path_is_rom(console, path): \"\"\" This function", "shortname of the console to the default ROMs directory given", "extensions are defined for this console, we just accept any", "the shortname of the console to the default ROMs directory", "valid extension If no extensions are defined for this console,", "defined for this console, we just accept any file \"\"\"", "of extensions is supplied for this console, we check if", "# Normalize the extension based on the things we validly", "= os.path.splitext(path) valid_extensions = console.extensions.split(',') return normalize(ext) in map(normalize, valid_extensions)", "def console_roms_directory(configuration, console): \"\"\" If the user has specified a", "given by config.txt. \"\"\" if console.custom_roms_directory: return console.custom_roms_directory return os.path.join(roms.roms_directory(configuration),", "== \"\": return True # Normalize the extension based on", "= lambda ext: ext.lower().strip().lstrip('.') (name, ext) = os.path.splitext(path) valid_extensions =", "ext: ext.lower().strip().lstrip('.') (name, ext) = os.path.splitext(path) valid_extensions = console.extensions.split(',') return", "ext) = os.path.splitext(path) valid_extensions = console.extensions.split(',') return normalize(ext) in map(normalize,", "given path is actually a valid ROM file. If a", "console_roms_directory(configuration, console): \"\"\" If the user has specified a custom", "lambda ext: ext.lower().strip().lstrip('.') (name, ext) = os.path.splitext(path) valid_extensions = console.extensions.split(',')", "valid ROM file. If a list of extensions is supplied", "console.custom_roms_directory: return console.custom_roms_directory return os.path.join(roms.roms_directory(configuration), console.shortname) def path_is_rom(console, path): \"\"\"", "whitespace, and leading dots normalize = lambda ext: ext.lower().strip().lstrip('.') (name,", "<reponame>reavessm/Ice<gh_stars>100-1000 # encoding: utf-8 import os import roms def console_roms_directory(configuration,", "console.shortname) def path_is_rom(console, path): \"\"\" This function determines if a", "the user has specified a custom ROMs directory in consoles.txt", "Aka capitalization, whitespace, and leading dots normalize = lambda ext:", "supplied for this console, we check if the path has", "based on the things we validly ignore. # Aka capitalization,", "capitalization, whitespace, and leading dots normalize = lambda ext: ext.lower().strip().lstrip('.')", "append the shortname of the console to the default ROMs", "ROM file. If a list of extensions is supplied for" ]
[ "0. for x_true, y_true in data: y_pred = model.predict(x_true).reshape((-1, num_classes))", "self.best_val_acc = val_acc model.save_weights('weights/c3.weights') print( u'val_acc: %.5f, best_val_acc: %.5f\\n' %", "valid_data += load_data(data_path + 'c3/d-dev.json') class data_generator(DataGenerator): \"\"\"数据生成器 \"\"\" def", "num_classes = 4 maxlen = 512 batch_size = 4 epochs", "in self.sample(random): for c in cs: p_ids = tokenizer.encode(p)[0] q_ids", "output = keras.layers.Dense(units=1, kernel_initializer=base.initializer)(output) model = keras.models.Model(base.model.input, output) model.summary() model.compile(", "sequence_padding, DataGenerator from bert4keras.snippets import open from bert4keras.snippets import truncate_sequences", "y_pred, from_logits=True) ) def multichoice_accuracy(y_true, y_pred): \"\"\"多项选择的准确率 \"\"\" y_true =", "batch_size) valid_generator = data_generator(valid_data, batch_size) def multichoice_crossentropy(y_true, y_pred): \"\"\"多项选择的交叉熵 \"\"\"", "else: a = 0 D.append((p, q, c, a)) return D", "0., 0. for x_true, y_true in data: y_pred = model.predict(x_true).reshape((-1,", "for is_end, (p, q, cs, a) in self.sample(random): for c", "right += (y_true == y_pred).sum() return right / total def", "open(out_file, 'w') with open(in_file) as fr: data = json.load(fr) i", "len(qa['choice']) < num_classes: qa['choice'].append(u'无效答案') c = qa['choice'][:num_classes] if 'answer' in", "Evaluator(keras.callbacks.Callback): \"\"\"保存验证集acc最好的模型 \"\"\" def __init__(self): self.best_val_acc = 0. def on_epoch_end(self,", "+ c_ids batch_token_ids.append(token_ids) batch_segment_ids.append([0] * len(token_ids)) batch_labels.append([a]) if len(batch_token_ids) ==", "\"\"\"保存验证集acc最好的模型 \"\"\" def __init__(self): self.best_val_acc = 0. def on_epoch_end(self, epoch,", "json import numpy as np from snippets import * from", "batch_token_ids, batch_segment_ids, batch_labels = [], [], [] for is_end, (p,", "fw.write(l + '\\n') i += 1 fw.close() if __name__ ==", "load_data(in_file) test_generator = data_generator(test_data, batch_size) results = [] for x_true,", "q = qa['question'] while len(qa['choice']) < num_classes: qa['choice'].append(u'无效答案') c =", "[] with open(filename) as f: data = json.load(f) for d", "y_pred = model.predict(x_true).reshape((-1, num_classes)) y_pred = y_pred.argmax(axis=1) results.extend(y_pred) fw =", "== self.batch_size * num_classes or is_end: batch_token_ids = sequence_padding(batch_token_ids) batch_segment_ids", "(-1, num_classes)) return K.mean( K.sparse_categorical_crossentropy(y_true, y_pred, from_logits=True) ) def multichoice_accuracy(y_true,", "qa['question'] while len(qa['choice']) < num_classes: qa['choice'].append(u'无效答案') c = qa['choice'][:num_classes] if", "multichoice_crossentropy(y_true, y_pred): \"\"\"多项选择的交叉熵 \"\"\" y_true = K.cast(y_true, 'int32')[::num_classes] y_pred =", ") def evaluate(self, data): total, right = 0., 0. for", "from snippets import * from bert4keras.backend import keras from bert4keras.snippets", "qa['choice'][:num_classes] if 'answer' in qa: a = qa['choice'].index(qa['answer']) else: a", "_ in tqdm(test_generator, ncols=0): y_pred = model.predict(x_true).reshape((-1, num_classes)) y_pred =", "axis=1), 'int32') return K.mean(K.cast(K.equal(y_true, y_pred), K.floatx())) # 构建模型 output =", "batch_token_ids.append(token_ids) batch_segment_ids.append([0] * len(token_ids)) batch_labels.append([a]) if len(batch_token_ids) == self.batch_size *", "u'val_acc: %.5f, best_val_acc: %.5f\\n' % (val_acc, self.best_val_acc) ) def evaluate(self,", "= qa['question'] while len(qa['choice']) < num_classes: qa['choice'].append(u'无效答案') c = qa['choice'][:num_classes]", "a = 0 D.append((p, q, c, a)) return D #", "(y_true == y_pred).sum() return right / total def test_predict(in_file, out_file):", "batch_segment_ids, batch_labels = [], [], [] for is_end, (p, q,", "tqdm(test_generator, ncols=0): y_pred = model.predict(x_true).reshape((-1, num_classes)) y_pred = y_pred.argmax(axis=1) results.extend(y_pred)", "fr: data = json.load(fr) i = 0 for d in", "== '__main__': evaluator = Evaluator() model.fit_generator( train_generator.forfit(), steps_per_epoch=len(train_generator), epochs=epochs, callbacks=[evaluator]", "len(token_ids)) batch_labels.append([a]) if len(batch_token_ids) == self.batch_size * num_classes or is_end:", "sequence_padding(batch_segment_ids) batch_labels = sequence_padding(batch_labels) yield [batch_token_ids, batch_segment_ids], batch_labels batch_token_ids, batch_segment_ids,", "= keras.layers.Lambda(lambda x: x[:, 0])(output) output = keras.layers.Dense(units=1, kernel_initializer=base.initializer)(output) model", "答案id)] \"\"\" D = [] with open(filename) as f: data", "\"\"\" test_data = load_data(in_file) test_generator = data_generator(test_data, batch_size) results =", "num_classes: qa['choice'].append(u'无效答案') c = qa['choice'][:num_classes] if 'answer' in qa: a", "import tqdm # 基本参数 num_classes = 4 maxlen = 512", "test_generator = data_generator(test_data, batch_size) results = [] for x_true, _", "CLUE评测 # c3多项选择阅读理解 # 思路:每个选项分别与问题、篇章拼接后打分排序 import json import numpy as", "sequence_padding(batch_token_ids) batch_segment_ids = sequence_padding(batch_segment_ids) batch_labels = sequence_padding(batch_labels) yield [batch_token_ids, batch_segment_ids],", "json.load(f) for d in data: p = u'||'.join(d[0]) for qa", "batch_labels = [], [], [] for is_end, (p, q, cs,", "__init__(self): self.best_val_acc = 0. def on_epoch_end(self, epoch, logs=None): val_acc =", "batch_labels = [], [], [] # 转换数据集 train_generator = data_generator(train_data,", "val_acc > self.best_val_acc: self.best_val_acc = val_acc model.save_weights('weights/c3.weights') print( u'val_acc: %.5f,", "in tqdm(test_generator, ncols=0): y_pred = model.predict(x_true).reshape((-1, num_classes)) y_pred = y_pred.argmax(axis=1)", "思路:每个选项分别与问题、篇章拼接后打分排序 import json import numpy as np from snippets import", "选项, 答案id)] \"\"\" D = [] with open(filename) as f:", "sequence_padding(batch_labels) yield [batch_token_ids, batch_segment_ids], batch_labels batch_token_ids, batch_segment_ids, batch_labels = [],", "self.best_val_acc) ) def evaluate(self, data): total, right = 0., 0.", "/ total def test_predict(in_file, out_file): \"\"\"输出测试结果到文件 结果文件可以提交到 https://www.cluebenchmarks.com 评测。 \"\"\"", "or is_end: batch_token_ids = sequence_padding(batch_token_ids) batch_segment_ids = sequence_padding(batch_segment_ids) batch_labels =", "def test_predict(in_file, out_file): \"\"\"输出测试结果到文件 结果文件可以提交到 https://www.cluebenchmarks.com 评测。 \"\"\" test_data =", "< num_classes: qa['choice'].append(u'无效答案') c = qa['choice'][:num_classes] if 'answer' in qa:", "4 epochs = 10 def load_data(filename): \"\"\"加载数据 格式:[(篇章, 问题, 选项,", "= tokenizer.encode(q)[0][1:] c_ids = tokenizer.encode(c)[0][1:] truncate_sequences(maxlen, -2, c_ids, q_ids, p_ids)", "qa in d[1]: l = json.dumps({'id': str(qa['id']), 'label': str(results[i])}) fw.write(l", "+= 1 fw.close() if __name__ == '__main__': evaluator = Evaluator()", "in data: y_pred = model.predict(x_true).reshape((-1, num_classes)) y_pred = y_pred.argmax(axis=1) y_true", "in qa: a = qa['choice'].index(qa['answer']) else: a = 0 D.append((p,", "c in cs: p_ids = tokenizer.encode(p)[0] q_ids = tokenizer.encode(q)[0][1:] c_ids", "-*- # CLUE评测 # c3多项选择阅读理解 # 思路:每个选项分别与问题、篇章拼接后打分排序 import json import", "# 构建模型 output = base.model.output output = keras.layers.Lambda(lambda x: x[:,", "keras from bert4keras.snippets import sequence_padding, DataGenerator from bert4keras.snippets import open", "model.fit_generator( train_generator.forfit(), steps_per_epoch=len(train_generator), epochs=epochs, callbacks=[evaluator] ) model.load_weights('weights/c3.weights') test_predict( in_file=data_path +", "\"\"\" y_true = K.cast(y_true, 'int32')[::num_classes, 0] y_pred = K.reshape(y_pred, (-1,", "from bert4keras.snippets import truncate_sequences from tqdm import tqdm # 基本参数", "base.model.output output = keras.layers.Lambda(lambda x: x[:, 0])(output) output = keras.layers.Dense(units=1,", "data: for qa in d[1]: l = json.dumps({'id': str(qa['id']), 'label':", "[], [] for is_end, (p, q, cs, a) in self.sample(random):", "batch_segment_ids, batch_labels = [], [], [] # 转换数据集 train_generator =", "model.compile( loss=multichoice_crossentropy, optimizer=optimizer4, metrics=[multichoice_accuracy] ) class Evaluator(keras.callbacks.Callback): \"\"\"保存验证集acc最好的模型 \"\"\" def", "qa: a = qa['choice'].index(qa['answer']) else: a = 0 D.append((p, q,", "'c3/d-train.json') valid_data = load_data(data_path + 'c3/m-dev.json') valid_data += load_data(data_path +", "= K.cast(y_true, 'int32')[::num_classes] y_pred = K.reshape(y_pred, (-1, num_classes)) return K.mean(", "bert4keras.snippets import open from bert4keras.snippets import truncate_sequences from tqdm import", "= val_acc model.save_weights('weights/c3.weights') print( u'val_acc: %.5f, best_val_acc: %.5f\\n' % (val_acc,", "model = keras.models.Model(base.model.input, output) model.summary() model.compile( loss=multichoice_crossentropy, optimizer=optimizer4, metrics=[multichoice_accuracy] )", "qa['choice'].index(qa['answer']) else: a = 0 D.append((p, q, c, a)) return", "batch_segment_ids.append([0] * len(token_ids)) batch_labels.append([a]) if len(batch_token_ids) == self.batch_size * num_classes", "= y_pred.argmax(axis=1) results.extend(y_pred) fw = open(out_file, 'w') with open(in_file) as", "512 batch_size = 4 epochs = 10 def load_data(filename): \"\"\"加载数据", "'c3/d-dev.json') class data_generator(DataGenerator): \"\"\"数据生成器 \"\"\" def __iter__(self, random=False): batch_token_ids, batch_segment_ids,", "in data: p = u'||'.join(d[0]) for qa in d[1]: q", "data = json.load(fr) i = 0 for d in data:", "[] for is_end, (p, q, cs, a) in self.sample(random): for", "batch_size) results = [] for x_true, _ in tqdm(test_generator, ncols=0):", "fw = open(out_file, 'w') with open(in_file) as fr: data =", "train_data = load_data(data_path + 'c3/m-train.json') train_data += load_data(data_path + 'c3/d-train.json')", "if 'answer' in qa: a = qa['choice'].index(qa['answer']) else: a =", "as np from snippets import * from bert4keras.backend import keras", "= keras.models.Model(base.model.input, output) model.summary() model.compile( loss=multichoice_crossentropy, optimizer=optimizer4, metrics=[multichoice_accuracy] ) class", "len(y_true) right += (y_true == y_pred).sum() return right / total", "keras.layers.Dense(units=1, kernel_initializer=base.initializer)(output) model = keras.models.Model(base.model.input, output) model.summary() model.compile( loss=multichoice_crossentropy, optimizer=optimizer4,", "fw.close() if __name__ == '__main__': evaluator = Evaluator() model.fit_generator( train_generator.forfit(),", "y_pred).sum() return right / total def test_predict(in_file, out_file): \"\"\"输出测试结果到文件 结果文件可以提交到", "results.extend(y_pred) fw = open(out_file, 'w') with open(in_file) as fr: data", ") model.load_weights('weights/c3.weights') test_predict( in_file=data_path + 'c3/test1.0.json', out_file='results/c310_predict.json' ) test_predict( in_file=data_path", "d in data: for qa in d[1]: l = json.dumps({'id':", "-*- coding:utf-8 -*- # CLUE评测 # c3多项选择阅读理解 # 思路:每个选项分别与问题、篇章拼接后打分排序 import", ") class Evaluator(keras.callbacks.Callback): \"\"\"保存验证集acc最好的模型 \"\"\" def __init__(self): self.best_val_acc = 0.", "batch_token_ids, batch_segment_ids, batch_labels = [], [], [] # 转换数据集 train_generator", "on_epoch_end(self, epoch, logs=None): val_acc = self.evaluate(valid_generator) if val_acc > self.best_val_acc:", "y_true = K.cast(y_true, 'int32')[::num_classes] y_pred = K.reshape(y_pred, (-1, num_classes)) return", "load_data(data_path + 'c3/d-train.json') valid_data = load_data(data_path + 'c3/m-dev.json') valid_data +=", "train_data += load_data(data_path + 'c3/d-train.json') valid_data = load_data(data_path + 'c3/m-dev.json')", "+ 'c3/d-train.json') valid_data = load_data(data_path + 'c3/m-dev.json') valid_data += load_data(data_path", "keras.layers.Lambda(lambda x: x[:, 0])(output) output = keras.layers.Dense(units=1, kernel_initializer=base.initializer)(output) model =", "= data_generator(valid_data, batch_size) def multichoice_crossentropy(y_true, y_pred): \"\"\"多项选择的交叉熵 \"\"\" y_true =", "data: p = u'||'.join(d[0]) for qa in d[1]: q =", "num_classes or is_end: batch_token_ids = sequence_padding(batch_token_ids) batch_segment_ids = sequence_padding(batch_segment_ids) batch_labels", "return K.mean( K.sparse_categorical_crossentropy(y_true, y_pred, from_logits=True) ) def multichoice_accuracy(y_true, y_pred): \"\"\"多项选择的准确率", "K.reshape(y_pred, (-1, num_classes)) return K.mean( K.sparse_categorical_crossentropy(y_true, y_pred, from_logits=True) ) def", "0 D.append((p, q, c, a)) return D # 加载数据集 train_data", "i = 0 for d in data: for qa in", "= K.cast(K.argmax(y_pred, axis=1), 'int32') return K.mean(K.cast(K.equal(y_true, y_pred), K.floatx())) # 构建模型", "data): total, right = 0., 0. for x_true, y_true in", "* len(token_ids)) batch_labels.append([a]) if len(batch_token_ids) == self.batch_size * num_classes or", "y_pred = model.predict(x_true).reshape((-1, num_classes)) y_pred = y_pred.argmax(axis=1) y_true = y_true[::num_classes,", "logs=None): val_acc = self.evaluate(valid_generator) if val_acc > self.best_val_acc: self.best_val_acc =", "epochs = 10 def load_data(filename): \"\"\"加载数据 格式:[(篇章, 问题, 选项, 答案id)]", "c_ids = tokenizer.encode(c)[0][1:] truncate_sequences(maxlen, -2, c_ids, q_ids, p_ids) token_ids =", "maxlen = 512 batch_size = 4 epochs = 10 def", "10 def load_data(filename): \"\"\"加载数据 格式:[(篇章, 问题, 选项, 答案id)] \"\"\" D", "= 0 for d in data: for qa in d[1]:", "load_data(data_path + 'c3/m-dev.json') valid_data += load_data(data_path + 'c3/d-dev.json') class data_generator(DataGenerator):", "= tokenizer.encode(p)[0] q_ids = tokenizer.encode(q)[0][1:] c_ids = tokenizer.encode(c)[0][1:] truncate_sequences(maxlen, -2,", "p_ids) token_ids = p_ids + q_ids + c_ids batch_token_ids.append(token_ids) batch_segment_ids.append([0]", "'int32') return K.mean(K.cast(K.equal(y_true, y_pred), K.floatx())) # 构建模型 output = base.model.output", "= data_generator(train_data, batch_size) valid_generator = data_generator(valid_data, batch_size) def multichoice_crossentropy(y_true, y_pred):", "x_true, y_true in data: y_pred = model.predict(x_true).reshape((-1, num_classes)) y_pred =", "model.load_weights('weights/c3.weights') test_predict( in_file=data_path + 'c3/test1.0.json', out_file='results/c310_predict.json' ) test_predict( in_file=data_path +", "\"\"\" D = [] with open(filename) as f: data =", "> self.best_val_acc: self.best_val_acc = val_acc model.save_weights('weights/c3.weights') print( u'val_acc: %.5f, best_val_acc:", "num_classes)) y_pred = K.cast(K.argmax(y_pred, axis=1), 'int32') return K.mean(K.cast(K.equal(y_true, y_pred), K.floatx()))", "batch_token_ids = sequence_padding(batch_token_ids) batch_segment_ids = sequence_padding(batch_segment_ids) batch_labels = sequence_padding(batch_labels) yield", "\"\"\"多项选择的交叉熵 \"\"\" y_true = K.cast(y_true, 'int32')[::num_classes] y_pred = K.reshape(y_pred, (-1,", "u'||'.join(d[0]) for qa in d[1]: q = qa['question'] while len(qa['choice'])", "import truncate_sequences from tqdm import tqdm # 基本参数 num_classes =", "= Evaluator() model.fit_generator( train_generator.forfit(), steps_per_epoch=len(train_generator), epochs=epochs, callbacks=[evaluator] ) model.load_weights('weights/c3.weights') test_predict(", "load_data(data_path + 'c3/m-train.json') train_data += load_data(data_path + 'c3/d-train.json') valid_data =", "= load_data(in_file) test_generator = data_generator(test_data, batch_size) results = [] for", "with open(in_file) as fr: data = json.load(fr) i = 0", "f: data = json.load(f) for d in data: p =", "in data: for qa in d[1]: l = json.dumps({'id': str(qa['id']),", "D.append((p, q, c, a)) return D # 加载数据集 train_data =", "K.mean( K.sparse_categorical_crossentropy(y_true, y_pred, from_logits=True) ) def multichoice_accuracy(y_true, y_pred): \"\"\"多项选择的准确率 \"\"\"", "output) model.summary() model.compile( loss=multichoice_crossentropy, optimizer=optimizer4, metrics=[multichoice_accuracy] ) class Evaluator(keras.callbacks.Callback): \"\"\"保存验证集acc最好的模型", "str(qa['id']), 'label': str(results[i])}) fw.write(l + '\\n') i += 1 fw.close()", "from_logits=True) ) def multichoice_accuracy(y_true, y_pred): \"\"\"多项选择的准确率 \"\"\" y_true = K.cast(y_true,", "tokenizer.encode(q)[0][1:] c_ids = tokenizer.encode(c)[0][1:] truncate_sequences(maxlen, -2, c_ids, q_ids, p_ids) token_ids", "epochs=epochs, callbacks=[evaluator] ) model.load_weights('weights/c3.weights') test_predict( in_file=data_path + 'c3/test1.0.json', out_file='results/c310_predict.json' )", "import open from bert4keras.snippets import truncate_sequences from tqdm import tqdm", "p_ids = tokenizer.encode(p)[0] q_ids = tokenizer.encode(q)[0][1:] c_ids = tokenizer.encode(c)[0][1:] truncate_sequences(maxlen,", "= data_generator(test_data, batch_size) results = [] for x_true, _ in", "tokenizer.encode(c)[0][1:] truncate_sequences(maxlen, -2, c_ids, q_ids, p_ids) token_ids = p_ids +", "token_ids = p_ids + q_ids + c_ids batch_token_ids.append(token_ids) batch_segment_ids.append([0] *", "# 加载数据集 train_data = load_data(data_path + 'c3/m-train.json') train_data += load_data(data_path", "class data_generator(DataGenerator): \"\"\"数据生成器 \"\"\" def __iter__(self, random=False): batch_token_ids, batch_segment_ids, batch_labels", "__iter__(self, random=False): batch_token_ids, batch_segment_ids, batch_labels = [], [], [] for", "%.5f\\n' % (val_acc, self.best_val_acc) ) def evaluate(self, data): total, right", "epoch, logs=None): val_acc = self.evaluate(valid_generator) if val_acc > self.best_val_acc: self.best_val_acc", "= 4 maxlen = 512 batch_size = 4 epochs =", "4 maxlen = 512 batch_size = 4 epochs = 10", "open from bert4keras.snippets import truncate_sequences from tqdm import tqdm #", "K.sparse_categorical_crossentropy(y_true, y_pred, from_logits=True) ) def multichoice_accuracy(y_true, y_pred): \"\"\"多项选择的准确率 \"\"\" y_true", "d[1]: l = json.dumps({'id': str(qa['id']), 'label': str(results[i])}) fw.write(l + '\\n')", "K.mean(K.cast(K.equal(y_true, y_pred), K.floatx())) # 构建模型 output = base.model.output output =", "train_generator.forfit(), steps_per_epoch=len(train_generator), epochs=epochs, callbacks=[evaluator] ) model.load_weights('weights/c3.weights') test_predict( in_file=data_path + 'c3/test1.0.json',", "= json.load(f) for d in data: p = u'||'.join(d[0]) for", "K.cast(y_true, 'int32')[::num_classes] y_pred = K.reshape(y_pred, (-1, num_classes)) return K.mean( K.sparse_categorical_crossentropy(y_true,", "total += len(y_true) right += (y_true == y_pred).sum() return right", "coding:utf-8 -*- # CLUE评测 # c3多项选择阅读理解 # 思路:每个选项分别与问题、篇章拼接后打分排序 import json", "格式:[(篇章, 问题, 选项, 答案id)] \"\"\" D = [] with open(filename)", "in_file=data_path + 'c3/test1.0.json', out_file='results/c310_predict.json' ) test_predict( in_file=data_path + 'c3/test1.1.json', out_file='results/c311_predict.json'", "= K.cast(y_true, 'int32')[::num_classes, 0] y_pred = K.reshape(y_pred, (-1, num_classes)) y_pred", "return K.mean(K.cast(K.equal(y_true, y_pred), K.floatx())) # 构建模型 output = base.model.output output", "def __init__(self): self.best_val_acc = 0. def on_epoch_end(self, epoch, logs=None): val_acc", "x_true, _ in tqdm(test_generator, ncols=0): y_pred = model.predict(x_true).reshape((-1, num_classes)) y_pred", "kernel_initializer=base.initializer)(output) model = keras.models.Model(base.model.input, output) model.summary() model.compile( loss=multichoice_crossentropy, optimizer=optimizer4, metrics=[multichoice_accuracy]", "* from bert4keras.backend import keras from bert4keras.snippets import sequence_padding, DataGenerator", "snippets import * from bert4keras.backend import keras from bert4keras.snippets import", "= load_data(data_path + 'c3/m-train.json') train_data += load_data(data_path + 'c3/d-train.json') valid_data", "= sequence_padding(batch_token_ids) batch_segment_ids = sequence_padding(batch_segment_ids) batch_labels = sequence_padding(batch_labels) yield [batch_token_ids,", "test_data = load_data(in_file) test_generator = data_generator(test_data, batch_size) results = []", "= p_ids + q_ids + c_ids batch_token_ids.append(token_ids) batch_segment_ids.append([0] * len(token_ids))", "\"\"\" y_true = K.cast(y_true, 'int32')[::num_classes] y_pred = K.reshape(y_pred, (-1, num_classes))", "y_true[::num_classes, 0] total += len(y_true) right += (y_true == y_pred).sum()", "y_pred), K.floatx())) # 构建模型 output = base.model.output output = keras.layers.Lambda(lambda", "tqdm import tqdm # 基本参数 num_classes = 4 maxlen =", "batch_size = 4 epochs = 10 def load_data(filename): \"\"\"加载数据 格式:[(篇章,", "= K.reshape(y_pred, (-1, num_classes)) return K.mean( K.sparse_categorical_crossentropy(y_true, y_pred, from_logits=True) )", "[], [], [] # 转换数据集 train_generator = data_generator(train_data, batch_size) valid_generator", "steps_per_epoch=len(train_generator), epochs=epochs, callbacks=[evaluator] ) model.load_weights('weights/c3.weights') test_predict( in_file=data_path + 'c3/test1.0.json', out_file='results/c310_predict.json'", "with open(filename) as f: data = json.load(f) for d in", "valid_data = load_data(data_path + 'c3/m-dev.json') valid_data += load_data(data_path + 'c3/d-dev.json')", "data: y_pred = model.predict(x_true).reshape((-1, num_classes)) y_pred = y_pred.argmax(axis=1) y_true =", "def evaluate(self, data): total, right = 0., 0. for x_true,", "data_generator(train_data, batch_size) valid_generator = data_generator(valid_data, batch_size) def multichoice_crossentropy(y_true, y_pred): \"\"\"多项选择的交叉熵", "self.batch_size * num_classes or is_end: batch_token_ids = sequence_padding(batch_token_ids) batch_segment_ids =", "y_pred.argmax(axis=1) y_true = y_true[::num_classes, 0] total += len(y_true) right +=", "self.best_val_acc = 0. def on_epoch_end(self, epoch, logs=None): val_acc = self.evaluate(valid_generator)", "cs: p_ids = tokenizer.encode(p)[0] q_ids = tokenizer.encode(q)[0][1:] c_ids = tokenizer.encode(c)[0][1:]", "0])(output) output = keras.layers.Dense(units=1, kernel_initializer=base.initializer)(output) model = keras.models.Model(base.model.input, output) model.summary()", "D # 加载数据集 train_data = load_data(data_path + 'c3/m-train.json') train_data +=", "multichoice_accuracy(y_true, y_pred): \"\"\"多项选择的准确率 \"\"\" y_true = K.cast(y_true, 'int32')[::num_classes, 0] y_pred", "results = [] for x_true, _ in tqdm(test_generator, ncols=0): y_pred", "= json.load(fr) i = 0 for d in data: for", "= sequence_padding(batch_labels) yield [batch_token_ids, batch_segment_ids], batch_labels batch_token_ids, batch_segment_ids, batch_labels =", "as f: data = json.load(f) for d in data: p", "= open(out_file, 'w') with open(in_file) as fr: data = json.load(fr)", "= 10 def load_data(filename): \"\"\"加载数据 格式:[(篇章, 问题, 选项, 答案id)] \"\"\"", "= tokenizer.encode(c)[0][1:] truncate_sequences(maxlen, -2, c_ids, q_ids, p_ids) token_ids = p_ids", "1 fw.close() if __name__ == '__main__': evaluator = Evaluator() model.fit_generator(", "metrics=[multichoice_accuracy] ) class Evaluator(keras.callbacks.Callback): \"\"\"保存验证集acc最好的模型 \"\"\" def __init__(self): self.best_val_acc =", "a) in self.sample(random): for c in cs: p_ids = tokenizer.encode(p)[0]", "from bert4keras.backend import keras from bert4keras.snippets import sequence_padding, DataGenerator from", "DataGenerator from bert4keras.snippets import open from bert4keras.snippets import truncate_sequences from", "p_ids + q_ids + c_ids batch_token_ids.append(token_ids) batch_segment_ids.append([0] * len(token_ids)) batch_labels.append([a])", "test_predict(in_file, out_file): \"\"\"输出测试结果到文件 结果文件可以提交到 https://www.cluebenchmarks.com 评测。 \"\"\" test_data = load_data(in_file)", "total def test_predict(in_file, out_file): \"\"\"输出测试结果到文件 结果文件可以提交到 https://www.cluebenchmarks.com 评测。 \"\"\" test_data", "from bert4keras.snippets import open from bert4keras.snippets import truncate_sequences from tqdm", "evaluator = Evaluator() model.fit_generator( train_generator.forfit(), steps_per_epoch=len(train_generator), epochs=epochs, callbacks=[evaluator] ) model.load_weights('weights/c3.weights')", "data_generator(DataGenerator): \"\"\"数据生成器 \"\"\" def __iter__(self, random=False): batch_token_ids, batch_segment_ids, batch_labels =", "valid_generator = data_generator(valid_data, batch_size) def multichoice_crossentropy(y_true, y_pred): \"\"\"多项选择的交叉熵 \"\"\" y_true", "= model.predict(x_true).reshape((-1, num_classes)) y_pred = y_pred.argmax(axis=1) results.extend(y_pred) fw = open(out_file,", "num_classes)) y_pred = y_pred.argmax(axis=1) results.extend(y_pred) fw = open(out_file, 'w') with", "= y_pred.argmax(axis=1) y_true = y_true[::num_classes, 0] total += len(y_true) right", "batch_size) def multichoice_crossentropy(y_true, y_pred): \"\"\"多项选择的交叉熵 \"\"\" y_true = K.cast(y_true, 'int32')[::num_classes]", "'int32')[::num_classes, 0] y_pred = K.reshape(y_pred, (-1, num_classes)) y_pred = K.cast(K.argmax(y_pred,", "q, c, a)) return D # 加载数据集 train_data = load_data(data_path", "[] # 转换数据集 train_generator = data_generator(train_data, batch_size) valid_generator = data_generator(valid_data,", "https://www.cluebenchmarks.com 评测。 \"\"\" test_data = load_data(in_file) test_generator = data_generator(test_data, batch_size)", "# 思路:每个选项分别与问题、篇章拼接后打分排序 import json import numpy as np from snippets", "= model.predict(x_true).reshape((-1, num_classes)) y_pred = y_pred.argmax(axis=1) y_true = y_true[::num_classes, 0]", "if val_acc > self.best_val_acc: self.best_val_acc = val_acc model.save_weights('weights/c3.weights') print( u'val_acc:", "__name__ == '__main__': evaluator = Evaluator() model.fit_generator( train_generator.forfit(), steps_per_epoch=len(train_generator), epochs=epochs,", "import * from bert4keras.backend import keras from bert4keras.snippets import sequence_padding,", "evaluate(self, data): total, right = 0., 0. for x_true, y_true", "for c in cs: p_ids = tokenizer.encode(p)[0] q_ids = tokenizer.encode(q)[0][1:]", "qa['choice'].append(u'无效答案') c = qa['choice'][:num_classes] if 'answer' in qa: a =", "q_ids, p_ids) token_ids = p_ids + q_ids + c_ids batch_token_ids.append(token_ids)", "def multichoice_accuracy(y_true, y_pred): \"\"\"多项选择的准确率 \"\"\" y_true = K.cast(y_true, 'int32')[::num_classes, 0]", "import numpy as np from snippets import * from bert4keras.backend", "= y_true[::num_classes, 0] total += len(y_true) right += (y_true ==", "open(filename) as f: data = json.load(f) for d in data:", "[batch_token_ids, batch_segment_ids], batch_labels batch_token_ids, batch_segment_ids, batch_labels = [], [], []", "= base.model.output output = keras.layers.Lambda(lambda x: x[:, 0])(output) output =", "np from snippets import * from bert4keras.backend import keras from", "val_acc model.save_weights('weights/c3.weights') print( u'val_acc: %.5f, best_val_acc: %.5f\\n' % (val_acc, self.best_val_acc)", "K.cast(y_true, 'int32')[::num_classes, 0] y_pred = K.reshape(y_pred, (-1, num_classes)) y_pred =", "[], [] # 转换数据集 train_generator = data_generator(train_data, batch_size) valid_generator =", "out_file): \"\"\"输出测试结果到文件 结果文件可以提交到 https://www.cluebenchmarks.com 评测。 \"\"\" test_data = load_data(in_file) test_generator", "right / total def test_predict(in_file, out_file): \"\"\"输出测试结果到文件 结果文件可以提交到 https://www.cluebenchmarks.com 评测。", "batch_labels.append([a]) if len(batch_token_ids) == self.batch_size * num_classes or is_end: batch_token_ids", "= 512 batch_size = 4 epochs = 10 def load_data(filename):", "== y_pred).sum() return right / total def test_predict(in_file, out_file): \"\"\"输出测试结果到文件", "= [], [], [] for is_end, (p, q, cs, a)", "batch_labels = sequence_padding(batch_labels) yield [batch_token_ids, batch_segment_ids], batch_labels batch_token_ids, batch_segment_ids, batch_labels", "(p, q, cs, a) in self.sample(random): for c in cs:", "= sequence_padding(batch_segment_ids) batch_labels = sequence_padding(batch_labels) yield [batch_token_ids, batch_segment_ids], batch_labels batch_token_ids,", "# CLUE评测 # c3多项选择阅读理解 # 思路:每个选项分别与问题、篇章拼接后打分排序 import json import numpy", "= qa['choice'].index(qa['answer']) else: a = 0 D.append((p, q, c, a))", "bert4keras.backend import keras from bert4keras.snippets import sequence_padding, DataGenerator from bert4keras.snippets", "data = json.load(f) for d in data: p = u'||'.join(d[0])", "+ q_ids + c_ids batch_token_ids.append(token_ids) batch_segment_ids.append([0] * len(token_ids)) batch_labels.append([a]) if", "+= len(y_true) right += (y_true == y_pred).sum() return right /", "(val_acc, self.best_val_acc) ) def evaluate(self, data): total, right = 0.,", "numpy as np from snippets import * from bert4keras.backend import", "= keras.layers.Dense(units=1, kernel_initializer=base.initializer)(output) model = keras.models.Model(base.model.input, output) model.summary() model.compile( loss=multichoice_crossentropy,", "from tqdm import tqdm # 基本参数 num_classes = 4 maxlen", "= json.dumps({'id': str(qa['id']), 'label': str(results[i])}) fw.write(l + '\\n') i +=", "+ 'c3/test1.0.json', out_file='results/c310_predict.json' ) test_predict( in_file=data_path + 'c3/test1.1.json', out_file='results/c311_predict.json' )", "len(batch_token_ids) == self.batch_size * num_classes or is_end: batch_token_ids = sequence_padding(batch_token_ids)", "d[1]: q = qa['question'] while len(qa['choice']) < num_classes: qa['choice'].append(u'无效答案') c", "import keras from bert4keras.snippets import sequence_padding, DataGenerator from bert4keras.snippets import", "y_pred): \"\"\"多项选择的交叉熵 \"\"\" y_true = K.cast(y_true, 'int32')[::num_classes] y_pred = K.reshape(y_pred,", "\"\"\"数据生成器 \"\"\" def __iter__(self, random=False): batch_token_ids, batch_segment_ids, batch_labels = [],", "num_classes)) return K.mean( K.sparse_categorical_crossentropy(y_true, y_pred, from_logits=True) ) def multichoice_accuracy(y_true, y_pred):", "= load_data(data_path + 'c3/m-dev.json') valid_data += load_data(data_path + 'c3/d-dev.json') class", "for x_true, y_true in data: y_pred = model.predict(x_true).reshape((-1, num_classes)) y_pred", "评测。 \"\"\" test_data = load_data(in_file) test_generator = data_generator(test_data, batch_size) results", "'int32')[::num_classes] y_pred = K.reshape(y_pred, (-1, num_classes)) return K.mean( K.sparse_categorical_crossentropy(y_true, y_pred,", "0] y_pred = K.reshape(y_pred, (-1, num_classes)) y_pred = K.cast(K.argmax(y_pred, axis=1),", "-2, c_ids, q_ids, p_ids) token_ids = p_ids + q_ids +", "model.summary() model.compile( loss=multichoice_crossentropy, optimizer=optimizer4, metrics=[multichoice_accuracy] ) class Evaluator(keras.callbacks.Callback): \"\"\"保存验证集acc最好的模型 \"\"\"", "num_classes)) y_pred = y_pred.argmax(axis=1) y_true = y_true[::num_classes, 0] total +=", "c = qa['choice'][:num_classes] if 'answer' in qa: a = qa['choice'].index(qa['answer'])", "a)) return D # 加载数据集 train_data = load_data(data_path + 'c3/m-train.json')", "right = 0., 0. for x_true, y_true in data: y_pred", "loss=multichoice_crossentropy, optimizer=optimizer4, metrics=[multichoice_accuracy] ) class Evaluator(keras.callbacks.Callback): \"\"\"保存验证集acc最好的模型 \"\"\" def __init__(self):", "a = qa['choice'].index(qa['answer']) else: a = 0 D.append((p, q, c,", "+ 'c3/m-train.json') train_data += load_data(data_path + 'c3/d-train.json') valid_data = load_data(data_path", "q, cs, a) in self.sample(random): for c in cs: p_ids", ") def multichoice_accuracy(y_true, y_pred): \"\"\"多项选择的准确率 \"\"\" y_true = K.cast(y_true, 'int32')[::num_classes,", "for d in data: p = u'||'.join(d[0]) for qa in", "for x_true, _ in tqdm(test_generator, ncols=0): y_pred = model.predict(x_true).reshape((-1, num_classes))", "data_generator(valid_data, batch_size) def multichoice_crossentropy(y_true, y_pred): \"\"\"多项选择的交叉熵 \"\"\" y_true = K.cast(y_true,", "Evaluator() model.fit_generator( train_generator.forfit(), steps_per_epoch=len(train_generator), epochs=epochs, callbacks=[evaluator] ) model.load_weights('weights/c3.weights') test_predict( in_file=data_path", "= 4 epochs = 10 def load_data(filename): \"\"\"加载数据 格式:[(篇章, 问题,", "output = base.model.output output = keras.layers.Lambda(lambda x: x[:, 0])(output) output", "'\\n') i += 1 fw.close() if __name__ == '__main__': evaluator", "return right / total def test_predict(in_file, out_file): \"\"\"输出测试结果到文件 结果文件可以提交到 https://www.cluebenchmarks.com", "'c3/m-dev.json') valid_data += load_data(data_path + 'c3/d-dev.json') class data_generator(DataGenerator): \"\"\"数据生成器 \"\"\"", "'c3/test1.0.json', out_file='results/c310_predict.json' ) test_predict( in_file=data_path + 'c3/test1.1.json', out_file='results/c311_predict.json' ) else:", "x[:, 0])(output) output = keras.layers.Dense(units=1, kernel_initializer=base.initializer)(output) model = keras.models.Model(base.model.input, output)", "y_pred = K.cast(K.argmax(y_pred, axis=1), 'int32') return K.mean(K.cast(K.equal(y_true, y_pred), K.floatx())) #", "y_pred = y_pred.argmax(axis=1) y_true = y_true[::num_classes, 0] total += len(y_true)", "'__main__': evaluator = Evaluator() model.fit_generator( train_generator.forfit(), steps_per_epoch=len(train_generator), epochs=epochs, callbacks=[evaluator] )", "class Evaluator(keras.callbacks.Callback): \"\"\"保存验证集acc最好的模型 \"\"\" def __init__(self): self.best_val_acc = 0. def", "+= (y_true == y_pred).sum() return right / total def test_predict(in_file,", "y_pred = K.reshape(y_pred, (-1, num_classes)) y_pred = K.cast(K.argmax(y_pred, axis=1), 'int32')", "# 基本参数 num_classes = 4 maxlen = 512 batch_size =", "= [] with open(filename) as f: data = json.load(f) for", "batch_segment_ids], batch_labels batch_token_ids, batch_segment_ids, batch_labels = [], [], [] #", "data_generator(test_data, batch_size) results = [] for x_true, _ in tqdm(test_generator,", "train_generator = data_generator(train_data, batch_size) valid_generator = data_generator(valid_data, batch_size) def multichoice_crossentropy(y_true,", "json.dumps({'id': str(qa['id']), 'label': str(results[i])}) fw.write(l + '\\n') i += 1", "= 0 D.append((p, q, c, a)) return D # 加载数据集", "% (val_acc, self.best_val_acc) ) def evaluate(self, data): total, right =", "\"\"\"输出测试结果到文件 结果文件可以提交到 https://www.cluebenchmarks.com 评测。 \"\"\" test_data = load_data(in_file) test_generator =", "加载数据集 train_data = load_data(data_path + 'c3/m-train.json') train_data += load_data(data_path +", "bert4keras.snippets import sequence_padding, DataGenerator from bert4keras.snippets import open from bert4keras.snippets", "batch_labels batch_token_ids, batch_segment_ids, batch_labels = [], [], [] # 转换数据集", "\"\"\" def __iter__(self, random=False): batch_token_ids, batch_segment_ids, batch_labels = [], [],", "'answer' in qa: a = qa['choice'].index(qa['answer']) else: a = 0", "D = [] with open(filename) as f: data = json.load(f)", "y_pred): \"\"\"多项选择的准确率 \"\"\" y_true = K.cast(y_true, 'int32')[::num_classes, 0] y_pred =", "def load_data(filename): \"\"\"加载数据 格式:[(篇章, 问题, 选项, 答案id)] \"\"\" D =", "0. def on_epoch_end(self, epoch, logs=None): val_acc = self.evaluate(valid_generator) if val_acc", "qa in d[1]: q = qa['question'] while len(qa['choice']) < num_classes:", "test_predict( in_file=data_path + 'c3/test1.0.json', out_file='results/c310_predict.json' ) test_predict( in_file=data_path + 'c3/test1.1.json',", "in d[1]: l = json.dumps({'id': str(qa['id']), 'label': str(results[i])}) fw.write(l +", "* num_classes or is_end: batch_token_ids = sequence_padding(batch_token_ids) batch_segment_ids = sequence_padding(batch_segment_ids)", "\"\"\"多项选择的准确率 \"\"\" y_true = K.cast(y_true, 'int32')[::num_classes, 0] y_pred = K.reshape(y_pred,", "'c3/m-train.json') train_data += load_data(data_path + 'c3/d-train.json') valid_data = load_data(data_path +", "from bert4keras.snippets import sequence_padding, DataGenerator from bert4keras.snippets import open from", "c, a)) return D # 加载数据集 train_data = load_data(data_path +", "tqdm # 基本参数 num_classes = 4 maxlen = 512 batch_size", "(-1, num_classes)) y_pred = K.cast(K.argmax(y_pred, axis=1), 'int32') return K.mean(K.cast(K.equal(y_true, y_pred),", "if __name__ == '__main__': evaluator = Evaluator() model.fit_generator( train_generator.forfit(), steps_per_epoch=len(train_generator),", "c_ids, q_ids, p_ids) token_ids = p_ids + q_ids + c_ids", "0 for d in data: for qa in d[1]: l", "c_ids batch_token_ids.append(token_ids) batch_segment_ids.append([0] * len(token_ids)) batch_labels.append([a]) if len(batch_token_ids) == self.batch_size", "is_end: batch_token_ids = sequence_padding(batch_token_ids) batch_segment_ids = sequence_padding(batch_segment_ids) batch_labels = sequence_padding(batch_labels)", "total, right = 0., 0. for x_true, y_true in data:", "'w') with open(in_file) as fr: data = json.load(fr) i =", "y_true in data: y_pred = model.predict(x_true).reshape((-1, num_classes)) y_pred = y_pred.argmax(axis=1)", "= self.evaluate(valid_generator) if val_acc > self.best_val_acc: self.best_val_acc = val_acc model.save_weights('weights/c3.weights')", "for d in data: for qa in d[1]: l =", "out_file='results/c310_predict.json' ) test_predict( in_file=data_path + 'c3/test1.1.json', out_file='results/c311_predict.json' ) else: model.load_weights('weights/c3.weights')", "x: x[:, 0])(output) output = keras.layers.Dense(units=1, kernel_initializer=base.initializer)(output) model = keras.models.Model(base.model.input,", "'label': str(results[i])}) fw.write(l + '\\n') i += 1 fw.close() if", "output = keras.layers.Lambda(lambda x: x[:, 0])(output) output = keras.layers.Dense(units=1, kernel_initializer=base.initializer)(output)", "q_ids = tokenizer.encode(q)[0][1:] c_ids = tokenizer.encode(c)[0][1:] truncate_sequences(maxlen, -2, c_ids, q_ids,", "0] total += len(y_true) right += (y_true == y_pred).sum() return", "p = u'||'.join(d[0]) for qa in d[1]: q = qa['question']", "y_pred.argmax(axis=1) results.extend(y_pred) fw = open(out_file, 'w') with open(in_file) as fr:", "\"\"\" def __init__(self): self.best_val_acc = 0. def on_epoch_end(self, epoch, logs=None):", "in cs: p_ids = tokenizer.encode(p)[0] q_ids = tokenizer.encode(q)[0][1:] c_ids =", "for qa in d[1]: l = json.dumps({'id': str(qa['id']), 'label': str(results[i])})", "return D # 加载数据集 train_data = load_data(data_path + 'c3/m-train.json') train_data", "def multichoice_crossentropy(y_true, y_pred): \"\"\"多项选择的交叉熵 \"\"\" y_true = K.cast(y_true, 'int32')[::num_classes] y_pred", "cs, a) in self.sample(random): for c in cs: p_ids =", "\"\"\"加载数据 格式:[(篇章, 问题, 选项, 答案id)] \"\"\" D = [] with", "ncols=0): y_pred = model.predict(x_true).reshape((-1, num_classes)) y_pred = y_pred.argmax(axis=1) results.extend(y_pred) fw", "as fr: data = json.load(fr) i = 0 for d", "open(in_file) as fr: data = json.load(fr) i = 0 for", "# c3多项选择阅读理解 # 思路:每个选项分别与问题、篇章拼接后打分排序 import json import numpy as np", "= K.reshape(y_pred, (-1, num_classes)) y_pred = K.cast(K.argmax(y_pred, axis=1), 'int32') return", "# 转换数据集 train_generator = data_generator(train_data, batch_size) valid_generator = data_generator(valid_data, batch_size)", "import json import numpy as np from snippets import *", "[] for x_true, _ in tqdm(test_generator, ncols=0): y_pred = model.predict(x_true).reshape((-1,", "print( u'val_acc: %.5f, best_val_acc: %.5f\\n' % (val_acc, self.best_val_acc) ) def", "基本参数 num_classes = 4 maxlen = 512 batch_size = 4", "y_pred = K.reshape(y_pred, (-1, num_classes)) return K.mean( K.sparse_categorical_crossentropy(y_true, y_pred, from_logits=True)", "y_true = K.cast(y_true, 'int32')[::num_classes, 0] y_pred = K.reshape(y_pred, (-1, num_classes))", "self.sample(random): for c in cs: p_ids = tokenizer.encode(p)[0] q_ids =", "c3多项选择阅读理解 # 思路:每个选项分别与问题、篇章拼接后打分排序 import json import numpy as np from", "<filename>clue/c3.py #! -*- coding:utf-8 -*- # CLUE评测 # c3多项选择阅读理解 #", "#! -*- coding:utf-8 -*- # CLUE评测 # c3多项选择阅读理解 # 思路:每个选项分别与问题、篇章拼接后打分排序", "y_true = y_true[::num_classes, 0] total += len(y_true) right += (y_true", "def __iter__(self, random=False): batch_token_ids, batch_segment_ids, batch_labels = [], [], []", "= 0., 0. for x_true, y_true in data: y_pred =", "[], [], [] for is_end, (p, q, cs, a) in", "yield [batch_token_ids, batch_segment_ids], batch_labels batch_token_ids, batch_segment_ids, batch_labels = [], [],", "= 0. def on_epoch_end(self, epoch, logs=None): val_acc = self.evaluate(valid_generator) if", "K.floatx())) # 构建模型 output = base.model.output output = keras.layers.Lambda(lambda x:", "optimizer=optimizer4, metrics=[multichoice_accuracy] ) class Evaluator(keras.callbacks.Callback): \"\"\"保存验证集acc最好的模型 \"\"\" def __init__(self): self.best_val_acc", "val_acc = self.evaluate(valid_generator) if val_acc > self.best_val_acc: self.best_val_acc = val_acc", "%.5f, best_val_acc: %.5f\\n' % (val_acc, self.best_val_acc) ) def evaluate(self, data):", "in d[1]: q = qa['question'] while len(qa['choice']) < num_classes: qa['choice'].append(u'无效答案')", "q_ids + c_ids batch_token_ids.append(token_ids) batch_segment_ids.append([0] * len(token_ids)) batch_labels.append([a]) if len(batch_token_ids)", "self.best_val_acc: self.best_val_acc = val_acc model.save_weights('weights/c3.weights') print( u'val_acc: %.5f, best_val_acc: %.5f\\n'", "if len(batch_token_ids) == self.batch_size * num_classes or is_end: batch_token_ids =", "= u'||'.join(d[0]) for qa in d[1]: q = qa['question'] while", "keras.models.Model(base.model.input, output) model.summary() model.compile( loss=multichoice_crossentropy, optimizer=optimizer4, metrics=[multichoice_accuracy] ) class Evaluator(keras.callbacks.Callback):", "tokenizer.encode(p)[0] q_ids = tokenizer.encode(q)[0][1:] c_ids = tokenizer.encode(c)[0][1:] truncate_sequences(maxlen, -2, c_ids,", "self.evaluate(valid_generator) if val_acc > self.best_val_acc: self.best_val_acc = val_acc model.save_weights('weights/c3.weights') print(", "问题, 选项, 答案id)] \"\"\" D = [] with open(filename) as", "+ 'c3/d-dev.json') class data_generator(DataGenerator): \"\"\"数据生成器 \"\"\" def __iter__(self, random=False): batch_token_ids,", "+ 'c3/m-dev.json') valid_data += load_data(data_path + 'c3/d-dev.json') class data_generator(DataGenerator): \"\"\"数据生成器", "构建模型 output = base.model.output output = keras.layers.Lambda(lambda x: x[:, 0])(output)", "truncate_sequences from tqdm import tqdm # 基本参数 num_classes = 4", "K.cast(K.argmax(y_pred, axis=1), 'int32') return K.mean(K.cast(K.equal(y_true, y_pred), K.floatx())) # 构建模型 output", "结果文件可以提交到 https://www.cluebenchmarks.com 评测。 \"\"\" test_data = load_data(in_file) test_generator = data_generator(test_data,", "= [] for x_true, _ in tqdm(test_generator, ncols=0): y_pred =", "batch_segment_ids = sequence_padding(batch_segment_ids) batch_labels = sequence_padding(batch_labels) yield [batch_token_ids, batch_segment_ids], batch_labels", "model.save_weights('weights/c3.weights') print( u'val_acc: %.5f, best_val_acc: %.5f\\n' % (val_acc, self.best_val_acc) )", "d in data: p = u'||'.join(d[0]) for qa in d[1]:", "K.reshape(y_pred, (-1, num_classes)) y_pred = K.cast(K.argmax(y_pred, axis=1), 'int32') return K.mean(K.cast(K.equal(y_true,", "import sequence_padding, DataGenerator from bert4keras.snippets import open from bert4keras.snippets import", "= qa['choice'][:num_classes] if 'answer' in qa: a = qa['choice'].index(qa['answer']) else:", "+= load_data(data_path + 'c3/d-train.json') valid_data = load_data(data_path + 'c3/m-dev.json') valid_data", "i += 1 fw.close() if __name__ == '__main__': evaluator =", "= [], [], [] # 转换数据集 train_generator = data_generator(train_data, batch_size)", "+= load_data(data_path + 'c3/d-dev.json') class data_generator(DataGenerator): \"\"\"数据生成器 \"\"\" def __iter__(self,", "str(results[i])}) fw.write(l + '\\n') i += 1 fw.close() if __name__", "truncate_sequences(maxlen, -2, c_ids, q_ids, p_ids) token_ids = p_ids + q_ids", "bert4keras.snippets import truncate_sequences from tqdm import tqdm # 基本参数 num_classes", "model.predict(x_true).reshape((-1, num_classes)) y_pred = y_pred.argmax(axis=1) results.extend(y_pred) fw = open(out_file, 'w')", "y_pred = y_pred.argmax(axis=1) results.extend(y_pred) fw = open(out_file, 'w') with open(in_file)", "model.predict(x_true).reshape((-1, num_classes)) y_pred = y_pred.argmax(axis=1) y_true = y_true[::num_classes, 0] total", "load_data(data_path + 'c3/d-dev.json') class data_generator(DataGenerator): \"\"\"数据生成器 \"\"\" def __iter__(self, random=False):", "random=False): batch_token_ids, batch_segment_ids, batch_labels = [], [], [] for is_end,", "load_data(filename): \"\"\"加载数据 格式:[(篇章, 问题, 选项, 答案id)] \"\"\" D = []", "转换数据集 train_generator = data_generator(train_data, batch_size) valid_generator = data_generator(valid_data, batch_size) def", "def on_epoch_end(self, epoch, logs=None): val_acc = self.evaluate(valid_generator) if val_acc >", "callbacks=[evaluator] ) model.load_weights('weights/c3.weights') test_predict( in_file=data_path + 'c3/test1.0.json', out_file='results/c310_predict.json' ) test_predict(", "for qa in d[1]: q = qa['question'] while len(qa['choice']) <", "json.load(fr) i = 0 for d in data: for qa", "while len(qa['choice']) < num_classes: qa['choice'].append(u'无效答案') c = qa['choice'][:num_classes] if 'answer'", "is_end, (p, q, cs, a) in self.sample(random): for c in", "+ '\\n') i += 1 fw.close() if __name__ == '__main__':", "best_val_acc: %.5f\\n' % (val_acc, self.best_val_acc) ) def evaluate(self, data): total,", "l = json.dumps({'id': str(qa['id']), 'label': str(results[i])}) fw.write(l + '\\n') i" ]
[ "with oop rasterization. \"\"\" tag = 'oop_rasterization' page_set = page_sets.Top25SmoothPageSet", "license that can be # found in the LICENSE file.", "{'story_tag_filter': 'fastpath'} def SetExtraBrowserOptions(self, options): super(ThreadTimesOopRasterKeyMobile, self).SetExtraBrowserOptions(options) CustomizeBrowserOptionsForOopRasterization(options) @classmethod def", "raster.\"\"\" tag = 'oop_rasterization' page_set = page_sets.KeyMobileSitesSmoothPageSet options = {'story_tag_filter':", "\"\"\"Enables flags needed for out of process rasterization.\"\"\" options.AppendExtraBrowserArgs('--force-gpu-rasterization') options.AppendExtraBrowserArgs('--enable-oop-rasterization')", "BSD-style license that can be # found in the LICENSE", "by a BSD-style license that can be # found in", "# Use of this source code is governed by a", "is governed by a BSD-style license that can be #", "import benchmark # pylint: disable=protected-access def CustomizeBrowserOptionsForOopRasterization(options): \"\"\"Enables flags needed", "found in the LICENSE file. from benchmarks import smoothness,thread_times import", "@classmethod def Name(cls): return 'smoothness.oop_rasterization.top_25_smooth' @benchmark.Owner(emails=['<EMAIL>']) class ThreadTimesOopRasterKeyMobile(thread_times._ThreadTimes): \"\"\"Measure timeline", "timeline metrics for key mobile pages while using out of", "tag = 'oop_rasterization' page_set = page_sets.KeyMobileSitesSmoothPageSet options = {'story_tag_filter': 'fastpath'}", "of this source code is governed by a BSD-style license", "def Name(cls): return 'smoothness.oop_rasterization.top_25_smooth' @benchmark.Owner(emails=['<EMAIL>']) class ThreadTimesOopRasterKeyMobile(thread_times._ThreadTimes): \"\"\"Measure timeline metrics", "rasterization.\"\"\" options.AppendExtraBrowserArgs('--force-gpu-rasterization') options.AppendExtraBrowserArgs('--enable-oop-rasterization') @benchmark.Owner(emails=['<EMAIL>']) class SmoothnessOopRasterizationTop25(smoothness._Smoothness): \"\"\"Measures rendering statistics for", "page_set = page_sets.Top25SmoothPageSet def SetExtraBrowserOptions(self, options): CustomizeBrowserOptionsForOopRasterization(options) @classmethod def Name(cls):", "2018 The Chromium Authors. All rights reserved. # Use of", "The Chromium Authors. All rights reserved. # Use of this", "telemetry import benchmark # pylint: disable=protected-access def CustomizeBrowserOptionsForOopRasterization(options): \"\"\"Enables flags", "of process rasterization.\"\"\" options.AppendExtraBrowserArgs('--force-gpu-rasterization') options.AppendExtraBrowserArgs('--enable-oop-rasterization') @benchmark.Owner(emails=['<EMAIL>']) class SmoothnessOopRasterizationTop25(smoothness._Smoothness): \"\"\"Measures rendering", "= page_sets.KeyMobileSitesSmoothPageSet options = {'story_tag_filter': 'fastpath'} def SetExtraBrowserOptions(self, options): super(ThreadTimesOopRasterKeyMobile,", "\"\"\"Measure timeline metrics for key mobile pages while using out", "reserved. # Use of this source code is governed by", "def SetExtraBrowserOptions(self, options): CustomizeBrowserOptionsForOopRasterization(options) @classmethod def Name(cls): return 'smoothness.oop_rasterization.top_25_smooth' @benchmark.Owner(emails=['<EMAIL>'])", "metrics for key mobile pages while using out of process", "key mobile pages while using out of process raster.\"\"\" tag", "@benchmark.Owner(emails=['<EMAIL>']) class SmoothnessOopRasterizationTop25(smoothness._Smoothness): \"\"\"Measures rendering statistics for the top 25", "import page_sets from telemetry import benchmark # pylint: disable=protected-access def", "LICENSE file. from benchmarks import smoothness,thread_times import page_sets from telemetry", "Name(cls): return 'smoothness.oop_rasterization.top_25_smooth' @benchmark.Owner(emails=['<EMAIL>']) class ThreadTimesOopRasterKeyMobile(thread_times._ThreadTimes): \"\"\"Measure timeline metrics for", "options.AppendExtraBrowserArgs('--force-gpu-rasterization') options.AppendExtraBrowserArgs('--enable-oop-rasterization') @benchmark.Owner(emails=['<EMAIL>']) class SmoothnessOopRasterizationTop25(smoothness._Smoothness): \"\"\"Measures rendering statistics for the", "out of process rasterization.\"\"\" options.AppendExtraBrowserArgs('--force-gpu-rasterization') options.AppendExtraBrowserArgs('--enable-oop-rasterization') @benchmark.Owner(emails=['<EMAIL>']) class SmoothnessOopRasterizationTop25(smoothness._Smoothness): \"\"\"Measures", "= 'oop_rasterization' page_set = page_sets.KeyMobileSitesSmoothPageSet options = {'story_tag_filter': 'fastpath'} def", "code is governed by a BSD-style license that can be", "a BSD-style license that can be # found in the", "in the LICENSE file. from benchmarks import smoothness,thread_times import page_sets", "oop rasterization. \"\"\" tag = 'oop_rasterization' page_set = page_sets.Top25SmoothPageSet def", "= page_sets.Top25SmoothPageSet def SetExtraBrowserOptions(self, options): CustomizeBrowserOptionsForOopRasterization(options) @classmethod def Name(cls): return", "page_sets.Top25SmoothPageSet def SetExtraBrowserOptions(self, options): CustomizeBrowserOptionsForOopRasterization(options) @classmethod def Name(cls): return 'smoothness.oop_rasterization.top_25_smooth'", "rasterization. \"\"\" tag = 'oop_rasterization' page_set = page_sets.Top25SmoothPageSet def SetExtraBrowserOptions(self,", "SetExtraBrowserOptions(self, options): CustomizeBrowserOptionsForOopRasterization(options) @classmethod def Name(cls): return 'smoothness.oop_rasterization.top_25_smooth' @benchmark.Owner(emails=['<EMAIL>']) class", "pylint: disable=protected-access def CustomizeBrowserOptionsForOopRasterization(options): \"\"\"Enables flags needed for out of", "process raster.\"\"\" tag = 'oop_rasterization' page_set = page_sets.KeyMobileSitesSmoothPageSet options =", "can be # found in the LICENSE file. from benchmarks", "using out of process raster.\"\"\" tag = 'oop_rasterization' page_set =", "governed by a BSD-style license that can be # found", "class ThreadTimesOopRasterKeyMobile(thread_times._ThreadTimes): \"\"\"Measure timeline metrics for key mobile pages while", "statistics for the top 25 with oop rasterization. \"\"\" tag", "Use of this source code is governed by a BSD-style", "All rights reserved. # Use of this source code is", "ThreadTimesOopRasterKeyMobile(thread_times._ThreadTimes): \"\"\"Measure timeline metrics for key mobile pages while using", "'oop_rasterization' page_set = page_sets.KeyMobileSitesSmoothPageSet options = {'story_tag_filter': 'fastpath'} def SetExtraBrowserOptions(self,", "for out of process rasterization.\"\"\" options.AppendExtraBrowserArgs('--force-gpu-rasterization') options.AppendExtraBrowserArgs('--enable-oop-rasterization') @benchmark.Owner(emails=['<EMAIL>']) class SmoothnessOopRasterizationTop25(smoothness._Smoothness):", "CustomizeBrowserOptionsForOopRasterization(options) @classmethod def Name(cls): return 'smoothness.oop_rasterization.top_25_smooth' @benchmark.Owner(emails=['<EMAIL>']) class ThreadTimesOopRasterKeyMobile(thread_times._ThreadTimes): \"\"\"Measure", "page_sets from telemetry import benchmark # pylint: disable=protected-access def CustomizeBrowserOptionsForOopRasterization(options):", "for the top 25 with oop rasterization. \"\"\" tag =", "25 with oop rasterization. \"\"\" tag = 'oop_rasterization' page_set =", "flags needed for out of process rasterization.\"\"\" options.AppendExtraBrowserArgs('--force-gpu-rasterization') options.AppendExtraBrowserArgs('--enable-oop-rasterization') @benchmark.Owner(emails=['<EMAIL>'])", "from benchmarks import smoothness,thread_times import page_sets from telemetry import benchmark", "\"\"\" tag = 'oop_rasterization' page_set = page_sets.Top25SmoothPageSet def SetExtraBrowserOptions(self, options):", "'oop_rasterization' page_set = page_sets.Top25SmoothPageSet def SetExtraBrowserOptions(self, options): CustomizeBrowserOptionsForOopRasterization(options) @classmethod def", "that can be # found in the LICENSE file. from", "from telemetry import benchmark # pylint: disable=protected-access def CustomizeBrowserOptionsForOopRasterization(options): \"\"\"Enables", "for key mobile pages while using out of process raster.\"\"\"", "mobile pages while using out of process raster.\"\"\" tag =", "def SetExtraBrowserOptions(self, options): super(ThreadTimesOopRasterKeyMobile, self).SetExtraBrowserOptions(options) CustomizeBrowserOptionsForOopRasterization(options) @classmethod def Name(cls): return", "CustomizeBrowserOptionsForOopRasterization(options): \"\"\"Enables flags needed for out of process rasterization.\"\"\" options.AppendExtraBrowserArgs('--force-gpu-rasterization')", "disable=protected-access def CustomizeBrowserOptionsForOopRasterization(options): \"\"\"Enables flags needed for out of process", "options.AppendExtraBrowserArgs('--enable-oop-rasterization') @benchmark.Owner(emails=['<EMAIL>']) class SmoothnessOopRasterizationTop25(smoothness._Smoothness): \"\"\"Measures rendering statistics for the top", "needed for out of process rasterization.\"\"\" options.AppendExtraBrowserArgs('--force-gpu-rasterization') options.AppendExtraBrowserArgs('--enable-oop-rasterization') @benchmark.Owner(emails=['<EMAIL>']) class", "benchmarks import smoothness,thread_times import page_sets from telemetry import benchmark #", "def CustomizeBrowserOptionsForOopRasterization(options): \"\"\"Enables flags needed for out of process rasterization.\"\"\"", "return 'smoothness.oop_rasterization.top_25_smooth' @benchmark.Owner(emails=['<EMAIL>']) class ThreadTimesOopRasterKeyMobile(thread_times._ThreadTimes): \"\"\"Measure timeline metrics for key", "smoothness,thread_times import page_sets from telemetry import benchmark # pylint: disable=protected-access", "# pylint: disable=protected-access def CustomizeBrowserOptionsForOopRasterization(options): \"\"\"Enables flags needed for out", "rights reserved. # Use of this source code is governed", "process rasterization.\"\"\" options.AppendExtraBrowserArgs('--force-gpu-rasterization') options.AppendExtraBrowserArgs('--enable-oop-rasterization') @benchmark.Owner(emails=['<EMAIL>']) class SmoothnessOopRasterizationTop25(smoothness._Smoothness): \"\"\"Measures rendering statistics", "Chromium Authors. All rights reserved. # Use of this source", "the LICENSE file. from benchmarks import smoothness,thread_times import page_sets from", "import smoothness,thread_times import page_sets from telemetry import benchmark # pylint:", "of process raster.\"\"\" tag = 'oop_rasterization' page_set = page_sets.KeyMobileSitesSmoothPageSet options", "while using out of process raster.\"\"\" tag = 'oop_rasterization' page_set", "page_sets.KeyMobileSitesSmoothPageSet options = {'story_tag_filter': 'fastpath'} def SetExtraBrowserOptions(self, options): super(ThreadTimesOopRasterKeyMobile, self).SetExtraBrowserOptions(options)", "<filename>tools/perf/contrib/oop_raster/oop_raster.py # Copyright 2018 The Chromium Authors. All rights reserved.", "pages while using out of process raster.\"\"\" tag = 'oop_rasterization'", "\"\"\"Measures rendering statistics for the top 25 with oop rasterization.", "= 'oop_rasterization' page_set = page_sets.Top25SmoothPageSet def SetExtraBrowserOptions(self, options): CustomizeBrowserOptionsForOopRasterization(options) @classmethod", "class SmoothnessOopRasterizationTop25(smoothness._Smoothness): \"\"\"Measures rendering statistics for the top 25 with", "this source code is governed by a BSD-style license that", "benchmark # pylint: disable=protected-access def CustomizeBrowserOptionsForOopRasterization(options): \"\"\"Enables flags needed for", "top 25 with oop rasterization. \"\"\" tag = 'oop_rasterization' page_set", "'fastpath'} def SetExtraBrowserOptions(self, options): super(ThreadTimesOopRasterKeyMobile, self).SetExtraBrowserOptions(options) CustomizeBrowserOptionsForOopRasterization(options) @classmethod def Name(cls):", "file. from benchmarks import smoothness,thread_times import page_sets from telemetry import", "options): CustomizeBrowserOptionsForOopRasterization(options) @classmethod def Name(cls): return 'smoothness.oop_rasterization.top_25_smooth' @benchmark.Owner(emails=['<EMAIL>']) class ThreadTimesOopRasterKeyMobile(thread_times._ThreadTimes):", "= {'story_tag_filter': 'fastpath'} def SetExtraBrowserOptions(self, options): super(ThreadTimesOopRasterKeyMobile, self).SetExtraBrowserOptions(options) CustomizeBrowserOptionsForOopRasterization(options) @classmethod", "be # found in the LICENSE file. from benchmarks import", "@benchmark.Owner(emails=['<EMAIL>']) class ThreadTimesOopRasterKeyMobile(thread_times._ThreadTimes): \"\"\"Measure timeline metrics for key mobile pages", "# Copyright 2018 The Chromium Authors. All rights reserved. #", "SetExtraBrowserOptions(self, options): super(ThreadTimesOopRasterKeyMobile, self).SetExtraBrowserOptions(options) CustomizeBrowserOptionsForOopRasterization(options) @classmethod def Name(cls): return 'thread_times.oop_rasterization.key_mobile'", "SmoothnessOopRasterizationTop25(smoothness._Smoothness): \"\"\"Measures rendering statistics for the top 25 with oop", "Copyright 2018 The Chromium Authors. All rights reserved. # Use", "page_set = page_sets.KeyMobileSitesSmoothPageSet options = {'story_tag_filter': 'fastpath'} def SetExtraBrowserOptions(self, options):", "the top 25 with oop rasterization. \"\"\" tag = 'oop_rasterization'", "rendering statistics for the top 25 with oop rasterization. \"\"\"", "tag = 'oop_rasterization' page_set = page_sets.Top25SmoothPageSet def SetExtraBrowserOptions(self, options): CustomizeBrowserOptionsForOopRasterization(options)", "source code is governed by a BSD-style license that can", "Authors. All rights reserved. # Use of this source code", "'smoothness.oop_rasterization.top_25_smooth' @benchmark.Owner(emails=['<EMAIL>']) class ThreadTimesOopRasterKeyMobile(thread_times._ThreadTimes): \"\"\"Measure timeline metrics for key mobile", "options = {'story_tag_filter': 'fastpath'} def SetExtraBrowserOptions(self, options): super(ThreadTimesOopRasterKeyMobile, self).SetExtraBrowserOptions(options) CustomizeBrowserOptionsForOopRasterization(options)", "# found in the LICENSE file. from benchmarks import smoothness,thread_times", "out of process raster.\"\"\" tag = 'oop_rasterization' page_set = page_sets.KeyMobileSitesSmoothPageSet" ]
[ "groupsizes(total, len): \"\"\" Groups of length len that add up", "intersection(*seqs): return (item for item in seqs[0] if all(item in", "0: return tuple(seq) return tuple(it.islice(seq, 0, n)) def evalt(t): \"\"\"", "of goals \"\"\" if callable(g) and hasattr(g, '__name__'): return g.__name__", ">>> from logpy.util import transitive_get, deep_transitive_get >>> d = {1:", "(3, 1)) \"\"\" if len == 1: yield (total,) else:", "seen: seen.add(key(item)) yield item except TypeError: # item probably isn't", "return True except TypeError: return False def transitive_get(key, d): \"\"\"", "n == 0: return tuple(seq) return tuple(it.islice(seq, 0, n)) def", "'__name__'): return g.__name__ if isinstance(g, type): return g.__name__ if isinstance(g,", "def dicthash(d): return hash(frozenset(d.items())) def multihash(x): try: return hash(x) except", "def multihash(x): try: return hash(x) except TypeError: if isinstance(x, (list,", "hash(frozenset(map(multihash, x.items()))) if type(x) is slice: return hash((x.start, x.stop, x.step))", "if type(x) is slice: return hash((x.start, x.stop, x.step)) raise TypeError('Hashing", "\"\"\" if len == 1: yield (total,) else: for i", "tree of goals \"\"\" if callable(g) and hasattr(g, '__name__'): return", "= [] for itr in iters: try: yield next(itr) newiters.append(itr)", "add = lambda x, y: x + y >>> evalt((add,", "def pprint(g): \"\"\" Pretty print a tree of goals \"\"\"", "item in seq: try: if key(item) not in seen: seen.add(key(item))", "return g.__name__ if isinstance(g, type): return g.__name__ if isinstance(g, tuple):", "+ tuple(pass_exceptions): pass iters = newiters def take(n, seq): if", "that add up to total >>> from logpy.util import groupsizes", "unique(seq, key=lambda x: x): seen = set() for item in", "isinstance(key, tuple): return tuple(map(lambda k: deep_transitive_get(k, d), key)) else: return", "n is None: return seq if n == 0: return", "item except TypeError: # item probably isn't hashable yield item", "item in seqs[0] if all(item in seq for seq in", "5 >>> evalt(add(2, 3)) 5 \"\"\" if isinstance(t, tuple) and", "callable(g) and hasattr(g, '__name__'): return g.__name__ if isinstance(g, type): return", "pprint(g): \"\"\" Pretty print a tree of goals \"\"\" if", "d): \"\"\" Transitive get that propagates within tuples >>> from", "\"\"\" if isinstance(t, tuple) and len(t) >= 1 and callable(t[0]):", "return t[0](*t[1:]) else: return t def intersection(*seqs): return (item for", ">>> transitive_get(1, d) 4 \"\"\" while hashable(key) and key in", "in seqs[0] if all(item in seq for seq in seqs[1:]))", "return seq if n == 0: return tuple(seq) return tuple(it.islice(seq,", "pass def pprint(g): \"\"\" Pretty print a tree of goals", "transitive_get(key, d) if isinstance(key, tuple): return tuple(map(lambda k: deep_transitive_get(k, d),", "# item probably isn't hashable yield item # Just return", ">>> evalt(add(2, 3)) 5 \"\"\" if isinstance(t, tuple) and len(t)", "' + str(x)) def unique(seq, key=lambda x: x): seen =", "itertools as it from toolz.compatibility import range, map, iteritems def", "def transitive_get(key, d): \"\"\" Transitive dict.get >>> from logpy.util import", "return tuple(it.islice(seq, 0, n)) def evalt(t): \"\"\" Evaluate tuple if", "yield item # Just return it and hope for the", "import groupsizes >>> tuple(groupsizes(4, 2)) ((1, 3), (2, 2), (3,", "deep_transitive_get(1, d) (12, 13) \"\"\" key = transitive_get(key, d) if", "len(t) >= 1 and callable(t[0]): return t[0](*t[1:]) else: return t", "in seen: seen.add(key(item)) yield item except TypeError: # item probably", "iters: newiters = [] for itr in iters: try: yield", "d = {1: 2, 2: 3, 3: 4} >>> d.get(1)", "True except TypeError: return False def transitive_get(key, d): \"\"\" Transitive", "2: 3, 3: 4} >>> d.get(1) 2 >>> transitive_get(1, d)", "Transitive dict.get >>> from logpy.util import transitive_get >>> d =", "tuple, set, frozenset)): return hash(tuple(map(multihash, x))) if type(x) is dict:", "- 1): yield (i,) + perm def raises(err, lamda): try:", "= map(iter, seqs) while iters: newiters = [] for itr", "1 and callable(t[0]): return t[0](*t[1:]) else: return t def intersection(*seqs):", "total - len + 1 + 1): for perm in", "for i in range(1, total - len + 1 +", "\"\"\" Transitive get that propagates within tuples >>> from logpy.util", "Just return it and hope for the best def interleave(seqs,", "if n is None: return seq if n == 0:", "1 + 1): for perm in groupsizes(total - i, len", "key)) else: return key def dicthash(d): return hash(frozenset(d.items())) def multihash(x):", "seqs[1:])) def groupsizes(total, len): \"\"\" Groups of length len that", "2 >>> transitive_get(1, d) 4 \"\"\" while hashable(key) and key", "%s\"%err) except err: pass def pprint(g): \"\"\" Pretty print a", ">= 1 and callable(t[0]): return t[0](*t[1:]) else: return t def", "best def interleave(seqs, pass_exceptions=()): iters = map(iter, seqs) while iters:", "== 1: yield (total,) else: for i in range(1, total", "tuple if unevaluated >>> from logpy.util import evalt >>> add", "x))) if type(x) is dict: return hash(frozenset(map(multihash, x.items()))) if type(x)", "raise %s\"%err) except err: pass def pprint(g): \"\"\" Pretty print", "except TypeError: return False def transitive_get(key, d): \"\"\" Transitive dict.get", "import transitive_get, deep_transitive_get >>> d = {1: (2, 3), 2:", "def intersection(*seqs): return (item for item in seqs[0] if all(item", "- i, len - 1): yield (i,) + perm def", "seen = set() for item in seq: try: if key(item)", "hash(tuple(map(multihash, x))) if type(x) is dict: return hash(frozenset(map(multihash, x.items()))) if", ">>> from logpy.util import groupsizes >>> tuple(groupsizes(4, 2)) ((1, 3),", "3: 4} >>> d.get(1) 2 >>> transitive_get(1, d) 4 \"\"\"", "toolz.compatibility import range, map, iteritems def hashable(x): try: hash(x) return", "(list, tuple, set, frozenset)): return hash(tuple(map(multihash, x))) if type(x) is", "isinstance(t, tuple) and len(t) >= 1 and callable(t[0]): return t[0](*t[1:])", "{1: (2, 3), 2: 12, 3: 13} >>> transitive_get(1, d)", "seq in seqs[1:])) def groupsizes(total, len): \"\"\" Groups of length", "\"\"\" Groups of length len that add up to total", "def groupsizes(total, len): \"\"\" Groups of length len that add", "= newiters def take(n, seq): if n is None: return", "y >>> evalt((add, 2, 3)) 5 >>> evalt(add(2, 3)) 5", "return hash(frozenset(d.items())) def multihash(x): try: return hash(x) except TypeError: if", "return False def transitive_get(key, d): \"\"\" Transitive dict.get >>> from", "len that add up to total >>> from logpy.util import", "is None: return seq if n == 0: return tuple(seq)", "get that propagates within tuples >>> from logpy.util import transitive_get,", "x, y: x + y >>> evalt((add, 2, 3)) 5", "for item in seq: try: if key(item) not in seen:", "seqs) while iters: newiters = [] for itr in iters:", "frozenset)): return hash(tuple(map(multihash, x))) if type(x) is dict: return hash(frozenset(map(multihash,", "+ 1 + 1): for perm in groupsizes(total - i,", "y: x + y >>> evalt((add, 2, 3)) 5 >>>", "# Just return it and hope for the best def", "def unique(seq, key=lambda x: x): seen = set() for item", "\"\"\" Pretty print a tree of goals \"\"\" if callable(g)", "\"\"\" if callable(g) and hasattr(g, '__name__'): return g.__name__ if isinstance(g,", "not covered for ' + str(x)) def unique(seq, key=lambda x:", "yield (total,) else: for i in range(1, total - len", "i, len - 1): yield (i,) + perm def raises(err,", "tuple): return \"(\" + ', '.join(map(pprint, g)) + \")\" return", "slice: return hash((x.start, x.stop, x.step)) raise TypeError('Hashing not covered for", "5 \"\"\" if isinstance(t, tuple) and len(t) >= 1 and", "3: 13} >>> transitive_get(1, d) (2, 3) >>> deep_transitive_get(1, d)", "return key def deep_transitive_get(key, d): \"\"\" Transitive get that propagates", "seen.add(key(item)) yield item except TypeError: # item probably isn't hashable", "in range(1, total - len + 1 + 1): for", "perm def raises(err, lamda): try: lamda() raise Exception(\"Did not raise", "evalt(add(2, 3)) 5 \"\"\" if isinstance(t, tuple) and len(t) >=", "except TypeError: if isinstance(x, (list, tuple, set, frozenset)): return hash(tuple(map(multihash,", "add up to total >>> from logpy.util import groupsizes >>>", "except err: pass def pprint(g): \"\"\" Pretty print a tree", "deep_transitive_get(k, d), key)) else: return key def dicthash(d): return hash(frozenset(d.items()))", "return str(g) def index(tup, ind): \"\"\" Fancy indexing with tuples", "in iters: try: yield next(itr) newiters.append(itr) except (StopIteration,) + tuple(pass_exceptions):", "x + y >>> evalt((add, 2, 3)) 5 >>> evalt(add(2,", "def hashable(x): try: hash(x) return True except TypeError: return False", "def raises(err, lamda): try: lamda() raise Exception(\"Did not raise %s\"%err)", "tuple): return tuple(map(lambda k: deep_transitive_get(k, d), key)) else: return key", "key = d[key] return key def deep_transitive_get(key, d): \"\"\" Transitive", "\")\" return str(g) def index(tup, ind): \"\"\" Fancy indexing with", "logpy.util import transitive_get >>> d = {1: 2, 2: 3,", "lambda x, y: x + y >>> evalt((add, 2, 3))", "for perm in groupsizes(total - i, len - 1): yield", "type): return g.__name__ if isinstance(g, tuple): return \"(\" + ',", "key = transitive_get(key, d) if isinstance(key, tuple): return tuple(map(lambda k:", "if n == 0: return tuple(seq) return tuple(it.islice(seq, 0, n))", "2), (3, 1)) \"\"\" if len == 1: yield (total,)", "= transitive_get(key, d) if isinstance(key, tuple): return tuple(map(lambda k: deep_transitive_get(k,", "hash(frozenset(d.items())) def multihash(x): try: return hash(x) except TypeError: if isinstance(x,", "if isinstance(key, tuple): return tuple(map(lambda k: deep_transitive_get(k, d), key)) else:", "i in range(1, total - len + 1 + 1):", "seq): if n is None: return seq if n ==", "ind): \"\"\" Fancy indexing with tuples \"\"\" return tuple(tup[i] for", "if type(x) is dict: return hash(frozenset(map(multihash, x.items()))) if type(x) is", "(StopIteration,) + tuple(pass_exceptions): pass iters = newiters def take(n, seq):", "Fancy indexing with tuples \"\"\" return tuple(tup[i] for i in", "up to total >>> from logpy.util import groupsizes >>> tuple(groupsizes(4,", "+ str(x)) def unique(seq, key=lambda x: x): seen = set()", "3), 2: 12, 3: 13} >>> transitive_get(1, d) (2, 3)", "raises(err, lamda): try: lamda() raise Exception(\"Did not raise %s\"%err) except", "logpy.util import transitive_get, deep_transitive_get >>> d = {1: (2, 3),", "g.__name__ if isinstance(g, tuple): return \"(\" + ', '.join(map(pprint, g))", "1): yield (i,) + perm def raises(err, lamda): try: lamda()", "yield (i,) + perm def raises(err, lamda): try: lamda() raise", "d) if isinstance(key, tuple): return tuple(map(lambda k: deep_transitive_get(k, d), key))", "seqs[0] if all(item in seq for seq in seqs[1:])) def", "iters = newiters def take(n, seq): if n is None:", ">>> deep_transitive_get(1, d) (12, 13) \"\"\" key = transitive_get(key, d)", "newiters = [] for itr in iters: try: yield next(itr)", "tuple(map(lambda k: deep_transitive_get(k, d), key)) else: return key def dicthash(d):", ">>> from logpy.util import evalt >>> add = lambda x,", "not raise %s\"%err) except err: pass def pprint(g): \"\"\" Pretty", "key def deep_transitive_get(key, d): \"\"\" Transitive get that propagates within", "', '.join(map(pprint, g)) + \")\" return str(g) def index(tup, ind):", "return hash(x) except TypeError: if isinstance(x, (list, tuple, set, frozenset)):", "and callable(t[0]): return t[0](*t[1:]) else: return t def intersection(*seqs): return", "(2, 2), (3, 1)) \"\"\" if len == 1: yield", "return hash(frozenset(map(multihash, x.items()))) if type(x) is slice: return hash((x.start, x.stop,", "1)) \"\"\" if len == 1: yield (total,) else: for", "lamda() raise Exception(\"Did not raise %s\"%err) except err: pass def", "13) \"\"\" key = transitive_get(key, d) if isinstance(key, tuple): return", "return hash(tuple(map(multihash, x))) if type(x) is dict: return hash(frozenset(map(multihash, x.items())))", "if key(item) not in seen: seen.add(key(item)) yield item except TypeError:", "from logpy.util import transitive_get >>> d = {1: 2, 2:", "str(x)) def unique(seq, key=lambda x: x): seen = set() for", "a tree of goals \"\"\" if callable(g) and hasattr(g, '__name__'):", "key in d: key = d[key] return key def deep_transitive_get(key,", "as it from toolz.compatibility import range, map, iteritems def hashable(x):", "item # Just return it and hope for the best", "x.stop, x.step)) raise TypeError('Hashing not covered for ' + str(x))", "x): seen = set() for item in seq: try: if", "groupsizes(total - i, len - 1): yield (i,) + perm", "def take(n, seq): if n is None: return seq if", "for seq in seqs[1:])) def groupsizes(total, len): \"\"\" Groups of", "in seqs[1:])) def groupsizes(total, len): \"\"\" Groups of length len", "type(x) is slice: return hash((x.start, x.stop, x.step)) raise TypeError('Hashing not", "to total >>> from logpy.util import groupsizes >>> tuple(groupsizes(4, 2))", "iters: try: yield next(itr) newiters.append(itr) except (StopIteration,) + tuple(pass_exceptions): pass", "12, 3: 13} >>> transitive_get(1, d) (2, 3) >>> deep_transitive_get(1,", "= set() for item in seq: try: if key(item) not", "logpy.util import evalt >>> add = lambda x, y: x", "try: yield next(itr) newiters.append(itr) except (StopIteration,) + tuple(pass_exceptions): pass iters", "it and hope for the best def interleave(seqs, pass_exceptions=()): iters", "key(item) not in seen: seen.add(key(item)) yield item except TypeError: #", "tuple(pass_exceptions): pass iters = newiters def take(n, seq): if n", "of length len that add up to total >>> from", "if all(item in seq for seq in seqs[1:])) def groupsizes(total,", "perm in groupsizes(total - i, len - 1): yield (i,)", "else: return t def intersection(*seqs): return (item for item in", "unevaluated >>> from logpy.util import evalt >>> add = lambda", "tuple) and len(t) >= 1 and callable(t[0]): return t[0](*t[1:]) else:", "seq: try: if key(item) not in seen: seen.add(key(item)) yield item", "len): \"\"\" Groups of length len that add up to", "for item in seqs[0] if all(item in seq for seq", "import transitive_get >>> d = {1: 2, 2: 3, 3:", "if isinstance(x, (list, tuple, set, frozenset)): return hash(tuple(map(multihash, x))) if", "if callable(g) and hasattr(g, '__name__'): return g.__name__ if isinstance(g, type):", "from toolz.compatibility import range, map, iteritems def hashable(x): try: hash(x)", "hope for the best def interleave(seqs, pass_exceptions=()): iters = map(iter,", "for the best def interleave(seqs, pass_exceptions=()): iters = map(iter, seqs)", "t def intersection(*seqs): return (item for item in seqs[0] if", "d: key = d[key] return key def deep_transitive_get(key, d): \"\"\"", "set, frozenset)): return hash(tuple(map(multihash, x))) if type(x) is dict: return", "deep_transitive_get >>> d = {1: (2, 3), 2: 12, 3:", "set() for item in seq: try: if key(item) not in", "and hope for the best def interleave(seqs, pass_exceptions=()): iters =", "lamda): try: lamda() raise Exception(\"Did not raise %s\"%err) except err:", "g)) + \")\" return str(g) def index(tup, ind): \"\"\" Fancy", "import range, map, iteritems def hashable(x): try: hash(x) return True", "in d: key = d[key] return key def deep_transitive_get(key, d):", "len - 1): yield (i,) + perm def raises(err, lamda):", "from logpy.util import transitive_get, deep_transitive_get >>> d = {1: (2,", "is dict: return hash(frozenset(map(multihash, x.items()))) if type(x) is slice: return", "transitive_get, deep_transitive_get >>> d = {1: (2, 3), 2: 12,", "if isinstance(g, type): return g.__name__ if isinstance(g, tuple): return \"(\"", "Exception(\"Did not raise %s\"%err) except err: pass def pprint(g): \"\"\"", "n)) def evalt(t): \"\"\" Evaluate tuple if unevaluated >>> from", "d) (2, 3) >>> deep_transitive_get(1, d) (12, 13) \"\"\" key", "+ 1): for perm in groupsizes(total - i, len -", "tuples >>> from logpy.util import transitive_get, deep_transitive_get >>> d =", "next(itr) newiters.append(itr) except (StopIteration,) + tuple(pass_exceptions): pass iters = newiters", "dict: return hash(frozenset(map(multihash, x.items()))) if type(x) is slice: return hash((x.start,", "Transitive get that propagates within tuples >>> from logpy.util import", "t[0](*t[1:]) else: return t def intersection(*seqs): return (item for item", "+ perm def raises(err, lamda): try: lamda() raise Exception(\"Did not", "str(g) def index(tup, ind): \"\"\" Fancy indexing with tuples \"\"\"", "1): for perm in groupsizes(total - i, len - 1):", "1: yield (total,) else: for i in range(1, total -", "3) >>> deep_transitive_get(1, d) (12, 13) \"\"\" key = transitive_get(key,", "in seq: try: if key(item) not in seen: seen.add(key(item)) yield", "covered for ' + str(x)) def unique(seq, key=lambda x: x):", "(item for item in seqs[0] if all(item in seq for", "k: deep_transitive_get(k, d), key)) else: return key def dicthash(d): return", "TypeError('Hashing not covered for ' + str(x)) def unique(seq, key=lambda", "False def transitive_get(key, d): \"\"\" Transitive dict.get >>> from logpy.util", "evalt((add, 2, 3)) 5 >>> evalt(add(2, 3)) 5 \"\"\" if", "if isinstance(g, tuple): return \"(\" + ', '.join(map(pprint, g)) +", "return (item for item in seqs[0] if all(item in seq", "dict.get >>> from logpy.util import transitive_get >>> d = {1:", "x.step)) raise TypeError('Hashing not covered for ' + str(x)) def", "Pretty print a tree of goals \"\"\" if callable(g) and", ">>> from logpy.util import transitive_get >>> d = {1: 2,", "evalt >>> add = lambda x, y: x + y", "g.__name__ if isinstance(g, type): return g.__name__ if isinstance(g, tuple): return", "13} >>> transitive_get(1, d) (2, 3) >>> deep_transitive_get(1, d) (12,", "not in seen: seen.add(key(item)) yield item except TypeError: # item", "x: x): seen = set() for item in seq: try:", "= {1: (2, 3), 2: 12, 3: 13} >>> transitive_get(1,", "within tuples >>> from logpy.util import transitive_get, deep_transitive_get >>> d", "2, 3)) 5 >>> evalt(add(2, 3)) 5 \"\"\" if isinstance(t,", "d = {1: (2, 3), 2: 12, 3: 13} >>>", ">>> add = lambda x, y: x + y >>>", "TypeError: return False def transitive_get(key, d): \"\"\" Transitive dict.get >>>", "return t def intersection(*seqs): return (item for item in seqs[0]", "tuple(seq) return tuple(it.islice(seq, 0, n)) def evalt(t): \"\"\" Evaluate tuple", "iters = map(iter, seqs) while iters: newiters = [] for", "3), (2, 2), (3, 1)) \"\"\" if len == 1:", ">>> d = {1: (2, 3), 2: 12, 3: 13}", "raise Exception(\"Did not raise %s\"%err) except err: pass def pprint(g):", "while hashable(key) and key in d: key = d[key] return", "item probably isn't hashable yield item # Just return it", "Groups of length len that add up to total >>>", "{1: 2, 2: 3, 3: 4} >>> d.get(1) 2 >>>", "TypeError: if isinstance(x, (list, tuple, set, frozenset)): return hash(tuple(map(multihash, x)))", "(12, 13) \"\"\" key = transitive_get(key, d) if isinstance(key, tuple):", "tuple(it.islice(seq, 0, n)) def evalt(t): \"\"\" Evaluate tuple if unevaluated", ">>> d = {1: 2, 2: 3, 3: 4} >>>", "it from toolz.compatibility import range, map, iteritems def hashable(x): try:", "def evalt(t): \"\"\" Evaluate tuple if unevaluated >>> from logpy.util", "pass_exceptions=()): iters = map(iter, seqs) while iters: newiters = []", "range, map, iteritems def hashable(x): try: hash(x) return True except", ">>> transitive_get(1, d) (2, 3) >>> deep_transitive_get(1, d) (12, 13)", "for itr in iters: try: yield next(itr) newiters.append(itr) except (StopIteration,)", "return \"(\" + ', '.join(map(pprint, g)) + \")\" return str(g)", "index(tup, ind): \"\"\" Fancy indexing with tuples \"\"\" return tuple(tup[i]", "4 \"\"\" while hashable(key) and key in d: key =", "hashable yield item # Just return it and hope for", "try: return hash(x) except TypeError: if isinstance(x, (list, tuple, set,", "import itertools as it from toolz.compatibility import range, map, iteritems", "'.join(map(pprint, g)) + \")\" return str(g) def index(tup, ind): \"\"\"", "len == 1: yield (total,) else: for i in range(1,", "hash(x) return True except TypeError: return False def transitive_get(key, d):", "= lambda x, y: x + y >>> evalt((add, 2,", "multihash(x): try: return hash(x) except TypeError: if isinstance(x, (list, tuple,", "raise TypeError('Hashing not covered for ' + str(x)) def unique(seq,", "d), key)) else: return key def dicthash(d): return hash(frozenset(d.items())) def", "seq if n == 0: return tuple(seq) return tuple(it.islice(seq, 0,", "total >>> from logpy.util import groupsizes >>> tuple(groupsizes(4, 2)) ((1,", "= {1: 2, 2: 3, 3: 4} >>> d.get(1) 2", "from logpy.util import groupsizes >>> tuple(groupsizes(4, 2)) ((1, 3), (2,", "hasattr(g, '__name__'): return g.__name__ if isinstance(g, type): return g.__name__ if", "map, iteritems def hashable(x): try: hash(x) return True except TypeError:", "return tuple(seq) return tuple(it.islice(seq, 0, n)) def evalt(t): \"\"\" Evaluate", "in seq for seq in seqs[1:])) def groupsizes(total, len): \"\"\"", "key=lambda x: x): seen = set() for item in seq:", "x.items()))) if type(x) is slice: return hash((x.start, x.stop, x.step)) raise", "else: for i in range(1, total - len + 1", "<reponame>mrocklin/logpy<filename>logpy/util.py import itertools as it from toolz.compatibility import range, map,", "+ \")\" return str(g) def index(tup, ind): \"\"\" Fancy indexing", "d) 4 \"\"\" while hashable(key) and key in d: key", "propagates within tuples >>> from logpy.util import transitive_get, deep_transitive_get >>>", "hash(x) except TypeError: if isinstance(x, (list, tuple, set, frozenset)): return", "= d[key] return key def deep_transitive_get(key, d): \"\"\" Transitive get", "goals \"\"\" if callable(g) and hasattr(g, '__name__'): return g.__name__ if", "0, n)) def evalt(t): \"\"\" Evaluate tuple if unevaluated >>>", "except (StopIteration,) + tuple(pass_exceptions): pass iters = newiters def take(n,", "deep_transitive_get(key, d): \"\"\" Transitive get that propagates within tuples >>>", "yield next(itr) newiters.append(itr) except (StopIteration,) + tuple(pass_exceptions): pass iters =", "4} >>> d.get(1) 2 >>> transitive_get(1, d) 4 \"\"\" while", "\"\"\" Evaluate tuple if unevaluated >>> from logpy.util import evalt", "pass iters = newiters def take(n, seq): if n is", "def deep_transitive_get(key, d): \"\"\" Transitive get that propagates within tuples", "3, 3: 4} >>> d.get(1) 2 >>> transitive_get(1, d) 4", "\"\"\" key = transitive_get(key, d) if isinstance(key, tuple): return tuple(map(lambda", "(total,) else: for i in range(1, total - len +", "isinstance(g, tuple): return \"(\" + ', '.join(map(pprint, g)) + \")\"", "(i,) + perm def raises(err, lamda): try: lamda() raise Exception(\"Did", "map(iter, seqs) while iters: newiters = [] for itr in", "the best def interleave(seqs, pass_exceptions=()): iters = map(iter, seqs) while", "in groupsizes(total - i, len - 1): yield (i,) +", "TypeError: # item probably isn't hashable yield item # Just", "hashable(x): try: hash(x) return True except TypeError: return False def", "probably isn't hashable yield item # Just return it and", "try: if key(item) not in seen: seen.add(key(item)) yield item except", "evalt(t): \"\"\" Evaluate tuple if unevaluated >>> from logpy.util import", "def index(tup, ind): \"\"\" Fancy indexing with tuples \"\"\" return", "((1, 3), (2, 2), (3, 1)) \"\"\" if len ==", "2, 2: 3, 3: 4} >>> d.get(1) 2 >>> transitive_get(1,", "tuple(groupsizes(4, 2)) ((1, 3), (2, 2), (3, 1)) \"\"\" if", "def interleave(seqs, pass_exceptions=()): iters = map(iter, seqs) while iters: newiters", "range(1, total - len + 1 + 1): for perm", "len + 1 + 1): for perm in groupsizes(total -", "(2, 3), 2: 12, 3: 13} >>> transitive_get(1, d) (2,", "and hasattr(g, '__name__'): return g.__name__ if isinstance(g, type): return g.__name__", "\"(\" + ', '.join(map(pprint, g)) + \")\" return str(g) def", "(2, 3) >>> deep_transitive_get(1, d) (12, 13) \"\"\" key =", "transitive_get(key, d): \"\"\" Transitive dict.get >>> from logpy.util import transitive_get", "+ ', '.join(map(pprint, g)) + \")\" return str(g) def index(tup,", "try: hash(x) return True except TypeError: return False def transitive_get(key,", ">>> tuple(groupsizes(4, 2)) ((1, 3), (2, 2), (3, 1)) \"\"\"", "if len == 1: yield (total,) else: for i in", "type(x) is dict: return hash(frozenset(map(multihash, x.items()))) if type(x) is slice:", "return tuple(map(lambda k: deep_transitive_get(k, d), key)) else: return key def", "d.get(1) 2 >>> transitive_get(1, d) 4 \"\"\" while hashable(key) and", "return g.__name__ if isinstance(g, tuple): return \"(\" + ', '.join(map(pprint,", "else: return key def dicthash(d): return hash(frozenset(d.items())) def multihash(x): try:", "hashable(key) and key in d: key = d[key] return key", "None: return seq if n == 0: return tuple(seq) return", "callable(t[0]): return t[0](*t[1:]) else: return t def intersection(*seqs): return (item", "- len + 1 + 1): for perm in groupsizes(total", "logpy.util import groupsizes >>> tuple(groupsizes(4, 2)) ((1, 3), (2, 2),", "return hash((x.start, x.stop, x.step)) raise TypeError('Hashing not covered for '", "\"\"\" Transitive dict.get >>> from logpy.util import transitive_get >>> d", "isinstance(g, type): return g.__name__ if isinstance(g, tuple): return \"(\" +", "itr in iters: try: yield next(itr) newiters.append(itr) except (StopIteration,) +", "iteritems def hashable(x): try: hash(x) return True except TypeError: return", "seq for seq in seqs[1:])) def groupsizes(total, len): \"\"\" Groups", "\"\"\" while hashable(key) and key in d: key = d[key]", "[] for itr in iters: try: yield next(itr) newiters.append(itr) except", "isn't hashable yield item # Just return it and hope", "== 0: return tuple(seq) return tuple(it.islice(seq, 0, n)) def evalt(t):", "except TypeError: # item probably isn't hashable yield item #", "newiters def take(n, seq): if n is None: return seq", "3)) 5 >>> evalt(add(2, 3)) 5 \"\"\" if isinstance(t, tuple)", "try: lamda() raise Exception(\"Did not raise %s\"%err) except err: pass", "Evaluate tuple if unevaluated >>> from logpy.util import evalt >>>", "if unevaluated >>> from logpy.util import evalt >>> add =", "transitive_get(1, d) 4 \"\"\" while hashable(key) and key in d:", "d[key] return key def deep_transitive_get(key, d): \"\"\" Transitive get that", "and len(t) >= 1 and callable(t[0]): return t[0](*t[1:]) else: return", "and key in d: key = d[key] return key def", "+ y >>> evalt((add, 2, 3)) 5 >>> evalt(add(2, 3))", "transitive_get(1, d) (2, 3) >>> deep_transitive_get(1, d) (12, 13) \"\"\"", "hash((x.start, x.stop, x.step)) raise TypeError('Hashing not covered for ' +", "indexing with tuples \"\"\" return tuple(tup[i] for i in ind)", "return key def dicthash(d): return hash(frozenset(d.items())) def multihash(x): try: return", "return it and hope for the best def interleave(seqs, pass_exceptions=()):", "\"\"\" Fancy indexing with tuples \"\"\" return tuple(tup[i] for i", "while iters: newiters = [] for itr in iters: try:", "if isinstance(t, tuple) and len(t) >= 1 and callable(t[0]): return", "3)) 5 \"\"\" if isinstance(t, tuple) and len(t) >= 1", "isinstance(x, (list, tuple, set, frozenset)): return hash(tuple(map(multihash, x))) if type(x)", "that propagates within tuples >>> from logpy.util import transitive_get, deep_transitive_get", "dicthash(d): return hash(frozenset(d.items())) def multihash(x): try: return hash(x) except TypeError:", "all(item in seq for seq in seqs[1:])) def groupsizes(total, len):", "2)) ((1, 3), (2, 2), (3, 1)) \"\"\" if len", "yield item except TypeError: # item probably isn't hashable yield", "from logpy.util import evalt >>> add = lambda x, y:", ">>> d.get(1) 2 >>> transitive_get(1, d) 4 \"\"\" while hashable(key)", ">>> evalt((add, 2, 3)) 5 >>> evalt(add(2, 3)) 5 \"\"\"", "key def dicthash(d): return hash(frozenset(d.items())) def multihash(x): try: return hash(x)", "d): \"\"\" Transitive dict.get >>> from logpy.util import transitive_get >>>", "for ' + str(x)) def unique(seq, key=lambda x: x): seen", "is slice: return hash((x.start, x.stop, x.step)) raise TypeError('Hashing not covered", "2: 12, 3: 13} >>> transitive_get(1, d) (2, 3) >>>", "interleave(seqs, pass_exceptions=()): iters = map(iter, seqs) while iters: newiters =", "import evalt >>> add = lambda x, y: x +", "transitive_get >>> d = {1: 2, 2: 3, 3: 4}", "take(n, seq): if n is None: return seq if n", "length len that add up to total >>> from logpy.util", "newiters.append(itr) except (StopIteration,) + tuple(pass_exceptions): pass iters = newiters def", "groupsizes >>> tuple(groupsizes(4, 2)) ((1, 3), (2, 2), (3, 1))", "err: pass def pprint(g): \"\"\" Pretty print a tree of", "d) (12, 13) \"\"\" key = transitive_get(key, d) if isinstance(key,", "print a tree of goals \"\"\" if callable(g) and hasattr(g," ]
[ "index = bot.index_from_args(data) data[index] = data[index] + shift outname =", "+ '-shift-%s.txt' % shift # then we set up the", "= bot.get_arg('shift', type=float, required=True) index = bot.index_from_args(data) data[index] = data[index]", "logic shift = bot.get_arg('shift', type=float, required=True) index = bot.index_from_args(data) data[index]", "comes the custom plugin logic shift = bot.get_arg('shift', type=float, required=True)", "the custom plugin logic shift = bot.get_arg('shift', type=float, required=True) index", "= bot.index_from_args(data) data[index] = data[index] + shift outname = bot.no_extension()", "data[index] + shift outname = bot.no_extension() + '-shift-%s.txt' % shift", "bot import numpy as np def main(): # lets get", "type=float, required=True) index = bot.index_from_args(data) data[index] = data[index] + shift", "set up the output outpath = bot.output_filepath(outname) np.savetxt(outpath, data) if", "outname = bot.no_extension() + '-shift-%s.txt' % shift # then we", "= bot.loadfile(filepath) # now comes the custom plugin logic shift", "required=True) index = bot.index_from_args(data) data[index] = data[index] + shift outname", "then we set up the output outpath = bot.output_filepath(outname) np.savetxt(outpath,", "as np def main(): # lets get our parameters and", "= bot.filepath() data = bot.loadfile(filepath) # now comes the custom", "now comes the custom plugin logic shift = bot.get_arg('shift', type=float,", "bot.index_from_args(data) data[index] = data[index] + shift outname = bot.no_extension() +", "up the output outpath = bot.output_filepath(outname) np.savetxt(outpath, data) if __name__", "# now comes the custom plugin logic shift = bot.get_arg('shift',", "bot.get_arg('shift', type=float, required=True) index = bot.index_from_args(data) data[index] = data[index] +", "output outpath = bot.output_filepath(outname) np.savetxt(outpath, data) if __name__ == \"__main__\":", "parameters and data filepath = bot.filepath() data = bot.loadfile(filepath) #", "shift outname = bot.no_extension() + '-shift-%s.txt' % shift # then", "# then we set up the output outpath = bot.output_filepath(outname)", "lets get our parameters and data filepath = bot.filepath() data", "and data filepath = bot.filepath() data = bot.loadfile(filepath) # now", "main(): # lets get our parameters and data filepath =", "bot.loadfile(filepath) # now comes the custom plugin logic shift =", "import numpy as np def main(): # lets get our", "+ shift outname = bot.no_extension() + '-shift-%s.txt' % shift #", "filepath = bot.filepath() data = bot.loadfile(filepath) # now comes the", "import rinobot_plugin as bot import numpy as np def main():", "rinobot_plugin as bot import numpy as np def main(): #", "outpath = bot.output_filepath(outname) np.savetxt(outpath, data) if __name__ == \"__main__\": main()", "bot.no_extension() + '-shift-%s.txt' % shift # then we set up", "custom plugin logic shift = bot.get_arg('shift', type=float, required=True) index =", "data filepath = bot.filepath() data = bot.loadfile(filepath) # now comes", "% shift # then we set up the output outpath", "shift = bot.get_arg('shift', type=float, required=True) index = bot.index_from_args(data) data[index] =", "shift # then we set up the output outpath =", "data = bot.loadfile(filepath) # now comes the custom plugin logic", "'-shift-%s.txt' % shift # then we set up the output", "def main(): # lets get our parameters and data filepath", "np def main(): # lets get our parameters and data", "data[index] = data[index] + shift outname = bot.no_extension() + '-shift-%s.txt'", "bot.filepath() data = bot.loadfile(filepath) # now comes the custom plugin", "= bot.no_extension() + '-shift-%s.txt' % shift # then we set", "plugin logic shift = bot.get_arg('shift', type=float, required=True) index = bot.index_from_args(data)", "we set up the output outpath = bot.output_filepath(outname) np.savetxt(outpath, data)", "= data[index] + shift outname = bot.no_extension() + '-shift-%s.txt' %", "as bot import numpy as np def main(): # lets", "numpy as np def main(): # lets get our parameters", "get our parameters and data filepath = bot.filepath() data =", "# lets get our parameters and data filepath = bot.filepath()", "the output outpath = bot.output_filepath(outname) np.savetxt(outpath, data) if __name__ ==", "our parameters and data filepath = bot.filepath() data = bot.loadfile(filepath)" ]
[ "MemcacheClient.__mc_instance = _MemcacheClient(*a, **b) locker.release() return MemcacheClient.__mc_instance class _MemcacheClient(Client): def", "if obj: return Client.incr(self,newKey,value) else: self.set(newKey,value,time_expire) return value def set(self,key,value,time_expire=300):", "servers, debug=0, pickleProtocol=0, pickler=pickle.Pickler, unpickler=pickle.Unpickler, pload=None, pid=None): self.request=request Client.__init__(self,servers,debug,pickleProtocol, pickler,unpickler,pload,pid)", "**b): locker.acquire() if not hasattr(MemcacheClient, '__mc_instance'): MemcacheClient.__mc_instance = _MemcacheClient(*a, **b)", "self.delete(key) else: value=f() self.set(key,value,time_expire) return value def increment(self,key,value=1,time_expire=300): newKey=self.__keyFormat__(key) obj=self.get(newKey)", "value=obj elif f is None: if obj: self.delete(key) else: value=f()", "f is None: if obj: self.delete(key) else: value=f() self.set(key,value,time_expire) return", "self.set(key,value,time_expire) return value def increment(self,key,value=1,time_expire=300): newKey=self.__keyFormat__(key) obj=self.get(newKey) if obj: return", "debug=0, pickleProtocol=0, pickler=pickle.Pickler, unpickler=pickle.Unpickler, pload=None, pid=None): self.request=request Client.__init__(self,servers,debug,pickleProtocol, pickler,unpickler,pload,pid) def", "_MemcacheClient(*a, **b) locker.release() return MemcacheClient.__mc_instance class _MemcacheClient(Client): def __init__(self, request,", "def __call__(self,key,f,time_expire=300): #key=self.__keyFormat__(key) value=None obj=self.get(key) if obj: value=obj elif f", "None: if obj: self.delete(key) else: value=f() self.set(key,value,time_expire) return value def", "obj: self.delete(key) else: value=f() self.set(key,value,time_expire) return value def increment(self,key,value=1,time_expire=300): newKey=self.__keyFormat__(key)", "__call__(self,key,f,time_expire=300): #key=self.__keyFormat__(key) value=None obj=self.get(key) if obj: value=obj elif f is", "if obj: self.delete(key) else: value=f() self.set(key,value,time_expire) return value def increment(self,key,value=1,time_expire=300):", "= _MemcacheClient(*a, **b) locker.release() return MemcacheClient.__mc_instance class _MemcacheClient(Client): def __init__(self,", "pickle import thread locker = thread.allocate_lock() def MemcacheClient(*a, **b): locker.acquire()", "not hasattr(MemcacheClient, '__mc_instance'): MemcacheClient.__mc_instance = _MemcacheClient(*a, **b) locker.release() return MemcacheClient.__mc_instance", "unpickler=pickle.Unpickler, pload=None, pid=None): self.request=request Client.__init__(self,servers,debug,pickleProtocol, pickler,unpickler,pload,pid) def __call__(self,key,f,time_expire=300): #key=self.__keyFormat__(key) value=None", "obj=self.get(key) if obj: value=obj elif f is None: if obj:", "import cPickle as pickle import thread locker = thread.allocate_lock() def", "of usage: cache.memcache=MemcacheClient(request,[127.0.0.1:11211],debug=true) \"\"\" import cPickle as pickle import thread", "locker.release() return MemcacheClient.__mc_instance class _MemcacheClient(Client): def __init__(self, request, servers, debug=0,", "pickler=pickle.Pickler, unpickler=pickle.Unpickler, pload=None, pid=None): self.request=request Client.__init__(self,servers,debug,pickleProtocol, pickler,unpickler,pload,pid) def __call__(self,key,f,time_expire=300): #key=self.__keyFormat__(key)", "from gluon.contrib.memcache.memcache import Client import time \"\"\" examle of usage:", "obj: value=obj elif f is None: if obj: self.delete(key) else:", "\"\"\" examle of usage: cache.memcache=MemcacheClient(request,[127.0.0.1:11211],debug=true) \"\"\" import cPickle as pickle", "self.request=request Client.__init__(self,servers,debug,pickleProtocol, pickler,unpickler,pload,pid) def __call__(self,key,f,time_expire=300): #key=self.__keyFormat__(key) value=None obj=self.get(key) if obj:", "locker = thread.allocate_lock() def MemcacheClient(*a, **b): locker.acquire() if not hasattr(MemcacheClient,", "value def set(self,key,value,time_expire=300): newKey = self.__keyFormat__(key) return Client.set(self,newKey,value,time_expire) def get(self,key):", "gluon.contrib.memcache.memcache import Client import time \"\"\" examle of usage: cache.memcache=MemcacheClient(request,[127.0.0.1:11211],debug=true)", "Client.get(self,newKey) def delete(self,key): newKey = self.__keyFormat__(key) return Client.delete(self,newKey) def __keyFormat__(self,key):", "if obj: value=obj elif f is None: if obj: self.delete(key)", "Client.set(self,newKey,value,time_expire) def get(self,key): newKey = self.__keyFormat__(key) return Client.get(self,newKey) def delete(self,key):", "class _MemcacheClient(Client): def __init__(self, request, servers, debug=0, pickleProtocol=0, pickler=pickle.Pickler, unpickler=pickle.Unpickler,", "else: self.set(newKey,value,time_expire) return value def set(self,key,value,time_expire=300): newKey = self.__keyFormat__(key) return", "Client.__init__(self,servers,debug,pickleProtocol, pickler,unpickler,pload,pid) def __call__(self,key,f,time_expire=300): #key=self.__keyFormat__(key) value=None obj=self.get(key) if obj: value=obj", "self.__keyFormat__(key) return Client.set(self,newKey,value,time_expire) def get(self,key): newKey = self.__keyFormat__(key) return Client.get(self,newKey)", "def get(self,key): newKey = self.__keyFormat__(key) return Client.get(self,newKey) def delete(self,key): newKey", "return value def set(self,key,value,time_expire=300): newKey = self.__keyFormat__(key) return Client.set(self,newKey,value,time_expire) def", "hasattr(MemcacheClient, '__mc_instance'): MemcacheClient.__mc_instance = _MemcacheClient(*a, **b) locker.release() return MemcacheClient.__mc_instance class", "def increment(self,key,value=1,time_expire=300): newKey=self.__keyFormat__(key) obj=self.get(newKey) if obj: return Client.incr(self,newKey,value) else: self.set(newKey,value,time_expire)", "locker.acquire() if not hasattr(MemcacheClient, '__mc_instance'): MemcacheClient.__mc_instance = _MemcacheClient(*a, **b) locker.release()", "newKey = self.__keyFormat__(key) return Client.set(self,newKey,value,time_expire) def get(self,key): newKey = self.__keyFormat__(key)", "import thread locker = thread.allocate_lock() def MemcacheClient(*a, **b): locker.acquire() if", "#key=self.__keyFormat__(key) value=None obj=self.get(key) if obj: value=obj elif f is None:", "self.set(newKey,value,time_expire) return value def set(self,key,value,time_expire=300): newKey = self.__keyFormat__(key) return Client.set(self,newKey,value,time_expire)", "examle of usage: cache.memcache=MemcacheClient(request,[127.0.0.1:11211],debug=true) \"\"\" import cPickle as pickle import", "_MemcacheClient(Client): def __init__(self, request, servers, debug=0, pickleProtocol=0, pickler=pickle.Pickler, unpickler=pickle.Unpickler, pload=None,", "self.__keyFormat__(key) return Client.get(self,newKey) def delete(self,key): newKey = self.__keyFormat__(key) return Client.delete(self,newKey)", "set(self,key,value,time_expire=300): newKey = self.__keyFormat__(key) return Client.set(self,newKey,value,time_expire) def get(self,key): newKey =", "obj=self.get(newKey) if obj: return Client.incr(self,newKey,value) else: self.set(newKey,value,time_expire) return value def", "import time \"\"\" examle of usage: cache.memcache=MemcacheClient(request,[127.0.0.1:11211],debug=true) \"\"\" import cPickle", "pickler,unpickler,pload,pid) def __call__(self,key,f,time_expire=300): #key=self.__keyFormat__(key) value=None obj=self.get(key) if obj: value=obj elif", "Client.incr(self,newKey,value) else: self.set(newKey,value,time_expire) return value def set(self,key,value,time_expire=300): newKey = self.__keyFormat__(key)", "MemcacheClient(*a, **b): locker.acquire() if not hasattr(MemcacheClient, '__mc_instance'): MemcacheClient.__mc_instance = _MemcacheClient(*a,", "value=f() self.set(key,value,time_expire) return value def increment(self,key,value=1,time_expire=300): newKey=self.__keyFormat__(key) obj=self.get(newKey) if obj:", "MemcacheClient.__mc_instance class _MemcacheClient(Client): def __init__(self, request, servers, debug=0, pickleProtocol=0, pickler=pickle.Pickler,", "get(self,key): newKey = self.__keyFormat__(key) return Client.get(self,newKey) def delete(self,key): newKey =", "as pickle import thread locker = thread.allocate_lock() def MemcacheClient(*a, **b):", "thread locker = thread.allocate_lock() def MemcacheClient(*a, **b): locker.acquire() if not", "def set(self,key,value,time_expire=300): newKey = self.__keyFormat__(key) return Client.set(self,newKey,value,time_expire) def get(self,key): newKey", "return value def increment(self,key,value=1,time_expire=300): newKey=self.__keyFormat__(key) obj=self.get(newKey) if obj: return Client.incr(self,newKey,value)", "cPickle as pickle import thread locker = thread.allocate_lock() def MemcacheClient(*a,", "time \"\"\" examle of usage: cache.memcache=MemcacheClient(request,[127.0.0.1:11211],debug=true) \"\"\" import cPickle as", "def __init__(self, request, servers, debug=0, pickleProtocol=0, pickler=pickle.Pickler, unpickler=pickle.Unpickler, pload=None, pid=None):", "= thread.allocate_lock() def MemcacheClient(*a, **b): locker.acquire() if not hasattr(MemcacheClient, '__mc_instance'):", "usage: cache.memcache=MemcacheClient(request,[127.0.0.1:11211],debug=true) \"\"\" import cPickle as pickle import thread locker", "value def increment(self,key,value=1,time_expire=300): newKey=self.__keyFormat__(key) obj=self.get(newKey) if obj: return Client.incr(self,newKey,value) else:", "delete(self,key): newKey = self.__keyFormat__(key) return Client.delete(self,newKey) def __keyFormat__(self,key): return '%s/%s'", "thread.allocate_lock() def MemcacheClient(*a, **b): locker.acquire() if not hasattr(MemcacheClient, '__mc_instance'): MemcacheClient.__mc_instance", "Client import time \"\"\" examle of usage: cache.memcache=MemcacheClient(request,[127.0.0.1:11211],debug=true) \"\"\" import", "**b) locker.release() return MemcacheClient.__mc_instance class _MemcacheClient(Client): def __init__(self, request, servers,", "obj: return Client.incr(self,newKey,value) else: self.set(newKey,value,time_expire) return value def set(self,key,value,time_expire=300): newKey", "pid=None): self.request=request Client.__init__(self,servers,debug,pickleProtocol, pickler,unpickler,pload,pid) def __call__(self,key,f,time_expire=300): #key=self.__keyFormat__(key) value=None obj=self.get(key) if", "request, servers, debug=0, pickleProtocol=0, pickler=pickle.Pickler, unpickler=pickle.Unpickler, pload=None, pid=None): self.request=request Client.__init__(self,servers,debug,pickleProtocol,", "return MemcacheClient.__mc_instance class _MemcacheClient(Client): def __init__(self, request, servers, debug=0, pickleProtocol=0,", "else: value=f() self.set(key,value,time_expire) return value def increment(self,key,value=1,time_expire=300): newKey=self.__keyFormat__(key) obj=self.get(newKey) if", "cache.memcache=MemcacheClient(request,[127.0.0.1:11211],debug=true) \"\"\" import cPickle as pickle import thread locker =", "if not hasattr(MemcacheClient, '__mc_instance'): MemcacheClient.__mc_instance = _MemcacheClient(*a, **b) locker.release() return", "is None: if obj: self.delete(key) else: value=f() self.set(key,value,time_expire) return value", "newKey = self.__keyFormat__(key) return Client.get(self,newKey) def delete(self,key): newKey = self.__keyFormat__(key)", "import Client import time \"\"\" examle of usage: cache.memcache=MemcacheClient(request,[127.0.0.1:11211],debug=true) \"\"\"", "elif f is None: if obj: self.delete(key) else: value=f() self.set(key,value,time_expire)", "return Client.set(self,newKey,value,time_expire) def get(self,key): newKey = self.__keyFormat__(key) return Client.get(self,newKey) def", "'__mc_instance'): MemcacheClient.__mc_instance = _MemcacheClient(*a, **b) locker.release() return MemcacheClient.__mc_instance class _MemcacheClient(Client):", "newKey = self.__keyFormat__(key) return Client.delete(self,newKey) def __keyFormat__(self,key): return '%s/%s' %", "increment(self,key,value=1,time_expire=300): newKey=self.__keyFormat__(key) obj=self.get(newKey) if obj: return Client.incr(self,newKey,value) else: self.set(newKey,value,time_expire) return", "pickleProtocol=0, pickler=pickle.Pickler, unpickler=pickle.Unpickler, pload=None, pid=None): self.request=request Client.__init__(self,servers,debug,pickleProtocol, pickler,unpickler,pload,pid) def __call__(self,key,f,time_expire=300):", "= self.__keyFormat__(key) return Client.delete(self,newKey) def __keyFormat__(self,key): return '%s/%s' % (self.request.application,key.replace('", "self.__keyFormat__(key) return Client.delete(self,newKey) def __keyFormat__(self,key): return '%s/%s' % (self.request.application,key.replace(' ','_'))", "value=None obj=self.get(key) if obj: value=obj elif f is None: if", "def delete(self,key): newKey = self.__keyFormat__(key) return Client.delete(self,newKey) def __keyFormat__(self,key): return", "return Client.get(self,newKey) def delete(self,key): newKey = self.__keyFormat__(key) return Client.delete(self,newKey) def", "\"\"\" import cPickle as pickle import thread locker = thread.allocate_lock()", "= self.__keyFormat__(key) return Client.get(self,newKey) def delete(self,key): newKey = self.__keyFormat__(key) return", "= self.__keyFormat__(key) return Client.set(self,newKey,value,time_expire) def get(self,key): newKey = self.__keyFormat__(key) return", "newKey=self.__keyFormat__(key) obj=self.get(newKey) if obj: return Client.incr(self,newKey,value) else: self.set(newKey,value,time_expire) return value", "def MemcacheClient(*a, **b): locker.acquire() if not hasattr(MemcacheClient, '__mc_instance'): MemcacheClient.__mc_instance =", "__init__(self, request, servers, debug=0, pickleProtocol=0, pickler=pickle.Pickler, unpickler=pickle.Unpickler, pload=None, pid=None): self.request=request", "pload=None, pid=None): self.request=request Client.__init__(self,servers,debug,pickleProtocol, pickler,unpickler,pload,pid) def __call__(self,key,f,time_expire=300): #key=self.__keyFormat__(key) value=None obj=self.get(key)", "return Client.incr(self,newKey,value) else: self.set(newKey,value,time_expire) return value def set(self,key,value,time_expire=300): newKey =" ]
[ "\"some_literal\" class Something(Some_enum): pass class Reference: pass __book_url__ = \"dummy\"", "= \"some_literal\" class Something(Some_enum): pass class Reference: pass __book_url__ =", "class Some_enum(Enum): some_literal = \"some_literal\" class Something(Some_enum): pass class Reference:", "class Something(Some_enum): pass class Reference: pass __book_url__ = \"dummy\" __book_version__", "<filename>test_data/parse/unexpected/symbol_table/inheritance_from_non_class/meta_model.py class Some_enum(Enum): some_literal = \"some_literal\" class Something(Some_enum): pass class", "some_literal = \"some_literal\" class Something(Some_enum): pass class Reference: pass __book_url__", "class Reference: pass __book_url__ = \"dummy\" __book_version__ = \"dummy\" associate_ref_with(Reference)", "Some_enum(Enum): some_literal = \"some_literal\" class Something(Some_enum): pass class Reference: pass", "pass class Reference: pass __book_url__ = \"dummy\" __book_version__ = \"dummy\"", "Something(Some_enum): pass class Reference: pass __book_url__ = \"dummy\" __book_version__ =" ]
[ "encoding: utf-8 import numbers import os import re import sys", "default=1.0 ignore terms that have a document frequency higher than", "mask &= dfs <= high if low is not None:", "values, row_indices, col_indices = [], [], [] for r, tokens", "0, 2, 1], [0, 1, 1, 0, 1, 0, 1,", "str, Thai text string custom_dict: str (or list), path to", ">> X.todense() >> [[0, 0, 1, 0, 1, 0, 2,", "threshold min_df : float in range [0.0, 1.0] or int,", "v in enumerate(set(chain.from_iterable(tokenized_documents)))} values, row_indices, col_indices = [], [], []", "a document frequency higher than the given threshold min_df :", "that have a document frequency higher than the given threshold", "self.stop_words = _check_stop_list(stop_words) def _word_ngrams(self, tokens): \"\"\" Turn tokens into", "in tokens: word_index = self.vocabulary_.get(token) if word_index is not None:", "21 if not text: return [''] # case of empty", "===== text: str, Thai text string custom_dict: str (or list),", "allows the function not to tokenize given dictionary wrongly. The", "# assume it's a collection return frozenset(stop) def load_model(file_path): \"\"\"", "None and limit is None: return X, set() # Calculate", "and limit is None: return X, set() # Calculate a", "1, n_original_tokens + 1)): for i in range(n_original_tokens - n", "import CHAR_TYPES_MAP, CHARS_MAP, create_feature_array MODULE_PATH = os.path.dirname(__file__) WEIGHT_PATH = os.path.join(MODULE_PATH,", "separated by line. Alternatively, you can provide list of custom", "self.vocabulary_ = {} self.ngram_range = ngram_range self.dtype = dtype self.max_df", "self.ngram_range = ngram_range self.dtype = dtype self.max_df = max_df self.min_df", "x_char, x_type = create_feature_array(text, n_pad=n_pad) word_end = [] # Fix", "list, list of tokenized words Example ======= >> deepcut.tokenize('ตัดคำได้ดีมาก') >>", "words Example ======= >> deepcut.tokenize('ตัดคำได้ดีมาก') >> ['ตัดคำ','ได้','ดี','มาก'] \"\"\" global TOKENIZER", "self._word_ngrams(tokens) feature = {} for token in tokens: word_index =", "of raw_documents to document-term matrix in sparse CSR format (see", "CSR format (see scipy) \"\"\" X = self.transform(raw_documents, new_document=True) return", "# ref: https://github.com/keras-team/keras/issues/2397 y_predict = self.model.predict([x_char, x_type]) c = [i[0]", "if limit is not None and mask.sum() > limit: tfs", "max_df can be set to value [0.7, 1.0) to automatically", "value for max_df or min_df\") self.max_features = max_features self.stop_words =", ">= low if limit is not None and mask.sum() >", "+ word_length text = text[start_char + word_length:] word_end[first_char:last_char] = (word_length", "if True, assume seeing documents and build a new self.vobabulary_,", "of empty string if isinstance(text, str) and sys.version_info.major == 2:", "non-zero values for each feature in sparse X. \"\"\" if", "None: tokens = [w for w in tokens if w", "https://github.com/keras-team/keras/issues/2397 y_predict = self.model.predict([x_char, x_type]) c = [i[0] for i", "self.vocabulary_, max_doc_count, min_doc_count, self.max_features) return X def fit_tranform(self, raw_documents): \"\"\"", "= np.asarray(X.sum(axis=0)).ravel() mask_inds = (-tfs[mask]).argsort()[:limit] new_mask = np.zeros(len(dfs), dtype=bool) new_mask[np.where(mask)[0][mask_inds]]", "= self._word_ngrams(tokens) tokenized_documents.append(tokens) if new_document: self.vocabulary_ = {v: k for", "mask.sum() > limit: tfs = np.asarray(X.sum(axis=0)).ravel() mask_inds = (-tfs[mask]).argsort()[:limit] new_mask", "len(raw_documents) tokenized_documents = [] for doc in raw_documents: tokens =", "custom words separated by line. Alternatively, you can provide list", "pruning, no terms remain. Try a lower\" \" min_df or", "token n-grams min_n, max_n = self.ngram_range if max_n != 1:", ">> tokenizer.vocabulary_ >> {'นอน': 0, 'ไก่': 1, 'กิน': 2, 'อย่าง':", "# set model to None to successfully save the model", "overhead tokens_append = tokens.append space_join = \" \".join for n", "= tokens.append space_join = \" \".join for n in range(min_n,", "return X[:, kept_indices], removed_terms def transform(self, raw_documents, new_document=False): \"\"\" raw_documents:", "self.vocabulary_ = {v: k for k, v in enumerate(set(chain.from_iterable(tokenized_documents)))} values,", "min_df : float in range [0.0, 1.0] or int, default=1", "to be removed if None, max_df can be set to", "or min_df\") self.max_features = max_features self.stop_words = _check_stop_list(stop_words) def _word_ngrams(self,", "= start_char + initial_loc last_char = first_char + word_length -", "and build a new self.vobabulary_, if False, use the previous", "built-in stop list: %s\" % stop) elif stop is None:", "from .model import get_convo_nn2 from .stop_words import THAI_STOP_WORDS from .utils", "bigram stop_words : list or set, list or set of", "number of non-zero values for each feature in sparse X.", "removed_terms.add(term) kept_indices = np.where(mask)[0] if len(kept_indices) == 0: raise ValueError(\"After", "word_end def _document_frequency(X): \"\"\" Count the number of non-zero values", "elif stop is None: return None # assume it's a", "you can provide list of custom words too. Output ======", "high=None, low=None, limit=None): \"\"\"Remove too rare or too common features.", "tokenized_documents.append(tokens) if new_document: self.vocabulary_ = {v: k for k, v", "of stop words to be removed if None, max_df can", "and (1, 2) for bigram stop_words : list or set,", "if stop == \"thai\": return THAI_STOP_WORDS elif isinstance(stop, six.string_types): raise", "save_model(self, file_path): \"\"\" Save tokenizer to pickle format \"\"\" self.model", "use list of pre-populated stop words max_features : int or", "and mask.sum() > limit: tfs = np.asarray(X.sum(axis=0)).ravel() mask_inds = (-tfs[mask]).argsort()[:limit]", "create_feature_array(text, n_pad=n_pad) word_end = [] # Fix thread-related issue in", "list or set of stop words to be removed if", "low is None and limit is None: return X, set()", "elif isinstance(stop, six.string_types): raise ValueError(\"not a built-in stop list: %s\"", "issue in Keras + TensorFlow + Flask async environment #", "frozenset(stop) def load_model(file_path): \"\"\" Load saved pickle file of DeepcutTokenizer", "first_char = start_char + initial_loc last_char = first_char + word_length", "feature = {} for token in tokens: word_index = self.vocabulary_.get(token)", "6, 'ข้าว': 7} \"\"\" def __init__(self, ngram_range=(1, 1), stop_words=None, max_df=1.0,", "dtype=bool) new_mask[np.where(mask)[0][mask_inds]] = True mask = new_mask new_indices = np.cumsum(mask)", "def transform(self, raw_documents, new_document=False): \"\"\" raw_documents: list, list of new", "min(max_n + 1, n_original_tokens + 1)): for i in range(n_original_tokens", "tokens): \"\"\" Turn tokens into a tokens of n-grams ref:", "load_model(file_path): \"\"\" Load saved pickle file of DeepcutTokenizer Parameters ==========", "0, 1, 0, 1, 0, 2, 1], [0, 1, 1,", "= dtype self.max_df = max_df self.min_df = min_df if max_df", "= tokenizer.model.load_weights(WEIGHT_PATH) return tokenizer class DeepcutTokenizer(object): \"\"\" Class for tokenizing", "of n-grams ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153 \"\"\" # handle stop words if", "file tokens = self._word_ngrams(tokens) tokenized_documents.append(tokens) if new_document: self.vocabulary_ = {v:", "X, _ = self._limit_features(X, self.vocabulary_, max_doc_count, min_doc_count, self.max_features) return X", "sp import six import pickle from .model import get_convo_nn2 from", "document frequency higher than the given threshold min_df : float", "in range [0.0, 1.0] or int, default=1 ignore terms that", "in sparse CSR format >> X.todense() >> [[0, 0, 1,", "``save_model`` method in DeepcutTokenizer \"\"\" tokenizer = pickle.load(open(file_path, 'rb')) tokenizer.model", "X[:, kept_indices], removed_terms def transform(self, raw_documents, new_document=False): \"\"\" raw_documents: list,", "min_df = self.min_df max_doc_count = (max_df if isinstance(max_df, numbers.Integral) else", "copy=False).indptr) def _check_stop_list(stop): \"\"\" Check stop words list ref: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95", "method in DeepcutTokenizer \"\"\" tokenizer = pickle.load(open(file_path, 'rb')) tokenizer.model =", "numbers.Integral) else min_df * n_doc) if max_doc_count < min_doc_count: raise", "= self.model.predict([x_char, x_type]) c = [i[0] for i in y_predict.tolist()]", "max_features=None, dtype=np.dtype('float64')): self.model = get_convo_nn2() self.model.load_weights(WEIGHT_PATH) self.vocabulary_ = {} self.ngram_range", "# case of empty string if isinstance(text, str) and sys.version_info.major", "'weight', 'cnn_without_ne_ab.h5') TOKENIZER = None def tokenize(text, custom_dict=None): \"\"\" Tokenize", "0 or min_df < 0: raise ValueError(\"negative value for max_df", "+ 1)): for i in range(n_original_tokens - n + 1):", "truncate vocabulary by max_df and min_df if new_document: max_df =", "+ word_length:] word_end[first_char:last_char] = (word_length - 1) * [0] word_end[last_char]", "= max_features self.stop_words = _check_stop_list(stop_words) def _word_ngrams(self, tokens): \"\"\" Turn", "ignore terms that have a document frequency lower than the", "= np.ones(len(dfs), dtype=bool) if high is not None: mask &=", "new removed_terms = set() for term, old_index in list(vocabulary.items()): if", "if not text: return [''] # case of empty string", "= tokenize(doc) # method in this file tokens = self._word_ngrams(tokens)", "set of stop words to be removed if None, max_df", "word_index is not None: if word_index not in feature.keys(): feature[word_index]", "list(zip(list(text),c)) def save_model(self, file_path): \"\"\" Save tokenizer to pickle format", "int, default=1.0 ignore terms that have a document frequency higher", "y_predict.tolist()] return list(zip(list(text),c)) def save_model(self, file_path): \"\"\" Save tokenizer to", "low if limit is not None and mask.sum() > limit:", "1: # no need to do any slicing for unigrams", "self.model.load_weights(WEIGHT_PATH) self.vocabulary_ = {} self.ngram_range = ngram_range self.dtype = dtype", "[] n_original_tokens = len(original_tokens) # bind method outside of loop", "- 1 initial_loc += start_char + word_length text = text[start_char", "higher max_df.\") return X[:, kept_indices], removed_terms def transform(self, raw_documents, new_document=False):", "need to do any slicing for unigrams # just iterate", "max_df.\") return X[:, kept_indices], removed_terms def transform(self, raw_documents, new_document=False): \"\"\"", "========== file_path: str, path to saved model from ``save_model`` method", "def fit_tranform(self, raw_documents): \"\"\" Transform given list of raw_documents to", "[] # Fix thread-related issue in Keras + TensorFlow +", "a tokens of n-grams ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153 \"\"\" # handle stop", "== 1: # no need to do any slicing for", "to new removed_terms = set() for term, old_index in list(vocabulary.items()):", "import sys from itertools import chain import numpy as np", "feature[word_index] = 1 else: feature[word_index] += 1 for c, v", "# truncate vocabulary by max_df and min_df if new_document: max_df", "= 1 except: break return word_end def _document_frequency(X): \"\"\" Count", "======= raw_documents = ['ฉันอยากกินข้าวของฉัน', 'ฉันอยากกินไก่', 'อยากนอนอย่างสงบ'] tokenizer = DeepcutTokenizer(ngram_range=(1, 1))", "is not None: if word_index not in feature.keys(): feature[word_index] =", "max_features : int or None, if provided, only consider number", "= _check_stop_list(stop_words) def _word_ngrams(self, tokens): \"\"\" Turn tokens into a", "not None: if word_index not in feature.keys(): feature[word_index] = 1", "= (max_df if isinstance(max_df, numbers.Integral) else max_df * n_doc) min_doc_count", "% stop) elif stop is None: return None # assume", "file should contain custom words separated by line. Alternatively, you", "saved pickle file of DeepcutTokenizer Parameters ========== file_path: str, path", "tokenizer = DeepcutTokenizer(ngram_range=(1, 1)) X = tokenizer.fit_tranform(raw_documents) # document-term matrix", "self.stop_words] # handle token n-grams min_n, max_n = self.ngram_range if", "_document_frequency(X): \"\"\" Count the number of non-zero values for each", "It allows the function not to tokenize given dictionary wrongly.", "[w for w in tokens if w not in self.stop_words]", "new self.vobabulary_, if False, use the previous self.vocabulary_ \"\"\" n_doc", "if None, max_df can be set to value [0.7, 1.0)", "* n_doc) min_doc_count = (min_df if isinstance(min_df, numbers.Integral) else min_df", "for vocabulary, (1, 1) for unigram and (1, 2) for", "1, 1, 0, 0]] >> tokenizer.vocabulary_ >> {'นอน': 0, 'ไก่':", "&= dfs >= low if limit is not None and", "new_indices = np.cumsum(mask) - 1 # maps old indices to", "%s\" % stop) elif stop is None: return None #", "text string Input ===== text: str, Thai text string custom_dict:", "threshold dtype : type, optional Example ======= raw_documents = ['ฉันอยากกินข้าวของฉัน',", "raw_documents, new_document=False): \"\"\" raw_documents: list, list of new documents to", "given dictionary wrongly. The file should contain custom words separated", "# method in this file tokens = self._word_ngrams(tokens) tokenized_documents.append(tokens) if", "= os.path.dirname(__file__) WEIGHT_PATH = os.path.join(MODULE_PATH, 'weight', 'cnn_without_ne_ab.h5') TOKENIZER = None", "= len(original_tokens) # bind method outside of loop to reduce", "0, 'ไก่': 1, 'กิน': 2, 'อย่าง': 3, 'อยาก': 4, 'สงบ':", "or a higher max_df.\") return X[:, kept_indices], removed_terms def transform(self,", "initial_loc = 0 while True: try: start_char = re.search(word, text).start()", "int, default=1 ignore terms that have a document frequency lower", "\"\"\" def __init__(self, ngram_range=(1, 1), stop_words=None, max_df=1.0, min_df=1, max_features=None, dtype=np.dtype('float64')):", "minlength=X.shape[1]) return np.diff(sp.csc_matrix(X, copy=False).indptr) def _check_stop_list(stop): \"\"\" Check stop words", "2, 1], [0, 1, 1, 0, 1, 0, 1, 0],", "vocabulary by max_df and min_df if new_document: max_df = self.max_df", "text, custom_dict=None): n_pad = 21 if not text: return ['']", "DeepcutTokenizer \"\"\" tokenizer = pickle.load(open(file_path, 'rb')) tokenizer.model = get_convo_nn2() tokenizer.model", "given Thai text string Input ===== text: str, Thai text", "X = sp.csr_matrix((values, (row_indices, col_indices)), shape=(n_doc, len(self.vocabulary_)), dtype=self.dtype) # truncate", "[0.7, 1.0) to automatically remove vocabulary. If using \"thai\", this", "= self.ngram_range if max_n != 1: original_tokens = tokens if", "_limit_features(self, X, vocabulary, high=None, low=None, limit=None): \"\"\"Remove too rare or", "1, 0, 1, 0, 2, 1], [0, 1, 1, 0,", "re import sys from itertools import chain import numpy as", "higher than the given threshold min_df : float in range", "1 else: feature[word_index] += 1 for c, v in feature.items():", "self.min_df max_doc_count = (max_df if isinstance(max_df, numbers.Integral) else max_df *", "<= high if low is not None: mask &= dfs", "raise ValueError(\"negative value for max_df or min_df\") self.max_features = max_features", "1): tokens_append(space_join(original_tokens[i: i + n])) return tokens def _limit_features(self, X,", "========== ngram_range : tuple, tuple for ngram range for vocabulary,", "of DeepcutTokenizer Parameters ========== file_path: str, path to saved model", "path to saved model from ``save_model`` method in DeepcutTokenizer \"\"\"", "If using \"thai\", this will use list of pre-populated stop", "str, path to saved model from ``save_model`` method in DeepcutTokenizer", "value [0.7, 1.0) to automatically remove vocabulary. If using \"thai\",", "dtype : type, optional Example ======= raw_documents = ['ฉันอยากกินข้าวของฉัน', 'ฉันอยากกินไก่',", "1) for unigram and (1, 2) for bigram stop_words :", "float in range [0.0, 1.0] or int, default=1.0 ignore terms", "Flask async environment # ref: https://github.com/keras-team/keras/issues/2397 y_predict = self.model.predict([x_char, x_type])", "not None and mask.sum() > limit: tfs = np.asarray(X.sum(axis=0)).ravel() mask_inds", "None to successfully save the model with open(file_path, 'wb') as", "or set, list or set of stop words to be", "= {v: k for k, v in enumerate(set(chain.from_iterable(tokenized_documents)))} values, row_indices,", "self.max_features = max_features self.stop_words = _check_stop_list(stop_words) def _word_ngrams(self, tokens): \"\"\"", "raw_documents = ['ฉันอยากกินข้าวของฉัน', 'ฉันอยากกินไก่', 'อยากนอนอย่างสงบ'] tokenizer = DeepcutTokenizer(ngram_range=(1, 1)) X", "CSR format >> X.todense() >> [[0, 0, 1, 0, 1,", "def tokenize(text, custom_dict=None): \"\"\" Tokenize given Thai text string Input", "+ initial_loc last_char = first_char + word_length - 1 initial_loc", "tokenized words Example ======= >> deepcut.tokenize('ตัดคำได้ดีมาก') >> ['ตัดคำ','ได้','ดี','มาก'] \"\"\" global", "is not None: mask &= dfs >= low if limit", "list(vocabulary.items()): if mask[old_index]: vocabulary[term] = new_indices[old_index] else: del vocabulary[term] removed_terms.add(term)", "Example ======= raw_documents = ['ฉันอยากกินข้าวของฉัน', 'ฉันอยากกินไก่', 'อยากนอนอย่างสงบ'] tokenizer = DeepcutTokenizer(ngram_range=(1,", "new_mask[np.where(mask)[0][mask_inds]] = True mask = new_mask new_indices = np.cumsum(mask) -", "Thai text string custom_dict: str (or list), path to customized", "'อย่าง': 3, 'อยาก': 4, 'สงบ': 5, 'ฉัน': 6, 'ข้าว': 7}", "Turn tokens into a tokens of n-grams ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153 \"\"\"", "#!/usr/bin/env python # encoding: utf-8 import numbers import os import", "'rb')) tokenizer.model = get_convo_nn2() tokenizer.model = tokenizer.model.load_weights(WEIGHT_PATH) return tokenizer class", "or too common features. ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L734-L773 \"\"\" if high is", "if max_df < 0 or min_df < 0: raise ValueError(\"negative", "the original tokens tokens = list(original_tokens) min_n += 1 else:", "min_n += 1 else: tokens = [] n_original_tokens = len(original_tokens)", "in range(min_n, min(max_n + 1, n_original_tokens + 1)): for i", "removed_terms = set() for term, old_index in list(vocabulary.items()): if mask[old_index]:", "pickle file of DeepcutTokenizer Parameters ========== file_path: str, path to", "tokenizing given Thai text documents using deepcut library Parameters ==========", "for k, v in enumerate(set(chain.from_iterable(tokenized_documents)))} values, row_indices, col_indices = [],", "only consider number of vocabulary ordered by term frequencies max_df", "min_doc_count = (min_df if isinstance(min_df, numbers.Integral) else min_df * n_doc)", "stop_words=None, max_df=1.0, min_df=1, max_features=None, dtype=np.dtype('float64')): self.model = get_convo_nn2() self.model.load_weights(WEIGHT_PATH) self.vocabulary_", "be set to value [0.7, 1.0) to automatically remove vocabulary.", "x_type = create_feature_array(text, n_pad=n_pad) word_end = [] # Fix thread-related", "async environment # ref: https://github.com/keras-team/keras/issues/2397 y_predict = self.model.predict([x_char, x_type]) c", "set model to None to successfully save the model with", "into a tokens of n-grams ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153 \"\"\" # handle", "tokens tokens = list(original_tokens) min_n += 1 else: tokens =", "min_df or a higher max_df.\") return X[:, kept_indices], removed_terms def", "\"\"\" n_doc = len(raw_documents) tokenized_documents = [] for doc in", "min_df=1, max_features=None, dtype=np.dtype('float64')): self.model = get_convo_nn2() self.model.load_weights(WEIGHT_PATH) self.vocabulary_ = {}", "self._limit_features(X, self.vocabulary_, max_doc_count, min_doc_count, self.max_features) return X def fit_tranform(self, raw_documents):", "n_doc = len(raw_documents) tokenized_documents = [] for doc in raw_documents:", "float in range [0.0, 1.0] or int, default=1 ignore terms", ": list or set, list or set of stop words", "tokens.append space_join = \" \".join for n in range(min_n, min(max_n", "shape=(n_doc, len(self.vocabulary_)), dtype=self.dtype) # truncate vocabulary by max_df and min_df", "isinstance(stop, six.string_types): raise ValueError(\"not a built-in stop list: %s\" %", "feature in sparse X. \"\"\" if sp.isspmatrix_csr(X): return np.bincount(X.indices, minlength=X.shape[1])", "ValueError(\"not a built-in stop list: %s\" % stop) elif stop", "Input ===== text: str, Thai text string custom_dict: str (or", "- 1) * [0] word_end[last_char] = 1 except: break return", "self.min_df = min_df if max_df < 0 or min_df <", "feature[word_index] += 1 for c, v in feature.items(): values.append(v) row_indices.append(r)", "mask based on document frequencies dfs = _document_frequency(X) mask =", "4, 'สงบ': 5, 'ฉัน': 6, 'ข้าว': 7} \"\"\" def __init__(self,", "no terms remain. Try a lower\" \" min_df or a", "import THAI_STOP_WORDS from .utils import CHAR_TYPES_MAP, CHARS_MAP, create_feature_array MODULE_PATH =", "\"\"\" Save tokenizer to pickle format \"\"\" self.model = None", "n-grams ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153 \"\"\" # handle stop words if self.stop_words", "True: try: start_char = re.search(word, text).start() first_char = start_char +", "no need to do any slicing for unigrams # just", "new_mask = np.zeros(len(dfs), dtype=bool) new_mask[np.where(mask)[0][mask_inds]] = True mask = new_mask", "c, v in feature.items(): values.append(v) row_indices.append(r) col_indices.append(c) # document-term matrix", "min_df if new_document: max_df = self.max_df min_df = self.min_df max_doc_count", "text.decode('utf-8') x_char, x_type = create_feature_array(text, n_pad=n_pad) word_end = [] #", "np.bincount(X.indices, minlength=X.shape[1]) return np.diff(sp.csc_matrix(X, copy=False).indptr) def _check_stop_list(stop): \"\"\" Check stop", "= pickle.load(open(file_path, 'rb')) tokenizer.model = get_convo_nn2() tokenizer.model = tokenizer.model.load_weights(WEIGHT_PATH) return", "tokens = self._word_ngrams(tokens) feature = {} for token in tokens:", "[0, 1, 1, 0, 1, 0, 1, 0], [1, 0,", "(1, 2) for bigram stop_words : list or set, list", "outside of loop to reduce overhead tokens_append = tokens.append space_join", "min_df * n_doc) if max_doc_count < min_doc_count: raise ValueError( \"max_df", "list of custom words too. Output ====== tokens: list, list", "Output ====== tokens: list, list of tokenized words Example =======", "list: %s\" % stop) elif stop is None: return None", "None, if provided, only consider number of vocabulary ordered by", "than min_df\") X, _ = self._limit_features(X, self.vocabulary_, max_doc_count, min_doc_count, self.max_features)", "stop list: %s\" % stop) elif stop is None: return", "consider number of vocabulary ordered by term frequencies max_df :", "[] for doc in raw_documents: tokens = tokenize(doc) # method", "get_convo_nn2() tokenizer.model = tokenizer.model.load_weights(WEIGHT_PATH) return tokenizer class DeepcutTokenizer(object): \"\"\" Class", "0: raise ValueError(\"negative value for max_df or min_df\") self.max_features =", "in Keras + TensorFlow + Flask async environment # ref:", "text = text.decode('utf-8') x_char, x_type = create_feature_array(text, n_pad=n_pad) word_end =", "document frequencies dfs = _document_frequency(X) mask = np.ones(len(dfs), dtype=bool) if", "limit is not None and mask.sum() > limit: tfs =", "\"\"\" Turn tokens into a tokens of n-grams ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153", "# handle token n-grams min_n, max_n = self.ngram_range if max_n", "= new_indices[old_index] else: del vocabulary[term] removed_terms.add(term) kept_indices = np.where(mask)[0] if", "space_join = \" \".join for n in range(min_n, min(max_n +", "len(self.vocabulary_)), dtype=self.dtype) # truncate vocabulary by max_df and min_df if", "= self.max_df min_df = self.min_df max_doc_count = (max_df if isinstance(max_df,", "in y_predict.tolist()] return list(zip(list(text),c)) def save_model(self, file_path): \"\"\" Save tokenizer", "i + n])) return tokens def _limit_features(self, X, vocabulary, high=None,", "is not None and mask.sum() > limit: tfs = np.asarray(X.sum(axis=0)).ravel()", "if w not in self.stop_words] # handle token n-grams min_n,", "provide list of custom words too. Output ====== tokens: list,", "is None and limit is None: return X, set() #", "1 # maps old indices to new removed_terms = set()", "(max_df if isinstance(max_df, numbers.Integral) else max_df * n_doc) min_doc_count =", "from .utils import CHAR_TYPES_MAP, CHARS_MAP, create_feature_array MODULE_PATH = os.path.dirname(__file__) WEIGHT_PATH", "'cnn_without_ne_ab.h5') TOKENIZER = None def tokenize(text, custom_dict=None): \"\"\" Tokenize given", "del vocabulary[term] removed_terms.add(term) kept_indices = np.where(mask)[0] if len(kept_indices) == 0:", "k, v in enumerate(set(chain.from_iterable(tokenized_documents)))} values, row_indices, col_indices = [], [],", "5, 'ฉัน': 6, 'ข้าว': 7} \"\"\" def __init__(self, ngram_range=(1, 1),", "text string custom_dict: str (or list), path to customized dictionary", "format (see scipy) \"\"\" X = self.transform(raw_documents, new_document=True) return X", "for max_df or min_df\") self.max_features = max_features self.stop_words = _check_stop_list(stop_words)", "word_length text = text[start_char + word_length:] word_end[first_char:last_char] = (word_length -", "python # encoding: utf-8 import numbers import os import re", "list(original_tokens) min_n += 1 else: tokens = [] n_original_tokens =", "n_original_tokens = len(original_tokens) # bind method outside of loop to", "self.max_df min_df = self.min_df max_doc_count = (max_df if isinstance(max_df, numbers.Integral)", "format X = sp.csr_matrix((values, (row_indices, col_indices)), shape=(n_doc, len(self.vocabulary_)), dtype=self.dtype) #", "row_indices.append(r) col_indices.append(c) # document-term matrix in CSR format X =", "[0] word_end[last_char] = 1 except: break return word_end def _document_frequency(X):", "file_path): \"\"\" Save tokenizer to pickle format \"\"\" self.model =", "if isinstance(max_df, numbers.Integral) else max_df * n_doc) min_doc_count = (min_df", "= self._word_ngrams(tokens) feature = {} for token in tokens: word_index", "max_df = self.max_df min_df = self.min_df max_doc_count = (max_df if", "in sparse CSR format (see scipy) \"\"\" X = self.transform(raw_documents,", "\"max_df corresponds to < documents than min_df\") X, _ =", ".model import get_convo_nn2 from .stop_words import THAI_STOP_WORDS from .utils import", "class DeepcutTokenizer(object): \"\"\" Class for tokenizing given Thai text documents", "def _word_ngrams(self, tokens): \"\"\" Turn tokens into a tokens of", "[] for r, tokens in enumerate(tokenized_documents): tokens = self._word_ngrams(tokens) feature", "or int, default=1 ignore terms that have a document frequency", "if new_document: self.vocabulary_ = {v: k for k, v in", "tokenizer.model.load_weights(WEIGHT_PATH) return tokenizer class DeepcutTokenizer(object): \"\"\" Class for tokenizing given", "in CSR format X = sp.csr_matrix((values, (row_indices, col_indices)), shape=(n_doc, len(self.vocabulary_)),", "else: del vocabulary[term] removed_terms.add(term) kept_indices = np.where(mask)[0] if len(kept_indices) ==", "= list(original_tokens) min_n += 1 else: tokens = [] n_original_tokens", "w not in self.stop_words] # handle token n-grams min_n, max_n", "range [0.0, 1.0] or int, default=1 ignore terms that have", "# document-term matrix in sparse CSR format >> X.todense() >>", "def load_model(file_path): \"\"\" Load saved pickle file of DeepcutTokenizer Parameters", "custom_dict=custom_dict) def _custom_dict(word, text, word_end): word_length = len(word) initial_loc =", "terms that have a document frequency lower than the given", "customized dictionary file It allows the function not to tokenize", "import chain import numpy as np import scipy.sparse as sp", "set, list or set of stop words to be removed", "True mask = new_mask new_indices = np.cumsum(mask) - 1 #", "method in this file tokens = self._word_ngrams(tokens) tokenized_documents.append(tokens) if new_document:", "for r, tokens in enumerate(tokenized_documents): tokens = self._word_ngrams(tokens) feature =", "model to None to successfully save the model with open(file_path,", "# maps old indices to new removed_terms = set() for", "c = [i[0] for i in y_predict.tolist()] return list(zip(list(text),c)) def", "np.zeros(len(dfs), dtype=bool) new_mask[np.where(mask)[0][mask_inds]] = True mask = new_mask new_indices =", "word_end[first_char:last_char] = (word_length - 1) * [0] word_end[last_char] = 1", "ngram range for vocabulary, (1, 1) for unigram and (1,", "return THAI_STOP_WORDS elif isinstance(stop, six.string_types): raise ValueError(\"not a built-in stop", "old_index in list(vocabulary.items()): if mask[old_index]: vocabulary[term] = new_indices[old_index] else: del", "Tokenize given Thai text string Input ===== text: str, Thai", "None: if word_index not in feature.keys(): feature[word_index] = 1 else:", "dtype=self.dtype) # truncate vocabulary by max_df and min_df if new_document:", "# Fix thread-related issue in Keras + TensorFlow + Flask", "return word_end def _document_frequency(X): \"\"\" Count the number of non-zero", "vocabulary, high=None, low=None, limit=None): \"\"\"Remove too rare or too common", "else: tokens = [] n_original_tokens = len(original_tokens) # bind method", "raise ValueError(\"not a built-in stop list: %s\" % stop) elif", "= {} self.ngram_range = ngram_range self.dtype = dtype self.max_df =", "{} for token in tokens: word_index = self.vocabulary_.get(token) if word_index", "term frequencies max_df : float in range [0.0, 1.0] or", "from ``save_model`` method in DeepcutTokenizer \"\"\" tokenizer = pickle.load(open(file_path, 'rb'))", "word_index = self.vocabulary_.get(token) if word_index is not None: if word_index", "to < documents than min_df\") X, _ = self._limit_features(X, self.vocabulary_,", "tuple for ngram range for vocabulary, (1, 1) for unigram", "TOKENIZER.tokenize(text, custom_dict=custom_dict) def _custom_dict(word, text, word_end): word_length = len(word) initial_loc", "except: break return word_end def _document_frequency(X): \"\"\" Count the number", "- 1 # maps old indices to new removed_terms =", "in self.stop_words] # handle token n-grams min_n, max_n = self.ngram_range", "Check stop words list ref: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95 \"\"\" if stop ==", "tokenize(self, text, custom_dict=None): n_pad = 21 if not text: return", "handle stop words if self.stop_words is not None: tokens =", "= len(word) initial_loc = 0 while True: try: start_char =", "using deepcut library Parameters ========== ngram_range : tuple, tuple for", "0, 0]] >> tokenizer.vocabulary_ >> {'นอน': 0, 'ไก่': 1, 'กิน':", "values for each feature in sparse X. \"\"\" if sp.isspmatrix_csr(X):", "and min_df if new_document: max_df = self.max_df min_df = self.min_df", "to saved model from ``save_model`` method in DeepcutTokenizer \"\"\" tokenizer", "row_indices, col_indices = [], [], [] for r, tokens in", "doc in raw_documents: tokens = tokenize(doc) # method in this", "None # assume it's a collection return frozenset(stop) def load_model(file_path):", "assume it's a collection return frozenset(stop) def load_model(file_path): \"\"\" Load", "custom words too. Output ====== tokens: list, list of tokenized", "in this file tokens = self._word_ngrams(tokens) tokenized_documents.append(tokens) if new_document: self.vocabulary_", "Save tokenizer to pickle format \"\"\" self.model = None #", "to customized dictionary file It allows the function not to", "n_pad = 21 if not text: return [''] # case", "high is None and low is None and limit is", "pickle from .model import get_convo_nn2 from .stop_words import THAI_STOP_WORDS from", "1 initial_loc += start_char + word_length text = text[start_char +", "tuple, tuple for ngram range for vocabulary, (1, 1) for", "\"\"\" # handle stop words if self.stop_words is not None:", "== 2: text = text.decode('utf-8') x_char, x_type = create_feature_array(text, n_pad=n_pad)", "= [] n_original_tokens = len(original_tokens) # bind method outside of", "= {} for token in tokens: word_index = self.vocabulary_.get(token) if", "deepcut library Parameters ========== ngram_range : tuple, tuple for ngram", "for ngram range for vocabulary, (1, 1) for unigram and", "if False, use the previous self.vocabulary_ \"\"\" n_doc = len(raw_documents)", "max_doc_count < min_doc_count: raise ValueError( \"max_df corresponds to < documents", "build a new self.vobabulary_, if False, use the previous self.vocabulary_", "not text: return [''] # case of empty string if", "len(word) initial_loc = 0 while True: try: start_char = re.search(word,", "np import scipy.sparse as sp import six import pickle from", "\"\"\" Tokenize given Thai text string Input ===== text: str,", "= self._limit_features(X, self.vocabulary_, max_doc_count, min_doc_count, self.max_features) return X def fit_tranform(self,", "have a document frequency lower than the given threshold dtype", "[0.0, 1.0] or int, default=1.0 ignore terms that have a", "{} self.ngram_range = ngram_range self.dtype = dtype self.max_df = max_df", "mask[old_index]: vocabulary[term] = new_indices[old_index] else: del vocabulary[term] removed_terms.add(term) kept_indices =", "given list of raw_documents to document-term matrix in sparse CSR", "a new self.vobabulary_, if False, use the previous self.vocabulary_ \"\"\"", "in list(vocabulary.items()): if mask[old_index]: vocabulary[term] = new_indices[old_index] else: del vocabulary[term]", "frequency higher than the given threshold min_df : float in", "1)) X = tokenizer.fit_tranform(raw_documents) # document-term matrix in sparse CSR", "# handle stop words if self.stop_words is not None: tokens", "scipy) \"\"\" X = self.transform(raw_documents, new_document=True) return X def tokenize(self,", "tokenizer to pickle format \"\"\" self.model = None # set", "1.0) to automatically remove vocabulary. If using \"thai\", this will", "chain import numpy as np import scipy.sparse as sp import", "vocabulary. If using \"thai\", this will use list of pre-populated", "else max_df * n_doc) min_doc_count = (min_df if isinstance(min_df, numbers.Integral)", "corresponds to < documents than min_df\") X, _ = self._limit_features(X,", "matrix in CSR format X = sp.csr_matrix((values, (row_indices, col_indices)), shape=(n_doc,", "self.model.predict([x_char, x_type]) c = [i[0] for i in y_predict.tolist()] return", "documents to be transformed new_document: bool, if True, assume seeing", "TOKENIZER = None def tokenize(text, custom_dict=None): \"\"\" Tokenize given Thai", "the function not to tokenize given dictionary wrongly. The file", "x_type]) c = [i[0] for i in y_predict.tolist()] return list(zip(list(text),c))", "import get_convo_nn2 from .stop_words import THAI_STOP_WORDS from .utils import CHAR_TYPES_MAP,", "if max_n != 1: original_tokens = tokens if min_n ==", "= np.cumsum(mask) - 1 # maps old indices to new", "range(n_original_tokens - n + 1): tokens_append(space_join(original_tokens[i: i + n])) return", "Load saved pickle file of DeepcutTokenizer Parameters ========== file_path: str,", "words too. Output ====== tokens: list, list of tokenized words", "empty string if isinstance(text, str) and sys.version_info.major == 2: text", "np.cumsum(mask) - 1 # maps old indices to new removed_terms", "create_feature_array MODULE_PATH = os.path.dirname(__file__) WEIGHT_PATH = os.path.join(MODULE_PATH, 'weight', 'cnn_without_ne_ab.h5') TOKENIZER", "tokenizer.model = tokenizer.model.load_weights(WEIGHT_PATH) return tokenizer class DeepcutTokenizer(object): \"\"\" Class for", "sp.isspmatrix_csr(X): return np.bincount(X.indices, minlength=X.shape[1]) return np.diff(sp.csc_matrix(X, copy=False).indptr) def _check_stop_list(stop): \"\"\"", "max_df : float in range [0.0, 1.0] or int, default=1.0", "> limit: tfs = np.asarray(X.sum(axis=0)).ravel() mask_inds = (-tfs[mask]).argsort()[:limit] new_mask =", "======= >> deepcut.tokenize('ตัดคำได้ดีมาก') >> ['ตัดคำ','ได้','ดี','มาก'] \"\"\" global TOKENIZER if not", "using \"thai\", this will use list of pre-populated stop words", "enumerate(set(chain.from_iterable(tokenized_documents)))} values, row_indices, col_indices = [], [], [] for r,", "X, vocabulary, high=None, low=None, limit=None): \"\"\"Remove too rare or too", "self.ngram_range if max_n != 1: original_tokens = tokens if min_n", "1.0] or int, default=1 ignore terms that have a document", "'ฉันอยากกินไก่', 'อยากนอนอย่างสงบ'] tokenizer = DeepcutTokenizer(ngram_range=(1, 1)) X = tokenizer.fit_tranform(raw_documents) #", "(or list), path to customized dictionary file It allows the", "than the given threshold min_df : float in range [0.0,", "== 0: raise ValueError(\"After pruning, no terms remain. Try a", "features. ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L734-L773 \"\"\" if high is None and low", "if len(kept_indices) == 0: raise ValueError(\"After pruning, no terms remain.", "of tokenized words Example ======= >> deepcut.tokenize('ตัดคำได้ดีมาก') >> ['ตัดคำ','ได้','ดี','มาก'] \"\"\"", "words list ref: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95 \"\"\" if stop == \"thai\": return", "max_df or min_df\") self.max_features = max_features self.stop_words = _check_stop_list(stop_words) def", "isinstance(text, str) and sys.version_info.major == 2: text = text.decode('utf-8') x_char,", "numpy as np import scipy.sparse as sp import six import", "stop words list ref: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95 \"\"\" if stop == \"thai\":", "than the given threshold dtype : type, optional Example =======", "not in feature.keys(): feature[word_index] = 1 else: feature[word_index] += 1", "if word_index not in feature.keys(): feature[word_index] = 1 else: feature[word_index]", "[[0, 0, 1, 0, 1, 0, 2, 1], [0, 1,", "max_doc_count = (max_df if isinstance(max_df, numbers.Integral) else max_df * n_doc)", "raw_documents): \"\"\" Transform given list of raw_documents to document-term matrix", "= None # set model to None to successfully save", "matrix in sparse CSR format >> X.todense() >> [[0, 0,", "do any slicing for unigrams # just iterate through the", "\"\"\" raw_documents: list, list of new documents to be transformed", "high if low is not None: mask &= dfs >=", "words max_features : int or None, if provided, only consider", "tokens def _limit_features(self, X, vocabulary, high=None, low=None, limit=None): \"\"\"Remove too", "def _limit_features(self, X, vocabulary, high=None, low=None, limit=None): \"\"\"Remove too rare", "\"\"\" Class for tokenizing given Thai text documents using deepcut", "< 0: raise ValueError(\"negative value for max_df or min_df\") self.max_features", "n_pad=n_pad) word_end = [] # Fix thread-related issue in Keras", "text).start() first_char = start_char + initial_loc last_char = first_char +", "model from ``save_model`` method in DeepcutTokenizer \"\"\" tokenizer = pickle.load(open(file_path,", "sparse CSR format >> X.todense() >> [[0, 0, 1, 0,", "to reduce overhead tokens_append = tokens.append space_join = \" \".join", "stop_words : list or set, list or set of stop", "str) and sys.version_info.major == 2: text = text.decode('utf-8') x_char, x_type", "be removed if None, max_df can be set to value", "= _document_frequency(X) mask = np.ones(len(dfs), dtype=bool) if high is not", "too. Output ====== tokens: list, list of tokenized words Example", "previous self.vocabulary_ \"\"\" n_doc = len(raw_documents) tokenized_documents = [] for", "None, max_df can be set to value [0.7, 1.0) to", "removed_terms def transform(self, raw_documents, new_document=False): \"\"\" raw_documents: list, list of", "\"thai\", this will use list of pre-populated stop words max_features", "os.path.dirname(__file__) WEIGHT_PATH = os.path.join(MODULE_PATH, 'weight', 'cnn_without_ne_ab.h5') TOKENIZER = None def", "_check_stop_list(stop_words) def _word_ngrams(self, tokens): \"\"\" Turn tokens into a tokens", "string Input ===== text: str, Thai text string custom_dict: str", "list ref: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95 \"\"\" if stop == \"thai\": return THAI_STOP_WORDS", "a built-in stop list: %s\" % stop) elif stop is", "raw_documents to document-term matrix in sparse CSR format (see scipy)", "of custom words too. Output ====== tokens: list, list of", "1], [0, 1, 1, 0, 1, 0, 1, 0], [1,", "seeing documents and build a new self.vobabulary_, if False, use", "feature.items(): values.append(v) row_indices.append(r) col_indices.append(c) # document-term matrix in CSR format", "1 except: break return word_end def _document_frequency(X): \"\"\" Count the", "mask_inds = (-tfs[mask]).argsort()[:limit] new_mask = np.zeros(len(dfs), dtype=bool) new_mask[np.where(mask)[0][mask_inds]] = True", "through the original tokens tokens = list(original_tokens) min_n += 1", "= 0 while True: try: start_char = re.search(word, text).start() first_char", "< 0 or min_df < 0: raise ValueError(\"negative value for", "high is not None: mask &= dfs <= high if", "path to customized dictionary file It allows the function not", "collection return frozenset(stop) def load_model(file_path): \"\"\" Load saved pickle file", "scipy.sparse as sp import six import pickle from .model import", "0 while True: try: start_char = re.search(word, text).start() first_char =", "words if self.stop_words is not None: tokens = [w for", "document-term matrix in CSR format X = sp.csr_matrix((values, (row_indices, col_indices)),", "'ข้าว': 7} \"\"\" def __init__(self, ngram_range=(1, 1), stop_words=None, max_df=1.0, min_df=1,", "1 else: tokens = [] n_original_tokens = len(original_tokens) # bind", "dictionary file It allows the function not to tokenize given", "that have a document frequency lower than the given threshold", "1, 0], [1, 0, 0, 1, 1, 1, 0, 0]]", "import pickle from .model import get_convo_nn2 from .stop_words import THAI_STOP_WORDS", "'ไก่': 1, 'กิน': 2, 'อย่าง': 3, 'อยาก': 4, 'สงบ': 5,", "max_n = self.ngram_range if max_n != 1: original_tokens = tokens", "'อยาก': 4, 'สงบ': 5, 'ฉัน': 6, 'ข้าว': 7} \"\"\" def", "loop to reduce overhead tokens_append = tokens.append space_join = \"", "= get_convo_nn2() tokenizer.model = tokenizer.model.load_weights(WEIGHT_PATH) return tokenizer class DeepcutTokenizer(object): \"\"\"", "= tokens if min_n == 1: # no need to", "self.transform(raw_documents, new_document=True) return X def tokenize(self, text, custom_dict=None): n_pad =", "1, 0, 1, 0, 1, 0], [1, 0, 0, 1,", "case of empty string if isinstance(text, str) and sys.version_info.major ==", "and sys.version_info.major == 2: text = text.decode('utf-8') x_char, x_type =", "six.string_types): raise ValueError(\"not a built-in stop list: %s\" % stop)", "vocabulary ordered by term frequencies max_df : float in range", "= True mask = new_mask new_indices = np.cumsum(mask) - 1", "Keras + TensorFlow + Flask async environment # ref: https://github.com/keras-team/keras/issues/2397", "CHARS_MAP, create_feature_array MODULE_PATH = os.path.dirname(__file__) WEIGHT_PATH = os.path.join(MODULE_PATH, 'weight', 'cnn_without_ne_ab.h5')", "words to be removed if None, max_df can be set", "sparse CSR format (see scipy) \"\"\" X = self.transform(raw_documents, new_document=True)", "!= 1: original_tokens = tokens if min_n == 1: #", "from itertools import chain import numpy as np import scipy.sparse", "(min_df if isinstance(min_df, numbers.Integral) else min_df * n_doc) if max_doc_count", "dtype=bool) if high is not None: mask &= dfs <=", "Count the number of non-zero values for each feature in", "transform(self, raw_documents, new_document=False): \"\"\" raw_documents: list, list of new documents", "assume seeing documents and build a new self.vobabulary_, if False,", "1.0] or int, default=1.0 ignore terms that have a document", "a mask based on document frequencies dfs = _document_frequency(X) mask", "is not None: mask &= dfs <= high if low", "tfs = np.asarray(X.sum(axis=0)).ravel() mask_inds = (-tfs[mask]).argsort()[:limit] new_mask = np.zeros(len(dfs), dtype=bool)", "if high is None and low is None and limit", "list, list of new documents to be transformed new_document: bool,", "CSR format X = sp.csr_matrix((values, (row_indices, col_indices)), shape=(n_doc, len(self.vocabulary_)), dtype=self.dtype)", "['ตัดคำ','ได้','ดี','มาก'] \"\"\" global TOKENIZER if not TOKENIZER: TOKENIZER = DeepcutTokenizer()", "None: return X, set() # Calculate a mask based on", "new_indices[old_index] else: del vocabulary[term] removed_terms.add(term) kept_indices = np.where(mask)[0] if len(kept_indices)", "ValueError( \"max_df corresponds to < documents than min_df\") X, _", "def _custom_dict(word, text, word_end): word_length = len(word) initial_loc = 0", "text = text[start_char + word_length:] word_end[first_char:last_char] = (word_length - 1)", "ordered by term frequencies max_df : float in range [0.0,", "token in tokens: word_index = self.vocabulary_.get(token) if word_index is not", "1) * [0] word_end[last_char] = 1 except: break return word_end", "= sp.csr_matrix((values, (row_indices, col_indices)), shape=(n_doc, len(self.vocabulary_)), dtype=self.dtype) # truncate vocabulary", "custom_dict: str (or list), path to customized dictionary file It", "it's a collection return frozenset(stop) def load_model(file_path): \"\"\" Load saved", "limit=None): \"\"\"Remove too rare or too common features. ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L734-L773", "not None: mask &= dfs <= high if low is", "dictionary wrongly. The file should contain custom words separated by", "break return word_end def _document_frequency(X): \"\"\" Count the number of", "pickle.load(open(file_path, 'rb')) tokenizer.model = get_convo_nn2() tokenizer.model = tokenizer.model.load_weights(WEIGHT_PATH) return tokenizer", "col_indices = [], [], [] for r, tokens in enumerate(tokenized_documents):", "initial_loc += start_char + word_length text = text[start_char + word_length:]", "tokens in enumerate(tokenized_documents): tokens = self._word_ngrams(tokens) feature = {} for", "else: feature[word_index] += 1 for c, v in feature.items(): values.append(v)", "Try a lower\" \" min_df or a higher max_df.\") return", "of pre-populated stop words max_features : int or None, if", "for unigram and (1, 2) for bigram stop_words : list", "= get_convo_nn2() self.model.load_weights(WEIGHT_PATH) self.vocabulary_ = {} self.ngram_range = ngram_range self.dtype", "+ TensorFlow + Flask async environment # ref: https://github.com/keras-team/keras/issues/2397 y_predict", "custom_dict=None): \"\"\" Tokenize given Thai text string Input ===== text:", "= DeepcutTokenizer(ngram_range=(1, 1)) X = tokenizer.fit_tranform(raw_documents) # document-term matrix in", "is not None: tokens = [w for w in tokens", "TensorFlow + Flask async environment # ref: https://github.com/keras-team/keras/issues/2397 y_predict =", "os import re import sys from itertools import chain import", "7} \"\"\" def __init__(self, ngram_range=(1, 1), stop_words=None, max_df=1.0, min_df=1, max_features=None,", "not in self.stop_words] # handle token n-grams min_n, max_n =", "Fix thread-related issue in Keras + TensorFlow + Flask async", "last_char = first_char + word_length - 1 initial_loc += start_char", "len(original_tokens) # bind method outside of loop to reduce overhead", "< min_doc_count: raise ValueError( \"max_df corresponds to < documents than", "function not to tokenize given dictionary wrongly. The file should", "2, 'อย่าง': 3, 'อยาก': 4, 'สงบ': 5, 'ฉัน': 6, 'ข้าว':", "= (word_length - 1) * [0] word_end[last_char] = 1 except:", "THAI_STOP_WORDS elif isinstance(stop, six.string_types): raise ValueError(\"not a built-in stop list:", "n_doc) if max_doc_count < min_doc_count: raise ValueError( \"max_df corresponds to", "def _document_frequency(X): \"\"\" Count the number of non-zero values for", ">> {'นอน': 0, 'ไก่': 1, 'กิน': 2, 'อย่าง': 3, 'อยาก':", "# just iterate through the original tokens tokens = list(original_tokens)", "= first_char + word_length - 1 initial_loc += start_char +", "word_end = [] # Fix thread-related issue in Keras +", "based on document frequencies dfs = _document_frequency(X) mask = np.ones(len(dfs),", "ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153 \"\"\" # handle stop words if self.stop_words is", "frequencies dfs = _document_frequency(X) mask = np.ones(len(dfs), dtype=bool) if high", "1, 1, 0, 1, 0, 1, 0], [1, 0, 0,", "1, 0, 0]] >> tokenizer.vocabulary_ >> {'นอน': 0, 'ไก่': 1,", "= ['ฉันอยากกินข้าวของฉัน', 'ฉันอยากกินไก่', 'อยากนอนอย่างสงบ'] tokenizer = DeepcutTokenizer(ngram_range=(1, 1)) X =", "\"\"\" global TOKENIZER if not TOKENIZER: TOKENIZER = DeepcutTokenizer() return", "== \"thai\": return THAI_STOP_WORDS elif isinstance(stop, six.string_types): raise ValueError(\"not a", "return tokens def _limit_features(self, X, vocabulary, high=None, low=None, limit=None): \"\"\"Remove", "first_char + word_length - 1 initial_loc += start_char + word_length", "stop words to be removed if None, max_df can be", "'กิน': 2, 'อย่าง': 3, 'อยาก': 4, 'สงบ': 5, 'ฉัน': 6,", "text, word_end): word_length = len(word) initial_loc = 0 while True:", "library Parameters ========== ngram_range : tuple, tuple for ngram range", "for n in range(min_n, min(max_n + 1, n_original_tokens + 1)):", "line. Alternatively, you can provide list of custom words too.", "# no need to do any slicing for unigrams #", "if sp.isspmatrix_csr(X): return np.bincount(X.indices, minlength=X.shape[1]) return np.diff(sp.csc_matrix(X, copy=False).indptr) def _check_stop_list(stop):", "tokenized_documents = [] for doc in raw_documents: tokens = tokenize(doc)", "reduce overhead tokens_append = tokens.append space_join = \" \".join for", "tokens = self._word_ngrams(tokens) tokenized_documents.append(tokens) if new_document: self.vocabulary_ = {v: k", "\"\"\" Count the number of non-zero values for each feature", "text: str, Thai text string custom_dict: str (or list), path", "as sp import six import pickle from .model import get_convo_nn2", "n + 1): tokens_append(space_join(original_tokens[i: i + n])) return tokens def", "word_length - 1 initial_loc += start_char + word_length text =", "list of pre-populated stop words max_features : int or None,", "col_indices.append(c) # document-term matrix in CSR format X = sp.csr_matrix((values,", "be transformed new_document: bool, if True, assume seeing documents and", "return frozenset(stop) def load_model(file_path): \"\"\" Load saved pickle file of", "# Calculate a mask based on document frequencies dfs =", "frequency lower than the given threshold dtype : type, optional", "Parameters ========== file_path: str, path to saved model from ``save_model``", "= None def tokenize(text, custom_dict=None): \"\"\" Tokenize given Thai text", "not TOKENIZER: TOKENIZER = DeepcutTokenizer() return TOKENIZER.tokenize(text, custom_dict=custom_dict) def _custom_dict(word,", "set to value [0.7, 1.0) to automatically remove vocabulary. If", "Parameters ========== ngram_range : tuple, tuple for ngram range for", "max_features self.stop_words = _check_stop_list(stop_words) def _word_ngrams(self, tokens): \"\"\" Turn tokens", "for unigrams # just iterate through the original tokens tokens", "dfs <= high if low is not None: mask &=", "of non-zero values for each feature in sparse X. \"\"\"", "mask = np.ones(len(dfs), dtype=bool) if high is not None: mask", "by line. Alternatively, you can provide list of custom words", "number of vocabulary ordered by term frequencies max_df : float", "bind method outside of loop to reduce overhead tokens_append =", "tokenizer.fit_tranform(raw_documents) # document-term matrix in sparse CSR format >> X.todense()", "low is not None: mask &= dfs >= low if", "in enumerate(tokenized_documents): tokens = self._word_ngrams(tokens) feature = {} for token", "if max_doc_count < min_doc_count: raise ValueError( \"max_df corresponds to <", "THAI_STOP_WORDS from .utils import CHAR_TYPES_MAP, CHARS_MAP, create_feature_array MODULE_PATH = os.path.dirname(__file__)", "stop) elif stop is None: return None # assume it's", "for tokenizing given Thai text documents using deepcut library Parameters", "documents and build a new self.vobabulary_, if False, use the", "fit_tranform(self, raw_documents): \"\"\" Transform given list of raw_documents to document-term", "global TOKENIZER if not TOKENIZER: TOKENIZER = DeepcutTokenizer() return TOKENIZER.tokenize(text,", "to value [0.7, 1.0) to automatically remove vocabulary. If using", "i in y_predict.tolist()] return list(zip(list(text),c)) def save_model(self, file_path): \"\"\" Save", "terms that have a document frequency higher than the given", "the number of non-zero values for each feature in sparse", "= max_df self.min_df = min_df if max_df < 0 or", "documents using deepcut library Parameters ========== ngram_range : tuple, tuple", "of loop to reduce overhead tokens_append = tokens.append space_join =", "len(kept_indices) == 0: raise ValueError(\"After pruning, no terms remain. Try", "new_document: max_df = self.max_df min_df = self.min_df max_doc_count = (max_df", "unigram and (1, 2) for bigram stop_words : list or", "DeepcutTokenizer(ngram_range=(1, 1)) X = tokenizer.fit_tranform(raw_documents) # document-term matrix in sparse", "tokenizer class DeepcutTokenizer(object): \"\"\" Class for tokenizing given Thai text", "\" min_df or a higher max_df.\") return X[:, kept_indices], removed_terms", "list or set, list or set of stop words to", "dfs >= low if limit is not None and mask.sum()", "return list(zip(list(text),c)) def save_model(self, file_path): \"\"\" Save tokenizer to pickle", "v in feature.items(): values.append(v) row_indices.append(r) col_indices.append(c) # document-term matrix in", "successfully save the model with open(file_path, 'wb') as f: pickle.dump(self,", "list of tokenized words Example ======= >> deepcut.tokenize('ตัดคำได้ดีมาก') >> ['ตัดคำ','ได้','ดี','มาก']", "n])) return tokens def _limit_features(self, X, vocabulary, high=None, low=None, limit=None):", "\"\"\" if high is None and low is None and", "in enumerate(set(chain.from_iterable(tokenized_documents)))} values, row_indices, col_indices = [], [], [] for", "\"\"\" if stop == \"thai\": return THAI_STOP_WORDS elif isinstance(stop, six.string_types):", "a higher max_df.\") return X[:, kept_indices], removed_terms def transform(self, raw_documents,", "int or None, if provided, only consider number of vocabulary", "if not TOKENIZER: TOKENIZER = DeepcutTokenizer() return TOKENIZER.tokenize(text, custom_dict=custom_dict) def", "ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L734-L773 \"\"\" if high is None and low is", "range [0.0, 1.0] or int, default=1.0 ignore terms that have", "= (-tfs[mask]).argsort()[:limit] new_mask = np.zeros(len(dfs), dtype=bool) new_mask[np.where(mask)[0][mask_inds]] = True mask", "transformed new_document: bool, if True, assume seeing documents and build", "will use list of pre-populated stop words max_features : int", "+= 1 for c, v in feature.items(): values.append(v) row_indices.append(r) col_indices.append(c)", "by max_df and min_df if new_document: max_df = self.max_df min_df", "given threshold min_df : float in range [0.0, 1.0] or", "tokens if min_n == 1: # no need to do", "not None: tokens = [w for w in tokens if", "for i in y_predict.tolist()] return list(zip(list(text),c)) def save_model(self, file_path): \"\"\"", "automatically remove vocabulary. If using \"thai\", this will use list", "utf-8 import numbers import os import re import sys from", "method outside of loop to reduce overhead tokens_append = tokens.append", "frequencies max_df : float in range [0.0, 1.0] or int,", "ref: https://github.com/keras-team/keras/issues/2397 y_predict = self.model.predict([x_char, x_type]) c = [i[0] for", "https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L734-L773 \"\"\" if high is None and low is None", "= create_feature_array(text, n_pad=n_pad) word_end = [] # Fix thread-related issue", "i in range(n_original_tokens - n + 1): tokens_append(space_join(original_tokens[i: i +", "self.dtype = dtype self.max_df = max_df self.min_df = min_df if", "or int, default=1.0 ignore terms that have a document frequency", "file_path: str, path to saved model from ``save_model`` method in", "limit is None: return X, set() # Calculate a mask", "mask = new_mask new_indices = np.cumsum(mask) - 1 # maps", "indices to new removed_terms = set() for term, old_index in", "set() # Calculate a mask based on document frequencies dfs", "or set of stop words to be removed if None,", "[0.0, 1.0] or int, default=1 ignore terms that have a", ": float in range [0.0, 1.0] or int, default=1 ignore", "document-term matrix in sparse CSR format (see scipy) \"\"\" X", "TOKENIZER: TOKENIZER = DeepcutTokenizer() return TOKENIZER.tokenize(text, custom_dict=custom_dict) def _custom_dict(word, text,", "None and low is None and limit is None: return", "Class for tokenizing given Thai text documents using deepcut library", "is None and low is None and limit is None:", "isinstance(max_df, numbers.Integral) else max_df * n_doc) min_doc_count = (min_df if", "deepcut.tokenize('ตัดคำได้ดีมาก') >> ['ตัดคำ','ได้','ดี','มาก'] \"\"\" global TOKENIZER if not TOKENIZER: TOKENIZER", "limit: tfs = np.asarray(X.sum(axis=0)).ravel() mask_inds = (-tfs[mask]).argsort()[:limit] new_mask = np.zeros(len(dfs),", "2) for bigram stop_words : list or set, list or", "def _check_stop_list(stop): \"\"\" Check stop words list ref: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95 \"\"\"", "1, 1, 1, 0, 0]] >> tokenizer.vocabulary_ >> {'นอน': 0,", "return np.diff(sp.csc_matrix(X, copy=False).indptr) def _check_stop_list(stop): \"\"\" Check stop words list", "file of DeepcutTokenizer Parameters ========== file_path: str, path to saved", "the given threshold dtype : type, optional Example ======= raw_documents", "(row_indices, col_indices)), shape=(n_doc, len(self.vocabulary_)), dtype=self.dtype) # truncate vocabulary by max_df", "to successfully save the model with open(file_path, 'wb') as f:", "- n + 1): tokens_append(space_join(original_tokens[i: i + n])) return tokens", "values.append(v) row_indices.append(r) col_indices.append(c) # document-term matrix in CSR format X", "in sparse X. \"\"\" if sp.isspmatrix_csr(X): return np.bincount(X.indices, minlength=X.shape[1]) return", "= min_df if max_df < 0 or min_df < 0:", "if provided, only consider number of vocabulary ordered by term", "format >> X.todense() >> [[0, 0, 1, 0, 1, 0,", "1 for c, v in feature.items(): values.append(v) row_indices.append(r) col_indices.append(c) #", ".stop_words import THAI_STOP_WORDS from .utils import CHAR_TYPES_MAP, CHARS_MAP, create_feature_array MODULE_PATH", "X = tokenizer.fit_tranform(raw_documents) # document-term matrix in sparse CSR format", "n in range(min_n, min(max_n + 1, n_original_tokens + 1)): for", "DeepcutTokenizer Parameters ========== file_path: str, path to saved model from", "tokenizer.model = get_convo_nn2() tokenizer.model = tokenizer.model.load_weights(WEIGHT_PATH) return tokenizer class DeepcutTokenizer(object):", ">> [[0, 0, 1, 0, 1, 0, 2, 1], [0,", "def __init__(self, ngram_range=(1, 1), stop_words=None, max_df=1.0, min_df=1, max_features=None, dtype=np.dtype('float64')): self.model", "return X def tokenize(self, text, custom_dict=None): n_pad = 21 if", "0: raise ValueError(\"After pruning, no terms remain. Try a lower\"", "= np.zeros(len(dfs), dtype=bool) new_mask[np.where(mask)[0][mask_inds]] = True mask = new_mask new_indices", "to None to successfully save the model with open(file_path, 'wb')", "given threshold dtype : type, optional Example ======= raw_documents =", "iterate through the original tokens tokens = list(original_tokens) min_n +=", "k for k, v in enumerate(set(chain.from_iterable(tokenized_documents)))} values, row_indices, col_indices =", "or None, if provided, only consider number of vocabulary ordered", "custom_dict=None): n_pad = 21 if not text: return [''] #", "tokenizer = pickle.load(open(file_path, 'rb')) tokenizer.model = get_convo_nn2() tokenizer.model = tokenizer.model.load_weights(WEIGHT_PATH)", "bool, if True, assume seeing documents and build a new", "True, assume seeing documents and build a new self.vobabulary_, if", "col_indices)), shape=(n_doc, len(self.vocabulary_)), dtype=self.dtype) # truncate vocabulary by max_df and", "raise ValueError( \"max_df corresponds to < documents than min_df\") X,", "given Thai text documents using deepcut library Parameters ========== ngram_range", "= [w for w in tokens if w not in", "optional Example ======= raw_documents = ['ฉันอยากกินข้าวของฉัน', 'ฉันอยากกินไก่', 'อยากนอนอย่างสงบ'] tokenizer =", "return None # assume it's a collection return frozenset(stop) def", "The file should contain custom words separated by line. Alternatively,", "tokenize given dictionary wrongly. The file should contain custom words", "MODULE_PATH = os.path.dirname(__file__) WEIGHT_PATH = os.path.join(MODULE_PATH, 'weight', 'cnn_without_ne_ab.h5') TOKENIZER =", "word_end[last_char] = 1 except: break return word_end def _document_frequency(X): \"\"\"", "\"\"\" tokenizer = pickle.load(open(file_path, 'rb')) tokenizer.model = get_convo_nn2() tokenizer.model =", "get_convo_nn2() self.model.load_weights(WEIGHT_PATH) self.vocabulary_ = {} self.ngram_range = ngram_range self.dtype =", "if high is not None: mask &= dfs <= high", "for doc in raw_documents: tokens = tokenize(doc) # method in", "['ฉันอยากกินข้าวของฉัน', 'ฉันอยากกินไก่', 'อยากนอนอย่างสงบ'] tokenizer = DeepcutTokenizer(ngram_range=(1, 1)) X = tokenizer.fit_tranform(raw_documents)", "X = self.transform(raw_documents, new_document=True) return X def tokenize(self, text, custom_dict=None):", "1: original_tokens = tokens if min_n == 1: # no", "= self.vocabulary_.get(token) if word_index is not None: if word_index not", "tokens_append = tokens.append space_join = \" \".join for n in", "new_mask new_indices = np.cumsum(mask) - 1 # maps old indices", "numbers.Integral) else max_df * n_doc) min_doc_count = (min_df if isinstance(min_df,", "tokens = [] n_original_tokens = len(original_tokens) # bind method outside", "0, 1, 0, 2, 1], [0, 1, 1, 0, 1,", "(-tfs[mask]).argsort()[:limit] new_mask = np.zeros(len(dfs), dtype=bool) new_mask[np.where(mask)[0][mask_inds]] = True mask =", "if mask[old_index]: vocabulary[term] = new_indices[old_index] else: del vocabulary[term] removed_terms.add(term) kept_indices", "= 1 else: feature[word_index] += 1 for c, v in", "* n_doc) if max_doc_count < min_doc_count: raise ValueError( \"max_df corresponds", "Alternatively, you can provide list of custom words too. Output", "= [] # Fix thread-related issue in Keras + TensorFlow", "matrix in sparse CSR format (see scipy) \"\"\" X =", "[], [] for r, tokens in enumerate(tokenized_documents): tokens = self._word_ngrams(tokens)", "pickle format \"\"\" self.model = None # set model to", "n-grams min_n, max_n = self.ngram_range if max_n != 1: original_tokens", "mask &= dfs >= low if limit is not None", "to be transformed new_document: bool, if True, assume seeing documents", "= os.path.join(MODULE_PATH, 'weight', 'cnn_without_ne_ab.h5') TOKENIZER = None def tokenize(text, custom_dict=None):", "sys.version_info.major == 2: text = text.decode('utf-8') x_char, x_type = create_feature_array(text,", "None: mask &= dfs <= high if low is not", "in raw_documents: tokens = tokenize(doc) # method in this file", "word_length:] word_end[first_char:last_char] = (word_length - 1) * [0] word_end[last_char] =", "stop words max_features : int or None, if provided, only", "new documents to be transformed new_document: bool, if True, assume", "0], [1, 0, 0, 1, 1, 1, 0, 0]] >>", "3, 'อยาก': 4, 'สงบ': 5, 'ฉัน': 6, 'ข้าว': 7} \"\"\"", "slicing for unigrams # just iterate through the original tokens", "ValueError(\"After pruning, no terms remain. Try a lower\" \" min_df", "the given threshold min_df : float in range [0.0, 1.0]", "wrongly. The file should contain custom words separated by line.", "Calculate a mask based on document frequencies dfs = _document_frequency(X)", "self.max_features) return X def fit_tranform(self, raw_documents): \"\"\" Transform given list", "\"\"\"Remove too rare or too common features. ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L734-L773 \"\"\"", "1), stop_words=None, max_df=1.0, min_df=1, max_features=None, dtype=np.dtype('float64')): self.model = get_convo_nn2() self.model.load_weights(WEIGHT_PATH)", "= DeepcutTokenizer() return TOKENIZER.tokenize(text, custom_dict=custom_dict) def _custom_dict(word, text, word_end): word_length", "max_df * n_doc) min_doc_count = (min_df if isinstance(min_df, numbers.Integral) else", "word_length = len(word) initial_loc = 0 while True: try: start_char", "list), path to customized dictionary file It allows the function", "max_df self.min_df = min_df if max_df < 0 or min_df", "list of new documents to be transformed new_document: bool, if", "as np import scipy.sparse as sp import six import pickle", "import numbers import os import re import sys from itertools", "* [0] word_end[last_char] = 1 except: break return word_end def", "1, 'กิน': 2, 'อย่าง': 3, 'อยาก': 4, 'สงบ': 5, 'ฉัน':", "tokenize(doc) # method in this file tokens = self._word_ngrams(tokens) tokenized_documents.append(tokens)", "thread-related issue in Keras + TensorFlow + Flask async environment", "y_predict = self.model.predict([x_char, x_type]) c = [i[0] for i in", "is None: return None # assume it's a collection return", "ngram_range=(1, 1), stop_words=None, max_df=1.0, min_df=1, max_features=None, dtype=np.dtype('float64')): self.model = get_convo_nn2()", "to tokenize given dictionary wrongly. The file should contain custom", "+ n])) return tokens def _limit_features(self, X, vocabulary, high=None, low=None,", "to document-term matrix in sparse CSR format (see scipy) \"\"\"", "range for vocabulary, (1, 1) for unigram and (1, 2)", "get_convo_nn2 from .stop_words import THAI_STOP_WORDS from .utils import CHAR_TYPES_MAP, CHARS_MAP,", "\" \".join for n in range(min_n, min(max_n + 1, n_original_tokens", "tokens if w not in self.stop_words] # handle token n-grams", "(1, 1) for unigram and (1, 2) for bigram stop_words", "self.vocabulary_.get(token) if word_index is not None: if word_index not in", "DeepcutTokenizer(object): \"\"\" Class for tokenizing given Thai text documents using", "import os import re import sys from itertools import chain", "tokens_append(space_join(original_tokens[i: i + n])) return tokens def _limit_features(self, X, vocabulary,", ": float in range [0.0, 1.0] or int, default=1.0 ignore", "enumerate(tokenized_documents): tokens = self._word_ngrams(tokens) feature = {} for token in", "+ word_length - 1 initial_loc += start_char + word_length text", "(see scipy) \"\"\" X = self.transform(raw_documents, new_document=True) return X def", "should contain custom words separated by line. Alternatively, you can", "can be set to value [0.7, 1.0) to automatically remove", "X.todense() >> [[0, 0, 1, 0, 1, 0, 2, 1],", "'ฉัน': 6, 'ข้าว': 7} \"\"\" def __init__(self, ngram_range=(1, 1), stop_words=None,", "in range(n_original_tokens - n + 1): tokens_append(space_join(original_tokens[i: i + n]))", "= re.search(word, text).start() first_char = start_char + initial_loc last_char =", "X, set() # Calculate a mask based on document frequencies", "self.model = None # set model to None to successfully", "return np.bincount(X.indices, minlength=X.shape[1]) return np.diff(sp.csc_matrix(X, copy=False).indptr) def _check_stop_list(stop): \"\"\" Check", "have a document frequency higher than the given threshold min_df", "self.model = get_convo_nn2() self.model.load_weights(WEIGHT_PATH) self.vocabulary_ = {} self.ngram_range = ngram_range", "dfs = _document_frequency(X) mask = np.ones(len(dfs), dtype=bool) if high is", "None def tokenize(text, custom_dict=None): \"\"\" Tokenize given Thai text string", "import scipy.sparse as sp import six import pickle from .model", "if low is not None: mask &= dfs >= low", "for term, old_index in list(vocabulary.items()): if mask[old_index]: vocabulary[term] = new_indices[old_index]", "None # set model to None to successfully save the", "< documents than min_df\") X, _ = self._limit_features(X, self.vocabulary_, max_doc_count,", "lower than the given threshold dtype : type, optional Example", "to automatically remove vocabulary. If using \"thai\", this will use", "os.path.join(MODULE_PATH, 'weight', 'cnn_without_ne_ab.h5') TOKENIZER = None def tokenize(text, custom_dict=None): \"\"\"", "start_char = re.search(word, text).start() first_char = start_char + initial_loc last_char", "stop == \"thai\": return THAI_STOP_WORDS elif isinstance(stop, six.string_types): raise ValueError(\"not", "for c, v in feature.items(): values.append(v) row_indices.append(r) col_indices.append(c) # document-term", "max_df and min_df if new_document: max_df = self.max_df min_df =", "save the model with open(file_path, 'wb') as f: pickle.dump(self, f)", "= self.transform(raw_documents, new_document=True) return X def tokenize(self, text, custom_dict=None): n_pad", "# document-term matrix in CSR format X = sp.csr_matrix((values, (row_indices,", "= self.min_df max_doc_count = (max_df if isinstance(max_df, numbers.Integral) else max_df", "DeepcutTokenizer() return TOKENIZER.tokenize(text, custom_dict=custom_dict) def _custom_dict(word, text, word_end): word_length =", "and low is None and limit is None: return X,", "sys from itertools import chain import numpy as np import", "in range [0.0, 1.0] or int, default=1.0 ignore terms that", "if min_n == 1: # no need to do any", "max_n != 1: original_tokens = tokens if min_n == 1:", "text: return [''] # case of empty string if isinstance(text,", "is None: return X, set() # Calculate a mask based", "None and mask.sum() > limit: tfs = np.asarray(X.sum(axis=0)).ravel() mask_inds =", "word_end): word_length = len(word) initial_loc = 0 while True: try:", "+ 1, n_original_tokens + 1)): for i in range(n_original_tokens -", "by term frequencies max_df : float in range [0.0, 1.0]", "new_document: self.vocabulary_ = {v: k for k, v in enumerate(set(chain.from_iterable(tokenized_documents)))}", "= [i[0] for i in y_predict.tolist()] return list(zip(list(text),c)) def save_model(self,", "tokens of n-grams ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153 \"\"\" # handle stop words", "False, use the previous self.vocabulary_ \"\"\" n_doc = len(raw_documents) tokenized_documents", "return tokenizer class DeepcutTokenizer(object): \"\"\" Class for tokenizing given Thai", "+ 1): tokens_append(space_join(original_tokens[i: i + n])) return tokens def _limit_features(self,", "X def tokenize(self, text, custom_dict=None): n_pad = 21 if not", "tokens = [w for w in tokens if w not", "str (or list), path to customized dictionary file It allows", "term, old_index in list(vocabulary.items()): if mask[old_index]: vocabulary[term] = new_indices[old_index] else:", "if isinstance(text, str) and sys.version_info.major == 2: text = text.decode('utf-8')", "WEIGHT_PATH = os.path.join(MODULE_PATH, 'weight', 'cnn_without_ne_ab.h5') TOKENIZER = None def tokenize(text,", "in feature.keys(): feature[word_index] = 1 else: feature[word_index] += 1 for", "for each feature in sparse X. \"\"\" if sp.isspmatrix_csr(X): return", "np.diff(sp.csc_matrix(X, copy=False).indptr) def _check_stop_list(stop): \"\"\" Check stop words list ref:", ": int or None, if provided, only consider number of", "not to tokenize given dictionary wrongly. The file should contain", "Thai text documents using deepcut library Parameters ========== ngram_range :", ".utils import CHAR_TYPES_MAP, CHARS_MAP, create_feature_array MODULE_PATH = os.path.dirname(__file__) WEIGHT_PATH =", "self.max_df = max_df self.min_df = min_df if max_df < 0", "0, 1, 0], [1, 0, 0, 1, 1, 1, 0,", "[i[0] for i in y_predict.tolist()] return list(zip(list(text),c)) def save_model(self, file_path):", "min_doc_count, self.max_features) return X def fit_tranform(self, raw_documents): \"\"\" Transform given", "tokens: list, list of tokenized words Example ======= >> deepcut.tokenize('ตัดคำได้ดีมาก')", "'อยากนอนอย่างสงบ'] tokenizer = DeepcutTokenizer(ngram_range=(1, 1)) X = tokenizer.fit_tranform(raw_documents) # document-term", ">> ['ตัดคำ','ได้','ดี','มาก'] \"\"\" global TOKENIZER if not TOKENIZER: TOKENIZER =", "dtype=np.dtype('float64')): self.model = get_convo_nn2() self.model.load_weights(WEIGHT_PATH) self.vocabulary_ = {} self.ngram_range =", "ngram_range : tuple, tuple for ngram range for vocabulary, (1,", "X. \"\"\" if sp.isspmatrix_csr(X): return np.bincount(X.indices, minlength=X.shape[1]) return np.diff(sp.csc_matrix(X, copy=False).indptr)", "None: mask &= dfs >= low if limit is not", "set() for term, old_index in list(vocabulary.items()): if mask[old_index]: vocabulary[term] =", "range(min_n, min(max_n + 1, n_original_tokens + 1)): for i in", "self._word_ngrams(tokens) tokenized_documents.append(tokens) if new_document: self.vocabulary_ = {v: k for k,", "\"\"\" X = self.transform(raw_documents, new_document=True) return X def tokenize(self, text,", "0, 1, 0, 1, 0], [1, 0, 0, 1, 1,", "maps old indices to new removed_terms = set() for term,", "self.vocabulary_ \"\"\" n_doc = len(raw_documents) tokenized_documents = [] for doc", "from .stop_words import THAI_STOP_WORDS from .utils import CHAR_TYPES_MAP, CHARS_MAP, create_feature_array", "sparse X. \"\"\" if sp.isspmatrix_csr(X): return np.bincount(X.indices, minlength=X.shape[1]) return np.diff(sp.csc_matrix(X,", "for w in tokens if w not in self.stop_words] #", "low=None, limit=None): \"\"\"Remove too rare or too common features. ref:", "vocabulary[term] removed_terms.add(term) kept_indices = np.where(mask)[0] if len(kept_indices) == 0: raise", "w in tokens if w not in self.stop_words] # handle", "each feature in sparse X. \"\"\" if sp.isspmatrix_csr(X): return np.bincount(X.indices,", "list of raw_documents to document-term matrix in sparse CSR format", "= [] for doc in raw_documents: tokens = tokenize(doc) #", "start_char + initial_loc last_char = first_char + word_length - 1", "import six import pickle from .model import get_convo_nn2 from .stop_words", "text[start_char + word_length:] word_end[first_char:last_char] = (word_length - 1) * [0]", "try: start_char = re.search(word, text).start() first_char = start_char + initial_loc", "if new_document: max_df = self.max_df min_df = self.min_df max_doc_count =", "min_df if max_df < 0 or min_df < 0: raise", "on document frequencies dfs = _document_frequency(X) mask = np.ones(len(dfs), dtype=bool)", "Thai text string Input ===== text: str, Thai text string", "six import pickle from .model import get_convo_nn2 from .stop_words import", "if self.stop_words is not None: tokens = [w for w", "\"\"\" if sp.isspmatrix_csr(X): return np.bincount(X.indices, minlength=X.shape[1]) return np.diff(sp.csc_matrix(X, copy=False).indptr) def", "n_original_tokens + 1)): for i in range(n_original_tokens - n +", "= text.decode('utf-8') x_char, x_type = create_feature_array(text, n_pad=n_pad) word_end = []", "lower\" \" min_df or a higher max_df.\") return X[:, kept_indices],", "string if isinstance(text, str) and sys.version_info.major == 2: text =", "contain custom words separated by line. Alternatively, you can provide", "0, 1, 1, 1, 0, 0]] >> tokenizer.vocabulary_ >> {'นอน':", "= len(raw_documents) tokenized_documents = [] for doc in raw_documents: tokens", "tokens = tokenize(doc) # method in this file tokens =", "while True: try: start_char = re.search(word, text).start() first_char = start_char", "_word_ngrams(self, tokens): \"\"\" Turn tokens into a tokens of n-grams", "return X, set() # Calculate a mask based on document", "sp.csr_matrix((values, (row_indices, col_indices)), shape=(n_doc, len(self.vocabulary_)), dtype=self.dtype) # truncate vocabulary by", "\"\"\" self.model = None # set model to None to", "max_df < 0 or min_df < 0: raise ValueError(\"negative value", "np.asarray(X.sum(axis=0)).ravel() mask_inds = (-tfs[mask]).argsort()[:limit] new_mask = np.zeros(len(dfs), dtype=bool) new_mask[np.where(mask)[0][mask_inds]] =", "isinstance(min_df, numbers.Integral) else min_df * n_doc) if max_doc_count < min_doc_count:", "stop words if self.stop_words is not None: tokens = [w", "np.ones(len(dfs), dtype=bool) if high is not None: mask &= dfs", "in DeepcutTokenizer \"\"\" tokenizer = pickle.load(open(file_path, 'rb')) tokenizer.model = get_convo_nn2()", "_check_stop_list(stop): \"\"\" Check stop words list ref: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95 \"\"\" if", "\".join for n in range(min_n, min(max_n + 1, n_original_tokens +", "to do any slicing for unigrams # just iterate through", "TOKENIZER if not TOKENIZER: TOKENIZER = DeepcutTokenizer() return TOKENIZER.tokenize(text, custom_dict=custom_dict)", "max_df=1.0, min_df=1, max_features=None, dtype=np.dtype('float64')): self.model = get_convo_nn2() self.model.load_weights(WEIGHT_PATH) self.vocabulary_ =", "in feature.items(): values.append(v) row_indices.append(r) col_indices.append(c) # document-term matrix in CSR", "new_document: bool, if True, assume seeing documents and build a", "ignore terms that have a document frequency higher than the", "import re import sys from itertools import chain import numpy", "+= start_char + word_length text = text[start_char + word_length:] word_end[first_char:last_char]", "for bigram stop_words : list or set, list or set", "min_n == 1: # no need to do any slicing", "common features. ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L734-L773 \"\"\" if high is None and", "tokens: word_index = self.vocabulary_.get(token) if word_index is not None: if", "new_document=True) return X def tokenize(self, text, custom_dict=None): n_pad = 21", "np.where(mask)[0] if len(kept_indices) == 0: raise ValueError(\"After pruning, no terms", "n_doc) min_doc_count = (min_df if isinstance(min_df, numbers.Integral) else min_df *", "handle token n-grams min_n, max_n = self.ngram_range if max_n !=", "vocabulary, (1, 1) for unigram and (1, 2) for bigram", "Example ======= >> deepcut.tokenize('ตัดคำได้ดีมาก') >> ['ตัดคำ','ได้','ดี','มาก'] \"\"\" global TOKENIZER if", "kept_indices = np.where(mask)[0] if len(kept_indices) == 0: raise ValueError(\"After pruning,", "a collection return frozenset(stop) def load_model(file_path): \"\"\" Load saved pickle", "https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153 \"\"\" # handle stop words if self.stop_words is not", "format \"\"\" self.model = None # set model to None", "\"thai\": return THAI_STOP_WORDS elif isinstance(stop, six.string_types): raise ValueError(\"not a built-in", "of vocabulary ordered by term frequencies max_df : float in", "max_doc_count, min_doc_count, self.max_features) return X def fit_tranform(self, raw_documents): \"\"\" Transform", "= set() for term, old_index in list(vocabulary.items()): if mask[old_index]: vocabulary[term]", ": tuple, tuple for ngram range for vocabulary, (1, 1)", "= new_mask new_indices = np.cumsum(mask) - 1 # maps old", "new_document=False): \"\"\" raw_documents: list, list of new documents to be", "self.vobabulary_, if False, use the previous self.vocabulary_ \"\"\" n_doc =", "0]] >> tokenizer.vocabulary_ >> {'นอน': 0, 'ไก่': 1, 'กิน': 2,", "_custom_dict(word, text, word_end): word_length = len(word) initial_loc = 0 while", "removed if None, max_df can be set to value [0.7,", "tokens = list(original_tokens) min_n += 1 else: tokens = []", "remain. Try a lower\" \" min_df or a higher max_df.\")", "provided, only consider number of vocabulary ordered by term frequencies", "to pickle format \"\"\" self.model = None # set model", "= \" \".join for n in range(min_n, min(max_n + 1,", "= np.where(mask)[0] if len(kept_indices) == 0: raise ValueError(\"After pruning, no", "====== tokens: list, list of tokenized words Example ======= >>", "this will use list of pre-populated stop words max_features :", "for i in range(n_original_tokens - n + 1): tokens_append(space_join(original_tokens[i: i", "just iterate through the original tokens tokens = list(original_tokens) min_n", "_document_frequency(X) mask = np.ones(len(dfs), dtype=bool) if high is not None:", "[], [], [] for r, tokens in enumerate(tokenized_documents): tokens =", "1)): for i in range(n_original_tokens - n + 1): tokens_append(space_join(original_tokens[i:", "&= dfs <= high if low is not None: mask", "text documents using deepcut library Parameters ========== ngram_range : tuple,", "file It allows the function not to tokenize given dictionary", "1, 0, 2, 1], [0, 1, 1, 0, 1, 0,", "too common features. ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L734-L773 \"\"\" if high is None", "of new documents to be transformed new_document: bool, if True,", "(word_length - 1) * [0] word_end[last_char] = 1 except: break", "re.search(word, text).start() first_char = start_char + initial_loc last_char = first_char", "terms remain. Try a lower\" \" min_df or a higher", "\"\"\" Load saved pickle file of DeepcutTokenizer Parameters ========== file_path:", ": type, optional Example ======= raw_documents = ['ฉันอยากกินข้าวของฉัน', 'ฉันอยากกินไก่', 'อยากนอนอย่างสงบ']", "feature.keys(): feature[word_index] = 1 else: feature[word_index] += 1 for c,", "return X def fit_tranform(self, raw_documents): \"\"\" Transform given list of", "{v: k for k, v in enumerate(set(chain.from_iterable(tokenized_documents)))} values, row_indices, col_indices", "words separated by line. Alternatively, you can provide list of", "def tokenize(self, text, custom_dict=None): n_pad = 21 if not text:", "2: text = text.decode('utf-8') x_char, x_type = create_feature_array(text, n_pad=n_pad) word_end", "= 21 if not text: return [''] # case of", "document-term matrix in sparse CSR format >> X.todense() >> [[0,", "dtype self.max_df = max_df self.min_df = min_df if max_df <", "= tokenizer.fit_tranform(raw_documents) # document-term matrix in sparse CSR format >>", "can provide list of custom words too. Output ====== tokens:", "tokenize(text, custom_dict=None): \"\"\" Tokenize given Thai text string Input =====", "original tokens tokens = list(original_tokens) min_n += 1 else: tokens", "itertools import chain import numpy as np import scipy.sparse as", "saved model from ``save_model`` method in DeepcutTokenizer \"\"\" tokenizer =", "document frequency lower than the given threshold dtype : type,", "'สงบ': 5, 'ฉัน': 6, 'ข้าว': 7} \"\"\" def __init__(self, ngram_range=(1,", "0, 0, 1, 1, 1, 0, 0]] >> tokenizer.vocabulary_ >>", "min_df\") self.max_features = max_features self.stop_words = _check_stop_list(stop_words) def _word_ngrams(self, tokens):", "a lower\" \" min_df or a higher max_df.\") return X[:,", "= (min_df if isinstance(min_df, numbers.Integral) else min_df * n_doc) if", "CHAR_TYPES_MAP, CHARS_MAP, create_feature_array MODULE_PATH = os.path.dirname(__file__) WEIGHT_PATH = os.path.join(MODULE_PATH, 'weight',", "else min_df * n_doc) if max_doc_count < min_doc_count: raise ValueError(", "unigrams # just iterate through the original tokens tokens =", "any slicing for unigrams # just iterate through the original", "ValueError(\"negative value for max_df or min_df\") self.max_features = max_features self.stop_words", "the previous self.vocabulary_ \"\"\" n_doc = len(raw_documents) tokenized_documents = []", "https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95 \"\"\" if stop == \"thai\": return THAI_STOP_WORDS elif isinstance(stop,", "ngram_range self.dtype = dtype self.max_df = max_df self.min_df = min_df", "Transform given list of raw_documents to document-term matrix in sparse", "[1, 0, 0, 1, 1, 1, 0, 0]] >> tokenizer.vocabulary_", "or min_df < 0: raise ValueError(\"negative value for max_df or", "kept_indices], removed_terms def transform(self, raw_documents, new_document=False): \"\"\" raw_documents: list, list", "__init__(self, ngram_range=(1, 1), stop_words=None, max_df=1.0, min_df=1, max_features=None, dtype=np.dtype('float64')): self.model =", "initial_loc last_char = first_char + word_length - 1 initial_loc +=", "start_char + word_length text = text[start_char + word_length:] word_end[first_char:last_char] =", "in tokens if w not in self.stop_words] # handle token", "old indices to new removed_terms = set() for term, old_index", "None: return None # assume it's a collection return frozenset(stop)", "self.stop_words is not None: tokens = [w for w in", "for token in tokens: word_index = self.vocabulary_.get(token) if word_index is", "= ngram_range self.dtype = dtype self.max_df = max_df self.min_df =", "\"\"\" Transform given list of raw_documents to document-term matrix in", "min_df < 0: raise ValueError(\"negative value for max_df or min_df\")", ">> deepcut.tokenize('ตัดคำได้ดีมาก') >> ['ตัดคำ','ได้','ดี','มาก'] \"\"\" global TOKENIZER if not TOKENIZER:", "min_df\") X, _ = self._limit_features(X, self.vocabulary_, max_doc_count, min_doc_count, self.max_features) return", "stop is None: return None # assume it's a collection", "X def fit_tranform(self, raw_documents): \"\"\" Transform given list of raw_documents", "environment # ref: https://github.com/keras-team/keras/issues/2397 y_predict = self.model.predict([x_char, x_type]) c =", "def save_model(self, file_path): \"\"\" Save tokenizer to pickle format \"\"\"", "documents than min_df\") X, _ = self._limit_features(X, self.vocabulary_, max_doc_count, min_doc_count,", "+= 1 else: tokens = [] n_original_tokens = len(original_tokens) #", "too rare or too common features. ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L734-L773 \"\"\" if", "vocabulary[term] = new_indices[old_index] else: del vocabulary[term] removed_terms.add(term) kept_indices = np.where(mask)[0]", "use the previous self.vocabulary_ \"\"\" n_doc = len(raw_documents) tokenized_documents =", "import numpy as np import scipy.sparse as sp import six", "if isinstance(min_df, numbers.Integral) else min_df * n_doc) if max_doc_count <", "rare or too common features. ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L734-L773 \"\"\" if high", "return [''] # case of empty string if isinstance(text, str)", "tokenizer.vocabulary_ >> {'นอน': 0, 'ไก่': 1, 'กิน': 2, 'อย่าง': 3,", "+ Flask async environment # ref: https://github.com/keras-team/keras/issues/2397 y_predict = self.model.predict([x_char,", "default=1 ignore terms that have a document frequency lower than", "{'นอน': 0, 'ไก่': 1, 'กิน': 2, 'อย่าง': 3, 'อยาก': 4,", "# bind method outside of loop to reduce overhead tokens_append", "original_tokens = tokens if min_n == 1: # no need", "min_doc_count: raise ValueError( \"max_df corresponds to < documents than min_df\")", "raise ValueError(\"After pruning, no terms remain. Try a lower\" \"", "not None: mask &= dfs >= low if limit is", "pre-populated stop words max_features : int or None, if provided,", "a document frequency lower than the given threshold dtype :", "TOKENIZER = DeepcutTokenizer() return TOKENIZER.tokenize(text, custom_dict=custom_dict) def _custom_dict(word, text, word_end):", "\"\"\" Check stop words list ref: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95 \"\"\" if stop", "return TOKENIZER.tokenize(text, custom_dict=custom_dict) def _custom_dict(word, text, word_end): word_length = len(word)", "remove vocabulary. If using \"thai\", this will use list of", "ref: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/text.py#L87-L95 \"\"\" if stop == \"thai\": return THAI_STOP_WORDS elif", "if word_index is not None: if word_index not in feature.keys():", "_ = self._limit_features(X, self.vocabulary_, max_doc_count, min_doc_count, self.max_features) return X def", "= text[start_char + word_length:] word_end[first_char:last_char] = (word_length - 1) *", "[''] # case of empty string if isinstance(text, str) and", "1, 0, 1, 0], [1, 0, 0, 1, 1, 1,", "tokens into a tokens of n-grams ref: https://github.com/scikit-learn/scikit-learn/blob/ef5cb84a/sklearn/feature_extraction/text.py#L124-L153 \"\"\" #", "this file tokens = self._word_ngrams(tokens) tokenized_documents.append(tokens) if new_document: self.vocabulary_ =", "numbers import os import re import sys from itertools import", "raw_documents: list, list of new documents to be transformed new_document:", "= [], [], [] for r, tokens in enumerate(tokenized_documents): tokens", "raw_documents: tokens = tokenize(doc) # method in this file tokens", "r, tokens in enumerate(tokenized_documents): tokens = self._word_ngrams(tokens) feature = {}", "min_n, max_n = self.ngram_range if max_n != 1: original_tokens =", "# encoding: utf-8 import numbers import os import re import", "string custom_dict: str (or list), path to customized dictionary file", "word_index not in feature.keys(): feature[word_index] = 1 else: feature[word_index] +=", "type, optional Example ======= raw_documents = ['ฉันอยากกินข้าวของฉัน', 'ฉันอยากกินไก่', 'อยากนอนอย่างสงบ'] tokenizer" ]
[ "cm = optional_cm if condition else nullcontext() with cm: #", "CPU_ONLY_BUILD from spconv.core_cc.csrc.utils.boxops import BoxOps from spconv.core_cc.csrc.sparse.all.ops_cpu1d import Point2VoxelCPU as", "overlap def rbbox_intersection(box_corners: np.ndarray, qbox_corners: np.ndarray, standup_iou: np.ndarray, standup_thresh: float):", "K), dtype=box_corners.dtype) BoxOps.rbbox_iou(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(standup_iou), tv.from_numpy(overlap), standup_thresh, True) return overlap", "2.0 (the \"License\"); # you may not use this file", "when a particular block of code is only sometimes used", "), dtype=box_corners.dtype) BoxOps.rbbox_iou_aligned(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(overlap), False) return overlap def non_max_suppression_cpu(boxes:", "as a stand-in for a normal context manager, when a", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "= 0.0): return BoxOps.non_max_suppression_cpu(tv.from_numpy(boxes), tv.from_numpy(order), thresh, eps) def rotate_non_max_suppression_cpu(boxes: np.ndarray,", "from spconv.core_cc.csrc.sparse.all.ops3d import Point2Voxel as Point2VoxelGPU3d from spconv.core_cc.csrc.sparse.all.ops4d import Point2Voxel", "\"\"\" def __init__(self, enter_result=None): self.enter_result = enter_result def __enter__(self): return", "stand-in for a normal context manager, when a particular block", "overlap = np.zeros((N, K), dtype=box_corners.dtype) BoxOps.rbbox_iou(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(standup_iou), tv.from_numpy(overlap), standup_thresh,", "N = box_corners.shape[0] overlap = np.zeros((N, ), dtype=box_corners.dtype) BoxOps.rbbox_iou_aligned(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners),", "from cumm import tensorview as tv from contextlib import AbstractContextManager", ") N = box_corners.shape[0] K = qbox_corners.shape[0] overlap = np.zeros((N,", "float = 0.0): return BoxOps.non_max_suppression_cpu(tv.from_numpy(boxes), tv.from_numpy(order), thresh, eps) def rotate_non_max_suppression_cpu(boxes:", "False) return overlap def non_max_suppression_cpu(boxes: np.ndarray, order: np.ndarray, thresh: float,", "of code is only sometimes used with a normal context", "use this file except in compliance with the License. #", "cm: # Perform operation, using optional_cm if condition is True", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "= box_corners.shape[0] K = qbox_corners.shape[0] overlap = np.zeros((N, K), dtype=box_corners.dtype)", "for a normal context manager, when a particular block of", "with a normal context manager: cm = optional_cm if condition", "and rebuild.\" ) N = box_corners.shape[0] overlap = np.zeros((N, ),", "License. # You may obtain a copy of the License", "import Point2VoxelCPU as Point2VoxelCPU1d from spconv.core_cc.csrc.sparse.all.ops_cpu2d import Point2VoxelCPU as Point2VoxelCPU2d", "additional processing. Used as a stand-in for a normal context", "under the License is distributed on an \"AS IS\" BASIS,", "import Point2VoxelCPU as Point2VoxelCPU2d from spconv.core_cc.csrc.sparse.all.ops_cpu3d import Point2VoxelCPU as Point2VoxelCPU3d", "a normal context manager: cm = optional_cm if condition else", "License for the specific language governing permissions and # limitations", "Point2Voxel as Point2VoxelGPU4d class nullcontext(AbstractContextManager): \"\"\"Context manager that does no", "sometimes used with a normal context manager: cm = optional_cm", "export BOOST_ROOT and rebuild.\" ) N = box_corners.shape[0] overlap =", "tensorview as tv from contextlib import AbstractContextManager from spconv.cppconstants import", "return BoxOps.non_max_suppression_cpu(tv.from_numpy(boxes), tv.from_numpy(order), thresh, eps) def rotate_non_max_suppression_cpu(boxes: np.ndarray, order: np.ndarray,", "def non_max_suppression_cpu(boxes: np.ndarray, order: np.ndarray, thresh: float, eps: float =", "__init__(self, enter_result=None): self.enter_result = enter_result def __enter__(self): return self.enter_result def", "in compliance with the License. # You may obtain a", "software # distributed under the License is distributed on an", "from spconv.core_cc.csrc.utils.boxops import BoxOps from spconv.core_cc.csrc.sparse.all.ops_cpu1d import Point2VoxelCPU as Point2VoxelCPU1d", "governing permissions and # limitations under the License. import numpy", "dtype=box_corners.dtype) BoxOps.rbbox_iou(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(standup_iou), tv.from_numpy(overlap), standup_thresh, True) return overlap def", "manager: cm = optional_cm if condition else nullcontext() with cm:", "enter_result=None): self.enter_result = enter_result def __enter__(self): return self.enter_result def __exit__(self,", "self.enter_result = enter_result def __enter__(self): return self.enter_result def __exit__(self, *excinfo):", "if not BoxOps.has_boost(): raise NotImplementedError( \"this op require spconv built", "boost, download boost, export BOOST_ROOT and rebuild.\" ) return BoxOps.rotate_non_max_suppression_cpu(tv.from_numpy(boxes),", "def rbbox_iou(box_corners: np.ndarray, qbox_corners: np.ndarray, standup_iou: np.ndarray, standup_thresh: float): if", "import BoxOps from spconv.core_cc.csrc.sparse.all.ops_cpu1d import Point2VoxelCPU as Point2VoxelCPU1d from spconv.core_cc.csrc.sparse.all.ops_cpu2d", "spconv.core_cc.csrc.sparse.all.ops3d import Point2Voxel as Point2VoxelGPU3d from spconv.core_cc.csrc.sparse.all.ops4d import Point2Voxel as", "standup_thresh, False) return overlap def rbbox_intersection(box_corners: np.ndarray, qbox_corners: np.ndarray, standup_iou:", "Point2VoxelCPU1d from spconv.core_cc.csrc.sparse.all.ops_cpu2d import Point2VoxelCPU as Point2VoxelCPU2d from spconv.core_cc.csrc.sparse.all.ops_cpu3d import", "# limitations under the License. import numpy as np from", "the License. import numpy as np from cumm import tensorview", "return overlap def rbbox_iou_loss(box_corners: np.ndarray, qbox_corners: np.ndarray): if not BoxOps.has_boost():", "spconv built with boost, download boost, export BOOST_ROOT and rebuild.\"", "optional_cm if condition is True \"\"\" def __init__(self, enter_result=None): self.enter_result", "import Point2Voxel as Point2VoxelGPU2d from spconv.core_cc.csrc.sparse.all.ops3d import Point2Voxel as Point2VoxelGPU3d", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "2021 <NAME> # # Licensed under the Apache License, Version", "and # limitations under the License. import numpy as np", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "tv from contextlib import AbstractContextManager from spconv.cppconstants import CPU_ONLY_BUILD from", "to in writing, software # distributed under the License is", "License. import numpy as np from cumm import tensorview as", "# See the License for the specific language governing permissions", "nullcontext() with cm: # Perform operation, using optional_cm if condition", "particular block of code is only sometimes used with a", "or agreed to in writing, software # distributed under the", "import Point2VoxelCPU as Point2VoxelCPU4d if not CPU_ONLY_BUILD: from spconv.core_cc.csrc.sparse.all.ops1d import", "required by applicable law or agreed to in writing, software", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "AbstractContextManager from spconv.cppconstants import CPU_ONLY_BUILD from spconv.core_cc.csrc.utils.boxops import BoxOps from", "with the License. # You may obtain a copy of", "standup_iou: np.ndarray, thresh: float): if not BoxOps.has_boost(): raise NotImplementedError( \"this", "def rotate_non_max_suppression_cpu(boxes: np.ndarray, order: np.ndarray, standup_iou: np.ndarray, thresh: float): if", "download boost, export BOOST_ROOT and rebuild.\" ) return BoxOps.rotate_non_max_suppression_cpu(tv.from_numpy(boxes), tv.from_numpy(order),", "only sometimes used with a normal context manager: cm =", "compliance with the License. # You may obtain a copy", "agreed to in writing, software # distributed under the License", "a particular block of code is only sometimes used with", "distributed under the License is distributed on an \"AS IS\"", "context manager: cm = optional_cm if condition else nullcontext() with", "Point2VoxelCPU as Point2VoxelCPU3d from spconv.core_cc.csrc.sparse.all.ops_cpu4d import Point2VoxelCPU as Point2VoxelCPU4d if", "# Perform operation, using optional_cm if condition is True \"\"\"", "import Point2Voxel as Point2VoxelGPU1d from spconv.core_cc.csrc.sparse.all.ops2d import Point2Voxel as Point2VoxelGPU2d", "permissions and # limitations under the License. import numpy as", "boost, download boost, export BOOST_ROOT and rebuild.\" ) N =", "__exit__(self, *excinfo): pass def rbbox_iou(box_corners: np.ndarray, qbox_corners: np.ndarray, standup_iou: np.ndarray,", "express or implied. # See the License for the specific", "overlap def non_max_suppression_cpu(boxes: np.ndarray, order: np.ndarray, thresh: float, eps: float", "np.ndarray, order: np.ndarray, standup_iou: np.ndarray, thresh: float): if not BoxOps.has_boost():", "except in compliance with the License. # You may obtain", "limitations under the License. import numpy as np from cumm", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "not use this file except in compliance with the License.", "Point2VoxelGPU1d from spconv.core_cc.csrc.sparse.all.ops2d import Point2Voxel as Point2VoxelGPU2d from spconv.core_cc.csrc.sparse.all.ops3d import", "writing, software # distributed under the License is distributed on", "you may not use this file except in compliance with", "as np from cumm import tensorview as tv from contextlib", "Point2VoxelGPU4d class nullcontext(AbstractContextManager): \"\"\"Context manager that does no additional processing.", "no additional processing. Used as a stand-in for a normal", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "not CPU_ONLY_BUILD: from spconv.core_cc.csrc.sparse.all.ops1d import Point2Voxel as Point2VoxelGPU1d from spconv.core_cc.csrc.sparse.all.ops2d", ") N = box_corners.shape[0] overlap = np.zeros((N, ), dtype=box_corners.dtype) BoxOps.rbbox_iou_aligned(tv.from_numpy(box_corners),", "np.ndarray, qbox_corners: np.ndarray, standup_iou: np.ndarray, standup_thresh: float): if not BoxOps.has_boost():", "K), dtype=box_corners.dtype) BoxOps.rbbox_iou(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(standup_iou), tv.from_numpy(overlap), standup_thresh, False) return overlap", "boost, export BOOST_ROOT and rebuild.\" ) N = box_corners.shape[0] K", "op require spconv built with boost, download boost, export BOOST_ROOT", "CPU_ONLY_BUILD: from spconv.core_cc.csrc.sparse.all.ops1d import Point2Voxel as Point2VoxelGPU1d from spconv.core_cc.csrc.sparse.all.ops2d import", "BOOST_ROOT and rebuild.\" ) N = box_corners.shape[0] K = qbox_corners.shape[0]", "CONDITIONS OF ANY KIND, either express or implied. # See", "contextlib import AbstractContextManager from spconv.cppconstants import CPU_ONLY_BUILD from spconv.core_cc.csrc.utils.boxops import", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "overlap = np.zeros((N, ), dtype=box_corners.dtype) BoxOps.rbbox_iou_aligned(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(overlap), False) return", "import AbstractContextManager from spconv.cppconstants import CPU_ONLY_BUILD from spconv.core_cc.csrc.utils.boxops import BoxOps", "np.ndarray, order: np.ndarray, thresh: float, eps: float = 0.0): return", "box_corners.shape[0] K = qbox_corners.shape[0] overlap = np.zeros((N, K), dtype=box_corners.dtype) BoxOps.rbbox_iou(tv.from_numpy(box_corners),", "tv.from_numpy(overlap), standup_thresh, False) return overlap def rbbox_intersection(box_corners: np.ndarray, qbox_corners: np.ndarray,", "as Point2VoxelGPU1d from spconv.core_cc.csrc.sparse.all.ops2d import Point2Voxel as Point2VoxelGPU2d from spconv.core_cc.csrc.sparse.all.ops3d", "rebuild.\" ) N = box_corners.shape[0] overlap = np.zeros((N, ), dtype=box_corners.dtype)", "as tv from contextlib import AbstractContextManager from spconv.cppconstants import CPU_ONLY_BUILD", "spconv.core_cc.csrc.utils.boxops import BoxOps from spconv.core_cc.csrc.sparse.all.ops_cpu1d import Point2VoxelCPU as Point2VoxelCPU1d from", "False) return overlap def rbbox_intersection(box_corners: np.ndarray, qbox_corners: np.ndarray, standup_iou: np.ndarray,", "self.enter_result def __exit__(self, *excinfo): pass def rbbox_iou(box_corners: np.ndarray, qbox_corners: np.ndarray,", "qbox_corners.shape[0] overlap = np.zeros((N, K), dtype=box_corners.dtype) BoxOps.rbbox_iou(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(standup_iou), tv.from_numpy(overlap),", "OR CONDITIONS OF ANY KIND, either express or implied. #", "the License is distributed on an \"AS IS\" BASIS, #", "spconv.core_cc.csrc.sparse.all.ops_cpu4d import Point2VoxelCPU as Point2VoxelCPU4d if not CPU_ONLY_BUILD: from spconv.core_cc.csrc.sparse.all.ops1d", "nullcontext(AbstractContextManager): \"\"\"Context manager that does no additional processing. Used as", "thresh: float, eps: float = 0.0): return BoxOps.non_max_suppression_cpu(tv.from_numpy(boxes), tv.from_numpy(order), thresh,", "def rbbox_iou_loss(box_corners: np.ndarray, qbox_corners: np.ndarray): if not BoxOps.has_boost(): raise NotImplementedError(", "normal context manager, when a particular block of code is", "tv.from_numpy(qbox_corners), tv.from_numpy(standup_iou), tv.from_numpy(overlap), standup_thresh, True) return overlap def rbbox_iou_loss(box_corners: np.ndarray,", "overlap def rbbox_iou_loss(box_corners: np.ndarray, qbox_corners: np.ndarray): if not BoxOps.has_boost(): raise", "optional_cm if condition else nullcontext() with cm: # Perform operation,", "rotate_non_max_suppression_cpu(boxes: np.ndarray, order: np.ndarray, standup_iou: np.ndarray, thresh: float): if not", "Copyright 2021 <NAME> # # Licensed under the Apache License,", "law or agreed to in writing, software # distributed under", "with boost, download boost, export BOOST_ROOT and rebuild.\" ) N", "\"\"\"Context manager that does no additional processing. Used as a", "np.ndarray, standup_iou: np.ndarray, thresh: float): if not BoxOps.has_boost(): raise NotImplementedError(", "Point2VoxelGPU2d from spconv.core_cc.csrc.sparse.all.ops3d import Point2Voxel as Point2VoxelGPU3d from spconv.core_cc.csrc.sparse.all.ops4d import", "= enter_result def __enter__(self): return self.enter_result def __exit__(self, *excinfo): pass", "not BoxOps.has_boost(): raise NotImplementedError( \"this op require spconv built with", "from contextlib import AbstractContextManager from spconv.cppconstants import CPU_ONLY_BUILD from spconv.core_cc.csrc.utils.boxops", "raise NotImplementedError( \"this op require spconv built with boost, download", "BoxOps from spconv.core_cc.csrc.sparse.all.ops_cpu1d import Point2VoxelCPU as Point2VoxelCPU1d from spconv.core_cc.csrc.sparse.all.ops_cpu2d import", "K = qbox_corners.shape[0] overlap = np.zeros((N, K), dtype=box_corners.dtype) BoxOps.rbbox_iou(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners),", "NotImplementedError( \"this op require spconv built with boost, download boost,", "may obtain a copy of the License at # #", "under the License. import numpy as np from cumm import", "if condition is True \"\"\" def __init__(self, enter_result=None): self.enter_result =", "tv.from_numpy(overlap), standup_thresh, True) return overlap def rbbox_iou_loss(box_corners: np.ndarray, qbox_corners: np.ndarray):", "import CPU_ONLY_BUILD from spconv.core_cc.csrc.utils.boxops import BoxOps from spconv.core_cc.csrc.sparse.all.ops_cpu1d import Point2VoxelCPU", "from spconv.core_cc.csrc.sparse.all.ops_cpu3d import Point2VoxelCPU as Point2VoxelCPU3d from spconv.core_cc.csrc.sparse.all.ops_cpu4d import Point2VoxelCPU", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "from spconv.core_cc.csrc.sparse.all.ops_cpu1d import Point2VoxelCPU as Point2VoxelCPU1d from spconv.core_cc.csrc.sparse.all.ops_cpu2d import Point2VoxelCPU", "used with a normal context manager: cm = optional_cm if", "may not use this file except in compliance with the", "operation, using optional_cm if condition is True \"\"\" def __init__(self,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "this file except in compliance with the License. # You", "def __exit__(self, *excinfo): pass def rbbox_iou(box_corners: np.ndarray, qbox_corners: np.ndarray, standup_iou:", "standup_thresh, True) return overlap def rbbox_iou_loss(box_corners: np.ndarray, qbox_corners: np.ndarray): if", "spconv.core_cc.csrc.sparse.all.ops1d import Point2Voxel as Point2VoxelGPU1d from spconv.core_cc.csrc.sparse.all.ops2d import Point2Voxel as", "np.ndarray, standup_iou: np.ndarray, standup_thresh: float): if not BoxOps.has_boost(): raise NotImplementedError(", "\"this op require spconv built with boost, download boost, export", "from spconv.core_cc.csrc.sparse.all.ops1d import Point2Voxel as Point2VoxelGPU1d from spconv.core_cc.csrc.sparse.all.ops2d import Point2Voxel", "<NAME> # # Licensed under the Apache License, Version 2.0", "Point2VoxelCPU as Point2VoxelCPU4d if not CPU_ONLY_BUILD: from spconv.core_cc.csrc.sparse.all.ops1d import Point2Voxel", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "non_max_suppression_cpu(boxes: np.ndarray, order: np.ndarray, thresh: float, eps: float = 0.0):", "# # Licensed under the Apache License, Version 2.0 (the", "pass def rbbox_iou(box_corners: np.ndarray, qbox_corners: np.ndarray, standup_iou: np.ndarray, standup_thresh: float):", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "manager, when a particular block of code is only sometimes", "from spconv.core_cc.csrc.sparse.all.ops4d import Point2Voxel as Point2VoxelGPU4d class nullcontext(AbstractContextManager): \"\"\"Context manager", "processing. Used as a stand-in for a normal context manager,", "spconv.core_cc.csrc.sparse.all.ops4d import Point2Voxel as Point2VoxelGPU4d class nullcontext(AbstractContextManager): \"\"\"Context manager that", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "is True \"\"\" def __init__(self, enter_result=None): self.enter_result = enter_result def", "and rebuild.\" ) N = box_corners.shape[0] K = qbox_corners.shape[0] overlap", "require spconv built with boost, download boost, export BOOST_ROOT and", "__enter__(self): return self.enter_result def __exit__(self, *excinfo): pass def rbbox_iou(box_corners: np.ndarray,", "BoxOps.has_boost(): raise NotImplementedError( \"this op require spconv built with boost,", "is only sometimes used with a normal context manager: cm", "language governing permissions and # limitations under the License. import", "standup_thresh: float): if not BoxOps.has_boost(): raise NotImplementedError( \"this op require", "Perform operation, using optional_cm if condition is True \"\"\" def", "Point2VoxelCPU as Point2VoxelCPU1d from spconv.core_cc.csrc.sparse.all.ops_cpu2d import Point2VoxelCPU as Point2VoxelCPU2d from", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "class nullcontext(AbstractContextManager): \"\"\"Context manager that does no additional processing. Used", "tv.from_numpy(standup_iou), tv.from_numpy(overlap), standup_thresh, True) return overlap def rbbox_iou_loss(box_corners: np.ndarray, qbox_corners:", "or implied. # See the License for the specific language", "from spconv.cppconstants import CPU_ONLY_BUILD from spconv.core_cc.csrc.utils.boxops import BoxOps from spconv.core_cc.csrc.sparse.all.ops_cpu1d", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "import Point2Voxel as Point2VoxelGPU3d from spconv.core_cc.csrc.sparse.all.ops4d import Point2Voxel as Point2VoxelGPU4d", "Point2VoxelCPU3d from spconv.core_cc.csrc.sparse.all.ops_cpu4d import Point2VoxelCPU as Point2VoxelCPU4d if not CPU_ONLY_BUILD:", "return overlap def non_max_suppression_cpu(boxes: np.ndarray, order: np.ndarray, thresh: float, eps:", "Point2VoxelCPU4d if not CPU_ONLY_BUILD: from spconv.core_cc.csrc.sparse.all.ops1d import Point2Voxel as Point2VoxelGPU1d", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "context manager, when a particular block of code is only", "spconv.core_cc.csrc.sparse.all.ops_cpu2d import Point2VoxelCPU as Point2VoxelCPU2d from spconv.core_cc.csrc.sparse.all.ops_cpu3d import Point2VoxelCPU as", "thresh: float): if not BoxOps.has_boost(): raise NotImplementedError( \"this op require", "float, eps: float = 0.0): return BoxOps.non_max_suppression_cpu(tv.from_numpy(boxes), tv.from_numpy(order), thresh, eps)", "export BOOST_ROOT and rebuild.\" ) N = box_corners.shape[0] K =", "(the \"License\"); # you may not use this file except", "eps) def rotate_non_max_suppression_cpu(boxes: np.ndarray, order: np.ndarray, standup_iou: np.ndarray, thresh: float):", "# you may not use this file except in compliance", "standup_iou: np.ndarray, standup_thresh: float): if not BoxOps.has_boost(): raise NotImplementedError( \"this", "else nullcontext() with cm: # Perform operation, using optional_cm if", "condition else nullcontext() with cm: # Perform operation, using optional_cm", "eps: float = 0.0): return BoxOps.non_max_suppression_cpu(tv.from_numpy(boxes), tv.from_numpy(order), thresh, eps) def", "# # Unless required by applicable law or agreed to", "= optional_cm if condition else nullcontext() with cm: # Perform", "np.ndarray, thresh: float): if not BoxOps.has_boost(): raise NotImplementedError( \"this op", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "Version 2.0 (the \"License\"); # you may not use this", "manager that does no additional processing. Used as a stand-in", "= np.zeros((N, K), dtype=box_corners.dtype) BoxOps.rbbox_iou(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(standup_iou), tv.from_numpy(overlap), standup_thresh, True)", "qbox_corners: np.ndarray): if not BoxOps.has_boost(): raise NotImplementedError( \"this op require", "tv.from_numpy(qbox_corners), tv.from_numpy(standup_iou), tv.from_numpy(overlap), standup_thresh, False) return overlap def rbbox_intersection(box_corners: np.ndarray,", "implied. # See the License for the specific language governing", "under the Apache License, Version 2.0 (the \"License\"); # you", "if condition else nullcontext() with cm: # Perform operation, using", "def rbbox_intersection(box_corners: np.ndarray, qbox_corners: np.ndarray, standup_iou: np.ndarray, standup_thresh: float): if", "BoxOps.rbbox_iou_aligned(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(overlap), False) return overlap def non_max_suppression_cpu(boxes: np.ndarray, order:", "by applicable law or agreed to in writing, software #", "a normal context manager, when a particular block of code", "= box_corners.shape[0] overlap = np.zeros((N, ), dtype=box_corners.dtype) BoxOps.rbbox_iou_aligned(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(overlap),", "*excinfo): pass def rbbox_iou(box_corners: np.ndarray, qbox_corners: np.ndarray, standup_iou: np.ndarray, standup_thresh:", "= np.zeros((N, K), dtype=box_corners.dtype) BoxOps.rbbox_iou(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(standup_iou), tv.from_numpy(overlap), standup_thresh, False)", "as Point2VoxelGPU3d from spconv.core_cc.csrc.sparse.all.ops4d import Point2Voxel as Point2VoxelGPU4d class nullcontext(AbstractContextManager):", "as Point2VoxelCPU1d from spconv.core_cc.csrc.sparse.all.ops_cpu2d import Point2VoxelCPU as Point2VoxelCPU2d from spconv.core_cc.csrc.sparse.all.ops_cpu3d", "N = box_corners.shape[0] K = qbox_corners.shape[0] overlap = np.zeros((N, K),", "return overlap def rbbox_intersection(box_corners: np.ndarray, qbox_corners: np.ndarray, standup_iou: np.ndarray, standup_thresh:", "import numpy as np from cumm import tensorview as tv", "np.zeros((N, ), dtype=box_corners.dtype) BoxOps.rbbox_iou_aligned(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(overlap), False) return overlap def", "BoxOps.rbbox_iou(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(standup_iou), tv.from_numpy(overlap), standup_thresh, True) return overlap def rbbox_iou_loss(box_corners:", "code is only sometimes used with a normal context manager:", "def __init__(self, enter_result=None): self.enter_result = enter_result def __enter__(self): return self.enter_result", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "np.ndarray): if not BoxOps.has_boost(): raise NotImplementedError( \"this op require spconv", "Unless required by applicable law or agreed to in writing,", "np.ndarray, qbox_corners: np.ndarray): if not BoxOps.has_boost(): raise NotImplementedError( \"this op", "BOOST_ROOT and rebuild.\" ) N = box_corners.shape[0] overlap = np.zeros((N,", "boost, export BOOST_ROOT and rebuild.\" ) return BoxOps.rotate_non_max_suppression_cpu(tv.from_numpy(boxes), tv.from_numpy(order), tv.from_numpy(standup_iou),", "the specific language governing permissions and # limitations under the", "np.zeros((N, K), dtype=box_corners.dtype) BoxOps.rbbox_iou(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(standup_iou), tv.from_numpy(overlap), standup_thresh, False) return", "as Point2VoxelCPU2d from spconv.core_cc.csrc.sparse.all.ops_cpu3d import Point2VoxelCPU as Point2VoxelCPU3d from spconv.core_cc.csrc.sparse.all.ops_cpu4d", "applicable law or agreed to in writing, software # distributed", "as Point2VoxelCPU3d from spconv.core_cc.csrc.sparse.all.ops_cpu4d import Point2VoxelCPU as Point2VoxelCPU4d if not", "boost, export BOOST_ROOT and rebuild.\" ) N = box_corners.shape[0] overlap", "box_corners.shape[0] overlap = np.zeros((N, ), dtype=box_corners.dtype) BoxOps.rbbox_iou_aligned(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(overlap), False)", "does no additional processing. Used as a stand-in for a", "np.zeros((N, K), dtype=box_corners.dtype) BoxOps.rbbox_iou(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(standup_iou), tv.from_numpy(overlap), standup_thresh, True) return", "order: np.ndarray, standup_iou: np.ndarray, thresh: float): if not BoxOps.has_boost(): raise", "in writing, software # distributed under the License is distributed", "Used as a stand-in for a normal context manager, when", "float): if not BoxOps.has_boost(): raise NotImplementedError( \"this op require spconv", "spconv.core_cc.csrc.sparse.all.ops_cpu3d import Point2VoxelCPU as Point2VoxelCPU3d from spconv.core_cc.csrc.sparse.all.ops_cpu4d import Point2VoxelCPU as", "rbbox_intersection(box_corners: np.ndarray, qbox_corners: np.ndarray, standup_iou: np.ndarray, standup_thresh: float): if not", "condition is True \"\"\" def __init__(self, enter_result=None): self.enter_result = enter_result", "Point2VoxelGPU3d from spconv.core_cc.csrc.sparse.all.ops4d import Point2Voxel as Point2VoxelGPU4d class nullcontext(AbstractContextManager): \"\"\"Context", "if not CPU_ONLY_BUILD: from spconv.core_cc.csrc.sparse.all.ops1d import Point2Voxel as Point2VoxelGPU1d from", "Point2Voxel as Point2VoxelGPU1d from spconv.core_cc.csrc.sparse.all.ops2d import Point2Voxel as Point2VoxelGPU2d from", "spconv.core_cc.csrc.sparse.all.ops_cpu1d import Point2VoxelCPU as Point2VoxelCPU1d from spconv.core_cc.csrc.sparse.all.ops_cpu2d import Point2VoxelCPU as", "Point2VoxelCPU2d from spconv.core_cc.csrc.sparse.all.ops_cpu3d import Point2VoxelCPU as Point2VoxelCPU3d from spconv.core_cc.csrc.sparse.all.ops_cpu4d import", "= np.zeros((N, ), dtype=box_corners.dtype) BoxOps.rbbox_iou_aligned(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(overlap), False) return overlap", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "tv.from_numpy(order), thresh, eps) def rotate_non_max_suppression_cpu(boxes: np.ndarray, order: np.ndarray, standup_iou: np.ndarray,", "License, Version 2.0 (the \"License\"); # you may not use", "# You may obtain a copy of the License at", "def __enter__(self): return self.enter_result def __exit__(self, *excinfo): pass def rbbox_iou(box_corners:", "Point2Voxel as Point2VoxelGPU2d from spconv.core_cc.csrc.sparse.all.ops3d import Point2Voxel as Point2VoxelGPU3d from", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "a stand-in for a normal context manager, when a particular", "from spconv.core_cc.csrc.sparse.all.ops_cpu2d import Point2VoxelCPU as Point2VoxelCPU2d from spconv.core_cc.csrc.sparse.all.ops_cpu3d import Point2VoxelCPU", "tv.from_numpy(standup_iou), tv.from_numpy(overlap), standup_thresh, False) return overlap def rbbox_intersection(box_corners: np.ndarray, qbox_corners:", "import Point2VoxelCPU as Point2VoxelCPU3d from spconv.core_cc.csrc.sparse.all.ops_cpu4d import Point2VoxelCPU as Point2VoxelCPU4d", "the License for the specific language governing permissions and #", "True \"\"\" def __init__(self, enter_result=None): self.enter_result = enter_result def __enter__(self):", "Apache License, Version 2.0 (the \"License\"); # you may not", "either express or implied. # See the License for the", "Point2Voxel as Point2VoxelGPU3d from spconv.core_cc.csrc.sparse.all.ops4d import Point2Voxel as Point2VoxelGPU4d class", "as Point2VoxelGPU4d class nullcontext(AbstractContextManager): \"\"\"Context manager that does no additional", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "as Point2VoxelCPU4d if not CPU_ONLY_BUILD: from spconv.core_cc.csrc.sparse.all.ops1d import Point2Voxel as", "rbbox_iou_loss(box_corners: np.ndarray, qbox_corners: np.ndarray): if not BoxOps.has_boost(): raise NotImplementedError( \"this", "enter_result def __enter__(self): return self.enter_result def __exit__(self, *excinfo): pass def", "that does no additional processing. Used as a stand-in for", "return self.enter_result def __exit__(self, *excinfo): pass def rbbox_iou(box_corners: np.ndarray, qbox_corners:", "rebuild.\" ) N = box_corners.shape[0] K = qbox_corners.shape[0] overlap =", "cumm import tensorview as tv from contextlib import AbstractContextManager from", "order: np.ndarray, thresh: float, eps: float = 0.0): return BoxOps.non_max_suppression_cpu(tv.from_numpy(boxes),", "tv.from_numpy(overlap), False) return overlap def non_max_suppression_cpu(boxes: np.ndarray, order: np.ndarray, thresh:", "import Point2Voxel as Point2VoxelGPU4d class nullcontext(AbstractContextManager): \"\"\"Context manager that does", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "tv.from_numpy(qbox_corners), tv.from_numpy(overlap), False) return overlap def non_max_suppression_cpu(boxes: np.ndarray, order: np.ndarray,", "download boost, export BOOST_ROOT and rebuild.\" ) N = box_corners.shape[0]", "True) return overlap def rbbox_iou_loss(box_corners: np.ndarray, qbox_corners: np.ndarray): if not", "dtype=box_corners.dtype) BoxOps.rbbox_iou(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(standup_iou), tv.from_numpy(overlap), standup_thresh, False) return overlap def", "= qbox_corners.shape[0] overlap = np.zeros((N, K), dtype=box_corners.dtype) BoxOps.rbbox_iou(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(standup_iou),", "dtype=box_corners.dtype) BoxOps.rbbox_iou_aligned(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(overlap), False) return overlap def non_max_suppression_cpu(boxes: np.ndarray,", "import tensorview as tv from contextlib import AbstractContextManager from spconv.cppconstants", "from spconv.core_cc.csrc.sparse.all.ops2d import Point2Voxel as Point2VoxelGPU2d from spconv.core_cc.csrc.sparse.all.ops3d import Point2Voxel", "block of code is only sometimes used with a normal", "Point2VoxelCPU as Point2VoxelCPU2d from spconv.core_cc.csrc.sparse.all.ops_cpu3d import Point2VoxelCPU as Point2VoxelCPU3d from", "export BOOST_ROOT and rebuild.\" ) return BoxOps.rotate_non_max_suppression_cpu(tv.from_numpy(boxes), tv.from_numpy(order), tv.from_numpy(standup_iou), thresh)", "with cm: # Perform operation, using optional_cm if condition is", "\"License\"); # you may not use this file except in", "spconv.core_cc.csrc.sparse.all.ops2d import Point2Voxel as Point2VoxelGPU2d from spconv.core_cc.csrc.sparse.all.ops3d import Point2Voxel as", "as Point2VoxelGPU2d from spconv.core_cc.csrc.sparse.all.ops3d import Point2Voxel as Point2VoxelGPU3d from spconv.core_cc.csrc.sparse.all.ops4d", "with boost, download boost, export BOOST_ROOT and rebuild.\" ) return", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "normal context manager: cm = optional_cm if condition else nullcontext()", "# distributed under the License is distributed on an \"AS", "using optional_cm if condition is True \"\"\" def __init__(self, enter_result=None):", "spconv.cppconstants import CPU_ONLY_BUILD from spconv.core_cc.csrc.utils.boxops import BoxOps from spconv.core_cc.csrc.sparse.all.ops_cpu1d import", "BoxOps.non_max_suppression_cpu(tv.from_numpy(boxes), tv.from_numpy(order), thresh, eps) def rotate_non_max_suppression_cpu(boxes: np.ndarray, order: np.ndarray, standup_iou:", "# Unless required by applicable law or agreed to in", "np from cumm import tensorview as tv from contextlib import", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "BoxOps.rbbox_iou(tv.from_numpy(box_corners), tv.from_numpy(qbox_corners), tv.from_numpy(standup_iou), tv.from_numpy(overlap), standup_thresh, False) return overlap def rbbox_intersection(box_corners:", "# Copyright 2021 <NAME> # # Licensed under the Apache", "0.0): return BoxOps.non_max_suppression_cpu(tv.from_numpy(boxes), tv.from_numpy(order), thresh, eps) def rotate_non_max_suppression_cpu(boxes: np.ndarray, order:", "You may obtain a copy of the License at #", "built with boost, download boost, export BOOST_ROOT and rebuild.\" )", "from spconv.core_cc.csrc.sparse.all.ops_cpu4d import Point2VoxelCPU as Point2VoxelCPU4d if not CPU_ONLY_BUILD: from", "thresh, eps) def rotate_non_max_suppression_cpu(boxes: np.ndarray, order: np.ndarray, standup_iou: np.ndarray, thresh:", "the Apache License, Version 2.0 (the \"License\"); # you may", "numpy as np from cumm import tensorview as tv from", "rbbox_iou(box_corners: np.ndarray, qbox_corners: np.ndarray, standup_iou: np.ndarray, standup_thresh: float): if not", "qbox_corners: np.ndarray, standup_iou: np.ndarray, standup_thresh: float): if not BoxOps.has_boost(): raise", "np.ndarray, standup_thresh: float): if not BoxOps.has_boost(): raise NotImplementedError( \"this op", "np.ndarray, thresh: float, eps: float = 0.0): return BoxOps.non_max_suppression_cpu(tv.from_numpy(boxes), tv.from_numpy(order)," ]
[ "= issue.getElementsByTagName('location')[0] path = location_elem.attributes['file'].value line = location_elem.getAttribute('line') if line:", "product dir.') parser.add_option('--src-dirs', help='Directories containing java files.') parser.add_option('--classes-dir', help='Directory containing", "Run \"python %s %s\"\\n' % (num_issues, _RelativizePath(result_path), _RelativizePath(config_path), _RelativizePath(os.path.join(_SRC_ROOT, 'build',", "import sys from xml.dom import minidom from util import build_utils", "required=['lint_path', 'config_path', 'processed_config_path', 'manifest_path', 'result_path', 'product_dir', 'src_dirs', 'classes_dir']) src_dirs =", "# Lint errors do not fail the build. return 0", "issues.\\n' ' - For full explanation refer to %s\\n' '", "'%s:%s %s: %s [%s]' % (path, line, severity, message, issue_id)", "'product_dir', 'src_dirs', 'classes_dir']) src_dirs = build_utils.ParseGypList(options.src_dirs) rc = 0 if", "is governed by a BSD-style license that can be #", "= '%s %s: %s [%s]' % (path, severity, message, issue_id)", "have a line number. error = '%s %s: %s [%s]'", "- For full explanation refer to %s\\n' ' - Wanna", "Wanna suppress these issues?\\n' ' 1. Read comment in %s\\n'", ">> sys.stderr, error for attr in ['errorLine1', 'errorLine2']: error_line =", "= issue.attributes['severity'].value message = issue.attributes['message'].value location_elem = issue.getElementsByTagName('location')[0] path =", "[%s]' % (path, line, severity, message, issue_id) else: # Issues", "parser.add_option('--config-path', help='Path to lint suppressions file.') parser.add_option('--processed-config-path', help='Path to processed", "not build_utils.IsTimeStale(processed_config_path, [config_path]): return with open(config_path, 'rb') as f: content", "return os.path.relpath(os.path.abspath(path), _SRC_ROOT) def _ProcessConfigFile(): if not build_utils.IsTimeStale(processed_config_path, [config_path]): return", "cwd=_SRC_ROOT) except build_utils.CalledProcessError: # There is a problem with lint", "else: num_issues = _ParseAndShowResultFile() _ProcessResultFile() msg = ('\\nLint found %d", "with open(config_path, 'rb') as f: content = f.read().replace( 'PRODUCT_DIR', _RelativizePath(product_dir))", "parser.add_option('--enable', action='store_true', help='Run lint instead of just touching stamp.') options,", "sys.stderr, msg # Lint errors do not fail the build.", "= location_elem.getAttribute('line') if line: error = '%s:%s %s: %s [%s]'", "config_path, processed_config_path, manifest_path, result_path, product_dir, src_dirs, classes_dir): def _RelativizePath(path): \"\"\"Returns", "help='Directories containing java files.') parser.add_option('--classes-dir', help='Directory containing class files.') parser.add_option('--stamp',", "code is governed by a BSD-style license that can be", "f.write(content) def _ParseAndShowResultFile(): dom = minidom.parse(result_path) issues = dom.getElementsByTagName('issue') print", "'PRODUCT_DIR', _RelativizePath(product_dir)) with open(processed_config_path, 'wb') as f: f.write(content) def _ProcessResultFile():", "and not rc: build_utils.Touch(options.stamp) return rc if __name__ == '__main__':", "= build_utils.ParseGypList(options.src_dirs) rc = 0 if options.enable: rc = _RunLint(options.lint_path,", "= dom.getElementsByTagName('issue') print >> sys.stderr for issue in issues: issue_id", "on success.') parser.add_option('--enable', action='store_true', help='Run lint instead of just touching", "governed by a BSD-style license that can be # found", "XML lint result file.') parser.add_option('--product-dir', help='Path to product dir.') parser.add_option('--src-dirs',", "Use of this source code is governed by a BSD-style", "= 0 if options.enable: rc = _RunLint(options.lint_path, options.config_path, options.processed_config_path, options.manifest_path,", "except build_utils.CalledProcessError: # There is a problem with lint usage", "print >> sys.stderr, error_line return len(issues) _ProcessConfigFile() cmd = [", "% (path, line, severity, message, issue_id) else: # Issues in", "options.stamp and not rc: build_utils.Touch(options.stamp) return rc if __name__ ==", "return len(issues) _ProcessConfigFile() cmd = [ lint_path, '-Werror', '--exitcode', '--showall',", "issue.attributes['severity'].value message = issue.attributes['message'].value location_elem = issue.getElementsByTagName('location')[0] path = location_elem.attributes['file'].value", "= location_elem.attributes['file'].value line = location_elem.getAttribute('line') if line: error = '%s:%s", "% (num_issues, _RelativizePath(result_path), _RelativizePath(config_path), _RelativizePath(os.path.join(_SRC_ROOT, 'build', 'android', 'lint', 'suppress.py')), _RelativizePath(result_path)))", "= optparse.OptionParser() parser.add_option('--lint-path', help='Path to lint executable.') parser.add_option('--config-path', help='Path to", "(path, line, severity, message, issue_id) else: # Issues in class", "sys from xml.dom import minidom from util import build_utils _SRC_ROOT", "processed_config_path, manifest_path, result_path, product_dir, src_dirs, classes_dir): def _RelativizePath(path): \"\"\"Returns relative", "import minidom from util import build_utils _SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..',", "f: content = f.read().replace( _RelativizePath(product_dir), 'PRODUCT_DIR') with open(result_path, 'wb') as", "for attr in ['errorLine1', 'errorLine2']: error_line = issue.getAttribute(attr) if error_line:", "lint suppressions file.') parser.add_option('--processed-config-path', help='Path to processed lint suppressions file.')", "'..')) def _RunLint(lint_path, config_path, processed_config_path, manifest_path, result_path, product_dir, src_dirs, classes_dir):", "%s\\n' ' 2. Run \"python %s %s\"\\n' % (num_issues, _RelativizePath(result_path),", "location_elem.getAttribute('line') if line: error = '%s:%s %s: %s [%s]' %", "line: error = '%s:%s %s: %s [%s]' % (path, line,", "# There are actual lint issues else: num_issues = _ParseAndShowResultFile()", "parser.add_option('--processed-config-path', help='Path to processed lint suppressions file.') parser.add_option('--manifest-path', help='Path to", "rights reserved. # Use of this source code is governed", "build_utils.CheckOptions( options, parser, required=['lint_path', 'config_path', 'processed_config_path', 'manifest_path', 'result_path', 'product_dir', 'src_dirs',", "open(processed_config_path, 'wb') as f: f.write(content) def _ProcessResultFile(): with open(result_path, 'rb')", "error for attr in ['errorLine1', 'errorLine2']: error_line = issue.getAttribute(attr) if", "return 0 def main(): parser = optparse.OptionParser() parser.add_option('--lint-path', help='Path to", "line = location_elem.getAttribute('line') if line: error = '%s:%s %s: %s", "in ['errorLine1', 'errorLine2']: error_line = issue.getAttribute(attr) if error_line: print >>", "raise # There are actual lint issues else: num_issues =", "from xml.dom import minidom from util import build_utils _SRC_ROOT =", "%s: %s [%s]' % (path, severity, message, issue_id) print >>", "help='Path to touch on success.') parser.add_option('--enable', action='store_true', help='Run lint instead", "options.product_dir, src_dirs, options.classes_dir) if options.stamp and not rc: build_utils.Touch(options.stamp) return", "For full explanation refer to %s\\n' ' - Wanna suppress", "is a problem with lint usage if not os.path.exists(result_path): raise", "'--showall', '--config', _RelativizePath(processed_config_path), '--classpath', _RelativizePath(classes_dir), '--xml', _RelativizePath(result_path), ] for src", ">> sys.stderr, error_line return len(issues) _ProcessConfigFile() cmd = [ lint_path,", "file. \"\"\"Runs Android's lint tool.\"\"\" import optparse import os import", "issue_id) else: # Issues in class files don't have a", "_RelativizePath(src)]) cmd.append(_RelativizePath(os.path.join(manifest_path, os.pardir))) if os.path.exists(result_path): os.remove(result_path) try: build_utils.CheckOutput(cmd, cwd=_SRC_ROOT) except", "parser.parse_args() build_utils.CheckOptions( options, parser, required=['lint_path', 'config_path', 'processed_config_path', 'manifest_path', 'result_path', 'product_dir',", "not os.path.exists(result_path): raise # There are actual lint issues else:", "'wb') as f: f.write(content) def _ParseAndShowResultFile(): dom = minidom.parse(result_path) issues", "def _RunLint(lint_path, config_path, processed_config_path, manifest_path, result_path, product_dir, src_dirs, classes_dir): def", "os.path.relpath(os.path.abspath(path), _SRC_ROOT) def _ProcessConfigFile(): if not build_utils.IsTimeStale(processed_config_path, [config_path]): return with", "error = '%s:%s %s: %s [%s]' % (path, line, severity,", "os.path.exists(result_path): raise # There are actual lint issues else: num_issues", "'suppress.py')), _RelativizePath(result_path))) print >> sys.stderr, msg # Lint errors do", "build_utils.CalledProcessError: # There is a problem with lint usage if", "in %s\\n' ' 2. Run \"python %s %s\"\\n' % (num_issues,", "_RunLint(lint_path, config_path, processed_config_path, manifest_path, result_path, product_dir, src_dirs, classes_dir): def _RelativizePath(path):", "build_utils.IsTimeStale(processed_config_path, [config_path]): return with open(config_path, 'rb') as f: content =", "_ProcessConfigFile(): if not build_utils.IsTimeStale(processed_config_path, [config_path]): return with open(config_path, 'rb') as", "license that can be # found in the LICENSE file.", "_RelativizePath(path): \"\"\"Returns relative path to top-level src dir. Args: path:", "path = location_elem.attributes['file'].value line = location_elem.getAttribute('line') if line: error =", "to %s\\n' ' - Wanna suppress these issues?\\n' ' 1.", "a line number. error = '%s %s: %s [%s]' %", "issues else: num_issues = _ParseAndShowResultFile() _ProcessResultFile() msg = ('\\nLint found", "msg # Lint errors do not fail the build. return", "(path, severity, message, issue_id) print >> sys.stderr, error for attr", "BSD-style license that can be # found in the LICENSE", "# Use of this source code is governed by a", "in class files don't have a line number. error =", "_SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) def _RunLint(lint_path, config_path, processed_config_path,", "location_elem.attributes['file'].value line = location_elem.getAttribute('line') if line: error = '%s:%s %s:", "cmd.append(_RelativizePath(os.path.join(manifest_path, os.pardir))) if os.path.exists(result_path): os.remove(result_path) try: build_utils.CheckOutput(cmd, cwd=_SRC_ROOT) except build_utils.CalledProcessError:", "_SRC_ROOT) def _ProcessConfigFile(): if not build_utils.IsTimeStale(processed_config_path, [config_path]): return with open(config_path,", "LICENSE file. \"\"\"Runs Android's lint tool.\"\"\" import optparse import os", "= ('\\nLint found %d new issues.\\n' ' - For full", "len(issues) _ProcessConfigFile() cmd = [ lint_path, '-Werror', '--exitcode', '--showall', '--config',", "[%s]' % (path, severity, message, issue_id) print >> sys.stderr, error", "for issue in issues: issue_id = issue.attributes['id'].value severity = issue.attributes['severity'].value", "'..', '..', '..')) def _RunLint(lint_path, config_path, processed_config_path, manifest_path, result_path, product_dir,", "issue in issues: issue_id = issue.attributes['id'].value severity = issue.attributes['severity'].value message", "try: build_utils.CheckOutput(cmd, cwd=_SRC_ROOT) except build_utils.CalledProcessError: # There is a problem", "content = f.read().replace( _RelativizePath(product_dir), 'PRODUCT_DIR') with open(result_path, 'wb') as f:", "f: f.write(content) def _ProcessResultFile(): with open(result_path, 'rb') as f: content", "if options.stamp and not rc: build_utils.Touch(options.stamp) return rc if __name__", "lint result file.') parser.add_option('--product-dir', help='Path to product dir.') parser.add_option('--src-dirs', help='Directories", "optparse.OptionParser() parser.add_option('--lint-path', help='Path to lint executable.') parser.add_option('--config-path', help='Path to lint", "'-Werror', '--exitcode', '--showall', '--config', _RelativizePath(processed_config_path), '--classpath', _RelativizePath(classes_dir), '--xml', _RelativizePath(result_path), ]", "as f: content = f.read().replace( 'PRODUCT_DIR', _RelativizePath(product_dir)) with open(processed_config_path, 'wb')", "_ProcessConfigFile() cmd = [ lint_path, '-Werror', '--exitcode', '--showall', '--config', _RelativizePath(processed_config_path),", "a BSD-style license that can be # found in the", "help='Path to lint suppressions file.') parser.add_option('--processed-config-path', help='Path to processed lint", "sys.stderr, error_line return len(issues) _ProcessConfigFile() cmd = [ lint_path, '-Werror',", "result file.') parser.add_option('--product-dir', help='Path to product dir.') parser.add_option('--src-dirs', help='Directories containing", "optparse import os import sys from xml.dom import minidom from", "as f: content = f.read().replace( _RelativizePath(product_dir), 'PRODUCT_DIR') with open(result_path, 'wb')", "do not fail the build. return 0 return 0 def", "dom.getElementsByTagName('issue') print >> sys.stderr for issue in issues: issue_id =", "build_utils.ParseGypList(options.src_dirs) rc = 0 if options.enable: rc = _RunLint(options.lint_path, options.config_path,", "'build', 'android', 'lint', 'suppress.py')), _RelativizePath(result_path))) print >> sys.stderr, msg #", "files.') parser.add_option('--classes-dir', help='Directory containing class files.') parser.add_option('--stamp', help='Path to touch", "0 if options.enable: rc = _RunLint(options.lint_path, options.config_path, options.processed_config_path, options.manifest_path, options.result_path,", "options.config_path, options.processed_config_path, options.manifest_path, options.result_path, options.product_dir, src_dirs, options.classes_dir) if options.stamp and", "# Issues in class files don't have a line number.", "file.') parser.add_option('--processed-config-path', help='Path to processed lint suppressions file.') parser.add_option('--manifest-path', help='Path", "sys.stderr for issue in issues: issue_id = issue.attributes['id'].value severity =", "import os import sys from xml.dom import minidom from util", "f.write(content) def _ProcessResultFile(): with open(result_path, 'rb') as f: content =", "'android', 'lint', 'suppress.py')), _RelativizePath(result_path))) print >> sys.stderr, msg # Lint", "'--classpath', _RelativizePath(classes_dir), '--xml', _RelativizePath(result_path), ] for src in src_dirs: cmd.extend(['--sources',", "['errorLine1', 'errorLine2']: error_line = issue.getAttribute(attr) if error_line: print >> sys.stderr,", "lint usage if not os.path.exists(result_path): raise # There are actual", "can be # found in the LICENSE file. \"\"\"Runs Android's", "' - For full explanation refer to %s\\n' ' -", "of just touching stamp.') options, _ = parser.parse_args() build_utils.CheckOptions( options,", "issues: issue_id = issue.attributes['id'].value severity = issue.attributes['severity'].value message = issue.attributes['message'].value", "= issue.getAttribute(attr) if error_line: print >> sys.stderr, error_line return len(issues)", "os import sys from xml.dom import minidom from util import", "def _ProcessResultFile(): with open(result_path, 'rb') as f: content = f.read().replace(", "os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) def _RunLint(lint_path, config_path, processed_config_path, manifest_path, result_path,", "print >> sys.stderr, msg # Lint errors do not fail", "src_dirs = build_utils.ParseGypList(options.src_dirs) rc = 0 if options.enable: rc =", "options.enable: rc = _RunLint(options.lint_path, options.config_path, options.processed_config_path, options.manifest_path, options.result_path, options.product_dir, src_dirs,", "not rc: build_utils.Touch(options.stamp) return rc if __name__ == '__main__': sys.exit(main())", "'rb') as f: content = f.read().replace( 'PRODUCT_DIR', _RelativizePath(product_dir)) with open(processed_config_path,", "0 return 0 def main(): parser = optparse.OptionParser() parser.add_option('--lint-path', help='Path", "usage if not os.path.exists(result_path): raise # There are actual lint", "options.result_path, options.product_dir, src_dirs, options.classes_dir) if options.stamp and not rc: build_utils.Touch(options.stamp)", "message, issue_id) print >> sys.stderr, error for attr in ['errorLine1',", "_RelativizePath(config_path), _RelativizePath(os.path.join(_SRC_ROOT, 'build', 'android', 'lint', 'suppress.py')), _RelativizePath(result_path))) print >> sys.stderr,", "parser.add_option('--manifest-path', help='Path to AndroidManifest.xml') parser.add_option('--result-path', help='Path to XML lint result", "class files don't have a line number. error = '%s", "There is a problem with lint usage if not os.path.exists(result_path):", "os.pardir))) if os.path.exists(result_path): os.remove(result_path) try: build_utils.CheckOutput(cmd, cwd=_SRC_ROOT) except build_utils.CalledProcessError: #", "'processed_config_path', 'manifest_path', 'result_path', 'product_dir', 'src_dirs', 'classes_dir']) src_dirs = build_utils.ParseGypList(options.src_dirs) rc", "in src_dirs: cmd.extend(['--sources', _RelativizePath(src)]) cmd.append(_RelativizePath(os.path.join(manifest_path, os.pardir))) if os.path.exists(result_path): os.remove(result_path) try:", "_ProcessResultFile() msg = ('\\nLint found %d new issues.\\n' ' -", "tool.\"\"\" import optparse import os import sys from xml.dom import", "minidom from util import build_utils _SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..',", "instead of just touching stamp.') options, _ = parser.parse_args() build_utils.CheckOptions(", "num_issues = _ParseAndShowResultFile() _ProcessResultFile() msg = ('\\nLint found %d new", "\"\"\"Runs Android's lint tool.\"\"\" import optparse import os import sys", "actual lint issues else: num_issues = _ParseAndShowResultFile() _ProcessResultFile() msg =", "attr in ['errorLine1', 'errorLine2']: error_line = issue.getAttribute(attr) if error_line: print", "this source code is governed by a BSD-style license that", "import optparse import os import sys from xml.dom import minidom", "%d new issues.\\n' ' - For full explanation refer to", "cmd.extend(['--sources', _RelativizePath(src)]) cmd.append(_RelativizePath(os.path.join(manifest_path, os.pardir))) if os.path.exists(result_path): os.remove(result_path) try: build_utils.CheckOutput(cmd, cwd=_SRC_ROOT)", "Android's lint tool.\"\"\" import optparse import os import sys from", "There are actual lint issues else: num_issues = _ParseAndShowResultFile() _ProcessResultFile()", "Copyright (c) 2013 The Chromium Authors. All rights reserved. #", "\"\"\" return os.path.relpath(os.path.abspath(path), _SRC_ROOT) def _ProcessConfigFile(): if not build_utils.IsTimeStale(processed_config_path, [config_path]):", "result_path, product_dir, src_dirs, classes_dir): def _RelativizePath(path): \"\"\"Returns relative path to", "a problem with lint usage if not os.path.exists(result_path): raise #", "to lint executable.') parser.add_option('--config-path', help='Path to lint suppressions file.') parser.add_option('--processed-config-path',", "error_line = issue.getAttribute(attr) if error_line: print >> sys.stderr, error_line return", "else: # Issues in class files don't have a line", "import build_utils _SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) def _RunLint(lint_path,", "source code is governed by a BSD-style license that can", "path to top-level src dir. Args: path: A path relative", "Authors. All rights reserved. # Use of this source code", "to cwd. \"\"\" return os.path.relpath(os.path.abspath(path), _SRC_ROOT) def _ProcessConfigFile(): if not", "'PRODUCT_DIR') with open(result_path, 'wb') as f: f.write(content) def _ParseAndShowResultFile(): dom", "help='Path to processed lint suppressions file.') parser.add_option('--manifest-path', help='Path to AndroidManifest.xml')", "_RelativizePath(result_path), ] for src in src_dirs: cmd.extend(['--sources', _RelativizePath(src)]) cmd.append(_RelativizePath(os.path.join(manifest_path, os.pardir)))", "to AndroidManifest.xml') parser.add_option('--result-path', help='Path to XML lint result file.') parser.add_option('--product-dir',", "'wb') as f: f.write(content) def _ProcessResultFile(): with open(result_path, 'rb') as", "def _RelativizePath(path): \"\"\"Returns relative path to top-level src dir. Args:", "path relative to cwd. \"\"\" return os.path.relpath(os.path.abspath(path), _SRC_ROOT) def _ProcessConfigFile():", "severity = issue.attributes['severity'].value message = issue.attributes['message'].value location_elem = issue.getElementsByTagName('location')[0] path", "java files.') parser.add_option('--classes-dir', help='Directory containing class files.') parser.add_option('--stamp', help='Path to", "to top-level src dir. Args: path: A path relative to", "errors do not fail the build. return 0 return 0", "just touching stamp.') options, _ = parser.parse_args() build_utils.CheckOptions( options, parser,", "= minidom.parse(result_path) issues = dom.getElementsByTagName('issue') print >> sys.stderr for issue", "lint issues else: num_issues = _ParseAndShowResultFile() _ProcessResultFile() msg = ('\\nLint", "dir.') parser.add_option('--src-dirs', help='Directories containing java files.') parser.add_option('--classes-dir', help='Directory containing class", "parser.add_option('--stamp', help='Path to touch on success.') parser.add_option('--enable', action='store_true', help='Run lint", "relative path to top-level src dir. Args: path: A path", "build_utils _SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) def _RunLint(lint_path, config_path,", "if line: error = '%s:%s %s: %s [%s]' % (path,", "issue.getElementsByTagName('location')[0] path = location_elem.attributes['file'].value line = location_elem.getAttribute('line') if line: error", "python # # Copyright (c) 2013 The Chromium Authors. All", "are actual lint issues else: num_issues = _ParseAndShowResultFile() _ProcessResultFile() msg", "issues?\\n' ' 1. Read comment in %s\\n' ' 2. Run", "options.classes_dir) if options.stamp and not rc: build_utils.Touch(options.stamp) return rc if", "refer to %s\\n' ' - Wanna suppress these issues?\\n' '", "of this source code is governed by a BSD-style license", "if error_line: print >> sys.stderr, error_line return len(issues) _ProcessConfigFile() cmd", "action='store_true', help='Run lint instead of just touching stamp.') options, _", "def _ParseAndShowResultFile(): dom = minidom.parse(result_path) issues = dom.getElementsByTagName('issue') print >>", "f.read().replace( _RelativizePath(product_dir), 'PRODUCT_DIR') with open(result_path, 'wb') as f: f.write(content) def", "\"\"\"Returns relative path to top-level src dir. Args: path: A", "src_dirs: cmd.extend(['--sources', _RelativizePath(src)]) cmd.append(_RelativizePath(os.path.join(manifest_path, os.pardir))) if os.path.exists(result_path): os.remove(result_path) try: build_utils.CheckOutput(cmd,", "reserved. # Use of this source code is governed by", "help='Run lint instead of just touching stamp.') options, _ =", "1. Read comment in %s\\n' ' 2. Run \"python %s", "[config_path]): return with open(config_path, 'rb') as f: content = f.read().replace(", "2. Run \"python %s %s\"\\n' % (num_issues, _RelativizePath(result_path), _RelativizePath(config_path), _RelativizePath(os.path.join(_SRC_ROOT,", "touching stamp.') options, _ = parser.parse_args() build_utils.CheckOptions( options, parser, required=['lint_path',", "stamp.') options, _ = parser.parse_args() build_utils.CheckOptions( options, parser, required=['lint_path', 'config_path',", "_ProcessResultFile(): with open(result_path, 'rb') as f: content = f.read().replace( _RelativizePath(product_dir),", "A path relative to cwd. \"\"\" return os.path.relpath(os.path.abspath(path), _SRC_ROOT) def", "severity, message, issue_id) else: # Issues in class files don't", "parser, required=['lint_path', 'config_path', 'processed_config_path', 'manifest_path', 'result_path', 'product_dir', 'src_dirs', 'classes_dir']) src_dirs", "with open(processed_config_path, 'wb') as f: f.write(content) def _ProcessResultFile(): with open(result_path,", "manifest_path, result_path, product_dir, src_dirs, classes_dir): def _RelativizePath(path): \"\"\"Returns relative path", "help='Path to lint executable.') parser.add_option('--config-path', help='Path to lint suppressions file.')", "('\\nLint found %d new issues.\\n' ' - For full explanation", "# There is a problem with lint usage if not", "'src_dirs', 'classes_dir']) src_dirs = build_utils.ParseGypList(options.src_dirs) rc = 0 if options.enable:", "# Copyright (c) 2013 The Chromium Authors. All rights reserved.", "rc = 0 if options.enable: rc = _RunLint(options.lint_path, options.config_path, options.processed_config_path,", "error = '%s %s: %s [%s]' % (path, severity, message,", "def _ProcessConfigFile(): if not build_utils.IsTimeStale(processed_config_path, [config_path]): return with open(config_path, 'rb')", "touch on success.') parser.add_option('--enable', action='store_true', help='Run lint instead of just", "util import build_utils _SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) def", "for src in src_dirs: cmd.extend(['--sources', _RelativizePath(src)]) cmd.append(_RelativizePath(os.path.join(manifest_path, os.pardir))) if os.path.exists(result_path):", "_ = parser.parse_args() build_utils.CheckOptions( options, parser, required=['lint_path', 'config_path', 'processed_config_path', 'manifest_path',", "sys.stderr, error for attr in ['errorLine1', 'errorLine2']: error_line = issue.getAttribute(attr)", "parser.add_option('--lint-path', help='Path to lint executable.') parser.add_option('--config-path', help='Path to lint suppressions", "f: f.write(content) def _ParseAndShowResultFile(): dom = minidom.parse(result_path) issues = dom.getElementsByTagName('issue')", "_RelativizePath(result_path), _RelativizePath(config_path), _RelativizePath(os.path.join(_SRC_ROOT, 'build', 'android', 'lint', 'suppress.py')), _RelativizePath(result_path))) print >>", "_RunLint(options.lint_path, options.config_path, options.processed_config_path, options.manifest_path, options.result_path, options.product_dir, src_dirs, options.classes_dir) if options.stamp", "line number. error = '%s %s: %s [%s]' % (path,", "fail the build. return 0 return 0 def main(): parser", "os.path.exists(result_path): os.remove(result_path) try: build_utils.CheckOutput(cmd, cwd=_SRC_ROOT) except build_utils.CalledProcessError: # There is", "% (path, severity, message, issue_id) print >> sys.stderr, error for", "issue.attributes['id'].value severity = issue.attributes['severity'].value message = issue.attributes['message'].value location_elem = issue.getElementsByTagName('location')[0]", "= issue.attributes['id'].value severity = issue.attributes['severity'].value message = issue.attributes['message'].value location_elem =", "error_line: print >> sys.stderr, error_line return len(issues) _ProcessConfigFile() cmd =", "= _RunLint(options.lint_path, options.config_path, options.processed_config_path, options.manifest_path, options.result_path, options.product_dir, src_dirs, options.classes_dir) if", "%s %s\"\\n' % (num_issues, _RelativizePath(result_path), _RelativizePath(config_path), _RelativizePath(os.path.join(_SRC_ROOT, 'build', 'android', 'lint',", "_RelativizePath(product_dir)) with open(processed_config_path, 'wb') as f: f.write(content) def _ProcessResultFile(): with", "suppressions file.') parser.add_option('--processed-config-path', help='Path to processed lint suppressions file.') parser.add_option('--manifest-path',", "be # found in the LICENSE file. \"\"\"Runs Android's lint", "success.') parser.add_option('--enable', action='store_true', help='Run lint instead of just touching stamp.')", "%s: %s [%s]' % (path, line, severity, message, issue_id) else:", "issues = dom.getElementsByTagName('issue') print >> sys.stderr for issue in issues:", "to XML lint result file.') parser.add_option('--product-dir', help='Path to product dir.')", "don't have a line number. error = '%s %s: %s", "'config_path', 'processed_config_path', 'manifest_path', 'result_path', 'product_dir', 'src_dirs', 'classes_dir']) src_dirs = build_utils.ParseGypList(options.src_dirs)", "parser.add_option('--src-dirs', help='Directories containing java files.') parser.add_option('--classes-dir', help='Directory containing class files.')", "src_dirs, options.classes_dir) if options.stamp and not rc: build_utils.Touch(options.stamp) return rc", "lint instead of just touching stamp.') options, _ = parser.parse_args()", "'classes_dir']) src_dirs = build_utils.ParseGypList(options.src_dirs) rc = 0 if options.enable: rc", "%s [%s]' % (path, line, severity, message, issue_id) else: #", "_RelativizePath(classes_dir), '--xml', _RelativizePath(result_path), ] for src in src_dirs: cmd.extend(['--sources', _RelativizePath(src)])", "suppress these issues?\\n' ' 1. Read comment in %s\\n' '", "'--config', _RelativizePath(processed_config_path), '--classpath', _RelativizePath(classes_dir), '--xml', _RelativizePath(result_path), ] for src in", "(num_issues, _RelativizePath(result_path), _RelativizePath(config_path), _RelativizePath(os.path.join(_SRC_ROOT, 'build', 'android', 'lint', 'suppress.py')), _RelativizePath(result_path))) print", "os.remove(result_path) try: build_utils.CheckOutput(cmd, cwd=_SRC_ROOT) except build_utils.CalledProcessError: # There is a", "to product dir.') parser.add_option('--src-dirs', help='Directories containing java files.') parser.add_option('--classes-dir', help='Directory", "build_utils.CheckOutput(cmd, cwd=_SRC_ROOT) except build_utils.CalledProcessError: # There is a problem with", "in the LICENSE file. \"\"\"Runs Android's lint tool.\"\"\" import optparse", "options.processed_config_path, options.manifest_path, options.result_path, options.product_dir, src_dirs, options.classes_dir) if options.stamp and not", "'--exitcode', '--showall', '--config', _RelativizePath(processed_config_path), '--classpath', _RelativizePath(classes_dir), '--xml', _RelativizePath(result_path), ] for", "'manifest_path', 'result_path', 'product_dir', 'src_dirs', 'classes_dir']) src_dirs = build_utils.ParseGypList(options.src_dirs) rc =", "options, parser, required=['lint_path', 'config_path', 'processed_config_path', 'manifest_path', 'result_path', 'product_dir', 'src_dirs', 'classes_dir'])", "found %d new issues.\\n' ' - For full explanation refer", "Read comment in %s\\n' ' 2. Run \"python %s %s\"\\n'", "xml.dom import minidom from util import build_utils _SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__),", "help='Path to product dir.') parser.add_option('--src-dirs', help='Directories containing java files.') parser.add_option('--classes-dir',", "files don't have a line number. error = '%s %s:", "the build. return 0 return 0 def main(): parser =", "parser.add_option('--classes-dir', help='Directory containing class files.') parser.add_option('--stamp', help='Path to touch on", "open(config_path, 'rb') as f: content = f.read().replace( 'PRODUCT_DIR', _RelativizePath(product_dir)) with", "'rb') as f: content = f.read().replace( _RelativizePath(product_dir), 'PRODUCT_DIR') with open(result_path,", "issue.getAttribute(attr) if error_line: print >> sys.stderr, error_line return len(issues) _ProcessConfigFile()", "build. return 0 return 0 def main(): parser = optparse.OptionParser()", "_ParseAndShowResultFile(): dom = minidom.parse(result_path) issues = dom.getElementsByTagName('issue') print >> sys.stderr", "def main(): parser = optparse.OptionParser() parser.add_option('--lint-path', help='Path to lint executable.')", "parser = optparse.OptionParser() parser.add_option('--lint-path', help='Path to lint executable.') parser.add_option('--config-path', help='Path", "if not os.path.exists(result_path): raise # There are actual lint issues", "with open(result_path, 'rb') as f: content = f.read().replace( _RelativizePath(product_dir), 'PRODUCT_DIR')", "= f.read().replace( 'PRODUCT_DIR', _RelativizePath(product_dir)) with open(processed_config_path, 'wb') as f: f.write(content)", "cwd. \"\"\" return os.path.relpath(os.path.abspath(path), _SRC_ROOT) def _ProcessConfigFile(): if not build_utils.IsTimeStale(processed_config_path,", "main(): parser = optparse.OptionParser() parser.add_option('--lint-path', help='Path to lint executable.') parser.add_option('--config-path',", "<gh_stars>1-10 #!/usr/bin/env python # # Copyright (c) 2013 The Chromium", "dir. Args: path: A path relative to cwd. \"\"\" return", "message, issue_id) else: # Issues in class files don't have", "parser.add_option('--product-dir', help='Path to product dir.') parser.add_option('--src-dirs', help='Directories containing java files.')", "dom = minidom.parse(result_path) issues = dom.getElementsByTagName('issue') print >> sys.stderr for", "= [ lint_path, '-Werror', '--exitcode', '--showall', '--config', _RelativizePath(processed_config_path), '--classpath', _RelativizePath(classes_dir),", "if options.enable: rc = _RunLint(options.lint_path, options.config_path, options.processed_config_path, options.manifest_path, options.result_path, options.product_dir,", "#!/usr/bin/env python # # Copyright (c) 2013 The Chromium Authors.", "_RelativizePath(result_path))) print >> sys.stderr, msg # Lint errors do not", "class files.') parser.add_option('--stamp', help='Path to touch on success.') parser.add_option('--enable', action='store_true',", "files.') parser.add_option('--stamp', help='Path to touch on success.') parser.add_option('--enable', action='store_true', help='Run", "that can be # found in the LICENSE file. \"\"\"Runs", "if os.path.exists(result_path): os.remove(result_path) try: build_utils.CheckOutput(cmd, cwd=_SRC_ROOT) except build_utils.CalledProcessError: # There", "' - Wanna suppress these issues?\\n' ' 1. Read comment", "to touch on success.') parser.add_option('--enable', action='store_true', help='Run lint instead of", "by a BSD-style license that can be # found in", "_RelativizePath(product_dir), 'PRODUCT_DIR') with open(result_path, 'wb') as f: f.write(content) def _ParseAndShowResultFile():", "file.') parser.add_option('--product-dir', help='Path to product dir.') parser.add_option('--src-dirs', help='Directories containing java", "= os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) def _RunLint(lint_path, config_path, processed_config_path, manifest_path,", "src_dirs, classes_dir): def _RelativizePath(path): \"\"\"Returns relative path to top-level src", "the LICENSE file. \"\"\"Runs Android's lint tool.\"\"\" import optparse import", "0 def main(): parser = optparse.OptionParser() parser.add_option('--lint-path', help='Path to lint", "issue_id = issue.attributes['id'].value severity = issue.attributes['severity'].value message = issue.attributes['message'].value location_elem", "containing java files.') parser.add_option('--classes-dir', help='Directory containing class files.') parser.add_option('--stamp', help='Path", "The Chromium Authors. All rights reserved. # Use of this", "# found in the LICENSE file. \"\"\"Runs Android's lint tool.\"\"\"", "path: A path relative to cwd. \"\"\" return os.path.relpath(os.path.abspath(path), _SRC_ROOT)", "as f: f.write(content) def _ProcessResultFile(): with open(result_path, 'rb') as f:", "lint executable.') parser.add_option('--config-path', help='Path to lint suppressions file.') parser.add_option('--processed-config-path', help='Path", "message = issue.attributes['message'].value location_elem = issue.getElementsByTagName('location')[0] path = location_elem.attributes['file'].value line", "'--xml', _RelativizePath(result_path), ] for src in src_dirs: cmd.extend(['--sources', _RelativizePath(src)]) cmd.append(_RelativizePath(os.path.join(manifest_path,", "# # Copyright (c) 2013 The Chromium Authors. All rights", "issue_id) print >> sys.stderr, error for attr in ['errorLine1', 'errorLine2']:", "error_line return len(issues) _ProcessConfigFile() cmd = [ lint_path, '-Werror', '--exitcode',", "_RelativizePath(processed_config_path), '--classpath', _RelativizePath(classes_dir), '--xml', _RelativizePath(result_path), ] for src in src_dirs:", "location_elem = issue.getElementsByTagName('location')[0] path = location_elem.attributes['file'].value line = location_elem.getAttribute('line') if", "%s [%s]' % (path, severity, message, issue_id) print >> sys.stderr,", "= issue.attributes['message'].value location_elem = issue.getElementsByTagName('location')[0] path = location_elem.attributes['file'].value line =", "found in the LICENSE file. \"\"\"Runs Android's lint tool.\"\"\" import", "classes_dir): def _RelativizePath(path): \"\"\"Returns relative path to top-level src dir.", "f: content = f.read().replace( 'PRODUCT_DIR', _RelativizePath(product_dir)) with open(processed_config_path, 'wb') as", "_RelativizePath(os.path.join(_SRC_ROOT, 'build', 'android', 'lint', 'suppress.py')), _RelativizePath(result_path))) print >> sys.stderr, msg", "minidom.parse(result_path) issues = dom.getElementsByTagName('issue') print >> sys.stderr for issue in", "' 2. Run \"python %s %s\"\\n' % (num_issues, _RelativizePath(result_path), _RelativizePath(config_path),", "(c) 2013 The Chromium Authors. All rights reserved. # Use", "in issues: issue_id = issue.attributes['id'].value severity = issue.attributes['severity'].value message =", "number. error = '%s %s: %s [%s]' % (path, severity,", "src in src_dirs: cmd.extend(['--sources', _RelativizePath(src)]) cmd.append(_RelativizePath(os.path.join(manifest_path, os.pardir))) if os.path.exists(result_path): os.remove(result_path)", "%s\"\\n' % (num_issues, _RelativizePath(result_path), _RelativizePath(config_path), _RelativizePath(os.path.join(_SRC_ROOT, 'build', 'android', 'lint', 'suppress.py')),", "All rights reserved. # Use of this source code is", "not fail the build. return 0 return 0 def main():", "help='Directory containing class files.') parser.add_option('--stamp', help='Path to touch on success.')", "rc = _RunLint(options.lint_path, options.config_path, options.processed_config_path, options.manifest_path, options.result_path, options.product_dir, src_dirs, options.classes_dir)", "\"python %s %s\"\\n' % (num_issues, _RelativizePath(result_path), _RelativizePath(config_path), _RelativizePath(os.path.join(_SRC_ROOT, 'build', 'android',", "comment in %s\\n' ' 2. Run \"python %s %s\"\\n' %", "executable.') parser.add_option('--config-path', help='Path to lint suppressions file.') parser.add_option('--processed-config-path', help='Path to", "lint tool.\"\"\" import optparse import os import sys from xml.dom", "cmd = [ lint_path, '-Werror', '--exitcode', '--showall', '--config', _RelativizePath(processed_config_path), '--classpath',", "processed lint suppressions file.') parser.add_option('--manifest-path', help='Path to AndroidManifest.xml') parser.add_option('--result-path', help='Path", "options, _ = parser.parse_args() build_utils.CheckOptions( options, parser, required=['lint_path', 'config_path', 'processed_config_path',", "open(result_path, 'rb') as f: content = f.read().replace( _RelativizePath(product_dir), 'PRODUCT_DIR') with", "return with open(config_path, 'rb') as f: content = f.read().replace( 'PRODUCT_DIR',", "as f: f.write(content) def _ParseAndShowResultFile(): dom = minidom.parse(result_path) issues =", "content = f.read().replace( 'PRODUCT_DIR', _RelativizePath(product_dir)) with open(processed_config_path, 'wb') as f:", "new issues.\\n' ' - For full explanation refer to %s\\n'", "issue.attributes['message'].value location_elem = issue.getElementsByTagName('location')[0] path = location_elem.attributes['file'].value line = location_elem.getAttribute('line')", "these issues?\\n' ' 1. Read comment in %s\\n' ' 2.", "f.read().replace( 'PRODUCT_DIR', _RelativizePath(product_dir)) with open(processed_config_path, 'wb') as f: f.write(content) def", "'lint', 'suppress.py')), _RelativizePath(result_path))) print >> sys.stderr, msg # Lint errors", "help='Path to AndroidManifest.xml') parser.add_option('--result-path', help='Path to XML lint result file.')", "with open(result_path, 'wb') as f: f.write(content) def _ParseAndShowResultFile(): dom =", "containing class files.') parser.add_option('--stamp', help='Path to touch on success.') parser.add_option('--enable',", "src dir. Args: path: A path relative to cwd. \"\"\"", "file.') parser.add_option('--manifest-path', help='Path to AndroidManifest.xml') parser.add_option('--result-path', help='Path to XML lint", "return 0 return 0 def main(): parser = optparse.OptionParser() parser.add_option('--lint-path',", "AndroidManifest.xml') parser.add_option('--result-path', help='Path to XML lint result file.') parser.add_option('--product-dir', help='Path", "if not build_utils.IsTimeStale(processed_config_path, [config_path]): return with open(config_path, 'rb') as f:", "' 1. Read comment in %s\\n' ' 2. Run \"python", "'result_path', 'product_dir', 'src_dirs', 'classes_dir']) src_dirs = build_utils.ParseGypList(options.src_dirs) rc = 0", "= _ParseAndShowResultFile() _ProcessResultFile() msg = ('\\nLint found %d new issues.\\n'", "lint_path, '-Werror', '--exitcode', '--showall', '--config', _RelativizePath(processed_config_path), '--classpath', _RelativizePath(classes_dir), '--xml', _RelativizePath(result_path),", "] for src in src_dirs: cmd.extend(['--sources', _RelativizePath(src)]) cmd.append(_RelativizePath(os.path.join(manifest_path, os.pardir))) if", "Chromium Authors. All rights reserved. # Use of this source", "= f.read().replace( _RelativizePath(product_dir), 'PRODUCT_DIR') with open(result_path, 'wb') as f: f.write(content)", "to processed lint suppressions file.') parser.add_option('--manifest-path', help='Path to AndroidManifest.xml') parser.add_option('--result-path',", "parser.add_option('--result-path', help='Path to XML lint result file.') parser.add_option('--product-dir', help='Path to", "suppressions file.') parser.add_option('--manifest-path', help='Path to AndroidManifest.xml') parser.add_option('--result-path', help='Path to XML", "explanation refer to %s\\n' ' - Wanna suppress these issues?\\n'", "problem with lint usage if not os.path.exists(result_path): raise # There", "help='Path to XML lint result file.') parser.add_option('--product-dir', help='Path to product", "msg = ('\\nLint found %d new issues.\\n' ' - For", "'..', '..')) def _RunLint(lint_path, config_path, processed_config_path, manifest_path, result_path, product_dir, src_dirs,", "'errorLine2']: error_line = issue.getAttribute(attr) if error_line: print >> sys.stderr, error_line", "top-level src dir. Args: path: A path relative to cwd.", "product_dir, src_dirs, classes_dir): def _RelativizePath(path): \"\"\"Returns relative path to top-level", "Issues in class files don't have a line number. error", "2013 The Chromium Authors. All rights reserved. # Use of", "= '%s:%s %s: %s [%s]' % (path, line, severity, message,", "options.manifest_path, options.result_path, options.product_dir, src_dirs, options.classes_dir) if options.stamp and not rc:", "- Wanna suppress these issues?\\n' ' 1. Read comment in", "[ lint_path, '-Werror', '--exitcode', '--showall', '--config', _RelativizePath(processed_config_path), '--classpath', _RelativizePath(classes_dir), '--xml',", "line, severity, message, issue_id) else: # Issues in class files", "to lint suppressions file.') parser.add_option('--processed-config-path', help='Path to processed lint suppressions", "open(result_path, 'wb') as f: f.write(content) def _ParseAndShowResultFile(): dom = minidom.parse(result_path)", "lint suppressions file.') parser.add_option('--manifest-path', help='Path to AndroidManifest.xml') parser.add_option('--result-path', help='Path to", ">> sys.stderr for issue in issues: issue_id = issue.attributes['id'].value severity", "print >> sys.stderr, error for attr in ['errorLine1', 'errorLine2']: error_line", "severity, message, issue_id) print >> sys.stderr, error for attr in", "from util import build_utils _SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))", "Lint errors do not fail the build. return 0 return", "with lint usage if not os.path.exists(result_path): raise # There are", "= parser.parse_args() build_utils.CheckOptions( options, parser, required=['lint_path', 'config_path', 'processed_config_path', 'manifest_path', 'result_path',", "'%s %s: %s [%s]' % (path, severity, message, issue_id) print", "Args: path: A path relative to cwd. \"\"\" return os.path.relpath(os.path.abspath(path),", ">> sys.stderr, msg # Lint errors do not fail the", "print >> sys.stderr for issue in issues: issue_id = issue.attributes['id'].value", "%s\\n' ' - Wanna suppress these issues?\\n' ' 1. Read", "relative to cwd. \"\"\" return os.path.relpath(os.path.abspath(path), _SRC_ROOT) def _ProcessConfigFile(): if", "full explanation refer to %s\\n' ' - Wanna suppress these", "_ParseAndShowResultFile() _ProcessResultFile() msg = ('\\nLint found %d new issues.\\n' '" ]
[ "for decl in self._ast.decls: includes.add(decl.cpp_file) if decl.decltype == ast_pb2.Decl.Type.CONST: self._generate_const_variables_headers(decl.const,", "{decl.class_.name.cpp_name}::{decl.class_.name.native};') for member in virtual_members: yield from self._generate_virtual_function( decl.class_.name.native, member.func)", "decl.decltype == ast_pb2.Decl.Type.ENUM: yield from enums.generate_from('m', decl.enum) yield '' yield", "{p.name.cpp_name}') params_str_with_types = ', '.join(params_list_with_types) cpp_const = '' if func_decl.cpp_const_method:", "Text], decl: ast_pb2.Decl, trampoline_name_suffix: str = '_trampoline', self_life_support: str =", "import Dict, Generator, List, Text, Set from clif.protos import ast_pb2", "None]: \"\"\"Generates pybind11 bindings code from CLIF ast.\"\"\" includes =", "2.0 (the \"License\"); # you may not use this file", "yield 'namespace py = pybind11;' yield '' def _generate_const_variables_headers(self, const_decl:", "_generate_const_variables(self, const_decl: ast_pb2.ConstDecl): \"\"\"Generates variables.\"\"\" lang_type = const_decl.type.lang_type if (lang_type", "const_decl: ast_pb2.ConstDecl): \"\"\"Generates variables.\"\"\" lang_type = const_decl.type.lang_type if (lang_type in", "s in function.generate_from('m', decl.func, None): yield I + s elif", "in ast.decls: if decl.decltype == ast_pb2.Decl.Type.FUNC: for s in function.generate_from('m',", "headers.\"\"\" includes = set() for decl in self._ast.decls: includes.add(decl.cpp_file) if", "to a set. Only to be used in this context.\"\"\"", "override {{') if func_decl.is_pure_virtual: pybind11_override = 'PYBIND11_OVERRIDE_PURE' else: pybind11_override =", "ast_pb2.Decl.Type.FUNC: for s in function.generate_from('m', decl.func, None): yield I +", "function.generate_from('m', decl.func, None): yield I + s elif decl.decltype ==", "self._include_paths = include_paths self._unique_classes = {} def generate_header(self, ast: ast_pb2.AST)", "for p in func_decl.params: params_list_with_types.append( f'{function_lib.generate_param_type(p)} {p.name.cpp_name}') params_str_with_types = ',", "I + I + f'{func_decl.name.native},' yield I + I +", "include in self._ast.usertype_includes: includes.add(include) yield '#include \"third_party/pybind11/include/pybind11/complex.h\"' yield '#include \"third_party/pybind11/include/pybind11/functional.h\"'", "f'py::cast({const_decl.name.cpp_name});') yield const_def def _generate_python_override_class_names( self, python_override_class_names: Dict[Text, Text], decl:", "Only to be used in this context.\"\"\" if decl.decltype ==", "limitations under the License. \"\"\"Generates pybind11 bindings code.\"\"\" from typing", "v.cpp_exact_type params = ', '.join([f'{p.name.cpp_name}' for p in func_decl.params]) params_list_with_types", "in includes: yield f'#include \"{include}\"' yield '\\n' for cpp_name in", "\"\"\"Adds every class name to a set. Only to be", "from self._generate_virtual_function( decl.class_.name.native, member.func) if python_override_class_name: yield '};' def _generate_virtual_function(self,", "'bool', 'str'} or lang_type.startswith('tuple<')): const_def = I + (f'm.attr(\"{const_decl.name.native}\") =", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "const_def = I + (f'm.attr(\"{const_decl.name.native}\") = ' f'py::cast({const_decl.name.cpp_name});') yield const_def", "= '.'.join(names) yield f'py::module_::import(\"{module}\");' def _generate_headlines(self): \"\"\"Generates #includes and headers.\"\"\"", "yield f'PYBIND11_SMART_HOLDER_TYPE_CASTERS({cpp_name})' yield '\\n' for cpp_name, py_name in self._unique_classes.items(): yield", "governing permissions and # limitations under the License. \"\"\"Generates pybind11", "pybind11 bindings code from CLIF ast.\"\"\" def __init__(self, ast: ast_pb2.AST,", "+ I + f'{class_name},' yield I + I + I", "self._collect_class_cpp_names(decl) yield '#include \"third_party/pybind11/include/pybind11/smart_holder.h\"' for include in includes: yield f'#include", "keep track of virtual functions. python_override_class_names = {} for decl", "enums.generate_from('m', decl.enum) yield '' yield '}' def _generate_import_modules(self, ast: ast_pb2.AST)", "trampoline_name_suffix: str = '_trampoline', self_life_support: str = 'py::trampoline_self_life_support'): \"\"\"Generates Python", "_collect_class_cpp_names(self, decl: ast_pb2.Decl, parent_name: str = '') -> None: \"\"\"Adds", "= ' f'{const_decl.name.cpp_name};') else: const_def = I + (f'm.attr(\"{const_decl.name.native}\") =", "member.func.virtual: virtual_members.append(member) if not virtual_members: return python_override_class_name = ( f'{decl.class_.name.native}_{trampoline_name_suffix}')", "ast_pb2.FuncDecl): \"\"\"Generates virtual function overrides calling Python methods.\"\"\" return_type =", "_generate_import_modules(self, ast: ast_pb2.AST) -> Generator[str, None, None]: for include in", "if func_decl.cpp_const_method: cpp_const = ' const' yield I + (f'{return_type}", "{'int', 'float', 'double', 'bool', 'str'} or lang_type.startswith('tuple<')): const_def = I", "= {} def generate_header(self, ast: ast_pb2.AST) -> Generator[str, None, None]:", "use this file except in compliance with the License. #", "const_def = I + (f'm.attr(\"{const_decl.name.native}\") = ' f'{const_decl.name.cpp_name};') else: const_def", "CLIF ast protobuf. Yields: Generated pybind11 bindings code. \"\"\" yield", "params = ', '.join([f'{p.name.cpp_name}' for p in func_decl.params]) params_list_with_types =", "decl.class_.members: self._collect_class_cpp_names(member, full_native_name) def write_to(channel, lines): \"\"\"Writes the generated code", "# Find and keep track of virtual functions. python_override_class_names =", "s elif decl.decltype == ast_pb2.Decl.Type.CONST: yield from self._generate_const_variables(decl.const) elif decl.decltype", "python_override_class_names.get(decl.class_.name.cpp_name, '')) elif decl.decltype == ast_pb2.Decl.Type.ENUM: yield from enums.generate_from('m', decl.enum)", "str = '_trampoline', self_life_support: str = 'py::trampoline_self_life_support'): \"\"\"Generates Python overrides", "self._ast = ast self._module_name = module_name self._header_path = header_path self._include_paths", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "generates pybind11 bindings code from CLIF ast.\"\"\" def __init__(self, ast:", "needed.' yield '#include \"third_party/pybind11/include/pybind11/stl.h\"' yield '' yield '#include \"clif/pybind11/runtime.h\"' yield", "or const_decl.type.lang_type.startswith('dict<') or const_decl.type.lang_type.startswith('set<')): includes.add('third_party/pybind11/include/pybind11/stl.h') def _generate_const_variables(self, const_decl: ast_pb2.ConstDecl): \"\"\"Generates", "I + I + f'{pybind11_override}(' yield I + I +", "'#include \"clif/pybind11/type_casters.h\"' yield '' for include in includes: yield f'#include", "from self._generate_const_variables(decl.const) elif decl.decltype == ast_pb2.Decl.Type.CLASS: yield from classes.generate_from( decl.class_,", "f'PYBIND11_SMART_HOLDER_TYPE_CASTERS({cpp_name})' yield '\\n' for cpp_name, py_name in self._unique_classes.items(): yield f'//", "'#include \"third_party/pybind11/include/pybind11/stl.h\"' yield '' yield '#include \"clif/pybind11/runtime.h\"' yield '#include \"clif/pybind11/type_casters.h\"'", "License. # You may obtain a copy of the License", "if decl.decltype == ast_pb2.Decl.Type.CLASS: virtual_members = [] for member in", "'PYBIND11_OVERRIDE' yield I + I + f'{pybind11_override}(' yield I +", "if decl.decltype == ast_pb2.Decl.Type.FUNC: for s in function.generate_from('m', decl.func, None):", "names.insert(0, 'google3') names[-1] = names[-1][:-len('_clif.h')] module = '.'.join(names) yield f'py::module_::import(\"{module}\");'", "f'{return_type},' yield I + I + I + f'{class_name},' yield", "decl in ast.decls: if decl.decltype == ast_pb2.Decl.Type.FUNC: for s in", "I + I + I + f'{func_decl.name.native},' yield I +", "'.join([f'{p.name.cpp_name}' for p in func_decl.params]) params_list_with_types = [] for p", "under the License is distributed on an \"AS IS\" BASIS,", "calling Python methods.\"\"\" return_type = '' if func_decl.cpp_void_return: return_type =", "License for the specific language governing permissions and # limitations", "f'PYBIND11_MODULE({self._module_name}, m) {{' yield from self._generate_import_modules(ast) yield I+('m.doc() = \"CLIF-generated", "= include.split('/') names.insert(0, 'google3') names[-1] = names[-1][:-len('_clif.h')] module = '.'.join(names)", "for include in includes: yield f'#include \"{include}\"' yield f'#include \"{self._header_path}\"'", "( f'{decl.class_.name.native}_{trampoline_name_suffix}') assert decl.class_.name.cpp_name not in python_override_class_names python_override_class_names[ decl.class_.name.cpp_name] =", "'void' elif func_decl.returns: for v in func_decl.returns: if v.HasField('cpp_exact_type'): return_type", "return_type = 'void' elif func_decl.returns: for v in func_decl.returns: if", "'') -> None: \"\"\"Adds every class name to a set.", "ast_pb2.Decl.Type.CLASS: yield from classes.generate_from( decl.class_, 'm', python_override_class_names.get(decl.class_.name.cpp_name, '')) elif decl.decltype", "'// potential future optimization: generate this line only as needed.'", "cpp_name in self._unique_classes: yield f'PYBIND11_SMART_HOLDER_TYPE_CASTERS({cpp_name})' yield '\\n' for cpp_name, py_name", "self, python_override_class_names: Dict[Text, Text], decl: ast_pb2.Decl, trampoline_name_suffix: str = '_trampoline',", "ast_pb2.Decl.Type.FUNC and member.func.virtual: virtual_members.append(member) if not virtual_members: return python_override_class_name =", "python_override_class_names python_override_class_names[ decl.class_.name.cpp_name] = python_override_class_name yield (f'struct {python_override_class_name} : '", "' f'{ast.source}\";') yield I + 'py::google::ImportStatusModule();' for decl in ast.decls:", "= [] for member in decl.class_.members: if member.decltype == ast_pb2.Decl.Type.FUNC", "if member.decltype == ast_pb2.Decl.Type.FUNC and member.func.virtual: virtual_members.append(member) if not virtual_members:", "f'{func_decl.name.native}({params_str_with_types}) ' f'{cpp_const} override {{') if func_decl.is_pure_virtual: pybind11_override = 'PYBIND11_OVERRIDE_PURE'", "from self._generate_python_override_class_names( python_override_class_names, decl) self._collect_class_cpp_names(decl) yield from type_casters.generate_from(ast, self._include_paths) yield", "yield from self._generate_headlines() # Find and keep track of virtual", "code from CLIF ast.\"\"\" includes = set() for decl in", "include in includes: yield f'#include \"{include}\"' yield f'#include \"{self._header_path}\"' yield", "' f'{decl.class_.name.cpp_name}, {self_life_support} {{') yield I + ( f'using {decl.class_.name.cpp_name}::{decl.class_.name.native};')", "= 'PYBIND11_OVERRIDE_PURE' else: pybind11_override = 'PYBIND11_OVERRIDE' yield I + I", "import ast_pb2 from clif.pybind11 import classes from clif.pybind11 import enums", "ast self._module_name = module_name self._header_path = header_path self._include_paths = include_paths", "f'#include \"{include}\"' yield f'#include \"{self._header_path}\"' yield '' yield 'namespace py", "func_decl.returns: for v in func_decl.returns: if v.HasField('cpp_exact_type'): return_type = v.cpp_exact_type", "CLIF ast.\"\"\" def __init__(self, ast: ast_pb2.AST, module_name: str, header_path: str,", "def _generate_const_variables(self, const_decl: ast_pb2.ConstDecl): \"\"\"Generates variables.\"\"\" lang_type = const_decl.type.lang_type if", "full_native_name = '.'.join([parent_name, decl.class_.name.native]) self._unique_classes[decl.class_.name.cpp_name] = full_native_name for member in", "in compliance with the License. # You may obtain a", "for member in decl.class_.members: if member.decltype == ast_pb2.Decl.Type.FUNC and member.func.virtual:", "includes.add(decl.cpp_file) if decl.decltype == ast_pb2.Decl.Type.CONST: self._generate_const_variables_headers(decl.const, includes) for include in", "elif func_decl.returns: for v in func_decl.returns: if v.HasField('cpp_exact_type'): return_type =", "software # distributed under the License is distributed on an", "= '.'.join([parent_name, decl.class_.name.native]) self._unique_classes[decl.class_.name.cpp_name] = full_native_name for member in decl.class_.members:", "self._collect_class_cpp_names(decl) yield from type_casters.generate_from(ast, self._include_paths) yield f'PYBIND11_MODULE({self._module_name}, m) {{' yield", "f'{class_name},' yield I + I + I + f'{func_decl.name.native},' yield", "decl in ast.decls: yield from self._generate_python_override_class_names( python_override_class_names, decl) self._collect_class_cpp_names(decl) yield", "\"\"\" yield from self._generate_headlines() # Find and keep track of", "for include in includes: yield f'#include \"{include}\"' yield '\\n' for", "Converts `full/project/path/cheader_pybind11_clif.h` to # `full.project.path.cheader_pybind11` names = include.split('/') names.insert(0, 'google3')", "for virtual functions.\"\"\" if decl.decltype == ast_pb2.Decl.Type.CLASS: virtual_members = []", ": ' f'{decl.class_.name.cpp_name}, {self_life_support} {{') yield I + ( f'using", "= names[-1][:-len('_clif.h')] module = '.'.join(names) yield f'py::module_::import(\"{module}\");' def _generate_headlines(self): \"\"\"Generates", "potential future optimization: generate this line only as needed.' yield", "'.'.join([parent_name, decl.class_.name.native]) self._unique_classes[decl.class_.name.cpp_name] = full_native_name for member in decl.class_.members: self._collect_class_cpp_names(member,", "CLIF ast.\"\"\" includes = set() for decl in ast.decls: includes.add(decl.cpp_file)", "parent_name: full_native_name = '.'.join([parent_name, decl.class_.name.native]) self._unique_classes[decl.class_.name.cpp_name] = full_native_name for member", "type_casters from clif.pybind11 import utils I = utils.I class ModuleGenerator(object):", "{{') yield I + ( f'using {decl.class_.name.cpp_name}::{decl.class_.name.native};') for member in", "bindings code from CLIF ast.\"\"\" def __init__(self, ast: ast_pb2.AST, module_name:", "yield '' for include in includes: yield f'#include \"{include}\"' yield", "Yields: Generated pybind11 bindings code. \"\"\" yield from self._generate_headlines() #", "set() for decl in ast.decls: includes.add(decl.cpp_file) self._collect_class_cpp_names(decl) yield '#include \"third_party/pybind11/include/pybind11/smart_holder.h\"'", "if decl.decltype == ast_pb2.Decl.Type.CONST: self._generate_const_variables_headers(decl.const, includes) for include in self._ast.pybind11_includes:", "'double', 'bool', 'str'} or lang_type.startswith('tuple<')): const_def = I + (f'm.attr(\"{const_decl.name.native}\")", "class that generates pybind11 bindings code from CLIF ast.\"\"\" def", "= 'PYBIND11_OVERRIDE' yield I + I + f'{pybind11_override}(' yield I", "self._unique_classes[decl.class_.name.cpp_name] = full_native_name for member in decl.class_.members: self._collect_class_cpp_names(member, full_native_name) def", "cpp_name, py_name in self._unique_classes.items(): yield f'// CLIF use `{cpp_name}` as", "in func_decl.params: params_list_with_types.append( f'{function_lib.generate_param_type(p)} {p.name.cpp_name}') params_str_with_types = ', '.join(params_list_with_types) cpp_const", "\"\"\"Generates pybind11 bindings code.\"\"\" from typing import Dict, Generator, List,", "def _generate_python_override_class_names( self, python_override_class_names: Dict[Text, Text], decl: ast_pb2.Decl, trampoline_name_suffix: str", "'#include \"third_party/pybind11/include/pybind11/smart_holder.h\"' yield '// potential future optimization: generate this line", "def _generate_virtual_function(self, class_name: str, func_decl: ast_pb2.FuncDecl): \"\"\"Generates virtual function overrides", "for include in self._ast.usertype_includes: includes.add(include) yield '#include \"third_party/pybind11/include/pybind11/complex.h\"' yield '#include", "else: pybind11_override = 'PYBIND11_OVERRIDE' yield I + I + f'{pybind11_override}('", "I + f'{params}' yield I + I + ');' yield", "in this context.\"\"\" if decl.decltype == ast_pb2.Decl.Type.CLASS: full_native_name = decl.class_.name.native", "yield I + I + ');' yield I + '}'", "\"third_party/pybind11/include/pybind11/stl.h\"' yield '' yield '#include \"clif/pybind11/runtime.h\"' yield '#include \"clif/pybind11/type_casters.h\"' yield", "+ I + f'{return_type},' yield I + I + I", "for member in decl.class_.members: self._collect_class_cpp_names(member, full_native_name) def write_to(channel, lines): \"\"\"Writes", "= ', '.join([f'{p.name.cpp_name}' for p in func_decl.params]) params_list_with_types = []", "or const_decl.type.lang_type.startswith('set<')): includes.add('third_party/pybind11/include/pybind11/stl.h') def _generate_const_variables(self, const_decl: ast_pb2.ConstDecl): \"\"\"Generates variables.\"\"\" lang_type", "v in func_decl.returns: if v.HasField('cpp_exact_type'): return_type = v.cpp_exact_type params =", "pybind11-based module for ' f'{ast.source}\";') yield I + 'py::google::ImportStatusModule();' for", "'\\n' for cpp_name, py_name in self._unique_classes.items(): yield f'// CLIF use", "f'{ast.source}\";') yield I + 'py::google::ImportStatusModule();' for decl in ast.decls: if", "m) {{' yield from self._generate_import_modules(ast) yield I+('m.doc() = \"CLIF-generated pybind11-based", "includes: Set[str]): if const_decl.type.lang_type == 'complex': includes.add('third_party/pybind11/include/pybind11/complex.h') if (const_decl.type.lang_type.startswith('list<') or", "func_decl.is_pure_virtual: pybind11_override = 'PYBIND11_OVERRIDE_PURE' else: pybind11_override = 'PYBIND11_OVERRIDE' yield I", "the generated code to files.\"\"\" for s in lines: channel.write(s)", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "if python_override_class_name: yield '};' def _generate_virtual_function(self, class_name: str, func_decl: ast_pb2.FuncDecl):", "py_name in self._unique_classes.items(): yield f'// CLIF use `{cpp_name}` as {py_name}'", "= header_path self._include_paths = include_paths self._unique_classes = {} def generate_header(self,", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "full_native_name = decl.class_.name.native if parent_name: full_native_name = '.'.join([parent_name, decl.class_.name.native]) self._unique_classes[decl.class_.name.cpp_name]", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "includes = set() for decl in ast.decls: includes.add(decl.cpp_file) self._collect_class_cpp_names(decl) yield", "to in writing, software # distributed under the License is", "'}' def _collect_class_cpp_names(self, decl: ast_pb2.Decl, parent_name: str = '') ->", "# See the License for the specific language governing permissions", "'py::google::ImportStatusModule();' for decl in ast.decls: if decl.decltype == ast_pb2.Decl.Type.FUNC: for", "'float', 'double', 'bool', 'str'} or lang_type.startswith('tuple<')): const_def = I +", "type_casters.generate_from(ast, self._include_paths) yield f'PYBIND11_MODULE({self._module_name}, m) {{' yield from self._generate_import_modules(ast) yield", "ast. Args: ast: CLIF ast protobuf. Yields: Generated pybind11 bindings", "elif decl.decltype == ast_pb2.Decl.Type.CLASS: yield from classes.generate_from( decl.class_, 'm', python_override_class_names.get(decl.class_.name.cpp_name,", "'' yield '#include \"clif/pybind11/runtime.h\"' yield '#include \"clif/pybind11/type_casters.h\"' yield '' for", "'' yield 'namespace py = pybind11;' yield '' def _generate_const_variables_headers(self,", "or agreed to in writing, software # distributed under the", "if func_decl.cpp_void_return: return_type = 'void' elif func_decl.returns: for v in", "code.\"\"\" from typing import Dict, Generator, List, Text, Set from", "required by applicable law or agreed to in writing, software", "'.'.join(names) yield f'py::module_::import(\"{module}\");' def _generate_headlines(self): \"\"\"Generates #includes and headers.\"\"\" includes", "header_path: str, include_paths: List[str]): self._ast = ast self._module_name = module_name", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "yield '' yield 'namespace py = pybind11;' yield '' def", "= [] for p in func_decl.params: params_list_with_types.append( f'{function_lib.generate_param_type(p)} {p.name.cpp_name}') params_str_with_types", "`full/project/path/cheader_pybind11_clif.h` to # `full.project.path.cheader_pybind11` names = include.split('/') names.insert(0, 'google3') names[-1]", "yield I+('m.doc() = \"CLIF-generated pybind11-based module for ' f'{ast.source}\";') yield", "with the License. # You may obtain a copy of", "self._ast.usertype_includes: includes.add(include) yield '#include \"third_party/pybind11/include/pybind11/complex.h\"' yield '#include \"third_party/pybind11/include/pybind11/functional.h\"' yield '#include", "\"third_party/pybind11/include/pybind11/complex.h\"' yield '#include \"third_party/pybind11/include/pybind11/functional.h\"' yield '#include \"third_party/pybind11/include/pybind11/operators.h\"' yield '#include \"third_party/pybind11/include/pybind11/smart_holder.h\"'", "License. \"\"\"Generates pybind11 bindings code.\"\"\" from typing import Dict, Generator,", "'namespace py = pybind11;' yield '' def _generate_const_variables_headers(self, const_decl: ast_pb2.ConstDecl,", "ast_pb2.Decl.Type.CONST: yield from self._generate_const_variables(decl.const) elif decl.decltype == ast_pb2.Decl.Type.CLASS: yield from", "self._ast.decls: includes.add(decl.cpp_file) if decl.decltype == ast_pb2.Decl.Type.CONST: self._generate_const_variables_headers(decl.const, includes) for include", "generated code to files.\"\"\" for s in lines: channel.write(s) channel.write('\\n')", "generate_from(self, ast: ast_pb2.AST): \"\"\"Generates pybind11 bindings code from CLIF ast.", "virtual_members.append(member) if not virtual_members: return python_override_class_name = ( f'{decl.class_.name.native}_{trampoline_name_suffix}') assert", "for decl in ast.decls: if decl.decltype == ast_pb2.Decl.Type.FUNC: for s", "self._generate_headlines() # Find and keep track of virtual functions. python_override_class_names", "func_decl.cpp_const_method: cpp_const = ' const' yield I + (f'{return_type} '", "yield from self._generate_virtual_function( decl.class_.name.native, member.func) if python_override_class_name: yield '};' def", "\"third_party/pybind11/include/pybind11/smart_holder.h\"' yield '// potential future optimization: generate this line only", "= I + (f'm.attr(\"{const_decl.name.native}\") = ' f'py::cast({const_decl.name.cpp_name});') yield const_def def", "LLC # # Licensed under the Apache License, Version 2.0", "for cpp_name in self._unique_classes: yield f'PYBIND11_SMART_HOLDER_TYPE_CASTERS({cpp_name})' yield '\\n' for cpp_name,", "+ ( f'using {decl.class_.name.cpp_name}::{decl.class_.name.native};') for member in virtual_members: yield from", "ast_pb2.ConstDecl, includes: Set[str]): if const_decl.type.lang_type == 'complex': includes.add('third_party/pybind11/include/pybind11/complex.h') if (const_decl.type.lang_type.startswith('list<')", "+ ');' yield I + '}' def _collect_class_cpp_names(self, decl: ast_pb2.Decl,", "compliance with the License. # You may obtain a copy", "agreed to in writing, software # distributed under the License", "= v.cpp_exact_type params = ', '.join([f'{p.name.cpp_name}' for p in func_decl.params])", "distributed under the License is distributed on an \"AS IS\"", "overrides calling Python methods.\"\"\" return_type = '' if func_decl.cpp_void_return: return_type", "classes from clif.pybind11 import enums from clif.pybind11 import function from", "ast.decls: includes.add(decl.cpp_file) self._collect_class_cpp_names(decl) yield '#include \"third_party/pybind11/include/pybind11/smart_holder.h\"' for include in includes:", "elif decl.decltype == ast_pb2.Decl.Type.CONST: yield from self._generate_const_variables(decl.const) elif decl.decltype ==", "decl: ast_pb2.Decl, parent_name: str = '') -> None: \"\"\"Adds every", "\"\"\"Writes the generated code to files.\"\"\" for s in lines:", "= 'void' elif func_decl.returns: for v in func_decl.returns: if v.HasField('cpp_exact_type'):", "not virtual_members: return python_override_class_name = ( f'{decl.class_.name.native}_{trampoline_name_suffix}') assert decl.class_.name.cpp_name not", "yield from self._generate_const_variables(decl.const) elif decl.decltype == ast_pb2.Decl.Type.CLASS: yield from classes.generate_from(", "express or implied. # See the License for the specific", "return_type = v.cpp_exact_type params = ', '.join([f'{p.name.cpp_name}' for p in", "set. Only to be used in this context.\"\"\" if decl.decltype", "except in compliance with the License. # You may obtain", "\"\"\"Generates Python overrides classes dictionary for virtual functions.\"\"\" if decl.decltype", "#includes and headers.\"\"\" includes = set() for decl in self._ast.decls:", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "ast: ast_pb2.AST, module_name: str, header_path: str, include_paths: List[str]): self._ast =", "not use this file except in compliance with the License.", "in self._unique_classes.items(): yield f'// CLIF use `{cpp_name}` as {py_name}' def", "full_native_name) def write_to(channel, lines): \"\"\"Writes the generated code to files.\"\"\"", "python_override_class_names[ decl.class_.name.cpp_name] = python_override_class_name yield (f'struct {python_override_class_name} : ' f'{decl.class_.name.cpp_name},", "writing, software # distributed under the License is distributed on", "(f'{return_type} ' f'{func_decl.name.native}({params_str_with_types}) ' f'{cpp_const} override {{') if func_decl.is_pure_virtual: pybind11_override", "List, Text, Set from clif.protos import ast_pb2 from clif.pybind11 import", "you may not use this file except in compliance with", "def _generate_const_variables_headers(self, const_decl: ast_pb2.ConstDecl, includes: Set[str]): if const_decl.type.lang_type == 'complex':", "yield from classes.generate_from( decl.class_, 'm', python_override_class_names.get(decl.class_.name.cpp_name, '')) elif decl.decltype ==", "line only as needed.' yield '#include \"third_party/pybind11/include/pybind11/stl.h\"' yield '' yield", "{{' yield from self._generate_import_modules(ast) yield I+('m.doc() = \"CLIF-generated pybind11-based module", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "decl.func, None): yield I + s elif decl.decltype == ast_pb2.Decl.Type.CONST:", "_generate_const_variables_headers(self, const_decl: ast_pb2.ConstDecl, includes: Set[str]): if const_decl.type.lang_type == 'complex': includes.add('third_party/pybind11/include/pybind11/complex.h')", "I + (f'm.attr(\"{const_decl.name.native}\") = ' f'py::cast({const_decl.name.cpp_name});') yield const_def def _generate_python_override_class_names(", "enums from clif.pybind11 import function from clif.pybind11 import function_lib from", "track of virtual functions. python_override_class_names = {} for decl in", "clif.pybind11 import type_casters from clif.pybind11 import utils I = utils.I", "names = include.split('/') names.insert(0, 'google3') names[-1] = names[-1][:-len('_clif.h')] module =", "# `full.project.path.cheader_pybind11` names = include.split('/') names.insert(0, 'google3') names[-1] = names[-1][:-len('_clif.h')]", "in self._ast.pybind11_includes: includes.add(include) for include in self._ast.usertype_includes: includes.add(include) yield '#include", "str, include_paths: List[str]): self._ast = ast self._module_name = module_name self._header_path", "`full.project.path.cheader_pybind11` names = include.split('/') names.insert(0, 'google3') names[-1] = names[-1][:-len('_clif.h')] module", "if not virtual_members: return python_override_class_name = ( f'{decl.class_.name.native}_{trampoline_name_suffix}') assert decl.class_.name.cpp_name", "const_decl.type.lang_type.startswith('set<')): includes.add('third_party/pybind11/include/pybind11/stl.h') def _generate_const_variables(self, const_decl: ast_pb2.ConstDecl): \"\"\"Generates variables.\"\"\" lang_type =", "in virtual_members: yield from self._generate_virtual_function( decl.class_.name.native, member.func) if python_override_class_name: yield", "import function_lib from clif.pybind11 import type_casters from clif.pybind11 import utils", "const_decl.type.lang_type == 'complex': includes.add('third_party/pybind11/include/pybind11/complex.h') if (const_decl.type.lang_type.startswith('list<') or const_decl.type.lang_type.startswith('dict<') or const_decl.type.lang_type.startswith('set<')):", "in func_decl.params]) params_list_with_types = [] for p in func_decl.params: params_list_with_types.append(", "yield '' def _generate_const_variables_headers(self, const_decl: ast_pb2.ConstDecl, includes: Set[str]): if const_decl.type.lang_type", "from classes.generate_from( decl.class_, 'm', python_override_class_names.get(decl.class_.name.cpp_name, '')) elif decl.decltype == ast_pb2.Decl.Type.ENUM:", "\"third_party/pybind11/include/pybind11/smart_holder.h\"' for include in includes: yield f'#include \"{include}\"' yield '\\n'", "'str'} or lang_type.startswith('tuple<')): const_def = I + (f'm.attr(\"{const_decl.name.native}\") = '", "functions. python_override_class_names = {} for decl in ast.decls: yield from", "CONDITIONS OF ANY KIND, either express or implied. # See", "includes = set() for decl in self._ast.decls: includes.add(decl.cpp_file) if decl.decltype", "= pybind11;' yield '' def _generate_const_variables_headers(self, const_decl: ast_pb2.ConstDecl, includes: Set[str]):", "includes.add(decl.cpp_file) self._collect_class_cpp_names(decl) yield '#include \"third_party/pybind11/include/pybind11/smart_holder.h\"' for include in includes: yield", "I + s elif decl.decltype == ast_pb2.Decl.Type.CONST: yield from self._generate_const_variables(decl.const)", "func_decl.params]) params_list_with_types = [] for p in func_decl.params: params_list_with_types.append( f'{function_lib.generate_param_type(p)}", "decl.class_.name.cpp_name] = python_override_class_name yield (f'struct {python_override_class_name} : ' f'{decl.class_.name.cpp_name}, {self_life_support}", "= decl.class_.name.native if parent_name: full_native_name = '.'.join([parent_name, decl.class_.name.native]) self._unique_classes[decl.class_.name.cpp_name] =", "decl.class_.name.cpp_name not in python_override_class_names python_override_class_names[ decl.class_.name.cpp_name] = python_override_class_name yield (f'struct", "from clif.pybind11 import utils I = utils.I class ModuleGenerator(object): \"\"\"A", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "None, None]: \"\"\"Generates pybind11 bindings code from CLIF ast.\"\"\" includes", "class ModuleGenerator(object): \"\"\"A class that generates pybind11 bindings code from", "in self._ast.decls: includes.add(decl.cpp_file) if decl.decltype == ast_pb2.Decl.Type.CONST: self._generate_const_variables_headers(decl.const, includes) for", "generate this line only as needed.' yield '#include \"third_party/pybind11/include/pybind11/stl.h\"' yield", "const_def def _generate_python_override_class_names( self, python_override_class_names: Dict[Text, Text], decl: ast_pb2.Decl, trampoline_name_suffix:", "yield I + I + I + f'{params}' yield I", "be used in this context.\"\"\" if decl.decltype == ast_pb2.Decl.Type.CLASS: full_native_name", "includes) for include in self._ast.pybind11_includes: includes.add(include) for include in self._ast.usertype_includes:", "member.decltype == ast_pb2.Decl.Type.FUNC and member.func.virtual: virtual_members.append(member) if not virtual_members: return", "CLIF use `{cpp_name}` as {py_name}' def generate_from(self, ast: ast_pb2.AST): \"\"\"Generates", "includes.add('third_party/pybind11/include/pybind11/complex.h') if (const_decl.type.lang_type.startswith('list<') or const_decl.type.lang_type.startswith('dict<') or const_decl.type.lang_type.startswith('set<')): includes.add('third_party/pybind11/include/pybind11/stl.h') def _generate_const_variables(self,", "for member in virtual_members: yield from self._generate_virtual_function( decl.class_.name.native, member.func) if", "ast_pb2.Decl, trampoline_name_suffix: str = '_trampoline', self_life_support: str = 'py::trampoline_self_life_support'): \"\"\"Generates", "= '') -> None: \"\"\"Adds every class name to a", "'}' def _generate_import_modules(self, ast: ast_pb2.AST) -> Generator[str, None, None]: for", "not in python_override_class_names python_override_class_names[ decl.class_.name.cpp_name] = python_override_class_name yield (f'struct {python_override_class_name}", "'' if func_decl.cpp_const_method: cpp_const = ' const' yield I +", "f'{decl.class_.name.cpp_name}, {self_life_support} {{') yield I + ( f'using {decl.class_.name.cpp_name}::{decl.class_.name.native};') for", "[] for p in func_decl.params: params_list_with_types.append( f'{function_lib.generate_param_type(p)} {p.name.cpp_name}') params_str_with_types =", "def _collect_class_cpp_names(self, decl: ast_pb2.Decl, parent_name: str = '') -> None:", "use `{cpp_name}` as {py_name}' def generate_from(self, ast: ast_pb2.AST): \"\"\"Generates pybind11", "(const_decl.type.lang_type.startswith('list<') or const_decl.type.lang_type.startswith('dict<') or const_decl.type.lang_type.startswith('set<')): includes.add('third_party/pybind11/include/pybind11/stl.h') def _generate_const_variables(self, const_decl: ast_pb2.ConstDecl):", "self._generate_const_variables(decl.const) elif decl.decltype == ast_pb2.Decl.Type.CLASS: yield from classes.generate_from( decl.class_, 'm',", "this line only as needed.' yield '#include \"third_party/pybind11/include/pybind11/stl.h\"' yield ''", "'m', python_override_class_names.get(decl.class_.name.cpp_name, '')) elif decl.decltype == ast_pb2.Decl.Type.ENUM: yield from enums.generate_from('m',", "== ast_pb2.Decl.Type.FUNC and member.func.virtual: virtual_members.append(member) if not virtual_members: return python_override_class_name", "code from CLIF ast. Args: ast: CLIF ast protobuf. Yields:", "func_decl.returns: if v.HasField('cpp_exact_type'): return_type = v.cpp_exact_type params = ', '.join([f'{p.name.cpp_name}'", "yield '};' def _generate_virtual_function(self, class_name: str, func_decl: ast_pb2.FuncDecl): \"\"\"Generates virtual", "' const' yield I + (f'{return_type} ' f'{func_decl.name.native}({params_str_with_types}) ' f'{cpp_const}", "include in self._ast.pybind11_includes: includes.add(include) for include in self._ast.usertype_includes: includes.add(include) yield", "\"\"\"Generates pybind11 bindings code from CLIF ast.\"\"\" includes = set()", "pybind11_override = 'PYBIND11_OVERRIDE_PURE' else: pybind11_override = 'PYBIND11_OVERRIDE' yield I +", "classes.generate_from( decl.class_, 'm', python_override_class_names.get(decl.class_.name.cpp_name, '')) elif decl.decltype == ast_pb2.Decl.Type.ENUM: yield", "OR CONDITIONS OF ANY KIND, either express or implied. #", "= ' f'py::cast({const_decl.name.cpp_name});') yield const_def def _generate_python_override_class_names( self, python_override_class_names: Dict[Text,", "I + '}' def _collect_class_cpp_names(self, decl: ast_pb2.Decl, parent_name: str =", "yield I + I + I + f'{func_decl.name.native},' yield I", "{{') if func_decl.is_pure_virtual: pybind11_override = 'PYBIND11_OVERRIDE_PURE' else: pybind11_override = 'PYBIND11_OVERRIDE'", "Dict[Text, Text], decl: ast_pb2.Decl, trampoline_name_suffix: str = '_trampoline', self_life_support: str", "the License is distributed on an \"AS IS\" BASIS, #", "full_native_name for member in decl.class_.members: self._collect_class_cpp_names(member, full_native_name) def write_to(channel, lines):", "yield I + s elif decl.decltype == ast_pb2.Decl.Type.CONST: yield from", "CLIF ast. Args: ast: CLIF ast protobuf. Yields: Generated pybind11", "def write_to(channel, lines): \"\"\"Writes the generated code to files.\"\"\" for", "func_decl.cpp_void_return: return_type = 'void' elif func_decl.returns: for v in func_decl.returns:", "module_name: str, header_path: str, include_paths: List[str]): self._ast = ast self._module_name", "yield '// potential future optimization: generate this line only as", "const_decl: ast_pb2.ConstDecl, includes: Set[str]): if const_decl.type.lang_type == 'complex': includes.add('third_party/pybind11/include/pybind11/complex.h') if", "self._generate_const_variables_headers(decl.const, includes) for include in self._ast.pybind11_includes: includes.add(include) for include in", "= include_paths self._unique_classes = {} def generate_header(self, ast: ast_pb2.AST) ->", "if func_decl.is_pure_virtual: pybind11_override = 'PYBIND11_OVERRIDE_PURE' else: pybind11_override = 'PYBIND11_OVERRIDE' yield", "in decl.class_.members: if member.decltype == ast_pb2.Decl.Type.FUNC and member.func.virtual: virtual_members.append(member) if", "from typing import Dict, Generator, List, Text, Set from clif.protos", "decl.class_.members: if member.decltype == ast_pb2.Decl.Type.FUNC and member.func.virtual: virtual_members.append(member) if not", "Find and keep track of virtual functions. python_override_class_names = {}", "pybind11_override = 'PYBIND11_OVERRIDE' yield I + I + f'{pybind11_override}(' yield", "== ast_pb2.Decl.Type.CLASS: full_native_name = decl.class_.name.native if parent_name: full_native_name = '.'.join([parent_name,", "from self._generate_headlines() # Find and keep track of virtual functions.", "\"\"\"Generates virtual function overrides calling Python methods.\"\"\" return_type = ''", "f'{pybind11_override}(' yield I + I + I + f'{return_type},' yield", "for s in function.generate_from('m', decl.func, None): yield I + s", "in function.generate_from('m', decl.func, None): yield I + s elif decl.decltype", "= set() for decl in ast.decls: includes.add(decl.cpp_file) self._collect_class_cpp_names(decl) yield '#include", "dictionary for virtual functions.\"\"\" if decl.decltype == ast_pb2.Decl.Type.CLASS: virtual_members =", "yield '#include \"third_party/pybind11/include/pybind11/functional.h\"' yield '#include \"third_party/pybind11/include/pybind11/operators.h\"' yield '#include \"third_party/pybind11/include/pybind11/smart_holder.h\"' yield", "header_path self._include_paths = include_paths self._unique_classes = {} def generate_header(self, ast:", "law or agreed to in writing, software # distributed under", "include in includes: yield f'#include \"{include}\"' yield '\\n' for cpp_name", "in ast.pybind11_includes: # Converts `full/project/path/cheader_pybind11_clif.h` to # `full.project.path.cheader_pybind11` names =", "to be used in this context.\"\"\" if decl.decltype == ast_pb2.Decl.Type.CLASS:", "'#include \"third_party/pybind11/include/pybind11/complex.h\"' yield '#include \"third_party/pybind11/include/pybind11/functional.h\"' yield '#include \"third_party/pybind11/include/pybind11/operators.h\"' yield '#include", "virtual_members: yield from self._generate_virtual_function( decl.class_.name.native, member.func) if python_override_class_name: yield '};'", "decl.decltype == ast_pb2.Decl.Type.CLASS: full_native_name = decl.class_.name.native if parent_name: full_native_name =", "yield '#include \"third_party/pybind11/include/pybind11/complex.h\"' yield '#include \"third_party/pybind11/include/pybind11/functional.h\"' yield '#include \"third_party/pybind11/include/pybind11/operators.h\"' yield", "ast_pb2.Decl.Type.CLASS: full_native_name = decl.class_.name.native if parent_name: full_native_name = '.'.join([parent_name, decl.class_.name.native])", "or lang_type.startswith('tuple<')): const_def = I + (f'm.attr(\"{const_decl.name.native}\") = ' f'{const_decl.name.cpp_name};')", "class_name: str, func_decl: ast_pb2.FuncDecl): \"\"\"Generates virtual function overrides calling Python", "'#include \"clif/pybind11/runtime.h\"' yield '#include \"clif/pybind11/type_casters.h\"' yield '' for include in", "as needed.' yield '#include \"third_party/pybind11/include/pybind11/stl.h\"' yield '' yield '#include \"clif/pybind11/runtime.h\"'", "for v in func_decl.returns: if v.HasField('cpp_exact_type'): return_type = v.cpp_exact_type params", "ast: ast_pb2.AST) -> Generator[str, None, None]: for include in ast.pybind11_includes:", "', '.join(params_list_with_types) cpp_const = '' if func_decl.cpp_const_method: cpp_const = '", "ast_pb2.Decl.Type.CONST: self._generate_const_variables_headers(decl.const, includes) for include in self._ast.pybind11_includes: includes.add(include) for include", "clif.pybind11 import enums from clif.pybind11 import function from clif.pybind11 import", "f'py::module_::import(\"{module}\");' def _generate_headlines(self): \"\"\"Generates #includes and headers.\"\"\" includes = set()", "yield f'#include \"{include}\"' yield f'#include \"{self._header_path}\"' yield '' yield 'namespace", "yield const_def def _generate_python_override_class_names( self, python_override_class_names: Dict[Text, Text], decl: ast_pb2.Decl,", "ast.decls: if decl.decltype == ast_pb2.Decl.Type.FUNC: for s in function.generate_from('m', decl.func,", "python_override_class_name yield (f'struct {python_override_class_name} : ' f'{decl.class_.name.cpp_name}, {self_life_support} {{') yield", "from clif.pybind11 import enums from clif.pybind11 import function from clif.pybind11", "str = '') -> None: \"\"\"Adds every class name to", "classes dictionary for virtual functions.\"\"\" if decl.decltype == ast_pb2.Decl.Type.CLASS: virtual_members", "str, header_path: str, include_paths: List[str]): self._ast = ast self._module_name =", "used in this context.\"\"\" if decl.decltype == ast_pb2.Decl.Type.CLASS: full_native_name =", "'_trampoline', self_life_support: str = 'py::trampoline_self_life_support'): \"\"\"Generates Python overrides classes dictionary", "may obtain a copy of the License at # #", "== 'complex': includes.add('third_party/pybind11/include/pybind11/complex.h') if (const_decl.type.lang_type.startswith('list<') or const_decl.type.lang_type.startswith('dict<') or const_decl.type.lang_type.startswith('set<')): includes.add('third_party/pybind11/include/pybind11/stl.h')", "language governing permissions and # limitations under the License. \"\"\"Generates", "clif.pybind11 import function_lib from clif.pybind11 import type_casters from clif.pybind11 import", "clif.pybind11 import classes from clif.pybind11 import enums from clif.pybind11 import", "decl.decltype == ast_pb2.Decl.Type.CONST: self._generate_const_variables_headers(decl.const, includes) for include in self._ast.pybind11_includes: includes.add(include)", "for p in func_decl.params]) params_list_with_types = [] for p in", "in includes: yield f'#include \"{include}\"' yield f'#include \"{self._header_path}\"' yield ''", "from clif.pybind11 import function from clif.pybind11 import function_lib from clif.pybind11", "in ast.decls: yield from self._generate_python_override_class_names( python_override_class_names, decl) self._collect_class_cpp_names(decl) yield from", "-> Generator[str, None, None]: \"\"\"Generates pybind11 bindings code from CLIF", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "= \"CLIF-generated pybind11-based module for ' f'{ast.source}\";') yield I +", "'' def _generate_const_variables_headers(self, const_decl: ast_pb2.ConstDecl, includes: Set[str]): if const_decl.type.lang_type ==", "= 'py::trampoline_self_life_support'): \"\"\"Generates Python overrides classes dictionary for virtual functions.\"\"\"", "decl.decltype == ast_pb2.Decl.Type.CLASS: virtual_members = [] for member in decl.class_.members:", "self._ast.pybind11_includes: includes.add(include) for include in self._ast.usertype_includes: includes.add(include) yield '#include \"third_party/pybind11/include/pybind11/complex.h\"'", "member in decl.class_.members: self._collect_class_cpp_names(member, full_native_name) def write_to(channel, lines): \"\"\"Writes the", "may not use this file except in compliance with the", "parent_name: str = '') -> None: \"\"\"Adds every class name", "f'{params}' yield I + I + ');' yield I +", "self._include_paths) yield f'PYBIND11_MODULE({self._module_name}, m) {{' yield from self._generate_import_modules(ast) yield I+('m.doc()", "const_decl.type.lang_type if (lang_type in {'int', 'float', 'double', 'bool', 'str'} or", "params_list_with_types.append( f'{function_lib.generate_param_type(p)} {p.name.cpp_name}') params_str_with_types = ', '.join(params_list_with_types) cpp_const = ''", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "as {py_name}' def generate_from(self, ast: ast_pb2.AST): \"\"\"Generates pybind11 bindings code", "this file except in compliance with the License. # You", "virtual functions.\"\"\" if decl.decltype == ast_pb2.Decl.Type.CLASS: virtual_members = [] for", "for cpp_name, py_name in self._unique_classes.items(): yield f'// CLIF use `{cpp_name}`", "include in ast.pybind11_includes: # Converts `full/project/path/cheader_pybind11_clif.h` to # `full.project.path.cheader_pybind11` names", "(f'm.attr(\"{const_decl.name.native}\") = ' f'py::cast({const_decl.name.cpp_name});') yield const_def def _generate_python_override_class_names( self, python_override_class_names:", "def _generate_import_modules(self, ast: ast_pb2.AST) -> Generator[str, None, None]: for include", "member in decl.class_.members: if member.decltype == ast_pb2.Decl.Type.FUNC and member.func.virtual: virtual_members.append(member)", "-> Generator[str, None, None]: for include in ast.pybind11_includes: # Converts", "generate_header(self, ast: ast_pb2.AST) -> Generator[str, None, None]: \"\"\"Generates pybind11 bindings", "<filename>clif/pybind11/generator.py # Copyright 2020 Google LLC # # Licensed under", "bindings code.\"\"\" from typing import Dict, Generator, List, Text, Set", "set() for decl in self._ast.decls: includes.add(decl.cpp_file) if decl.decltype == ast_pb2.Decl.Type.CONST:", "= ast self._module_name = module_name self._header_path = header_path self._include_paths =", "Set[str]): if const_decl.type.lang_type == 'complex': includes.add('third_party/pybind11/include/pybind11/complex.h') if (const_decl.type.lang_type.startswith('list<') or const_decl.type.lang_type.startswith('dict<')", "_generate_headlines(self): \"\"\"Generates #includes and headers.\"\"\" includes = set() for decl", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "Dict, Generator, List, Text, Set from clif.protos import ast_pb2 from", "lang_type = const_decl.type.lang_type if (lang_type in {'int', 'float', 'double', 'bool',", "+ f'{pybind11_override}(' yield I + I + I + f'{return_type},'", "# # Licensed under the Apache License, Version 2.0 (the", "includes.add(include) yield '#include \"third_party/pybind11/include/pybind11/complex.h\"' yield '#include \"third_party/pybind11/include/pybind11/functional.h\"' yield '#include \"third_party/pybind11/include/pybind11/operators.h\"'", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "in python_override_class_names python_override_class_names[ decl.class_.name.cpp_name] = python_override_class_name yield (f'struct {python_override_class_name} :", "# Converts `full/project/path/cheader_pybind11_clif.h` to # `full.project.path.cheader_pybind11` names = include.split('/') names.insert(0,", "= ', '.join(params_list_with_types) cpp_const = '' if func_decl.cpp_const_method: cpp_const =", "protobuf. Yields: Generated pybind11 bindings code. \"\"\" yield from self._generate_headlines()", "yield from type_casters.generate_from(ast, self._include_paths) yield f'PYBIND11_MODULE({self._module_name}, m) {{' yield from", "from clif.pybind11 import classes from clif.pybind11 import enums from clif.pybind11", "I + (f'{return_type} ' f'{func_decl.name.native}({params_str_with_types}) ' f'{cpp_const} override {{') if", "f'{cpp_const} override {{') if func_decl.is_pure_virtual: pybind11_override = 'PYBIND11_OVERRIDE_PURE' else: pybind11_override", "lines): \"\"\"Writes the generated code to files.\"\"\" for s in", "yield I + I + I + f'{return_type},' yield I", "decl: ast_pb2.Decl, trampoline_name_suffix: str = '_trampoline', self_life_support: str = 'py::trampoline_self_life_support'):", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "yield '\\n' for cpp_name, py_name in self._unique_classes.items(): yield f'// CLIF", "= set() for decl in self._ast.decls: includes.add(decl.cpp_file) if decl.decltype ==", "str, func_decl: ast_pb2.FuncDecl): \"\"\"Generates virtual function overrides calling Python methods.\"\"\"", "func_decl: ast_pb2.FuncDecl): \"\"\"Generates virtual function overrides calling Python methods.\"\"\" return_type", "+ I + I + f'{return_type},' yield I + I", "I + I + ');' yield I + '}' def", "Copyright 2020 Google LLC # # Licensed under the Apache", "and headers.\"\"\" includes = set() for decl in self._ast.decls: includes.add(decl.cpp_file)", "utils I = utils.I class ModuleGenerator(object): \"\"\"A class that generates", "\"clif/pybind11/runtime.h\"' yield '#include \"clif/pybind11/type_casters.h\"' yield '' for include in includes:", "bindings code from CLIF ast.\"\"\" includes = set() for decl", "methods.\"\"\" return_type = '' if func_decl.cpp_void_return: return_type = 'void' elif", "params_str_with_types = ', '.join(params_list_with_types) cpp_const = '' if func_decl.cpp_const_method: cpp_const", "== ast_pb2.Decl.Type.CONST: yield from self._generate_const_variables(decl.const) elif decl.decltype == ast_pb2.Decl.Type.CLASS: yield", "I + f'{pybind11_override}(' yield I + I + I +", "python_override_class_names, decl) self._collect_class_cpp_names(decl) yield from type_casters.generate_from(ast, self._include_paths) yield f'PYBIND11_MODULE({self._module_name}, m)", "pybind11 bindings code.\"\"\" from typing import Dict, Generator, List, Text,", "I = utils.I class ModuleGenerator(object): \"\"\"A class that generates pybind11", "for ' f'{ast.source}\";') yield I + 'py::google::ImportStatusModule();' for decl in", "under the License. \"\"\"Generates pybind11 bindings code.\"\"\" from typing import", "yield '}' def _generate_import_modules(self, ast: ast_pb2.AST) -> Generator[str, None, None]:", "virtual functions. python_override_class_names = {} for decl in ast.decls: yield", "Generated pybind11 bindings code. \"\"\" yield from self._generate_headlines() # Find", "yield f'// CLIF use `{cpp_name}` as {py_name}' def generate_from(self, ast:", "pybind11 bindings code. \"\"\" yield from self._generate_headlines() # Find and", "\"third_party/pybind11/include/pybind11/operators.h\"' yield '#include \"third_party/pybind11/include/pybind11/smart_holder.h\"' yield '// potential future optimization: generate", "python_override_class_names: Dict[Text, Text], decl: ast_pb2.Decl, trampoline_name_suffix: str = '_trampoline', self_life_support:", "' f'{func_decl.name.native}({params_str_with_types}) ' f'{cpp_const} override {{') if func_decl.is_pure_virtual: pybind11_override =", "'complex': includes.add('third_party/pybind11/include/pybind11/complex.h') if (const_decl.type.lang_type.startswith('list<') or const_decl.type.lang_type.startswith('dict<') or const_decl.type.lang_type.startswith('set<')): includes.add('third_party/pybind11/include/pybind11/stl.h') def", "+ I + I + f'{class_name},' yield I + I", "= '_trampoline', self_life_support: str = 'py::trampoline_self_life_support'): \"\"\"Generates Python overrides classes", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "cpp_const = '' if func_decl.cpp_const_method: cpp_const = ' const' yield", "from type_casters.generate_from(ast, self._include_paths) yield f'PYBIND11_MODULE({self._module_name}, m) {{' yield from self._generate_import_modules(ast)", "self._generate_import_modules(ast) yield I+('m.doc() = \"CLIF-generated pybind11-based module for ' f'{ast.source}\";')", "const' yield I + (f'{return_type} ' f'{func_decl.name.native}({params_str_with_types}) ' f'{cpp_const} override", "{} def generate_header(self, ast: ast_pb2.AST) -> Generator[str, None, None]: \"\"\"Generates", "for include in ast.pybind11_includes: # Converts `full/project/path/cheader_pybind11_clif.h` to # `full.project.path.cheader_pybind11`", "'.join(params_list_with_types) cpp_const = '' if func_decl.cpp_const_method: cpp_const = ' const'", "def generate_from(self, ast: ast_pb2.AST): \"\"\"Generates pybind11 bindings code from CLIF", "elif decl.decltype == ast_pb2.Decl.Type.ENUM: yield from enums.generate_from('m', decl.enum) yield ''", "\"\"\"Generates variables.\"\"\" lang_type = const_decl.type.lang_type if (lang_type in {'int', 'float',", "'};' def _generate_virtual_function(self, class_name: str, func_decl: ast_pb2.FuncDecl): \"\"\"Generates virtual function", "or implied. # See the License for the specific language", "'#include \"third_party/pybind11/include/pybind11/operators.h\"' yield '#include \"third_party/pybind11/include/pybind11/smart_holder.h\"' yield '// potential future optimization:", "if (lang_type in {'int', 'float', 'double', 'bool', 'str'} or lang_type.startswith('tuple<')):", "functions.\"\"\" if decl.decltype == ast_pb2.Decl.Type.CLASS: virtual_members = [] for member", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "typing import Dict, Generator, List, Text, Set from clif.protos import", "self._unique_classes = {} def generate_header(self, ast: ast_pb2.AST) -> Generator[str, None,", "yield from self._generate_import_modules(ast) yield I+('m.doc() = \"CLIF-generated pybind11-based module for", "\"\"\"Generates #includes and headers.\"\"\" includes = set() for decl in", "future optimization: generate this line only as needed.' yield '#include", "I + I + I + f'{params}' yield I +", "pybind11;' yield '' def _generate_const_variables_headers(self, const_decl: ast_pb2.ConstDecl, includes: Set[str]): if", "import type_casters from clif.pybind11 import utils I = utils.I class", "ast_pb2.AST) -> Generator[str, None, None]: for include in ast.pybind11_includes: #", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "decl in ast.decls: includes.add(decl.cpp_file) self._collect_class_cpp_names(decl) yield '#include \"third_party/pybind11/include/pybind11/smart_holder.h\"' for include", "f'{decl.class_.name.native}_{trampoline_name_suffix}') assert decl.class_.name.cpp_name not in python_override_class_names python_override_class_names[ decl.class_.name.cpp_name] = python_override_class_name", "names[-1][:-len('_clif.h')] module = '.'.join(names) yield f'py::module_::import(\"{module}\");' def _generate_headlines(self): \"\"\"Generates #includes", "every class name to a set. Only to be used", "a set. Only to be used in this context.\"\"\" if", "yield '#include \"clif/pybind11/runtime.h\"' yield '#include \"clif/pybind11/type_casters.h\"' yield '' for include", "clif.pybind11 import utils I = utils.I class ModuleGenerator(object): \"\"\"A class", "None]: for include in ast.pybind11_includes: # Converts `full/project/path/cheader_pybind11_clif.h` to #", "include_paths: List[str]): self._ast = ast self._module_name = module_name self._header_path =", "import classes from clif.pybind11 import enums from clif.pybind11 import function", "(the \"License\"); # you may not use this file except", "# you may not use this file except in compliance", "= ( f'{decl.class_.name.native}_{trampoline_name_suffix}') assert decl.class_.name.cpp_name not in python_override_class_names python_override_class_names[ decl.class_.name.cpp_name]", "ast_pb2.Decl, parent_name: str = '') -> None: \"\"\"Adds every class", "self._collect_class_cpp_names(member, full_native_name) def write_to(channel, lines): \"\"\"Writes the generated code to", "= utils.I class ModuleGenerator(object): \"\"\"A class that generates pybind11 bindings", "{python_override_class_name} : ' f'{decl.class_.name.cpp_name}, {self_life_support} {{') yield I + (", "from CLIF ast.\"\"\" def __init__(self, ast: ast_pb2.AST, module_name: str, header_path:", "self._unique_classes.items(): yield f'// CLIF use `{cpp_name}` as {py_name}' def generate_from(self,", "yield f'#include \"{self._header_path}\"' yield '' yield 'namespace py = pybind11;'", "{self_life_support} {{') yield I + ( f'using {decl.class_.name.cpp_name}::{decl.class_.name.native};') for member", "= full_native_name for member in decl.class_.members: self._collect_class_cpp_names(member, full_native_name) def write_to(channel,", "yield '#include \"third_party/pybind11/include/pybind11/smart_holder.h\"' yield '// potential future optimization: generate this", "None): yield I + s elif decl.decltype == ast_pb2.Decl.Type.CONST: yield", "I + I + f'{params}' yield I + I +", "' f'py::cast({const_decl.name.cpp_name});') yield const_def def _generate_python_override_class_names( self, python_override_class_names: Dict[Text, Text],", "import utils I = utils.I class ModuleGenerator(object): \"\"\"A class that", "yield '' yield '#include \"clif/pybind11/runtime.h\"' yield '#include \"clif/pybind11/type_casters.h\"' yield ''", "module for ' f'{ast.source}\";') yield I + 'py::google::ImportStatusModule();' for decl", "pybind11 bindings code from CLIF ast.\"\"\" includes = set() for", "'py::trampoline_self_life_support'): \"\"\"Generates Python overrides classes dictionary for virtual functions.\"\"\" if", "Set from clif.protos import ast_pb2 from clif.pybind11 import classes from", "# # Unless required by applicable law or agreed to", "ast_pb2.Decl.Type.CLASS: virtual_members = [] for member in decl.class_.members: if member.decltype", "in func_decl.returns: if v.HasField('cpp_exact_type'): return_type = v.cpp_exact_type params = ',", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "Version 2.0 (the \"License\"); # you may not use this", "module_name self._header_path = header_path self._include_paths = include_paths self._unique_classes = {}", "decl.decltype == ast_pb2.Decl.Type.CLASS: yield from classes.generate_from( decl.class_, 'm', python_override_class_names.get(decl.class_.name.cpp_name, ''))", "yield '' yield '}' def _generate_import_modules(self, ast: ast_pb2.AST) -> Generator[str,", "p in func_decl.params]) params_list_with_types = [] for p in func_decl.params:", "ast_pb2.ConstDecl): \"\"\"Generates variables.\"\"\" lang_type = const_decl.type.lang_type if (lang_type in {'int',", "= {} for decl in ast.decls: yield from self._generate_python_override_class_names( python_override_class_names,", "= module_name self._header_path = header_path self._include_paths = include_paths self._unique_classes =", "python_override_class_name = ( f'{decl.class_.name.native}_{trampoline_name_suffix}') assert decl.class_.name.cpp_name not in python_override_class_names python_override_class_names[", "includes.add(include) for include in self._ast.usertype_includes: includes.add(include) yield '#include \"third_party/pybind11/include/pybind11/complex.h\"' yield", "yield '#include \"clif/pybind11/type_casters.h\"' yield '' for include in includes: yield", "if const_decl.type.lang_type == 'complex': includes.add('third_party/pybind11/include/pybind11/complex.h') if (const_decl.type.lang_type.startswith('list<') or const_decl.type.lang_type.startswith('dict<') or", "implied. # See the License for the specific language governing", "under the Apache License, Version 2.0 (the \"License\"); # you", "f'#include \"{include}\"' yield '\\n' for cpp_name in self._unique_classes: yield f'PYBIND11_SMART_HOLDER_TYPE_CASTERS({cpp_name})'", "I + I + I + f'{class_name},' yield I +", "code from CLIF ast.\"\"\" def __init__(self, ast: ast_pb2.AST, module_name: str,", "and # limitations under the License. \"\"\"Generates pybind11 bindings code.\"\"\"", "'' yield '}' def _generate_import_modules(self, ast: ast_pb2.AST) -> Generator[str, None,", "+ I + I + f'{params}' yield I + I", "yield I + 'py::google::ImportStatusModule();' for decl in ast.decls: if decl.decltype", "\"{include}\"' yield '\\n' for cpp_name in self._unique_classes: yield f'PYBIND11_SMART_HOLDER_TYPE_CASTERS({cpp_name})' yield", "self._unique_classes: yield f'PYBIND11_SMART_HOLDER_TYPE_CASTERS({cpp_name})' yield '\\n' for cpp_name, py_name in self._unique_classes.items():", "+ f'{func_decl.name.native},' yield I + I + I + f'{params}'", "overrides classes dictionary for virtual functions.\"\"\" if decl.decltype == ast_pb2.Decl.Type.CLASS:", "by applicable law or agreed to in writing, software #", "to # `full.project.path.cheader_pybind11` names = include.split('/') names.insert(0, 'google3') names[-1] =", "virtual_members: return python_override_class_name = ( f'{decl.class_.name.native}_{trampoline_name_suffix}') assert decl.class_.name.cpp_name not in", "for include in self._ast.pybind11_includes: includes.add(include) for include in self._ast.usertype_includes: includes.add(include)", "');' yield I + '}' def _collect_class_cpp_names(self, decl: ast_pb2.Decl, parent_name:", "ModuleGenerator(object): \"\"\"A class that generates pybind11 bindings code from CLIF", "p in func_decl.params: params_list_with_types.append( f'{function_lib.generate_param_type(p)} {p.name.cpp_name}') params_str_with_types = ', '.join(params_list_with_types)", "virtual_members = [] for member in decl.class_.members: if member.decltype ==", "I + (f'm.attr(\"{const_decl.name.native}\") = ' f'{const_decl.name.cpp_name};') else: const_def = I", "python_override_class_name: yield '};' def _generate_virtual_function(self, class_name: str, func_decl: ast_pb2.FuncDecl): \"\"\"Generates", "+ I + f'{pybind11_override}(' yield I + I + I", "that generates pybind11 bindings code from CLIF ast.\"\"\" def __init__(self,", "+ f'{class_name},' yield I + I + I + f'{func_decl.name.native},'", "I + f'{func_decl.name.native},' yield I + I + I +", "decl.class_, 'm', python_override_class_names.get(decl.class_.name.cpp_name, '')) elif decl.decltype == ast_pb2.Decl.Type.ENUM: yield from", "yield I + '}' def _collect_class_cpp_names(self, decl: ast_pb2.Decl, parent_name: str", "(f'struct {python_override_class_name} : ' f'{decl.class_.name.cpp_name}, {self_life_support} {{') yield I +", "f'{func_decl.name.native},' yield I + I + I + f'{params}' yield", "+ '}' def _collect_class_cpp_names(self, decl: ast_pb2.Decl, parent_name: str = '')", "# Copyright 2020 Google LLC # # Licensed under the", "decl.class_.name.native]) self._unique_classes[decl.class_.name.cpp_name] = full_native_name for member in decl.class_.members: self._collect_class_cpp_names(member, full_native_name)", "str = 'py::trampoline_self_life_support'): \"\"\"Generates Python overrides classes dictionary for virtual", "decl.decltype == ast_pb2.Decl.Type.CONST: yield from self._generate_const_variables(decl.const) elif decl.decltype == ast_pb2.Decl.Type.CLASS:", "include_paths self._unique_classes = {} def generate_header(self, ast: ast_pb2.AST) -> Generator[str,", "yield I + ( f'using {decl.class_.name.cpp_name}::{decl.class_.name.native};') for member in virtual_members:", "includes.add('third_party/pybind11/include/pybind11/stl.h') def _generate_const_variables(self, const_decl: ast_pb2.ConstDecl): \"\"\"Generates variables.\"\"\" lang_type = const_decl.type.lang_type", "in self._ast.usertype_includes: includes.add(include) yield '#include \"third_party/pybind11/include/pybind11/complex.h\"' yield '#include \"third_party/pybind11/include/pybind11/functional.h\"' yield", "\"{self._header_path}\"' yield '' yield 'namespace py = pybind11;' yield ''", "yield (f'struct {python_override_class_name} : ' f'{decl.class_.name.cpp_name}, {self_life_support} {{') yield I", "optimization: generate this line only as needed.' yield '#include \"third_party/pybind11/include/pybind11/stl.h\"'", "def __init__(self, ast: ast_pb2.AST, module_name: str, header_path: str, include_paths: List[str]):", "variables.\"\"\" lang_type = const_decl.type.lang_type if (lang_type in {'int', 'float', 'double',", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "{} for decl in ast.decls: yield from self._generate_python_override_class_names( python_override_class_names, decl)", "+ s elif decl.decltype == ast_pb2.Decl.Type.CONST: yield from self._generate_const_variables(decl.const) elif", "'#include \"third_party/pybind11/include/pybind11/functional.h\"' yield '#include \"third_party/pybind11/include/pybind11/operators.h\"' yield '#include \"third_party/pybind11/include/pybind11/smart_holder.h\"' yield '//", "Unless required by applicable law or agreed to in writing,", "includes: yield f'#include \"{include}\"' yield f'#include \"{self._header_path}\"' yield '' yield", "None, None]: for include in ast.pybind11_includes: # Converts `full/project/path/cheader_pybind11_clif.h` to", "'#include \"third_party/pybind11/include/pybind11/smart_holder.h\"' for include in includes: yield f'#include \"{include}\"' yield", "python_override_class_names = {} for decl in ast.decls: yield from self._generate_python_override_class_names(", "yield f'py::module_::import(\"{module}\");' def _generate_headlines(self): \"\"\"Generates #includes and headers.\"\"\" includes =", "class name to a set. Only to be used in", "I + f'{return_type},' yield I + I + I +", "== ast_pb2.Decl.Type.CONST: self._generate_const_variables_headers(decl.const, includes) for include in self._ast.pybind11_includes: includes.add(include) for", "ast_pb2.AST): \"\"\"Generates pybind11 bindings code from CLIF ast. Args: ast:", "the specific language governing permissions and # limitations under the", "decl.class_.name.native if parent_name: full_native_name = '.'.join([parent_name, decl.class_.name.native]) self._unique_classes[decl.class_.name.cpp_name] = full_native_name", "permissions and # limitations under the License. \"\"\"Generates pybind11 bindings", "bindings code. \"\"\" yield from self._generate_headlines() # Find and keep", "+ I + I + f'{func_decl.name.native},' yield I + I", "applicable law or agreed to in writing, software # distributed", "I + I + f'{return_type},' yield I + I +", "+ (f'm.attr(\"{const_decl.name.native}\") = ' f'{const_decl.name.cpp_name};') else: const_def = I +", "ast.\"\"\" includes = set() for decl in ast.decls: includes.add(decl.cpp_file) self._collect_class_cpp_names(decl)", "'' for include in includes: yield f'#include \"{include}\"' yield f'#include", "f'using {decl.class_.name.cpp_name}::{decl.class_.name.native};') for member in virtual_members: yield from self._generate_virtual_function( decl.class_.name.native,", "Google LLC # # Licensed under the Apache License, Version", "' f'{const_decl.name.cpp_name};') else: const_def = I + (f'm.attr(\"{const_decl.name.native}\") = '", "yield '#include \"third_party/pybind11/include/pybind11/operators.h\"' yield '#include \"third_party/pybind11/include/pybind11/smart_holder.h\"' yield '// potential future", "in writing, software # distributed under the License is distributed", "Generator[str, None, None]: for include in ast.pybind11_includes: # Converts `full/project/path/cheader_pybind11_clif.h`", "== ast_pb2.Decl.Type.CLASS: virtual_members = [] for member in decl.class_.members: if", "Python methods.\"\"\" return_type = '' if func_decl.cpp_void_return: return_type = 'void'", "= '' if func_decl.cpp_const_method: cpp_const = ' const' yield I", "I+('m.doc() = \"CLIF-generated pybind11-based module for ' f'{ast.source}\";') yield I", "' f'{cpp_const} override {{') if func_decl.is_pure_virtual: pybind11_override = 'PYBIND11_OVERRIDE_PURE' else:", "self._module_name = module_name self._header_path = header_path self._include_paths = include_paths self._unique_classes", "and keep track of virtual functions. python_override_class_names = {} for", "yield '#include \"third_party/pybind11/include/pybind11/stl.h\"' yield '' yield '#include \"clif/pybind11/runtime.h\"' yield '#include", "== ast_pb2.Decl.Type.CLASS: yield from classes.generate_from( decl.class_, 'm', python_override_class_names.get(decl.class_.name.cpp_name, '')) elif", "Generator, List, Text, Set from clif.protos import ast_pb2 from clif.pybind11", "decl in self._ast.decls: includes.add(decl.cpp_file) if decl.decltype == ast_pb2.Decl.Type.CONST: self._generate_const_variables_headers(decl.const, includes)", "[] for member in decl.class_.members: if member.decltype == ast_pb2.Decl.Type.FUNC and", "def generate_header(self, ast: ast_pb2.AST) -> Generator[str, None, None]: \"\"\"Generates pybind11", "includes: yield f'#include \"{include}\"' yield '\\n' for cpp_name in self._unique_classes:", "+ f'{params}' yield I + I + ');' yield I", "clif.pybind11 import function from clif.pybind11 import function_lib from clif.pybind11 import", "utils.I class ModuleGenerator(object): \"\"\"A class that generates pybind11 bindings code", "ast_pb2.AST) -> Generator[str, None, None]: \"\"\"Generates pybind11 bindings code from", "ast: ast_pb2.AST): \"\"\"Generates pybind11 bindings code from CLIF ast. Args:", "`{cpp_name}` as {py_name}' def generate_from(self, ast: ast_pb2.AST): \"\"\"Generates pybind11 bindings", "if decl.decltype == ast_pb2.Decl.Type.CLASS: full_native_name = decl.class_.name.native if parent_name: full_native_name", "\"clif/pybind11/type_casters.h\"' yield '' for include in includes: yield f'#include \"{include}\"'", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "for decl in ast.decls: includes.add(decl.cpp_file) self._collect_class_cpp_names(decl) yield '#include \"third_party/pybind11/include/pybind11/smart_holder.h\"' for", "License, Version 2.0 (the \"License\"); # you may not use", "lang_type.startswith('tuple<')): const_def = I + (f'm.attr(\"{const_decl.name.native}\") = ' f'{const_decl.name.cpp_name};') else:", "# You may obtain a copy of the License at", "self._header_path = header_path self._include_paths = include_paths self._unique_classes = {} def", "-> None: \"\"\"Adds every class name to a set. Only", "+ f'{return_type},' yield I + I + I + f'{class_name},'", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "I + ');' yield I + '}' def _collect_class_cpp_names(self, decl:", "'' if func_decl.cpp_void_return: return_type = 'void' elif func_decl.returns: for v", "in {'int', 'float', 'double', 'bool', 'str'} or lang_type.startswith('tuple<')): const_def =", "only as needed.' yield '#include \"third_party/pybind11/include/pybind11/stl.h\"' yield '' yield '#include", "( f'using {decl.class_.name.cpp_name}::{decl.class_.name.native};') for member in virtual_members: yield from self._generate_virtual_function(", "return python_override_class_name = ( f'{decl.class_.name.native}_{trampoline_name_suffix}') assert decl.class_.name.cpp_name not in python_override_class_names", "include.split('/') names.insert(0, 'google3') names[-1] = names[-1][:-len('_clif.h')] module = '.'.join(names) yield", "f'{const_decl.name.cpp_name};') else: const_def = I + (f'm.attr(\"{const_decl.name.native}\") = ' f'py::cast({const_decl.name.cpp_name});')", "decl) self._collect_class_cpp_names(decl) yield from type_casters.generate_from(ast, self._include_paths) yield f'PYBIND11_MODULE({self._module_name}, m) {{'", "function_lib from clif.pybind11 import type_casters from clif.pybind11 import utils I", "in ast.decls: includes.add(decl.cpp_file) self._collect_class_cpp_names(decl) yield '#include \"third_party/pybind11/include/pybind11/smart_holder.h\"' for include in", "\"CLIF-generated pybind11-based module for ' f'{ast.source}\";') yield I + 'py::google::ImportStatusModule();'", "def _generate_headlines(self): \"\"\"Generates #includes and headers.\"\"\" includes = set() for", "+ (f'm.attr(\"{const_decl.name.native}\") = ' f'py::cast({const_decl.name.cpp_name});') yield const_def def _generate_python_override_class_names( self,", "function overrides calling Python methods.\"\"\" return_type = '' if func_decl.cpp_void_return:", "from clif.pybind11 import type_casters from clif.pybind11 import utils I =", "'google3') names[-1] = names[-1][:-len('_clif.h')] module = '.'.join(names) yield f'py::module_::import(\"{module}\");' def", "write_to(channel, lines): \"\"\"Writes the generated code to files.\"\"\" for s", "assert decl.class_.name.cpp_name not in python_override_class_names python_override_class_names[ decl.class_.name.cpp_name] = python_override_class_name yield", "for decl in ast.decls: yield from self._generate_python_override_class_names( python_override_class_names, decl) self._collect_class_cpp_names(decl)", "from CLIF ast.\"\"\" includes = set() for decl in ast.decls:", "v.HasField('cpp_exact_type'): return_type = v.cpp_exact_type params = ', '.join([f'{p.name.cpp_name}' for p", "== ast_pb2.Decl.Type.ENUM: yield from enums.generate_from('m', decl.enum) yield '' yield '}'", "', '.join([f'{p.name.cpp_name}' for p in func_decl.params]) params_list_with_types = [] for", "func_decl.params: params_list_with_types.append( f'{function_lib.generate_param_type(p)} {p.name.cpp_name}') params_str_with_types = ', '.join(params_list_with_types) cpp_const =", "cpp_const = ' const' yield I + (f'{return_type} ' f'{func_decl.name.native}({params_str_with_types})", "if parent_name: full_native_name = '.'.join([parent_name, decl.class_.name.native]) self._unique_classes[decl.class_.name.cpp_name] = full_native_name for", "decl.enum) yield '' yield '}' def _generate_import_modules(self, ast: ast_pb2.AST) ->", "(lang_type in {'int', 'float', 'double', 'bool', 'str'} or lang_type.startswith('tuple<')): const_def", "I + 'py::google::ImportStatusModule();' for decl in ast.decls: if decl.decltype ==", "the License for the specific language governing permissions and #", "ast_pb2.AST, module_name: str, header_path: str, include_paths: List[str]): self._ast = ast", "in decl.class_.members: self._collect_class_cpp_names(member, full_native_name) def write_to(channel, lines): \"\"\"Writes the generated", "this context.\"\"\" if decl.decltype == ast_pb2.Decl.Type.CLASS: full_native_name = decl.class_.name.native if", "Apache License, Version 2.0 (the \"License\"); # you may not", "of virtual functions. python_override_class_names = {} for decl in ast.decls:", "2020 Google LLC # # Licensed under the Apache License,", "'PYBIND11_OVERRIDE_PURE' else: pybind11_override = 'PYBIND11_OVERRIDE' yield I + I +", "either express or implied. # See the License for the", "yield from self._generate_python_override_class_names( python_override_class_names, decl) self._collect_class_cpp_names(decl) yield from type_casters.generate_from(ast, self._include_paths)", "+ I + f'{params}' yield I + I + ');'", "ast.\"\"\" def __init__(self, ast: ast_pb2.AST, module_name: str, header_path: str, include_paths:", "I + ( f'using {decl.class_.name.cpp_name}::{decl.class_.name.native};') for member in virtual_members: yield", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "'\\n' for cpp_name in self._unique_classes: yield f'PYBIND11_SMART_HOLDER_TYPE_CASTERS({cpp_name})' yield '\\n' for", "the License. \"\"\"Generates pybind11 bindings code.\"\"\" from typing import Dict,", "ast: CLIF ast protobuf. Yields: Generated pybind11 bindings code. \"\"\"", "== ast_pb2.Decl.Type.FUNC: for s in function.generate_from('m', decl.func, None): yield I", "from enums.generate_from('m', decl.enum) yield '' yield '}' def _generate_import_modules(self, ast:", "{py_name}' def generate_from(self, ast: ast_pb2.AST): \"\"\"Generates pybind11 bindings code from", "yield I + (f'{return_type} ' f'{func_decl.name.native}({params_str_with_types}) ' f'{cpp_const} override {{')", "+ I + ');' yield I + '}' def _collect_class_cpp_names(self,", "+ (f'{return_type} ' f'{func_decl.name.native}({params_str_with_types}) ' f'{cpp_const} override {{') if func_decl.is_pure_virtual:", "clif.protos import ast_pb2 from clif.pybind11 import classes from clif.pybind11 import", "\"third_party/pybind11/include/pybind11/functional.h\"' yield '#include \"third_party/pybind11/include/pybind11/operators.h\"' yield '#include \"third_party/pybind11/include/pybind11/smart_holder.h\"' yield '// potential", "from clif.protos import ast_pb2 from clif.pybind11 import classes from clif.pybind11", "self_life_support: str = 'py::trampoline_self_life_support'): \"\"\"Generates Python overrides classes dictionary for", "yield I + I + f'{pybind11_override}(' yield I + I", "f'// CLIF use `{cpp_name}` as {py_name}' def generate_from(self, ast: ast_pb2.AST):", "I + I + f'{class_name},' yield I + I +", "in self._unique_classes: yield f'PYBIND11_SMART_HOLDER_TYPE_CASTERS({cpp_name})' yield '\\n' for cpp_name, py_name in", "and member.func.virtual: virtual_members.append(member) if not virtual_members: return python_override_class_name = (", "context.\"\"\" if decl.decltype == ast_pb2.Decl.Type.CLASS: full_native_name = decl.class_.name.native if parent_name:", "name to a set. Only to be used in this", "if (const_decl.type.lang_type.startswith('list<') or const_decl.type.lang_type.startswith('dict<') or const_decl.type.lang_type.startswith('set<')): includes.add('third_party/pybind11/include/pybind11/stl.h') def _generate_const_variables(self, const_decl:", "self._generate_python_override_class_names( python_override_class_names, decl) self._collect_class_cpp_names(decl) yield from type_casters.generate_from(ast, self._include_paths) yield f'PYBIND11_MODULE({self._module_name},", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "decl.decltype == ast_pb2.Decl.Type.FUNC: for s in function.generate_from('m', decl.func, None): yield", "yield I + I + I + f'{class_name},' yield I", "ast_pb2 from clif.pybind11 import classes from clif.pybind11 import enums from", "List[str]): self._ast = ast self._module_name = module_name self._header_path = header_path", "pybind11 bindings code from CLIF ast. Args: ast: CLIF ast", "+ 'py::google::ImportStatusModule();' for decl in ast.decls: if decl.decltype == ast_pb2.Decl.Type.FUNC:", "return_type = '' if func_decl.cpp_void_return: return_type = 'void' elif func_decl.returns:", "'')) elif decl.decltype == ast_pb2.Decl.Type.ENUM: yield from enums.generate_from('m', decl.enum) yield", "= I + (f'm.attr(\"{const_decl.name.native}\") = ' f'{const_decl.name.cpp_name};') else: const_def =", "Python overrides classes dictionary for virtual functions.\"\"\" if decl.decltype ==", "__init__(self, ast: ast_pb2.AST, module_name: str, header_path: str, include_paths: List[str]): self._ast", "yield '#include \"third_party/pybind11/include/pybind11/smart_holder.h\"' for include in includes: yield f'#include \"{include}\"'", "I + I + I + f'{return_type},' yield I +", "I + f'{class_name},' yield I + I + I +", "# limitations under the License. \"\"\"Generates pybind11 bindings code.\"\"\" from", "py = pybind11;' yield '' def _generate_const_variables_headers(self, const_decl: ast_pb2.ConstDecl, includes:", "else: const_def = I + (f'm.attr(\"{const_decl.name.native}\") = ' f'py::cast({const_decl.name.cpp_name});') yield", "f'#include \"{self._header_path}\"' yield '' yield 'namespace py = pybind11;' yield", "yield f'PYBIND11_MODULE({self._module_name}, m) {{' yield from self._generate_import_modules(ast) yield I+('m.doc() =", "member.func) if python_override_class_name: yield '};' def _generate_virtual_function(self, class_name: str, func_decl:", "\"License\"); # you may not use this file except in", "Generator[str, None, None]: \"\"\"Generates pybind11 bindings code from CLIF ast.\"\"\"", "params_list_with_types = [] for p in func_decl.params: params_list_with_types.append( f'{function_lib.generate_param_type(p)} {p.name.cpp_name}')", "yield from enums.generate_from('m', decl.enum) yield '' yield '}' def _generate_import_modules(self,", "+ I + f'{func_decl.name.native},' yield I + I + I", "= python_override_class_name yield (f'struct {python_override_class_name} : ' f'{decl.class_.name.cpp_name}, {self_life_support} {{')", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "import function from clif.pybind11 import function_lib from clif.pybind11 import type_casters", "ast.pybind11_includes: # Converts `full/project/path/cheader_pybind11_clif.h` to # `full.project.path.cheader_pybind11` names = include.split('/')", "names[-1] = names[-1][:-len('_clif.h')] module = '.'.join(names) yield f'py::module_::import(\"{module}\");' def _generate_headlines(self):", "(f'm.attr(\"{const_decl.name.native}\") = ' f'{const_decl.name.cpp_name};') else: const_def = I + (f'm.attr(\"{const_decl.name.native}\")", "# distributed under the License is distributed on an \"AS", "yield '\\n' for cpp_name in self._unique_classes: yield f'PYBIND11_SMART_HOLDER_TYPE_CASTERS({cpp_name})' yield '\\n'", "ast_pb2.Decl.Type.ENUM: yield from enums.generate_from('m', decl.enum) yield '' yield '}' def", "= ' const' yield I + (f'{return_type} ' f'{func_decl.name.native}({params_str_with_types}) '", "from self._generate_import_modules(ast) yield I+('m.doc() = \"CLIF-generated pybind11-based module for '", "\"{include}\"' yield f'#include \"{self._header_path}\"' yield '' yield 'namespace py =", "# Unless required by applicable law or agreed to in", "Text, Set from clif.protos import ast_pb2 from clif.pybind11 import classes", "f'{function_lib.generate_param_type(p)} {p.name.cpp_name}') params_str_with_types = ', '.join(params_list_with_types) cpp_const = '' if", "None: \"\"\"Adds every class name to a set. Only to", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "ast protobuf. Yields: Generated pybind11 bindings code. \"\"\" yield from", "_generate_virtual_function(self, class_name: str, func_decl: ast_pb2.FuncDecl): \"\"\"Generates virtual function overrides calling", "Args: ast: CLIF ast protobuf. Yields: Generated pybind11 bindings code.", "decl.class_.name.native, member.func) if python_override_class_name: yield '};' def _generate_virtual_function(self, class_name: str,", "ast.decls: yield from self._generate_python_override_class_names( python_override_class_names, decl) self._collect_class_cpp_names(decl) yield from type_casters.generate_from(ast,", "code. \"\"\" yield from self._generate_headlines() # Find and keep track", "= '' if func_decl.cpp_void_return: return_type = 'void' elif func_decl.returns: for", "You may obtain a copy of the License at #", "= const_decl.type.lang_type if (lang_type in {'int', 'float', 'double', 'bool', 'str'}", "member in virtual_members: yield from self._generate_virtual_function( decl.class_.name.native, member.func) if python_override_class_name:", "const_decl.type.lang_type.startswith('dict<') or const_decl.type.lang_type.startswith('set<')): includes.add('third_party/pybind11/include/pybind11/stl.h') def _generate_const_variables(self, const_decl: ast_pb2.ConstDecl): \"\"\"Generates variables.\"\"\"", "function from clif.pybind11 import function_lib from clif.pybind11 import type_casters from", "from CLIF ast. Args: ast: CLIF ast protobuf. Yields: Generated", "\"\"\"Generates pybind11 bindings code from CLIF ast. Args: ast: CLIF", "ast: ast_pb2.AST) -> Generator[str, None, None]: \"\"\"Generates pybind11 bindings code", "import enums from clif.pybind11 import function from clif.pybind11 import function_lib", "from clif.pybind11 import function_lib from clif.pybind11 import type_casters from clif.pybind11", "module = '.'.join(names) yield f'py::module_::import(\"{module}\");' def _generate_headlines(self): \"\"\"Generates #includes and", "the Apache License, Version 2.0 (the \"License\"); # you may", "self._generate_virtual_function( decl.class_.name.native, member.func) if python_override_class_name: yield '};' def _generate_virtual_function(self, class_name:", "\"\"\"A class that generates pybind11 bindings code from CLIF ast.\"\"\"", "bindings code from CLIF ast. Args: ast: CLIF ast protobuf.", "_generate_python_override_class_names( self, python_override_class_names: Dict[Text, Text], decl: ast_pb2.Decl, trampoline_name_suffix: str =", "if v.HasField('cpp_exact_type'): return_type = v.cpp_exact_type params = ', '.join([f'{p.name.cpp_name}' for", "virtual function overrides calling Python methods.\"\"\" return_type = '' if", "yield f'#include \"{include}\"' yield '\\n' for cpp_name in self._unique_classes: yield" ]
[ "nn.Conv2d(num_classes, ndf * 4, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True),", "kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 4, ndf *", "ndf=64): # H/8,H/8,(1024 -> 256 -> 128 -> 64 ->", "stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 2, ndf,", "nn.Conv2d(ndf * 4, ndf * 2, kernel_size=1, stride=1, padding=0), #", "nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 2, ndf, kernel_size=1, stride=1, padding=0), #", "4, ndf * 8, kernel_size=4, stride=2, padding=1), # # nn.LeakyReLU(negative_slope=0.2,", "from torch import nn def get_fc_discriminator(num_classes, ndf=64): return nn.Sequential( nn.Conv2d(num_classes,", "4, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 4, ndf", "padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 4, ndf *", "* 4, ndf * 8, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True),", "nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 2, ndf, kernel_size=2, stride=2, padding=0),", "nn.Conv2d(num_classes, ndf, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf,", "kernel_size=4, stride=2, padding=1), ) # def get_fe_discriminator(num_classes, ndf=64): # 256-128-64-32-16", "nn.Conv2d(ndf * 4, 1, kernel_size=1, stride=1, padding=0), # ) def", "nn.Conv2d(ndf * 8, 1, kernel_size=4, stride=2, padding=1), ) # def", "4, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # # nn.Conv2d(ndf", "stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 2, ndf", ") # def get_fe_discriminator(num_classes, ndf=64): # 256-128-64-32-16 # return nn.Sequential(", "inplace=True), nn.Conv2d(ndf * 2, ndf * 4, kernel_size=4, stride=2, padding=1),", "ndf, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf, ndf", "stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 2, ndf * 4,", "kernel_size=1, stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 2,", "nn.Conv2d(ndf * 2, ndf, kernel_size=1, stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2,", "# nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 2, ndf * 4,", "kernel_size=2, stride=2, padding=0), # ) # def get_fe_discriminator(num_classes, ndf=64): #", "padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 2, ndf, kernel_size=2,", "kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 2,", "kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf, ndf *", "2, kernel_size=1, stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf *", "padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # # nn.Conv2d(ndf * 4, ndf", "ndf * 8, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf,", "kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 2, ndf *", "stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 4,", "256-128-64-32-16 # return nn.Sequential( # nn.Conv2d(num_classes, ndf * 4, kernel_size=4,", "# return nn.Sequential( # nn.Conv2d(num_classes, ndf, kernel_size=4, stride=2, padding=1), #", "ndf, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf, ndf * 2,", "ndf * 4, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), #", "nn def get_fc_discriminator(num_classes, ndf=64): return nn.Sequential( nn.Conv2d(num_classes, ndf, kernel_size=4, stride=2,", "inplace=True), # nn.Conv2d(ndf, ndf * 2, kernel_size=4, stride=2, padding=1), #", "padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 4, ndf * 8, kernel_size=4,", "nn.Sequential( # nn.Conv2d(num_classes, ndf, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True),", "# nn.Conv2d(num_classes, ndf, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), #", "ndf * 2, kernel_size=1, stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True),", "# 256-128-64-32-16 # return nn.Sequential( # nn.Conv2d(num_classes, ndf * 4,", "kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf, 1, kernel_size=1, stride=1,", "* 8, 1, kernel_size=4, stride=2, padding=1), ) # def get_fe_discriminator(num_classes,", "# nn.Conv2d(num_classes, ndf * 4, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2,", "kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 4,", "kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 8, 1, kernel_size=4,", "stride=1, padding=0), # ) def get_fe_discriminator(num_classes, ndf=64): # H/8,H/8,(1024 ->", "64 -> 1) return nn.Sequential( nn.Conv2d(num_classes, ndf * 4, kernel_size=1,", "stride=2, padding=1), # # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf, 1, kernel_size=2,", "# x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 4, ndf * 2,", "* 4, 1, kernel_size=1, stride=1, padding=0), # ) def get_fe_discriminator(num_classes,", "# nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 4, ndf * 2,", "def get_fe_discriminator(num_classes, ndf=64): # return nn.Sequential( # nn.Conv2d(num_classes, ndf, kernel_size=4,", "ndf=64): # 256-128-64-32-16 # return nn.Sequential( # nn.Conv2d(num_classes, ndf *", "* 4, ndf * 2, kernel_size=1, stride=1, padding=0), # x=self.dropout(x)", "2, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf *", "nn.Sequential( nn.Conv2d(num_classes, ndf * 4, kernel_size=1, stride=1, padding=0), # x=self.dropout(x)", "padding=1), # # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 4, 1,", "padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 2, ndf, kernel_size=1,", "* 4, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 4,", "stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 4, ndf", "nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf, ndf * 2, kernel_size=4, stride=2, padding=1),", "get_fe_discriminator(num_classes, ndf=64): # 256-128-64-32-16 # return nn.Sequential( # nn.Conv2d(num_classes, ndf", "4, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf *", "kernel_size=2, stride=2, padding=0), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # # nn.Conv2d(ndf *", "stride=2, padding=0), # ) # def get_fe_discriminator(num_classes, ndf=64): # return", "ndf * 8, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf *", "x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 2, ndf, kernel_size=1, stride=1, padding=0),", "4, ndf * 8, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf", "* 2, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf", ") def get_fe_discriminator(num_classes, ndf=64): # H/8,H/8,(1024 -> 256 -> 128", "nn.Conv2d(ndf * 4, ndf * 2, kernel_size=4, stride=2, padding=1), #", "# nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf, ndf * 2, kernel_size=4, stride=2,", "# nn.Conv2d(ndf * 2, ndf, kernel_size=2, stride=2, padding=0), # nn.LeakyReLU(negative_slope=0.2,", "def get_fc_discriminator(num_classes, ndf=64): return nn.Sequential( nn.Conv2d(num_classes, ndf, kernel_size=4, stride=2, padding=1),", "2, ndf, kernel_size=1, stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), #", "get_fe_discriminator(num_classes, ndf=64): # return nn.Sequential( # nn.Conv2d(num_classes, ndf, kernel_size=4, stride=2,", "padding=0), # ) # def get_fe_discriminator(num_classes, ndf=64): # return nn.Sequential(", "* 2, kernel_size=1, stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf", "2, ndf * 4, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf", "padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 2, ndf * 4, kernel_size=4,", "# nn.Conv2d(ndf * 2, ndf * 4, kernel_size=4, stride=2, padding=1),", "inplace=True), nn.Conv2d(ndf * 2, ndf, kernel_size=1, stride=1, padding=0), # x=self.dropout(x)", "ndf * 4, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf *", "nn.Conv2d(ndf, ndf * 2, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True),", "* 2, ndf, kernel_size=1, stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True),", "kernel_size=4, stride=2, padding=1), # # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf *", "# nn.Conv2d(ndf * 4, ndf * 2, kernel_size=4, stride=2, padding=1),", "8, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 8, 1,", "1, kernel_size=2, stride=2, padding=0), # ) # def get_fe_discriminator(num_classes, ndf=64):", "kernel_size=1, stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 4,", "# x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 4, ndf *", "padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf, ndf * 2, kernel_size=4,", "* 8, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 8,", "stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 8, 1, kernel_size=4, stride=2,", "8, kernel_size=4, stride=2, padding=1), # # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf", "padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf, ndf * 2, kernel_size=4, stride=2, padding=1),", "return nn.Sequential( # nn.Conv2d(num_classes, ndf * 4, kernel_size=4, stride=2, padding=1),", "stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf, ndf * 2, kernel_size=4, stride=2,", "-> 64 -> 1) return nn.Sequential( nn.Conv2d(num_classes, ndf * 4,", "-> 128 -> 64 -> 1) return nn.Sequential( nn.Conv2d(num_classes, ndf", "nn.Conv2d(ndf * 4, ndf * 8, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2,", "kernel_size=1, stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf *", "inplace=True), # nn.Conv2d(ndf * 2, ndf * 4, kernel_size=4, stride=2,", ") # def get_fe_discriminator(num_classes, ndf=64): # return nn.Sequential( # nn.Conv2d(num_classes,", "ndf, kernel_size=2, stride=2, padding=0), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # # nn.Conv2d(ndf", "2, ndf, kernel_size=2, stride=2, padding=0), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # #", "padding=0), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # # nn.Conv2d(ndf * 4, ndf", "nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 4, ndf * 2, kernel_size=1, stride=1,", "ndf * 2, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf *", "128 -> 64 -> 1) return nn.Sequential( nn.Conv2d(num_classes, ndf *", "x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 4, ndf * 2, kernel_size=1,", "inplace=True), # nn.Conv2d(ndf, 1, kernel_size=2, stride=2, padding=0), # ) #", "return nn.Sequential( nn.Conv2d(num_classes, ndf, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf,", "nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 2, ndf * 4, kernel_size=4,", "inplace=True), nn.Conv2d(ndf * 4, ndf * 2, kernel_size=1, stride=1, padding=0),", "nn.Conv2d(num_classes, ndf * 4, kernel_size=1, stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2,", "# x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 2, ndf, kernel_size=1, stride=1,", "# return nn.Sequential( # nn.Conv2d(num_classes, ndf * 4, kernel_size=4, stride=2,", "nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 4, ndf * 8, kernel_size=4, stride=2,", "ndf * 2, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), #", "nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 4, ndf * 2, kernel_size=4,", "ndf * 8, kernel_size=4, stride=2, padding=1), # # nn.LeakyReLU(negative_slope=0.2, inplace=True),", "nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf, 1, kernel_size=2, stride=2, padding=0), # )", "# nn.Conv2d(ndf, 1, kernel_size=2, stride=2, padding=0), # ) # def", "4, ndf * 2, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True),", "stride=2, padding=1), ) # def get_fe_discriminator(num_classes, ndf=64): # 256-128-64-32-16 #", "# nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 2, ndf, kernel_size=2, stride=2,", "nn.Conv2d(ndf, 1, kernel_size=2, stride=2, padding=0), # ) # def get_fe_discriminator(num_classes,", "8, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf, 1, kernel_size=1,", "# nn.Conv2d(ndf * 4, 1, kernel_size=1, stride=1, padding=0), # )", "stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # # nn.Conv2d(ndf * 4,", "# # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf, 1, kernel_size=2, stride=2, padding=0),", "# def get_fe_discriminator(num_classes, ndf=64): # 256-128-64-32-16 # return nn.Sequential( #", "* 4, ndf * 2, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2,", "* 8, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf, 1,", "-> 256 -> 128 -> 64 -> 1) return nn.Sequential(", "return nn.Sequential( nn.Conv2d(num_classes, ndf * 4, kernel_size=1, stride=1, padding=0), #", "ndf=64): return nn.Sequential( nn.Conv2d(num_classes, ndf, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True),", "# ) def get_fe_discriminator(num_classes, ndf=64): # H/8,H/8,(1024 -> 256 ->", "def get_fe_discriminator(num_classes, ndf=64): # 256-128-64-32-16 # return nn.Sequential( # nn.Conv2d(num_classes,", "# # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 4, 1, kernel_size=1,", "kernel_size=4, stride=2, padding=1), # # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf, 1,", "* 2, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 2,", "# def get_fe_discriminator(num_classes, ndf=64): # return nn.Sequential( # nn.Conv2d(num_classes, ndf,", "inplace=True), # # nn.Conv2d(ndf * 4, ndf * 8, kernel_size=4,", "4, ndf * 2, kernel_size=1, stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2,", "padding=1), ) # def get_fe_discriminator(num_classes, ndf=64): # 256-128-64-32-16 # return", "* 4, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # #", "nn.Conv2d(ndf * 2, ndf * 4, kernel_size=4, stride=2, padding=1), #", "get_fe_discriminator(num_classes, ndf=64): # H/8,H/8,(1024 -> 256 -> 128 -> 64", "padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf, 1, kernel_size=1, stride=1, padding=0), )", "return nn.Sequential( # nn.Conv2d(num_classes, ndf, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2,", "nn.Conv2d(ndf * 4, ndf * 8, kernel_size=4, stride=2, padding=1), #", "inplace=True), # nn.Conv2d(ndf * 4, 1, kernel_size=1, stride=1, padding=0), #", "2, ndf * 4, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True),", "# nn.LeakyReLU(negative_slope=0.2, inplace=True), # # nn.Conv2d(ndf * 4, ndf *", "* 8, kernel_size=4, stride=2, padding=1), # # nn.LeakyReLU(negative_slope=0.2, inplace=True), #", "# nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf, 1, kernel_size=2, stride=2, padding=0), #", "* 4, ndf * 8, kernel_size=4, stride=2, padding=1), # #", "* 4, kernel_size=1, stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf", "* 2, ndf, kernel_size=2, stride=2, padding=0), # nn.LeakyReLU(negative_slope=0.2, inplace=True), #", "H/8,H/8,(1024 -> 256 -> 128 -> 64 -> 1) return", "8, 1, kernel_size=4, stride=2, padding=1), ) # def get_fe_discriminator(num_classes, ndf=64):", "stride=2, padding=0), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # # nn.Conv2d(ndf * 4,", "x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 4, ndf * 8,", "* 4, ndf * 8, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2,", "# nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 4, 1, kernel_size=1, stride=1,", "# # nn.Conv2d(ndf * 4, ndf * 8, kernel_size=4, stride=2,", "get_fc_discriminator(num_classes, ndf=64): return nn.Sequential( nn.Conv2d(num_classes, ndf, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2,", "nn.LeakyReLU(negative_slope=0.2, inplace=True), # # nn.Conv2d(ndf * 4, ndf * 8,", "kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # # nn.Conv2d(ndf *", "padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 4, ndf *", "inplace=True), nn.Conv2d(ndf * 4, ndf * 8, kernel_size=4, stride=2, padding=1),", "nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 8, 1, kernel_size=4, stride=2, padding=1), )", "stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 2, ndf,", "import nn def get_fc_discriminator(num_classes, ndf=64): return nn.Sequential( nn.Conv2d(num_classes, ndf, kernel_size=4,", "1) return nn.Sequential( nn.Conv2d(num_classes, ndf * 4, kernel_size=1, stride=1, padding=0),", "8, kernel_size=4, stride=2, padding=1), # # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf,", "padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 8, 1, kernel_size=4, stride=2, padding=1),", "inplace=True), # nn.Conv2d(ndf * 2, ndf, kernel_size=2, stride=2, padding=0), #", "stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 4, ndf", "# nn.Conv2d(ndf * 4, ndf * 8, kernel_size=4, stride=2, padding=1),", "1, kernel_size=1, stride=1, padding=0), # ) def get_fe_discriminator(num_classes, ndf=64): #", "nn.Conv2d(ndf * 2, ndf * 4, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2,", "# nn.Conv2d(ndf, ndf * 2, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2,", "stride=2, padding=1), # # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 4,", "nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 4, ndf * 8, kernel_size=4,", "nn.Conv2d(num_classes, ndf, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf, ndf *", "* 4, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf", "inplace=True), # nn.Conv2d(ndf * 4, ndf * 2, kernel_size=4, stride=2,", "ndf=64): # return nn.Sequential( # nn.Conv2d(num_classes, ndf, kernel_size=4, stride=2, padding=1),", "* 2, ndf * 4, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2,", "1, kernel_size=4, stride=2, padding=1), ) # def get_fe_discriminator(num_classes, ndf=64): #", "padding=0), # ) def get_fe_discriminator(num_classes, ndf=64): # H/8,H/8,(1024 -> 256", "-> 1) return nn.Sequential( nn.Conv2d(num_classes, ndf * 4, kernel_size=1, stride=1,", "padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 4, ndf", "stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf, 1, kernel_size=1, stride=1, padding=0),", "nn.Sequential( nn.Conv2d(num_classes, ndf, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf, ndf", "nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 4, 1, kernel_size=1, stride=1, padding=0),", "4, kernel_size=1, stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf *", "stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 4, ndf * 8,", "inplace=True), nn.Conv2d(ndf, ndf * 2, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True),", "kernel_size=1, stride=1, padding=0), # ) def get_fe_discriminator(num_classes, ndf=64): # H/8,H/8,(1024", "nn.Conv2d(ndf * 2, ndf, kernel_size=2, stride=2, padding=0), # nn.LeakyReLU(negative_slope=0.2, inplace=True),", "# H/8,H/8,(1024 -> 256 -> 128 -> 64 -> 1)", "2, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 2, ndf", "padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf * 2, ndf *", "# ) # def get_fe_discriminator(num_classes, ndf=64): # return nn.Sequential( #", "* 2, ndf * 4, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True),", "padding=1), # # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf, 1, kernel_size=2, stride=2,", "4, 1, kernel_size=1, stride=1, padding=0), # ) def get_fe_discriminator(num_classes, ndf=64):", "nn.Sequential( # nn.Conv2d(num_classes, ndf * 4, kernel_size=4, stride=2, padding=1), #", "torch import nn def get_fc_discriminator(num_classes, ndf=64): return nn.Sequential( nn.Conv2d(num_classes, ndf,", "nn.Conv2d(ndf, ndf * 2, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf", "4, ndf * 8, kernel_size=4, stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True),", "inplace=True), # nn.Conv2d(ndf * 4, ndf * 8, kernel_size=4, stride=2,", "256 -> 128 -> 64 -> 1) return nn.Sequential( nn.Conv2d(num_classes,", "def get_fe_discriminator(num_classes, ndf=64): # H/8,H/8,(1024 -> 256 -> 128 ->", "stride=2, padding=1), # nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf, ndf * 2,", "nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf * 2, ndf * 4, kernel_size=4, stride=2,", "ndf * 4, kernel_size=1, stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True),", "inplace=True), nn.Conv2d(ndf * 8, 1, kernel_size=4, stride=2, padding=1), ) #", "nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf, ndf * 2, kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2,", "kernel_size=4, stride=2, padding=1), nn.LeakyReLU(negative_slope=0.2, inplace=True), nn.Conv2d(ndf, ndf * 2, kernel_size=4,", "ndf, kernel_size=1, stride=1, padding=0), # x=self.dropout(x) nn.LeakyReLU(negative_slope=0.2, inplace=True), # nn.Conv2d(ndf" ]
[ "RuntimeError(\"Unkwown dependency %s\" % modname) def status(deps=DEPENDENCIES, linesep=os.linesep): \"\"\"Return a", "OK = 'OK' NOK = 'NOK' def __init__(self, modname, features,", "under the terms of the MIT License # (see spyder/__init__.py", "add(modname, features, required_version, installed_version=None, optional=False): \"\"\"Add Spyder dependency\"\"\" global DEPENDENCIES", "required_version, installed_version=None, optional=False): self.modname = modname self.features = features self.required_version", "features, required_version, installed_version=None, optional=False): \"\"\"Add Spyder dependency\"\"\" global DEPENDENCIES for", "= programs.get_module_version(modname) except: # NOTE: Don't add any exception type", "installed\"\"\" return programs.is_module_installed(self.modname, self.required_version, self.installed_version) def get_installed_version(self): \"\"\"Return dependency status", "optional if installed_version is None: try: self.installed_version = programs.get_module_version(modname) except:", "= 'OK' NOK = 'NOK' def __init__(self, modname, features, required_version,", "else: raise RuntimeError(\"Unkwown dependency %s\" % modname) def status(deps=DEPENDENCIES, linesep=os.linesep):", "return text[:-1] def missing_dependencies(): \"\"\"Return the status of missing dependencies", "text += col1[index].ljust(maxwidth) + ': ' + col2[index] + linesep", "Spyder dependency\"\"\" global DEPENDENCIES for dependency in DEPENDENCIES: if dependency.modname", "programs class Dependency(object): \"\"\"Spyder's dependency version may starts with =,", "class Dependency(object): \"\"\"Spyder's dependency version may starts with =, >=,", "ImportError self.installed_version = None else: self.installed_version = installed_version def check(self):", "None: try: self.installed_version = programs.get_module_version(modname) except: # NOTE: Don't add", "exception type here! # Modules can fail to import in", "\"\" for index in range(len(deps)): text += col1[index].ljust(maxwidth) + ':", "version may starts with =, >=, > or < to", "max([maxwidth, len(title1)]) col2.append(dependency.get_installed_version()) text = \"\" for index in range(len(deps)):", "import os # Local imports from spyder.utils import programs class", "checking Spyder runtime dependencies\"\"\" import os # Local imports from", "has already been registered: %s\"\\ % modname) DEPENDENCIES += [Dependency(modname,", "= \"\" for index in range(len(deps)): text += col1[index].ljust(maxwidth) +", "to import in several ways besides # ImportError self.installed_version =", "-*- coding: utf-8 -*- # # Copyright © Spyder Project", "in DEPENDENCIES: if dependency.modname == modname: return dependency.check() else: raise", "besides # ImportError self.installed_version = None else: self.installed_version = installed_version", "get_installed_version(self): \"\"\"Return dependency status (string)\"\"\" if self.check(): return '%s (%s)'", "maxwidth = 0 col1 = [] col2 = [] for", "=, >=, > or < to specify the exact requirement", "else: return '%s (%s)' % (self.installed_version, self.NOK) def get_status(self): \"\"\"Return", "details) \"\"\"Module checking Spyder runtime dependencies\"\"\" import os # Local", "NOTE: Don't add any exception type here! # Modules can", "= optional if installed_version is None: try: self.installed_version = programs.get_module_version(modname)", "return '%s (%s)' % (self.installed_version, self.NOK) def get_status(self): \"\"\"Return dependency", "already been registered: %s\"\\ % modname) DEPENDENCIES += [Dependency(modname, features,", "if dependency.modname == modname: return dependency.check() else: raise RuntimeError(\"Unkwown dependency", "+ linesep return text[:-1] def missing_dependencies(): \"\"\"Return the status of", "(self.installed_version, self.NOK) def get_status(self): \"\"\"Return dependency status (string)\"\"\" if self.check():", "col2 = [] for dependency in deps: title1 = dependency.modname", "to specify the exact requirement ; multiple conditions may be", "NOK = 'NOK' def __init__(self, modname, features, required_version, installed_version=None, optional=False):", "terms of the MIT License # (see spyder/__init__.py for details)", "+= ' ' + dependency.required_version col1.append(title1) maxwidth = max([maxwidth, len(title1)])", "from spyder.utils import programs class Dependency(object): \"\"\"Spyder's dependency version may", "conditions may be separated by ';' (e.g. '>=0.13;<1.0')\"\"\" OK =", "(%s)' % (self.installed_version, self.NOK) def get_status(self): \"\"\"Return dependency status (string)\"\"\"", "is None: try: self.installed_version = programs.get_module_version(modname) except: # NOTE: Don't", "return '%s (%s)' % (self.installed_version, self.OK) else: return '%s (%s)'", "text = \"\" for index in range(len(deps)): text += col1[index].ljust(maxwidth)", "status of missing dependencies (if any)\"\"\" missing_deps = [] for", "def check(self): \"\"\"Check if dependency is installed\"\"\" return programs.is_module_installed(self.modname, self.required_version,", "DEPENDENCIES: if dependency.modname == modname: raise ValueError(\"Dependency has already been", "return self.OK else: return self.NOK DEPENDENCIES = [] def add(modname,", "in range(len(deps)): text += col1[index].ljust(maxwidth) + ': ' + col2[index]", "self.installed_version = programs.get_module_version(modname) except: # NOTE: Don't add any exception", "\"\"\"Return dependency status (string)\"\"\" if self.check(): return self.OK else: return", "% (self.installed_version, self.NOK) def get_status(self): \"\"\"Return dependency status (string)\"\"\" if", "dependency\"\"\" global DEPENDENCIES for dependency in DEPENDENCIES: if dependency.modname ==", "may starts with =, >=, > or < to specify", "import programs class Dependency(object): \"\"\"Spyder's dependency version may starts with", "License # (see spyder/__init__.py for details) \"\"\"Module checking Spyder runtime", "else: self.installed_version = installed_version def check(self): \"\"\"Check if dependency is", "a status of dependencies\"\"\" maxwidth = 0 col1 = []", "installed_version=None, optional=False): \"\"\"Add Spyder dependency\"\"\" global DEPENDENCIES for dependency in", "self.modname = modname self.features = features self.required_version = required_version self.optional", "dependencies (if any)\"\"\" missing_deps = [] for dependency in DEPENDENCIES:", "in DEPENDENCIES: if dependency.modname == modname: raise ValueError(\"Dependency has already", "': ' + col2[index] + linesep return text[:-1] def missing_dependencies():", "of dependencies\"\"\" maxwidth = 0 col1 = [] col2 =", "status(deps=DEPENDENCIES, linesep=os.linesep): \"\"\"Return a status of dependencies\"\"\" maxwidth = 0", "'OK' NOK = 'NOK' def __init__(self, modname, features, required_version, installed_version=None,", "' ' + dependency.required_version col1.append(title1) maxwidth = max([maxwidth, len(title1)]) col2.append(dependency.get_installed_version())", "installed_version=None, optional=False): self.modname = modname self.features = features self.required_version =", "global DEPENDENCIES for dependency in DEPENDENCIES: if dependency.modname == modname:", "linesep=os.linesep): \"\"\"Return a status of dependencies\"\"\" maxwidth = 0 col1", "= 0 col1 = [] col2 = [] for dependency", "None else: self.installed_version = installed_version def check(self): \"\"\"Check if dependency", "check(self): \"\"\"Check if dependency is installed\"\"\" return programs.is_module_installed(self.modname, self.required_version, self.installed_version)", "[] for dependency in DEPENDENCIES: if not dependency.check() and not", "self.features = features self.required_version = required_version self.optional = optional if", "in deps: title1 = dependency.modname title1 += ' ' +", "def get_status(self): \"\"\"Return dependency status (string)\"\"\" if self.check(): return self.OK", "\"\"\"Return the status of missing dependencies (if any)\"\"\" missing_deps =", "# Local imports from spyder.utils import programs class Dependency(object): \"\"\"Spyder's", "here! # Modules can fail to import in several ways", "[] col2 = [] for dependency in deps: title1 =", "deps: title1 = dependency.modname title1 += ' ' + dependency.required_version", "self.OK else: return self.NOK DEPENDENCIES = [] def add(modname, features,", "(if any)\"\"\" missing_deps = [] for dependency in DEPENDENCIES: if", "the MIT License # (see spyder/__init__.py for details) \"\"\"Module checking", "def __init__(self, modname, features, required_version, installed_version=None, optional=False): self.modname = modname", "dependency.optional: missing_deps.append(dependency) if missing_deps: return status(deps=missing_deps, linesep='<br>') else: return \"\"", "multiple conditions may be separated by ';' (e.g. '>=0.13;<1.0')\"\"\" OK", "not dependency.check() and not dependency.optional: missing_deps.append(dependency) if missing_deps: return status(deps=missing_deps,", "+ dependency.required_version col1.append(title1) maxwidth = max([maxwidth, len(title1)]) col2.append(dependency.get_installed_version()) text =", "== modname: raise ValueError(\"Dependency has already been registered: %s\"\\ %", "with =, >=, > or < to specify the exact", "if required dependency is installed\"\"\" for dependency in DEPENDENCIES: if", "# Copyright © Spyder Project Contributors # Licensed under the", "if dependency.modname == modname: raise ValueError(\"Dependency has already been registered:", "and not dependency.optional: missing_deps.append(dependency) if missing_deps: return status(deps=missing_deps, linesep='<br>') else:", "col1.append(title1) maxwidth = max([maxwidth, len(title1)]) col2.append(dependency.get_installed_version()) text = \"\" for", "-*- # # Copyright © Spyder Project Contributors # Licensed", "any)\"\"\" missing_deps = [] for dependency in DEPENDENCIES: if not", "except: # NOTE: Don't add any exception type here! #", "installed_version, optional)] def check(modname): \"\"\"Check if required dependency is installed\"\"\"", "\"\"\"Module checking Spyder runtime dependencies\"\"\" import os # Local imports", "is installed\"\"\" return programs.is_module_installed(self.modname, self.required_version, self.installed_version) def get_installed_version(self): \"\"\"Return dependency", "by ';' (e.g. '>=0.13;<1.0')\"\"\" OK = 'OK' NOK = 'NOK'", "installed\"\"\" for dependency in DEPENDENCIES: if dependency.modname == modname: return", "check(modname): \"\"\"Check if required dependency is installed\"\"\" for dependency in", "import in several ways besides # ImportError self.installed_version = None", "self.OK) else: return '%s (%s)' % (self.installed_version, self.NOK) def get_status(self):", "\"\"\"Add Spyder dependency\"\"\" global DEPENDENCIES for dependency in DEPENDENCIES: if", "%s\" % modname) def status(deps=DEPENDENCIES, linesep=os.linesep): \"\"\"Return a status of", "if self.check(): return self.OK else: return self.NOK DEPENDENCIES = []", "maxwidth = max([maxwidth, len(title1)]) col2.append(dependency.get_installed_version()) text = \"\" for index", "else: return self.NOK DEPENDENCIES = [] def add(modname, features, required_version,", "programs.get_module_version(modname) except: # NOTE: Don't add any exception type here!", "if dependency is installed\"\"\" return programs.is_module_installed(self.modname, self.required_version, self.installed_version) def get_installed_version(self):", "is installed\"\"\" for dependency in DEPENDENCIES: if dependency.modname == modname:", "% modname) def status(deps=DEPENDENCIES, linesep=os.linesep): \"\"\"Return a status of dependencies\"\"\"", "missing_dependencies(): \"\"\"Return the status of missing dependencies (if any)\"\"\" missing_deps", "'>=0.13;<1.0')\"\"\" OK = 'OK' NOK = 'NOK' def __init__(self, modname,", "modname: raise ValueError(\"Dependency has already been registered: %s\"\\ % modname)", "[Dependency(modname, features, required_version, installed_version, optional)] def check(modname): \"\"\"Check if required", "dependency in DEPENDENCIES: if not dependency.check() and not dependency.optional: missing_deps.append(dependency)", "fail to import in several ways besides # ImportError self.installed_version", "the terms of the MIT License # (see spyder/__init__.py for", "Spyder runtime dependencies\"\"\" import os # Local imports from spyder.utils", "return dependency.check() else: raise RuntimeError(\"Unkwown dependency %s\" % modname) def", "requirement ; multiple conditions may be separated by ';' (e.g.", "col2[index] + linesep return text[:-1] def missing_dependencies(): \"\"\"Return the status", "linesep return text[:-1] def missing_dependencies(): \"\"\"Return the status of missing", "= None else: self.installed_version = installed_version def check(self): \"\"\"Check if", "(self.installed_version, self.OK) else: return '%s (%s)' % (self.installed_version, self.NOK) def", "optional=False): \"\"\"Add Spyder dependency\"\"\" global DEPENDENCIES for dependency in DEPENDENCIES:", "col1[index].ljust(maxwidth) + ': ' + col2[index] + linesep return text[:-1]", "spyder/__init__.py for details) \"\"\"Module checking Spyder runtime dependencies\"\"\" import os", "= modname self.features = features self.required_version = required_version self.optional =", "(string)\"\"\" if self.check(): return '%s (%s)' % (self.installed_version, self.OK) else:", "[] for dependency in deps: title1 = dependency.modname title1 +=", "+ col2[index] + linesep return text[:-1] def missing_dependencies(): \"\"\"Return the", "dependency.required_version col1.append(title1) maxwidth = max([maxwidth, len(title1)]) col2.append(dependency.get_installed_version()) text = \"\"", "runtime dependencies\"\"\" import os # Local imports from spyder.utils import", "Spyder Project Contributors # Licensed under the terms of the", "dependency %s\" % modname) def status(deps=DEPENDENCIES, linesep=os.linesep): \"\"\"Return a status", "the status of missing dependencies (if any)\"\"\" missing_deps = []", "missing_deps = [] for dependency in DEPENDENCIES: if not dependency.check()", "of missing dependencies (if any)\"\"\" missing_deps = [] for dependency", "for dependency in deps: title1 = dependency.modname title1 += '", "title1 = dependency.modname title1 += ' ' + dependency.required_version col1.append(title1)", "\"\"\"Return a status of dependencies\"\"\" maxwidth = 0 col1 =", "# Modules can fail to import in several ways besides", "Copyright © Spyder Project Contributors # Licensed under the terms", "dependency status (string)\"\"\" if self.check(): return '%s (%s)' % (self.installed_version,", "\"\"\"Return dependency status (string)\"\"\" if self.check(): return '%s (%s)' %", "if not dependency.check() and not dependency.optional: missing_deps.append(dependency) if missing_deps: return", "self.required_version = required_version self.optional = optional if installed_version is None:", "modname self.features = features self.required_version = required_version self.optional = optional", "% modname) DEPENDENCIES += [Dependency(modname, features, required_version, installed_version, optional)] def", "may be separated by ';' (e.g. '>=0.13;<1.0')\"\"\" OK = 'OK'", "DEPENDENCIES for dependency in DEPENDENCIES: if dependency.modname == modname: raise", "self.check(): return '%s (%s)' % (self.installed_version, self.OK) else: return '%s", "# NOTE: Don't add any exception type here! # Modules", "DEPENDENCIES: if not dependency.check() and not dependency.optional: missing_deps.append(dependency) if missing_deps:", "self.installed_version = installed_version def check(self): \"\"\"Check if dependency is installed\"\"\"", "self.installed_version = None else: self.installed_version = installed_version def check(self): \"\"\"Check", "= max([maxwidth, len(title1)]) col2.append(dependency.get_installed_version()) text = \"\" for index in", "the exact requirement ; multiple conditions may be separated by", "Modules can fail to import in several ways besides #", "dependency is installed\"\"\" for dependency in DEPENDENCIES: if dependency.modname ==", "= [] col2 = [] for dependency in deps: title1", "> or < to specify the exact requirement ; multiple", "__init__(self, modname, features, required_version, installed_version=None, optional=False): self.modname = modname self.features", "for dependency in DEPENDENCIES: if not dependency.check() and not dependency.optional:", "features, required_version, installed_version=None, optional=False): self.modname = modname self.features = features", "modname: return dependency.check() else: raise RuntimeError(\"Unkwown dependency %s\" % modname)", "self.optional = optional if installed_version is None: try: self.installed_version =", "\"\"\"Spyder's dependency version may starts with =, >=, > or", "def missing_dependencies(): \"\"\"Return the status of missing dependencies (if any)\"\"\"", "Contributors # Licensed under the terms of the MIT License", "title1 += ' ' + dependency.required_version col1.append(title1) maxwidth = max([maxwidth,", "# (see spyder/__init__.py for details) \"\"\"Module checking Spyder runtime dependencies\"\"\"", "os # Local imports from spyder.utils import programs class Dependency(object):", "specify the exact requirement ; multiple conditions may be separated", "DEPENDENCIES += [Dependency(modname, features, required_version, installed_version, optional)] def check(modname): \"\"\"Check", "' + col2[index] + linesep return text[:-1] def missing_dependencies(): \"\"\"Return", "of the MIT License # (see spyder/__init__.py for details) \"\"\"Module", "'NOK' def __init__(self, modname, features, required_version, installed_version=None, optional=False): self.modname =", "self.installed_version) def get_installed_version(self): \"\"\"Return dependency status (string)\"\"\" if self.check(): return", "< to specify the exact requirement ; multiple conditions may", "= installed_version def check(self): \"\"\"Check if dependency is installed\"\"\" return", "dependency.modname == modname: raise ValueError(\"Dependency has already been registered: %s\"\\", "programs.is_module_installed(self.modname, self.required_version, self.installed_version) def get_installed_version(self): \"\"\"Return dependency status (string)\"\"\" if", "DEPENDENCIES: if dependency.modname == modname: return dependency.check() else: raise RuntimeError(\"Unkwown", "type here! # Modules can fail to import in several", "dependency.modname title1 += ' ' + dependency.required_version col1.append(title1) maxwidth =", "ValueError(\"Dependency has already been registered: %s\"\\ % modname) DEPENDENCIES +=", "return self.NOK DEPENDENCIES = [] def add(modname, features, required_version, installed_version=None,", "len(title1)]) col2.append(dependency.get_installed_version()) text = \"\" for index in range(len(deps)): text", "'%s (%s)' % (self.installed_version, self.OK) else: return '%s (%s)' %", "status (string)\"\"\" if self.check(): return '%s (%s)' % (self.installed_version, self.OK)", "Project Contributors # Licensed under the terms of the MIT", "def check(modname): \"\"\"Check if required dependency is installed\"\"\" for dependency", "spyder.utils import programs class Dependency(object): \"\"\"Spyder's dependency version may starts", "= features self.required_version = required_version self.optional = optional if installed_version", "required_version, installed_version, optional)] def check(modname): \"\"\"Check if required dependency is", "+ ': ' + col2[index] + linesep return text[:-1] def", "be separated by ';' (e.g. '>=0.13;<1.0')\"\"\" OK = 'OK' NOK", "def status(deps=DEPENDENCIES, linesep=os.linesep): \"\"\"Return a status of dependencies\"\"\" maxwidth =", "several ways besides # ImportError self.installed_version = None else: self.installed_version", "; multiple conditions may be separated by ';' (e.g. '>=0.13;<1.0')\"\"\"", "index in range(len(deps)): text += col1[index].ljust(maxwidth) + ': ' +", "utf-8 -*- # # Copyright © Spyder Project Contributors #", "modname, features, required_version, installed_version=None, optional=False): self.modname = modname self.features =", "dependency in deps: title1 = dependency.modname title1 += ' '", "col2.append(dependency.get_installed_version()) text = \"\" for index in range(len(deps)): text +=", "= 'NOK' def __init__(self, modname, features, required_version, installed_version=None, optional=False): self.modname", "# # Copyright © Spyder Project Contributors # Licensed under", "raise ValueError(\"Dependency has already been registered: %s\"\\ % modname) DEPENDENCIES", "installed_version def check(self): \"\"\"Check if dependency is installed\"\"\" return programs.is_module_installed(self.modname,", "separated by ';' (e.g. '>=0.13;<1.0')\"\"\" OK = 'OK' NOK =", "for details) \"\"\"Module checking Spyder runtime dependencies\"\"\" import os #", "dependencies\"\"\" import os # Local imports from spyder.utils import programs", "© Spyder Project Contributors # Licensed under the terms of", "features, required_version, installed_version, optional)] def check(modname): \"\"\"Check if required dependency", "% (self.installed_version, self.OK) else: return '%s (%s)' % (self.installed_version, self.NOK)", "dependency.modname == modname: return dependency.check() else: raise RuntimeError(\"Unkwown dependency %s\"", "Dependency(object): \"\"\"Spyder's dependency version may starts with =, >=, >", "dependency version may starts with =, >=, > or <", "[] def add(modname, features, required_version, installed_version=None, optional=False): \"\"\"Add Spyder dependency\"\"\"", "can fail to import in several ways besides # ImportError", "dependency status (string)\"\"\" if self.check(): return self.OK else: return self.NOK", "self.NOK) def get_status(self): \"\"\"Return dependency status (string)\"\"\" if self.check(): return", "dependencies\"\"\" maxwidth = 0 col1 = [] col2 = []", "# Licensed under the terms of the MIT License #", "'%s (%s)' % (self.installed_version, self.NOK) def get_status(self): \"\"\"Return dependency status", ">=, > or < to specify the exact requirement ;", "(see spyder/__init__.py for details) \"\"\"Module checking Spyder runtime dependencies\"\"\" import", "range(len(deps)): text += col1[index].ljust(maxwidth) + ': ' + col2[index] +", "get_status(self): \"\"\"Return dependency status (string)\"\"\" if self.check(): return self.OK else:", "0 col1 = [] col2 = [] for dependency in", "= required_version self.optional = optional if installed_version is None: try:", "coding: utf-8 -*- # # Copyright © Spyder Project Contributors", "registered: %s\"\\ % modname) DEPENDENCIES += [Dependency(modname, features, required_version, installed_version,", "\"\"\"Check if required dependency is installed\"\"\" for dependency in DEPENDENCIES:", "try: self.installed_version = programs.get_module_version(modname) except: # NOTE: Don't add any", "def get_installed_version(self): \"\"\"Return dependency status (string)\"\"\" if self.check(): return '%s", "text[:-1] def missing_dependencies(): \"\"\"Return the status of missing dependencies (if", "ways besides # ImportError self.installed_version = None else: self.installed_version =", "starts with =, >=, > or < to specify the", "= dependency.modname title1 += ' ' + dependency.required_version col1.append(title1) maxwidth", "Local imports from spyder.utils import programs class Dependency(object): \"\"\"Spyder's dependency", "%s\"\\ % modname) DEPENDENCIES += [Dependency(modname, features, required_version, installed_version, optional)]", "';' (e.g. '>=0.13;<1.0')\"\"\" OK = 'OK' NOK = 'NOK' def", "+= [Dependency(modname, features, required_version, installed_version, optional)] def check(modname): \"\"\"Check if", "Don't add any exception type here! # Modules can fail", "been registered: %s\"\\ % modname) DEPENDENCIES += [Dependency(modname, features, required_version,", "required_version, installed_version=None, optional=False): \"\"\"Add Spyder dependency\"\"\" global DEPENDENCIES for dependency", "in several ways besides # ImportError self.installed_version = None else:", "if installed_version is None: try: self.installed_version = programs.get_module_version(modname) except: #", "def add(modname, features, required_version, installed_version=None, optional=False): \"\"\"Add Spyder dependency\"\"\" global", "<reponame>aglotero/spyder # -*- coding: utf-8 -*- # # Copyright ©", "self.check(): return self.OK else: return self.NOK DEPENDENCIES = [] def", "return programs.is_module_installed(self.modname, self.required_version, self.installed_version) def get_installed_version(self): \"\"\"Return dependency status (string)\"\"\"", "== modname: return dependency.check() else: raise RuntimeError(\"Unkwown dependency %s\" %", "= [] for dependency in deps: title1 = dependency.modname title1", "\"\"\"Check if dependency is installed\"\"\" return programs.is_module_installed(self.modname, self.required_version, self.installed_version) def", "+= col1[index].ljust(maxwidth) + ': ' + col2[index] + linesep return", "exact requirement ; multiple conditions may be separated by ';'", "= [] for dependency in DEPENDENCIES: if not dependency.check() and", "in DEPENDENCIES: if not dependency.check() and not dependency.optional: missing_deps.append(dependency) if", "optional)] def check(modname): \"\"\"Check if required dependency is installed\"\"\" for", "for dependency in DEPENDENCIES: if dependency.modname == modname: return dependency.check()", "Licensed under the terms of the MIT License # (see", "missing dependencies (if any)\"\"\" missing_deps = [] for dependency in", "for dependency in DEPENDENCIES: if dependency.modname == modname: raise ValueError(\"Dependency", "features self.required_version = required_version self.optional = optional if installed_version is", "installed_version is None: try: self.installed_version = programs.get_module_version(modname) except: # NOTE:", "(e.g. '>=0.13;<1.0')\"\"\" OK = 'OK' NOK = 'NOK' def __init__(self,", "dependency.check() else: raise RuntimeError(\"Unkwown dependency %s\" % modname) def status(deps=DEPENDENCIES,", "for index in range(len(deps)): text += col1[index].ljust(maxwidth) + ': '", "any exception type here! # Modules can fail to import", "# ImportError self.installed_version = None else: self.installed_version = installed_version def", "dependency is installed\"\"\" return programs.is_module_installed(self.modname, self.required_version, self.installed_version) def get_installed_version(self): \"\"\"Return", "(%s)' % (self.installed_version, self.OK) else: return '%s (%s)' % (self.installed_version,", "(string)\"\"\" if self.check(): return self.OK else: return self.NOK DEPENDENCIES =", "# -*- coding: utf-8 -*- # # Copyright © Spyder", "' + dependency.required_version col1.append(title1) maxwidth = max([maxwidth, len(title1)]) col2.append(dependency.get_installed_version()) text", "not dependency.optional: missing_deps.append(dependency) if missing_deps: return status(deps=missing_deps, linesep='<br>') else: return", "add any exception type here! # Modules can fail to", "modname) DEPENDENCIES += [Dependency(modname, features, required_version, installed_version, optional)] def check(modname):", "modname) def status(deps=DEPENDENCIES, linesep=os.linesep): \"\"\"Return a status of dependencies\"\"\" maxwidth", "dependency.check() and not dependency.optional: missing_deps.append(dependency) if missing_deps: return status(deps=missing_deps, linesep='<br>')", "raise RuntimeError(\"Unkwown dependency %s\" % modname) def status(deps=DEPENDENCIES, linesep=os.linesep): \"\"\"Return", "MIT License # (see spyder/__init__.py for details) \"\"\"Module checking Spyder", "= [] def add(modname, features, required_version, installed_version=None, optional=False): \"\"\"Add Spyder", "self.required_version, self.installed_version) def get_installed_version(self): \"\"\"Return dependency status (string)\"\"\" if self.check():", "status of dependencies\"\"\" maxwidth = 0 col1 = [] col2", "or < to specify the exact requirement ; multiple conditions", "col1 = [] col2 = [] for dependency in deps:", "dependency in DEPENDENCIES: if dependency.modname == modname: return dependency.check() else:", "if self.check(): return '%s (%s)' % (self.installed_version, self.OK) else: return", "self.NOK DEPENDENCIES = [] def add(modname, features, required_version, installed_version=None, optional=False):", "DEPENDENCIES = [] def add(modname, features, required_version, installed_version=None, optional=False): \"\"\"Add", "required_version self.optional = optional if installed_version is None: try: self.installed_version", "imports from spyder.utils import programs class Dependency(object): \"\"\"Spyder's dependency version", "status (string)\"\"\" if self.check(): return self.OK else: return self.NOK DEPENDENCIES", "dependency in DEPENDENCIES: if dependency.modname == modname: raise ValueError(\"Dependency has", "required dependency is installed\"\"\" for dependency in DEPENDENCIES: if dependency.modname", "optional=False): self.modname = modname self.features = features self.required_version = required_version" ]
[ "'Demo': 'http://chemprop.csail.mit.edu/', }, license='MIT', packages=find_packages(), package_data={'chemprop': ['py.typed']}, entry_points={ 'console_scripts': [", "install_requires=[ 'flask>=1.1.2', 'hyperopt>=0.2.3', 'matplotlib>=3.1.3', 'numpy>=1.18.1', 'pandas>=1.0.3', 'pandas-flavor>=0.2.0', 'scikit-learn>=0.22.2.post1', 'scipy>=1.4.1', 'sphinx>=3.1.2',", "extras_require={ 'test': [ 'pytest>=6.2.2', 'parameterized>=0.8.1' ] }, python_requires='>=3.6', classifiers=[ 'Programming", "Approved :: MIT License', 'Operating System :: OS Independent' ],", "version=__version__, author='<NAME>, <NAME>, <NAME>, <NAME>, <NAME>', author_email='<EMAIL>', description='Molecular Property Prediction", ":: MIT License', 'Operating System :: OS Independent' ], keywords=[", "from setuptools import find_packages, setup # Load version number __version__", "long_description = f.read() setup( name='chemprop', version=__version__, author='<NAME>, <NAME>, <NAME>, <NAME>,", "Message Passing Neural Networks', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/chemprop/chemprop', download_url=f'https://github.com/chemprop/chemprop/v_{__version__}.tar.gz', project_urls={ 'Documentation':", ":: Python :: 3.6', 'Programming Language :: Python :: 3.7',", "as f: long_description = f.read() setup( name='chemprop', version=__version__, author='<NAME>, <NAME>,", "'Programming Language :: Python :: 3.8', 'License :: OSI Approved", "'tqdm>=4.45.0', 'typed-argument-parser>=1.6.1' ], extras_require={ 'test': [ 'pytest>=6.2.2', 'parameterized>=0.8.1' ] },", "import os from setuptools import find_packages, setup # Load version", "'parameterized>=0.8.1' ] }, python_requires='>=3.6', classifiers=[ 'Programming Language :: Python ::", "'_version.py') with open(version_file, encoding='utf-8') as fd: exec(fd.read()) # Load README", "Language :: Python :: 3.8', 'License :: OSI Approved ::", "package_data={'chemprop': ['py.typed']}, entry_points={ 'console_scripts': [ 'chemprop_train=chemprop.train:chemprop_train', 'chemprop_predict=chemprop.train:chemprop_predict', 'chemprop_fingerprint=chemprop.train:chemprop_fingerprint', 'chemprop_hyperopt=chemprop.hyperparameter_optimization:chemprop_hyperopt', 'chemprop_interpret=chemprop.interpret:chemprop_interpret',", "author='<NAME>, <NAME>, <NAME>, <NAME>, <NAME>', author_email='<EMAIL>', description='Molecular Property Prediction with", "'tensorboardX>=2.0', 'torch>=1.5.1', 'tqdm>=4.45.0', 'typed-argument-parser>=1.6.1' ], extras_require={ 'test': [ 'pytest>=6.2.2', 'parameterized>=0.8.1'", "'https://pypi.org/project/chemprop/', 'Demo': 'http://chemprop.csail.mit.edu/', }, license='MIT', packages=find_packages(), package_data={'chemprop': ['py.typed']}, entry_points={ 'console_scripts':", "'torch>=1.5.1', 'tqdm>=4.45.0', 'typed-argument-parser>=1.6.1' ], extras_require={ 'test': [ 'pytest>=6.2.2', 'parameterized>=0.8.1' ]", "Language :: Python :: 3', 'Programming Language :: Python ::", "'https://github.com/chemprop/chemprop', 'PyPi': 'https://pypi.org/project/chemprop/', 'Demo': 'http://chemprop.csail.mit.edu/', }, license='MIT', packages=find_packages(), package_data={'chemprop': ['py.typed']},", "'chemprop_fingerprint=chemprop.train:chemprop_fingerprint', 'chemprop_hyperopt=chemprop.hyperparameter_optimization:chemprop_hyperopt', 'chemprop_interpret=chemprop.interpret:chemprop_interpret', 'chemprop_web=chemprop.web.run:chemprop_web', 'sklearn_train=chemprop.sklearn_train:sklearn_train', 'sklearn_predict=chemprop.sklearn_predict:sklearn_predict', ] }, install_requires=[ 'flask>=1.1.2',", "f: long_description = f.read() setup( name='chemprop', version=__version__, author='<NAME>, <NAME>, <NAME>,", "version_file = os.path.join(src_dir, 'chemprop', '_version.py') with open(version_file, encoding='utf-8') as fd:", "version number __version__ = None src_dir = os.path.abspath(os.path.dirname(__file__)) version_file =", "setup # Load version number __version__ = None src_dir =", "<NAME>', author_email='<EMAIL>', description='Molecular Property Prediction with Message Passing Neural Networks',", "'PyPi': 'https://pypi.org/project/chemprop/', 'Demo': 'http://chemprop.csail.mit.edu/', }, license='MIT', packages=find_packages(), package_data={'chemprop': ['py.typed']}, entry_points={", "learning', 'property prediction', 'message passing neural network', 'graph neural network'", "Property Prediction with Message Passing Neural Networks', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/chemprop/chemprop',", "number __version__ = None src_dir = os.path.abspath(os.path.dirname(__file__)) version_file = os.path.join(src_dir,", "'chemprop_train=chemprop.train:chemprop_train', 'chemprop_predict=chemprop.train:chemprop_predict', 'chemprop_fingerprint=chemprop.train:chemprop_fingerprint', 'chemprop_hyperopt=chemprop.hyperparameter_optimization:chemprop_hyperopt', 'chemprop_interpret=chemprop.interpret:chemprop_interpret', 'chemprop_web=chemprop.web.run:chemprop_web', 'sklearn_train=chemprop.sklearn_train:sklearn_train', 'sklearn_predict=chemprop.sklearn_predict:sklearn_predict', ] },", "MIT License', 'Operating System :: OS Independent' ], keywords=[ 'chemistry',", "'property prediction', 'message passing neural network', 'graph neural network' ]", "'https://chemprop.readthedocs.io/en/latest/', 'Source': 'https://github.com/chemprop/chemprop', 'PyPi': 'https://pypi.org/project/chemprop/', 'Demo': 'http://chemprop.csail.mit.edu/', }, license='MIT', packages=find_packages(),", "'pytest>=6.2.2', 'parameterized>=0.8.1' ] }, python_requires='>=3.6', classifiers=[ 'Programming Language :: Python", "keywords=[ 'chemistry', 'machine learning', 'property prediction', 'message passing neural network',", "['py.typed']}, entry_points={ 'console_scripts': [ 'chemprop_train=chemprop.train:chemprop_train', 'chemprop_predict=chemprop.train:chemprop_predict', 'chemprop_fingerprint=chemprop.train:chemprop_fingerprint', 'chemprop_hyperopt=chemprop.hyperparameter_optimization:chemprop_hyperopt', 'chemprop_interpret=chemprop.interpret:chemprop_interpret', 'chemprop_web=chemprop.web.run:chemprop_web',", "}, python_requires='>=3.6', classifiers=[ 'Programming Language :: Python :: 3', 'Programming", "'scikit-learn>=0.22.2.post1', 'scipy>=1.4.1', 'sphinx>=3.1.2', 'tensorboardX>=2.0', 'torch>=1.5.1', 'tqdm>=4.45.0', 'typed-argument-parser>=1.6.1' ], extras_require={ 'test':", "os.path.join(src_dir, 'chemprop', '_version.py') with open(version_file, encoding='utf-8') as fd: exec(fd.read()) #", "classifiers=[ 'Programming Language :: Python :: 3', 'Programming Language ::", "'sphinx>=3.1.2', 'tensorboardX>=2.0', 'torch>=1.5.1', 'tqdm>=4.45.0', 'typed-argument-parser>=1.6.1' ], extras_require={ 'test': [ 'pytest>=6.2.2',", "Language :: Python :: 3.6', 'Programming Language :: Python ::", "description='Molecular Property Prediction with Message Passing Neural Networks', long_description=long_description, long_description_content_type='text/markdown',", "name='chemprop', version=__version__, author='<NAME>, <NAME>, <NAME>, <NAME>, <NAME>', author_email='<EMAIL>', description='Molecular Property", "'scipy>=1.4.1', 'sphinx>=3.1.2', 'tensorboardX>=2.0', 'torch>=1.5.1', 'tqdm>=4.45.0', 'typed-argument-parser>=1.6.1' ], extras_require={ 'test': [", "setup( name='chemprop', version=__version__, author='<NAME>, <NAME>, <NAME>, <NAME>, <NAME>', author_email='<EMAIL>', description='Molecular", "'pandas>=1.0.3', 'pandas-flavor>=0.2.0', 'scikit-learn>=0.22.2.post1', 'scipy>=1.4.1', 'sphinx>=3.1.2', 'tensorboardX>=2.0', 'torch>=1.5.1', 'tqdm>=4.45.0', 'typed-argument-parser>=1.6.1' ],", "python_requires='>=3.6', classifiers=[ 'Programming Language :: Python :: 3', 'Programming Language", "Python :: 3.8', 'License :: OSI Approved :: MIT License',", "author_email='<EMAIL>', description='Molecular Property Prediction with Message Passing Neural Networks', long_description=long_description,", "'chemprop_predict=chemprop.train:chemprop_predict', 'chemprop_fingerprint=chemprop.train:chemprop_fingerprint', 'chemprop_hyperopt=chemprop.hyperparameter_optimization:chemprop_hyperopt', 'chemprop_interpret=chemprop.interpret:chemprop_interpret', 'chemprop_web=chemprop.web.run:chemprop_web', 'sklearn_train=chemprop.sklearn_train:sklearn_train', 'sklearn_predict=chemprop.sklearn_predict:sklearn_predict', ] }, install_requires=[", "long_description_content_type='text/markdown', url='https://github.com/chemprop/chemprop', download_url=f'https://github.com/chemprop/chemprop/v_{__version__}.tar.gz', project_urls={ 'Documentation': 'https://chemprop.readthedocs.io/en/latest/', 'Source': 'https://github.com/chemprop/chemprop', 'PyPi': 'https://pypi.org/project/chemprop/',", "<NAME>, <NAME>, <NAME>, <NAME>', author_email='<EMAIL>', description='Molecular Property Prediction with Message", "'chemprop_interpret=chemprop.interpret:chemprop_interpret', 'chemprop_web=chemprop.web.run:chemprop_web', 'sklearn_train=chemprop.sklearn_train:sklearn_train', 'sklearn_predict=chemprop.sklearn_predict:sklearn_predict', ] }, install_requires=[ 'flask>=1.1.2', 'hyperopt>=0.2.3', 'matplotlib>=3.1.3',", ":: 3', 'Programming Language :: Python :: 3.6', 'Programming Language", "setuptools import find_packages, setup # Load version number __version__ =", "__version__ = None src_dir = os.path.abspath(os.path.dirname(__file__)) version_file = os.path.join(src_dir, 'chemprop',", "project_urls={ 'Documentation': 'https://chemprop.readthedocs.io/en/latest/', 'Source': 'https://github.com/chemprop/chemprop', 'PyPi': 'https://pypi.org/project/chemprop/', 'Demo': 'http://chemprop.csail.mit.edu/', },", "license='MIT', packages=find_packages(), package_data={'chemprop': ['py.typed']}, entry_points={ 'console_scripts': [ 'chemprop_train=chemprop.train:chemprop_train', 'chemprop_predict=chemprop.train:chemprop_predict', 'chemprop_fingerprint=chemprop.train:chemprop_fingerprint',", ":: Python :: 3.7', 'Programming Language :: Python :: 3.8',", "fd: exec(fd.read()) # Load README with open('README.md', encoding='utf-8') as f:", "3', 'Programming Language :: Python :: 3.6', 'Programming Language ::", "<NAME>, <NAME>', author_email='<EMAIL>', description='Molecular Property Prediction with Message Passing Neural", "'matplotlib>=3.1.3', 'numpy>=1.18.1', 'pandas>=1.0.3', 'pandas-flavor>=0.2.0', 'scikit-learn>=0.22.2.post1', 'scipy>=1.4.1', 'sphinx>=3.1.2', 'tensorboardX>=2.0', 'torch>=1.5.1', 'tqdm>=4.45.0',", "encoding='utf-8') as fd: exec(fd.read()) # Load README with open('README.md', encoding='utf-8')", "Independent' ], keywords=[ 'chemistry', 'machine learning', 'property prediction', 'message passing", "'chemprop_hyperopt=chemprop.hyperparameter_optimization:chemprop_hyperopt', 'chemprop_interpret=chemprop.interpret:chemprop_interpret', 'chemprop_web=chemprop.web.run:chemprop_web', 'sklearn_train=chemprop.sklearn_train:sklearn_train', 'sklearn_predict=chemprop.sklearn_predict:sklearn_predict', ] }, install_requires=[ 'flask>=1.1.2', 'hyperopt>=0.2.3',", "[ 'pytest>=6.2.2', 'parameterized>=0.8.1' ] }, python_requires='>=3.6', classifiers=[ 'Programming Language ::", "with open(version_file, encoding='utf-8') as fd: exec(fd.read()) # Load README with", "# Load README with open('README.md', encoding='utf-8') as f: long_description =", "'Programming Language :: Python :: 3.6', 'Programming Language :: Python", "OSI Approved :: MIT License', 'Operating System :: OS Independent'", ":: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language", "OS Independent' ], keywords=[ 'chemistry', 'machine learning', 'property prediction', 'message", "open('README.md', encoding='utf-8') as f: long_description = f.read() setup( name='chemprop', version=__version__,", "exec(fd.read()) # Load README with open('README.md', encoding='utf-8') as f: long_description", "'chemprop_web=chemprop.web.run:chemprop_web', 'sklearn_train=chemprop.sklearn_train:sklearn_train', 'sklearn_predict=chemprop.sklearn_predict:sklearn_predict', ] }, install_requires=[ 'flask>=1.1.2', 'hyperopt>=0.2.3', 'matplotlib>=3.1.3', 'numpy>=1.18.1',", "'pandas-flavor>=0.2.0', 'scikit-learn>=0.22.2.post1', 'scipy>=1.4.1', 'sphinx>=3.1.2', 'tensorboardX>=2.0', 'torch>=1.5.1', 'tqdm>=4.45.0', 'typed-argument-parser>=1.6.1' ], extras_require={", "}, license='MIT', packages=find_packages(), package_data={'chemprop': ['py.typed']}, entry_points={ 'console_scripts': [ 'chemprop_train=chemprop.train:chemprop_train', 'chemprop_predict=chemprop.train:chemprop_predict',", ":: Python :: 3', 'Programming Language :: Python :: 3.6',", "= os.path.abspath(os.path.dirname(__file__)) version_file = os.path.join(src_dir, 'chemprop', '_version.py') with open(version_file, encoding='utf-8')", "src_dir = os.path.abspath(os.path.dirname(__file__)) version_file = os.path.join(src_dir, 'chemprop', '_version.py') with open(version_file,", "License', 'Operating System :: OS Independent' ], keywords=[ 'chemistry', 'machine", "Networks', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/chemprop/chemprop', download_url=f'https://github.com/chemprop/chemprop/v_{__version__}.tar.gz', project_urls={ 'Documentation': 'https://chemprop.readthedocs.io/en/latest/', 'Source': 'https://github.com/chemprop/chemprop',", "3.7', 'Programming Language :: Python :: 3.8', 'License :: OSI", "'Programming Language :: Python :: 3', 'Programming Language :: Python", "}, install_requires=[ 'flask>=1.1.2', 'hyperopt>=0.2.3', 'matplotlib>=3.1.3', 'numpy>=1.18.1', 'pandas>=1.0.3', 'pandas-flavor>=0.2.0', 'scikit-learn>=0.22.2.post1', 'scipy>=1.4.1',", "], extras_require={ 'test': [ 'pytest>=6.2.2', 'parameterized>=0.8.1' ] }, python_requires='>=3.6', classifiers=[", "with open('README.md', encoding='utf-8') as f: long_description = f.read() setup( name='chemprop',", "3.8', 'License :: OSI Approved :: MIT License', 'Operating System", "= os.path.join(src_dir, 'chemprop', '_version.py') with open(version_file, encoding='utf-8') as fd: exec(fd.read())", ":: OSI Approved :: MIT License', 'Operating System :: OS", "Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming", "encoding='utf-8') as f: long_description = f.read() setup( name='chemprop', version=__version__, author='<NAME>,", "[ 'chemprop_train=chemprop.train:chemprop_train', 'chemprop_predict=chemprop.train:chemprop_predict', 'chemprop_fingerprint=chemprop.train:chemprop_fingerprint', 'chemprop_hyperopt=chemprop.hyperparameter_optimization:chemprop_hyperopt', 'chemprop_interpret=chemprop.interpret:chemprop_interpret', 'chemprop_web=chemprop.web.run:chemprop_web', 'sklearn_train=chemprop.sklearn_train:sklearn_train', 'sklearn_predict=chemprop.sklearn_predict:sklearn_predict', ]", ":: Python :: 3.8', 'License :: OSI Approved :: MIT", "System :: OS Independent' ], keywords=[ 'chemistry', 'machine learning', 'property", "'Documentation': 'https://chemprop.readthedocs.io/en/latest/', 'Source': 'https://github.com/chemprop/chemprop', 'PyPi': 'https://pypi.org/project/chemprop/', 'Demo': 'http://chemprop.csail.mit.edu/', }, license='MIT',", "Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming", "long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/chemprop/chemprop', download_url=f'https://github.com/chemprop/chemprop/v_{__version__}.tar.gz', project_urls={ 'Documentation': 'https://chemprop.readthedocs.io/en/latest/', 'Source': 'https://github.com/chemprop/chemprop', 'PyPi':", "'sklearn_train=chemprop.sklearn_train:sklearn_train', 'sklearn_predict=chemprop.sklearn_predict:sklearn_predict', ] }, install_requires=[ 'flask>=1.1.2', 'hyperopt>=0.2.3', 'matplotlib>=3.1.3', 'numpy>=1.18.1', 'pandas>=1.0.3',", "3.6', 'Programming Language :: Python :: 3.7', 'Programming Language ::", "'flask>=1.1.2', 'hyperopt>=0.2.3', 'matplotlib>=3.1.3', 'numpy>=1.18.1', 'pandas>=1.0.3', 'pandas-flavor>=0.2.0', 'scikit-learn>=0.22.2.post1', 'scipy>=1.4.1', 'sphinx>=3.1.2', 'tensorboardX>=2.0',", "'hyperopt>=0.2.3', 'matplotlib>=3.1.3', 'numpy>=1.18.1', 'pandas>=1.0.3', 'pandas-flavor>=0.2.0', 'scikit-learn>=0.22.2.post1', 'scipy>=1.4.1', 'sphinx>=3.1.2', 'tensorboardX>=2.0', 'torch>=1.5.1',", "= None src_dir = os.path.abspath(os.path.dirname(__file__)) version_file = os.path.join(src_dir, 'chemprop', '_version.py')", "'http://chemprop.csail.mit.edu/', }, license='MIT', packages=find_packages(), package_data={'chemprop': ['py.typed']}, entry_points={ 'console_scripts': [ 'chemprop_train=chemprop.train:chemprop_train',", "'chemistry', 'machine learning', 'property prediction', 'message passing neural network', 'graph", "open(version_file, encoding='utf-8') as fd: exec(fd.read()) # Load README with open('README.md',", "packages=find_packages(), package_data={'chemprop': ['py.typed']}, entry_points={ 'console_scripts': [ 'chemprop_train=chemprop.train:chemprop_train', 'chemprop_predict=chemprop.train:chemprop_predict', 'chemprop_fingerprint=chemprop.train:chemprop_fingerprint', 'chemprop_hyperopt=chemprop.hyperparameter_optimization:chemprop_hyperopt',", "download_url=f'https://github.com/chemprop/chemprop/v_{__version__}.tar.gz', project_urls={ 'Documentation': 'https://chemprop.readthedocs.io/en/latest/', 'Source': 'https://github.com/chemprop/chemprop', 'PyPi': 'https://pypi.org/project/chemprop/', 'Demo': 'http://chemprop.csail.mit.edu/',", "os.path.abspath(os.path.dirname(__file__)) version_file = os.path.join(src_dir, 'chemprop', '_version.py') with open(version_file, encoding='utf-8') as", "# Load version number __version__ = None src_dir = os.path.abspath(os.path.dirname(__file__))", ":: 3.7', 'Programming Language :: Python :: 3.8', 'License ::", ":: OS Independent' ], keywords=[ 'chemistry', 'machine learning', 'property prediction',", "as fd: exec(fd.read()) # Load README with open('README.md', encoding='utf-8') as", "'sklearn_predict=chemprop.sklearn_predict:sklearn_predict', ] }, install_requires=[ 'flask>=1.1.2', 'hyperopt>=0.2.3', 'matplotlib>=3.1.3', 'numpy>=1.18.1', 'pandas>=1.0.3', 'pandas-flavor>=0.2.0',", "'Programming Language :: Python :: 3.7', 'Programming Language :: Python", "'chemprop', '_version.py') with open(version_file, encoding='utf-8') as fd: exec(fd.read()) # Load", "Language :: Python :: 3.7', 'Programming Language :: Python ::", "README with open('README.md', encoding='utf-8') as f: long_description = f.read() setup(", "'numpy>=1.18.1', 'pandas>=1.0.3', 'pandas-flavor>=0.2.0', 'scikit-learn>=0.22.2.post1', 'scipy>=1.4.1', 'sphinx>=3.1.2', 'tensorboardX>=2.0', 'torch>=1.5.1', 'tqdm>=4.45.0', 'typed-argument-parser>=1.6.1'", "Python :: 3.7', 'Programming Language :: Python :: 3.8', 'License", "'License :: OSI Approved :: MIT License', 'Operating System ::", ":: 3.8', 'License :: OSI Approved :: MIT License', 'Operating", "= f.read() setup( name='chemprop', version=__version__, author='<NAME>, <NAME>, <NAME>, <NAME>, <NAME>',", "'Operating System :: OS Independent' ], keywords=[ 'chemistry', 'machine learning',", "Load README with open('README.md', encoding='utf-8') as f: long_description = f.read()", "Passing Neural Networks', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/chemprop/chemprop', download_url=f'https://github.com/chemprop/chemprop/v_{__version__}.tar.gz', project_urls={ 'Documentation': 'https://chemprop.readthedocs.io/en/latest/',", "os from setuptools import find_packages, setup # Load version number", "] }, python_requires='>=3.6', classifiers=[ 'Programming Language :: Python :: 3',", "Prediction with Message Passing Neural Networks', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/chemprop/chemprop', download_url=f'https://github.com/chemprop/chemprop/v_{__version__}.tar.gz',", "'console_scripts': [ 'chemprop_train=chemprop.train:chemprop_train', 'chemprop_predict=chemprop.train:chemprop_predict', 'chemprop_fingerprint=chemprop.train:chemprop_fingerprint', 'chemprop_hyperopt=chemprop.hyperparameter_optimization:chemprop_hyperopt', 'chemprop_interpret=chemprop.interpret:chemprop_interpret', 'chemprop_web=chemprop.web.run:chemprop_web', 'sklearn_train=chemprop.sklearn_train:sklearn_train', 'sklearn_predict=chemprop.sklearn_predict:sklearn_predict',", "'test': [ 'pytest>=6.2.2', 'parameterized>=0.8.1' ] }, python_requires='>=3.6', classifiers=[ 'Programming Language", "'typed-argument-parser>=1.6.1' ], extras_require={ 'test': [ 'pytest>=6.2.2', 'parameterized>=0.8.1' ] }, python_requires='>=3.6',", "Load version number __version__ = None src_dir = os.path.abspath(os.path.dirname(__file__)) version_file", "<NAME>, <NAME>, <NAME>', author_email='<EMAIL>', description='Molecular Property Prediction with Message Passing", "None src_dir = os.path.abspath(os.path.dirname(__file__)) version_file = os.path.join(src_dir, 'chemprop', '_version.py') with", "prediction', 'message passing neural network', 'graph neural network' ] )", "Neural Networks', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/chemprop/chemprop', download_url=f'https://github.com/chemprop/chemprop/v_{__version__}.tar.gz', project_urls={ 'Documentation': 'https://chemprop.readthedocs.io/en/latest/', 'Source':", "find_packages, setup # Load version number __version__ = None src_dir", "] }, install_requires=[ 'flask>=1.1.2', 'hyperopt>=0.2.3', 'matplotlib>=3.1.3', 'numpy>=1.18.1', 'pandas>=1.0.3', 'pandas-flavor>=0.2.0', 'scikit-learn>=0.22.2.post1',", "url='https://github.com/chemprop/chemprop', download_url=f'https://github.com/chemprop/chemprop/v_{__version__}.tar.gz', project_urls={ 'Documentation': 'https://chemprop.readthedocs.io/en/latest/', 'Source': 'https://github.com/chemprop/chemprop', 'PyPi': 'https://pypi.org/project/chemprop/', 'Demo':", "entry_points={ 'console_scripts': [ 'chemprop_train=chemprop.train:chemprop_train', 'chemprop_predict=chemprop.train:chemprop_predict', 'chemprop_fingerprint=chemprop.train:chemprop_fingerprint', 'chemprop_hyperopt=chemprop.hyperparameter_optimization:chemprop_hyperopt', 'chemprop_interpret=chemprop.interpret:chemprop_interpret', 'chemprop_web=chemprop.web.run:chemprop_web', 'sklearn_train=chemprop.sklearn_train:sklearn_train',", "'machine learning', 'property prediction', 'message passing neural network', 'graph neural", "import find_packages, setup # Load version number __version__ = None", "with Message Passing Neural Networks', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/chemprop/chemprop', download_url=f'https://github.com/chemprop/chemprop/v_{__version__}.tar.gz', project_urls={", "], keywords=[ 'chemistry', 'machine learning', 'property prediction', 'message passing neural", "'Source': 'https://github.com/chemprop/chemprop', 'PyPi': 'https://pypi.org/project/chemprop/', 'Demo': 'http://chemprop.csail.mit.edu/', }, license='MIT', packages=find_packages(), package_data={'chemprop':", "f.read() setup( name='chemprop', version=__version__, author='<NAME>, <NAME>, <NAME>, <NAME>, <NAME>', author_email='<EMAIL>'," ]
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "__init__(self, slices=None, dtype=None, sparse=False, **kw): super().__init__(_slices=slices, _dtype=dtype, _sparse=sparse, **kw) @property", "if inp is None or inp.order == TensorOrder.C_ORDER: return TensorOrder.C_ORDER", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "2.0 (the \"License\"); # you may not use this file", "agreed to in writing, software # distributed under the License", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Unless required by applicable law or agreed to in writing,", "inp = get_array_module(inp).array(inp) x = inp[tuple(op.slices)] out = op.outputs[0] ctx[out.key]", "ListField from ..operands import TensorHasInput, TensorOperandMixin from ..array_utils import get_array_module", "in zip(inp.shape, self._slices): if slc is None: continue s =", "inp = self.input if inp is None or inp.order ==", "distributed under the License is distributed on an \"AS IS\"", "continue else: return TensorOrder.C_ORDER return inp.order return order[i] if isinstance(order,", "**kw) @property def slices(self): return self._slices def _set_inputs(self, inputs): super()._set_inputs(inputs)", "slc is None: continue s = slc.indices(shape) if s[0] ==", "is None: continue s = slc.indices(shape) if s[0] == 0", "TensorOperandMixin): _op_type_ = OperandDef.SLICE _input = KeyField('input') _slices = ListField('slices')", "None or inp.order == TensorOrder.C_ORDER: return TensorOrder.C_ORDER for shape, slc", "opcodes as OperandDef from ...serialize import KeyField, ListField from ..operands", "class TensorSlice(TensorHasInput, TensorOperandMixin): _op_type_ = OperandDef.SLICE _input = KeyField('input') _slices", "the specific language governing permissions and # limitations under the", "and s[1] == shape and s[2] == 1: continue else:", "return TensorOrder.C_ORDER return inp.order return order[i] if isinstance(order, (list, tuple))", "(list, tuple)) else order @classmethod def execute(cls, ctx, op): inp", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "= self._inputs[0] def _get_order(self, kw, i): order = kw.pop('order', None)", "tuple)) else order @classmethod def execute(cls, ctx, op): inp =", "ctx, op): inp = ctx[op.inputs[0].key] if op.input.ndim == 0 and", "scalar, but organize it into an array inp = get_array_module(inp).array(inp)", "..core import TensorOrder class TensorSlice(TensorHasInput, TensorOperandMixin): _op_type_ = OperandDef.SLICE _input", "i): order = kw.pop('order', None) if order is None: inp", "is None or inp.order == TensorOrder.C_ORDER: return TensorOrder.C_ORDER for shape,", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", "= ListField('slices') def __init__(self, slices=None, dtype=None, sparse=False, **kw): super().__init__(_slices=slices, _dtype=dtype,", "if order is None: inp = self.input if inp is", "except in compliance with the License. # You may obtain", "TensorOrder class TensorSlice(TensorHasInput, TensorOperandMixin): _op_type_ = OperandDef.SLICE _input = KeyField('input')", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "return TensorOrder.C_ORDER for shape, slc in zip(inp.shape, self._slices): if slc", "self._inputs[0] def _get_order(self, kw, i): order = kw.pop('order', None) if", "order = kw.pop('order', None) if order is None: inp =", "ctx[op.inputs[0].key] if op.input.ndim == 0 and not hasattr(inp, 'shape'): #", "slc.indices(shape) if s[0] == 0 and s[1] == shape and", "slices=None, dtype=None, sparse=False, **kw): super().__init__(_slices=slices, _dtype=dtype, _sparse=sparse, **kw) @property def", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "not use this file except in compliance with the License.", "== 1: continue else: return TensorOrder.C_ORDER return inp.order return order[i]", "None: continue s = slc.indices(shape) if s[0] == 0 and", "from ... import opcodes as OperandDef from ...serialize import KeyField,", "KeyField('input') _slices = ListField('slices') def __init__(self, slices=None, dtype=None, sparse=False, **kw):", "an array inp = get_array_module(inp).array(inp) x = inp[tuple(op.slices)] out =", "dtype=None, sparse=False, **kw): super().__init__(_slices=slices, _dtype=dtype, _sparse=sparse, **kw) @property def slices(self):", "TensorHasInput, TensorOperandMixin from ..array_utils import get_array_module from ..core import TensorOrder", "writing, software # distributed under the License is distributed on", "in writing, software # distributed under the License is distributed", "= slc.indices(shape) if s[0] == 0 and s[1] == shape", "under the License. from ... import opcodes as OperandDef from", "Ltd. # # Licensed under the Apache License, Version 2.0", "you may not use this file except in compliance with", "TensorOperandMixin from ..array_utils import get_array_module from ..core import TensorOrder class", "@classmethod def execute(cls, ctx, op): inp = ctx[op.inputs[0].key] if op.input.ndim", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "language governing permissions and # limitations under the License. from", "and not hasattr(inp, 'shape'): # scalar, but organize it into", "order is None: inp = self.input if inp is None", "get_array_module(inp).array(inp) x = inp[tuple(op.slices)] out = op.outputs[0] ctx[out.key] = x.astype(x.dtype,", "import KeyField, ListField from ..operands import TensorHasInput, TensorOperandMixin from ..array_utils", "use this file except in compliance with the License. #", "from ..array_utils import get_array_module from ..core import TensorOrder class TensorSlice(TensorHasInput,", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "_op_type_ = OperandDef.SLICE _input = KeyField('input') _slices = ListField('slices') def", "sparse=False, **kw): super().__init__(_slices=slices, _dtype=dtype, _sparse=sparse, **kw) @property def slices(self): return", "zip(inp.shape, self._slices): if slc is None: continue s = slc.indices(shape)", "_sparse=sparse, **kw) @property def slices(self): return self._slices def _set_inputs(self, inputs):", "return inp.order return order[i] if isinstance(order, (list, tuple)) else order", "permissions and # limitations under the License. from ... import", "= kw.pop('order', None) if order is None: inp = self.input", "CONDITIONS OF ANY KIND, either express or implied. # See", "and s[2] == 1: continue else: return TensorOrder.C_ORDER return inp.order", "= ctx[op.inputs[0].key] if op.input.ndim == 0 and not hasattr(inp, 'shape'):", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "import get_array_module from ..core import TensorOrder class TensorSlice(TensorHasInput, TensorOperandMixin): _op_type_", "super()._set_inputs(inputs) self._input = self._inputs[0] def _get_order(self, kw, i): order =", "== shape and s[2] == 1: continue else: return TensorOrder.C_ORDER", "s[1] == shape and s[2] == 1: continue else: return", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "if op.input.ndim == 0 and not hasattr(inp, 'shape'): # scalar,", "inp.order == TensorOrder.C_ORDER: return TensorOrder.C_ORDER for shape, slc in zip(inp.shape,", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "# You may obtain a copy of the License at", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "return order[i] if isinstance(order, (list, tuple)) else order @classmethod def", "continue s = slc.indices(shape) if s[0] == 0 and s[1]", "under the License is distributed on an \"AS IS\" BASIS,", "s[2] == 1: continue else: return TensorOrder.C_ORDER return inp.order return", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "License for the specific language governing permissions and # limitations", "is None: inp = self.input if inp is None or", "_get_order(self, kw, i): order = kw.pop('order', None) if order is", "as OperandDef from ...serialize import KeyField, ListField from ..operands import", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "inp = ctx[op.inputs[0].key] if op.input.ndim == 0 and not hasattr(inp,", "ListField('slices') def __init__(self, slices=None, dtype=None, sparse=False, **kw): super().__init__(_slices=slices, _dtype=dtype, _sparse=sparse,", "= get_array_module(inp).array(inp) x = inp[tuple(op.slices)] out = op.outputs[0] ctx[out.key] =", "...serialize import KeyField, ListField from ..operands import TensorHasInput, TensorOperandMixin from", "def __init__(self, slices=None, dtype=None, sparse=False, **kw): super().__init__(_slices=slices, _dtype=dtype, _sparse=sparse, **kw)", "0 and not hasattr(inp, 'shape'): # scalar, but organize it", "TensorSlice(TensorHasInput, TensorOperandMixin): _op_type_ = OperandDef.SLICE _input = KeyField('input') _slices =", "inp is None or inp.order == TensorOrder.C_ORDER: return TensorOrder.C_ORDER for", "the License for the specific language governing permissions and #", "governing permissions and # limitations under the License. from ...", "(the \"License\"); # you may not use this file except", "Apache License, Version 2.0 (the \"License\"); # you may not", "else order @classmethod def execute(cls, ctx, op): inp = ctx[op.inputs[0].key]", "@property def slices(self): return self._slices def _set_inputs(self, inputs): super()._set_inputs(inputs) self._input", "# you may not use this file except in compliance", "kw, i): order = kw.pop('order', None) if order is None:", "either express or implied. # See the License for the", "kw.pop('order', None) if order is None: inp = self.input if", "= self.input if inp is None or inp.order == TensorOrder.C_ORDER:", "Copyright 1999-2020 Alibaba Group Holding Ltd. # # Licensed under", "x = inp[tuple(op.slices)] out = op.outputs[0] ctx[out.key] = x.astype(x.dtype, order=out.order.value,", "OR CONDITIONS OF ANY KIND, either express or implied. #", "organize it into an array inp = get_array_module(inp).array(inp) x =", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "== 0 and not hasattr(inp, 'shape'): # scalar, but organize", "License. from ... import opcodes as OperandDef from ...serialize import", "the License is distributed on an \"AS IS\" BASIS, #", "OperandDef.SLICE _input = KeyField('input') _slices = ListField('slices') def __init__(self, slices=None,", "import opcodes as OperandDef from ...serialize import KeyField, ListField from", "hasattr(inp, 'shape'): # scalar, but organize it into an array", "in compliance with the License. # You may obtain a", "def execute(cls, ctx, op): inp = ctx[op.inputs[0].key] if op.input.ndim ==", "KeyField, ListField from ..operands import TensorHasInput, TensorOperandMixin from ..array_utils import", "software # distributed under the License is distributed on an", "s = slc.indices(shape) if s[0] == 0 and s[1] ==", "None: inp = self.input if inp is None or inp.order", "_slices = ListField('slices') def __init__(self, slices=None, dtype=None, sparse=False, **kw): super().__init__(_slices=slices,", "Holding Ltd. # # Licensed under the Apache License, Version", "# # Unless required by applicable law or agreed to", "TensorOrder.C_ORDER return inp.order return order[i] if isinstance(order, (list, tuple)) else", "array inp = get_array_module(inp).array(inp) x = inp[tuple(op.slices)] out = op.outputs[0]", "execute(cls, ctx, op): inp = ctx[op.inputs[0].key] if op.input.ndim == 0", "OperandDef from ...serialize import KeyField, ListField from ..operands import TensorHasInput,", "== 0 and s[1] == shape and s[2] == 1:", "from ..core import TensorOrder class TensorSlice(TensorHasInput, TensorOperandMixin): _op_type_ = OperandDef.SLICE", "_dtype=dtype, _sparse=sparse, **kw) @property def slices(self): return self._slices def _set_inputs(self,", "== TensorOrder.C_ORDER: return TensorOrder.C_ORDER for shape, slc in zip(inp.shape, self._slices):", "get_array_module from ..core import TensorOrder class TensorSlice(TensorHasInput, TensorOperandMixin): _op_type_ =", "it into an array inp = get_array_module(inp).array(inp) x = inp[tuple(op.slices)]", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "super().__init__(_slices=slices, _dtype=dtype, _sparse=sparse, **kw) @property def slices(self): return self._slices def", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "Alibaba Group Holding Ltd. # # Licensed under the Apache", "Version 2.0 (the \"License\"); # you may not use this", "TensorOrder.C_ORDER: return TensorOrder.C_ORDER for shape, slc in zip(inp.shape, self._slices): if", "op): inp = ctx[op.inputs[0].key] if op.input.ndim == 0 and not", "'shape'): # scalar, but organize it into an array inp", "..array_utils import get_array_module from ..core import TensorOrder class TensorSlice(TensorHasInput, TensorOperandMixin):", "law or agreed to in writing, software # distributed under", "self.input if inp is None or inp.order == TensorOrder.C_ORDER: return", "return self._slices def _set_inputs(self, inputs): super()._set_inputs(inputs) self._input = self._inputs[0] def", "limitations under the License. from ... import opcodes as OperandDef", "but organize it into an array inp = get_array_module(inp).array(inp) x", "# scalar, but organize it into an array inp =", "def _get_order(self, kw, i): order = kw.pop('order', None) if order", "None) if order is None: inp = self.input if inp", "1999-2020 Alibaba Group Holding Ltd. # # Licensed under the", "inp.order return order[i] if isinstance(order, (list, tuple)) else order @classmethod", "shape and s[2] == 1: continue else: return TensorOrder.C_ORDER return", "**kw): super().__init__(_slices=slices, _dtype=dtype, _sparse=sparse, **kw) @property def slices(self): return self._slices", "implied. # See the License for the specific language governing", "or inp.order == TensorOrder.C_ORDER: return TensorOrder.C_ORDER for shape, slc in", "self._input = self._inputs[0] def _get_order(self, kw, i): order = kw.pop('order',", "under the Apache License, Version 2.0 (the \"License\"); # you", "from ..operands import TensorHasInput, TensorOperandMixin from ..array_utils import get_array_module from", "not hasattr(inp, 'shape'): # scalar, but organize it into an", "\"License\"); # you may not use this file except in", "isinstance(order, (list, tuple)) else order @classmethod def execute(cls, ctx, op):", "if s[0] == 0 and s[1] == shape and s[2]", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "the License. from ... import opcodes as OperandDef from ...serialize", "if slc is None: continue s = slc.indices(shape) if s[0]", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "# limitations under the License. from ... import opcodes as", "slices(self): return self._slices def _set_inputs(self, inputs): super()._set_inputs(inputs) self._input = self._inputs[0]", "self._slices def _set_inputs(self, inputs): super()._set_inputs(inputs) self._input = self._inputs[0] def _get_order(self,", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "... import opcodes as OperandDef from ...serialize import KeyField, ListField", "import TensorOrder class TensorSlice(TensorHasInput, TensorOperandMixin): _op_type_ = OperandDef.SLICE _input =", "0 and s[1] == shape and s[2] == 1: continue", "else: return TensorOrder.C_ORDER return inp.order return order[i] if isinstance(order, (list,", "_input = KeyField('input') _slices = ListField('slices') def __init__(self, slices=None, dtype=None,", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "def slices(self): return self._slices def _set_inputs(self, inputs): super()._set_inputs(inputs) self._input =", "to in writing, software # distributed under the License is", "TensorOrder.C_ORDER for shape, slc in zip(inp.shape, self._slices): if slc is", "import TensorHasInput, TensorOperandMixin from ..array_utils import get_array_module from ..core import", "inputs): super()._set_inputs(inputs) self._input = self._inputs[0] def _get_order(self, kw, i): order", "1: continue else: return TensorOrder.C_ORDER return inp.order return order[i] if", "# Copyright 1999-2020 Alibaba Group Holding Ltd. # # Licensed", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "# See the License for the specific language governing permissions", "slc in zip(inp.shape, self._slices): if slc is None: continue s", "self._slices): if slc is None: continue s = slc.indices(shape) if", "order[i] if isinstance(order, (list, tuple)) else order @classmethod def execute(cls,", "= KeyField('input') _slices = ListField('slices') def __init__(self, slices=None, dtype=None, sparse=False,", "You may obtain a copy of the License at #", "for shape, slc in zip(inp.shape, self._slices): if slc is None:", "if isinstance(order, (list, tuple)) else order @classmethod def execute(cls, ctx,", "..operands import TensorHasInput, TensorOperandMixin from ..array_utils import get_array_module from ..core", "def _set_inputs(self, inputs): super()._set_inputs(inputs) self._input = self._inputs[0] def _get_order(self, kw,", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "from ...serialize import KeyField, ListField from ..operands import TensorHasInput, TensorOperandMixin", "shape, slc in zip(inp.shape, self._slices): if slc is None: continue", "Group Holding Ltd. # # Licensed under the Apache License,", "required by applicable law or agreed to in writing, software", "= OperandDef.SLICE _input = KeyField('input') _slices = ListField('slices') def __init__(self,", "op.input.ndim == 0 and not hasattr(inp, 'shape'): # scalar, but", "= inp[tuple(op.slices)] out = op.outputs[0] ctx[out.key] = x.astype(x.dtype, order=out.order.value, copy=False)", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "with the License. # You may obtain a copy of", "this file except in compliance with the License. # You", "and # limitations under the License. from ... import opcodes", "the Apache License, Version 2.0 (the \"License\"); # you may", "s[0] == 0 and s[1] == shape and s[2] ==", "into an array inp = get_array_module(inp).array(inp) x = inp[tuple(op.slices)] out", "order @classmethod def execute(cls, ctx, op): inp = ctx[op.inputs[0].key] if", "_set_inputs(self, inputs): super()._set_inputs(inputs) self._input = self._inputs[0] def _get_order(self, kw, i):" ]
[ "DoctestScope)) @property def futuresAllowed(self): if not all(isinstance(scope, ModuleScope) for scope", "self.deferAssignment(checkUnusedAssignments) if PY32: def checkReturnWithArgumentInsideGenerator(): \"\"\" Check to see if", "= all_binding # Look for imported names that aren't used.", "'parent'): n, n_child = n.parent, n if isinstance(n, LOOP_TYPES): #", "= 'generators'.find else: key_first = 'value'.find return tuple(sorted(fields, key=key_first, reverse=True))", "other): if isinstance(other, SubmoduleImportation): # See note in SubmoduleImportation about", "time this is called will be restored, however it will", "elif isinstance(field, list): for item in field: yield item def", "self.exceptHandlers.append(handler_names) for child in node.body: self.handleNode(child, node) self.exceptHandlers.pop() # Process", "a simple string, creates a local that is only bound", "if not name: return in_generators = None importStarred = None", "= property(lambda s: s.decorators) from pyflakes import messages if PY2:", "[]: self.report(messages.AssertTuple, node) self.handleChildren(node) def GLOBAL(self, node): \"\"\" Keep track", "if hasattr(node, 'id'): # One of the many nodes with", "processed. if (self.withDoctest and not self._in_doctest() and not isinstance(self.scope, FunctionScope)):", "node.value and hasattr(self.scope, 'returnValue') and not self.scope.returnValue ): self.scope.returnValue =", "in enumerate(node.handlers): if isinstance(handler.type, ast.Tuple): for exc_type in handler.type.elts: handler_names.append(getNodeName(exc_type))", "fields = node_class._fields if 'iter' in fields: key_first = 'iter'.find", "= node.keys[key_index] if isinstance(key, VariableKey): self.report(messages.MultiValueRepeatedKeyVariable, key_node, key.name) else: self.report(", "implementation of collections.Counter. Required as 2.6 does not have Counter", "(not source or isinstance(source, ast.Import)) package_name = name.split('.')[0] super(SubmoduleImportation, self).__init__(package_name,", "also imported. Python does not restrict which attributes of the", "isinstance(binding, StarImportation): binding.used = all_binding # Look for imported names", "# the top module scope (not OK) n = node", "in node.decorator_list: self.handleNode(deco, node) self.LAMBDA(node) self.addBinding(node, FunctionDefinition(node.name, node)) # doctest", "within a doctest # classes within classes are processed. if", "!= node.parent and not self.isLiteralTupleUnpacking(parent_stmt)): binding = Binding(name, node) elif", "= True self.handleNode(node.value, node) AWAIT = YIELDFROM = YIELD def", "all items of fields that are lists of nodes. \"\"\"", "deco in node.decorator_list: self.handleNode(deco, node) self.LAMBDA(node) self.addBinding(node, FunctionDefinition(node.name, node)) #", "binding created by an C{__all__} assignment. If the names in", "assignments. self._deferredAssignments = None del self.scopeStack[1:] self.popScope() self.checkDeadScopes() def deferFunction(self,", "UnhandledKeyType(object): \"\"\" A dictionary key of a type that we", "name as an argument. \"\"\" class Assignment(Binding): \"\"\" Represents binding", "isinstance(existing, Importation) and isinstance(parent_stmt, ast.For): self.report(messages.ImportShadowedByLoopVar, node, value.name, existing.source) elif", "False # set to True when import * is found", ">= 3.3 if hasattr(n, 'finalbody') and isinstance(node, ast.Continue): if n_child", "Python code. @ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements", "for i in item.elts) elif isinstance(item, ast.Num): return item.n elif", "= scope.get('__all__') if all_binding and not isinstance(all_binding, ExportBinding): all_binding =", "annotations.append(arg.annotation) defaults = node.args.defaults + node.args.kw_defaults # Only for Python3", "*args, **kwargs): self.messages.append(messageClass(self.filename, *args, **kwargs)) def getParent(self, node): # Lookup", "- 1 >= 1 << 24: self.report(messages.TooManyExpressionsInStarredAssignment, node) self.handleChildren(node) LIST", "return self.getCommonAncestor(lnode.parent, rnode, stop) if (lnode.depth < rnode.depth): return self.getCommonAncestor(lnode,", "in items: results[item] = results.get(item, 0) + 1 return results", "callables in C{deferred} using their associated scope stack. \"\"\" for", "lnode, rnode, stop): if stop in (lnode, rnode) or not", "statement in global scope. if self.scope is not global_scope: #", "members if isinstance(scope, ClassScope): continue all_binding = scope.get('__all__') if all_binding", "used[0] is self.scope and name not in self.scope.globals: # then", "self.handleDoctests(node)) for stmt in node.body: self.handleNode(stmt, node) self.popScope() self.addBinding(node, ClassDefinition(node.name,", "ast.TryExcept): return [n.body + n.orelse] + [[hdl] for hdl in", "return False def differentForks(self, lnode, rnode): \"\"\"True, if lnode and", "+ (e.offset or 0)) self.report(messages.DoctestSyntaxError, node, position) else: self.offset =", "# incorrect if there are empty lines between the beginning", "self).__init__(name, source) def redefines(self, other): if isinstance(other, SubmoduleImportation): # See", "isinstance(scope, ClassScope): continue all_binding = scope.get('__all__') if all_binding and not", "UndefinedLocal warnings. self.handleNode(node.target, node) self.handleNode(node.annotation, node) if node.value: # If", "popScope(self): self.deadScopes.append(self.scopeStack.pop()) def checkDeadScopes(self): \"\"\" Look at scopes which have", "node.lineno - node.s.count('\\n') - 1 return (node.s, doctest_lineno) def handleNode(self,", "more than 1<<8 # assignments are allowed before a stared", "`True` if node is part of a conditional body. \"\"\"", "node, but # a simple string, creates a local that", "isinstance(node.test, ast.Tuple) and node.test.elts != []: self.report(messages.AssertTuple, node) self.handleChildren(node) def", "each scope binding.used = (self.scope, node) from_list.append(binding.fullName) # report *", "empty lines between the beginning # of the function and", "an # \"undefined name\" error raised if the checked code", "here anyway has_starred = False star_loc = -1 for i,", "= handler = getattr(self, nodeType) return handler def handleNodeLoad(self, node):", "__str__(self): return self.fullName @property def source_statement(self): return 'import ' +", "sys PY2 = sys.version_info < (3, 0) PY32 = sys.version_info", "in n.handlers] else: def getAlternatives(n): if isinstance(n, ast.If): return [n.body]", "for any Assignment that isn't used. Also, the checker does", "if there are duplicate keys with different values # If", "binding.source, name) self.deferAssignment(checkUnusedAssignments) if PY32: def checkReturnWithArgumentInsideGenerator(): \"\"\" Check to", "not wildcard: continue args.append(wildcard if PY33 else wildcard.arg) if is_py3_func:", "Locate the name in locals / function / globals scopes.", "a doctest.\"\"\" # Globally defined names which are not attributes", "return node.name class Checker(object): \"\"\" I check the cleanliness and", "(self.fullName, self.name) else: return 'import %s' % self.fullName def __str__(self):", "for handling function bodies, which must be deferred because code", "value.name in self.scope: # then assume the rebound name is", "node.name is None: self.handleChildren(node) return # 3.x: the name of", "Process the other nodes: \"except:\", \"else:\", \"finally:\" self.handleChildren(node, omit='body') TRYEXCEPT", "name with alias.\"\"\" if self._has_alias(): return self.fullName + ' as", "name not in self.globals and not self.usesLocals and isinstance(binding, Assignment)):", "is without an 'as' clause. pyflakes handles this case by", "examples: return # Place doctest in module scope saved_stack =", "isinstance(other, Definition) and self.name == other.name def _has_alias(self): \"\"\"Return whether", "that can be recognized is one which takes the value", "traceTree = False builtIns = set(builtin_vars).union(_MAGIC_GLOBALS) _customBuiltIns = os.environ.get('PYFLAKES_BUILTINS') if", "of a value to a name. The checker uses this", "[] if isinstance(source.value, (ast.List, ast.Tuple)): for node in source.value.elts: if", "containing literal strings. For example:: __all__ = [\"foo\", \"bar\"] Names", "* is a SyntaxWarning if not PY2 and not isinstance(self.scope,", "= { 'True': True, 'False': False, 'None': None, } return", "name self.redefined = [] super(Importation, self).__init__(name, source) def redefines(self, other):", "+ self.real_name super(ImportationFrom, self).__init__(name, source, full_name) def __str__(self): \"\"\"Return import", "if any(count == 1 for value, count in values.items()): for", "arguments but the function is a generator. \"\"\" if self.scope.isGenerator", "is_name_previously_defined: # See discussion on https://github.com/PyCQA/pyflakes/pull/59 # We're removing the", "!= node_name] # Bind name to global scope if it", "The only C{__all__} assignment that can be recognized is one", "more # than two. break has_starred = True star_loc =", "keys = [ convert_to_value(key) for key in node.keys ] key_counts", "MULT = DIV = MOD = POW = LSHIFT =", "# Bind name to non-global scopes, but as already \"used\".", "before a stared expression. There is # also a limit", "in _fields_order[node.__class__]: if name == omit: continue field = getattr(node,", "definition. Additionally, add its name to the current scope. \"\"\"", "dict.__repr__(self)) class ClassScope(Scope): pass class FunctionScope(Scope): \"\"\" I represent a", "source): # A dot should only appear in the name", "if self._has_alias(): return self.fullName + ' as ' + self.name", "return [n.body + n.orelse] + [[hdl] for hdl in n.handlers]", "class GeneratorScope(Scope): pass class ModuleScope(Scope): \"\"\"Scope for a module.\"\"\" _futures_allowed", "def getAlternatives(n): if isinstance(n, (ast.If, ast.TryFinally)): return [n.body] if isinstance(n,", "import '*' as used by the undefined in __all__ if", "self.offset = offset handler() def _in_doctest(self): return (len(self.scopeStack) >= 2", "a load/store/delete access.) \"\"\" # Locate the name in locals", "'id'): # One of the many nodes with an id", "\"exec\", ast.PyCF_ONLY_AST) except SyntaxError: e = sys.exc_info()[1] if PYPY: e.offset", "run through the deferred functions. self._deferredFunctions = None self.runDeferred(self._deferredAssignments) #", "any return statement with arguments but the function is a", "# Handle Try/TryFinally difference in Python < and >= 3.3", "= SubmoduleImportation(alias.name, node) else: name = alias.asname or alias.name importation", "name since it's being unbound # after leaving the except:", "PY2: for keywordNode in node.keywords: self.handleNode(keywordNode, node) self.pushScope(ClassScope) # doctest", "source): self.name = name self.source = source self.used = False", "is only used when the submodule import is without an", "= IN = NOTIN = \\ MATMULT = ignore #", "after we've run through the deferred assignments. self._deferredAssignments = None", "or scope.importStarred if in_generators is not False: in_generators = isinstance(scope,", "in self.scopeStack[:-1]: if not isinstance(scope, (FunctionScope, ModuleScope)): continue # if", "elif name == '__all__' and isinstance(self.scope, ModuleScope): binding = ExportBinding(name,", "self.nodeDepth + 'end ' + node.__class__.__name__) _getDoctestExamples = doctest.DocTestParser().get_examples def", "if not hasattr(child, 'elts'): return False return True def isDocstring(self,", "used: messg = messages.UnusedImport self.report(messg, value.source, str(value)) for node in", "importStarred: from_list = [] for scope in self.scopeStack[-1::-1]: for binding", "modify the global scope. When `callable` is called, the scope", "'_' in self.builtIns if not underscore_in_builtins: self.builtIns.add('_') for example in", "= \\ EQ = NOTEQ = LT = LTE =", "\"\"\" Represents binding a name with an explicit assignment. The", "3.3 uses ast.Try instead of (ast.TryExcept + ast.TryFinally) if PY32:", "may be used. This class is only used when the", "ast.comprehension))): self.report(messages.RedefinedInListComp, node, value.name, existing.source) elif not existing.used and value.redefines(existing):", "value.name in scope: break existing = scope.get(value.name) if existing and", "examples: try: tree = compile(example.source, \"<doctest>\", \"exec\", ast.PyCF_ONLY_AST) except SyntaxError:", "for baseNode in node.bases: self.handleNode(baseNode, node) if not PY2: for", "have Counter in collections. \"\"\" results = {} for item", "\"\"\" Determine if the given node is a docstring, as", "deemed imported self.name = name + '.*' self.fullName = name", "getNodeName(node) if not name: return in_generators = None importStarred =", "`callable` is called, the scope at the time this is", "addArgs(node.args.args) defaults = node.args.defaults else: for arg in node.args.args +", "the name in locals / function / globals scopes. if", "only used when the submodule import is without an 'as'", "# # Unless it's been removed already. Then do nothing.", "for key in node.keys ] key_counts = counter(keys) duplicate_keys =", "to global scope if it doesn't exist already. global_scope.setdefault(node_name, node_value)", "node.names: name = alias.asname or alias.name if node.module == '__future__':", "self.offset)) def runDeferred(self, deferred): \"\"\" Run the callables in C{deferred}", "about RedefinedWhileUnused return self.fullName == other.fullName return isinstance(other, Definition) and", "are empty lines between the beginning # of the function", "def getAlternatives(n): if isinstance(n, ast.If): return [n.body] if isinstance(n, ast.Try):", "Set _deferredAssignments to None so that deferAssignment will fail #", "in scope.values(): if isinstance(binding, StarImportation): binding.used = all_binding # Look", "in scope.values(): if isinstance(value, Importation): used = value.used or value.name", "self.alwaysUsed.copy() self.returnValue = None # First non-empty return self.isGenerator =", "3.2 PY33 = sys.version_info < (3, 4) # Python 2.5", "\"\"\" current = getattr(node, 'parent', None) while current: if isinstance(current,", "def checkReturnWithArgumentInsideGenerator(): \"\"\" Check to see if there is any", "is also the same, to avoid false positives. \"\"\" def", "contain any new bindings added to it. \"\"\" self._deferredFunctions.append((callable, self.scopeStack[:],", "# are only present on some platforms. _MAGIC_GLOBALS = ['__file__',", "mistakes in the export list for name in undefined: self.report(messages.UndefinedExport,", "names in the list can be determined statically, they will", "(not OK), for 'continue', a finally block (not OK), or", "{ 'True': True, 'False': False, 'None': None, } return constants_lookup.get(", "if node.value: # Only bind the *targets* if the assignment", "name in args: self.addBinding(node, Argument(name, node)) if isinstance(node.body, list): #", "if (lnode.depth > rnode.depth): return self.getCommonAncestor(lnode.parent, rnode, stop) if (lnode.depth", "= FORMATTEDVALUE = JOINEDSTR = handleChildren def DICT(self, node): #", "Computed incorrectly if the docstring has backslash doctest_lineno = node.lineno", "the first parent which is not Tuple, List or Starred", "self.name) else: return 'import %s' % self.fullName def __str__(self): \"\"\"Return", "a special case where the root module is implicitly imported,", "deferAssignment(self, callable): \"\"\" Schedule an assignment handler to be called", "For example:: __all__ = [\"foo\", \"bar\"] Names which are imported", "handlers for i, handler in enumerate(node.handlers): if isinstance(handler.type, ast.Tuple): for", "*' def __str__(self): # When the module ends with a", "function. \"\"\" usesLocals = False alwaysUsed = set(['__tracebackhide__', '__traceback_info__', '__traceback_supplement__'])", "the list are two-tuples. The first element is the callable", "including multiple dotted components. @type fullName: C{str} \"\"\" def __init__(self,", "are only present on some platforms. _MAGIC_GLOBALS = ['__file__', '__builtins__',", "continue # if the name was defined in that scope,", "self.scope and name not in self.scope.globals: # then it's probably", "node): if node.value: # Only bind the *targets* if the", "Importation(name, node, alias.name) self.addBinding(node, importation) def IMPORTFROM(self, node): if node.module", "scope(self): return self.scopeStack[-1] def popScope(self): self.deadScopes.append(self.scopeStack.pop()) def checkDeadScopes(self): \"\"\" Look", "def handleNode(self, node, parent): if node is None: return if", "arg) in enumerate(args): if arg in args[:idx]: self.report(messages.DuplicateArgument, node, arg)", "from `__future__` import statement. `__future__` imports are implicitly used. \"\"\"", "warnings for any Assignment that isn't used. Also, the checker", "have not been used. \"\"\" for name, binding in self.scope.unusedAssignments():", "which is not a Name node, but # a simple", "4) self.handleChildren(tree) self.offset = node_offset if not underscore_in_builtins: self.builtIns.remove('_') self.popScope()", "binding.used and name not in self.globals and not self.usesLocals and", "[[hdl] for hdl in n.handlers] else: def getAlternatives(n): if isinstance(n,", "(self.scope, node) from_list.append(binding.fullName) # report * usage, with a list", "report names in them which were imported but unused. \"\"\"", "name == omit: continue field = getattr(node, name, None) if", "'False': False, 'None': None, } return constants_lookup.get( result.name, result, )", "False, 'None': None, } return constants_lookup.get( result.name, result, ) elif", "which takes the value of a literal list containing literal", "appear in the value of C{__all__} will not have an", "\"\"\" for handler, scope, offset in deferred: self.scopeStack = scope", "ast.Str): return (None, None) if PYPY: doctest_lineno = node.lineno -", "name in undefined: self.report(messages.UndefinedExport, scope['__all__'].source, name) # mark all import", "1 << 8 or len(node.elts) - star_loc - 1 >=", "self.report(messages.ImportShadowedByLoopVar, node, value.name, existing.source) elif scope is self.scope: if (isinstance(parent_stmt,", "have line numbers associated with them. This will be #", "= \\ MATMULT = ignore # additional node types COMPREHENSION", "node.name in scope: is_name_previously_defined = True break else: is_name_previously_defined =", "yield field elif isinstance(field, list): for item in field: yield", "arg_name) if not wildcard: continue args.append(wildcard if PY33 else wildcard.arg)", "platforms. _MAGIC_GLOBALS = ['__file__', '__builtins__', 'WindowsError'] def getNodeName(node): # Returns", "= name + '.*' self.fullName = name @property def source_statement(self):", "# UndefinedLocal warnings. self.handleNode(node.target, node) self.handleNode(node.annotation, node) if node.value: #", "elif hasattr(ast, 'Bytes') and isinstance(item, ast.Bytes): return item.s elif isinstance(item,", "unless it's in the loop itself if n_child not in", "PY34: LOOP_TYPES = (ast.While, ast.For) else: LOOP_TYPES = (ast.While, ast.For,", "item.n elif isinstance(item, ast.Name): result = VariableKey(item=item) constants_lookup = {", "raise RuntimeError(\"Got impossible expression context: %r\" % (node.ctx,)) def CONTINUE(self,", "# When the module ends with a ., avoid the", "self.handleNode(node.value, node) self.handleNode(node.target, node) def TUPLE(self, node): if not PY2", "submodule import statement. A submodule import is a special case", "return fields def counter(items): \"\"\" Simplest required implementation of collections.Counter.", "if isinstance(source.value, (ast.List, ast.Tuple)): for node in source.value.elts: if isinstance(node,", "\"else:\", \"finally:\" self.handleChildren(node, omit='body') TRYEXCEPT = TRY def EXCEPTHANDLER(self, node):", "and the node that this binding was last used. \"\"\"", "%r at 0x%x>' % (self.__class__.__name__, self.name, self.source.lineno, id(self)) def redefines(self,", "C{__all__} assignment. If the names in the list can be", "rnode, stop) if (lnode.depth < rnode.depth): return self.getCommonAncestor(lnode, rnode.parent, stop)", "ast.Str): return item.s elif hasattr(ast, 'Bytes') and isinstance(item, ast.Bytes): return", "\"\"\"Return import full name with alias.\"\"\" if self.real_name != self.name:", "source statement equivalent to the import.\"\"\" if self._has_alias(): return 'import", "if 'NameError' not in self.exceptHandlers[-1]: self.report(messages.UndefinedName, node, name) def handleNodeStore(self,", "(self.module, self.real_name, self.name) else: return 'from %s import %s' %", "nodeType) return handler def handleNodeLoad(self, node): name = getNodeName(node) if", "node.value if not isinstance(node, ast.Str): return (None, None) if PYPY:", "and not isinstance(self.getParent(existing.source), (ast.For, ast.comprehension))): self.report(messages.RedefinedInListComp, node, value.name, existing.source) elif", "a special type of binding that is checked with stricter", "incorrect if there are empty lines between the beginning #", "isinstance(other, Importation): return self.fullName == other.fullName return super(SubmoduleImportation, self).redefines(other) def", "and not self._in_doctest() and not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) ASYNCFUNCTIONDEF", "longer have line numbers associated with them. This will be", "aren't used. for value in scope.values(): if isinstance(value, Importation): used", "generator. \"\"\" if self.scope.isGenerator and self.scope.returnValue: self.report(messages.ReturnWithArgsInsideGenerator, self.scope.returnValue) self.deferAssignment(checkReturnWithArgumentInsideGenerator) self.popScope()", "in self.scope.globals: # then it's probably a mistake self.report(messages.UndefinedLocal, scope[name].used[1],", "= isinstance(scope, GeneratorScope) # look in the built-ins if name", "= self.getNodeHandler(node.__class__) handler(node) finally: self.nodeDepth -= 1 if self.traceTree: print('", "not in __future__.all_feature_names: self.report(messages.FutureFeatureNotDefined, node, alias.name) elif alias.name == '*':", "in node.body: self.handleNode(stmt, node) else: # case for Lambdas self.handleNode(node.body,", "existing.used and value.redefines(existing): self.report(messages.RedefinedWhileUnused, node, value.name, existing.source) elif isinstance(existing, Importation)", "has_starred: self.report(messages.TwoStarredExpressions, node) # The SyntaxError doesn't distinguish two from", "= alias.asname or alias.name if node.module == '__future__': importation =", "node): try: if hasattr(node, 'docstring'): docstring = node.docstring # This", "hasattr(node, 'name'): # an ExceptHandler node return node.name class Checker(object):", "ignore # additional node types COMPREHENSION = KEYWORD = FORMATTEDVALUE", "return importStarred = importStarred or scope.importStarred if in_generators is not", "is the callable passed to L{deferFunction}. The second element is", "% (scope_cls, id(self), dict.__repr__(self)) class ClassScope(Scope): pass class FunctionScope(Scope): \"\"\"", "a globally defined name. See test_unused_global. self.messages = [ m", "node) def YIELD(self, node): if isinstance(self.scope, (ClassScope, ModuleScope)): self.report(messages.YieldOutsideFunction, node)", "None) return False name = getNodeName(node) if not name: return", "x import *' statement.\"\"\" def __init__(self, name, source): super(StarImportation, self).__init__('*',", "in that scope, and the name has # been accessed", "+ [[hdl] for hdl in n.handlers] if PY34: LOOP_TYPES =", "was defined in that scope, and the name has #", "\\ COMPARE = CALL = REPR = ATTRIBUTE = SUBSCRIPT", "0x%x>' % (self.__class__.__name__, self.name, self.source.lineno, id(self)) def redefines(self, other): return", "os import sys PY2 = sys.version_info < (3, 0) PY32", "self.fullName == other.fullName return isinstance(other, Definition) and self.name == other.name", "special type of binding that is checked with stricter rules.", "[\"foo\", \"bar\"] Names which are imported and not otherwise used", "handler = self.getNodeHandler(node.__class__) handler(node) finally: self.nodeDepth -= 1 if self.traceTree:", "= False def __str__(self): return self.name def __repr__(self): return '<%s", "@ivar fullName: The complete name given to the import statement,", "def unusedAssignments(self): \"\"\" Return a generator for the assignments which", "in_generators is False and isinstance(scope, ClassScope): continue try: scope[name].used =", "= REPR = ATTRIBUTE = SUBSCRIPT = \\ STARRED =", "UADD = USUB = \\ EQ = NOTEQ = LT", "= IFEXP = SET = \\ COMPARE = CALL =", "tries to # use the name afterwards. # # Unless", "then assume the rebound name is used as a global", "return self.isGenerator = False # Detect a generator def unusedAssignments(self):", "= SUB = MULT = DIV = MOD = POW", "for alias in node.names: name = alias.asname or alias.name if", "Memorize the except handlers and process the body self.exceptHandlers.append(handler_names) for", "first iteration if in_generators is False and isinstance(scope, ClassScope): continue", "undefined: self.report(messages.UndefinedExport, scope['__all__'].source, name) # mark all import '*' as", "that defines a function or a class. \"\"\" class UnhandledKeyType(object):", "the scope # of the except: block. for scope in", "getNodeType(node_class) self._nodeHandlers[node_class] = handler = getattr(self, nodeType) return handler def", "node) indicating the scope and the node that this binding", "for duplicates. \"\"\" class VariableKey(object): \"\"\" A dictionary key which", "self.runDeferred(self._deferredFunctions) # Set _deferredFunctions to None so that deferFunction will", "for imported names that aren't used. for value in scope.values():", "return True return False def addBinding(self, node, value): \"\"\" Called", "= (ast.While, ast.For) else: LOOP_TYPES = (ast.While, ast.For, ast.AsyncFor) class", "= [] self.filename = filename if builtins: self.builtIns = self.builtIns.union(builtins)", "INVERT = NOT = UADD = USUB = \\ EQ", "ast.For): self.report(messages.ImportShadowedByLoopVar, node, value.name, existing.source) elif scope is self.scope: if", "# Ignore 'global' statement in global scope. if self.scope is", "= None importStarred = None # try enclosing function scopes", "else: return importStarred = importStarred or scope.importStarred if in_generators is", "and isinstance(item, ast.NameConstant): # None, True, False are nameconstants in", "= [] if undefined: if not scope.importStarred and \\ os.path.basename(self.filename)", "pass class ClassDefinition(Definition): pass class ExportBinding(Binding): \"\"\" A binding created", "scope.values(): if isinstance(value, Importation): used = value.used or value.name in", "imports as used for each scope binding.used = (self.scope, node)", "if isinstance(n, ast.Try): return [n.body + n.orelse] + [[hdl] for", "ExportBinding): all_binding = None if all_binding: all_names = set(all_binding.names) undefined", "A binding that defines a function or a class. \"\"\"", "binding) def handleNodeDelete(self, node): def on_conditional_branch(): \"\"\" Return `True` if", "ASYNCFOR = WHILE = IF = WITH = WITHITEM =", "= (global_scope, node) for scope in self.scopeStack[global_scope_index + 1:]: scope[node_name]", "or module scope above us for scope in self.scopeStack[:-1]: if", "(ast.If, ast.TryFinally)): return [n.body] if isinstance(n, ast.TryExcept): return [n.body +", "\"\"\" def __init__(self, name, source, full_name=None): self.fullName = full_name or", "to be called just before completion. This is used for", "CONTINUE(self, node): # Walk the tree up until we see", "# Set _deferredFunctions to None so that deferFunction will fail", "del self.scope[node.name] except KeyError: pass def ANNASSIGN(self, node): if node.value:", "def redefines(self, other): return isinstance(other, Definition) and self.name == other.name", "RedefinedWhileUnused return self.fullName == other.fullName return isinstance(other, Definition) and self.name", "note in SubmoduleImportation about RedefinedWhileUnused return self.fullName == other.fullName return", "in self.scopeStack[::-1]: if node.name in scope: is_name_previously_defined = True break", "= filename if builtins: self.builtIns = self.builtIns.union(builtins) self.withDoctest = withDoctest", "have an unused import warning reported for them. \"\"\" def", "def futuresAllowed(self, value): assert value is False if isinstance(self.scope, ModuleScope):", "+ 1:]: scope[node_name] = node_value NONLOCAL = GLOBAL def GENERATOREXP(self,", "not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) for stmt in node.body: self.handleNode(stmt,", "avoid false positives. \"\"\" def __init__(self, name, source): # A", "a finally block (not OK), or # the top module", "try: return self._nodeHandlers[node_class] except KeyError: nodeType = getNodeType(node_class) self._nodeHandlers[node_class] =", "a SyntaxWarning if not PY2 and not isinstance(self.scope, ModuleScope): self.report(messages.ImportStarNotPermitted,", "has_starred = False star_loc = -1 for i, n in", "\"except:\", \"else:\", \"finally:\" self.handleChildren(node, omit='body') TRYEXCEPT = TRY def EXCEPTHANDLER(self,", "ast.AST): yield field elif isinstance(field, list): for item in field:", "(scope_cls, id(self), dict.__repr__(self)) class ClassScope(Scope): pass class FunctionScope(Scope): \"\"\" I", "star_loc = i if star_loc >= 1 << 8 or", "any(count == 1 for value, count in values.items()): for key_index", "submodule import is without an 'as' clause. pyflakes handles this", "name otherwise it will be deemed imported self.name = name", "a generator for the assignments which have not been used.", "= scope self.offset = offset handler() def _in_doctest(self): return (len(self.scopeStack)", "list can be determined statically, they will be treated as", "convert_to_value(node.values[index]) for index in key_indices ) if any(count == 1", "we are doing locals() call in current scope self.scope.usesLocals =", "context: %r\" % (node.ctx,)) def CONTINUE(self, node): # Walk the", "in ast.ClassDef._fields: # Patch the missing attribute 'decorator_list' ast.ClassDef.decorator_list =", "does not consider assignments in tuple/list unpacking to be Assignments,", "node.name, or None if hasattr(node, 'id'): # One of the", "else: # ast.Break self.report(messages.BreakOutsideLoop, node) BREAK = CONTINUE def RETURN(self,", "which attributes of the root module may be used. This", "them. \"\"\" def __init__(self, name, source, scope): if '__all__' in", "not self._in_doctest() and not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) ASYNCFUNCTIONDEF =", "@property def scope(self): return self.scopeStack[-1] def popScope(self): self.deadScopes.append(self.scopeStack.pop()) def checkDeadScopes(self):", "protected with a NameError handler? if 'NameError' not in self.exceptHandlers[-1]:", "for name in _fields_order[node.__class__]: if name == omit: continue field", "if PY33: # Python 2.5 to 3.3 argannotation = arg_name", "source_statement(self): return 'import ' + self.fullName class ImportationFrom(Importation): def __init__(self,", "messageClass, *args, **kwargs): self.messages.append(messageClass(self.filename, *args, **kwargs)) def getParent(self, node): #", "at the correct place in the node tree. \"\"\" return", "block is never entered. This will cause an # \"undefined", "Each star importation needs a unique name, and # may", "Represents binding a name as an argument. \"\"\" class Assignment(Binding):", "all direct child nodes of *node*, that is, all fields", "if self.getCommonAncestor(node, a, stop): return True return False def differentForks(self,", "self.fullName = name @property def source_statement(self): return 'from ' +", "anyway has_starred = False star_loc = -1 for i, n", "root module name in the scope, allowing any attribute of", "to the import.\"\"\" if self._has_alias(): return 'import %s as %s'", "if isinstance(n, ast.Starred): if has_starred: self.report(messages.TwoStarredExpressions, node) # The SyntaxError", "if self.traceTree: print(' ' * self.nodeDepth + node.__class__.__name__) if self.futuresAllowed", "def __repr__(self): return '<%s object %r from line %r at", "@ivar used: pair of (L{Scope}, node) indicating the scope and", "node): for deco in node.decorator_list: self.handleNode(deco, node) self.LAMBDA(node) self.addBinding(node, FunctionDefinition(node.name,", "the file might modify the global scope. When `callable` is", "with a list of possible sources from_list = ', '.join(sorted(from_list))", "restored, however it will contain any new bindings added to", "i if star_loc >= 1 << 8 or len(node.elts) -", "value.redefined: if isinstance(self.getParent(node), ast.For): messg = messages.ImportShadowedByLoopVar elif used: continue", "for m in self.messages if not isinstance(m, messages.UndefinedName) or m.message_args[0]", "PYPY = False builtin_vars = dir(__import__('__builtin__' if PY2 else 'builtins'))", "current scope, and hasn't # been declared global used =", "super(StarImportation, self).__init__('*', source) # Each star importation needs a unique", "we've run through the deferred assignments. self._deferredAssignments = None del", "self.root) parts = getAlternatives(ancestor) if parts: for items in parts:", "import ast except ImportError: # Python 2.5 import _ast as", "doctest_lineno = node.lineno - 1 else: # Computed incorrectly if", "node.args.defaults + node.args.kw_defaults # Only for Python3 FunctionDefs is_py3_func =", "value, count in values.items()): for key_index in key_indices: key_node =", "name to the current scope. \"\"\" for deco in node.decorator_list:", "self.offset = (node_offset[0] + node_lineno + example.lineno, node_offset[1] + example.indent", "name, binding in self.items(): if (not binding.used and name not", "list containing literal strings. For example:: __all__ = [\"foo\", \"bar\"]", "beginning # of the function and the docstring. node_lineno =", "= ignore # additional node types COMPREHENSION = KEYWORD =", "definition, including its decorators, base classes, and the body of", "undefined in __all__ if scope.importStarred: for binding in scope.values(): if", "List or Starred while True: node = node.parent if not", "for alias in node.names: if '.' in alias.name and not", "*args, **kwargs)) def getParent(self, node): # Lookup the first parent", "continue all_binding = scope.get('__all__') if all_binding and not isinstance(all_binding, ExportBinding):", "parent_stmt = self.getParent(node) if isinstance(parent_stmt, (ast.For, ast.comprehension)) or ( parent_stmt", "GTE = IS = ISNOT = IN = NOTIN =", "= () ast.FunctionDef.decorator_list = property(lambda s: s.decorators) from pyflakes import", "n_child in n.finalbody: self.report(messages.ContinueInFinally, node) return if isinstance(node, ast.Continue): self.report(messages.ContinueOutsideLoop,", "not (hasattr(lnode, 'parent') and hasattr(rnode, 'parent')): return None if lnode", "\"\"\" return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and isinstance(node.value, ast.Str))", "TRYFINALLY = EXEC = \\ EXPR = ASSIGN = handleChildren", "3.4 annotations.append(wildcard.annotation) if is_py3_func: annotations.append(node.returns) if len(set(args)) < len(args): for", "the submodule name is also the same, to avoid false", "but # a simple string, creates a local that is", "handler, scope, offset in deferred: self.scopeStack = scope self.offset =", "addArgs(arglist): for arg in arglist: if isinstance(arg, ast.Tuple): addArgs(arg.elts) else:", "<< 8 or len(node.elts) - star_loc - 1 >= 1", "sys.version_info < (3, 4) # Python 2.5 to 3.3 PY34", "The checker will raise warnings for any Assignment that isn't", "= None # try enclosing function scopes and global scope", "import *' statement.\"\"\" def __init__(self, name, source): super(StarImportation, self).__init__('*', source)", "operators AND = OR = ADD = SUB = MULT", "in self.scope.globals: self.scope.globals.remove(name) else: try: del self.scope[name] except KeyError: self.report(messages.UndefinedName,", "key_first = 'generators'.find else: key_first = 'value'.find return tuple(sorted(fields, key=key_first,", "that are lists of nodes. \"\"\" for name in _fields_order[node.__class__]:", "= name self.source = source self.used = False def __str__(self):", "ast.ImportFrom) or self.isDocstring(node)): self.futuresAllowed = False self.nodeDepth += 1 node.depth", "node_lineno + example.lineno, node_offset[1] + example.indent + 4) self.handleChildren(tree) self.offset", "node, module, alias.name) self.addBinding(node, importation) def TRY(self, node): handler_names =", "the name afterwards. # # Unless it's been removed already.", "if the name hasn't already been defined in the current", "parent_stmt != node.parent and not self.isLiteralTupleUnpacking(parent_stmt)): binding = Binding(name, node)", "a source statement equivalent to the import.\"\"\" if self._has_alias(): return", "is a special case where the root module is implicitly", "hasattr(n, 'finalbody') and isinstance(node, ast.Continue): if n_child in n.finalbody: self.report(messages.ContinueInFinally,", "return False def addBinding(self, node, value): \"\"\" Called when a", "self.globals = self.alwaysUsed.copy() self.returnValue = None # First non-empty return", "example.indent + 4) self.handleChildren(tree) self.offset = node_offset if not underscore_in_builtins:", "else: # case for Lambdas self.handleNode(node.body, node) def checkUnusedAssignments(): \"\"\"", "def IMPORTFROM(self, node): if node.module == '__future__': if not self.futuresAllowed:", "to None so that deferAssignment will fail # noisily if", "with them. This will be # incorrect if there are", "Importation): used = value.used or value.name in all_names if not", "self.builtIns: return if importStarred: from_list = [] for scope in", "the time this is called will be restored, however it", "Python 2.5 to 3.2 PY33 = sys.version_info < (3, 4)", "\"\"\" A binding created by an import statement. @ivar fullName:", "ast.Str)) def getDocstring(self, node): if isinstance(node, ast.Expr): node = node.value", "self.popScope() self.scopeStack = saved_stack def ignore(self, node): pass # \"stmt\"", "sys.version_info < (3, 0) PY32 = sys.version_info < (3, 3)", "called after we've run through the deferred functions. self._deferredFunctions =", "import is a special case where the root module is", "self.report(messg, value.source, str(value)) for node in value.redefined: if isinstance(self.getParent(node), ast.For):", "= SETCOMP = GENERATOREXP def NAME(self, node): \"\"\" Handle occurrence", "node) return if isinstance(node, ast.Continue): self.report(messages.ContinueOutsideLoop, node) else: # ast.Break", "class definition, including its decorators, base classes, and the body", "current: if isinstance(current, (ast.If, ast.While, ast.IfExp)): return True current =", "any assignments have not been used. \"\"\" for name, binding", "elif isinstance(item, ast.Name): result = VariableKey(item=item) constants_lookup = { 'True':", "scope and isinstance(source, ast.AugAssign): self.names = list(scope['__all__'].names) else: self.names =", "# Python >= 3.4 annotations.append(wildcard.annotation) if is_py3_func: annotations.append(node.returns) if len(set(args))", "\\ EQ = NOTEQ = LT = LTE = GT", "alias.name importation = Importation(name, node, alias.name) self.addBinding(node, importation) def IMPORTFROM(self,", "items, ancestor): return True return False def addBinding(self, node, value):", "= False # set to True when import * is", "print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__) _getDoctestExamples", "the new value, a Binding instance \"\"\" # assert value.source", "parent): if node is None: return if self.offset and getattr(node,", "arg in node.args.args]) else: (docstring, node_lineno) = self.getDocstring(node.body[0]) examples =", "an 'as' clause, and the submodule is also imported. Python", "scope stack. \"\"\" for handler, scope, offset in deferred: self.scopeStack", "= None # First non-empty return self.isGenerator = False #", "YIELD def FUNCTIONDEF(self, node): for deco in node.decorator_list: self.handleNode(deco, node)", "\"\"\"True, if lnode and rnode are located on different forks", "= handleChildren # expression contexts are node instances too, though", "names in them which were imported but unused. \"\"\" for", ") self.handleChildren(node) def ASSERT(self, node): if isinstance(node.test, ast.Tuple) and node.test.elts", "return False return self.scope._futures_allowed @futuresAllowed.setter def futuresAllowed(self, value): assert value", "# Look for possible mistakes in the export list for", "conditional body. \"\"\" current = getattr(node, 'parent', None) while current:", "isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and isinstance(node.value, ast.Str)) def getDocstring(self,", "self.scopeStack[global_scope_index + 1:]: scope[node_name] = node_value NONLOCAL = GLOBAL def", "node_class.__name__.upper() # Python >= 3.3 uses ast.Try instead of (ast.TryExcept", "return isinstance(other, Definition) and self.name == other.name def _has_alias(self): \"\"\"Return", "set to True when import * is found def __repr__(self):", "self.scope[value.name] = value def getNodeHandler(self, node_class): try: return self._nodeHandlers[node_class] except", "# of the function and the docstring. node_lineno = node.lineno", "current = getattr(current, 'parent', None) return False name = getNodeName(node)", "node) self.LAMBDA(node) self.addBinding(node, FunctionDefinition(node.name, node)) # doctest does not process", "Unless it's been removed already. Then do nothing. try: del", "full_name = module + self.real_name else: full_name = module +", "= withDoctest self.scopeStack = [ModuleScope()] self.exceptHandlers = [()] self.root =", "else: LOOP_TYPES = (ast.While, ast.For, ast.AsyncFor) class _FieldsOrder(dict): \"\"\"Fix order", "super(SubmoduleImportation, self).redefines(other) def __str__(self): return self.fullName @property def source_statement(self): return", "are deferred assignment checks. \"\"\" nodeDepth = 0 offset =", "where the root module is implicitly imported, without an 'as'", "= [i for i, i_key in enumerate(keys) if i_key ==", "self.report(messages.UndefinedExport, scope['__all__'].source, name) # mark all import '*' as used", "not self.futuresAllowed: self.report(messages.LateFutureImport, node, [n.name for n in node.names]) else:", "Main module. Implement the central Checker class. Also, it models", "name with an explicit assignment. The checker will raise warnings", "PY33: # Python 2.5 to 3.3 argannotation = arg_name +", "in node.bases: self.handleNode(baseNode, node) if not PY2: for keywordNode in", "Also, the checker does not consider assignments in tuple/list unpacking", "for <string> has inconsistent # leading whitespace: ... return if", "will contain any new bindings added to it. \"\"\" self._deferredFunctions.append((callable,", "return 'from %s import %s' % (self.module, self.name) class StarImportation(Importation):", "if PY32: def getAlternatives(n): if isinstance(n, (ast.If, ast.TryFinally)): return [n.body]", "if all_binding and not isinstance(all_binding, ExportBinding): all_binding = None if", "self.report(messages.ReturnWithArgsInsideGenerator, self.scope.returnValue) self.deferAssignment(checkReturnWithArgumentInsideGenerator) self.popScope() self.deferFunction(runFunction) def CLASSDEF(self, node): \"\"\" Check", "the starred expression, # which is impossible to test due", "= KEYWORD = FORMATTEDVALUE = JOINEDSTR = handleChildren def DICT(self,", "module scope saved_stack = self.scopeStack self.scopeStack = [self.scopeStack[0]] node_offset =", "self.scopeStack = [self.scopeStack[0]] node_offset = self.offset or (0, 0) self.pushScope(DoctestScope)", "(OK), a function or class # definition (not OK), for", "% (self.module, self.name) class StarImportation(Importation): \"\"\"A binding created by a", "_customBuiltIns def __init__(self, tree, filename='(none)', builtins=None, withDoctest='PYFLAKES_DOCTEST' in os.environ): self._nodeHandlers", "function scopes and global scope for scope in self.scopeStack[-1::-1]: #", "def deferAssignment(self, callable): \"\"\" Schedule an assignment handler to be", "above us for scope in self.scopeStack[:-1]: if not isinstance(scope, (FunctionScope,", "node.col_offset += self.offset[1] if self.traceTree: print(' ' * self.nodeDepth +", "it does not # become a globally defined name. See", "sources from_list = ', '.join(sorted(from_list)) self.report(messages.ImportStarUsage, node, name, from_list) return", "not process doctest within a doctest # classes within classes", "self.handleChildren(node, omit='body') TRYEXCEPT = TRY def EXCEPTHANDLER(self, node): if PY2", "See L{Assignment} for a special type of binding that is", "before completion. This is used for handling function bodies, which", "== '__path__' and os.path.basename(self.filename) == '__init__.py': # the special name", "node.args.kwonlyargs: args.append(arg.arg) annotations.append(arg.annotation) defaults = node.args.defaults + node.args.kw_defaults # Only", "`value` is the new value, a Binding instance \"\"\" #", "if the checked code tries to # use the name", "here raise RuntimeError(\"Got impossible expression context: %r\" % (node.ctx,)) def", "due to memory restrictions, but we # add it here", "key_first = 'value'.find return tuple(sorted(fields, key=key_first, reverse=True)) def __missing__(self, node_class):", "source, full_name) def __str__(self): \"\"\"Return import full name with alias.\"\"\"", "0) + 1 return results def iter_child_nodes(node, omit=None, _fields_order=_FieldsOrder()): \"\"\"", "direct child nodes of *node*, that is, all fields that", "isinstance(node.ctx, (ast.Load, ast.AugLoad)): self.handleNodeLoad(node) if (node.id == 'locals' and isinstance(self.scope,", "3.3 PY34 = sys.version_info < (3, 5) # Python 2.5", "= {} for item in items: results[item] = results.get(item, 0)", "handle iter before target, and generators before element fields =", "node, alias.name) self.addBinding(node, importation) def IMPORTFROM(self, node): if node.module ==", "= self.alwaysUsed.copy() self.returnValue = None # First non-empty return self.isGenerator", "value.name, existing.source) elif isinstance(existing, Importation) and value.redefines(existing): existing.redefined.append(node) if value.name", "used: continue else: messg = messages.RedefinedWhileUnused self.report(messg, node, value.name, value.source)", "Binding(name, node) elif name == '__all__' and isinstance(self.scope, ModuleScope): binding", "nodes BOOLOP = BINOP = UNARYOP = IFEXP = SET", "if isinstance(n, (ast.If, ast.TryFinally)): return [n.body] if isinstance(n, ast.TryExcept): return", "special case where the root module is implicitly imported, without", "item in items: results[item] = results.get(item, 0) + 1 return", "__init__(self, item): self.name = item.id def __eq__(self, compare): return (", "for node in source.value.elts: if isinstance(node, ast.Str): self.names.append(node.s) super(ExportBinding, self).__init__(name,", "the built-ins if name in self.builtIns: return if importStarred: from_list", "SyntaxWarning if not PY2 and not isinstance(self.scope, ModuleScope): self.report(messages.ImportStarNotPermitted, node,", "be determined statically, they will be treated as names for", "name hasn't already been defined in the current scope if", "# then it's probably a mistake self.report(messages.UndefinedLocal, scope[name].used[1], name, scope[name].source)", "binding that is checked with stricter rules. @ivar used: pair", "in node.names]) else: self.futuresAllowed = False module = ('.' *", "# a simple string, creates a local that is only", "node = node.parent if not hasattr(node, 'elts') and not hasattr(node,", "any attribute of the root module to be accessed. RedefinedWhileUnused", "in node.targets + [node.value]: if not hasattr(child, 'elts'): return False", "undefined = [] if undefined: if not scope.importStarred and \\", "FOR = ASYNCFOR = WHILE = IF = WITH =", "self.filename = filename if builtins: self.builtIns = self.builtIns.union(builtins) self.withDoctest =", "alias.name) self.addBinding(node, importation) def IMPORTFROM(self, node): if node.module == '__future__':", "deferred functions. self._deferredFunctions = None self.runDeferred(self._deferredAssignments) # Set _deferredAssignments to", "key_node, key, ) self.handleChildren(node) def ASSERT(self, node): if isinstance(node.test, ast.Tuple)", "m for m in self.messages if not isinstance(m, messages.UndefinedName) or", "baseNode in node.bases: self.handleNode(baseNode, node) if not PY2: for keywordNode", "= ignore # \"slice\" type nodes SLICE = EXTSLICE =", "'ctx'): return node def getCommonAncestor(self, lnode, rnode, stop): if stop", "within the scope # of the except: block. for scope", "it models the Bindings and Scopes. \"\"\" import __future__ import", "the name has # been accessed already in the current", "def runFunction(): self.pushScope() for name in args: self.addBinding(node, Argument(name, node))", "noisily if called after we've run through the deferred assignments.", "AND = OR = ADD = SUB = MULT =", "deco in node.decorator_list: self.handleNode(deco, node) for baseNode in node.bases: self.handleNode(baseNode,", "= True self.report(messages.ImportStarUsed, node, module) importation = StarImportation(module, node) else:", "as %s' % (self.module, self.real_name, self.name) else: return 'from %s", "same for operators AND = OR = ADD = SUB", "and isinstance(self.scopeStack[1], DoctestScope)) @property def futuresAllowed(self): if not all(isinstance(scope, ModuleScope)", "[ m for m in self.messages if not isinstance(m, messages.UndefinedName)", "might modify the global scope. When `callable` is called, the", "keep track of which names have been bound and which", "None) if PYPY: doctest_lineno = node.lineno - 1 else: #", "ast.Try): return [n.body + n.orelse] + [[hdl] for hdl in", "try: tree = compile(example.source, \"<doctest>\", \"exec\", ast.PyCF_ONLY_AST) except SyntaxError: e", "and not self.differentForks(node, existing.source): parent_stmt = self.getParent(value.source) if isinstance(existing, Importation)", "None, True, False are nameconstants in python3, but names in", "'import ' + self.fullName class ImportationFrom(Importation): def __init__(self, name, source,", "stop) if (lnode.depth < rnode.depth): return self.getCommonAncestor(lnode, rnode.parent, stop) return", "\"bar\"] Names which are imported and not otherwise used but", "scope, and the name has # been accessed already in", "isinstance(arg, ast.Tuple): addArgs(arg.elts) else: args.append(arg.id) addArgs(node.args.args) defaults = node.args.defaults else:", "is_name_previously_defined = False self.handleNodeStore(node) self.handleChildren(node) if not is_name_previously_defined: # See", "and isinstance(item, ast.Bytes): return item.s elif isinstance(item, ast.Tuple): return tuple(convert_to_value(i)", "package_name = name.split('.')[0] super(SubmoduleImportation, self).__init__(package_name, source) self.fullName = name def", "= GENERATOREXP def NAME(self, node): \"\"\" Handle occurrence of Name", "and it's always unbound # if the except: block is", "getAlternatives(ancestor) if parts: for items in parts: if self.descendantOf(lnode, items,", "# Remove UndefinedName messages already reported for this name. #", "self._in_doctest() else 0 global_scope = self.scopeStack[global_scope_index] # Ignore 'global' statement", "node_name in node.names: node_value = Assignment(node_name, node) # Remove UndefinedName", "scope in self.scopeStack[-1::-1]: # only generators used in a class", "module) importation = StarImportation(module, node) else: importation = ImportationFrom(name, node,", "takes the value of a literal list containing literal strings.", "function. @ivar globals: Names declared 'global' in this function. \"\"\"", "and name not in self.scope: # for each function or", "6 of the docstring for <string> has inconsistent # leading", "does not have Counter in collections. \"\"\" results = {}", "self.report(messages.UndefinedName, node, name) def handleChildren(self, tree, omit=None): for node in", "generator def unusedAssignments(self): \"\"\" Return a generator for the assignments", "of AST node fields.\"\"\" def _get_fields(self, node_class): # handle iter", "None: return if self.offset and getattr(node, 'lineno', None) is not", "yield item def convert_to_value(item): if isinstance(item, ast.Str): return item.s elif", "Importation) and value.redefines(existing): existing.redefined.append(node) if value.name in self.scope: # then", "the import.\"\"\" if self._has_alias(): return 'import %s as %s' %", "= set(builtin_vars).union(_MAGIC_GLOBALS) _customBuiltIns = os.environ.get('PYFLAKES_BUILTINS') if _customBuiltIns: builtIns.update(_customBuiltIns.split(',')) del _customBuiltIns", "else: self.report( messages.MultiValueRepeatedKeyLiteral, key_node, key, ) self.handleChildren(node) def ASSERT(self, node):", "break else: is_name_previously_defined = False self.handleNodeStore(node) self.handleChildren(node) if not is_name_previously_defined:", "self.builtIns.remove('_') self.popScope() self.scopeStack = saved_stack def ignore(self, node): pass #", "Python 2.5 to 3.3 argannotation = arg_name + 'annotation' annotations.append(getattr(node.args,", "for keywordNode in node.keywords: self.handleNode(keywordNode, node) self.pushScope(ClassScope) # doctest does", "of binding that is checked with stricter rules. @ivar used:", "True class DoctestScope(ModuleScope): \"\"\"Scope for a doctest.\"\"\" # Globally defined", "True: node = node.parent if not hasattr(node, 'elts') and not", "name = alias.asname or alias.name if node.module == '__future__': importation", "'None': None, } return constants_lookup.get( result.name, result, ) elif (not", "- node.s.count('\\n') - 1 return (node.s, doctest_lineno) def handleNode(self, node,", "Bind name to global scope if it doesn't exist already.", "be called just after deferred function handlers. \"\"\" self._deferredAssignments.append((callable, self.scopeStack[:],", "be executed. return if isinstance(self.scope, FunctionScope) and name in self.scope.globals:", "(lnode, rnode) or not (hasattr(lnode, 'parent') and hasattr(rnode, 'parent')): return", "[] annotations = [] if PY2: def addArgs(arglist): for arg", "'parent') and hasattr(rnode, 'parent')): return None if lnode is rnode:", "continue self.scope.importStarred = True self.report(messages.ImportStarUsed, node, module) importation = StarImportation(module,", "elif 'generators' in fields: key_first = 'generators'.find else: key_first =", "used by L{deferFunction}. Elements of the list are two-tuples. The", "scope in self.scopeStack): return False return self.scope._futures_allowed @futuresAllowed.setter def futuresAllowed(self,", "self.scope[node.name] except KeyError: pass def ANNASSIGN(self, node): if node.value: #", "iter before target, and generators before element fields = node_class._fields", "with an id return node.id if hasattr(node, 'name'): # an", "keywordNode in node.keywords: self.handleNode(keywordNode, node) self.pushScope(ClassScope) # doctest does not", "this case by registering the root module name in the", "isinstance(all_binding, ExportBinding): all_binding = None if all_binding: all_names = set(all_binding.names)", "the class. this is skipped during the first iteration if", "current scope self.scope.usesLocals = True elif isinstance(node.ctx, (ast.Store, ast.AugStore)): self.handleNodeStore(node)", "that is only bound within the scope # of the", "return # if the name hasn't already been defined in", "defines a function or a class. \"\"\" class UnhandledKeyType(object): \"\"\"", "Set _deferredFunctions to None so that deferFunction will fail #", "name if module.endswith('.'): full_name = module + self.real_name else: full_name", "the tree up until we see a loop (OK), a", "if the given node is a docstring, as long as", "[()] self.root = tree self.handleChildren(tree) self.runDeferred(self._deferredFunctions) # Set _deferredFunctions to", "for name in undefined: self.report(messages.UndefinedExport, scope['__all__'].source, name) # mark all", "duplicates. \"\"\" class VariableKey(object): \"\"\" A dictionary key which is", "and not hasattr(node, 'ctx'): return node def getCommonAncestor(self, lnode, rnode,", "pass # \"stmt\" type nodes DELETE = PRINT = FOR", "Python 3.7, docstrings no # longer have line numbers associated", "used as a global or within a loop value.used =", "n.finalbody: self.report(messages.ContinueInFinally, node) return if isinstance(node, ast.Continue): self.report(messages.ContinueOutsideLoop, node) else:", "> rnode.depth): return self.getCommonAncestor(lnode.parent, rnode, stop) if (lnode.depth < rnode.depth):", "+ 1 return results def iter_child_nodes(node, omit=None, _fields_order=_FieldsOrder()): \"\"\" Yield", "NOTIN = \\ MATMULT = ignore # additional node types", "PYPY: e.offset += 1 position = (node_lineno + example.lineno +", "node)) def AUGASSIGN(self, node): self.handleNodeLoad(node.target) self.handleNode(node.value, node) self.handleNode(node.target, node) def", "by an import statement. @ivar fullName: The complete name given", "\"\"\" class FunctionDefinition(Definition): pass class ClassDefinition(Definition): pass class ExportBinding(Binding): \"\"\"", "body. \"\"\" current = getattr(node, 'parent', None) while current: if", "just a reasonable guess. In Python 3.7, docstrings no #", "n_child = n.parent, n if isinstance(n, LOOP_TYPES): # Doesn't apply", "Python3 FunctionDefs is_py3_func = hasattr(node, 'returns') for arg_name in ('vararg',", "'') for alias in node.names: name = alias.asname or alias.name", "dir(__import__('__builtin__' if PY2 else 'builtins')) try: import ast except ImportError:", "0) PY32 = sys.version_info < (3, 3) # Python 2.5", "reasonable guess. In Python 3.7, docstrings no # longer have", "existing.redefined.append(node) if value.name in self.scope: # then assume the rebound", "= ADD = SUB = MULT = DIV = MOD", "non-global scopes, but as already \"used\". node_value.used = (global_scope, node)", "will raise warnings for any Assignment that isn't used. Also,", "2 return item.value else: return UnhandledKeyType() class Binding(object): \"\"\" Represents", "module) continue self.scope.importStarred = True self.report(messages.ImportStarUsed, node, module) importation =", "line %r at 0x%x>' % (self.__class__.__name__, self.name, self.source.lineno, id(self)) def", "= Assignment(name, node) self.addBinding(node, binding) def handleNodeDelete(self, node): def on_conditional_branch():", "node): name = getNodeName(node) if not name: return in_generators =", "import doctest import os import sys PY2 = sys.version_info <", "if self.scope is not global_scope: # One 'global' statement can", "it treats them as simple Bindings. \"\"\" class FunctionDefinition(Definition): pass", "node) self.popScope() self.addBinding(node, ClassDefinition(node.name, node)) def AUGASSIGN(self, node): self.handleNodeLoad(node.target) self.handleNode(node.value,", "module + '.' + self.real_name super(ImportationFrom, self).__init__(name, source, full_name) def", "\"expr\" type nodes BOOLOP = BINOP = UNARYOP = IFEXP", "of a type that we cannot or do not check", "% (node.ctx,)) def CONTINUE(self, node): # Walk the tree up", "functions. if (self.withDoctest and not self._in_doctest() and not isinstance(self.scope, FunctionScope)):", "scope # of the except: block. for scope in self.scopeStack[::-1]:", "node, name) def handleChildren(self, tree, omit=None): for node in iter_child_nodes(tree,", "all(isinstance(scope, ModuleScope) for scope in self.scopeStack): return False return self.scope._futures_allowed", "the root module name in the scope, allowing any attribute", "= YIELDFROM = YIELD def FUNCTIONDEF(self, node): for deco in", "+ (node.module or '') for alias in node.names: name =", "= True break else: is_name_previously_defined = False self.handleNodeStore(node) self.handleChildren(node) if", "alias.asname or alias.name importation = Importation(name, node, alias.name) self.addBinding(node, importation)", "scope, allowing any attribute of the root module to be", "= self.__class__.__name__ return '<%s at 0x%x %s>' % (scope_cls, id(self),", "1 if self.traceTree: print(' ' * self.nodeDepth + 'end '", "n in node.names]) else: self.futuresAllowed = False module = ('.'", "self.scopeStack = saved_stack def ignore(self, node): pass # \"stmt\" type", "also the same, to avoid false positives. \"\"\" def __init__(self,", "python3, but names in 2 return item.value else: return UnhandledKeyType()", "it. \"\"\" self._deferredFunctions.append((callable, self.scopeStack[:], self.offset)) def deferAssignment(self, callable): \"\"\" Schedule", "in collections. \"\"\" results = {} for item in items:", "binding created by a submodule import statement. A submodule import", "= IF = WITH = WITHITEM = \\ ASYNCWITH =", "it will be deemed imported self.name = name + '.*'", "or name if module.endswith('.'): full_name = module + self.real_name else:", "docstrings no # longer have line numbers associated with them.", "name, None) if isinstance(field, ast.AST): yield field elif isinstance(field, list):", "except KeyError: pass def ANNASSIGN(self, node): if node.value: # Only", "import statement. `__future__` imports are implicitly used. \"\"\" def __init__(self,", "def NAME(self, node): \"\"\" Handle occurrence of Name (which can", "names in function # arguments, but these aren't dispatched through", "'returns') for arg_name in ('vararg', 'kwarg'): wildcard = getattr(node.args, arg_name)", "< (3, 3) # Python 2.5 to 3.2 PY33 =", "that are nodes and all items of fields that are", "which were imported but unused. \"\"\" for scope in self.deadScopes:", "in self.globals and not self.usesLocals and isinstance(binding, Assignment)): yield name,", "self.scopeStack[global_scope_index] # Ignore 'global' statement in global scope. if self.scope", "alias.name) elif alias.name == '*': # Only Python 2, local", "importation) def TRY(self, node): handler_names = [] # List the", "isinstance(item, ast.Tuple): return tuple(convert_to_value(i) for i in item.elts) elif isinstance(item,", "isinstance(handler.type, ast.Tuple): for exc_type in handler.type.elts: handler_names.append(getNodeName(exc_type)) elif handler.type: handler_names.append(getNodeName(handler.type))", "for child in node.targets + [node.value]: if not hasattr(child, 'elts'):", "key_counts = counter(keys) duplicate_keys = [ key for key, count", "False def differentForks(self, lnode, rnode): \"\"\"True, if lnode and rnode", "self.scope.isGenerator = True self.handleNode(node.value, node) AWAIT = YIELDFROM = YIELD", "Keep track of globals declarations. \"\"\" global_scope_index = 1 if", "except: block is never entered. This will cause an #", "with a ., avoid the ambiguous '..*' if self.fullName.endswith('.'): return", "def handleNodeDelete(self, node): def on_conditional_branch(): \"\"\" Return `True` if node", "if used and used[0] is self.scope and name not in", "callable passed to L{deferFunction}. The second element is a copy", "Definition) and self.name == other.name def _has_alias(self): \"\"\"Return whether importation", "ELLIPSIS = ignore # \"slice\" type nodes SLICE = EXTSLICE", "def __init__(self, name, source): # A dot should only appear", "self.scope.returnValue) self.deferAssignment(checkReturnWithArgumentInsideGenerator) self.popScope() self.deferFunction(runFunction) def CLASSDEF(self, node): \"\"\" Check names", "a reasonable guess. In Python 3.7, docstrings no # longer", "a function handler to be called just before completion. This", "differentForks(self, lnode, rnode): \"\"\"True, if lnode and rnode are located", "key_first = 'iter'.find elif 'generators' in fields: key_first = 'generators'.find", "\"\"\" Check to see if there is any return statement", "isinstance(binding, Assignment)): yield name, binding class GeneratorScope(Scope): pass class ModuleScope(Scope):", "NONLOCAL = GLOBAL def GENERATOREXP(self, node): self.pushScope(GeneratorScope) self.handleChildren(node) self.popScope() LISTCOMP", "# See note in SubmoduleImportation about RedefinedWhileUnused return self.fullName ==", "item.value else: return UnhandledKeyType() class Binding(object): \"\"\" Represents the binding", "but unused. \"\"\" for scope in self.deadScopes: # imports in", "arglist: if isinstance(arg, ast.Tuple): addArgs(arg.elts) else: args.append(arg.id) addArgs(node.args.args) defaults =", "copy of the scope stack at the time L{deferFunction} was", "1 for value, count in values.items()): for key_index in key_indices:", "node) self.pushScope(ClassScope) # doctest does not process doctest within a", "a mistake self.report(messages.UndefinedLocal, scope[name].used[1], name, scope[name].source) break parent_stmt = self.getParent(node)", "tree. \"\"\" return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and isinstance(node.value,", "ast.PyCF_ONLY_AST) except SyntaxError: e = sys.exc_info()[1] if PYPY: e.offset +=", "unusedAssignments(self): \"\"\" Return a generator for the assignments which have", "ImportationFrom(name, node, module, alias.name) self.addBinding(node, importation) def TRY(self, node): handler_names", "in C{deferred} using their associated scope stack. \"\"\" for handler,", "Assignments, rather it treats them as simple Bindings. \"\"\" class", "determined statically, they will be treated as names for export", "add it here anyway has_starred = False star_loc = -1", "= False alwaysUsed = set(['__tracebackhide__', '__traceback_info__', '__traceback_supplement__']) def __init__(self): super(FunctionScope,", "# Unless it's been removed already. Then do nothing. try:", "and node.test.elts != []: self.report(messages.AssertTuple, node) self.handleChildren(node) def GLOBAL(self, node):", "# Computed incorrectly if the docstring has backslash doctest_lineno =", "%s' % (self.fullName, self.name) else: return 'import %s' % self.fullName", "ast.Import)) package_name = name.split('.')[0] super(SubmoduleImportation, self).__init__(package_name, source) self.fullName = name", "source_statement(self): if self.real_name != self.name: return 'from %s import %s", "self).__init__('*', source) # Each star importation needs a unique name,", "than 1<<8 # assignments are allowed before a stared expression.", "tuple(sorted(fields, key=key_first, reverse=True)) def __missing__(self, node_class): self[node_class] = fields =", "handleChildren NUM = STR = BYTES = ELLIPSIS = ignore", "None # try enclosing function scopes and global scope for", "already reported for this name. # TODO: if the global", "node): if isinstance(self.scope, (ClassScope, ModuleScope)): self.report(messages.ReturnOutsideFunction, node) return if (", "= ImportationFrom(name, node, module, alias.name) self.addBinding(node, importation) def TRY(self, node):", "for hdl in n.handlers] else: def getAlternatives(n): if isinstance(n, ast.If):", "@property def futuresAllowed(self): if not all(isinstance(scope, ModuleScope) for scope in", "key_indices ) if any(count == 1 for value, count in", "if isinstance(self.scope, (ClassScope, ModuleScope)): self.report(messages.YieldOutsideFunction, node) return self.scope.isGenerator = True", "The complete name given to the import statement, possibly including", "super(FutureImportation, self).__init__(name, source, '__future__') self.used = (scope, source) class Argument(Binding):", "+ node.args.kw_defaults # Only for Python3 FunctionDefs is_py3_func = hasattr(node,", "is None: return if self.offset and getattr(node, 'lineno', None) is", "node) elif name == '__all__' and isinstance(self.scope, ModuleScope): binding =", "= messages.ImportShadowedByLoopVar elif used: continue else: messg = messages.RedefinedWhileUnused self.report(messg,", "isinstance(field, list): for item in field: yield item def convert_to_value(item):", "# Only Python 2, local import * is a SyntaxWarning", "for the change - `value` is the new value, a", "in node.decorator_list: self.handleNode(deco, node) for baseNode in node.bases: self.handleNode(baseNode, node)", "< (3, 5) # Python 2.5 to 3.4 try: sys.pypy_version_info", "a 'from x import *' statement.\"\"\" def __init__(self, name, source):", "-= 1 if self.traceTree: print(' ' * self.nodeDepth + 'end", "return '<%s at 0x%x %s>' % (scope_cls, id(self), dict.__repr__(self)) class", "which are not attributes of the builtins module, or #", "def iter_child_nodes(node, omit=None, _fields_order=_FieldsOrder()): \"\"\" Yield all direct child nodes", "probably a mistake self.report(messages.UndefinedLocal, scope[name].used[1], name, scope[name].source) break parent_stmt =", "pass class FunctionScope(Scope): \"\"\" I represent a name scope for", "for binding in scope.values(): if isinstance(binding, StarImportation): binding.used = all_binding", "if node is None: return if self.offset and getattr(node, 'lineno',", "module scope above us for scope in self.scopeStack[:-1]: if not", "= GTE = IS = ISNOT = IN = NOTIN", "('.' * node.level) + (node.module or '') for alias in", "counter(items): \"\"\" Simplest required implementation of collections.Counter. Required as 2.6", "try: sys.pypy_version_info PYPY = True except AttributeError: PYPY = False", "return node_class.__name__.upper() # Python >= 3.3 uses ast.Try instead of", "is at the correct place in the node tree. \"\"\"", "return self.fullName @property def source_statement(self): if self.real_name != self.name: return", "values.items()): for key_index in key_indices: key_node = node.keys[key_index] if isinstance(key,", "of the root module to be accessed. RedefinedWhileUnused is suppressed", "function or module scope above us for scope in self.scopeStack[:-1]:", "in self.scopeStack[-1::-1]: # only generators used in a class scope", "scope.importStarred if in_generators is not False: in_generators = isinstance(scope, GeneratorScope)", "+ n.orelse] + [[hdl] for hdl in n.handlers] else: def", "'args'): node_lineno = max([node_lineno] + [arg.lineno for arg in node.args.args])", "self.handleNodeStore(node) elif isinstance(node.ctx, ast.Del): self.handleNodeDelete(node) else: # must be a", "node): if isinstance(self.scope, (ClassScope, ModuleScope)): self.report(messages.YieldOutsideFunction, node) return self.scope.isGenerator =", "generators used in a class scope can access the names", "False self.nodeDepth += 1 node.depth = self.nodeDepth node.parent = parent", "for exc_type in handler.type.elts: handler_names.append(getNodeName(exc_type)) elif handler.type: handler_names.append(getNodeName(handler.type)) if handler.type", "= compile(example.source, \"<doctest>\", \"exec\", ast.PyCF_ONLY_AST) except SyntaxError: e = sys.exc_info()[1]", "unpacking to be Assignments, rather it treats them as simple", "that deferFunction will fail # noisily if called after we've", "of globals declarations. \"\"\" global_scope_index = 1 if self._in_doctest() else", "IFEXP = SET = \\ COMPARE = CALL = REPR", "if builtins: self.builtIns = self.builtIns.union(builtins) self.withDoctest = withDoctest self.scopeStack =", "try enclosing function scopes and global scope for scope in", "generators before element fields = node_class._fields if 'iter' in fields:", "a literal list containing literal strings. For example:: __all__ =", "n = node while hasattr(n, 'parent'): n, n_child = n.parent,", "= POW = LSHIFT = RSHIFT = \\ BITOR =", "not. See L{Assignment} for a special type of binding that", "executed. return if isinstance(self.scope, FunctionScope) and name in self.scope.globals: self.scope.globals.remove(name)", "3.x: the name of the exception, which is not a", "def getParent(self, node): # Lookup the first parent which is", "of collections.Counter. Required as 2.6 does not have Counter in", "class. \"\"\" class UnhandledKeyType(object): \"\"\" A dictionary key of a", "function and the docstring. node_lineno = node.lineno if hasattr(node, 'args'):", "name, source, scope): if '__all__' in scope and isinstance(source, ast.AugAssign):", "+ e.lineno, example.indent + 4 + (e.offset or 0)) self.report(messages.DoctestSyntaxError,", "False def addBinding(self, node, value): \"\"\" Called when a binding", "does not process doctest within a doctest # classes within", "node) self.addBinding(node, binding) def handleNodeDelete(self, node): def on_conditional_branch(): \"\"\" Return", "IF/TRY\"\"\" ancestor = self.getCommonAncestor(lnode, rnode, self.root) parts = getAlternatives(ancestor) if", "it's in the loop itself if n_child not in n.orelse:", "imported names that aren't used. for value in scope.values(): if", "getattr(self, nodeType) return handler def handleNodeLoad(self, node): name = getNodeName(node)", "# leading whitespace: ... return if not examples: return #", "# doctest does not process doctest within a doctest #", "called just after deferred function handlers. \"\"\" self._deferredAssignments.append((callable, self.scopeStack[:], self.offset))", "+ [[hdl] for hdl in n.handlers] else: def getAlternatives(n): if", "doctest within a doctest, # or in nested functions. if", "FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) ASYNCFUNCTIONDEF = FUNCTIONDEF def LAMBDA(self, node): args", "in self.scope.unusedAssignments(): self.report(messages.UnusedVariable, binding.source, name) self.deferAssignment(checkUnusedAssignments) if PY32: def checkReturnWithArgumentInsideGenerator():", "Look for imported names that aren't used. for value in", "required implementation of collections.Counter. Required as 2.6 does not have", "clause. pyflakes handles this case by registering the root module", "silence # UndefinedLocal warnings. self.handleNode(node.target, node) self.handleNode(node.annotation, node) if node.value:", "rnode, stop): if stop in (lnode, rnode) or not (hasattr(lnode,", "class UnhandledKeyType(object): \"\"\" A dictionary key of a type that", "the submodule is also imported. Python does not restrict which", "A binding created by a from `__future__` import statement. `__future__`", "**kwargs): self.messages.append(messageClass(self.filename, *args, **kwargs)) def getParent(self, node): # Lookup the", "is the statement responsible for the change - `value` is", "self.getCommonAncestor(node, a, stop): return True return False def differentForks(self, lnode,", "return self.fullName @property def source_statement(self): return 'import ' + self.fullName", "NUM = STR = BYTES = ELLIPSIS = ignore #", "return 'import %s as %s' % (self.fullName, self.name) else: return", "ancestor = self.getCommonAncestor(lnode, rnode, self.root) parts = getAlternatives(ancestor) if parts:", "handler(node) finally: self.nodeDepth -= 1 if self.traceTree: print(' ' *", "for operators AND = OR = ADD = SUB =", "current scope. \"\"\" for deco in node.decorator_list: self.handleNode(deco, node) for", "\"\"\" for deco in node.decorator_list: self.handleNode(deco, node) for baseNode in", "advanced tuple unpacking: a, *b, c = d. # Only", "StarImportation): # mark '*' imports as used for each scope", "so that deferFunction will fail # noisily if called after", "ClassScope): continue try: scope[name].used = (self.scope, node) except KeyError: pass", "= self.getParent(node) if isinstance(parent_stmt, (ast.For, ast.comprehension)) or ( parent_stmt !=", "bound within the scope # of the except: block. for", "the missing attribute 'decorator_list' ast.ClassDef.decorator_list = () ast.FunctionDef.decorator_list = property(lambda", "True return False def differentForks(self, lnode, rnode): \"\"\"True, if lnode", "NOTEQ = LT = LTE = GT = GTE =", "False name = getNodeName(node) if not name: return if on_conditional_branch():", "only bound within the scope # of the except: block.", "Simplify: manage the special locals as globals self.globals = self.alwaysUsed.copy()", "self.name else: return self.fullName @property def source_statement(self): if self.real_name !=", "= 1 if self._in_doctest() else 0 global_scope = self.scopeStack[global_scope_index] #", "in the current scope if isinstance(self.scope, FunctionScope) and name not", "false positives. \"\"\" def __init__(self, name, source): # A dot", "= SET = \\ COMPARE = CALL = REPR =", "self.messages if not isinstance(m, messages.UndefinedName) or m.message_args[0] != node_name] #", "self.handleChildren(node) LIST = TUPLE def IMPORT(self, node): for alias in", "declarations. \"\"\" global_scope_index = 1 if self._in_doctest() else 0 global_scope", "in item.elts) elif isinstance(item, ast.Num): return item.n elif isinstance(item, ast.Name):", "the change - `value` is the new value, a Binding", "self.names = [] if isinstance(source.value, (ast.List, ast.Tuple)): for node in", "difference in Python < and >= 3.3 if hasattr(n, 'finalbody')", "imports are implicitly used. \"\"\" def __init__(self, name, source, scope):", "node): \"\"\" Determine if the given node is a docstring,", "('vararg', 'kwarg'): wildcard = getattr(node.args, arg_name) if not wildcard: continue", "== '__future__': if not self.futuresAllowed: self.report(messages.LateFutureImport, node, [n.name for n", "*' statement.\"\"\" def __init__(self, name, source): super(StarImportation, self).__init__('*', source) #", "self.used = (scope, source) class Argument(Binding): \"\"\" Represents binding a", "source, '__future__') self.used = (scope, source) class Argument(Binding): \"\"\" Represents", "a function. @ivar globals: Names declared 'global' in this function.", "or (isinstance(node, ast.Expr) and isinstance(node.value, ast.Str)) def getDocstring(self, node): if", "behaviour so we'll not complain. keys = [ convert_to_value(key) for", "check for duplicates. \"\"\" class VariableKey(object): \"\"\" A dictionary key", "importStarred = importStarred or scope.importStarred if in_generators is not False:", "Only Python 2, local import * is a SyntaxWarning if", "'as' clause, and the submodule is also imported. Python does", "for node_name in node.names: node_value = Assignment(node_name, node) # Remove", "scope in self.scopeStack[global_scope_index + 1:]: scope[node_name] = node_value NONLOCAL =", "the statement responsible for the change - `value` is the", "will not have an unused import warning reported for them.", "AST object. \"\"\" def __init__(self, item): self.name = item.id def", "to be Assignments, rather it treats them as simple Bindings.", "if count > 1 ] for key in duplicate_keys: key_indices", "# \"slice\" type nodes SLICE = EXTSLICE = INDEX =", "accessed. RedefinedWhileUnused is suppressed in `redefines` unless the submodule name", "isinstance(node.value, ast.Str)) def getDocstring(self, node): if isinstance(node, ast.Expr): node =", "the value of a literal list containing literal strings. For", "that deferAssignment will fail # noisily if called after we've", "equivalent to the import.\"\"\" if self._has_alias(): return 'import %s as", "SET = \\ COMPARE = CALL = REPR = ATTRIBUTE", "test due to memory restrictions, but we # add it", "is used as a global or within a loop value.used", "of (L{Scope}, node) indicating the scope and the node that", "node, name, from_list) return if name == '__path__' and os.path.basename(self.filename)", "is a SyntaxWarning if not PY2 and not isinstance(self.scope, ModuleScope):", "and the body of its definition. Additionally, add its name", "# A dot should only appear in the name when", "ast.Tuple): return tuple(convert_to_value(i) for i in item.elts) elif isinstance(item, ast.Num):", "or 0)) self.report(messages.DoctestSyntaxError, node, position) else: self.offset = (node_offset[0] +", "= \\ BITOR = BITXOR = BITAND = FLOORDIV =", "example.lineno, node_offset[1] + example.indent + 4) self.handleChildren(tree) self.offset = node_offset", "self.names = list(scope['__all__'].names) else: self.names = [] if isinstance(source.value, (ast.List,", "cleanliness and sanity of Python code. @ivar _deferredFunctions: Tracking list", "self.handleNode(baseNode, node) if not PY2: for keywordNode in node.keywords: self.handleNode(keywordNode,", "node.parent, self.scope) else: binding = Assignment(name, node) self.addBinding(node, binding) def", "else: self.names = [] if isinstance(source.value, (ast.List, ast.Tuple)): for node", "_fields_order=_FieldsOrder()): \"\"\" Yield all direct child nodes of *node*, that", "self.fullName class ImportationFrom(Importation): def __init__(self, name, source, module, real_name=None): self.module", "import %s as %s' % (self.module, self.real_name, self.name) else: return", "DICT(self, node): # Complain if there are duplicate keys with", "ModuleScope): self.report(messages.ImportStarNotPermitted, node, module) continue self.scope.importStarred = True self.report(messages.ImportStarUsed, node,", "builtin_vars = dir(__import__('__builtin__' if PY2 else 'builtins')) try: import ast", "return [n.body] if isinstance(n, ast.Try): return [n.body + n.orelse] +", "self._nodeHandlers = {} self._deferredFunctions = [] self._deferredAssignments = [] self.deadScopes", "consider assignments in tuple/list unpacking to be Assignments, rather it", "== 1 for value, count in values.items()): for key_index in", "self.getCommonAncestor(lnode, rnode.parent, stop) return self.getCommonAncestor(lnode.parent, rnode.parent, stop) def descendantOf(self, node,", "been used. \"\"\" for name, binding in self.scope.unusedAssignments(): self.report(messages.UnusedVariable, binding.source,", "simple string, creates a local that is only bound within", "# additional node types COMPREHENSION = KEYWORD = FORMATTEDVALUE =", "not in ast.ClassDef._fields: # Patch the missing attribute 'decorator_list' ast.ClassDef.decorator_list", "for value, count in values.items()): for key_index in key_indices: key_node", "a variable. @ivar item: The variable AST object. \"\"\" def", "parts = getAlternatives(ancestor) if parts: for items in parts: if", "if is_py3_func: annotations.append(node.returns) if len(set(args)) < len(args): for (idx, arg)", "if name in self.builtIns: return if importStarred: from_list = []", "self.fullName = full_name or name self.redefined = [] super(Importation, self).__init__(name,", "checkDeadScopes(self): \"\"\" Look at scopes which have been fully examined", "# Walk the tree up until we see a loop", "reported for this name. # TODO: if the global is", "if is_py3_func: if PY33: # Python 2.5 to 3.3 argannotation", "local import * is a SyntaxWarning if not PY2 and", "Handle occurrence of Name (which can be a load/store/delete access.)", "already. Then do nothing. try: del self.scope[node.name] except KeyError: pass", "all_binding = None if all_binding: all_names = set(all_binding.names) undefined =", "from_list = ', '.join(sorted(from_list)) self.report(messages.ImportStarUsage, node, name, from_list) return if", "SUBSCRIPT = \\ STARRED = NAMECONSTANT = handleChildren NUM =", "than two. break has_starred = True star_loc = i if", "not process doctest within a doctest, # or in nested", "global scope. if self.scope is not global_scope: # One 'global'", "not hasattr(child, 'elts'): return False return True def isDocstring(self, node):", "track of which names have been bound and which names", "JOINEDSTR = handleChildren def DICT(self, node): # Complain if there", "self._deferredAssignments = [] self.deadScopes = [] self.messages = [] self.filename", "self.deferAssignment(checkReturnWithArgumentInsideGenerator) self.popScope() self.deferFunction(runFunction) def CLASSDEF(self, node): \"\"\" Check names used", "= name @property def source_statement(self): return 'from ' + self.fullName", "isinstance(self.getParent(existing.source), (ast.For, ast.comprehension))): self.report(messages.RedefinedInListComp, node, value.name, existing.source) elif not existing.used", "TRY def EXCEPTHANDLER(self, node): if PY2 or node.name is None:", "except (ValueError, IndexError): # e.g. line 6 of the docstring", "(node.id == 'locals' and isinstance(self.scope, FunctionScope) and isinstance(node.parent, ast.Call)): #", "= sys.version_info < (3, 5) # Python 2.5 to 3.4", "hasattr(node, 'returns') for arg_name in ('vararg', 'kwarg'): wildcard = getattr(node.args,", "is_name_previously_defined = True break else: is_name_previously_defined = False self.handleNodeStore(node) self.handleChildren(node)", "look in the built-ins if name in self.builtIns: return if", "when it is a submodule import assert '.' in name", "module name otherwise it will be deemed imported self.name =", "run through the deferred assignments. self._deferredAssignments = None del self.scopeStack[1:]", "def getCommonAncestor(self, lnode, rnode, stop): if stop in (lnode, rnode)", "- star_loc - 1 >= 1 << 24: self.report(messages.TooManyExpressionsInStarredAssignment, node)", "< len(node.handlers) - 1: self.report(messages.DefaultExceptNotLast, handler) # Memorize the except", "def TUPLE(self, node): if not PY2 and isinstance(node.ctx, ast.Store): #", "node): if node.module == '__future__': if not self.futuresAllowed: self.report(messages.LateFutureImport, node,", "= node_offset if not underscore_in_builtins: self.builtIns.remove('_') self.popScope() self.scopeStack = saved_stack", "in function # arguments, but these aren't dispatched through here", "statement with arguments but the function is a generator. \"\"\"", "of C{__all__} will not have an unused import warning reported", "docstring. node_lineno = node.lineno if hasattr(node, 'args'): node_lineno = max([node_lineno]", "+ self.fullName + ' import *' def __str__(self): # When", "return in_generators = None importStarred = None # try enclosing", "attributes of the root module may be used. This class", "def __init__(self): super(FunctionScope, self).__init__() # Simplify: manage the special locals", "locals() call in current scope self.scope.usesLocals = True elif isinstance(node.ctx,", "a loop (OK), a function or class # definition (not", "node.module == '__future__': if not self.futuresAllowed: self.report(messages.LateFutureImport, node, [n.name for", "= DIV = MOD = POW = LSHIFT = RSHIFT", "the special locals as globals self.globals = self.alwaysUsed.copy() self.returnValue =", "return not self.fullName.split('.')[-1] == self.name @property def source_statement(self): \"\"\"Generate a", "if i_key == key] values = counter( convert_to_value(node.values[index]) for index", "global used = name in scope and scope[name].used if used", "scope if isinstance(self.scope, FunctionScope) and name not in self.scope: #", "# try enclosing function scopes and global scope for scope", "return item.n elif isinstance(item, ast.Name): result = VariableKey(item=item) constants_lookup =", "node in source.value.elts: if isinstance(node, ast.Str): self.names.append(node.s) super(ExportBinding, self).__init__(name, source)", "doctest_lineno = node.lineno - node.s.count('\\n') - 1 return (node.s, doctest_lineno)", "self._in_doctest() and not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) for stmt in", "self.real_name = real_name or name if module.endswith('.'): full_name = module", "assignment. The checker will raise warnings for any Assignment that", "_fields_order[node.__class__]: if name == omit: continue field = getattr(node, name,", "self.name: return self.fullName + ' as ' + self.name else:", "different forks of IF/TRY\"\"\" ancestor = self.getCommonAncestor(lnode, rnode, self.root) parts", "class Importation(Definition): \"\"\" A binding created by an import statement.", "if module.endswith('.'): full_name = module + self.real_name else: full_name =", "node.lineno if hasattr(node, 'args'): node_lineno = max([node_lineno] + [arg.lineno for", "SETCOMP = GENERATOREXP def NAME(self, node): \"\"\" Handle occurrence of", "getNodeName(node) if not name: return if on_conditional_branch(): # We cannot", "\\ os.path.basename(self.filename) != '__init__.py': # Look for possible mistakes in", "in self.scopeStack): return False return self.scope._futures_allowed @futuresAllowed.setter def futuresAllowed(self, value):", "TUPLE def IMPORT(self, node): for alias in node.names: if '.'", "offset handler() def _in_doctest(self): return (len(self.scopeStack) >= 2 and isinstance(self.scopeStack[1],", "nested functions. if (self.withDoctest and not self._in_doctest() and not isinstance(self.scope,", "inconsistent # leading whitespace: ... return if not examples: return", "list(scope['__all__'].names) else: self.names = [] if isinstance(source.value, (ast.List, ast.Tuple)): for", "its name to the current scope. \"\"\" for deco in", "or isinstance(source, ast.Import)) package_name = name.split('.')[0] super(SubmoduleImportation, self).__init__(package_name, source) self.fullName", "in __future__.all_feature_names: self.report(messages.FutureFeatureNotDefined, node, alias.name) elif alias.name == '*': #", "import is without an 'as' clause. pyflakes handles this case", "= module self.real_name = real_name or name if module.endswith('.'): full_name", "We're removing the local name since it's being unbound #", "if self.offset and getattr(node, 'lineno', None) is not None: node.lineno", "it here anyway has_starred = False star_loc = -1 for", "return 'from %s import %s as %s' % (self.module, self.real_name,", "= [] if PY2: def addArgs(arglist): for arg in arglist:", "all_names = set(all_binding.names) undefined = all_names.difference(scope) else: all_names = undefined", "called just before completion. This is used for handling function", "3 advanced tuple unpacking: a, *b, c = d. #", "Elements of the list are two-tuples. The first element is", "parts: for items in parts: if self.descendantOf(lnode, items, ancestor) ^", "this is skipped during the first iteration if in_generators is", "\"\"\"Scope for a module.\"\"\" _futures_allowed = True class DoctestScope(ModuleScope): \"\"\"Scope", "used. \"\"\" def __init__(self, name, source, scope): super(FutureImportation, self).__init__(name, source,", "# One 'global' statement can bind multiple (comma-delimited) names. for", "3.3 if hasattr(n, 'finalbody') and isinstance(node, ast.Continue): if n_child in", "max([node_lineno] + [arg.lineno for arg in node.args.args]) else: (docstring, node_lineno)", "key in duplicate_keys: key_indices = [i for i, i_key in", "used when the submodule import is without an 'as' clause.", "\"\"\" Represents the binding of a value to a name.", "and name not in self.globals and not self.usesLocals and isinstance(binding,", "self.scope.returnValue ): self.scope.returnValue = node.value self.handleNode(node.value, node) def YIELD(self, node):", "must be a Param context -- this only happens for", "its decorators, base classes, and the body of its definition.", "[n.body] if isinstance(n, ast.TryExcept): return [n.body + n.orelse] + [[hdl]", "self.name == other.name def _has_alias(self): \"\"\"Return whether importation needs an", "(None, None) if PYPY: doctest_lineno = node.lineno - 1 else:", "to see if there is any return statement with arguments", "' + node.__class__.__name__) _getDoctestExamples = doctest.DocTestParser().get_examples def handleDoctests(self, node): try:", "not going to cause potentially # unexpected behaviour so we'll", "importation = ImportationFrom(name, node, module, alias.name) self.addBinding(node, importation) def TRY(self,", "duplicate keys with different values # If they have the", "name = alias.asname or alias.name importation = Importation(name, node, alias.name)", "restrict which attributes of the root module may be used.", "case by registering the root module name in the scope,", "+ ast.TryFinally) if PY32: def getAlternatives(n): if isinstance(n, (ast.If, ast.TryFinally)):", "\"\"\" Represents binding a name as an argument. \"\"\" class", "'__init__.py': # Look for possible mistakes in the export list", "special name __path__ is valid only in packages return #", "scope self.scope.usesLocals = True elif isinstance(node.ctx, (ast.Store, ast.AugStore)): self.handleNodeStore(node) elif", "source, module, real_name=None): self.module = module self.real_name = real_name or", "will cause an # \"undefined name\" error raised if the", "\"\"\" def __init__(self, name, source): self.name = name self.source =", "self.scopeStack[::-1]: if value.name in scope: break existing = scope.get(value.name) if", "and isinstance(node.ctx, ast.Store): # Python 3 advanced tuple unpacking: a,", "= LT = LTE = GT = GTE = IS", "if isinstance(existing, Importation) and isinstance(parent_stmt, ast.For): self.report(messages.ImportShadowedByLoopVar, node, value.name, existing.source)", "def _has_alias(self): \"\"\"Return whether importation needs an as clause.\"\"\" return", "be restored, however it will contain any new bindings added", "ancestor): return True return False def addBinding(self, node, value): \"\"\"", "self._in_doctest() and not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) ASYNCFUNCTIONDEF = FUNCTIONDEF", "scope, it does not # become a globally defined name.", "# Memorize the except handlers and process the body self.exceptHandlers.append(handler_names)", "= FutureImportation(name, node, self.scope) if alias.name not in __future__.all_feature_names: self.report(messages.FutureFeatureNotDefined,", "binding in scope.values(): if isinstance(binding, StarImportation): # mark '*' imports", "if called after we've run through the deferred assignments. self._deferredAssignments", "n.handlers] else: def getAlternatives(n): if isinstance(n, ast.If): return [n.body] if", "+ [node.value]: if not hasattr(child, 'elts'): return False return True", "= hasattr(node, 'returns') for arg_name in ('vararg', 'kwarg'): wildcard =", "name) # mark all import '*' as used by the", "it is at the correct place in the node tree.", "name. # TODO: if the global is not used in", "doctest import os import sys PY2 = sys.version_info < (3,", "ast.If): return [n.body] if isinstance(n, ast.Try): return [n.body + n.orelse]", "simple Bindings. \"\"\" class FunctionDefinition(Definition): pass class ClassDefinition(Definition): pass class", "assume the rebound name is used as a global or", "is going to # be executed. return if isinstance(self.scope, FunctionScope)", "pair of (L{Scope}, node) indicating the scope and the node", "is any return statement with arguments but the function is", "DICTCOMP = SETCOMP = GENERATOREXP def NAME(self, node): \"\"\" Handle", "a copy of the scope stack at the time L{deferFunction}", "self.popScope() LISTCOMP = handleChildren if PY2 else GENERATOREXP DICTCOMP =", "messages.MultiValueRepeatedKeyLiteral, key_node, key, ) self.handleChildren(node) def ASSERT(self, node): if isinstance(node.test,", "= sys.version_info < (3, 4) # Python 2.5 to 3.3", "an argument. \"\"\" class Assignment(Binding): \"\"\" Represents binding a name", "annotations.append(getattr(node.args, argannotation)) else: # Python >= 3.4 annotations.append(wildcard.annotation) if is_py3_func:", "to the current scope. \"\"\" for deco in node.decorator_list: self.handleNode(deco,", "\"\"\"Scope for a doctest.\"\"\" # Globally defined names which are", "scope. \"\"\" for deco in node.decorator_list: self.handleNode(deco, node) for baseNode", "PY2: def addArgs(arglist): for arg in arglist: if isinstance(arg, ast.Tuple):", "process the body self.exceptHandlers.append(handler_names) for child in node.body: self.handleNode(child, node)", "+ n.orelse] + [[hdl] for hdl in n.handlers] if PY34:", "the loop itself if n_child not in n.orelse: return if", "= CONTINUE def RETURN(self, node): if isinstance(self.scope, (ClassScope, ModuleScope)): self.report(messages.ReturnOutsideFunction,", "return if on_conditional_branch(): # We cannot predict if this conditional", "of fields that are lists of nodes. \"\"\" for name", "i in item.elts) elif isinstance(item, ast.Num): return item.n elif isinstance(item,", "and compare.name == self.name ) def __hash__(self): return hash(self.name) class", "* self.nodeDepth + node.__class__.__name__) if self.futuresAllowed and not (isinstance(node, ast.ImportFrom)", "a class definition, including its decorators, base classes, and the", "stop): if stop in (lnode, rnode) or not (hasattr(lnode, 'parent')", "except SyntaxError: e = sys.exc_info()[1] if PYPY: e.offset += 1", "as ' + self.name else: return self.fullName @property def source_statement(self):", "in the name when it is a submodule import assert", "name in self.scope.globals: self.scope.globals.remove(name) else: try: del self.scope[name] except KeyError:", "if self.real_name != self.name: return self.fullName + ' as '", "Only bind the *targets* if the assignment has a value.", "PY2: def getNodeType(node_class): # workaround str.upper() which is locale-dependent return", "(idx, arg) in enumerate(args): if arg in args[:idx]: self.report(messages.DuplicateArgument, node,", "Names which are imported and not otherwise used but appear", "name in the scope, allowing any attribute of the root", "convert_to_value(item): if isinstance(item, ast.Str): return item.s elif hasattr(ast, 'Bytes') and", "if not used: messg = messages.UnusedImport self.report(messg, value.source, str(value)) for", "or ( parent_stmt != node.parent and not self.isLiteralTupleUnpacking(parent_stmt)): binding =", "def handleChildren(self, tree, omit=None): for node in iter_child_nodes(tree, omit=omit): self.handleNode(node,", "self.report(messages.DoctestSyntaxError, node, position) else: self.offset = (node_offset[0] + node_lineno +", "not isinstance(self.getParent(existing.source), (ast.For, ast.comprehension))): self.report(messages.RedefinedInListComp, node, value.name, existing.source) elif not", "used in this scope, it does not # become a", "for (idx, arg) in enumerate(args): if arg in args[:idx]: self.report(messages.DuplicateArgument,", "FORMATTEDVALUE = JOINEDSTR = handleChildren def DICT(self, node): # Complain", "a limit of 1<<24 expressions after the starred expression, #", "built-ins if name in self.builtIns: return if importStarred: from_list =", "USUB = \\ EQ = NOTEQ = LT = LTE", "(which can be a load/store/delete access.) \"\"\" # Locate the", "self.addBinding(node, importation) def IMPORTFROM(self, node): if node.module == '__future__': if", "and all items of fields that are lists of nodes.", "importation needs an as clause.\"\"\" return not self.fullName.split('.')[-1] == self.name", "C{__all__} assignment that can be recognized is one which takes", "was last used. \"\"\" def __init__(self, name, source): self.name =", "forks of IF/TRY\"\"\" ancestor = self.getCommonAncestor(lnode, rnode, self.root) parts =", "EXEC = \\ EXPR = ASSIGN = handleChildren PASS =", "= handleChildren def DICT(self, node): # Complain if there are", "# We're removing the local name since it's being unbound", "Determine if the given node is a docstring, as long", "# ast.Break self.report(messages.BreakOutsideLoop, node) BREAK = CONTINUE def RETURN(self, node):", "name of the exception, which is not a Name node,", "'iter' in fields: key_first = 'iter'.find elif 'generators' in fields:", "\"\"\" Look at scopes which have been fully examined and", "arg in node.args.args + node.args.kwonlyargs: args.append(arg.arg) annotations.append(arg.annotation) defaults = node.args.defaults", "if alias.name not in __future__.all_feature_names: self.report(messages.FutureFeatureNotDefined, node, alias.name) elif alias.name", "'__builtins__', 'WindowsError'] def getNodeName(node): # Returns node.id, or node.name, or", "builtins=None, withDoctest='PYFLAKES_DOCTEST' in os.environ): self._nodeHandlers = {} self._deferredFunctions = []", "change - `value` is the new value, a Binding instance", "`__future__` imports are implicitly used. \"\"\" def __init__(self, name, source,", "appear in the name when it is a submodule import", "their associated scope stack. \"\"\" for handler, scope, offset in", "handleDoctests(self, node): try: if hasattr(node, 'docstring'): docstring = node.docstring #", "isinstance(item, ast.Num): return item.n elif isinstance(item, ast.Name): result = VariableKey(item=item)", "except: block and it's always unbound # if the except:", "in this scope, it does not # become a globally", "but appear in the value of C{__all__} will not have", "Called when a binding is altered. - `node` is the", "all_binding # Look for imported names that aren't used. for", "test_unused_global. self.messages = [ m for m in self.messages if", "def AUGASSIGN(self, node): self.handleNodeLoad(node.target) self.handleNode(node.value, node) self.handleNode(node.target, node) def TUPLE(self,", "are doing locals() call in current scope self.scope.usesLocals = True", "See discussion on https://github.com/PyCQA/pyflakes/pull/59 # We're removing the local name", "# doctest does not process doctest within a doctest, #", "hasattr(node, 'ctx'): return node def getCommonAncestor(self, lnode, rnode, stop): if", "source) def redefines(self, other): if isinstance(other, SubmoduleImportation): # See note", "has inconsistent # leading whitespace: ... return if not examples:", "the exception handlers for i, handler in enumerate(node.handlers): if isinstance(handler.type,", "assignment checks. \"\"\" nodeDepth = 0 offset = None traceTree", "else: (docstring, node_lineno) = self.getDocstring(node.body[0]) examples = docstring and self._getDoctestExamples(docstring)", "node_name] # Bind name to global scope if it doesn't", "to # use the name afterwards. # # Unless it's", "return False name = getNodeName(node) if not name: return if", "messg = messages.RedefinedWhileUnused self.report(messg, node, value.name, value.source) def pushScope(self, scopeClass=FunctionScope):", "scopes. if isinstance(node.ctx, (ast.Load, ast.AugLoad)): self.handleNodeLoad(node) if (node.id == 'locals'", "\"\"\" for name in _fields_order[node.__class__]: if name == omit: continue", "try: if hasattr(node, 'docstring'): docstring = node.docstring # This is", "except AttributeError: PYPY = False builtin_vars = dir(__import__('__builtin__' if PY2", "loop (OK), a function or class # definition (not OK),", "This class is only used when the submodule import is", "name == '__all__' and isinstance(self.scope, ModuleScope): binding = ExportBinding(name, node.parent,", "to 3.3 argannotation = arg_name + 'annotation' annotations.append(getattr(node.args, argannotation)) else:", "self.runDeferred(self._deferredAssignments) # Set _deferredAssignments to None so that deferAssignment will", "assignments in tuple/list unpacking to be Assignments, rather it treats", "'global' statement in global scope. if self.scope is not global_scope:", "True when import * is found def __repr__(self): scope_cls =", "node) for baseNode in node.bases: self.handleNode(baseNode, node) if not PY2:", "predict if this conditional branch is going to # be", "as clause.\"\"\" return not self.fullName.split('.')[-1] == self.name @property def source_statement(self):", "name with alias.\"\"\" if self.real_name != self.name: return self.fullName +", "else: return UnhandledKeyType() class Binding(object): \"\"\" Represents the binding of", "return item.s elif isinstance(item, ast.Tuple): return tuple(convert_to_value(i) for i in", "\"\"\" Schedule a function handler to be called just before", "return self._nodeHandlers[node_class] except KeyError: nodeType = getNodeType(node_class) self._nodeHandlers[node_class] = handler", "node, alias.name) elif alias.name == '*': # Only Python 2,", "imports in classes are public members if isinstance(scope, ClassScope): continue", "and shouldn't silence # UndefinedLocal warnings. self.handleNode(node.target, node) self.handleNode(node.annotation, node)", "existing and not self.differentForks(node, existing.source): parent_stmt = self.getParent(value.source) if isinstance(existing,", "self.nodeDepth node.parent = parent try: handler = self.getNodeHandler(node.__class__) handler(node) finally:", "and hasattr(rnode, 'parent')): return None if lnode is rnode: return", "item.id def __eq__(self, compare): return ( compare.__class__ == self.__class__ and", "a in ancestors: if self.getCommonAncestor(node, a, stop): return True return", "created by a 'from x import *' statement.\"\"\" def __init__(self,", "rnode, self.root) parts = getAlternatives(ancestor) if parts: for items in", "isinstance(parent_stmt, ast.For): self.report(messages.ImportShadowedByLoopVar, node, value.name, existing.source) elif scope is self.scope:", "Definition) and self.name == other.name class Definition(Binding): \"\"\" A binding", "'from ' + self.fullName + ' import *' def __str__(self):", "field: yield item def convert_to_value(item): if isinstance(item, ast.Str): return item.s", "1 return results def iter_child_nodes(node, omit=None, _fields_order=_FieldsOrder()): \"\"\" Yield all", "builtIns = set(builtin_vars).union(_MAGIC_GLOBALS) _customBuiltIns = os.environ.get('PYFLAKES_BUILTINS') if _customBuiltIns: builtIns.update(_customBuiltIns.split(',')) del", "been declared global used = name in scope and scope[name].used", "= getNodeName(node) if not name: return if on_conditional_branch(): # We", "\"\"\"Generate a source statement equivalent to the import.\"\"\" if self._has_alias():", "the assignment has a value. # Otherwise it's not really", "BOOLOP = BINOP = UNARYOP = IFEXP = SET =", "= ASYNCFOR = WHILE = IF = WITH = WITHITEM", "Checker class. Also, it models the Bindings and Scopes. \"\"\"", "SyntaxError: e = sys.exc_info()[1] if PYPY: e.offset += 1 position", "names. for node_name in node.names: node_value = Assignment(node_name, node) #", "node_value NONLOCAL = GLOBAL def GENERATOREXP(self, node): self.pushScope(GeneratorScope) self.handleChildren(node) self.popScope()", "self.scope: if (isinstance(parent_stmt, ast.comprehension) and not isinstance(self.getParent(existing.source), (ast.For, ast.comprehension))): self.report(messages.RedefinedInListComp,", "Patch the missing attribute 'decorator_list' ast.ClassDef.decorator_list = () ast.FunctionDef.decorator_list =", "ast.IfExp)): return True current = getattr(current, 'parent', None) return False", "self.name @property def source_statement(self): \"\"\"Generate a source statement equivalent to", "The variable AST object. \"\"\" def __init__(self, item): self.name =", "PY2 = sys.version_info < (3, 0) PY32 = sys.version_info <", "value to a name. The checker uses this to keep", "'.' in name and (not source or isinstance(source, ast.Import)) package_name", "Param context -- this only happens for names in function", "in n.handlers] if PY34: LOOP_TYPES = (ast.While, ast.For) else: LOOP_TYPES", "builtins: self.builtIns = self.builtIns.union(builtins) self.withDoctest = withDoctest self.scopeStack = [ModuleScope()]", "constants LOAD = STORE = DEL = AUGLOAD = AUGSTORE", "self.handleChildren(node) def ASSERT(self, node): if isinstance(node.test, ast.Tuple) and node.test.elts !=", "doctest within a doctest # classes within classes are processed.", "isinstance(self.scope, FunctionScope) and name in self.scope.globals: self.scope.globals.remove(name) else: try: del", "# We cannot predict if this conditional branch is going", "before element fields = node_class._fields if 'iter' in fields: key_first", "ASSERT(self, node): if isinstance(node.test, ast.Tuple) and node.test.elts != []: self.report(messages.AssertTuple,", "is not None: node.lineno += self.offset[0] node.col_offset += self.offset[1] if", "self.LAMBDA(node) self.addBinding(node, FunctionDefinition(node.name, node)) # doctest does not process doctest", "global_scope_index = 1 if self._in_doctest() else 0 global_scope = self.scopeStack[global_scope_index]", "return True return False def differentForks(self, lnode, rnode): \"\"\"True, if", "self.addBinding(node, binding) def handleNodeDelete(self, node): def on_conditional_branch(): \"\"\" Return `True`", "between the beginning # of the function and the docstring.", "isinstance(self.scope, ModuleScope): self.report(messages.ImportStarNotPermitted, node, module) continue self.scope.importStarred = True self.report(messages.ImportStarUsed,", "elif isinstance(existing, Importation) and value.redefines(existing): existing.redefined.append(node) if value.name in self.scope:", "# Place doctest in module scope saved_stack = self.scopeStack self.scopeStack", "- `value` is the new value, a Binding instance \"\"\"", "One of the many nodes with an id return node.id", "[n.body] if isinstance(n, ast.Try): return [n.body + n.orelse] + [[hdl]", "not self.differentForks(node, existing.source): parent_stmt = self.getParent(value.source) if isinstance(existing, Importation) and", "[node.value]: if not hasattr(child, 'elts'): return False return True def", "for a in ancestors: if self.getCommonAncestor(node, a, stop): return True", "function bodies, which must be deferred because code later in", "the value of C{__all__} will not have an unused import", "0 global_scope = self.scopeStack[global_scope_index] # Ignore 'global' statement in global", "associated scope stack. \"\"\" for handler, scope, offset in deferred:", "Python < and >= 3.3 if hasattr(n, 'finalbody') and isinstance(node,", "or alias.name if node.module == '__future__': importation = FutureImportation(name, node,", "Represents binding a name with an explicit assignment. The checker", "GLOBAL(self, node): \"\"\" Keep track of globals declarations. \"\"\" global_scope_index", "else: try: del self.scope[name] except KeyError: self.report(messages.UndefinedName, node, name) def", "Checker(object): \"\"\" I check the cleanliness and sanity of Python", "def redefines(self, other): if isinstance(other, Importation): return self.fullName == other.fullName", "self.addBinding(node, FunctionDefinition(node.name, node)) # doctest does not process doctest within", "line numbers associated with them. This will be # incorrect", "'returnValue') and not self.scope.returnValue ): self.scope.returnValue = node.value self.handleNode(node.value, node)", "doesn't distinguish two from more # than two. break has_starred", "alias.\"\"\" if self.real_name != self.name: return self.fullName + ' as", "in the list can be determined statically, they will be", "whether importation needs an as clause.\"\"\" return not self.fullName.split('.')[-1] ==", "been removed already. Then do nothing. try: del self.scope[node.name] except", "*b, c = d. # Only one starred expression is", "in the node tree. \"\"\" return isinstance(node, ast.Str) or (isinstance(node,", "if not PY2: for keywordNode in node.keywords: self.handleNode(keywordNode, node) self.pushScope(ClassScope)", "this to keep track of which names have been bound", "which names have been bound and which names have not.", "the callable passed to L{deferFunction}. The second element is a", "handleNodeStore(self, node): name = getNodeName(node) if not name: return #", "scope[node_name] = node_value NONLOCAL = GLOBAL def GENERATOREXP(self, node): self.pushScope(GeneratorScope)", "= VariableKey(item=item) constants_lookup = { 'True': True, 'False': False, 'None':", "checked code tries to # use the name afterwards. #", "node): if isinstance(node.test, ast.Tuple) and node.test.elts != []: self.report(messages.AssertTuple, node)", "Represents the binding of a value to a name. The", "self.name: return 'from %s import %s as %s' % (self.module,", "if PY2 or node.name is None: self.handleChildren(node) return # 3.x:", "is rnode: return lnode if (lnode.depth > rnode.depth): return self.getCommonAncestor(lnode.parent,", "self).__init__(package_name, source) self.fullName = name def redefines(self, other): if isinstance(other,", "in them which were imported but unused. \"\"\" for scope", "\\ STARRED = NAMECONSTANT = handleChildren NUM = STR =", "if ( node.value and hasattr(self.scope, 'returnValue') and not self.scope.returnValue ):", "of 1<<24 expressions after the starred expression, # which is", "AUGSTORE = PARAM = ignore # same for operators AND", "and \\ os.path.basename(self.filename) != '__init__.py': # Look for possible mistakes", "does not # become a globally defined name. See test_unused_global.", "+ self.real_name else: full_name = module + '.' + self.real_name", "star_loc - 1 >= 1 << 24: self.report(messages.TooManyExpressionsInStarredAssignment, node) self.handleChildren(node)", "= [\"foo\", \"bar\"] Names which are imported and not otherwise", "def descendantOf(self, node, ancestors, stop): for a in ancestors: if", "def handleNodeLoad(self, node): name = getNodeName(node) if not name: return", "'parent', None) return False name = getNodeName(node) if not name:", "name not in self.scope.globals: # then it's probably a mistake", "node.body: self.handleNode(stmt, node) self.popScope() self.addBinding(node, ClassDefinition(node.name, node)) def AUGASSIGN(self, node):", "True elif isinstance(node.ctx, (ast.Store, ast.AugStore)): self.handleNodeStore(node) elif isinstance(node.ctx, ast.Del): self.handleNodeDelete(node)", "getattr(node, 'parent', None) while current: if isinstance(current, (ast.If, ast.While, ast.IfExp)):", "self.handleNode(deco, node) for baseNode in node.bases: self.handleNode(baseNode, node) if not", "dictionary key which is a variable. @ivar item: The variable", "functions. self._deferredFunctions = None self.runDeferred(self._deferredAssignments) # Set _deferredAssignments to None", "WITHITEM = \\ ASYNCWITH = ASYNCWITHITEM = RAISE = TRYFINALLY", "is a variable. @ivar item: The variable AST object. \"\"\"", "else 0 global_scope = self.scopeStack[global_scope_index] # Ignore 'global' statement in", "isinstance(source, ast.AugAssign): self.names = list(scope['__all__'].names) else: self.names = [] if", "= item.id def __eq__(self, compare): return ( compare.__class__ == self.__class__", "not name: return if on_conditional_branch(): # We cannot predict if", "= set(['__tracebackhide__', '__traceback_info__', '__traceback_supplement__']) def __init__(self): super(FunctionScope, self).__init__() # Simplify:", "node.s.count('\\n') - 1 return (node.s, doctest_lineno) def handleNode(self, node, parent):", "in field: yield item def convert_to_value(item): if isinstance(item, ast.Str): return", "scope.get('__all__') if all_binding and not isinstance(all_binding, ExportBinding): all_binding = None", "discussion on https://github.com/PyCQA/pyflakes/pull/59 # We're removing the local name since", "def on_conditional_branch(): \"\"\" Return `True` if node is part of", "Complain if there are duplicate keys with different values #", "return 'import %s' % self.fullName def __str__(self): \"\"\"Return import full", "function or class # definition (not OK), for 'continue', a", "Schedule a function handler to be called just before completion.", "__repr__(self): return '<%s object %r from line %r at 0x%x>'", "node_lineno) = self.getDocstring(node.body[0]) examples = docstring and self._getDoctestExamples(docstring) except (ValueError,", "self.getNodeHandler(node.__class__) handler(node) finally: self.nodeDepth -= 1 if self.traceTree: print(' '", "item.s elif isinstance(item, ast.Tuple): return tuple(convert_to_value(i) for i in item.elts)", "arg_name + 'annotation' annotations.append(getattr(node.args, argannotation)) else: # Python >= 3.4", "not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) ASYNCFUNCTIONDEF = FUNCTIONDEF def LAMBDA(self,", "\"\"\" for name, binding in self.items(): if (not binding.used and", "\"\"\" Called when a binding is altered. - `node` is", "of a conditional body. \"\"\" current = getattr(node, 'parent', None)", "in nested functions. if (self.withDoctest and not self._in_doctest() and not", "def handleDoctests(self, node): try: if hasattr(node, 'docstring'): docstring = node.docstring", "self.real_name, self.name) else: return 'from %s import %s' % (self.module,", "a type that we cannot or do not check for", "args.append(arg.arg) annotations.append(arg.annotation) defaults = node.args.defaults + node.args.kw_defaults # Only for", "node, module) importation = StarImportation(module, node) else: importation = ImportationFrom(name,", "self.report( messages.MultiValueRepeatedKeyLiteral, key_node, key, ) self.handleChildren(node) def ASSERT(self, node): if", "(node.ctx,)) def CONTINUE(self, node): # Walk the tree up until", "is not a Name node, but # a simple string,", "node tree. \"\"\" return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and", "self.scope.isGenerator and self.scope.returnValue: self.report(messages.ReturnWithArgsInsideGenerator, self.scope.returnValue) self.deferAssignment(checkReturnWithArgumentInsideGenerator) self.popScope() self.deferFunction(runFunction) def CLASSDEF(self,", "for a special type of binding that is checked with", "self.report(messages.AssertTuple, node) self.handleChildren(node) def GLOBAL(self, node): \"\"\" Keep track of", "uses this to keep track of which names have been", "type of binding that is checked with stricter rules. @ivar", "%s as %s' % (self.fullName, self.name) else: return 'import %s'", "and scope[name].used if used and used[0] is self.scope and name", "annotations.append(wildcard.annotation) if is_py3_func: annotations.append(node.returns) if len(set(args)) < len(args): for (idx,", "in a class definition, including its decorators, base classes, and", "while current: if isinstance(current, (ast.If, ast.While, ast.IfExp)): return True current", "value): assert value is False if isinstance(self.scope, ModuleScope): self.scope._futures_allowed =", "or '') for alias in node.names: name = alias.asname or", "= self.scopeStack[global_scope_index] # Ignore 'global' statement in global scope. if", "node in value.redefined: if isinstance(self.getParent(node), ast.For): messg = messages.ImportShadowedByLoopVar elif", "\"\"\" class Assignment(Binding): \"\"\" Represents binding a name with an", "as used for each scope binding.used = (self.scope, node) from_list.append(binding.fullName)", "convert_to_value(key) for key in node.keys ] key_counts = counter(keys) duplicate_keys", "fields = self._get_fields(node_class) return fields def counter(items): \"\"\" Simplest required", "else: args.append(arg.id) addArgs(node.args.args) defaults = node.args.defaults else: for arg in", "messages.UnusedImport self.report(messg, value.source, str(value)) for node in value.redefined: if isinstance(self.getParent(node),", "name is also the same, to avoid false positives. \"\"\"", "if isinstance(node, ast.Continue): self.report(messages.ContinueOutsideLoop, node) else: # ast.Break self.report(messages.BreakOutsideLoop, node)", "and hasattr(self.scope, 'returnValue') and not self.scope.returnValue ): self.scope.returnValue = node.value", "load/store/delete access.) \"\"\" # Locate the name in locals /", "' + self.fullName + ' import *' def __str__(self): #", "False module = ('.' * node.level) + (node.module or '')", "def __missing__(self, node_class): self[node_class] = fields = self._get_fields(node_class) return fields", "name has # been accessed already in the current scope,", "(3, 3) # Python 2.5 to 3.2 PY33 = sys.version_info", "BITAND = FLOORDIV = INVERT = NOT = UADD =", "aren't dispatched through here raise RuntimeError(\"Got impossible expression context: %r\"", "'lineno', None) is not None: node.lineno += self.offset[0] node.col_offset +=", "A dot should only appear in the name when it", "- `node` is the statement responsible for the change -", "self.scope.globals.remove(name) else: try: del self.scope[name] except KeyError: self.report(messages.UndefinedName, node, name)", "isinstance(n, LOOP_TYPES): # Doesn't apply unless it's in the loop", "hasattr(node, 'docstring'): docstring = node.docstring # This is just a", "= all_names.difference(scope) else: all_names = undefined = [] if undefined:", "global is not used in this scope, it does not", "continue args.append(wildcard if PY33 else wildcard.arg) if is_py3_func: if PY33:", "self.scope.returnValue: self.report(messages.ReturnWithArgsInsideGenerator, self.scope.returnValue) self.deferAssignment(checkReturnWithArgumentInsideGenerator) self.popScope() self.deferFunction(runFunction) def CLASSDEF(self, node): \"\"\"", "are processed. if (self.withDoctest and not self._in_doctest() and not isinstance(self.scope,", "binding in scope.values(): if isinstance(binding, StarImportation): binding.used = all_binding #", "= getattr(self, nodeType) return handler def handleNodeLoad(self, node): name =", "though being constants LOAD = STORE = DEL = AUGLOAD", "self.deadScopes: # imports in classes are public members if isinstance(scope,", "not hasattr(node, 'elts') and not hasattr(node, 'ctx'): return node def", "False and isinstance(scope, ClassScope): continue try: scope[name].used = (self.scope, node)", "or (0, 0) self.pushScope(DoctestScope) underscore_in_builtins = '_' in self.builtIns if", "a from `__future__` import statement. `__future__` imports are implicitly used.", "names that aren't used. for value in scope.values(): if isinstance(value,", "PY33 = sys.version_info < (3, 4) # Python 2.5 to", "in a class scope can access the names # of", "node_value = Assignment(node_name, node) # Remove UndefinedName messages already reported", "the time L{deferFunction} was called. @ivar _deferredAssignments: Similar to C{_deferredFunctions},", "if hasattr(node, 'args'): node_lineno = max([node_lineno] + [arg.lineno for arg", "but these aren't dispatched through here raise RuntimeError(\"Got impossible expression", "stmt in node.body: self.handleNode(stmt, node) else: # case for Lambdas", "PY32: def checkReturnWithArgumentInsideGenerator(): \"\"\" Check to see if there is", "+ '.' + self.real_name super(ImportationFrom, self).__init__(name, source, full_name) def __str__(self):", "or class # definition (not OK), for 'continue', a finally", "for child in node.body: self.handleNode(child, node) self.exceptHandlers.pop() # Process the", "of IF/TRY\"\"\" ancestor = self.getCommonAncestor(lnode, rnode, self.root) parts = getAlternatives(ancestor)", "return (node.s, doctest_lineno) def handleNode(self, node, parent): if node is", "for Python3 FunctionDefs is_py3_func = hasattr(node, 'returns') for arg_name in", "GT = GTE = IS = ISNOT = IN =", "suppressed in `redefines` unless the submodule name is also the", "self.pushScope() for name in args: self.addBinding(node, Argument(name, node)) if isinstance(node.body,", "Scopes. \"\"\" import __future__ import doctest import os import sys", "# Patch the missing attribute 'decorator_list' ast.ClassDef.decorator_list = () ast.FunctionDef.decorator_list", "= TRYFINALLY = EXEC = \\ EXPR = ASSIGN =", "False are nameconstants in python3, but names in 2 return", "because code later in the file might modify the global", "arg) for child in annotations + defaults: if child: self.handleNode(child,", "already. global_scope.setdefault(node_name, node_value) # Bind name to non-global scopes, but", "for deco in node.decorator_list: self.handleNode(deco, node) for baseNode in node.bases:", "from pyflakes import messages if PY2: def getNodeType(node_class): # workaround", "self.withDoctest = withDoctest self.scopeStack = [ModuleScope()] self.exceptHandlers = [()] self.root", "otherwise it will be deemed imported self.name = name +", "# Process the other nodes: \"except:\", \"else:\", \"finally:\" self.handleChildren(node, omit='body')", "collections. \"\"\" results = {} for item in items: results[item]", "of Python code. @ivar _deferredFunctions: Tracking list used by L{deferFunction}.", "name == '__path__' and os.path.basename(self.filename) == '__init__.py': # the special", "hasattr(node, 'args'): node_lineno = max([node_lineno] + [arg.lineno for arg in", "nodes DELETE = PRINT = FOR = ASYNCFOR = WHILE", "# Python 2.5 to 3.2 PY33 = sys.version_info < (3,", "getParent(self, node): # Lookup the first parent which is not", "= node.value if not isinstance(node, ast.Str): return (None, None) if", "self.getCommonAncestor(lnode, rnode, self.root) parts = getAlternatives(ancestor) if parts: for items", "in_generators = isinstance(scope, GeneratorScope) # look in the built-ins if", "scope.values(): if isinstance(binding, StarImportation): binding.used = all_binding # Look for", "Argument(name, node)) if isinstance(node.body, list): # case for FunctionDefs for", "count in values.items()): for key_index in key_indices: key_node = node.keys[key_index]", "= True star_loc = i if star_loc >= 1 <<", "counter( convert_to_value(node.values[index]) for index in key_indices ) if any(count ==", "if not hasattr(node, 'elts') and not hasattr(node, 'ctx'): return node", "pushScope(self, scopeClass=FunctionScope): self.scopeStack.append(scopeClass()) def report(self, messageClass, *args, **kwargs): self.messages.append(messageClass(self.filename, *args,", "in name and (not source or isinstance(source, ast.Import)) package_name =", "generator for the assignments which have not been used. \"\"\"", "node)) # doctest does not process doctest within a doctest,", "None importStarred = None # try enclosing function scopes and", "1 ] for key in duplicate_keys: key_indices = [i for", "ModuleScope)): self.report(messages.YieldOutsideFunction, node) return self.scope.isGenerator = True self.handleNode(node.value, node) AWAIT", "and sanity of Python code. @ivar _deferredFunctions: Tracking list used", "ast.comprehension)) or ( parent_stmt != node.parent and not self.isLiteralTupleUnpacking(parent_stmt)): binding", ">= 3.3 uses ast.Try instead of (ast.TryExcept + ast.TryFinally) if", ") def __hash__(self): return hash(self.name) class Importation(Definition): \"\"\" A binding", "child: self.handleNode(child, node) def runFunction(): self.pushScope() for name in args:", "are implicitly used. \"\"\" def __init__(self, name, source, scope): super(FutureImportation,", "PY2 else 'builtins')) try: import ast except ImportError: # Python", "ExportBinding(name, node.parent, self.scope) else: binding = Assignment(name, node) self.addBinding(node, binding)", "self.scope[name] except KeyError: self.report(messages.UndefinedName, node, name) def handleChildren(self, tree, omit=None):", "Importation(Definition): \"\"\" A binding created by an import statement. @ivar", "+ 4) self.handleChildren(tree) self.offset = node_offset if not underscore_in_builtins: self.builtIns.remove('_')", "and isinstance(self.scope, ModuleScope): binding = ExportBinding(name, node.parent, self.scope) else: binding", "occurrence of Name (which can be a load/store/delete access.) \"\"\"", "going to # be executed. return if isinstance(self.scope, FunctionScope) and", "__init__(self): super(FunctionScope, self).__init__() # Simplify: manage the special locals as", "binding in self.items(): if (not binding.used and name not in", "already been defined in the current scope if isinstance(self.scope, FunctionScope)", "'docstring'): docstring = node.docstring # This is just a reasonable", "is not used in this scope, it does not #", "self.scopeStack[::-1]: if node.name in scope: is_name_previously_defined = True break else:", "if isinstance(value, Importation): used = value.used or value.name in all_names", "def __init__(self, name, source): self.name = name self.source = source", "< (3, 0) PY32 = sys.version_info < (3, 3) #", "\"\"\" A binding that defines a function or a class.", "is part of a conditional body. \"\"\" current = getattr(node,", "classes, and the body of its definition. Additionally, add its", "isinstance(item, ast.Bytes): return item.s elif isinstance(item, ast.Tuple): return tuple(convert_to_value(i) for", "two from more # than two. break has_starred = True", "node, arg) for child in annotations + defaults: if child:", "self.pushScope(ClassScope) # doctest does not process doctest within a doctest", "the function is a generator. \"\"\" if self.scope.isGenerator and self.scope.returnValue:", "node return node.name class Checker(object): \"\"\" I check the cleanliness", "and process the body self.exceptHandlers.append(handler_names) for child in node.body: self.handleNode(child,", "the body self.exceptHandlers.append(handler_names) for child in node.body: self.handleNode(child, node) self.exceptHandlers.pop()", "StarImportation): binding.used = all_binding # Look for imported names that", "+= self.offset[0] node.col_offset += self.offset[1] if self.traceTree: print(' ' *", "passed to L{deferFunction}. The second element is a copy of", "in key_indices: key_node = node.keys[key_index] if isinstance(key, VariableKey): self.report(messages.MultiValueRepeatedKeyVariable, key_node,", "do not check for duplicates. \"\"\" class VariableKey(object): \"\"\" A", "name, source): super(StarImportation, self).__init__('*', source) # Each star importation needs", "(ast.While, ast.For, ast.AsyncFor) class _FieldsOrder(dict): \"\"\"Fix order of AST node", "self.handleNode(node, tree) def isLiteralTupleUnpacking(self, node): if isinstance(node, ast.Assign): for child", "= JOINEDSTR = handleChildren def DICT(self, node): # Complain if", "different values # If they have the same value it's", "n if isinstance(n, LOOP_TYPES): # Doesn't apply unless it's in", "globals: Names declared 'global' in this function. \"\"\" usesLocals =", "for arg in arglist: if isinstance(arg, ast.Tuple): addArgs(arg.elts) else: args.append(arg.id)", "lines between the beginning # of the function and the", "'from %s import %s' % (self.module, self.name) class StarImportation(Importation): \"\"\"A", "new value, a Binding instance \"\"\" # assert value.source in", "= STR = BYTES = ELLIPSIS = ignore # \"slice\"", "and >= 3.3 if hasattr(n, 'finalbody') and isinstance(node, ast.Continue): if", "report * usage, with a list of possible sources from_list", "!= self.name: return self.fullName + ' as ' + self.name", "futuresAllowed(self, value): assert value is False if isinstance(self.scope, ModuleScope): self.scope._futures_allowed", "# been declared global used = name in scope and", "submodule import is a special case where the root module", "module scope (not OK) n = node while hasattr(n, 'parent'):", "return self.scopeStack[-1] def popScope(self): self.deadScopes.append(self.scopeStack.pop()) def checkDeadScopes(self): \"\"\" Look at", "process doctest within a doctest, # or in nested functions.", "dotted components. @type fullName: C{str} \"\"\" def __init__(self, name, source,", "(node.module or '') for alias in node.names: name = alias.asname", "an 'as' clause. pyflakes handles this case by registering the", "if name == omit: continue field = getattr(node, name, None)", "if isinstance(self.scope, ModuleScope): self.scope._futures_allowed = False @property def scope(self): return", "self.deadScopes = [] self.messages = [] self.filename = filename if", "self.scope: # for each function or module scope above us", "isinstance(self.scopeStack[1], DoctestScope)) @property def futuresAllowed(self): if not all(isinstance(scope, ModuleScope) for", "False self.handleNodeStore(node) self.handleChildren(node) if not is_name_previously_defined: # See discussion on", "ClassScope(Scope): pass class FunctionScope(Scope): \"\"\" I represent a name scope", "\\ MATMULT = ignore # additional node types COMPREHENSION =", "Bindings. \"\"\" class FunctionDefinition(Definition): pass class ClassDefinition(Definition): pass class ExportBinding(Binding):", "statement. `__future__` imports are implicitly used. \"\"\" def __init__(self, name,", "value.name in all_names if not used: messg = messages.UnusedImport self.report(messg,", "omit=None): for node in iter_child_nodes(tree, omit=omit): self.handleNode(node, tree) def isLiteralTupleUnpacking(self,", "has a value. # Otherwise it's not really ast.Store and", "ast.Expr): node = node.value if not isinstance(node, ast.Str): return (None,", "key which is a variable. @ivar item: The variable AST", "= FOR = ASYNCFOR = WHILE = IF = WITH", "# may not be the module name otherwise it will", "underscore_in_builtins: self.builtIns.add('_') for example in examples: try: tree = compile(example.source,", "self.getDocstring(node.body[0]) examples = docstring and self._getDoctestExamples(docstring) except (ValueError, IndexError): #", "binding in self.scope.unusedAssignments(): self.report(messages.UnusedVariable, binding.source, name) self.deferAssignment(checkUnusedAssignments) if PY32: def", "object %r from line %r at 0x%x>' % (self.__class__.__name__, self.name,", "importStarred = False # set to True when import *", "else: full_name = module + '.' + self.real_name super(ImportationFrom, self).__init__(name,", "full_name or name self.redefined = [] super(Importation, self).__init__(name, source) def", "only generators used in a class scope can access the", "= node_value NONLOCAL = GLOBAL def GENERATOREXP(self, node): self.pushScope(GeneratorScope) self.handleChildren(node)", "'locals' and isinstance(self.scope, FunctionScope) and isinstance(node.parent, ast.Call)): # we are", "SUB = MULT = DIV = MOD = POW =", "When `callable` is called, the scope at the time this", "node_offset[1] + example.indent + 4) self.handleChildren(tree) self.offset = node_offset if", "node_lineno = max([node_lineno] + [arg.lineno for arg in node.args.args]) else:", "a Param context -- this only happens for names in", "global_scope = self.scopeStack[global_scope_index] # Ignore 'global' statement in global scope.", "to see if any assignments have not been used. \"\"\"", "binding created by a from `__future__` import statement. `__future__` imports", "for a module.\"\"\" _futures_allowed = True class DoctestScope(ModuleScope): \"\"\"Scope for", "Python 2.5 to 3.4 try: sys.pypy_version_info PYPY = True except", "isinstance(n, ast.If): return [n.body] if isinstance(n, ast.Try): return [n.body +", "None: node.lineno += self.offset[0] node.col_offset += self.offset[1] if self.traceTree: print('", "(ClassScope, ModuleScope)): self.report(messages.ReturnOutsideFunction, node) return if ( node.value and hasattr(self.scope,", "+= 1 node.depth = self.nodeDepth node.parent = parent try: handler", "in node.keywords: self.handleNode(keywordNode, node) self.pushScope(ClassScope) # doctest does not process", "1 << 24: self.report(messages.TooManyExpressionsInStarredAssignment, node) self.handleChildren(node) LIST = TUPLE def", "self.handleNode(stmt, node) else: # case for Lambdas self.handleNode(node.body, node) def", "[] self.filename = filename if builtins: self.builtIns = self.builtIns.union(builtins) self.withDoctest", "\"\"\" A binding created by a from `__future__` import statement.", "if existing and not self.differentForks(node, existing.source): parent_stmt = self.getParent(value.source) if", "False if isinstance(self.scope, ModuleScope): self.scope._futures_allowed = False @property def scope(self):", "__hash__(self): return hash(self.name) class Importation(Definition): \"\"\" A binding created by", "L{deferFunction}. Elements of the list are two-tuples. The first element", "== other.name def _has_alias(self): \"\"\"Return whether importation needs an as", "return if self.offset and getattr(node, 'lineno', None) is not None:", "= [ModuleScope()] self.exceptHandlers = [()] self.root = tree self.handleChildren(tree) self.runDeferred(self._deferredFunctions)", "items: results[item] = results.get(item, 0) + 1 return results def", "self).__init__() # Simplify: manage the special locals as globals self.globals", "_customBuiltIns: builtIns.update(_customBuiltIns.split(',')) del _customBuiltIns def __init__(self, tree, filename='(none)', builtins=None, withDoctest='PYFLAKES_DOCTEST'", "saved_stack = self.scopeStack self.scopeStack = [self.scopeStack[0]] node_offset = self.offset or", "is impossible to test due to memory restrictions, but we", "implicitly used. \"\"\" def __init__(self, name, source, scope): super(FutureImportation, self).__init__(name,", "if not self.futuresAllowed: self.report(messages.LateFutureImport, node, [n.name for n in node.names])", "= value.used or value.name in all_names if not used: messg", "were imported but unused. \"\"\" for scope in self.deadScopes: #", "long as it is at the correct place in the", "statement can bind multiple (comma-delimited) names. for node_name in node.names:", "defined in the current scope if isinstance(self.scope, FunctionScope) and name", "statement equivalent to the import.\"\"\" if self._has_alias(): return 'import %s", "called, the scope at the time this is called will", "isinstance(scope, (FunctionScope, ModuleScope)): continue # if the name was defined", "constants_lookup = { 'True': True, 'False': False, 'None': None, }", "handleNodeLoad(self, node): name = getNodeName(node) if not name: return in_generators", "there are duplicate keys with different values # If they", "self.name) else: return 'from %s import %s' % (self.module, self.name)", "futuresAllowed(self): if not all(isinstance(scope, ModuleScope) for scope in self.scopeStack): return", "# expression contexts are node instances too, though being constants", "# One of the many nodes with an id return", "self.getCommonAncestor(lnode.parent, rnode.parent, stop) def descendantOf(self, node, ancestors, stop): for a", "L{deferFunction}. The second element is a copy of the scope", "return item.value else: return UnhandledKeyType() class Binding(object): \"\"\" Represents the", "if handler.type is None and i < len(node.handlers) - 1:", "in fields: key_first = 'iter'.find elif 'generators' in fields: key_first", "node.args.kw_defaults # Only for Python3 FunctionDefs is_py3_func = hasattr(node, 'returns')", "node_lineno = node.lineno if hasattr(node, 'args'): node_lineno = max([node_lineno] +", "Python 2.5 to 3.3 PY34 = sys.version_info < (3, 5)", "2.5 to 3.4 try: sys.pypy_version_info PYPY = True except AttributeError:", "< (3, 4) # Python 2.5 to 3.3 PY34 =", "the global scope. When `callable` is called, the scope at", "docstring has backslash doctest_lineno = node.lineno - node.s.count('\\n') - 1", "it's always unbound # if the except: block is never", "code. @ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements of", "workaround str.upper() which is locale-dependent return str(unicode(node_class.__name__).upper()) else: def getNodeType(node_class):", "import warning reported for them. \"\"\" def __init__(self, name, source,", "name + '.*' self.fullName = name @property def source_statement(self): return", "doctest does not process doctest within a doctest # classes", "the callables in C{deferred} using their associated scope stack. \"\"\"", "() ast.FunctionDef.decorator_list = property(lambda s: s.decorators) from pyflakes import messages", "after we've run through the deferred functions. self._deferredFunctions = None", "to keep track of which names have been bound and", "in self.messages if not isinstance(m, messages.UndefinedName) or m.message_args[0] != node_name]", "self._get_fields(node_class) return fields def counter(items): \"\"\" Simplest required implementation of", "self.report(messg, node, value.name, value.source) def pushScope(self, scopeClass=FunctionScope): self.scopeStack.append(scopeClass()) def report(self,", "function # arguments, but these aren't dispatched through here raise", "has_starred = True star_loc = i if star_loc >= 1", "in source.value.elts: if isinstance(node, ast.Str): self.names.append(node.s) super(ExportBinding, self).__init__(name, source) class", "if hasattr(node, 'name'): # an ExceptHandler node return node.name class", "[] # List the exception handlers for i, handler in", "_get_fields(self, node_class): # handle iter before target, and generators before", "two-tuples. The first element is the callable passed to L{deferFunction}.", "def __str__(self): # When the module ends with a .,", "which is locale-dependent return str(unicode(node_class.__name__).upper()) else: def getNodeType(node_class): return node_class.__name__.upper()", "class ModuleScope(Scope): \"\"\"Scope for a module.\"\"\" _futures_allowed = True class", "or None if hasattr(node, 'id'): # One of the many", "any new bindings added to it. \"\"\" self._deferredFunctions.append((callable, self.scopeStack[:], self.offset))", "scope in self.scopeStack[::-1]: if node.name in scope: is_name_previously_defined = True", "Then do nothing. try: del self.scope[node.name] except KeyError: pass def", "import *' def __str__(self): # When the module ends with", "that this binding was last used. \"\"\" def __init__(self, name,", "ast.Assign): for child in node.targets + [node.value]: if not hasattr(child,", "handler? if 'NameError' not in self.exceptHandlers[-1]: self.report(messages.UndefinedName, node, name) def", "or Starred while True: node = node.parent if not hasattr(node,", "# If the assignment has value, handle the *value* now.", "return if isinstance(n, (ast.FunctionDef, ast.ClassDef)): break # Handle Try/TryFinally difference", "node.level) + (node.module or '') for alias in node.names: name", "to cause potentially # unexpected behaviour so we'll not complain.", "_futures_allowed = True class DoctestScope(ModuleScope): \"\"\"Scope for a doctest.\"\"\" #", "# then assume the rebound name is used as a", "self._has_alias(): return self.fullName + ' as ' + self.name else:", "Importation) and isinstance(parent_stmt, ast.For): self.report(messages.ImportShadowedByLoopVar, node, value.name, existing.source) elif scope", "__init__(self, name, source, full_name=None): self.fullName = full_name or name self.redefined", "list of possible sources from_list = ', '.join(sorted(from_list)) self.report(messages.ImportStarUsage, node,", "try: scope[name].used = (self.scope, node) except KeyError: pass else: return", "the binding of a value to a name. The checker", "return self.source_statement else: return self.name class FutureImportation(ImportationFrom): \"\"\" A binding", "or alias.name importation = Importation(name, node, alias.name) self.addBinding(node, importation) def", "if isinstance(handler.type, ast.Tuple): for exc_type in handler.type.elts: handler_names.append(getNodeName(exc_type)) elif handler.type:", "= None del self.scopeStack[1:] self.popScope() self.checkDeadScopes() def deferFunction(self, callable): \"\"\"", "doctest.\"\"\" # Globally defined names which are not attributes of", "KEYWORD = FORMATTEDVALUE = JOINEDSTR = handleChildren def DICT(self, node):", "fully examined and report names in them which were imported", "reverse=True)) def __missing__(self, node_class): self[node_class] = fields = self._get_fields(node_class) return", "self.report(messages.ReturnOutsideFunction, node) return if ( node.value and hasattr(self.scope, 'returnValue') and", "(e.offset or 0)) self.report(messages.DoctestSyntaxError, node, position) else: self.offset = (node_offset[0]", "node): # Complain if there are duplicate keys with different", "= node.value self.handleNode(node.value, node) def YIELD(self, node): if isinstance(self.scope, (ClassScope,", "self.getCommonAncestor(lnode.parent, rnode, stop) if (lnode.depth < rnode.depth): return self.getCommonAncestor(lnode, rnode.parent,", "in duplicate_keys: key_indices = [i for i, i_key in enumerate(keys)", "noisily if called after we've run through the deferred functions.", "'__all__' and isinstance(self.scope, ModuleScope): binding = ExportBinding(name, node.parent, self.scope) else:", "c = d. # Only one starred expression is allowed,", "name @property def source_statement(self): return 'from ' + self.fullName +", "os.environ.get('PYFLAKES_BUILTINS') if _customBuiltIns: builtIns.update(_customBuiltIns.split(',')) del _customBuiltIns def __init__(self, tree, filename='(none)',", "if self.descendantOf(lnode, items, ancestor) ^ \\ self.descendantOf(rnode, items, ancestor): return", "public members if isinstance(scope, ClassScope): continue all_binding = scope.get('__all__') if", "by the undefined in __all__ if scope.importStarred: for binding in", "== self.name @property def source_statement(self): \"\"\"Generate a source statement equivalent", "for name in args: self.addBinding(node, Argument(name, node)) if isinstance(node.body, list):", "node.names]) else: self.futuresAllowed = False module = ('.' * node.level)", "to C{_deferredFunctions}, but for callables which are deferred assignment checks.", "handler to be called just after deferred function handlers. \"\"\"", "in args[:idx]: self.report(messages.DuplicateArgument, node, arg) for child in annotations +", "= BITXOR = BITAND = FLOORDIV = INVERT = NOT", "= '_' in self.builtIns if not underscore_in_builtins: self.builtIns.add('_') for example", "item.s elif hasattr(ast, 'Bytes') and isinstance(item, ast.Bytes): return item.s elif", "been fully examined and report names in them which were", "binding = Assignment(name, node) self.addBinding(node, binding) def handleNodeDelete(self, node): def", "decorators, base classes, and the body of its definition. Additionally,", "self.scope._futures_allowed = False @property def scope(self): return self.scopeStack[-1] def popScope(self):", "__init__(self, name, source, scope): if '__all__' in scope and isinstance(source,", "messages.ImportShadowedByLoopVar elif used: continue else: messg = messages.RedefinedWhileUnused self.report(messg, node,", "def CLASSDEF(self, node): \"\"\" Check names used in a class", "in (lnode, rnode) or not (hasattr(lnode, 'parent') and hasattr(rnode, 'parent')):", "'global' in this function. \"\"\" usesLocals = False alwaysUsed =", "1:]: scope[node_name] = node_value NONLOCAL = GLOBAL def GENERATOREXP(self, node):", "\"\"\" class UnhandledKeyType(object): \"\"\" A dictionary key of a type", "# mark '*' imports as used for each scope binding.used", "for 'continue', a finally block (not OK), or # the", "which are deferred assignment checks. \"\"\" nodeDepth = 0 offset", "= ExportBinding(name, node.parent, self.scope) else: binding = Assignment(name, node) self.addBinding(node,", "(not OK), or # the top module scope (not OK)", "self.report(messages.TwoStarredExpressions, node) # The SyntaxError doesn't distinguish two from more", "child in node.body: self.handleNode(child, node) self.exceptHandlers.pop() # Process the other", "- 1: self.report(messages.DefaultExceptNotLast, handler) # Memorize the except handlers and", "type nodes BOOLOP = BINOP = UNARYOP = IFEXP =", "[n.name for n in node.names]) else: self.futuresAllowed = False module", "submodule name is also the same, to avoid false positives.", "False: in_generators = isinstance(scope, GeneratorScope) # look in the built-ins", "not global_scope: # One 'global' statement can bind multiple (comma-delimited)", "is implicitly imported, without an 'as' clause, and the submodule", "and not (isinstance(node, ast.ImportFrom) or self.isDocstring(node)): self.futuresAllowed = False self.nodeDepth", "ast.comprehension) and not isinstance(self.getParent(existing.source), (ast.For, ast.comprehension))): self.report(messages.RedefinedInListComp, node, value.name, existing.source)", "getAlternatives(n): if isinstance(n, (ast.If, ast.TryFinally)): return [n.body] if isinstance(n, ast.TryExcept):", "else: return self.fullName @property def source_statement(self): if self.real_name != self.name:", "have not been used. \"\"\" for name, binding in self.items():", "instances too, though being constants LOAD = STORE = DEL", "i < len(node.handlers) - 1: self.report(messages.DefaultExceptNotLast, handler) # Memorize the", "handler def handleNodeLoad(self, node): name = getNodeName(node) if not name:", "os.path.basename(self.filename) == '__init__.py': # the special name __path__ is valid", "alias.name not in __future__.all_feature_names: self.report(messages.FutureFeatureNotDefined, node, alias.name) elif alias.name ==", "in the current scope, and hasn't # been declared global", "name to non-global scopes, but as already \"used\". node_value.used =", "self.report(messages.DuplicateArgument, node, arg) for child in annotations + defaults: if", "for example in examples: try: tree = compile(example.source, \"<doctest>\", \"exec\",", "= ('.' * node.level) + (node.module or '') for alias", "@ivar _deferredFunctions: Tracking list used by L{deferFunction}. Elements of the", "class ExportBinding(Binding): \"\"\" A binding created by an C{__all__} assignment.", "self.report(messages.ImportStarUsed, node, module) importation = StarImportation(module, node) else: importation =", "= source self.used = False def __str__(self): return self.name def", "== self.name ) def __hash__(self): return hash(self.name) class Importation(Definition): \"\"\"", "class scope can access the names # of the class.", "else: key_first = 'value'.find return tuple(sorted(fields, key=key_first, reverse=True)) def __missing__(self,", "self.scopeStack = scope self.offset = offset handler() def _in_doctest(self): return", "node.docstring # This is just a reasonable guess. In Python", "= self.offset or (0, 0) self.pushScope(DoctestScope) underscore_in_builtins = '_' in", "== '__init__.py': # the special name __path__ is valid only", "(ast.While, ast.For) else: LOOP_TYPES = (ast.While, ast.For, ast.AsyncFor) class _FieldsOrder(dict):", "name and (not source or isinstance(source, ast.Import)) package_name = name.split('.')[0]", "whitespace: ... return if not examples: return # Place doctest", "= ASYNCWITHITEM = RAISE = TRYFINALLY = EXEC = \\", "names which are not attributes of the builtins module, or", "= INDEX = handleChildren # expression contexts are node instances", "and not self.scope.returnValue ): self.scope.returnValue = node.value self.handleNode(node.value, node) def", "only C{__all__} assignment that can be recognized is one which", "possible sources from_list = ', '.join(sorted(from_list)) self.report(messages.ImportStarUsage, node, name, from_list)", "the same value it's not going to cause potentially #", "is never entered. This will cause an # \"undefined name\"", "4 + (e.offset or 0)) self.report(messages.DoctestSyntaxError, node, position) else: self.offset", "Doesn't apply unless it's in the loop itself if n_child", "= scope.get(value.name) if existing and not self.differentForks(node, existing.source): parent_stmt =", "the current scope if isinstance(self.scope, FunctionScope) and name not in", "self._getDoctestExamples(docstring) except (ValueError, IndexError): # e.g. line 6 of the", "doctest, # or in nested functions. if (self.withDoctest and not", "in python3, but names in 2 return item.value else: return", "node.body: self.handleNode(stmt, node) else: # case for Lambdas self.handleNode(node.body, node)", "# add it here anyway has_starred = False star_loc =", "deferAssignment will fail # noisily if called after we've run", "n.orelse] + [[hdl] for hdl in n.handlers] if PY34: LOOP_TYPES", "unused. \"\"\" for scope in self.deadScopes: # imports in classes", "'__traceback_info__', '__traceback_supplement__']) def __init__(self): super(FunctionScope, self).__init__() # Simplify: manage the", "at the time L{deferFunction} was called. @ivar _deferredAssignments: Similar to", "valid only in packages return # protected with a NameError", "if not isinstance(m, messages.UndefinedName) or m.message_args[0] != node_name] # Bind", "if isinstance(node.test, ast.Tuple) and node.test.elts != []: self.report(messages.AssertTuple, node) self.handleChildren(node)", "= undefined = [] if undefined: if not scope.importStarred and", "len(args): for (idx, arg) in enumerate(args): if arg in args[:idx]:", "if (not binding.used and name not in self.globals and not", "self.scope._futures_allowed @futuresAllowed.setter def futuresAllowed(self, value): assert value is False if", "node.depth = self.nodeDepth node.parent = parent try: handler = self.getNodeHandler(node.__class__)", "already in the current scope, and hasn't # been declared", "in tuple/list unpacking to be Assignments, rather it treats them", "nodes: \"except:\", \"else:\", \"finally:\" self.handleChildren(node, omit='body') TRYEXCEPT = TRY def", "use the name afterwards. # # Unless it's been removed", "return if importStarred: from_list = [] for scope in self.scopeStack[-1::-1]:", "5) # Python 2.5 to 3.4 try: sys.pypy_version_info PYPY =", "= docstring and self._getDoctestExamples(docstring) except (ValueError, IndexError): # e.g. line", "parent_stmt = self.getParent(value.source) if isinstance(existing, Importation) and isinstance(parent_stmt, ast.For): self.report(messages.ImportShadowedByLoopVar,", "(ClassScope, ModuleScope)): self.report(messages.YieldOutsideFunction, node) return self.scope.isGenerator = True self.handleNode(node.value, node)", "if not scope.importStarred and \\ os.path.basename(self.filename) != '__init__.py': # Look", "return if name == '__path__' and os.path.basename(self.filename) == '__init__.py': #", "docstring for <string> has inconsistent # leading whitespace: ... return", "if isinstance(binding, StarImportation): binding.used = all_binding # Look for imported", "\"\"\"Fix order of AST node fields.\"\"\" def _get_fields(self, node_class): #", "ast.While, ast.IfExp)): return True current = getattr(current, 'parent', None) return", "PY33 else wildcard.arg) if is_py3_func: if PY33: # Python 2.5", "isinstance(other, Definition) and self.name == other.name class Definition(Binding): \"\"\" A", "the *targets* if the assignment has a value. # Otherwise", "in fields: key_first = 'generators'.find else: key_first = 'value'.find return", "self.scopeStack[-1::-1]: # only generators used in a class scope can", "messg = messages.UnusedImport self.report(messg, value.source, str(value)) for node in value.redefined:", "ModuleScope): self.scope._futures_allowed = False @property def scope(self): return self.scopeStack[-1] def", "function handler to be called just before completion. This is", "getNodeHandler(self, node_class): try: return self._nodeHandlers[node_class] except KeyError: nodeType = getNodeType(node_class)", "if node is part of a conditional body. \"\"\" current", "We cannot predict if this conditional branch is going to", "\"\"\" Check to see if any assignments have not been", "importation = Importation(name, node, alias.name) self.addBinding(node, importation) def IMPORTFROM(self, node):", "imported but unused. \"\"\" for scope in self.deadScopes: # imports", "locals as globals self.globals = self.alwaysUsed.copy() self.returnValue = None #", "lnode is rnode: return lnode if (lnode.depth > rnode.depth): return", "n, n_child = n.parent, n if isinstance(n, LOOP_TYPES): # Doesn't", "list): for item in field: yield item def convert_to_value(item): if", "is False and isinstance(scope, ClassScope): continue try: scope[name].used = (self.scope,", "__eq__(self, compare): return ( compare.__class__ == self.__class__ and compare.name ==", "%r\" % (node.ctx,)) def CONTINUE(self, node): # Walk the tree", "value.name, existing.source) elif scope is self.scope: if (isinstance(parent_stmt, ast.comprehension) and", "self.futuresAllowed = False self.nodeDepth += 1 node.depth = self.nodeDepth node.parent", "if not isinstance(scope, (FunctionScope, ModuleScope)): continue # if the name", "handler.type is None and i < len(node.handlers) - 1: self.report(messages.DefaultExceptNotLast,", "node.value: # Only bind the *targets* if the assignment has", "return isinstance(node, ast.Str) or (isinstance(node, ast.Expr) and isinstance(node.value, ast.Str)) def", "= True elif isinstance(node.ctx, (ast.Store, ast.AugStore)): self.handleNodeStore(node) elif isinstance(node.ctx, ast.Del):", "defined name. See test_unused_global. self.messages = [ m for m", "fields that are lists of nodes. \"\"\" for name in", "return tuple(convert_to_value(i) for i in item.elts) elif isinstance(item, ast.Num): return", "name scope for a function. @ivar globals: Names declared 'global'", "def __init__(self, tree, filename='(none)', builtins=None, withDoctest='PYFLAKES_DOCTEST' in os.environ): self._nodeHandlers =", "node def getCommonAncestor(self, lnode, rnode, stop): if stop in (lnode,", "# 3.x: the name of the exception, which is not", "else: return 'import %s' % self.fullName def __str__(self): \"\"\"Return import", "def __str__(self): return self.fullName @property def source_statement(self): return 'import '", "export and additional checking applied to them. The only C{__all__}", "stop): for a in ancestors: if self.getCommonAncestor(node, a, stop): return", "if len(set(args)) < len(args): for (idx, arg) in enumerate(args): if", "tree, filename='(none)', builtins=None, withDoctest='PYFLAKES_DOCTEST' in os.environ): self._nodeHandlers = {} self._deferredFunctions", "= node.docstring # This is just a reasonable guess. In", "in the export list for name in undefined: self.report(messages.UndefinedExport, scope['__all__'].source,", "or self.isDocstring(node)): self.futuresAllowed = False self.nodeDepth += 1 node.depth =", "nodes. \"\"\" for name in _fields_order[node.__class__]: if name == omit:", "node): # Lookup the first parent which is not Tuple,", "as an argument. \"\"\" class Assignment(Binding): \"\"\" Represents binding a", "mistake self.report(messages.UndefinedLocal, scope[name].used[1], name, scope[name].source) break parent_stmt = self.getParent(node) if", "docstring = node.docstring # This is just a reasonable guess.", "VariableKey): self.report(messages.MultiValueRepeatedKeyVariable, key_node, key.name) else: self.report( messages.MultiValueRepeatedKeyLiteral, key_node, key, )", "child in annotations + defaults: if child: self.handleNode(child, node) def", "= ELLIPSIS = ignore # \"slice\" type nodes SLICE =", "\"\"\"Return whether importation needs an as clause.\"\"\" return not self.fullName.split('.')[-1]", "s.decorators) from pyflakes import messages if PY2: def getNodeType(node_class): #", "tuple/list unpacking to be Assignments, rather it treats them as", "in_generators = None importStarred = None # try enclosing function", "class. this is skipped during the first iteration if in_generators", "node, value.name, existing.source) elif scope is self.scope: if (isinstance(parent_stmt, ast.comprehension)", "isinstance(scope, ClassScope): continue try: scope[name].used = (self.scope, node) except KeyError:", "/ function / globals scopes. if isinstance(node.ctx, (ast.Load, ast.AugLoad)): self.handleNodeLoad(node)", "not name: return in_generators = None importStarred = None #", "can be determined statically, they will be treated as names", "= i if star_loc >= 1 << 8 or len(node.elts)", "ast.NameConstant): # None, True, False are nameconstants in python3, but", "from_list) return if name == '__path__' and os.path.basename(self.filename) == '__init__.py':", "isinstance(existing, Importation) and value.redefines(existing): existing.redefined.append(node) if value.name in self.scope: #", "or within a loop value.used = self.scope[value.name].used self.scope[value.name] = value", "FunctionDefs is_py3_func = hasattr(node, 'returns') for arg_name in ('vararg', 'kwarg'):", "the root module to be accessed. RedefinedWhileUnused is suppressed in", "can bind multiple (comma-delimited) names. for node_name in node.names: node_value", "are nameconstants in python3, but names in 2 return item.value", "name, source, module, real_name=None): self.module = module self.real_name = real_name", "scope above us for scope in self.scopeStack[:-1]: if not isinstance(scope,", "self.report(messages.TooManyExpressionsInStarredAssignment, node) self.handleChildren(node) LIST = TUPLE def IMPORT(self, node): for", "packages return # protected with a NameError handler? if 'NameError'", "OR = ADD = SUB = MULT = DIV =", "= BINOP = UNARYOP = IFEXP = SET = \\", "and global scope for scope in self.scopeStack[-1::-1]: # only generators", "= node.lineno - 1 else: # Computed incorrectly if the", "PRINT = FOR = ASYNCFOR = WHILE = IF =", "case for Lambdas self.handleNode(node.body, node) def checkUnusedAssignments(): \"\"\" Check to", "key for key, count in key_counts.items() if count > 1", "if not PY2 and not isinstance(self.scope, ModuleScope): self.report(messages.ImportStarNotPermitted, node, module)", "parts: if self.descendantOf(lnode, items, ancestor) ^ \\ self.descendantOf(rnode, items, ancestor):", "= True class DoctestScope(ModuleScope): \"\"\"Scope for a doctest.\"\"\" # Globally", "in self.scopeStack[-1::-1]: for binding in scope.values(): if isinstance(binding, StarImportation): #", "# Only bind the *targets* if the assignment has a", "a ., avoid the ambiguous '..*' if self.fullName.endswith('.'): return self.source_statement", "[ convert_to_value(key) for key in node.keys ] key_counts = counter(keys)", "= handleChildren if PY2 else GENERATOREXP DICTCOMP = SETCOMP =", "2.6 does not have Counter in collections. \"\"\" results =", "Assignment that isn't used. Also, the checker does not consider", "def __init__(self, name, source, scope): if '__all__' in scope and", "an ExceptHandler node return node.name class Checker(object): \"\"\" I check", "for this name. # TODO: if the global is not", "elif isinstance(node.ctx, ast.Del): self.handleNodeDelete(node) else: # must be a Param", "stricter rules. @ivar used: pair of (L{Scope}, node) indicating the", "LOAD = STORE = DEL = AUGLOAD = AUGSTORE =", "is self.scope and name not in self.scope.globals: # then it's", "source, full_name=None): self.fullName = full_name or name self.redefined = []", "self.nodeDepth += 1 node.depth = self.nodeDepth node.parent = parent try:", "'True': True, 'False': False, 'None': None, } return constants_lookup.get( result.name,", "'parent')): return None if lnode is rnode: return lnode if", "with arguments but the function is a generator. \"\"\" if", "__init__(self, name, source): self.name = name self.source = source self.used", "isinstance(node.ctx, (ast.Store, ast.AugStore)): self.handleNodeStore(node) elif isinstance(node.ctx, ast.Del): self.handleNodeDelete(node) else: #", "(global_scope, node) for scope in self.scopeStack[global_scope_index + 1:]: scope[node_name] =", "an C{__all__} assignment. If the names in the list can", "wildcard = getattr(node.args, arg_name) if not wildcard: continue args.append(wildcard if", "other): return isinstance(other, Definition) and self.name == other.name class Definition(Binding):", "results.get(item, 0) + 1 return results def iter_child_nodes(node, omit=None, _fields_order=_FieldsOrder()):", "', '.join(sorted(from_list)) self.report(messages.ImportStarUsage, node, name, from_list) return if name ==", "used. for value in scope.values(): if isinstance(value, Importation): used =", "(isinstance(node, ast.ImportFrom) or self.isDocstring(node)): self.futuresAllowed = False self.nodeDepth += 1", "value.redefines(existing): self.report(messages.RedefinedWhileUnused, node, value.name, existing.source) elif isinstance(existing, Importation) and value.redefines(existing):", "The second element is a copy of the scope stack", "node): for alias in node.names: if '.' in alias.name and", "@property def source_statement(self): return 'import ' + self.fullName class ImportationFrom(Importation):", "if self.fullName.endswith('.'): return self.source_statement else: return self.name class FutureImportation(ImportationFrom): \"\"\"", "# Lookup the first parent which is not Tuple, List", "in `redefines` unless the submodule name is also the same,", "binding is altered. - `node` is the statement responsible for", "else: messg = messages.RedefinedWhileUnused self.report(messg, node, value.name, value.source) def pushScope(self,", "ast.Continue): self.report(messages.ContinueOutsideLoop, node) else: # ast.Break self.report(messages.BreakOutsideLoop, node) BREAK =", "= IS = ISNOT = IN = NOTIN = \\", "'iter'.find elif 'generators' in fields: key_first = 'generators'.find else: key_first", "{} self._deferredFunctions = [] self._deferredAssignments = [] self.deadScopes = []", "checking applied to them. The only C{__all__} assignment that can", "manage the special locals as globals self.globals = self.alwaysUsed.copy() self.returnValue", "iter_child_nodes(node, omit=None, _fields_order=_FieldsOrder()): \"\"\" Yield all direct child nodes of", "\"\"\" I check the cleanliness and sanity of Python code.", "undefined: if not scope.importStarred and \\ os.path.basename(self.filename) != '__init__.py': #", "fields that are nodes and all items of fields that", "UndefinedName messages already reported for this name. # TODO: if", "\"used\". node_value.used = (global_scope, node) for scope in self.scopeStack[global_scope_index +", "LISTCOMP = handleChildren if PY2 else GENERATOREXP DICTCOMP = SETCOMP", "while True: node = node.parent if not hasattr(node, 'elts') and", "it will contain any new bindings added to it. \"\"\"", "handleChildren(self, tree, omit=None): for node in iter_child_nodes(tree, omit=omit): self.handleNode(node, tree)", "node): if isinstance(node, ast.Expr): node = node.value if not isinstance(node,", "node.lineno += self.offset[0] node.col_offset += self.offset[1] if self.traceTree: print(' '", "self.items(): if (not binding.used and name not in self.globals and", "def differentForks(self, lnode, rnode): \"\"\"True, if lnode and rnode are", "= LSHIFT = RSHIFT = \\ BITOR = BITXOR =", "(node.s, doctest_lineno) def handleNode(self, node, parent): if node is None:", "source): super(StarImportation, self).__init__('*', source) # Each star importation needs a", "in the scope, allowing any attribute of the root module", "node): handler_names = [] # List the exception handlers for", "for scope in self.scopeStack[::-1]: if value.name in scope: break existing", "importation) def IMPORTFROM(self, node): if node.module == '__future__': if not", "args: self.addBinding(node, Argument(name, node)) if isinstance(node.body, list): # case for", "string, creates a local that is only bound within the", "FunctionDefinition(node.name, node)) # doctest does not process doctest within a", "is allowed, and no more than 1<<8 # assignments are", "this name. # TODO: if the global is not used", "tree) def isLiteralTupleUnpacking(self, node): if isinstance(node, ast.Assign): for child in", "*targets* if the assignment has a value. # Otherwise it's", "!= self.name: return 'from %s import %s as %s' %", "'.join(sorted(from_list)) self.report(messages.ImportStarUsage, node, name, from_list) return if name == '__path__'", "'__init__.py': # the special name __path__ is valid only in", "# Python 2.5 to 3.3 argannotation = arg_name + 'annotation'", "to the import statement, possibly including multiple dotted components. @type", "self._has_alias(): return 'import %s as %s' % (self.fullName, self.name) else:", "value.source) def pushScope(self, scopeClass=FunctionScope): self.scopeStack.append(scopeClass()) def report(self, messageClass, *args, **kwargs):", "child nodes of *node*, that is, all fields that are", "except KeyError: pass else: return importStarred = importStarred or scope.importStarred", "= UNARYOP = IFEXP = SET = \\ COMPARE =", "SyntaxError doesn't distinguish two from more # than two. break", "'*': # Only Python 2, local import * is a", "used. Also, the checker does not consider assignments in tuple/list", "if _customBuiltIns: builtIns.update(_customBuiltIns.split(',')) del _customBuiltIns def __init__(self, tree, filename='(none)', builtins=None,", "at the time this is called will be restored, however", "AST node fields.\"\"\" def _get_fields(self, node_class): # handle iter before", "self.usesLocals and isinstance(binding, Assignment)): yield name, binding class GeneratorScope(Scope): pass", "not complain. keys = [ convert_to_value(key) for key in node.keys", "@ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for callables which are", "getCommonAncestor(self, lnode, rnode, stop): if stop in (lnode, rnode) or", "= None self.runDeferred(self._deferredAssignments) # Set _deferredAssignments to None so that", "mark '*' imports as used for each scope binding.used =", "return 'import ' + self.fullName class ImportationFrom(Importation): def __init__(self, name,", "self.handleChildren(node) return # 3.x: the name of the exception, which", "\"finally:\" self.handleChildren(node, omit='body') TRYEXCEPT = TRY def EXCEPTHANDLER(self, node): if", "# See discussion on https://github.com/PyCQA/pyflakes/pull/59 # We're removing the local", "== '*': # Only Python 2, local import * is", "n.handlers] if PY34: LOOP_TYPES = (ast.While, ast.For) else: LOOP_TYPES =", "[] self.messages = [] self.filename = filename if builtins: self.builtIns", "e.g. line 6 of the docstring for <string> has inconsistent", "cannot predict if this conditional branch is going to #", "ast.Tuple)): for node in source.value.elts: if isinstance(node, ast.Str): self.names.append(node.s) super(ExportBinding,", "Globally defined names which are not attributes of the builtins", "\"\"\" def __init__(self, name, source, scope): if '__all__' in scope", "runDeferred(self, deferred): \"\"\" Run the callables in C{deferred} using their", "class. Also, it models the Bindings and Scopes. \"\"\" import", "source_statement(self): \"\"\"Generate a source statement equivalent to the import.\"\"\" if", "= EXEC = \\ EXPR = ASSIGN = handleChildren PASS", "been used. \"\"\" for name, binding in self.items(): if (not", "name in _fields_order[node.__class__]: if name == omit: continue field =", "code later in the file might modify the global scope.", "def __hash__(self): return hash(self.name) class Importation(Definition): \"\"\" A binding created", "global scope for scope in self.scopeStack[-1::-1]: # only generators used", "types COMPREHENSION = KEYWORD = FORMATTEDVALUE = JOINEDSTR = handleChildren", "to 3.4 try: sys.pypy_version_info PYPY = True except AttributeError: PYPY", "self.offset and getattr(node, 'lineno', None) is not None: node.lineno +=", "and no more than 1<<8 # assignments are allowed before", "the checker does not consider assignments in tuple/list unpacking to", "fields def counter(items): \"\"\" Simplest required implementation of collections.Counter. Required", "if PYPY: e.offset += 1 position = (node_lineno + example.lineno", "for them. \"\"\" def __init__(self, name, source, scope): if '__all__'", "# Locate the name in locals / function / globals", "SubmoduleImportation(alias.name, node) else: name = alias.asname or alias.name importation =", "ast.Name): result = VariableKey(item=item) constants_lookup = { 'True': True, 'False':", "a class. \"\"\" class UnhandledKeyType(object): \"\"\" A dictionary key of", "ast.AugAssign): self.names = list(scope['__all__'].names) else: self.names = [] if isinstance(source.value,", "A binding created by an C{__all__} assignment. If the names", "for a doctest.\"\"\" # Globally defined names which are not", "creates a local that is only bound within the scope", "= value def getNodeHandler(self, node_class): try: return self._nodeHandlers[node_class] except KeyError:", "\"\"\" Return `True` if node is part of a conditional", "\"\"\" results = {} for item in items: results[item] =", "one which takes the value of a literal list containing", "BREAK = CONTINUE def RETURN(self, node): if isinstance(self.scope, (ClassScope, ModuleScope)):", "the beginning # of the function and the docstring. node_lineno", "= ATTRIBUTE = SUBSCRIPT = \\ STARRED = NAMECONSTANT =", "ast.Del): self.handleNodeDelete(node) else: # must be a Param context --", "(len(self.scopeStack) >= 2 and isinstance(self.scopeStack[1], DoctestScope)) @property def futuresAllowed(self): if", "scopes, but as already \"used\". node_value.used = (global_scope, node) for", "Additionally, add its name to the current scope. \"\"\" for", "GENERATOREXP def NAME(self, node): \"\"\" Handle occurrence of Name (which", "self.scope[value.name].used self.scope[value.name] = value def getNodeHandler(self, node_class): try: return self._nodeHandlers[node_class]", "really ast.Store and shouldn't silence # UndefinedLocal warnings. self.handleNode(node.target, node)", "is a submodule import assert '.' in name and (not", "declared 'global' in this function. \"\"\" usesLocals = False alwaysUsed", "be the module name otherwise it will be deemed imported", "ModuleScope)): continue # if the name was defined in that", "and isinstance(self.scope, FunctionScope) and isinstance(node.parent, ast.Call)): # we are doing", "which have been fully examined and report names in them", "all_binding and not isinstance(all_binding, ExportBinding): all_binding = None if all_binding:", "PY2 or node.name is None: self.handleChildren(node) return # 3.x: the", "value.used or value.name in all_names if not used: messg =", "existing.source) elif scope is self.scope: if (isinstance(parent_stmt, ast.comprehension) and not", "tree up until we see a loop (OK), a function", "\"\"\" Main module. Implement the central Checker class. Also, it", "self.handleNode(node.annotation, node) if node.value: # If the assignment has value,", "\"\"\" if self.scope.isGenerator and self.scope.returnValue: self.report(messages.ReturnWithArgsInsideGenerator, self.scope.returnValue) self.deferAssignment(checkReturnWithArgumentInsideGenerator) self.popScope() self.deferFunction(runFunction)", "ast.AsyncFor) class _FieldsOrder(dict): \"\"\"Fix order of AST node fields.\"\"\" def", "of the builtins module, or # are only present on", "unless the submodule name is also the same, to avoid", "BINOP = UNARYOP = IFEXP = SET = \\ COMPARE", "isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) for stmt in node.body: self.handleNode(stmt, node)", "super(ExportBinding, self).__init__(name, source) class Scope(dict): importStarred = False # set", "C{_deferredFunctions}, but for callables which are deferred assignment checks. \"\"\"", "for each scope binding.used = (self.scope, node) from_list.append(binding.fullName) # report", "handler_names.append(getNodeName(handler.type)) if handler.type is None and i < len(node.handlers) -", "from_list = [] for scope in self.scopeStack[-1::-1]: for binding in", "'end ' + node.__class__.__name__) _getDoctestExamples = doctest.DocTestParser().get_examples def handleDoctests(self, node):", "deferFunction(self, callable): \"\"\" Schedule a function handler to be called", "name\" error raised if the checked code tries to #", "# First non-empty return self.isGenerator = False # Detect a", "getattr(node, name, None) if isinstance(field, ast.AST): yield field elif isinstance(field,", "submodule is also imported. Python does not restrict which attributes", "Simplest required implementation of collections.Counter. Required as 2.6 does not", "compare.name == self.name ) def __hash__(self): return hash(self.name) class Importation(Definition):", "\"slice\" type nodes SLICE = EXTSLICE = INDEX = handleChildren", "rnode.depth): return self.getCommonAncestor(lnode, rnode.parent, stop) return self.getCommonAncestor(lnode.parent, rnode.parent, stop) def", "the global is not used in this scope, it does", "ModuleScope) for scope in self.scopeStack): return False return self.scope._futures_allowed @futuresAllowed.setter", "GeneratorScope(Scope): pass class ModuleScope(Scope): \"\"\"Scope for a module.\"\"\" _futures_allowed =", "or # are only present on some platforms. _MAGIC_GLOBALS =", "= handleChildren PASS = ignore # \"expr\" type nodes BOOLOP", "withDoctest self.scopeStack = [ModuleScope()] self.exceptHandlers = [()] self.root = tree", "counter(keys) duplicate_keys = [ key for key, count in key_counts.items()", "expression is allowed, and no more than 1<<8 # assignments", "bind the *targets* if the assignment has a value. #", "instance \"\"\" # assert value.source in (node, node.parent): for scope", "self.report(messages.MultiValueRepeatedKeyVariable, key_node, key.name) else: self.report( messages.MultiValueRepeatedKeyLiteral, key_node, key, ) self.handleChildren(node)", "self.popScope() self.checkDeadScopes() def deferFunction(self, callable): \"\"\" Schedule a function handler", "allowed before a stared expression. There is # also a", "+ ' as ' + self.name else: return self.fullName class", "= 'iter'.find elif 'generators' in fields: key_first = 'generators'.find else:", "existing.source): parent_stmt = self.getParent(value.source) if isinstance(existing, Importation) and isinstance(parent_stmt, ast.For):", "Lookup the first parent which is not Tuple, List or", "scope[name].used = (self.scope, node) except KeyError: pass else: return importStarred", "unpacking: a, *b, c = d. # Only one starred", "else: self.offset = (node_offset[0] + node_lineno + example.lineno, node_offset[1] +", "not is_name_previously_defined: # See discussion on https://github.com/PyCQA/pyflakes/pull/59 # We're removing", "+ self.name else: return self.fullName @property def source_statement(self): if self.real_name", "def ignore(self, node): pass # \"stmt\" type nodes DELETE =", "KeyError: pass def ANNASSIGN(self, node): if node.value: # Only bind", "located on different forks of IF/TRY\"\"\" ancestor = self.getCommonAncestor(lnode, rnode,", "current scope if isinstance(self.scope, FunctionScope) and name not in self.scope:", "does not restrict which attributes of the root module may", "nodes of *node*, that is, all fields that are nodes", "(ast.For, ast.comprehension)) or ( parent_stmt != node.parent and not self.isLiteralTupleUnpacking(parent_stmt)):", "= sys.exc_info()[1] if PYPY: e.offset += 1 position = (node_lineno", "= [ key for key, count in key_counts.items() if count", "self.pushScope(GeneratorScope) self.handleChildren(node) self.popScope() LISTCOMP = handleChildren if PY2 else GENERATOREXP", "hasattr(self.scope, 'returnValue') and not self.scope.returnValue ): self.scope.returnValue = node.value self.handleNode(node.value,", "field = getattr(node, name, None) if isinstance(field, ast.AST): yield field", "True, False are nameconstants in python3, but names in 2", "nodeDepth = 0 offset = None traceTree = False builtIns", "part of a conditional body. \"\"\" current = getattr(node, 'parent',", "isinstance(node.body, list): # case for FunctionDefs for stmt in node.body:", "= (scope, source) class Argument(Binding): \"\"\" Represents binding a name", "self.scopeStack): return False return self.scope._futures_allowed @futuresAllowed.setter def futuresAllowed(self, value): assert", "existing = scope.get(value.name) if existing and not self.differentForks(node, existing.source): parent_stmt", "enumerate(keys) if i_key == key] values = counter( convert_to_value(node.values[index]) for", "arg in args[:idx]: self.report(messages.DuplicateArgument, node, arg) for child in annotations", "self.report(messages.FutureFeatureNotDefined, node, alias.name) elif alias.name == '*': # Only Python", "other nodes: \"except:\", \"else:\", \"finally:\" self.handleChildren(node, omit='body') TRYEXCEPT = TRY", "(isinstance(parent_stmt, ast.comprehension) and not isinstance(self.getParent(existing.source), (ast.For, ast.comprehension))): self.report(messages.RedefinedInListComp, node, value.name,", "_deferredFunctions: Tracking list used by L{deferFunction}. Elements of the list", "# Simplify: manage the special locals as globals self.globals =", "treats them as simple Bindings. \"\"\" class FunctionDefinition(Definition): pass class", "registering the root module name in the scope, allowing any", "module.endswith('.'): full_name = module + self.real_name else: full_name = module", "however it will contain any new bindings added to it.", "in (node, node.parent): for scope in self.scopeStack[::-1]: if value.name in", "(self.withDoctest and not self._in_doctest() and not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node))", "node)) if isinstance(node.body, list): # case for FunctionDefs for stmt", "= True except AttributeError: PYPY = False builtin_vars = dir(__import__('__builtin__'", "+ self.fullName class ImportationFrom(Importation): def __init__(self, name, source, module, real_name=None):", "self.checkDeadScopes() def deferFunction(self, callable): \"\"\" Schedule a function handler to", "that is checked with stricter rules. @ivar used: pair of", "of the class. this is skipped during the first iteration", "skipped during the first iteration if in_generators is False and", "# This is just a reasonable guess. In Python 3.7,", "in iter_child_nodes(tree, omit=omit): self.handleNode(node, tree) def isLiteralTupleUnpacking(self, node): if isinstance(node,", "the rebound name is used as a global or within", "isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) ASYNCFUNCTIONDEF = FUNCTIONDEF def LAMBDA(self, node):", "Lambdas self.handleNode(node.body, node) def checkUnusedAssignments(): \"\"\" Check to see if", "AWAIT = YIELDFROM = YIELD def FUNCTIONDEF(self, node): for deco", "CLASSDEF(self, node): \"\"\" Check names used in a class definition,", "the local name since it's being unbound # after leaving", "# assert value.source in (node, node.parent): for scope in self.scopeStack[::-1]:", "descendantOf(self, node, ancestors, stop): for a in ancestors: if self.getCommonAncestor(node,", "(3, 0) PY32 = sys.version_info < (3, 3) # Python", "be a load/store/delete access.) \"\"\" # Locate the name in", "node) self.handleChildren(node) def GLOBAL(self, node): \"\"\" Keep track of globals", "not # become a globally defined name. See test_unused_global. self.messages", "= FUNCTIONDEF def LAMBDA(self, node): args = [] annotations =", "self.globals and not self.usesLocals and isinstance(binding, Assignment)): yield name, binding", "FunctionDefs for stmt in node.body: self.handleNode(stmt, node) else: # case", "One 'global' statement can bind multiple (comma-delimited) names. for node_name", "+ 4 + (e.offset or 0)) self.report(messages.DoctestSyntaxError, node, position) else:", "in enumerate(keys) if i_key == key] values = counter( convert_to_value(node.values[index])", "rnode.depth): return self.getCommonAncestor(lnode.parent, rnode, stop) if (lnode.depth < rnode.depth): return", "False @property def scope(self): return self.scopeStack[-1] def popScope(self): self.deadScopes.append(self.scopeStack.pop()) def", "cause an # \"undefined name\" error raised if the checked", "a docstring, as long as it is at the correct", "line 6 of the docstring for <string> has inconsistent #", "the current scope, and hasn't # been declared global used", "but names in 2 return item.value else: return UnhandledKeyType() class", "all_binding = scope.get('__all__') if all_binding and not isinstance(all_binding, ExportBinding): all_binding", "else: def getAlternatives(n): if isinstance(n, ast.If): return [n.body] if isinstance(n,", "= ASSIGN = handleChildren PASS = ignore # \"expr\" type", "self.report(messages.ContinueOutsideLoop, node) else: # ast.Break self.report(messages.BreakOutsideLoop, node) BREAK = CONTINUE", "full_name = module + '.' + self.real_name super(ImportationFrom, self).__init__(name, source,", "but we # add it here anyway has_starred = False", "# imports in classes are public members if isinstance(scope, ClassScope):", "True return False def addBinding(self, node, value): \"\"\" Called when", "> 1 ] for key in duplicate_keys: key_indices = [i", "Binding instance \"\"\" # assert value.source in (node, node.parent): for", "a conditional body. \"\"\" current = getattr(node, 'parent', None) while", "are imported and not otherwise used but appear in the", "unbound # after leaving the except: block and it's always", "DoctestScope(ModuleScope): \"\"\"Scope for a doctest.\"\"\" # Globally defined names which", "a list of possible sources from_list = ', '.join(sorted(from_list)) self.report(messages.ImportStarUsage,", "and # may not be the module name otherwise it", "is locale-dependent return str(unicode(node_class.__name__).upper()) else: def getNodeType(node_class): return node_class.__name__.upper() #", "isinstance(node, ast.Continue): if n_child in n.finalbody: self.report(messages.ContinueInFinally, node) return if", "with an explicit assignment. The checker will raise warnings for", "else wildcard.arg) if is_py3_func: if PY33: # Python 2.5 to", "in locals / function / globals scopes. if isinstance(node.ctx, (ast.Load,", "name.split('.')[0] super(SubmoduleImportation, self).__init__(package_name, source) self.fullName = name def redefines(self, other):", "'__all__' in scope and isinstance(source, ast.AugAssign): self.names = list(scope['__all__'].names) else:", "handleNode(self, node, parent): if node is None: return if self.offset", "class Assignment(Binding): \"\"\" Represents binding a name with an explicit", "imported. Python does not restrict which attributes of the root", "= [self.scopeStack[0]] node_offset = self.offset or (0, 0) self.pushScope(DoctestScope) underscore_in_builtins", "fields.\"\"\" def _get_fields(self, node_class): # handle iter before target, and", "node): \"\"\" Keep track of globals declarations. \"\"\" global_scope_index =", "in alias.name and not alias.asname: importation = SubmoduleImportation(alias.name, node) else:", "as already \"used\". node_value.used = (global_scope, node) for scope in", "if node.value: # If the assignment has value, handle the", "def deferFunction(self, callable): \"\"\" Schedule a function handler to be", "= (self.scope, node) except KeyError: pass else: return importStarred =", "First non-empty return self.isGenerator = False # Detect a generator", "Look at scopes which have been fully examined and report", "hasattr(child, 'elts'): return False return True def isDocstring(self, node): \"\"\"", "\\ EXPR = ASSIGN = handleChildren PASS = ignore #", "\"undefined name\" error raised if the checked code tries to", "TODO: if the global is not used in this scope,", "def getNodeType(node_class): return node_class.__name__.upper() # Python >= 3.3 uses ast.Try", "node) else: importation = ImportationFrom(name, node, module, alias.name) self.addBinding(node, importation)", "= counter( convert_to_value(node.values[index]) for index in key_indices ) if any(count", "as a global or within a loop value.used = self.scope[value.name].used", "all_names.difference(scope) else: all_names = undefined = [] if undefined: if", "the Bindings and Scopes. \"\"\" import __future__ import doctest import", "within classes are processed. if (self.withDoctest and not self._in_doctest() and", "ast.Bytes): return item.s elif isinstance(item, ast.Tuple): return tuple(convert_to_value(i) for i", "name = getNodeName(node) if not name: return if on_conditional_branch(): #", "doctest_lineno) def handleNode(self, node, parent): if node is None: return", "self.getParent(node) if isinstance(parent_stmt, (ast.For, ast.comprehension)) or ( parent_stmt != node.parent", "unexpected behaviour so we'll not complain. keys = [ convert_to_value(key)", "+ node.__class__.__name__) if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or self.isDocstring(node)):", "element is the callable passed to L{deferFunction}. The second element", "EXPR = ASSIGN = handleChildren PASS = ignore # \"expr\"", "# None, True, False are nameconstants in python3, but names", "can be a load/store/delete access.) \"\"\" # Locate the name", "that scope, and the name has # been accessed already", "if isinstance(self.scope, FunctionScope) and name in self.scope.globals: self.scope.globals.remove(name) else: try:", "def __init__(self, name, source, full_name=None): self.fullName = full_name or name", "1<<24 expressions after the starred expression, # which is impossible", "place in the node tree. \"\"\" return isinstance(node, ast.Str) or", "None # First non-empty return self.isGenerator = False # Detect", "to avoid false positives. \"\"\" def __init__(self, name, source): #", ">= 2 and isinstance(self.scopeStack[1], DoctestScope)) @property def futuresAllowed(self): if not", "existing.source) elif isinstance(existing, Importation) and value.redefines(existing): existing.redefined.append(node) if value.name in", "ast.AugStore)): self.handleNodeStore(node) elif isinstance(node.ctx, ast.Del): self.handleNodeDelete(node) else: # must be", "and not otherwise used but appear in the value of", "then it's probably a mistake self.report(messages.UndefinedLocal, scope[name].used[1], name, scope[name].source) break", "incorrectly if the docstring has backslash doctest_lineno = node.lineno -", "leaving the except: block and it's always unbound # if", "of possible sources from_list = ', '.join(sorted(from_list)) self.report(messages.ImportStarUsage, node, name,", "__path__ is valid only in packages return # protected with", "\"\"\" Handle occurrence of Name (which can be a load/store/delete", "using their associated scope stack. \"\"\" for handler, scope, offset", "Implement the central Checker class. Also, it models the Bindings", "ast if 'decorator_list' not in ast.ClassDef._fields: # Patch the missing", "an explicit assignment. The checker will raise warnings for any", "called after we've run through the deferred assignments. self._deferredAssignments =", "handler to be called just before completion. This is used", "\"\"\" Return a generator for the assignments which have not", "= TRY def EXCEPTHANDLER(self, node): if PY2 or node.name is", "the assignment has value, handle the *value* now. self.handleNode(node.value, node)", "\"\"\" self._deferredAssignments.append((callable, self.scopeStack[:], self.offset)) def runDeferred(self, deferred): \"\"\" Run the", "import statement, possibly including multiple dotted components. @type fullName: C{str}", "if not name: return # if the name hasn't already", "value it's not going to cause potentially # unexpected behaviour", "other.fullName return super(SubmoduleImportation, self).redefines(other) def __str__(self): return self.fullName @property def", "key_node = node.keys[key_index] if isinstance(key, VariableKey): self.report(messages.MultiValueRepeatedKeyVariable, key_node, key.name) else:", "i, n in enumerate(node.elts): if isinstance(n, ast.Starred): if has_starred: self.report(messages.TwoStarredExpressions,", "them. The only C{__all__} assignment that can be recognized is", "nodeType = getNodeType(node_class) self._nodeHandlers[node_class] = handler = getattr(self, nodeType) return", "def handleNodeStore(self, node): name = getNodeName(node) if not name: return", "- 1 return (node.s, doctest_lineno) def handleNode(self, node, parent): if", "ast.Try instead of (ast.TryExcept + ast.TryFinally) if PY32: def getAlternatives(n):", "statically, they will be treated as names for export and", "= os.environ.get('PYFLAKES_BUILTINS') if _customBuiltIns: builtIns.update(_customBuiltIns.split(',')) del _customBuiltIns def __init__(self, tree,", "if not name: return if on_conditional_branch(): # We cannot predict", "key] values = counter( convert_to_value(node.values[index]) for index in key_indices )", "+ '.*' self.fullName = name @property def source_statement(self): return 'from", "_deferredAssignments to None so that deferAssignment will fail # noisily", "rather it treats them as simple Bindings. \"\"\" class FunctionDefinition(Definition):", "handlers. \"\"\" self._deferredAssignments.append((callable, self.scopeStack[:], self.offset)) def runDeferred(self, deferred): \"\"\" Run", "scope[name].used[1], name, scope[name].source) break parent_stmt = self.getParent(node) if isinstance(parent_stmt, (ast.For,", "(ast.TryExcept + ast.TryFinally) if PY32: def getAlternatives(n): if isinstance(n, (ast.If,", "not attributes of the builtins module, or # are only", "0 offset = None traceTree = False builtIns = set(builtin_vars).union(_MAGIC_GLOBALS)", "happens for names in function # arguments, but these aren't", "return statement with arguments but the function is a generator.", "= counter(keys) duplicate_keys = [ key for key, count in", "self.scope is not global_scope: # One 'global' statement can bind", "# Doesn't apply unless it's in the loop itself if", "potentially # unexpected behaviour so we'll not complain. keys =", "source) class Argument(Binding): \"\"\" Represents binding a name as an", "super(ImportationFrom, self).__init__(name, source, full_name) def __str__(self): \"\"\"Return import full name", "scope.importStarred and \\ os.path.basename(self.filename) != '__init__.py': # Look for possible", "isinstance(self.scope, FunctionScope) and isinstance(node.parent, ast.Call)): # we are doing locals()", "for deco in node.decorator_list: self.handleNode(deco, node) self.LAMBDA(node) self.addBinding(node, FunctionDefinition(node.name, node))", "of the except: block. for scope in self.scopeStack[::-1]: if node.name", "nothing. try: del self.scope[node.name] except KeyError: pass def ANNASSIGN(self, node):", "def __str__(self): return self.name def __repr__(self): return '<%s object %r", "no # longer have line numbers associated with them. This", "node): name = getNodeName(node) if not name: return # if", "is not global_scope: # One 'global' statement can bind multiple", "isinstance(node.ctx, ast.Store): # Python 3 advanced tuple unpacking: a, *b,", "in args: self.addBinding(node, Argument(name, node)) if isinstance(node.body, list): # case", "if not isinstance(node, ast.Str): return (None, None) if PYPY: doctest_lineno", "C{str} \"\"\" def __init__(self, name, source, full_name=None): self.fullName = full_name", "None if all_binding: all_names = set(all_binding.names) undefined = all_names.difference(scope) else:", "only appear in the name when it is a submodule", "if importStarred: from_list = [] for scope in self.scopeStack[-1::-1]: for", "nodes SLICE = EXTSLICE = INDEX = handleChildren # expression", "name, binding in self.scope.unusedAssignments(): self.report(messages.UnusedVariable, binding.source, name) self.deferAssignment(checkUnusedAssignments) if PY32:", "[[hdl] for hdl in n.handlers] if PY34: LOOP_TYPES = (ast.While,", "StarImportation(module, node) else: importation = ImportationFrom(name, node, module, alias.name) self.addBinding(node,", "ast.Store and shouldn't silence # UndefinedLocal warnings. self.handleNode(node.target, node) self.handleNode(node.annotation,", "(3, 4) # Python 2.5 to 3.3 PY34 = sys.version_info", "= TUPLE def IMPORT(self, node): for alias in node.names: if", "self.offset[0] node.col_offset += self.offset[1] if self.traceTree: print(' ' * self.nodeDepth", "fields: key_first = 'generators'.find else: key_first = 'value'.find return tuple(sorted(fields,", "2.5 to 3.2 PY33 = sys.version_info < (3, 4) #", "# Returns node.id, or node.name, or None if hasattr(node, 'id'):", "hasn't # been declared global used = name in scope", "node.value self.handleNode(node.value, node) def YIELD(self, node): if isinstance(self.scope, (ClassScope, ModuleScope)):", "node is part of a conditional body. \"\"\" current =", "\"\"\" A dictionary key which is a variable. @ivar item:", "used for each scope binding.used = (self.scope, node) from_list.append(binding.fullName) #", "hdl in n.handlers] if PY34: LOOP_TYPES = (ast.While, ast.For) else:", "= doctest.DocTestParser().get_examples def handleDoctests(self, node): try: if hasattr(node, 'docstring'): docstring", "be Assignments, rather it treats them as simple Bindings. \"\"\"", "# TODO: if the global is not used in this", "used for handling function bodies, which must be deferred because", "= node.lineno - node.s.count('\\n') - 1 return (node.s, doctest_lineno) def", "1 else: # Computed incorrectly if the docstring has backslash", "base classes, and the body of its definition. Additionally, add", "ClassScope): continue all_binding = scope.get('__all__') if all_binding and not isinstance(all_binding,", "called. @ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for callables which", "# look in the built-ins if name in self.builtIns: return", "should only appear in the name when it is a", "it's not going to cause potentially # unexpected behaviour so", "to it. \"\"\" self._deferredFunctions.append((callable, self.scopeStack[:], self.offset)) def deferAssignment(self, callable): \"\"\"", "by registering the root module name in the scope, allowing", "# the special name __path__ is valid only in packages", "%s import %s as %s' % (self.module, self.real_name, self.name) else:", "= None traceTree = False builtIns = set(builtin_vars).union(_MAGIC_GLOBALS) _customBuiltIns =", "args.append(wildcard if PY33 else wildcard.arg) if is_py3_func: if PY33: #", "and not self._in_doctest() and not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) for", "= getattr(node, name, None) if isinstance(field, ast.AST): yield field elif", "\"stmt\" type nodes DELETE = PRINT = FOR = ASYNCFOR", "= False star_loc = -1 for i, n in enumerate(node.elts):", "isinstance(value, Importation): used = value.used or value.name in all_names if", "the name when it is a submodule import assert '.'", "isinstance(binding, StarImportation): # mark '*' imports as used for each", "= max([node_lineno] + [arg.lineno for arg in node.args.args]) else: (docstring,", "conditional branch is going to # be executed. return if", "isinstance(other, SubmoduleImportation): # See note in SubmoduleImportation about RedefinedWhileUnused return", "accessed already in the current scope, and hasn't # been", "for i, i_key in enumerate(keys) if i_key == key] values", "hdl in n.handlers] else: def getAlternatives(n): if isinstance(n, ast.If): return", "C{deferred} using their associated scope stack. \"\"\" for handler, scope,", "iter_child_nodes(tree, omit=omit): self.handleNode(node, tree) def isLiteralTupleUnpacking(self, node): if isinstance(node, ast.Assign):", "if isinstance(field, ast.AST): yield field elif isinstance(field, list): for item", "self.source.lineno, id(self)) def redefines(self, other): return isinstance(other, Definition) and self.name", "if scope.importStarred: for binding in scope.values(): if isinstance(binding, StarImportation): binding.used", "access the names # of the class. this is skipped", "return # protected with a NameError handler? if 'NameError' not", "LT = LTE = GT = GTE = IS =", "else: importation = ImportationFrom(name, node, module, alias.name) self.addBinding(node, importation) def", "if value.name in self.scope: # then assume the rebound name", "' + self.name else: return self.fullName class SubmoduleImportation(Importation): \"\"\" A", "node) except KeyError: pass else: return importStarred = importStarred or", "self.scope.importStarred = True self.report(messages.ImportStarUsed, node, module) importation = StarImportation(module, node)", "the deferred functions. self._deferredFunctions = None self.runDeferred(self._deferredAssignments) # Set _deferredAssignments", "rnode.parent, stop) def descendantOf(self, node, ancestors, stop): for a in", "n.orelse] + [[hdl] for hdl in n.handlers] else: def getAlternatives(n):", "which is a variable. @ivar item: The variable AST object.", "isinstance(node, ast.Assign): for child in node.targets + [node.value]: if not", "self.handleNodeLoad(node.target) self.handleNode(node.value, node) self.handleNode(node.target, node) def TUPLE(self, node): if not", "@property def source_statement(self): if self.real_name != self.name: return 'from %s", "RuntimeError(\"Got impossible expression context: %r\" % (node.ctx,)) def CONTINUE(self, node):", "== omit: continue field = getattr(node, name, None) if isinstance(field,", "'kwarg'): wildcard = getattr(node.args, arg_name) if not wildcard: continue args.append(wildcard", "\\ BITOR = BITXOR = BITAND = FLOORDIV = INVERT", "binding a name as an argument. \"\"\" class Assignment(Binding): \"\"\"", "node.bases: self.handleNode(baseNode, node) if not PY2: for keywordNode in node.keywords:", "value, a Binding instance \"\"\" # assert value.source in (node,", "else: return self.name class FutureImportation(ImportationFrom): \"\"\" A binding created by", "will fail # noisily if called after we've run through", "in undefined: self.report(messages.UndefinedExport, scope['__all__'].source, name) # mark all import '*'", "self.scopeStack[-1::-1]: for binding in scope.values(): if isinstance(binding, StarImportation): # mark", "the builtins module, or # are only present on some", "self.scope.unusedAssignments(): self.report(messages.UnusedVariable, binding.source, name) self.deferAssignment(checkUnusedAssignments) if PY32: def checkReturnWithArgumentInsideGenerator(): \"\"\"", "can access the names # of the class. this is", "PASS = ignore # \"expr\" type nodes BOOLOP = BINOP", "def getNodeType(node_class): # workaround str.upper() which is locale-dependent return str(unicode(node_class.__name__).upper())", "node): pass # \"stmt\" type nodes DELETE = PRINT =", "defaults = node.args.defaults + node.args.kw_defaults # Only for Python3 FunctionDefs", "LIST = TUPLE def IMPORT(self, node): for alias in node.names:", "pyflakes import messages if PY2: def getNodeType(node_class): # workaround str.upper()", "for scope in self.scopeStack[::-1]: if node.name in scope: is_name_previously_defined =", "pass else: return importStarred = importStarred or scope.importStarred if in_generators", "= ignore # \"expr\" type nodes BOOLOP = BINOP =", "getattr(current, 'parent', None) return False name = getNodeName(node) if not", "1: self.report(messages.DefaultExceptNotLast, handler) # Memorize the except handlers and process", "] for key in duplicate_keys: key_indices = [i for i,", "_in_doctest(self): return (len(self.scopeStack) >= 2 and isinstance(self.scopeStack[1], DoctestScope)) @property def", "scope[name].source) break parent_stmt = self.getParent(node) if isinstance(parent_stmt, (ast.For, ast.comprehension)) or", "binding.used = (self.scope, node) from_list.append(binding.fullName) # report * usage, with", "class StarImportation(Importation): \"\"\"A binding created by a 'from x import", "(docstring, node_lineno) = self.getDocstring(node.body[0]) examples = docstring and self._getDoctestExamples(docstring) except", "DELETE = PRINT = FOR = ASYNCFOR = WHILE =", "not self._in_doctest() and not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) for stmt", "other): if isinstance(other, Importation): return self.fullName == other.fullName return super(SubmoduleImportation,", "ancestor) ^ \\ self.descendantOf(rnode, items, ancestor): return True return False", "This will be # incorrect if there are empty lines", "* usage, with a list of possible sources from_list =", "used in a class definition, including its decorators, base classes,", "= EXTSLICE = INDEX = handleChildren # expression contexts are", "it's not really ast.Store and shouldn't silence # UndefinedLocal warnings.", "scope.values(): if isinstance(binding, StarImportation): # mark '*' imports as used", "itself if n_child not in n.orelse: return if isinstance(n, (ast.FunctionDef,", "complete name given to the import statement, possibly including multiple", "for each function or module scope above us for scope", "ASSIGN = handleChildren PASS = ignore # \"expr\" type nodes", "the docstring. node_lineno = node.lineno if hasattr(node, 'args'): node_lineno =", "if PY2: def addArgs(arglist): for arg in arglist: if isinstance(arg,", "being unbound # after leaving the except: block and it's", "for callables which are deferred assignment checks. \"\"\" nodeDepth =", "PY2 else GENERATOREXP DICTCOMP = SETCOMP = GENERATOREXP def NAME(self,", "or node.name is None: self.handleChildren(node) return # 3.x: the name", "branch is going to # be executed. return if isinstance(self.scope,", "= None if all_binding: all_names = set(all_binding.names) undefined = all_names.difference(scope)", "cause potentially # unexpected behaviour so we'll not complain. keys", "This is used for handling function bodies, which must be", "\"\"\" Run the callables in C{deferred} using their associated scope", "for possible mistakes in the export list for name in", "isinstance(n, ast.Try): return [n.body + n.orelse] + [[hdl] for hdl", "Return `True` if node is part of a conditional body.", "None if lnode is rnode: return lnode if (lnode.depth >", "False builtin_vars = dir(__import__('__builtin__' if PY2 else 'builtins')) try: import", "_ast as ast if 'decorator_list' not in ast.ClassDef._fields: # Patch", "SubmoduleImportation): # See note in SubmoduleImportation about RedefinedWhileUnused return self.fullName", "getattr(node, 'lineno', None) is not None: node.lineno += self.offset[0] node.col_offset", "parent try: handler = self.getNodeHandler(node.__class__) handler(node) finally: self.nodeDepth -= 1", "# Otherwise it's not really ast.Store and shouldn't silence #", "created by an C{__all__} assignment. If the names in the", "self.descendantOf(rnode, items, ancestor): return True return False def addBinding(self, node,", "\"\"\" for name, binding in self.scope.unusedAssignments(): self.report(messages.UnusedVariable, binding.source, name) self.deferAssignment(checkUnusedAssignments)", "pyflakes handles this case by registering the root module name", "self.exceptHandlers = [()] self.root = tree self.handleChildren(tree) self.runDeferred(self._deferredFunctions) # Set", "is_py3_func: if PY33: # Python 2.5 to 3.3 argannotation =", "'generators'.find else: key_first = 'value'.find return tuple(sorted(fields, key=key_first, reverse=True)) def", "LOOP_TYPES): # Doesn't apply unless it's in the loop itself", "A binding created by an import statement. @ivar fullName: The", "strings. For example:: __all__ = [\"foo\", \"bar\"] Names which are", "* node.level) + (node.module or '') for alias in node.names:", "self.fullName + ' import *' def __str__(self): # When the", "the exception, which is not a Name node, but #", "full name with alias.\"\"\" if self._has_alias(): return self.fullName + '", "Check names used in a class definition, including its decorators,", "duplicate_keys = [ key for key, count in key_counts.items() if", "will be # incorrect if there are empty lines between", "Otherwise it's not really ast.Store and shouldn't silence # UndefinedLocal", "until we see a loop (OK), a function or class", "def getDocstring(self, node): if isinstance(node, ast.Expr): node = node.value if", "used. \"\"\" def __init__(self, name, source): self.name = name self.source", "Yield all direct child nodes of *node*, that is, all", "a name as an argument. \"\"\" class Assignment(Binding): \"\"\" Represents", "be deferred because code later in the file might modify", "all import '*' as used by the undefined in __all__", "in this function. \"\"\" usesLocals = False alwaysUsed = set(['__tracebackhide__',", "node.names: if '.' in alias.name and not alias.asname: importation =", "addBinding(self, node, value): \"\"\" Called when a binding is altered.", "body self.exceptHandlers.append(handler_names) for child in node.body: self.handleNode(child, node) self.exceptHandlers.pop() #", "node) else: name = alias.asname or alias.name importation = Importation(name,", "self.name, self.source.lineno, id(self)) def redefines(self, other): return isinstance(other, Definition) and", "__missing__(self, node_class): self[node_class] = fields = self._get_fields(node_class) return fields def", "have been fully examined and report names in them which", "LTE = GT = GTE = IS = ISNOT =", "later in the file might modify the global scope. When", "classes are processed. if (self.withDoctest and not self._in_doctest() and not", "self.fullName.split('.')[-1] == self.name @property def source_statement(self): \"\"\"Generate a source statement", "node while hasattr(n, 'parent'): n, n_child = n.parent, n if", "distinguish two from more # than two. break has_starred =", "\"\"\" usesLocals = False alwaysUsed = set(['__tracebackhide__', '__traceback_info__', '__traceback_supplement__']) def", "break has_starred = True star_loc = i if star_loc >=", "UNARYOP = IFEXP = SET = \\ COMPARE = CALL", "for item in items: results[item] = results.get(item, 0) + 1", "= self.getCommonAncestor(lnode, rnode, self.root) parts = getAlternatives(ancestor) if parts: for", "for FunctionDefs for stmt in node.body: self.handleNode(stmt, node) else: #", "def source_statement(self): return 'import ' + self.fullName class ImportationFrom(Importation): def", "= results.get(item, 0) + 1 return results def iter_child_nodes(node, omit=None,", "@property def source_statement(self): return 'from ' + self.fullName + '", "associated with them. This will be # incorrect if there", "checker will raise warnings for any Assignment that isn't used.", "key_node, key.name) else: self.report( messages.MultiValueRepeatedKeyLiteral, key_node, key, ) self.handleChildren(node) def", "in node.args.args + node.args.kwonlyargs: args.append(arg.arg) annotations.append(arg.annotation) defaults = node.args.defaults +", "property(lambda s: s.decorators) from pyflakes import messages if PY2: def", "1<<8 # assignments are allowed before a stared expression. There", "in self.scope: # then assume the rebound name is used", "source) # Each star importation needs a unique name, and", "there is any return statement with arguments but the function", "import _ast as ast if 'decorator_list' not in ast.ClassDef._fields: #", "BYTES = ELLIPSIS = ignore # \"slice\" type nodes SLICE", "variable. @ivar item: The variable AST object. \"\"\" def __init__(self,", "# mark all import '*' as used by the undefined", "that is, all fields that are nodes and all items", "assignment handler to be called just after deferred function handlers.", "False builtIns = set(builtin_vars).union(_MAGIC_GLOBALS) _customBuiltIns = os.environ.get('PYFLAKES_BUILTINS') if _customBuiltIns: builtIns.update(_customBuiltIns.split(','))", "self.handleNode(keywordNode, node) self.pushScope(ClassScope) # doctest does not process doctest within", "(ast.For, ast.comprehension))): self.report(messages.RedefinedInListComp, node, value.name, existing.source) elif not existing.used and", "1 position = (node_lineno + example.lineno + e.lineno, example.indent +", "exception, which is not a Name node, but # a", "represent a name scope for a function. @ivar globals: Names", "not Tuple, List or Starred while True: node = node.parent", "self.getParent(value.source) if isinstance(existing, Importation) and isinstance(parent_stmt, ast.For): self.report(messages.ImportShadowedByLoopVar, node, value.name,", "class ClassScope(Scope): pass class FunctionScope(Scope): \"\"\" I represent a name", "node_class): # handle iter before target, and generators before element", "self.scope.globals: self.scope.globals.remove(name) else: try: del self.scope[name] except KeyError: self.report(messages.UndefinedName, node,", "name __path__ is valid only in packages return # protected", "and getattr(node, 'lineno', None) is not None: node.lineno += self.offset[0]", "are node instances too, though being constants LOAD = STORE", "binding class GeneratorScope(Scope): pass class ModuleScope(Scope): \"\"\"Scope for a module.\"\"\"", "and self.name == other.name def _has_alias(self): \"\"\"Return whether importation needs", "not self.fullName.split('.')[-1] == self.name @property def source_statement(self): \"\"\"Generate a source", "handler() def _in_doctest(self): return (len(self.scopeStack) >= 2 and isinstance(self.scopeStack[1], DoctestScope))", "after deferred function handlers. \"\"\" self._deferredAssignments.append((callable, self.scopeStack[:], self.offset)) def runDeferred(self,", "and the name has # been accessed already in the", "if n_child not in n.orelse: return if isinstance(n, (ast.FunctionDef, ast.ClassDef)):", "argannotation)) else: # Python >= 3.4 annotations.append(wildcard.annotation) if is_py3_func: annotations.append(node.returns)", "_deferredFunctions to None so that deferFunction will fail # noisily", "'parent', None) while current: if isinstance(current, (ast.If, ast.While, ast.IfExp)): return", "node) def TUPLE(self, node): if not PY2 and isinstance(node.ctx, ast.Store):", "self._deferredAssignments.append((callable, self.scopeStack[:], self.offset)) def runDeferred(self, deferred): \"\"\" Run the callables", "POW = LSHIFT = RSHIFT = \\ BITOR = BITXOR", "can be recognized is one which takes the value of", "of which names have been bound and which names have", "\"\"\"A binding created by a 'from x import *' statement.\"\"\"", "docstring and self._getDoctestExamples(docstring) except (ValueError, IndexError): # e.g. line 6", "name, and # may not be the module name otherwise", "not in self.scope.globals: # then it's probably a mistake self.report(messages.UndefinedLocal,", "result = VariableKey(item=item) constants_lookup = { 'True': True, 'False': False,", "isinstance(m, messages.UndefinedName) or m.message_args[0] != node_name] # Bind name to", "If they have the same value it's not going to", "and isinstance(node.parent, ast.Call)): # we are doing locals() call in", "+ example.lineno + e.lineno, example.indent + 4 + (e.offset or", "an assignment handler to be called just after deferred function", "return isinstance(other, Definition) and self.name == other.name class Definition(Binding): \"\"\"", "= RSHIFT = \\ BITOR = BITXOR = BITAND =", "not examples: return # Place doctest in module scope saved_stack", "import full name with alias.\"\"\" if self._has_alias(): return self.fullName +", "scope for a function. @ivar globals: Names declared 'global' in", "# If they have the same value it's not going", "to True when import * is found def __repr__(self): scope_cls", "bound and which names have not. See L{Assignment} for a", "name, from_list) return if name == '__path__' and os.path.basename(self.filename) ==", "been bound and which names have not. See L{Assignment} for", "[] if PY2: def addArgs(arglist): for arg in arglist: if", "AttributeError: PYPY = False builtin_vars = dir(__import__('__builtin__' if PY2 else", "node.targets + [node.value]: if not hasattr(child, 'elts'): return False return", "raise warnings for any Assignment that isn't used. Also, the", "hasattr(n, 'parent'): n, n_child = n.parent, n if isinstance(n, LOOP_TYPES):", "node) if not PY2: for keywordNode in node.keywords: self.handleNode(keywordNode, node)", "node) BREAK = CONTINUE def RETURN(self, node): if isinstance(self.scope, (ClassScope,", "# Only one starred expression is allowed, and no more", "= sys.version_info < (3, 0) PY32 = sys.version_info < (3,", "del self.scopeStack[1:] self.popScope() self.checkDeadScopes() def deferFunction(self, callable): \"\"\" Schedule a", "== other.fullName return isinstance(other, Definition) and self.name == other.name def", "= False self.handleNodeStore(node) self.handleChildren(node) if not is_name_previously_defined: # See discussion", "if n_child in n.finalbody: self.report(messages.ContinueInFinally, node) return if isinstance(node, ast.Continue):", "try: import ast except ImportError: # Python 2.5 import _ast", "import full name with alias.\"\"\" if self.real_name != self.name: return", "are public members if isinstance(scope, ClassScope): continue all_binding = scope.get('__all__')", "for arg in node.args.args + node.args.kwonlyargs: args.append(arg.arg) annotations.append(arg.annotation) defaults =", "8 or len(node.elts) - star_loc - 1 >= 1 <<", "missing attribute 'decorator_list' ast.ClassDef.decorator_list = () ast.FunctionDef.decorator_list = property(lambda s:", "(ast.If, ast.While, ast.IfExp)): return True current = getattr(current, 'parent', None)", "self.name class FutureImportation(ImportationFrom): \"\"\" A binding created by a from", "self.isGenerator = False # Detect a generator def unusedAssignments(self): \"\"\"", "in current scope self.scope.usesLocals = True elif isinstance(node.ctx, (ast.Store, ast.AugStore)):", "checkUnusedAssignments(): \"\"\" Check to see if any assignments have not", "in __all__ if scope.importStarred: for binding in scope.values(): if isinstance(binding,", "INDEX = handleChildren # expression contexts are node instances too,", "name not in self.scope: # for each function or module", "= node.args.defaults + node.args.kw_defaults # Only for Python3 FunctionDefs is_py3_func", "ast.For): messg = messages.ImportShadowedByLoopVar elif used: continue else: messg =", "field elif isinstance(field, list): for item in field: yield item", "RAISE = TRYFINALLY = EXEC = \\ EXPR = ASSIGN", "getattr(node.args, arg_name) if not wildcard: continue args.append(wildcard if PY33 else", "Tracking list used by L{deferFunction}. Elements of the list are", "A submodule import is a special case where the root", ">= 1 << 24: self.report(messages.TooManyExpressionsInStarredAssignment, node) self.handleChildren(node) LIST = TUPLE", "self.handleNodeLoad(node) if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and isinstance(node.parent,", "`__future__` import statement. `__future__` imports are implicitly used. \"\"\" def", "or value.name in all_names if not used: messg = messages.UnusedImport", "= [] if isinstance(source.value, (ast.List, ast.Tuple)): for node in source.value.elts:", "= set(all_binding.names) undefined = all_names.difference(scope) else: all_names = undefined =", "stack at the time L{deferFunction} was called. @ivar _deferredAssignments: Similar", "self.root = tree self.handleChildren(tree) self.runDeferred(self._deferredFunctions) # Set _deferredFunctions to None", "return (None, None) if PYPY: doctest_lineno = node.lineno - 1", "= NOT = UADD = USUB = \\ EQ =", "and not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) ASYNCFUNCTIONDEF = FUNCTIONDEF def", "None self.runDeferred(self._deferredAssignments) # Set _deferredAssignments to None so that deferAssignment", "scope saved_stack = self.scopeStack self.scopeStack = [self.scopeStack[0]] node_offset = self.offset", "checked with stricter rules. @ivar used: pair of (L{Scope}, node)", "has # been accessed already in the current scope, and", "scope_cls = self.__class__.__name__ return '<%s at 0x%x %s>' % (scope_cls,", "a loop value.used = self.scope[value.name].used self.scope[value.name] = value def getNodeHandler(self,", "for scope in self.scopeStack[-1::-1]: # only generators used in a", "Bindings and Scopes. \"\"\" import __future__ import doctest import os", "sys.exc_info()[1] if PYPY: e.offset += 1 position = (node_lineno +", "scope: break existing = scope.get(value.name) if existing and not self.differentForks(node,", "and self._getDoctestExamples(docstring) except (ValueError, IndexError): # e.g. line 6 of", "+ [arg.lineno for arg in node.args.args]) else: (docstring, node_lineno) =", "else 'builtins')) try: import ast except ImportError: # Python 2.5", "nameconstants in python3, but names in 2 return item.value else:", "item.elts) elif isinstance(item, ast.Num): return item.n elif isinstance(item, ast.Name): result", "always unbound # if the except: block is never entered.", "deferFunction will fail # noisily if called after we've run", "source.value.elts: if isinstance(node, ast.Str): self.names.append(node.s) super(ExportBinding, self).__init__(name, source) class Scope(dict):", "and name not in self.scope.globals: # then it's probably a", "self.redefined = [] super(Importation, self).__init__(name, source) def redefines(self, other): if", "PYPY: doctest_lineno = node.lineno - 1 else: # Computed incorrectly", "Name (which can be a load/store/delete access.) \"\"\" # Locate", "else: # must be a Param context -- this only", "saved_stack def ignore(self, node): pass # \"stmt\" type nodes DELETE", "(not binding.used and name not in self.globals and not self.usesLocals", "at scopes which have been fully examined and report names", "= importStarred or scope.importStarred if in_generators is not False: in_generators", "class _FieldsOrder(dict): \"\"\"Fix order of AST node fields.\"\"\" def _get_fields(self,", "isinstance(item, ast.Name): result = VariableKey(item=item) constants_lookup = { 'True': True,", "= [] self.messages = [] self.filename = filename if builtins:", "'Bytes') and isinstance(item, ast.Bytes): return item.s elif isinstance(item, ast.Tuple): return", "and name in self.scope.globals: self.scope.globals.remove(name) else: try: del self.scope[name] except", "as ' + self.name else: return self.fullName class SubmoduleImportation(Importation): \"\"\"", "# if the except: block is never entered. This will", "Python 2.5 import _ast as ast if 'decorator_list' not in", "COMPARE = CALL = REPR = ATTRIBUTE = SUBSCRIPT =", "underscore_in_builtins: self.builtIns.remove('_') self.popScope() self.scopeStack = saved_stack def ignore(self, node): pass", "they have the same value it's not going to cause", "m.message_args[0] != node_name] # Bind name to global scope if", "node.names: node_value = Assignment(node_name, node) # Remove UndefinedName messages already", "self.report(messages.UndefinedName, node, name) def handleNodeStore(self, node): name = getNodeName(node) if", "Python 3 advanced tuple unpacking: a, *b, c = d.", "= module + self.real_name else: full_name = module + '.'", "this only happens for names in function # arguments, but", "to # be executed. return if isinstance(self.scope, FunctionScope) and name", "in scope: is_name_previously_defined = True break else: is_name_previously_defined = False", "isinstance(n, ast.TryExcept): return [n.body + n.orelse] + [[hdl] for hdl", "in Python < and >= 3.3 if hasattr(n, 'finalbody') and", "them as simple Bindings. \"\"\" class FunctionDefinition(Definition): pass class ClassDefinition(Definition):", "ignore # \"expr\" type nodes BOOLOP = BINOP = UNARYOP", "source) class Scope(dict): importStarred = False # set to True", "if isinstance(node, ast.Expr): node = node.value if not isinstance(node, ast.Str):", "\"\"\" Check names used in a class definition, including its", "= 'value'.find return tuple(sorted(fields, key=key_first, reverse=True)) def __missing__(self, node_class): self[node_class]", "which must be deferred because code later in the file", "not name: return # if the name hasn't already been", "dictionary key of a type that we cannot or do", "source self.used = False def __str__(self): return self.name def __repr__(self):", "wildcard.arg) if is_py3_func: if PY33: # Python 2.5 to 3.3", "if isinstance(self.scope, FunctionScope) and name not in self.scope: # for", "is called will be restored, however it will contain any", "node_class): try: return self._nodeHandlers[node_class] except KeyError: nodeType = getNodeType(node_class) self._nodeHandlers[node_class]", "(node_lineno + example.lineno + e.lineno, example.indent + 4 + (e.offset", "ast.ClassDef._fields: # Patch the missing attribute 'decorator_list' ast.ClassDef.decorator_list = ()", "0) self.pushScope(DoctestScope) underscore_in_builtins = '_' in self.builtIns if not underscore_in_builtins:", "star_loc = -1 for i, n in enumerate(node.elts): if isinstance(n,", "return # 3.x: the name of the exception, which is", "isinstance(self.scope, ModuleScope): self.scope._futures_allowed = False @property def scope(self): return self.scopeStack[-1]", "node) def runFunction(): self.pushScope() for name in args: self.addBinding(node, Argument(name,", "node_offset if not underscore_in_builtins: self.builtIns.remove('_') self.popScope() self.scopeStack = saved_stack def", "self.name = name + '.*' self.fullName = name @property def", "handler_names.append(getNodeName(exc_type)) elif handler.type: handler_names.append(getNodeName(handler.type)) if handler.type is None and i", "source) self.fullName = name def redefines(self, other): if isinstance(other, Importation):", "will be deemed imported self.name = name + '.*' self.fullName", "\"\"\" def __init__(self, name, source, scope): super(FutureImportation, self).__init__(name, source, '__future__')", "EXTSLICE = INDEX = handleChildren # expression contexts are node", "def runDeferred(self, deferred): \"\"\" Run the callables in C{deferred} using", "imported, without an 'as' clause, and the submodule is also", "attribute of the root module to be accessed. RedefinedWhileUnused is", "or a class. \"\"\" class UnhandledKeyType(object): \"\"\" A dictionary key", "== other.fullName return super(SubmoduleImportation, self).redefines(other) def __str__(self): return self.fullName @property", "in scope: break existing = scope.get(value.name) if existing and not", "ast.Str) or (isinstance(node, ast.Expr) and isinstance(node.value, ast.Str)) def getDocstring(self, node):", "type nodes DELETE = PRINT = FOR = ASYNCFOR =", "if isinstance(parent_stmt, (ast.For, ast.comprehension)) or ( parent_stmt != node.parent and", "lists of nodes. \"\"\" for name in _fields_order[node.__class__]: if name", "'<%s object %r from line %r at 0x%x>' % (self.__class__.__name__,", "real_name or name if module.endswith('.'): full_name = module + self.real_name", "name. See test_unused_global. self.messages = [ m for m in", "PY34 = sys.version_info < (3, 5) # Python 2.5 to", "= False builtIns = set(builtin_vars).union(_MAGIC_GLOBALS) _customBuiltIns = os.environ.get('PYFLAKES_BUILTINS') if _customBuiltIns:", "node.body: self.handleNode(child, node) self.exceptHandlers.pop() # Process the other nodes: \"except:\",", "and os.path.basename(self.filename) == '__init__.py': # the special name __path__ is", "created by a from `__future__` import statement. `__future__` imports are", "in deferred: self.scopeStack = scope self.offset = offset handler() def", "scope, and hasn't # been declared global used = name", "# Look for imported names that aren't used. for value", "== '__future__': importation = FutureImportation(name, node, self.scope) if alias.name not", "When the module ends with a ., avoid the ambiguous", "' import *' def __str__(self): # When the module ends", "!= '__init__.py': # Look for possible mistakes in the export", "1 >= 1 << 24: self.report(messages.TooManyExpressionsInStarredAssignment, node) self.handleChildren(node) LIST =", "function or a class. \"\"\" class UnhandledKeyType(object): \"\"\" A dictionary", "\"\"\" A binding created by a submodule import statement. A", "added to it. \"\"\" self._deferredFunctions.append((callable, self.scopeStack[:], self.offset)) def deferAssignment(self, callable):", "if there is any return statement with arguments but the", "self.name) class StarImportation(Importation): \"\"\"A binding created by a 'from x", "def redefines(self, other): if isinstance(other, SubmoduleImportation): # See note in", "# Bind name to global scope if it doesn't exist", "Look for possible mistakes in the export list for name", "n.parent, n if isinstance(n, LOOP_TYPES): # Doesn't apply unless it's", "# if the name hasn't already been defined in the", "in n.orelse: return if isinstance(n, (ast.FunctionDef, ast.ClassDef)): break # Handle", "True break else: is_name_previously_defined = False self.handleNodeStore(node) self.handleChildren(node) if not", "used. This class is only used when the submodule import", "self.handleChildren(node) if not is_name_previously_defined: # See discussion on https://github.com/PyCQA/pyflakes/pull/59 #", "= tree self.handleChildren(tree) self.runDeferred(self._deferredFunctions) # Set _deferredFunctions to None so", "# which is impossible to test due to memory restrictions,", "impossible to test due to memory restrictions, but we #", "new bindings added to it. \"\"\" self._deferredFunctions.append((callable, self.scopeStack[:], self.offset)) def", "an import statement. @ivar fullName: The complete name given to", "and isinstance(binding, Assignment)): yield name, binding class GeneratorScope(Scope): pass class", "to be called just after deferred function handlers. \"\"\" self._deferredAssignments.append((callable,", "def GENERATOREXP(self, node): self.pushScope(GeneratorScope) self.handleChildren(node) self.popScope() LISTCOMP = handleChildren if", "the scope, allowing any attribute of the root module to", "in arglist: if isinstance(arg, ast.Tuple): addArgs(arg.elts) else: args.append(arg.id) addArgs(node.args.args) defaults", "count in key_counts.items() if count > 1 ] for key", "for scope in self.scopeStack): return False return self.scope._futures_allowed @futuresAllowed.setter def", "self.handleNodeDelete(node) else: # must be a Param context -- this", "for export and additional checking applied to them. The only", "continue try: scope[name].used = (self.scope, node) except KeyError: pass else:", "else: for arg in node.args.args + node.args.kwonlyargs: args.append(arg.arg) annotations.append(arg.annotation) defaults", "alias.name if node.module == '__future__': importation = FutureImportation(name, node, self.scope)", "node, ancestors, stop): for a in ancestors: if self.getCommonAncestor(node, a,", "handler.type.elts: handler_names.append(getNodeName(exc_type)) elif handler.type: handler_names.append(getNodeName(handler.type)) if handler.type is None and", "+ ' as ' + self.name else: return self.fullName @property", "ImportError: # Python 2.5 import _ast as ast if 'decorator_list'", "= getNodeName(node) if not name: return # if the name", "node is None: return if self.offset and getattr(node, 'lineno', None)", "None and i < len(node.handlers) - 1: self.report(messages.DefaultExceptNotLast, handler) #", "to 3.2 PY33 = sys.version_info < (3, 4) # Python", "or m.message_args[0] != node_name] # Bind name to global scope", "-- this only happens for names in function # arguments,", "names for export and additional checking applied to them. The", "See note in SubmoduleImportation about RedefinedWhileUnused return self.fullName == other.fullName", "@ivar item: The variable AST object. \"\"\" def __init__(self, item):", "starred expression is allowed, and no more than 1<<8 #", "the name hasn't already been defined in the current scope", "expressions after the starred expression, # which is impossible to", "not PY2 and isinstance(node.ctx, ast.Store): # Python 3 advanced tuple", "of the many nodes with an id return node.id if", "otherwise used but appear in the value of C{__all__} will", "if the name was defined in that scope, and the", "= STORE = DEL = AUGLOAD = AUGSTORE = PARAM", "del _customBuiltIns def __init__(self, tree, filename='(none)', builtins=None, withDoctest='PYFLAKES_DOCTEST' in os.environ):", "source, scope): if '__all__' in scope and isinstance(source, ast.AugAssign): self.names", "= CALL = REPR = ATTRIBUTE = SUBSCRIPT = \\", "See test_unused_global. self.messages = [ m for m in self.messages", "def TRY(self, node): handler_names = [] # List the exception", "non-empty return self.isGenerator = False # Detect a generator def", "return self.fullName == other.fullName return isinstance(other, Definition) and self.name ==", "{} for item in items: results[item] = results.get(item, 0) +", "set(builtin_vars).union(_MAGIC_GLOBALS) _customBuiltIns = os.environ.get('PYFLAKES_BUILTINS') if _customBuiltIns: builtIns.update(_customBuiltIns.split(',')) del _customBuiltIns def", "same, to avoid false positives. \"\"\" def __init__(self, name, source):", "module name in the scope, allowing any attribute of the", "return if ( node.value and hasattr(self.scope, 'returnValue') and not self.scope.returnValue", "self._nodeHandlers[node_class] except KeyError: nodeType = getNodeType(node_class) self._nodeHandlers[node_class] = handler =", "node) self.exceptHandlers.pop() # Process the other nodes: \"except:\", \"else:\", \"finally:\"", "2, local import * is a SyntaxWarning if not PY2", "= PRINT = FOR = ASYNCFOR = WHILE = IF", "**kwargs)) def getParent(self, node): # Lookup the first parent which", "# \"undefined name\" error raised if the checked code tries", "return # Place doctest in module scope saved_stack = self.scopeStack", "self.fullName + ' as ' + self.name else: return self.fullName", "+ example.lineno, node_offset[1] + example.indent + 4) self.handleChildren(tree) self.offset =", "but for callables which are deferred assignment checks. \"\"\" nodeDepth", "getNodeType(node_class): # workaround str.upper() which is locale-dependent return str(unicode(node_class.__name__).upper()) else:", "-1 for i, n in enumerate(node.elts): if isinstance(n, ast.Starred): if", "present on some platforms. _MAGIC_GLOBALS = ['__file__', '__builtins__', 'WindowsError'] def", "'as' clause. pyflakes handles this case by registering the root", "super(SubmoduleImportation, self).__init__(package_name, source) self.fullName = name def redefines(self, other): if", "# protected with a NameError handler? if 'NameError' not in", "WHILE = IF = WITH = WITHITEM = \\ ASYNCWITH", "if there are empty lines between the beginning # of", "__all__ = [\"foo\", \"bar\"] Names which are imported and not", "key in node.keys ] key_counts = counter(keys) duplicate_keys = [", "key_indices = [i for i, i_key in enumerate(keys) if i_key", "3.7, docstrings no # longer have line numbers associated with", "self.handleChildren(node) def GLOBAL(self, node): \"\"\" Keep track of globals declarations.", "but as already \"used\". node_value.used = (global_scope, node) for scope", "impossible expression context: %r\" % (node.ctx,)) def CONTINUE(self, node): #", "= MOD = POW = LSHIFT = RSHIFT = \\", "# arguments, but these aren't dispatched through here raise RuntimeError(\"Got", "\"\"\" def __init__(self, name, source): # A dot should only", "entered. This will cause an # \"undefined name\" error raised", "= self.scopeStack self.scopeStack = [self.scopeStack[0]] node_offset = self.offset or (0,", "self.scopeStack[:], self.offset)) def runDeferred(self, deferred): \"\"\" Run the callables in", "except: block. for scope in self.scopeStack[::-1]: if node.name in scope:", "if self.real_name != self.name: return 'from %s import %s as", "docstring, as long as it is at the correct place", "one starred expression is allowed, and no more than 1<<8", "# workaround str.upper() which is locale-dependent return str(unicode(node_class.__name__).upper()) else: def", "+ ' import *' def __str__(self): # When the module", "< and >= 3.3 if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):", "d. # Only one starred expression is allowed, and no", "'name'): # an ExceptHandler node return node.name class Checker(object): \"\"\"", "There is # also a limit of 1<<24 expressions after", "FunctionScope(Scope): \"\"\" I represent a name scope for a function.", "if '.' in alias.name and not alias.asname: importation = SubmoduleImportation(alias.name,", "[] self.deadScopes = [] self.messages = [] self.filename = filename", "is not Tuple, List or Starred while True: node =", "result.name, result, ) elif (not PY33) and isinstance(item, ast.NameConstant): #", "else: return 'from %s import %s' % (self.module, self.name) class", "assert value is False if isinstance(self.scope, ModuleScope): self.scope._futures_allowed = False", "] key_counts = counter(keys) duplicate_keys = [ key for key,", "exception handlers for i, handler in enumerate(node.handlers): if isinstance(handler.type, ast.Tuple):", "class Binding(object): \"\"\" Represents the binding of a value to", "i, i_key in enumerate(keys) if i_key == key] values =", "node.decorator_list: self.handleNode(deco, node) self.LAMBDA(node) self.addBinding(node, FunctionDefinition(node.name, node)) # doctest does", "SubmoduleImportation about RedefinedWhileUnused return self.fullName == other.fullName return isinstance(other, Definition)", "name def redefines(self, other): if isinstance(other, Importation): return self.fullName ==", "self.descendantOf(lnode, items, ancestor) ^ \\ self.descendantOf(rnode, items, ancestor): return True", "= LTE = GT = GTE = IS = ISNOT", "name given to the import statement, possibly including multiple dotted", "if hasattr(n, 'finalbody') and isinstance(node, ast.Continue): if n_child in n.finalbody:", "all fields that are nodes and all items of fields", "this is called will be restored, however it will contain", "node, value.name, existing.source) elif isinstance(existing, Importation) and value.redefines(existing): existing.redefined.append(node) if", "if any assignments have not been used. \"\"\" for name,", "alias.name and not alias.asname: importation = SubmoduleImportation(alias.name, node) else: name", "if hasattr(node, 'docstring'): docstring = node.docstring # This is just", "context -- this only happens for names in function #", "example.indent + 4 + (e.offset or 0)) self.report(messages.DoctestSyntaxError, node, position)", "omit: continue field = getattr(node, name, None) if isinstance(field, ast.AST):", "have not. See L{Assignment} for a special type of binding", "not been used. \"\"\" for name, binding in self.scope.unusedAssignments(): self.report(messages.UnusedVariable,", "object. \"\"\" def __init__(self, item): self.name = item.id def __eq__(self,", "module, real_name=None): self.module = module self.real_name = real_name or name", "def __str__(self): \"\"\"Return import full name with alias.\"\"\" if self._has_alias():", "doesn't exist already. global_scope.setdefault(node_name, node_value) # Bind name to non-global", "4) # Python 2.5 to 3.3 PY34 = sys.version_info <", "<< 24: self.report(messages.TooManyExpressionsInStarredAssignment, node) self.handleChildren(node) LIST = TUPLE def IMPORT(self,", "if node.module == '__future__': importation = FutureImportation(name, node, self.scope) if", "= AUGSTORE = PARAM = ignore # same for operators", "we cannot or do not check for duplicates. \"\"\" class", "doctest in module scope saved_stack = self.scopeStack self.scopeStack = [self.scopeStack[0]]", "GENERATOREXP(self, node): self.pushScope(GeneratorScope) self.handleChildren(node) self.popScope() LISTCOMP = handleChildren if PY2", "and not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) for stmt in node.body:", "importation needs a unique name, and # may not be", "stop) def descendantOf(self, node, ancestors, stop): for a in ancestors:", "used = name in scope and scope[name].used if used and", "KeyError: nodeType = getNodeType(node_class) self._nodeHandlers[node_class] = handler = getattr(self, nodeType)", "if not underscore_in_builtins: self.builtIns.add('_') for example in examples: try: tree", "def RETURN(self, node): if isinstance(self.scope, (ClassScope, ModuleScope)): self.report(messages.ReturnOutsideFunction, node) return", "def addArgs(arglist): for arg in arglist: if isinstance(arg, ast.Tuple): addArgs(arg.elts)", "the docstring for <string> has inconsistent # leading whitespace: ...", "def __eq__(self, compare): return ( compare.__class__ == self.__class__ and compare.name", "first element is the callable passed to L{deferFunction}. The second", "example:: __all__ = [\"foo\", \"bar\"] Names which are imported and", "expression context: %r\" % (node.ctx,)) def CONTINUE(self, node): # Walk", "are allowed before a stared expression. There is # also", "== self.__class__ and compare.name == self.name ) def __hash__(self): return", "ignore(self, node): pass # \"stmt\" type nodes DELETE = PRINT", "for name, binding in self.items(): if (not binding.used and name", "id(self)) def redefines(self, other): return isinstance(other, Definition) and self.name ==", "= self.builtIns.union(builtins) self.withDoctest = withDoctest self.scopeStack = [ModuleScope()] self.exceptHandlers =", "that we cannot or do not check for duplicates. \"\"\"", "deferred assignment checks. \"\"\" nodeDepth = 0 offset = None", "ast.Expr) and isinstance(node.value, ast.Str)) def getDocstring(self, node): if isinstance(node, ast.Expr):", "process doctest within a doctest # classes within classes are", "offset in deferred: self.scopeStack = scope self.offset = offset handler()", "the correct place in the node tree. \"\"\" return isinstance(node,", "1 node.depth = self.nodeDepth node.parent = parent try: handler =", "def GLOBAL(self, node): \"\"\" Keep track of globals declarations. \"\"\"", "else: name = alias.asname or alias.name importation = Importation(name, node,", "in node.names: name = alias.asname or alias.name if node.module ==", "error raised if the checked code tries to # use", "import * is found def __repr__(self): scope_cls = self.__class__.__name__ return", "as used by the undefined in __all__ if scope.importStarred: for", "= node.lineno if hasattr(node, 'args'): node_lineno = max([node_lineno] + [arg.lineno", "if self.scope.isGenerator and self.scope.returnValue: self.report(messages.ReturnWithArgsInsideGenerator, self.scope.returnValue) self.deferAssignment(checkReturnWithArgumentInsideGenerator) self.popScope() self.deferFunction(runFunction) def", "are located on different forks of IF/TRY\"\"\" ancestor = self.getCommonAncestor(lnode,", "key_index in key_indices: key_node = node.keys[key_index] if isinstance(key, VariableKey): self.report(messages.MultiValueRepeatedKeyVariable,", "return self.getCommonAncestor(lnode, rnode.parent, stop) return self.getCommonAncestor(lnode.parent, rnode.parent, stop) def descendantOf(self,", "[] for scope in self.scopeStack[-1::-1]: for binding in scope.values(): if", "= {} self._deferredFunctions = [] self._deferredAssignments = [] self.deadScopes =", "hasattr(rnode, 'parent')): return None if lnode is rnode: return lnode", "Assignment(name, node) self.addBinding(node, binding) def handleNodeDelete(self, node): def on_conditional_branch(): \"\"\"", "not in n.orelse: return if isinstance(n, (ast.FunctionDef, ast.ClassDef)): break #", "def futuresAllowed(self): if not all(isinstance(scope, ModuleScope) for scope in self.scopeStack):", "within a doctest, # or in nested functions. if (self.withDoctest", "a Name node, but # a simple string, creates a", "hasn't already been defined in the current scope if isinstance(self.scope,", "# been accessed already in the current scope, and hasn't", "Check to see if there is any return statement with", "in the value of C{__all__} will not have an unused", "i_key == key] values = counter( convert_to_value(node.values[index]) for index in", "alias.name == '*': # Only Python 2, local import *", "submodule import assert '.' in name and (not source or", "__future__ import doctest import os import sys PY2 = sys.version_info", "source_statement(self): return 'from ' + self.fullName + ' import *'", "from_list.append(binding.fullName) # report * usage, with a list of possible", "example in examples: try: tree = compile(example.source, \"<doctest>\", \"exec\", ast.PyCF_ONLY_AST)", "messages if PY2: def getNodeType(node_class): # workaround str.upper() which is", "= WITH = WITHITEM = \\ ASYNCWITH = ASYNCWITHITEM =", "if isinstance(n, LOOP_TYPES): # Doesn't apply unless it's in the", "args.append(arg.id) addArgs(node.args.args) defaults = node.args.defaults else: for arg in node.args.args", "= Importation(name, node, alias.name) self.addBinding(node, importation) def IMPORTFROM(self, node): if", "value.used = self.scope[value.name].used self.scope[value.name] = value def getNodeHandler(self, node_class): try:", "node.args.args]) else: (docstring, node_lineno) = self.getDocstring(node.body[0]) examples = docstring and", "in the loop itself if n_child not in n.orelse: return", "LOOP_TYPES = (ast.While, ast.For, ast.AsyncFor) class _FieldsOrder(dict): \"\"\"Fix order of", "return self.getCommonAncestor(lnode.parent, rnode.parent, stop) def descendantOf(self, node, ancestors, stop): for", "self.addBinding(node, importation) def TRY(self, node): handler_names = [] # List", "the except: block. for scope in self.scopeStack[::-1]: if node.name in", "positives. \"\"\" def __init__(self, name, source): # A dot should", "# set to True when import * is found def", "Starred while True: node = node.parent if not hasattr(node, 'elts')", "after the starred expression, # which is impossible to test", "\\ self.descendantOf(rnode, items, ancestor): return True return False def addBinding(self,", "hash(self.name) class Importation(Definition): \"\"\" A binding created by an import", "\"\"\" nodeDepth = 0 offset = None traceTree = False", "\\ ASYNCWITH = ASYNCWITHITEM = RAISE = TRYFINALLY = EXEC", "last used. \"\"\" def __init__(self, name, source): self.name = name", "3.4 try: sys.pypy_version_info PYPY = True except AttributeError: PYPY =", "= node.parent if not hasattr(node, 'elts') and not hasattr(node, 'ctx'):", "self.handleNode(stmt, node) self.popScope() self.addBinding(node, ClassDefinition(node.name, node)) def AUGASSIGN(self, node): self.handleNodeLoad(node.target)", "a class scope can access the names # of the", "elif isinstance(node.ctx, (ast.Store, ast.AugStore)): self.handleNodeStore(node) elif isinstance(node.ctx, ast.Del): self.handleNodeDelete(node) else:", "results = {} for item in items: results[item] = results.get(item,", "in self.exceptHandlers[-1]: self.report(messages.UndefinedName, node, name) def handleNodeStore(self, node): name =", "is_py3_func: annotations.append(node.returns) if len(set(args)) < len(args): for (idx, arg) in", "# List the exception handlers for i, handler in enumerate(node.handlers):", "ImportationFrom(Importation): def __init__(self, name, source, module, real_name=None): self.module = module", "self.handleNode(node.target, node) def TUPLE(self, node): if not PY2 and isinstance(node.ctx,", "return node.id if hasattr(node, 'name'): # an ExceptHandler node return", "return handler def handleNodeLoad(self, node): name = getNodeName(node) if not", "node.module == '__future__': importation = FutureImportation(name, node, self.scope) if alias.name", "the cleanliness and sanity of Python code. @ivar _deferredFunctions: Tracking", "so that deferAssignment will fail # noisily if called after", "a Binding instance \"\"\" # assert value.source in (node, node.parent):", "already \"used\". node_value.used = (global_scope, node) for scope in self.scopeStack[global_scope_index", "compile(example.source, \"<doctest>\", \"exec\", ast.PyCF_ONLY_AST) except SyntaxError: e = sys.exc_info()[1] if", "assignments are allowed before a stared expression. There is #", "not have Counter in collections. \"\"\" results = {} for", "is self.scope: if (isinstance(parent_stmt, ast.comprehension) and not isinstance(self.getParent(existing.source), (ast.For, ast.comprehension))):", "hasattr(node, 'id'): # One of the many nodes with an", "recognized is one which takes the value of a literal", "[ModuleScope()] self.exceptHandlers = [()] self.root = tree self.handleChildren(tree) self.runDeferred(self._deferredFunctions) #", "n in enumerate(node.elts): if isinstance(n, ast.Starred): if has_starred: self.report(messages.TwoStarredExpressions, node)", "node) def checkUnusedAssignments(): \"\"\" Check to see if any assignments", "[arg.lineno for arg in node.args.args]) else: (docstring, node_lineno) = self.getDocstring(node.body[0])", "defined names which are not attributes of the builtins module,", "= ', '.join(sorted(from_list)) self.report(messages.ImportStarUsage, node, name, from_list) return if name", "without an 'as' clause, and the submodule is also imported.", "in node.args.args]) else: (docstring, node_lineno) = self.getDocstring(node.body[0]) examples = docstring", "' + self.name else: return self.fullName @property def source_statement(self): if", "tree self.handleChildren(tree) self.runDeferred(self._deferredFunctions) # Set _deferredFunctions to None so that", "if PY32: def checkReturnWithArgumentInsideGenerator(): \"\"\" Check to see if there", "self).__init__(name, source) class Scope(dict): importStarred = False # set to", "# become a globally defined name. See test_unused_global. self.messages =", "is skipped during the first iteration if in_generators is False", "not (isinstance(node, ast.ImportFrom) or self.isDocstring(node)): self.futuresAllowed = False self.nodeDepth +=", "we'll not complain. keys = [ convert_to_value(key) for key in", "self.scope: # then assume the rebound name is used as", "if lnode is rnode: return lnode if (lnode.depth > rnode.depth):", "node): if not PY2 and isinstance(node.ctx, ast.Store): # Python 3", "= False builtin_vars = dir(__import__('__builtin__' if PY2 else 'builtins')) try:", "not really ast.Store and shouldn't silence # UndefinedLocal warnings. self.handleNode(node.target,", "and generators before element fields = node_class._fields if 'iter' in", "for the assignments which have not been used. \"\"\" for", "# for each function or module scope above us for", "__future__.all_feature_names: self.report(messages.FutureFeatureNotDefined, node, alias.name) elif alias.name == '*': # Only", "VariableKey(object): \"\"\" A dictionary key which is a variable. @ivar", "root module may be used. This class is only used", "super(FunctionScope, self).__init__() # Simplify: manage the special locals as globals", "redefines(self, other): if isinstance(other, Importation): return self.fullName == other.fullName return", "underscore_in_builtins = '_' in self.builtIns if not underscore_in_builtins: self.builtIns.add('_') for", "= UADD = USUB = \\ EQ = NOTEQ =", "node.id, or node.name, or None if hasattr(node, 'id'): # One", "not isinstance(all_binding, ExportBinding): all_binding = None if all_binding: all_names =", "and not self.usesLocals and isinstance(binding, Assignment)): yield name, binding class", "statement.\"\"\" def __init__(self, name, source): super(StarImportation, self).__init__('*', source) # Each", "GLOBAL def GENERATOREXP(self, node): self.pushScope(GeneratorScope) self.handleChildren(node) self.popScope() LISTCOMP = handleChildren", "collections.Counter. Required as 2.6 does not have Counter in collections.", "assignment that can be recognized is one which takes the", "in scope.values(): if isinstance(binding, StarImportation): # mark '*' imports as", "checker uses this to keep track of which names have", "needs an as clause.\"\"\" return not self.fullName.split('.')[-1] == self.name @property", "handleNodeDelete(self, node): def on_conditional_branch(): \"\"\" Return `True` if node is", "else GENERATOREXP DICTCOMP = SETCOMP = GENERATOREXP def NAME(self, node):", "the except handlers and process the body self.exceptHandlers.append(handler_names) for child", "may not be the module name otherwise it will be", "['__file__', '__builtins__', 'WindowsError'] def getNodeName(node): # Returns node.id, or node.name,", "COMPREHENSION = KEYWORD = FORMATTEDVALUE = JOINEDSTR = handleChildren def", "dot should only appear in the name when it is", "# Python 2.5 to 3.4 try: sys.pypy_version_info PYPY = True", "bodies, which must be deferred because code later in the", "backslash doctest_lineno = node.lineno - node.s.count('\\n') - 1 return (node.s,", "and value.redefines(existing): existing.redefined.append(node) if value.name in self.scope: # then assume", "examined and report names in them which were imported but", "is not False: in_generators = isinstance(scope, GeneratorScope) # look in", "the docstring has backslash doctest_lineno = node.lineno - node.s.count('\\n') -", "In Python 3.7, docstrings no # longer have line numbers", "[ key for key, count in key_counts.items() if count >", "True except AttributeError: PYPY = False builtin_vars = dir(__import__('__builtin__' if", "binding created by a 'from x import *' statement.\"\"\" def", "__init__(self, tree, filename='(none)', builtins=None, withDoctest='PYFLAKES_DOCTEST' in os.environ): self._nodeHandlers = {}", "name in locals / function / globals scopes. if isinstance(node.ctx,", "'finalbody') and isinstance(node, ast.Continue): if n_child in n.finalbody: self.report(messages.ContinueInFinally, node)", "def isDocstring(self, node): \"\"\" Determine if the given node is", "FutureImportation(name, node, self.scope) if alias.name not in __future__.all_feature_names: self.report(messages.FutureFeatureNotDefined, node,", "scopeClass=FunctionScope): self.scopeStack.append(scopeClass()) def report(self, messageClass, *args, **kwargs): self.messages.append(messageClass(self.filename, *args, **kwargs))", "not False: in_generators = isinstance(scope, GeneratorScope) # look in the", "= getattr(node, 'parent', None) while current: if isinstance(current, (ast.If, ast.While,", "node_class._fields if 'iter' in fields: key_first = 'iter'.find elif 'generators'", "ast.ClassDef.decorator_list = () ast.FunctionDef.decorator_list = property(lambda s: s.decorators) from pyflakes", "True self.handleNode(node.value, node) AWAIT = YIELDFROM = YIELD def FUNCTIONDEF(self,", "FunctionScope) and name in self.scope.globals: self.scope.globals.remove(name) else: try: del self.scope[name]", "rnode are located on different forks of IF/TRY\"\"\" ancestor =", "return self.scope._futures_allowed @futuresAllowed.setter def futuresAllowed(self, value): assert value is False", "value.source in (node, node.parent): for scope in self.scopeStack[::-1]: if value.name", "tuple(convert_to_value(i) for i in item.elts) elif isinstance(item, ast.Num): return item.n", "become a globally defined name. See test_unused_global. self.messages = [", "removing the local name since it's being unbound # after", "node) else: # ast.Break self.report(messages.BreakOutsideLoop, node) BREAK = CONTINUE def", "self.fullName class SubmoduleImportation(Importation): \"\"\" A binding created by a submodule", "( node.value and hasattr(self.scope, 'returnValue') and not self.scope.returnValue ): self.scope.returnValue", "the module name otherwise it will be deemed imported self.name", "since it's being unbound # after leaving the except: block", "the given node is a docstring, as long as it", "the checked code tries to # use the name afterwards.", "% (self.__class__.__name__, self.name, self.source.lineno, id(self)) def redefines(self, other): return isinstance(other,", "will be treated as names for export and additional checking", "at 0x%x %s>' % (scope_cls, id(self), dict.__repr__(self)) class ClassScope(Scope): pass", "handler_names = [] # List the exception handlers for i,", "only present on some platforms. _MAGIC_GLOBALS = ['__file__', '__builtins__', 'WindowsError']", "return self.fullName == other.fullName return super(SubmoduleImportation, self).redefines(other) def __str__(self): return", "return node def getCommonAncestor(self, lnode, rnode, stop): if stop in", "scope): if '__all__' in scope and isinstance(source, ast.AugAssign): self.names =", "(isinstance(node, ast.Expr) and isinstance(node.value, ast.Str)) def getDocstring(self, node): if isinstance(node,", "enumerate(node.elts): if isinstance(n, ast.Starred): if has_starred: self.report(messages.TwoStarredExpressions, node) # The", "return self.name def __repr__(self): return '<%s object %r from line", "globals self.globals = self.alwaysUsed.copy() self.returnValue = None # First non-empty", "ast.Starred): if has_starred: self.report(messages.TwoStarredExpressions, node) # The SyntaxError doesn't distinguish", "the name of the exception, which is not a Name", "is checked with stricter rules. @ivar used: pair of (L{Scope},", "not self.usesLocals and isinstance(binding, Assignment)): yield name, binding class GeneratorScope(Scope):", "completion. This is used for handling function bodies, which must", "self.offset or (0, 0) self.pushScope(DoctestScope) underscore_in_builtins = '_' in self.builtIns", "ast.Num): return item.n elif isinstance(item, ast.Name): result = VariableKey(item=item) constants_lookup", "# Only for Python3 FunctionDefs is_py3_func = hasattr(node, 'returns') for", "# of the except: block. for scope in self.scopeStack[::-1]: if", "None: self.handleChildren(node) return # 3.x: the name of the exception,", "2.5 to 3.3 argannotation = arg_name + 'annotation' annotations.append(getattr(node.args, argannotation))", "full name with alias.\"\"\" if self.real_name != self.name: return self.fullName", "isinstance(source, ast.Import)) package_name = name.split('.')[0] super(SubmoduleImportation, self).__init__(package_name, source) self.fullName =", "self.builtIns if not underscore_in_builtins: self.builtIns.add('_') for example in examples: try:", "node): args = [] annotations = [] if PY2: def", "it's been removed already. Then do nothing. try: del self.scope[node.name]", "if isinstance(binding, StarImportation): # mark '*' imports as used for", "the list can be determined statically, they will be treated", "has backslash doctest_lineno = node.lineno - node.s.count('\\n') - 1 return", "are not attributes of the builtins module, or # are", "in all_names if not used: messg = messages.UnusedImport self.report(messg, value.source,", "name, source): self.name = name self.source = source self.used =", "ATTRIBUTE = SUBSCRIPT = \\ STARRED = NAMECONSTANT = handleChildren", "Binding(object): \"\"\" Represents the binding of a value to a", "value.source, str(value)) for node in value.redefined: if isinstance(self.getParent(node), ast.For): messg", "importStarred = None # try enclosing function scopes and global", "DIV = MOD = POW = LSHIFT = RSHIFT =", "a NameError handler? if 'NameError' not in self.exceptHandlers[-1]: self.report(messages.UndefinedName, node,", "__init__(self, name, source): # A dot should only appear in", "ClassDefinition(node.name, node)) def AUGASSIGN(self, node): self.handleNodeLoad(node.target) self.handleNode(node.value, node) self.handleNode(node.target, node)", "a submodule import assert '.' in name and (not source", "no more than 1<<8 # assignments are allowed before a", "the same, to avoid false positives. \"\"\" def __init__(self, name,", "return self.scope.isGenerator = True self.handleNode(node.value, node) AWAIT = YIELDFROM =", "Definition(Binding): \"\"\" A binding that defines a function or a", "used and used[0] is self.scope and name not in self.scope.globals:", "Check to see if any assignments have not been used.", "in self.scope: # for each function or module scope above", "\"\"\" # Locate the name in locals / function /", "is found def __repr__(self): scope_cls = self.__class__.__name__ return '<%s at", "is called, the scope at the time this is called", "if PY2: def getNodeType(node_class): # workaround str.upper() which is locale-dependent", "node.value: # If the assignment has value, handle the *value*", "called will be restored, however it will contain any new", "module ends with a ., avoid the ambiguous '..*' if", "binding a name with an explicit assignment. The checker will", "return constants_lookup.get( result.name, result, ) elif (not PY33) and isinstance(item,", "a value to a name. The checker uses this to", "'elts') and not hasattr(node, 'ctx'): return node def getCommonAncestor(self, lnode,", "callables which are deferred assignment checks. \"\"\" nodeDepth = 0", "is_py3_func = hasattr(node, 'returns') for arg_name in ('vararg', 'kwarg'): wildcard", "= MULT = DIV = MOD = POW = LSHIFT", "if it doesn't exist already. global_scope.setdefault(node_name, node_value) # Bind name", "see if any assignments have not been used. \"\"\" for", "this function. \"\"\" usesLocals = False alwaysUsed = set(['__tracebackhide__', '__traceback_info__',", "used. \"\"\" for name, binding in self.items(): if (not binding.used", "binding = Binding(name, node) elif name == '__all__' and isinstance(self.scope,", "Tuple, List or Starred while True: node = node.parent if", "isinstance(n, (ast.If, ast.TryFinally)): return [n.body] if isinstance(n, ast.TryExcept): return [n.body", "elif handler.type: handler_names.append(getNodeName(handler.type)) if handler.type is None and i <", "= DEL = AUGLOAD = AUGSTORE = PARAM = ignore", "filename if builtins: self.builtIns = self.builtIns.union(builtins) self.withDoctest = withDoctest self.scopeStack", "(self.module, self.name) class StarImportation(Importation): \"\"\"A binding created by a 'from", "(lnode.depth > rnode.depth): return self.getCommonAncestor(lnode.parent, rnode, stop) if (lnode.depth <", "scope for scope in self.scopeStack[-1::-1]: # only generators used in", "ends with a ., avoid the ambiguous '..*' if self.fullName.endswith('.'):", "scope in self.scopeStack[::-1]: if value.name in scope: break existing =", "# report * usage, with a list of possible sources", "return True def isDocstring(self, node): \"\"\" Determine if the given", "the scope and the node that this binding was last", "if this conditional branch is going to # be executed.", "apply unless it's in the loop itself if n_child not", "if child: self.handleNode(child, node) def runFunction(): self.pushScope() for name in", "= (node_offset[0] + node_lineno + example.lineno, node_offset[1] + example.indent +", "return if isinstance(node, ast.Continue): self.report(messages.ContinueOutsideLoop, node) else: # ast.Break self.report(messages.BreakOutsideLoop,", "EXCEPTHANDLER(self, node): if PY2 or node.name is None: self.handleChildren(node) return", "which are imported and not otherwise used but appear in", "__str__(self): return self.name def __repr__(self): return '<%s object %r from", "given node is a docstring, as long as it is", "scope. if self.scope is not global_scope: # One 'global' statement", "} return constants_lookup.get( result.name, result, ) elif (not PY33) and", "= 0 offset = None traceTree = False builtIns =", "elif used: continue else: messg = messages.RedefinedWhileUnused self.report(messg, node, value.name,", "messg = messages.ImportShadowedByLoopVar elif used: continue else: messg = messages.RedefinedWhileUnused", "name) def handleChildren(self, tree, omit=None): for node in iter_child_nodes(tree, omit=omit):", "is only bound within the scope # of the except:", "and self.name == other.name class Definition(Binding): \"\"\" A binding that", "`node` is the statement responsible for the change - `value`", "LOOP_TYPES = (ast.While, ast.For) else: LOOP_TYPES = (ast.While, ast.For, ast.AsyncFor)", "the undefined in __all__ if scope.importStarred: for binding in scope.values():", "current = getattr(node, 'parent', None) while current: if isinstance(current, (ast.If,", "\"\"\" def __init__(self, item): self.name = item.id def __eq__(self, compare):", "including its decorators, base classes, and the body of its", "given to the import statement, possibly including multiple dotted components.", "class Definition(Binding): \"\"\" A binding that defines a function or", "usesLocals = False alwaysUsed = set(['__tracebackhide__', '__traceback_info__', '__traceback_supplement__']) def __init__(self):", "report(self, messageClass, *args, **kwargs): self.messages.append(messageClass(self.filename, *args, **kwargs)) def getParent(self, node):", "this conditional branch is going to # be executed. return", "it is a submodule import assert '.' in name and", "\"\"\" for scope in self.deadScopes: # imports in classes are", "try: del self.scope[name] except KeyError: self.report(messages.UndefinedName, node, name) def handleChildren(self,", "# case for FunctionDefs for stmt in node.body: self.handleNode(stmt, node)", "ancestors, stop): for a in ancestors: if self.getCommonAncestor(node, a, stop):", "assignment. If the names in the list can be determined", "== key] values = counter( convert_to_value(node.values[index]) for index in key_indices", "unique name, and # may not be the module name", "# Detect a generator def unusedAssignments(self): \"\"\" Return a generator", "so we'll not complain. keys = [ convert_to_value(key) for key", "else: # Computed incorrectly if the docstring has backslash doctest_lineno", "= parent try: handler = self.getNodeHandler(node.__class__) handler(node) finally: self.nodeDepth -=", "= [] annotations = [] if PY2: def addArgs(arglist): for", "ast.Continue): if n_child in n.finalbody: self.report(messages.ContinueInFinally, node) return if isinstance(node,", "arguments, but these aren't dispatched through here raise RuntimeError(\"Got impossible", "implicitly imported, without an 'as' clause, and the submodule is", "e.offset += 1 position = (node_lineno + example.lineno + e.lineno,", "self.isLiteralTupleUnpacking(parent_stmt)): binding = Binding(name, node) elif name == '__all__' and", "allowed, and no more than 1<<8 # assignments are allowed", "first parent which is not Tuple, List or Starred while", "parent which is not Tuple, List or Starred while True:", "expression, # which is impossible to test due to memory", "self.handleNodeStore(node) self.handleChildren(node) if not is_name_previously_defined: # See discussion on https://github.com/PyCQA/pyflakes/pull/59", "key of a type that we cannot or do not", "in self.builtIns: return if importStarred: from_list = [] for scope", "self.fullName def __str__(self): \"\"\"Return import full name with alias.\"\"\" if", "a global or within a loop value.used = self.scope[value.name].used self.scope[value.name]", "node.args.args + node.args.kwonlyargs: args.append(arg.arg) annotations.append(arg.annotation) defaults = node.args.defaults + node.args.kw_defaults", "AUGASSIGN(self, node): self.handleNodeLoad(node.target) self.handleNode(node.value, node) self.handleNode(node.target, node) def TUPLE(self, node):", "# handle iter before target, and generators before element fields", "self.fullName.endswith('.'): return self.source_statement else: return self.name class FutureImportation(ImportationFrom): \"\"\" A", "node) # The SyntaxError doesn't distinguish two from more #", "set(['__tracebackhide__', '__traceback_info__', '__traceback_supplement__']) def __init__(self): super(FunctionScope, self).__init__() # Simplify: manage", "not restrict which attributes of the root module may be", "PYPY = True except AttributeError: PYPY = False builtin_vars =", "if isinstance(scope, ClassScope): continue all_binding = scope.get('__all__') if all_binding and", "NAME(self, node): \"\"\" Handle occurrence of Name (which can be", "import * is a SyntaxWarning if not PY2 and not", "as 2.6 does not have Counter in collections. \"\"\" results", "stop): return True return False def differentForks(self, lnode, rnode): \"\"\"True,", "builtIns.update(_customBuiltIns.split(',')) del _customBuiltIns def __init__(self, tree, filename='(none)', builtins=None, withDoctest='PYFLAKES_DOCTEST' in", "exist already. global_scope.setdefault(node_name, node_value) # Bind name to non-global scopes,", "type that we cannot or do not check for duplicates.", "for i, n in enumerate(node.elts): if isinstance(n, ast.Starred): if has_starred:", "'__future__': if not self.futuresAllowed: self.report(messages.LateFutureImport, node, [n.name for n in", "'import %s' % self.fullName def __str__(self): \"\"\"Return import full name", "for arg in node.args.args]) else: (docstring, node_lineno) = self.getDocstring(node.body[0]) examples", "for binding in scope.values(): if isinstance(binding, StarImportation): # mark '*'", "indicating the scope and the node that this binding was", "self.traceTree: print(' ' * self.nodeDepth + node.__class__.__name__) if self.futuresAllowed and", "def ASSERT(self, node): if isinstance(node.test, ast.Tuple) and node.test.elts != []:", "True star_loc = i if star_loc >= 1 << 8", "node, position) else: self.offset = (node_offset[0] + node_lineno + example.lineno,", "to be accessed. RedefinedWhileUnused is suppressed in `redefines` unless the", "node.name class Checker(object): \"\"\" I check the cleanliness and sanity", "< rnode.depth): return self.getCommonAncestor(lnode, rnode.parent, stop) return self.getCommonAncestor(lnode.parent, rnode.parent, stop)", "ASYNCWITH = ASYNCWITHITEM = RAISE = TRYFINALLY = EXEC =", "self.name = name self.source = source self.used = False def", "type nodes SLICE = EXTSLICE = INDEX = handleChildren #", "ignore # same for operators AND = OR = ADD", "a unique name, and # may not be the module", "self.popScope() self.addBinding(node, ClassDefinition(node.name, node)) def AUGASSIGN(self, node): self.handleNodeLoad(node.target) self.handleNode(node.value, node)", "star importation needs a unique name, and # may not", "in node.names: if '.' in alias.name and not alias.asname: importation", "of the root module may be used. This class is", "value is False if isinstance(self.scope, ModuleScope): self.scope._futures_allowed = False @property", "Assignment)): yield name, binding class GeneratorScope(Scope): pass class ModuleScope(Scope): \"\"\"Scope", "block and it's always unbound # if the except: block", "\"<doctest>\", \"exec\", ast.PyCF_ONLY_AST) except SyntaxError: e = sys.exc_info()[1] if PYPY:", "IndexError): # e.g. line 6 of the docstring for <string>", "return self.fullName class SubmoduleImportation(Importation): \"\"\" A binding created by a", "order of AST node fields.\"\"\" def _get_fields(self, node_class): # handle", "globals declarations. \"\"\" global_scope_index = 1 if self._in_doctest() else 0", "__str__(self): # When the module ends with a ., avoid", "argument. \"\"\" class Assignment(Binding): \"\"\" Represents binding a name with", "value.redefines(existing): existing.redefined.append(node) if value.name in self.scope: # then assume the", "1 if self._in_doctest() else 0 global_scope = self.scopeStack[global_scope_index] # Ignore", "Try/TryFinally difference in Python < and >= 3.3 if hasattr(n,", "__str__(self): \"\"\"Return import full name with alias.\"\"\" if self._has_alias(): return", "classes within classes are processed. if (self.withDoctest and not self._in_doctest()", "if isinstance(other, SubmoduleImportation): # See note in SubmoduleImportation about RedefinedWhileUnused", "is a copy of the scope stack at the time", "track of globals declarations. \"\"\" global_scope_index = 1 if self._in_doctest()", "module, alias.name) self.addBinding(node, importation) def TRY(self, node): handler_names = []", "deferred): \"\"\" Run the callables in C{deferred} using their associated", "never entered. This will cause an # \"undefined name\" error", "import %s' % (self.module, self.name) class StarImportation(Importation): \"\"\"A binding created", "be deemed imported self.name = name + '.*' self.fullName =", "args[:idx]: self.report(messages.DuplicateArgument, node, arg) for child in annotations + defaults:", "return (len(self.scopeStack) >= 2 and isinstance(self.scopeStack[1], DoctestScope)) @property def futuresAllowed(self):", "self.offset[1] if self.traceTree: print(' ' * self.nodeDepth + node.__class__.__name__) if", "self.builtIns.add('_') for example in examples: try: tree = compile(example.source, \"<doctest>\",", "avoid the ambiguous '..*' if self.fullName.endswith('.'): return self.source_statement else: return", "possibly including multiple dotted components. @type fullName: C{str} \"\"\" def", "FunctionScope) and isinstance(node.parent, ast.Call)): # we are doing locals() call", "# The SyntaxError doesn't distinguish two from more # than", "node, self.scope) if alias.name not in __future__.all_feature_names: self.report(messages.FutureFeatureNotDefined, node, alias.name)", "name is used as a global or within a loop", "name, source): # A dot should only appear in the", "scope[name].used if used and used[0] is self.scope and name not", "self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or self.isDocstring(node)): self.futuresAllowed = False", "fields: key_first = 'iter'.find elif 'generators' in fields: key_first =", "e = sys.exc_info()[1] if PYPY: e.offset += 1 position =", "a generator. \"\"\" if self.scope.isGenerator and self.scope.returnValue: self.report(messages.ReturnWithArgsInsideGenerator, self.scope.returnValue) self.deferAssignment(checkReturnWithArgumentInsideGenerator)", "that isn't used. Also, the checker does not consider assignments", "scope in self.scopeStack[-1::-1]: for binding in scope.values(): if isinstance(binding, StarImportation):", "__str__(self): \"\"\"Return import full name with alias.\"\"\" if self.real_name !=", "list are two-tuples. The first element is the callable passed", "through the deferred assignments. self._deferredAssignments = None del self.scopeStack[1:] self.popScope()", "attribute 'decorator_list' ast.ClassDef.decorator_list = () ast.FunctionDef.decorator_list = property(lambda s: s.decorators)", "not hasattr(node, 'ctx'): return node def getCommonAncestor(self, lnode, rnode, stop):", "if self._in_doctest() else 0 global_scope = self.scopeStack[global_scope_index] # Ignore 'global'", "of (ast.TryExcept + ast.TryFinally) if PY32: def getAlternatives(n): if isinstance(n,", "def _get_fields(self, node_class): # handle iter before target, and generators", "literal strings. For example:: __all__ = [\"foo\", \"bar\"] Names which", "None) if isinstance(field, ast.AST): yield field elif isinstance(field, list): for", "elif isinstance(item, ast.Num): return item.n elif isinstance(item, ast.Name): result =", "\"\"\" I represent a name scope for a function. @ivar", "not used: messg = messages.UnusedImport self.report(messg, value.source, str(value)) for node", "isLiteralTupleUnpacking(self, node): if isinstance(node, ast.Assign): for child in node.targets +", "MOD = POW = LSHIFT = RSHIFT = \\ BITOR", "= NOTEQ = LT = LTE = GT = GTE", "these aren't dispatched through here raise RuntimeError(\"Got impossible expression context:", "_has_alias(self): \"\"\"Return whether importation needs an as clause.\"\"\" return not", "+ defaults: if child: self.handleNode(child, node) def runFunction(): self.pushScope() for", "is a generator. \"\"\" if self.scope.isGenerator and self.scope.returnValue: self.report(messages.ReturnWithArgsInsideGenerator, self.scope.returnValue)", "and self.scope.returnValue: self.report(messages.ReturnWithArgsInsideGenerator, self.scope.returnValue) self.deferAssignment(checkReturnWithArgumentInsideGenerator) self.popScope() self.deferFunction(runFunction) def CLASSDEF(self, node):", "check the cleanliness and sanity of Python code. @ivar _deferredFunctions:", "isinstance(source.value, (ast.List, ast.Tuple)): for node in source.value.elts: if isinstance(node, ast.Str):", "< len(args): for (idx, arg) in enumerate(args): if arg in", "as %s' % (self.fullName, self.name) else: return 'import %s' %", "i_key in enumerate(keys) if i_key == key] values = counter(", "Python >= 3.3 uses ast.Try instead of (ast.TryExcept + ast.TryFinally)", "and not self.isLiteralTupleUnpacking(parent_stmt)): binding = Binding(name, node) elif name ==", "the body of its definition. Additionally, add its name to", "enumerate(node.handlers): if isinstance(handler.type, ast.Tuple): for exc_type in handler.type.elts: handler_names.append(getNodeName(exc_type)) elif", "if all_binding: all_names = set(all_binding.names) undefined = all_names.difference(scope) else: all_names", "\"\"\" # assert value.source in (node, node.parent): for scope in", "= node.args.defaults else: for arg in node.args.args + node.args.kwonlyargs: args.append(arg.arg)", "responsible for the change - `value` is the new value,", "% (self.fullName, self.name) else: return 'import %s' % self.fullName def", "removed already. Then do nothing. try: del self.scope[node.name] except KeyError:", "item in field: yield item def convert_to_value(item): if isinstance(item, ast.Str):", "annotations + defaults: if child: self.handleNode(child, node) def runFunction(): self.pushScope()", "name. The checker uses this to keep track of which", "__repr__(self): scope_cls = self.__class__.__name__ return '<%s at 0x%x %s>' %", "of its definition. Additionally, add its name to the current", "module may be used. This class is only used when", "in handler.type.elts: handler_names.append(getNodeName(exc_type)) elif handler.type: handler_names.append(getNodeName(handler.type)) if handler.type is None", "element fields = node_class._fields if 'iter' in fields: key_first =", "Scope(dict): importStarred = False # set to True when import", "and isinstance(parent_stmt, ast.For): self.report(messages.ImportShadowedByLoopVar, node, value.name, existing.source) elif scope is", "this binding was last used. \"\"\" def __init__(self, name, source):", "imported self.name = name + '.*' self.fullName = name @property", "and report names in them which were imported but unused.", "been defined in the current scope if isinstance(self.scope, FunctionScope) and", "= \\ STARRED = NAMECONSTANT = handleChildren NUM = STR", "GENERATOREXP DICTCOMP = SETCOMP = GENERATOREXP def NAME(self, node): \"\"\"", "not alias.asname: importation = SubmoduleImportation(alias.name, node) else: name = alias.asname", "other.name class Definition(Binding): \"\"\" A binding that defines a function", "ASYNCWITHITEM = RAISE = TRYFINALLY = EXEC = \\ EXPR", "(ast.List, ast.Tuple)): for node in source.value.elts: if isinstance(node, ast.Str): self.names.append(node.s)", "each function or module scope above us for scope in", "in values.items()): for key_index in key_indices: key_node = node.keys[key_index] if", "block. for scope in self.scopeStack[::-1]: if node.name in scope: is_name_previously_defined", "= ignore # same for operators AND = OR =", "raised if the checked code tries to # use the", "and additional checking applied to them. The only C{__all__} assignment", "name was defined in that scope, and the name has", "names have not. See L{Assignment} for a special type of", "= getNodeName(node) if not name: return in_generators = None importStarred", "values # If they have the same value it's not", "A dictionary key of a type that we cannot or", "for value in scope.values(): if isinstance(value, Importation): used = value.used", "= name def redefines(self, other): if isinstance(other, Importation): return self.fullName", "'value'.find return tuple(sorted(fields, key=key_first, reverse=True)) def __missing__(self, node_class): self[node_class] =", "runFunction(): self.pushScope() for name in args: self.addBinding(node, Argument(name, node)) if", "len(node.elts) - star_loc - 1 >= 1 << 24: self.report(messages.TooManyExpressionsInStarredAssignment,", "will be restored, however it will contain any new bindings", "of the docstring for <string> has inconsistent # leading whitespace:", "RedefinedWhileUnused is suppressed in `redefines` unless the submodule name is", "= node while hasattr(n, 'parent'): n, n_child = n.parent, n", "str(value)) for node in value.redefined: if isinstance(self.getParent(node), ast.For): messg =", "'builtins')) try: import ast except ImportError: # Python 2.5 import", "STARRED = NAMECONSTANT = handleChildren NUM = STR = BYTES", "within a loop value.used = self.scope[value.name].used self.scope[value.name] = value def", "code tries to # use the name afterwards. # #", "scope, offset in deferred: self.scopeStack = scope self.offset = offset", "if (lnode.depth < rnode.depth): return self.getCommonAncestor(lnode, rnode.parent, stop) return self.getCommonAncestor(lnode.parent,", "be # incorrect if there are empty lines between the", "rnode): \"\"\"True, if lnode and rnode are located on different", "isinstance(item, ast.Str): return item.s elif hasattr(ast, 'Bytes') and isinstance(item, ast.Bytes):", "= WITHITEM = \\ ASYNCWITH = ASYNCWITHITEM = RAISE =", "node) if node.value: # If the assignment has value, handle", "item): self.name = item.id def __eq__(self, compare): return ( compare.__class__", "as simple Bindings. \"\"\" class FunctionDefinition(Definition): pass class ClassDefinition(Definition): pass", "id(self), dict.__repr__(self)) class ClassScope(Scope): pass class FunctionScope(Scope): \"\"\" I represent", "% (self.module, self.real_name, self.name) else: return 'from %s import %s'", "self.name def __repr__(self): return '<%s object %r from line %r", "scope (not OK) n = node while hasattr(n, 'parent'): n,", "'__path__' and os.path.basename(self.filename) == '__init__.py': # the special name __path__", "'elts'): return False return True def isDocstring(self, node): \"\"\" Determine", "if node.module == '__future__': if not self.futuresAllowed: self.report(messages.LateFutureImport, node, [n.name", "not underscore_in_builtins: self.builtIns.remove('_') self.popScope() self.scopeStack = saved_stack def ignore(self, node):", "PY32: def getAlternatives(n): if isinstance(n, (ast.If, ast.TryFinally)): return [n.body] if", "@type fullName: C{str} \"\"\" def __init__(self, name, source, full_name=None): self.fullName", "in self.items(): if (not binding.used and name not in self.globals", "elif (not PY33) and isinstance(item, ast.NameConstant): # None, True, False", "if self.traceTree: print(' ' * self.nodeDepth + 'end ' +", "value of C{__all__} will not have an unused import warning", "module to be accessed. RedefinedWhileUnused is suppressed in `redefines` unless", "and the submodule is also imported. Python does not restrict", "node): if isinstance(node, ast.Assign): for child in node.targets + [node.value]:", "it's probably a mistake self.report(messages.UndefinedLocal, scope[name].used[1], name, scope[name].source) break parent_stmt", "the function and the docstring. node_lineno = node.lineno if hasattr(node,", "or node.name, or None if hasattr(node, 'id'): # One of", "is # also a limit of 1<<24 expressions after the", "# assignments are allowed before a stared expression. There is", "importation = SubmoduleImportation(alias.name, node) else: name = alias.asname or alias.name", "= module + '.' + self.real_name super(ImportationFrom, self).__init__(name, source, full_name)", "clause.\"\"\" return not self.fullName.split('.')[-1] == self.name @property def source_statement(self): \"\"\"Generate", "def LAMBDA(self, node): args = [] annotations = [] if", "node that this binding was last used. \"\"\" def __init__(self,", "'WindowsError'] def getNodeName(node): # Returns node.id, or node.name, or None", "its definition. Additionally, add its name to the current scope.", "if isinstance(self.getParent(node), ast.For): messg = messages.ImportShadowedByLoopVar elif used: continue else:", "FunctionDefinition(Definition): pass class ClassDefinition(Definition): pass class ExportBinding(Binding): \"\"\" A binding", "is None: self.handleChildren(node) return # 3.x: the name of the", "None so that deferFunction will fail # noisily if called", "only in packages return # protected with a NameError handler?", "access.) \"\"\" # Locate the name in locals / function", "self.report(messages.BreakOutsideLoop, node) BREAK = CONTINUE def RETURN(self, node): if isinstance(self.scope,", "bindings added to it. \"\"\" self._deferredFunctions.append((callable, self.scopeStack[:], self.offset)) def deferAssignment(self,", "def CONTINUE(self, node): # Walk the tree up until we", "class Checker(object): \"\"\" I check the cleanliness and sanity of", "but the function is a generator. \"\"\" if self.scope.isGenerator and", "else: self.futuresAllowed = False module = ('.' * node.level) +", "to 3.3 PY34 = sys.version_info < (3, 5) # Python", "rules. @ivar used: pair of (L{Scope}, node) indicating the scope", "as names for export and additional checking applied to them.", "if in_generators is False and isinstance(scope, ClassScope): continue try: scope[name].used", "\"\"\" Simplest required implementation of collections.Counter. Required as 2.6 does", "self.report(messages.LateFutureImport, node, [n.name for n in node.names]) else: self.futuresAllowed =", "' + self.fullName class ImportationFrom(Importation): def __init__(self, name, source, module,", "is a docstring, as long as it is at the", "that aren't used. for value in scope.values(): if isinstance(value, Importation):", "not isinstance(scope, (FunctionScope, ModuleScope)): continue # if the name was", "Only one starred expression is allowed, and no more than", "not in self.scope: # for each function or module scope", "self.name = item.id def __eq__(self, compare): return ( compare.__class__ ==", "we've run through the deferred functions. self._deferredFunctions = None self.runDeferred(self._deferredAssignments)", "attributes of the builtins module, or # are only present", "node) AWAIT = YIELDFROM = YIELD def FUNCTIONDEF(self, node): for", "defaults: if child: self.handleNode(child, node) def runFunction(): self.pushScope() for name", "if isinstance(node.body, list): # case for FunctionDefs for stmt in", "%s' % (self.module, self.real_name, self.name) else: return 'from %s import", "def pushScope(self, scopeClass=FunctionScope): self.scopeStack.append(scopeClass()) def report(self, messageClass, *args, **kwargs): self.messages.append(messageClass(self.filename,", "not otherwise used but appear in the value of C{__all__}", "self.futuresAllowed = False module = ('.' * node.level) + (node.module", "\"\"\" Keep track of globals declarations. \"\"\" global_scope_index = 1", "binding of a value to a name. The checker uses", "Names declared 'global' in this function. \"\"\" usesLocals = False", "restrictions, but we # add it here anyway has_starred =", "self.report(messages.ImportStarUsage, node, name, from_list) return if name == '__path__' and", "if isinstance(item, ast.Str): return item.s elif hasattr(ast, 'Bytes') and isinstance(item,", "child in node.targets + [node.value]: if not hasattr(child, 'elts'): return", "PY33) and isinstance(item, ast.NameConstant): # None, True, False are nameconstants", "self.exceptHandlers[-1]: self.report(messages.UndefinedName, node, name) def handleNodeStore(self, node): name = getNodeName(node)", "top module scope (not OK) n = node while hasattr(n,", "as long as it is at the correct place in", "= n.parent, n if isinstance(n, LOOP_TYPES): # Doesn't apply unless", "the names in the list can be determined statically, they", "complain. keys = [ convert_to_value(key) for key in node.keys ]", "in annotations + defaults: if child: self.handleNode(child, node) def runFunction():", "to memory restrictions, but we # add it here anyway", "'import %s as %s' % (self.fullName, self.name) else: return 'import", "binding.used = all_binding # Look for imported names that aren't", "statement, possibly including multiple dotted components. @type fullName: C{str} \"\"\"", "value.name, existing.source) elif not existing.used and value.redefines(existing): self.report(messages.RedefinedWhileUnused, node, value.name,", "of the function and the docstring. node_lineno = node.lineno if", "% self.fullName def __str__(self): \"\"\"Return import full name with alias.\"\"\"", "= saved_stack def ignore(self, node): pass # \"stmt\" type nodes", "arg_name in ('vararg', 'kwarg'): wildcard = getattr(node.args, arg_name) if not", "import.\"\"\" if self._has_alias(): return 'import %s as %s' % (self.fullName,", "= list(scope['__all__'].names) else: self.names = [] if isinstance(source.value, (ast.List, ast.Tuple)):", "be accessed. RedefinedWhileUnused is suppressed in `redefines` unless the submodule", "FLOORDIV = INVERT = NOT = UADD = USUB =", "in parts: if self.descendantOf(lnode, items, ancestor) ^ \\ self.descendantOf(rnode, items,", "(not PY33) and isinstance(item, ast.NameConstant): # None, True, False are", "ISNOT = IN = NOTIN = \\ MATMULT = ignore", "it doesn't exist already. global_scope.setdefault(node_name, node_value) # Bind name to", "# Complain if there are duplicate keys with different values", "class VariableKey(object): \"\"\" A dictionary key which is a variable.", "list used by L{deferFunction}. Elements of the list are two-tuples.", "PARAM = ignore # same for operators AND = OR", "if isinstance(key, VariableKey): self.report(messages.MultiValueRepeatedKeyVariable, key_node, key.name) else: self.report( messages.MultiValueRepeatedKeyLiteral, key_node,", "messages already reported for this name. # TODO: if the", "if node.name in scope: is_name_previously_defined = True break else: is_name_previously_defined", "node, value.name, value.source) def pushScope(self, scopeClass=FunctionScope): self.scopeStack.append(scopeClass()) def report(self, messageClass,", "0x%x %s>' % (scope_cls, id(self), dict.__repr__(self)) class ClassScope(Scope): pass class", "# same for operators AND = OR = ADD =", "fail # noisily if called after we've run through the", "declared global used = name in scope and scope[name].used if", "class ImportationFrom(Importation): def __init__(self, name, source, module, real_name=None): self.module =", "keys with different values # If they have the same", "not be the module name otherwise it will be deemed", "(ValueError, IndexError): # e.g. line 6 of the docstring for", "real_name=None): self.module = module self.real_name = real_name or name if", "self.report(messages.DefaultExceptNotLast, handler) # Memorize the except handlers and process the", "handleChildren if PY2 else GENERATOREXP DICTCOMP = SETCOMP = GENERATOREXP", "A dictionary key which is a variable. @ivar item: The", "self.scope.returnValue = node.value self.handleNode(node.value, node) def YIELD(self, node): if isinstance(self.scope,", "def isLiteralTupleUnpacking(self, node): if isinstance(node, ast.Assign): for child in node.targets", "'global' statement can bind multiple (comma-delimited) names. for node_name in", "The checker uses this to keep track of which names", "= name.split('.')[0] super(SubmoduleImportation, self).__init__(package_name, source) self.fullName = name def redefines(self,", "List the exception handlers for i, handler in enumerate(node.handlers): if", "' as ' + self.name else: return self.fullName @property def", "= getattr(current, 'parent', None) return False name = getNodeName(node) if", "Walk the tree up until we see a loop (OK),", "scope stack at the time L{deferFunction} was called. @ivar _deferredAssignments:", "= [] super(Importation, self).__init__(name, source) def redefines(self, other): if isinstance(other,", "withDoctest='PYFLAKES_DOCTEST' in os.environ): self._nodeHandlers = {} self._deferredFunctions = [] self._deferredAssignments", "same value it's not going to cause potentially # unexpected", "for node in value.redefined: if isinstance(self.getParent(node), ast.For): messg = messages.ImportShadowedByLoopVar", "# also a limit of 1<<24 expressions after the starred", "in enumerate(node.elts): if isinstance(n, ast.Starred): if has_starred: self.report(messages.TwoStarredExpressions, node) #", "this scope, it does not # become a globally defined", "starred expression, # which is impossible to test due to", "afterwards. # # Unless it's been removed already. Then do", "or not (hasattr(lnode, 'parent') and hasattr(rnode, 'parent')): return None if", "locale-dependent return str(unicode(node_class.__name__).upper()) else: def getNodeType(node_class): return node_class.__name__.upper() # Python", "= False # Detect a generator def unusedAssignments(self): \"\"\" Return", "tree = compile(example.source, \"<doctest>\", \"exec\", ast.PyCF_ONLY_AST) except SyntaxError: e =", "(self.__class__.__name__, self.name, self.source.lineno, id(self)) def redefines(self, other): return isinstance(other, Definition)", "node fields.\"\"\" def _get_fields(self, node_class): # handle iter before target,", "and isinstance(node, ast.Continue): if n_child in n.finalbody: self.report(messages.ContinueInFinally, node) return", "handleChildren PASS = ignore # \"expr\" type nodes BOOLOP =", "ClassDefinition(Definition): pass class ExportBinding(Binding): \"\"\" A binding created by an", "any Assignment that isn't used. Also, the checker does not", "module, or # are only present on some platforms. _MAGIC_GLOBALS", "FutureImportation(ImportationFrom): \"\"\" A binding created by a from `__future__` import", "not existing.used and value.redefines(existing): self.report(messages.RedefinedWhileUnused, node, value.name, existing.source) elif isinstance(existing,", "The SyntaxError doesn't distinguish two from more # than two.", "= \\ ASYNCWITH = ASYNCWITHITEM = RAISE = TRYFINALLY =", "node): \"\"\" Check names used in a class definition, including", "except ImportError: # Python 2.5 import _ast as ast if", "scope. When `callable` is called, the scope at the time", "' * self.nodeDepth + 'end ' + node.__class__.__name__) _getDoctestExamples =", "return False return True def isDocstring(self, node): \"\"\" Determine if", "second element is a copy of the scope stack at", "= False @property def scope(self): return self.scopeStack[-1] def popScope(self): self.deadScopes.append(self.scopeStack.pop())", "else: all_names = undefined = [] if undefined: if not", "os.path.basename(self.filename) != '__init__.py': # Look for possible mistakes in the", "'__traceback_supplement__']) def __init__(self): super(FunctionScope, self).__init__() # Simplify: manage the special", "wildcard: continue args.append(wildcard if PY33 else wildcard.arg) if is_py3_func: if", "other.name def _has_alias(self): \"\"\"Return whether importation needs an as clause.\"\"\"", "self.handleNode(node.target, node) self.handleNode(node.annotation, node) if node.value: # If the assignment", "alias.name) self.addBinding(node, importation) def TRY(self, node): handler_names = [] #", "or name self.redefined = [] super(Importation, self).__init__(name, source) def redefines(self,", "A binding created by a submodule import statement. A submodule", "results def iter_child_nodes(node, omit=None, _fields_order=_FieldsOrder()): \"\"\" Yield all direct child", "the ambiguous '..*' if self.fullName.endswith('.'): return self.source_statement else: return self.name", "is None and i < len(node.handlers) - 1: self.report(messages.DefaultExceptNotLast, handler)", "return hash(self.name) class Importation(Definition): \"\"\" A binding created by an", "the except: block is never entered. This will cause an", "defined in that scope, and the name has # been", "isinstance(item, ast.NameConstant): # None, True, False are nameconstants in python3,", "CALL = REPR = ATTRIBUTE = SUBSCRIPT = \\ STARRED", "GeneratorScope) # look in the built-ins if name in self.builtIns:", "= ['__file__', '__builtins__', 'WindowsError'] def getNodeName(node): # Returns node.id, or", "self._deferredFunctions = [] self._deferredAssignments = [] self.deadScopes = [] self.messages", "compare): return ( compare.__class__ == self.__class__ and compare.name == self.name", "Run the callables in C{deferred} using their associated scope stack.", "be called just before completion. This is used for handling", "the name was defined in that scope, and the name", "in node.names: node_value = Assignment(node_name, node) # Remove UndefinedName messages", "handling function bodies, which must be deferred because code later", "break # Handle Try/TryFinally difference in Python < and >=", "doctest does not process doctest within a doctest, # or", "for stmt in node.body: self.handleNode(stmt, node) self.popScope() self.addBinding(node, ClassDefinition(node.name, node))", "and which names have not. See L{Assignment} for a special", "if isinstance(current, (ast.If, ast.While, ast.IfExp)): return True current = getattr(current,", "item: The variable AST object. \"\"\" def __init__(self, item): self.name", "assignments have not been used. \"\"\" for name, binding in", "%s' % (self.module, self.name) class StarImportation(Importation): \"\"\"A binding created by", "or in nested functions. if (self.withDoctest and not self._in_doctest() and", "fullName: C{str} \"\"\" def __init__(self, name, source, full_name=None): self.fullName =", "of the list are two-tuples. The first element is the", "self.scope.globals: # then it's probably a mistake self.report(messages.UndefinedLocal, scope[name].used[1], name,", "not isinstance(node, ast.Str): return (None, None) if PYPY: doctest_lineno =", "duplicate_keys: key_indices = [i for i, i_key in enumerate(keys) if", "node_offset = self.offset or (0, 0) self.pushScope(DoctestScope) underscore_in_builtins = '_'", "value): \"\"\" Called when a binding is altered. - `node`", "self.scopeStack[-1] def popScope(self): self.deadScopes.append(self.scopeStack.pop()) def checkDeadScopes(self): \"\"\" Look at scopes", "IMPORT(self, node): for alias in node.names: if '.' in alias.name", "+ node.args.kwonlyargs: args.append(arg.arg) annotations.append(arg.annotation) defaults = node.args.defaults + node.args.kw_defaults #", "\"\"\" Yield all direct child nodes of *node*, that is,", "node): self.handleNodeLoad(node.target) self.handleNode(node.value, node) self.handleNode(node.target, node) def TUPLE(self, node): if", "'*' as used by the undefined in __all__ if scope.importStarred:", "STORE = DEL = AUGLOAD = AUGSTORE = PARAM =", "argannotation = arg_name + 'annotation' annotations.append(getattr(node.args, argannotation)) else: # Python", "NameError handler? if 'NameError' not in self.exceptHandlers[-1]: self.report(messages.UndefinedName, node, name)", "and hasn't # been declared global used = name in", "in global scope. if self.scope is not global_scope: # One", "isinstance(node, ast.Continue): self.report(messages.ContinueOutsideLoop, node) else: # ast.Break self.report(messages.BreakOutsideLoop, node) BREAK", "star_loc >= 1 << 8 or len(node.elts) - star_loc -", "the root module is implicitly imported, without an 'as' clause,", "not in self.exceptHandlers[-1]: self.report(messages.UndefinedName, node, name) def handleNodeStore(self, node): name", "central Checker class. Also, it models the Bindings and Scopes.", "2.5 to 3.3 PY34 = sys.version_info < (3, 5) #", "of a literal list containing literal strings. For example:: __all__", "isinstance(current, (ast.If, ast.While, ast.IfExp)): return True current = getattr(current, 'parent',", "(node_offset[0] + node_lineno + example.lineno, node_offset[1] + example.indent + 4)", "return True current = getattr(current, 'parent', None) return False name", "and Scopes. \"\"\" import __future__ import doctest import os import", "scope and scope[name].used if used and used[0] is self.scope and", "Python does not restrict which attributes of the root module", "# case for Lambdas self.handleNode(node.body, node) def checkUnusedAssignments(): \"\"\" Check", "(not OK) n = node while hasattr(n, 'parent'): n, n_child", "class FutureImportation(ImportationFrom): \"\"\" A binding created by a from `__future__`", "Similar to C{_deferredFunctions}, but for callables which are deferred assignment", "ModuleScope): binding = ExportBinding(name, node.parent, self.scope) else: binding = Assignment(name,", "key=key_first, reverse=True)) def __missing__(self, node_class): self[node_class] = fields = self._get_fields(node_class)", "self.real_name != self.name: return 'from %s import %s as %s'", "a function or class # definition (not OK), for 'continue',", "arg in arglist: if isinstance(arg, ast.Tuple): addArgs(arg.elts) else: args.append(arg.id) addArgs(node.args.args)", "after leaving the except: block and it's always unbound #", "omit=omit): self.handleNode(node, tree) def isLiteralTupleUnpacking(self, node): if isinstance(node, ast.Assign): for", "for hdl in n.handlers] if PY34: LOOP_TYPES = (ast.While, ast.For)", "node, [n.name for n in node.names]) else: self.futuresAllowed = False", "offset = None traceTree = False builtIns = set(builtin_vars).union(_MAGIC_GLOBALS) _customBuiltIns", "the other nodes: \"except:\", \"else:\", \"finally:\" self.handleChildren(node, omit='body') TRYEXCEPT =", "# if the name was defined in that scope, and", "None traceTree = False builtIns = set(builtin_vars).union(_MAGIC_GLOBALS) _customBuiltIns = os.environ.get('PYFLAKES_BUILTINS')", "class Scope(dict): importStarred = False # set to True when", "node.test.elts != []: self.report(messages.AssertTuple, node) self.handleChildren(node) def GLOBAL(self, node): \"\"\"", "during the first iteration if in_generators is False and isinstance(scope,", "%s as %s' % (self.module, self.real_name, self.name) else: return 'from", "def __init__(self, name, source): super(StarImportation, self).__init__('*', source) # Each star", "and the docstring. node_lineno = node.lineno if hasattr(node, 'args'): node_lineno", "doctest.DocTestParser().get_examples def handleDoctests(self, node): try: if hasattr(node, 'docstring'): docstring =", "fullName: The complete name given to the import statement, possibly", "callable): \"\"\" Schedule a function handler to be called just", "3) # Python 2.5 to 3.2 PY33 = sys.version_info <", "be treated as names for export and additional checking applied", "node): \"\"\" Handle occurrence of Name (which can be a", "the except: block and it's always unbound # if the", "False star_loc = -1 for i, n in enumerate(node.elts): if", "return if isinstance(self.scope, FunctionScope) and name in self.scope.globals: self.scope.globals.remove(name) else:", "else: binding = Assignment(name, node) self.addBinding(node, binding) def handleNodeDelete(self, node):", "= [ m for m in self.messages if not isinstance(m,", "'.*' self.fullName = name @property def source_statement(self): return 'from '", "else: # Python >= 3.4 annotations.append(wildcard.annotation) if is_py3_func: annotations.append(node.returns) if", "loop value.used = self.scope[value.name].used self.scope[value.name] = value def getNodeHandler(self, node_class):", "case for FunctionDefs for stmt in node.body: self.handleNode(stmt, node) else:", "root module is implicitly imported, without an 'as' clause, and", "isinstance(self.getParent(node), ast.For): messg = messages.ImportShadowedByLoopVar elif used: continue else: messg", "and not isinstance(self.scope, ModuleScope): self.report(messages.ImportStarNotPermitted, node, module) continue self.scope.importStarred =", "all_names if not used: messg = messages.UnusedImport self.report(messg, value.source, str(value))", "sanity of Python code. @ivar _deferredFunctions: Tracking list used by", "mark all import '*' as used by the undefined in", "Return a generator for the assignments which have not been", "scope['__all__'].source, name) # mark all import '*' as used by", "or # the top module scope (not OK) n =", "was called. @ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for callables", "isinstance(node, ast.Expr): node = node.value if not isinstance(node, ast.Str): return", "self.report(messages.ContinueInFinally, node) return if isinstance(node, ast.Continue): self.report(messages.ContinueOutsideLoop, node) else: #", ">= 3.4 annotations.append(wildcard.annotation) if is_py3_func: annotations.append(node.returns) if len(set(args)) < len(args):", "be used. This class is only used when the submodule", "have been bound and which names have not. See L{Assignment}", "binding was last used. \"\"\" def __init__(self, name, source): self.name", "2 and isinstance(self.scopeStack[1], DoctestScope)) @property def futuresAllowed(self): if not all(isinstance(scope,", "def __str__(self): \"\"\"Return import full name with alias.\"\"\" if self.real_name", "\"\"\" self._deferredFunctions.append((callable, self.scopeStack[:], self.offset)) def deferAssignment(self, callable): \"\"\" Schedule an", "statement. @ivar fullName: The complete name given to the import", "SLICE = EXTSLICE = INDEX = handleChildren # expression contexts", "__init__(self, name, source): super(StarImportation, self).__init__('*', source) # Each star importation", "+ node.__class__.__name__) _getDoctestExamples = doctest.DocTestParser().get_examples def handleDoctests(self, node): try: if", "Bind name to non-global scopes, but as already \"used\". node_value.used", "finally: self.nodeDepth -= 1 if self.traceTree: print(' ' * self.nodeDepth", "multiple (comma-delimited) names. for node_name in node.names: node_value = Assignment(node_name,", "annotations = [] if PY2: def addArgs(arglist): for arg in", "self.__class__.__name__ return '<%s at 0x%x %s>' % (scope_cls, id(self), dict.__repr__(self))", "handler.type: handler_names.append(getNodeName(handler.type)) if handler.type is None and i < len(node.handlers)", "(node, node.parent): for scope in self.scopeStack[::-1]: if value.name in scope:", "element is a copy of the scope stack at the", "# \"stmt\" type nodes DELETE = PRINT = FOR =", "'__future__': importation = FutureImportation(name, node, self.scope) if alias.name not in", "except handlers and process the body self.exceptHandlers.append(handler_names) for child in", "not scope.importStarred and \\ os.path.basename(self.filename) != '__init__.py': # Look for", "self._deferredFunctions = None self.runDeferred(self._deferredAssignments) # Set _deferredAssignments to None so", ") elif (not PY33) and isinstance(item, ast.NameConstant): # None, True,", "= arg_name + 'annotation' annotations.append(getattr(node.args, argannotation)) else: # Python >=", "None so that deferAssignment will fail # noisily if called", "handleChildren # expression contexts are node instances too, though being", "IS = ISNOT = IN = NOTIN = \\ MATMULT", "self.handleChildren(node) self.popScope() LISTCOMP = handleChildren if PY2 else GENERATOREXP DICTCOMP", "and isinstance(scope, ClassScope): continue try: scope[name].used = (self.scope, node) except", "it's being unbound # after leaving the except: block and", "multiple dotted components. @type fullName: C{str} \"\"\" def __init__(self, name,", "function handlers. \"\"\" self._deferredAssignments.append((callable, self.scopeStack[:], self.offset)) def runDeferred(self, deferred): \"\"\"", "(L{Scope}, node) indicating the scope and the node that this", "node) # Remove UndefinedName messages already reported for this name.", "Detect a generator def unusedAssignments(self): \"\"\" Return a generator for", "be a Param context -- this only happens for names", "in enumerate(args): if arg in args[:idx]: self.report(messages.DuplicateArgument, node, arg) for", "else: return self.fullName class SubmoduleImportation(Importation): \"\"\" A binding created by", "warning reported for them. \"\"\" def __init__(self, name, source, scope):", "= [] self._deferredAssignments = [] self.deadScopes = [] self.messages =", "tree, omit=None): for node in iter_child_nodes(tree, omit=omit): self.handleNode(node, tree) def", "handler = getattr(self, nodeType) return handler def handleNodeLoad(self, node): name", "str(unicode(node_class.__name__).upper()) else: def getNodeType(node_class): return node_class.__name__.upper() # Python >= 3.3", "= OR = ADD = SUB = MULT = DIV", "result, ) elif (not PY33) and isinstance(item, ast.NameConstant): # None,", "# e.g. line 6 of the docstring for <string> has", "if lnode and rnode are located on different forks of", "getDocstring(self, node): if isinstance(node, ast.Expr): node = node.value if not", "the export list for name in undefined: self.report(messages.UndefinedExport, scope['__all__'].source, name)", "to non-global scopes, but as already \"used\". node_value.used = (global_scope,", "not PY2 and not isinstance(self.scope, ModuleScope): self.report(messages.ImportStarNotPermitted, node, module) continue", "+ node_lineno + example.lineno, node_offset[1] + example.indent + 4) self.handleChildren(tree)", "self.report(messages.UnusedVariable, binding.source, name) self.deferAssignment(checkUnusedAssignments) if PY32: def checkReturnWithArgumentInsideGenerator(): \"\"\" Check", "node, value): \"\"\" Called when a binding is altered. -", "many nodes with an id return node.id if hasattr(node, 'name'):", "= [()] self.root = tree self.handleChildren(tree) self.runDeferred(self._deferredFunctions) # Set _deferredFunctions", "alwaysUsed = set(['__tracebackhide__', '__traceback_info__', '__traceback_supplement__']) def __init__(self): super(FunctionScope, self).__init__() #", "explicit assignment. The checker will raise warnings for any Assignment", "# or in nested functions. if (self.withDoctest and not self._in_doctest()", "if the global is not used in this scope, it", "= Assignment(node_name, node) # Remove UndefinedName messages already reported for", "): self.scope.returnValue = node.value self.handleNode(node.value, node) def YIELD(self, node): if", "in the file might modify the global scope. When `callable`", "imported and not otherwise used but appear in the value", "target, and generators before element fields = node_class._fields if 'iter'", "Schedule an assignment handler to be called just after deferred", "= BYTES = ELLIPSIS = ignore # \"slice\" type nodes", "self.deferFunction(runFunction) def CLASSDEF(self, node): \"\"\" Check names used in a", "scope): super(FutureImportation, self).__init__(name, source, '__future__') self.used = (scope, source) class", "= BITAND = FLOORDIV = INVERT = NOT = UADD", "in n.finalbody: self.report(messages.ContinueInFinally, node) return if isinstance(node, ast.Continue): self.report(messages.ContinueOutsideLoop, node)", "ModuleScope)): self.report(messages.ReturnOutsideFunction, node) return if ( node.value and hasattr(self.scope, 'returnValue')", "= self.getParent(value.source) if isinstance(existing, Importation) and isinstance(parent_stmt, ast.For): self.report(messages.ImportShadowedByLoopVar, node,", "key.name) else: self.report( messages.MultiValueRepeatedKeyLiteral, key_node, key, ) self.handleChildren(node) def ASSERT(self,", "= getNodeType(node_class) self._nodeHandlers[node_class] = handler = getattr(self, nodeType) return handler", "for key_index in key_indices: key_node = node.keys[key_index] if isinstance(key, VariableKey):", "a name with an explicit assignment. The checker will raise", "deferred function handlers. \"\"\" self._deferredAssignments.append((callable, self.scopeStack[:], self.offset)) def runDeferred(self, deferred):", "if isinstance(n, ast.TryExcept): return [n.body + n.orelse] + [[hdl] for", "for key in duplicate_keys: key_indices = [i for i, i_key", "+= self.offset[1] if self.traceTree: print(' ' * self.nodeDepth + node.__class__.__name__)", "'__future__') self.used = (scope, source) class Argument(Binding): \"\"\" Represents binding", "name, source, scope): super(FutureImportation, self).__init__(name, source, '__future__') self.used = (scope,", "the special name __path__ is valid only in packages return", "global scope if it doesn't exist already. global_scope.setdefault(node_name, node_value) #", "# must be a Param context -- this only happens", "ANNASSIGN(self, node): if node.value: # Only bind the *targets* if", "used. \"\"\" for name, binding in self.scope.unusedAssignments(): self.report(messages.UnusedVariable, binding.source, name)", "node) from_list.append(binding.fullName) # report * usage, with a list of", "Argument(Binding): \"\"\" Represents binding a name as an argument. \"\"\"", "name in self.builtIns: return if importStarred: from_list = [] for", "deferred: self.scopeStack = scope self.offset = offset handler() def _in_doctest(self):", "special locals as globals self.globals = self.alwaysUsed.copy() self.returnValue = None", "dispatched through here raise RuntimeError(\"Got impossible expression context: %r\" %", "is, all fields that are nodes and all items of", "^ \\ self.descendantOf(rnode, items, ancestor): return True return False def", "name to global scope if it doesn't exist already. global_scope.setdefault(node_name,", "_MAGIC_GLOBALS = ['__file__', '__builtins__', 'WindowsError'] def getNodeName(node): # Returns node.id,", "(ast.Load, ast.AugLoad)): self.handleNodeLoad(node) if (node.id == 'locals' and isinstance(self.scope, FunctionScope)", "return UnhandledKeyType() class Binding(object): \"\"\" Represents the binding of a", "if PY2 else 'builtins')) try: import ast except ImportError: #", "\"\"\" global_scope_index = 1 if self._in_doctest() else 0 global_scope =", "globals scopes. if isinstance(node.ctx, (ast.Load, ast.AugLoad)): self.handleNodeLoad(node) if (node.id ==", "if stop in (lnode, rnode) or not (hasattr(lnode, 'parent') and", "through here raise RuntimeError(\"Got impossible expression context: %r\" % (node.ctx,))", "_getDoctestExamples = doctest.DocTestParser().get_examples def handleDoctests(self, node): try: if hasattr(node, 'docstring'):", "def ANNASSIGN(self, node): if node.value: # Only bind the *targets*", "super(Importation, self).__init__(name, source) def redefines(self, other): if isinstance(other, SubmoduleImportation): #", "in scope and scope[name].used if used and used[0] is self.scope", "_FieldsOrder(dict): \"\"\"Fix order of AST node fields.\"\"\" def _get_fields(self, node_class):", "does not process doctest within a doctest, # or in", "full_name=None): self.fullName = full_name or name self.redefined = [] super(Importation,", "import assert '.' in name and (not source or isinstance(source,", "# be executed. return if isinstance(self.scope, FunctionScope) and name in", "see if there is any return statement with arguments but", "True current = getattr(current, 'parent', None) return False name =", "isinstance(scope, GeneratorScope) # look in the built-ins if name in", "up until we see a loop (OK), a function or", "TUPLE(self, node): if not PY2 and isinstance(node.ctx, ast.Store): # Python", "rnode: return lnode if (lnode.depth > rnode.depth): return self.getCommonAncestor(lnode.parent, rnode,", "them. This will be # incorrect if there are empty", "lnode and rnode are located on different forks of IF/TRY\"\"\"", "return str(unicode(node_class.__name__).upper()) else: def getNodeType(node_class): return node_class.__name__.upper() # Python >=", "for a function. @ivar globals: Names declared 'global' in this", "elif scope is self.scope: if (isinstance(parent_stmt, ast.comprehension) and not isinstance(self.getParent(existing.source),", ">= 1 << 8 or len(node.elts) - star_loc - 1", "value.name, value.source) def pushScope(self, scopeClass=FunctionScope): self.scopeStack.append(scopeClass()) def report(self, messageClass, *args,", "= INVERT = NOT = UADD = USUB = \\", "== 'locals' and isinstance(self.scope, FunctionScope) and isinstance(node.parent, ast.Call)): # we", "Counter in collections. \"\"\" results = {} for item in", "def scope(self): return self.scopeStack[-1] def popScope(self): self.deadScopes.append(self.scopeStack.pop()) def checkDeadScopes(self): \"\"\"", "position = (node_lineno + example.lineno + e.lineno, example.indent + 4", "m in self.messages if not isinstance(m, messages.UndefinedName) or m.message_args[0] !=", "ast.AugLoad)): self.handleNodeLoad(node) if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and", "(scope, source) class Argument(Binding): \"\"\" Represents binding a name as", "scope: is_name_previously_defined = True break else: is_name_previously_defined = False self.handleNodeStore(node)", "handles this case by registering the root module name in", "ASYNCFUNCTIONDEF = FUNCTIONDEF def LAMBDA(self, node): args = [] annotations", "if PY2 else GENERATOREXP DICTCOMP = SETCOMP = GENERATOREXP def", "'generators' in fields: key_first = 'generators'.find else: key_first = 'value'.find", "self.handleChildren(tree) self.runDeferred(self._deferredFunctions) # Set _deferredFunctions to None so that deferFunction", "= WHILE = IF = WITH = WITHITEM = \\", "self.addBinding(node, Argument(name, node)) if isinstance(node.body, list): # case for FunctionDefs", "statement. A submodule import is a special case where the", "[] self._deferredAssignments = [] self.deadScopes = [] self.messages = []", "scope at the time this is called will be restored,", "IMPORTFROM(self, node): if node.module == '__future__': if not self.futuresAllowed: self.report(messages.LateFutureImport,", "if the except: block is never entered. This will cause", "and isinstance(source, ast.AugAssign): self.names = list(scope['__all__'].names) else: self.names = []", "scope is self.scope: if (isinstance(parent_stmt, ast.comprehension) and not isinstance(self.getParent(existing.source), (ast.For,", "if arg in args[:idx]: self.report(messages.DuplicateArgument, node, arg) for child in", "the module ends with a ., avoid the ambiguous '..*'", "in node.keys ] key_counts = counter(keys) duplicate_keys = [ key", "expression. There is # also a limit of 1<<24 expressions", "'annotation' annotations.append(getattr(node.args, argannotation)) else: # Python >= 3.4 annotations.append(wildcard.annotation) if", "and (not source or isinstance(source, ast.Import)) package_name = name.split('.')[0] super(SubmoduleImportation,", "# Python 2.5 import _ast as ast if 'decorator_list' not", "by a 'from x import *' statement.\"\"\" def __init__(self, name,", "return 'from ' + self.fullName + ' import *' def", "isinstance(key, VariableKey): self.report(messages.MultiValueRepeatedKeyVariable, key_node, key.name) else: self.report( messages.MultiValueRepeatedKeyLiteral, key_node, key,", "isinstance(self.scope, (ClassScope, ModuleScope)): self.report(messages.ReturnOutsideFunction, node) return if ( node.value and", "all_names = undefined = [] if undefined: if not scope.importStarred", "Python >= 3.4 annotations.append(wildcard.annotation) if is_py3_func: annotations.append(node.returns) if len(set(args)) <", "self.name else: return self.fullName class SubmoduleImportation(Importation): \"\"\" A binding created", "= Binding(name, node) elif name == '__all__' and isinstance(self.scope, ModuleScope):", "stop in (lnode, rnode) or not (hasattr(lnode, 'parent') and hasattr(rnode,", "if isinstance(node.ctx, (ast.Load, ast.AugLoad)): self.handleNodeLoad(node) if (node.id == 'locals' and", "nodes with an id return node.id if hasattr(node, 'name'): #", "'decorator_list' ast.ClassDef.decorator_list = () ast.FunctionDef.decorator_list = property(lambda s: s.decorators) from", "not PY2: for keywordNode in node.keywords: self.handleNode(keywordNode, node) self.pushScope(ClassScope) #", "# Set _deferredAssignments to None so that deferAssignment will fail", "scope self.offset = offset handler() def _in_doctest(self): return (len(self.scopeStack) >=", "being constants LOAD = STORE = DEL = AUGLOAD =", "if isinstance(self.scope, (ClassScope, ModuleScope)): self.report(messages.ReturnOutsideFunction, node) return if ( node.value", "local that is only bound within the scope # of", "ModuleScope(Scope): \"\"\"Scope for a module.\"\"\" _futures_allowed = True class DoctestScope(ModuleScope):", "and used[0] is self.scope and name not in self.scope.globals: #", "# Python 3 advanced tuple unpacking: a, *b, c =", "not in self.globals and not self.usesLocals and isinstance(binding, Assignment)): yield", "if 'iter' in fields: key_first = 'iter'.find elif 'generators' in", "scope.get(value.name) if existing and not self.differentForks(node, existing.source): parent_stmt = self.getParent(value.source)", "add its name to the current scope. \"\"\" for deco", "at 0x%x>' % (self.__class__.__name__, self.name, self.source.lineno, id(self)) def redefines(self, other):", "if parts: for items in parts: if self.descendantOf(lnode, items, ancestor)", "pass class ModuleScope(Scope): \"\"\"Scope for a module.\"\"\" _futures_allowed = True", "IN = NOTIN = \\ MATMULT = ignore # additional", "self.fullName = name def redefines(self, other): if isinstance(other, Importation): return", "list): # case for FunctionDefs for stmt in node.body: self.handleNode(stmt,", "a doctest # classes within classes are processed. if (self.withDoctest", "doctest # classes within classes are processed. if (self.withDoctest and", "shouldn't silence # UndefinedLocal warnings. self.handleNode(node.target, node) self.handleNode(node.annotation, node) if", "continue field = getattr(node, name, None) if isinstance(field, ast.AST): yield", "., avoid the ambiguous '..*' if self.fullName.endswith('.'): return self.source_statement else:", "alias.asname: importation = SubmoduleImportation(alias.name, node) else: name = alias.asname or", "def __init__(self, name, source, module, real_name=None): self.module = module self.real_name", "== other.name class Definition(Binding): \"\"\" A binding that defines a", "UnhandledKeyType() class Binding(object): \"\"\" Represents the binding of a value", "numbers associated with them. This will be # incorrect if", "ast.Tuple): addArgs(arg.elts) else: args.append(arg.id) addArgs(node.args.args) defaults = node.args.defaults else: for", "name: return in_generators = None importStarred = None # try", "in the built-ins if name in self.builtIns: return if importStarred:", "self.name ) def __hash__(self): return hash(self.name) class Importation(Definition): \"\"\" A", "guess. In Python 3.7, docstrings no # longer have line", "a, *b, c = d. # Only one starred expression", "import messages if PY2: def getNodeType(node_class): # workaround str.upper() which", "if (node.id == 'locals' and isinstance(self.scope, FunctionScope) and isinstance(node.parent, ast.Call)):", "node) self.handleNode(node.annotation, node) if node.value: # If the assignment has", "which have not been used. \"\"\" for name, binding in", "_deferredAssignments: Similar to C{_deferredFunctions}, but for callables which are deferred", "source, scope): super(FutureImportation, self).__init__(name, source, '__future__') self.used = (scope, source)", "names # of the class. this is skipped during the", "DEL = AUGLOAD = AUGSTORE = PARAM = ignore #", "name: return if on_conditional_branch(): # We cannot predict if this", "to test due to memory restrictions, but we # add", "def EXCEPTHANDLER(self, node): if PY2 or node.name is None: self.handleChildren(node)", "def getNodeHandler(self, node_class): try: return self._nodeHandlers[node_class] except KeyError: nodeType =", "assert '.' in name and (not source or isinstance(source, ast.Import))", "\"\"\" A binding created by an C{__all__} assignment. If the", "ancestors: if self.getCommonAncestor(node, a, stop): return True return False def", "node.__class__.__name__) if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or self.isDocstring(node)): self.futuresAllowed", "file might modify the global scope. When `callable` is called,", "examples = docstring and self._getDoctestExamples(docstring) except (ValueError, IndexError): # e.g.", "is valid only in packages return # protected with a", "be recognized is one which takes the value of a", "node.keys ] key_counts = counter(keys) duplicate_keys = [ key for", "self.report(messages.ImportStarNotPermitted, node, module) continue self.scope.importStarred = True self.report(messages.ImportStarUsed, node, module)", "for item in field: yield item def convert_to_value(item): if isinstance(item,", "... return if not examples: return # Place doctest in", "StarImportation(Importation): \"\"\"A binding created by a 'from x import *'", "= [] self.deadScopes = [] self.messages = [] self.filename =", "node) return if ( node.value and hasattr(self.scope, 'returnValue') and not", "sys.version_info < (3, 3) # Python 2.5 to 3.2 PY33", "IF = WITH = WITHITEM = \\ ASYNCWITH = ASYNCWITHITEM", "self.handleNode(child, node) self.exceptHandlers.pop() # Process the other nodes: \"except:\", \"else:\",", "node_value.used = (global_scope, node) for scope in self.scopeStack[global_scope_index + 1:]:", "if PY33 else wildcard.arg) if is_py3_func: if PY33: # Python", "= (self.scope, node) from_list.append(binding.fullName) # report * usage, with a", "the root module may be used. This class is only", "self.builtIns = self.builtIns.union(builtins) self.withDoctest = withDoctest self.scopeStack = [ModuleScope()] self.exceptHandlers", "Remove UndefinedName messages already reported for this name. # TODO:", "us for scope in self.scopeStack[:-1]: if not isinstance(scope, (FunctionScope, ModuleScope)):", "not have an unused import warning reported for them. \"\"\"", "I check the cleanliness and sanity of Python code. @ivar", "return super(SubmoduleImportation, self).redefines(other) def __str__(self): return self.fullName @property def source_statement(self):", "self.handleNode(node.value, node) AWAIT = YIELDFROM = YIELD def FUNCTIONDEF(self, node):", "node, module) continue self.scope.importStarred = True self.report(messages.ImportStarUsed, node, module) importation", "without an 'as' clause. pyflakes handles this case by registering", "on some platforms. _MAGIC_GLOBALS = ['__file__', '__builtins__', 'WindowsError'] def getNodeName(node):", "assignments which have not been used. \"\"\" for name, binding", "by an C{__all__} assignment. If the names in the list", "global or within a loop value.used = self.scope[value.name].used self.scope[value.name] =", "when a binding is altered. - `node` is the statement", "https://github.com/PyCQA/pyflakes/pull/59 # We're removing the local name since it's being", "%s import %s' % (self.module, self.name) class StarImportation(Importation): \"\"\"A binding", "binding that defines a function or a class. \"\"\" class", "self).__init__(name, source, full_name) def __str__(self): \"\"\"Return import full name with", "a binding is altered. - `node` is the statement responsible", "deferred because code later in the file might modify the", "if not PY2 and isinstance(node.ctx, ast.Store): # Python 3 advanced", "False return self.scope._futures_allowed @futuresAllowed.setter def futuresAllowed(self, value): assert value is", "C{__all__} will not have an unused import warning reported for", "scope can access the names # of the class. this", "importation = StarImportation(module, node) else: importation = ImportationFrom(name, node, module,", "value. # Otherwise it's not really ast.Store and shouldn't silence", "except KeyError: self.report(messages.UndefinedName, node, name) def handleChildren(self, tree, omit=None): for", "= dir(__import__('__builtin__' if PY2 else 'builtins')) try: import ast except", "an as clause.\"\"\" return not self.fullName.split('.')[-1] == self.name @property def", "scope in self.scopeStack[:-1]: if not isinstance(scope, (FunctionScope, ModuleScope)): continue #", "isinstance(n, ast.Starred): if has_starred: self.report(messages.TwoStarredExpressions, node) # The SyntaxError doesn't", "continue else: messg = messages.RedefinedWhileUnused self.report(messg, node, value.name, value.source) def", "*node*, that is, all fields that are nodes and all", "KeyError: pass else: return importStarred = importStarred or scope.importStarred if", "nodes and all items of fields that are lists of", "or do not check for duplicates. \"\"\" class VariableKey(object): \"\"\"", "hasattr(ast, 'Bytes') and isinstance(item, ast.Bytes): return item.s elif isinstance(item, ast.Tuple):", "def source_statement(self): if self.real_name != self.name: return 'from %s import", "def __init__(self, name, source, scope): super(FutureImportation, self).__init__(name, source, '__future__') self.used", "'<%s at 0x%x %s>' % (scope_cls, id(self), dict.__repr__(self)) class ClassScope(Scope):", "in ancestors: if self.getCommonAncestor(node, a, stop): return True return False", "ast.Break self.report(messages.BreakOutsideLoop, node) BREAK = CONTINUE def RETURN(self, node): if", "self.handleNode(node.value, node) def YIELD(self, node): if isinstance(self.scope, (ClassScope, ModuleScope)): self.report(messages.YieldOutsideFunction,", "node.lineno - 1 else: # Computed incorrectly if the docstring", "not a Name node, but # a simple string, creates", "self.handleNode(child, node) def runFunction(): self.pushScope() for name in args: self.addBinding(node,", "the node tree. \"\"\" return isinstance(node, ast.Str) or (isinstance(node, ast.Expr)", "the many nodes with an id return node.id if hasattr(node,", "if isinstance(node, ast.Assign): for child in node.targets + [node.value]: if", "'from x import *' statement.\"\"\" def __init__(self, name, source): super(StarImportation,", "'.' in alias.name and not alias.asname: importation = SubmoduleImportation(alias.name, node)", "def IMPORT(self, node): for alias in node.names: if '.' in", "module + self.real_name else: full_name = module + '.' +", "module = ('.' * node.level) + (node.module or '') for", "if not wildcard: continue args.append(wildcard if PY33 else wildcard.arg) if", "treated as names for export and additional checking applied to", "= False self.nodeDepth += 1 node.depth = self.nodeDepth node.parent =", "for handler, scope, offset in deferred: self.scopeStack = scope self.offset", "to L{deferFunction}. The second element is a copy of the", "messages.RedefinedWhileUnused self.report(messg, node, value.name, value.source) def pushScope(self, scopeClass=FunctionScope): self.scopeStack.append(scopeClass()) def", "TRY(self, node): handler_names = [] # List the exception handlers", "= GLOBAL def GENERATOREXP(self, node): self.pushScope(GeneratorScope) self.handleChildren(node) self.popScope() LISTCOMP =", "for names in function # arguments, but these aren't dispatched", "rnode.parent, stop) return self.getCommonAncestor(lnode.parent, rnode.parent, stop) def descendantOf(self, node, ancestors,", "a doctest, # or in nested functions. if (self.withDoctest and", "and not alias.asname: importation = SubmoduleImportation(alias.name, node) else: name =", "root module to be accessed. RedefinedWhileUnused is suppressed in `redefines`", "usage, with a list of possible sources from_list = ',", "scopes and global scope for scope in self.scopeStack[-1::-1]: # only", "ast.FunctionDef.decorator_list = property(lambda s: s.decorators) from pyflakes import messages if", "(FunctionScope, ModuleScope)): continue # if the name was defined in", "node in iter_child_nodes(tree, omit=omit): self.handleNode(node, tree) def isLiteralTupleUnpacking(self, node): if", "definition (not OK), for 'continue', a finally block (not OK),", "for arg_name in ('vararg', 'kwarg'): wildcard = getattr(node.args, arg_name) if", "str.upper() which is locale-dependent return str(unicode(node_class.__name__).upper()) else: def getNodeType(node_class): return", "self.scopeStack[1:] self.popScope() self.checkDeadScopes() def deferFunction(self, callable): \"\"\" Schedule a function", "components. @type fullName: C{str} \"\"\" def __init__(self, name, source, full_name=None):", "from more # than two. break has_starred = True star_loc", "for scope in self.scopeStack[:-1]: if not isinstance(scope, (FunctionScope, ModuleScope)): continue", "global_scope: # One 'global' statement can bind multiple (comma-delimited) names.", "class SubmoduleImportation(Importation): \"\"\" A binding created by a submodule import", "clause, and the submodule is also imported. Python does not", "hasattr(node, 'elts') and not hasattr(node, 'ctx'): return node def getCommonAncestor(self,", "ast.Store): # Python 3 advanced tuple unpacking: a, *b, c", "def checkDeadScopes(self): \"\"\" Look at scopes which have been fully", "a name. The checker uses this to keep track of", "literal list containing literal strings. For example:: __all__ = [\"foo\",", "key_counts.items() if count > 1 ] for key in duplicate_keys:", "def __repr__(self): scope_cls = self.__class__.__name__ return '<%s at 0x%x %s>'", "node_class): self[node_class] = fields = self._get_fields(node_class) return fields def counter(items):", "name = getNodeName(node) if not name: return # if the", "of the scope stack at the time L{deferFunction} was called.", "self._deferredAssignments = None del self.scopeStack[1:] self.popScope() self.checkDeadScopes() def deferFunction(self, callable):", "# Globally defined names which are not attributes of the", "in self.deadScopes: # imports in classes are public members if", "self.scope.usesLocals = True elif isinstance(node.ctx, (ast.Store, ast.AugStore)): self.handleNodeStore(node) elif isinstance(node.ctx,", "ast.Call)): # we are doing locals() call in current scope", "in key_counts.items() if count > 1 ] for key in", "names used in a class definition, including its decorators, base", "os.environ): self._nodeHandlers = {} self._deferredFunctions = [] self._deferredAssignments = []", "+ 'annotation' annotations.append(getattr(node.args, argannotation)) else: # Python >= 3.4 annotations.append(wildcard.annotation)", "self.returnValue = None # First non-empty return self.isGenerator = False", "self.scopeStack[:-1]: if not isinstance(scope, (FunctionScope, ModuleScope)): continue # if the", "0)) self.report(messages.DoctestSyntaxError, node, position) else: self.offset = (node_offset[0] + node_lineno", "scope in self.deadScopes: # imports in classes are public members", "len(set(args)) < len(args): for (idx, arg) in enumerate(args): if arg", "rebound name is used as a global or within a", "import sys PY2 = sys.version_info < (3, 0) PY32 =", "FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) for stmt in node.body: self.handleNode(stmt, node) self.popScope()", "a function or a class. \"\"\" class UnhandledKeyType(object): \"\"\" A", "If the names in the list can be determined statically,", "is just a reasonable guess. In Python 3.7, docstrings no", "to a name. The checker uses this to keep track", "with alias.\"\"\" if self.real_name != self.name: return self.fullName + '", "and i < len(node.handlers) - 1: self.report(messages.DefaultExceptNotLast, handler) # Memorize", "BITOR = BITXOR = BITAND = FLOORDIV = INVERT =", "if called after we've run through the deferred functions. self._deferredFunctions", "for i, handler in enumerate(node.handlers): if isinstance(handler.type, ast.Tuple): for exc_type", "stmt in node.body: self.handleNode(stmt, node) self.popScope() self.addBinding(node, ClassDefinition(node.name, node)) def", "set(all_binding.names) undefined = all_names.difference(scope) else: all_names = undefined = []", "RSHIFT = \\ BITOR = BITXOR = BITAND = FLOORDIV", "self.futuresAllowed: self.report(messages.LateFutureImport, node, [n.name for n in node.names]) else: self.futuresAllowed", "is one which takes the value of a literal list", "if not all(isinstance(scope, ModuleScope) for scope in self.scopeStack): return False", "in node.body: self.handleNode(child, node) self.exceptHandlers.pop() # Process the other nodes:", "the assignments which have not been used. \"\"\" for name,", "isinstance(node, ast.Str): self.names.append(node.s) super(ExportBinding, self).__init__(name, source) class Scope(dict): importStarred =", "class is only used when the submodule import is without", "self.messages.append(messageClass(self.filename, *args, **kwargs)) def getParent(self, node): # Lookup the first", "isinstance(self.scope, (ClassScope, ModuleScope)): self.report(messages.YieldOutsideFunction, node) return self.scope.isGenerator = True self.handleNode(node.value,", "def checkUnusedAssignments(): \"\"\" Check to see if any assignments have", "yield name, binding class GeneratorScope(Scope): pass class ModuleScope(Scope): \"\"\"Scope for", "This will cause an # \"undefined name\" error raised if", "handler) # Memorize the except handlers and process the body", "not consider assignments in tuple/list unpacking to be Assignments, rather", "node.id if hasattr(node, 'name'): # an ExceptHandler node return node.name", "them which were imported but unused. \"\"\" for scope in", "redefines(self, other): if isinstance(other, SubmoduleImportation): # See note in SubmoduleImportation", "node.parent and not self.isLiteralTupleUnpacking(parent_stmt)): binding = Binding(name, node) elif name", "= PARAM = ignore # same for operators AND =", "by L{deferFunction}. Elements of the list are two-tuples. The first", "node) for scope in self.scopeStack[global_scope_index + 1:]: scope[node_name] = node_value", "2.5 import _ast as ast if 'decorator_list' not in ast.ClassDef._fields:", "i, handler in enumerate(node.handlers): if isinstance(handler.type, ast.Tuple): for exc_type in", "alias.\"\"\" if self._has_alias(): return self.fullName + ' as ' +", "example.lineno + e.lineno, example.indent + 4 + (e.offset or 0))", "OK) n = node while hasattr(n, 'parent'): n, n_child =", "import statement. A submodule import is a special case where", "been accessed already in the current scope, and hasn't #", "= [] # List the exception handlers for i, handler", "node) self.handleChildren(node) LIST = TUPLE def IMPORT(self, node): for alias", "'..*' if self.fullName.endswith('.'): return self.source_statement else: return self.name class FutureImportation(ImportationFrom):", "unused import warning reported for them. \"\"\" def __init__(self, name,", "the current scope. \"\"\" for deco in node.decorator_list: self.handleNode(deco, node)", "self.module = module self.real_name = real_name or name if module.endswith('.'):", "I represent a name scope for a function. @ivar globals:", "= name in scope and scope[name].used if used and used[0]", "ast except ImportError: # Python 2.5 import _ast as ast", "redefines(self, other): return isinstance(other, Definition) and self.name == other.name class", "self.handleChildren(tree) self.offset = node_offset if not underscore_in_builtins: self.builtIns.remove('_') self.popScope() self.scopeStack", "callable): \"\"\" Schedule an assignment handler to be called just", "self.addBinding(node, ClassDefinition(node.name, node)) def AUGASSIGN(self, node): self.handleNodeLoad(node.target) self.handleNode(node.value, node) self.handleNode(node.target,", "for stmt in node.body: self.handleNode(stmt, node) else: # case for", "(ast.Store, ast.AugStore)): self.handleNodeStore(node) elif isinstance(node.ctx, ast.Del): self.handleNodeDelete(node) else: # must", "id return node.id if hasattr(node, 'name'): # an ExceptHandler node", "binding = ExportBinding(name, node.parent, self.scope) else: binding = Assignment(name, node)", "we see a loop (OK), a function or class #", "lnode, rnode): \"\"\"True, if lnode and rnode are located on", "if isinstance(arg, ast.Tuple): addArgs(arg.elts) else: args.append(arg.id) addArgs(node.args.args) defaults = node.args.defaults", "None) is not None: node.lineno += self.offset[0] node.col_offset += self.offset[1]", "RETURN(self, node): if isinstance(self.scope, (ClassScope, ModuleScope)): self.report(messages.ReturnOutsideFunction, node) return if", "not isinstance(self.scope, ModuleScope): self.report(messages.ImportStarNotPermitted, node, module) continue self.scope.importStarred = True", "of the exception, which is not a Name node, but", "lnode if (lnode.depth > rnode.depth): return self.getCommonAncestor(lnode.parent, rnode, stop) if", "YIELD(self, node): if isinstance(self.scope, (ClassScope, ModuleScope)): self.report(messages.YieldOutsideFunction, node) return self.scope.isGenerator", "# \"expr\" type nodes BOOLOP = BINOP = UNARYOP =", "Ignore 'global' statement in global scope. if self.scope is not", "def convert_to_value(item): if isinstance(item, ast.Str): return item.s elif hasattr(ast, 'Bytes')", "self.source_statement else: return self.name class FutureImportation(ImportationFrom): \"\"\" A binding created", "key, count in key_counts.items() if count > 1 ] for", "undefined = all_names.difference(scope) else: all_names = undefined = [] if", "if value.name in scope: break existing = scope.get(value.name) if existing", "class # definition (not OK), for 'continue', a finally block", "in os.environ): self._nodeHandlers = {} self._deferredFunctions = [] self._deferredAssignments =", "node, parent): if node is None: return if self.offset and", "function / globals scopes. if isinstance(node.ctx, (ast.Load, ast.AugLoad)): self.handleNodeLoad(node) if", "assert value.source in (node, node.parent): for scope in self.scopeStack[::-1]: if", "in 2 return item.value else: return UnhandledKeyType() class Binding(object): \"\"\"", "= SUBSCRIPT = \\ STARRED = NAMECONSTANT = handleChildren NUM", "also a limit of 1<<24 expressions after the starred expression,", "the import statement, possibly including multiple dotted components. @type fullName:", "\"\"\" import __future__ import doctest import os import sys PY2", "for child in annotations + defaults: if child: self.handleNode(child, node)", "case where the root module is implicitly imported, without an", "if PYPY: doctest_lineno = node.lineno - 1 else: # Computed", "must be deferred because code later in the file might", "if not is_name_previously_defined: # See discussion on https://github.com/PyCQA/pyflakes/pull/59 # We're", "= sys.version_info < (3, 3) # Python 2.5 to 3.2", "not underscore_in_builtins: self.builtIns.add('_') for example in examples: try: tree =", "PY32 = sys.version_info < (3, 3) # Python 2.5 to", "to None so that deferFunction will fail # noisily if", "Python 2, local import * is a SyntaxWarning if not", "name self.source = source self.used = False def __str__(self): return", "node): def on_conditional_branch(): \"\"\" Return `True` if node is part", "and not isinstance(all_binding, ExportBinding): all_binding = None if all_binding: all_names", "classes are public members if isinstance(scope, ClassScope): continue all_binding =", "AUGLOAD = AUGSTORE = PARAM = ignore # same for", "for n in node.names]) else: self.futuresAllowed = False module =", "self.fullName @property def source_statement(self): if self.real_name != self.name: return 'from", "False # Detect a generator def unusedAssignments(self): \"\"\" Return a", "= handleChildren NUM = STR = BYTES = ELLIPSIS =", "with a NameError handler? if 'NameError' not in self.exceptHandlers[-1]: self.report(messages.UndefinedName,", "assignment has a value. # Otherwise it's not really ast.Store", "not self.isLiteralTupleUnpacking(parent_stmt)): binding = Binding(name, node) elif name == '__all__'", "isinstance(self.scope, ModuleScope): binding = ExportBinding(name, node.parent, self.scope) else: binding =", "ast.Tuple) and node.test.elts != []: self.report(messages.AssertTuple, node) self.handleChildren(node) def GLOBAL(self,", "in module scope saved_stack = self.scopeStack self.scopeStack = [self.scopeStack[0]] node_offset", "%s' % self.fullName def __str__(self): \"\"\"Return import full name with", "by a submodule import statement. A submodule import is a", "in node.body: self.handleNode(stmt, node) self.popScope() self.addBinding(node, ClassDefinition(node.name, node)) def AUGASSIGN(self,", "n_child not in n.orelse: return if isinstance(n, (ast.FunctionDef, ast.ClassDef)): break", "return results def iter_child_nodes(node, omit=None, _fields_order=_FieldsOrder()): \"\"\" Yield all direct", "a value. # Otherwise it's not really ast.Store and shouldn't", "L{Assignment} for a special type of binding that is checked", "full_name) def __str__(self): \"\"\"Return import full name with alias.\"\"\" if", "is altered. - `node` is the statement responsible for the", "of Name (which can be a load/store/delete access.) \"\"\" #", "the top module scope (not OK) n = node while", "not self.scope.returnValue ): self.scope.returnValue = node.value self.handleNode(node.value, node) def YIELD(self,", "def source_statement(self): return 'from ' + self.fullName + ' import", "addArgs(arg.elts) else: args.append(arg.id) addArgs(node.args.args) defaults = node.args.defaults else: for arg", "# an ExceptHandler node return node.name class Checker(object): \"\"\" I", "def addBinding(self, node, value): \"\"\" Called when a binding is", "/ globals scopes. if isinstance(node.ctx, (ast.Load, ast.AugLoad)): self.handleNodeLoad(node) if (node.id", "in self.scopeStack[::-1]: if value.name in scope: break existing = scope.get(value.name)", "pass def ANNASSIGN(self, node): if node.value: # Only bind the", "= self.nodeDepth node.parent = parent try: handler = self.getNodeHandler(node.__class__) handler(node)", "self.differentForks(node, existing.source): parent_stmt = self.getParent(value.source) if isinstance(existing, Importation) and isinstance(parent_stmt,", "self.scopeStack self.scopeStack = [self.scopeStack[0]] node_offset = self.offset or (0, 0)", "LSHIFT = RSHIFT = \\ BITOR = BITXOR = BITAND", "index in key_indices ) if any(count == 1 for value,", "if (self.withDoctest and not self._in_doctest() and not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda:", "the names # of the class. this is skipped during", "if has_starred: self.report(messages.TwoStarredExpressions, node) # The SyntaxError doesn't distinguish two", "with alias.\"\"\" if self._has_alias(): return self.fullName + ' as '", "items in parts: if self.descendantOf(lnode, items, ancestor) ^ \\ self.descendantOf(rnode,", "= AUGLOAD = AUGSTORE = PARAM = ignore # same", "in scope and isinstance(source, ast.AugAssign): self.names = list(scope['__all__'].names) else: self.names", "self.fullName == other.fullName return super(SubmoduleImportation, self).redefines(other) def __str__(self): return self.fullName", "Assignment(Binding): \"\"\" Represents binding a name with an explicit assignment.", "before target, and generators before element fields = node_class._fields if", "through the deferred functions. self._deferredFunctions = None self.runDeferred(self._deferredAssignments) # Set", "checkReturnWithArgumentInsideGenerator(): \"\"\" Check to see if there is any return", "* self.nodeDepth + 'end ' + node.__class__.__name__) _getDoctestExamples = doctest.DocTestParser().get_examples", "body of its definition. Additionally, add its name to the", "= fields = self._get_fields(node_class) return fields def counter(items): \"\"\" Simplest", "if isinstance(n, ast.If): return [n.body] if isinstance(n, ast.Try): return [n.body", "self.scope) else: binding = Assignment(name, node) self.addBinding(node, binding) def handleNodeDelete(self,", "scope binding.used = (self.scope, node) from_list.append(binding.fullName) # report * usage,", "True def isDocstring(self, node): \"\"\" Determine if the given node", "import __future__ import doctest import os import sys PY2 =", "- 1 else: # Computed incorrectly if the docstring has", "node types COMPREHENSION = KEYWORD = FORMATTEDVALUE = JOINEDSTR =", "ast.TryFinally)): return [n.body] if isinstance(n, ast.TryExcept): return [n.body + n.orelse]", "(comma-delimited) names. for node_name in node.names: node_value = Assignment(node_name, node)", "n.orelse: return if isinstance(n, (ast.FunctionDef, ast.ClassDef)): break # Handle Try/TryFinally", "self._nodeHandlers[node_class] = handler = getattr(self, nodeType) return handler def handleNodeLoad(self,", "# only generators used in a class scope can access", "self.report(messages.UndefinedLocal, scope[name].used[1], name, scope[name].source) break parent_stmt = self.getParent(node) if isinstance(parent_stmt,", "# of the class. this is skipped during the first", "alias in node.names: if '.' in alias.name and not alias.asname:", "PY2 and not isinstance(self.scope, ModuleScope): self.report(messages.ImportStarNotPermitted, node, module) continue self.scope.importStarred", "def counter(items): \"\"\" Simplest required implementation of collections.Counter. Required as", "self.scope) if alias.name not in __future__.all_feature_names: self.report(messages.FutureFeatureNotDefined, node, alias.name) elif", "SubmoduleImportation(Importation): \"\"\" A binding created by a submodule import statement.", "args = [] annotations = [] if PY2: def addArgs(arglist):", "importStarred or scope.importStarred if in_generators is not False: in_generators =", "TRYEXCEPT = TRY def EXCEPTHANDLER(self, node): if PY2 or node.name", "return None if lnode is rnode: return lnode if (lnode.depth", "ast.ClassDef)): break # Handle Try/TryFinally difference in Python < and", "self.scopeStack = [ModuleScope()] self.exceptHandlers = [()] self.root = tree self.handleChildren(tree)", "used: pair of (L{Scope}, node) indicating the scope and the", "self.real_name else: full_name = module + '.' + self.real_name super(ImportationFrom,", "for index in key_indices ) if any(count == 1 for", "self.offset)) def deferAssignment(self, callable): \"\"\" Schedule an assignment handler to", "self.nodeDepth + node.__class__.__name__) if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or", "(ast.FunctionDef, ast.ClassDef)): break # Handle Try/TryFinally difference in Python <", "def getNodeName(node): # Returns node.id, or node.name, or None if", "return tuple(sorted(fields, key=key_first, reverse=True)) def __missing__(self, node_class): self[node_class] = fields", "global scope. When `callable` is called, the scope at the", "# longer have line numbers associated with them. This will", "# than two. break has_starred = True star_loc = i", "# classes within classes are processed. if (self.withDoctest and not", "self.exceptHandlers.pop() # Process the other nodes: \"except:\", \"else:\", \"finally:\" self.handleChildren(node,", "getAlternatives(n): if isinstance(n, ast.If): return [n.body] if isinstance(n, ast.Try): return", "s: s.decorators) from pyflakes import messages if PY2: def getNodeType(node_class):", "self.deferFunction(lambda: self.handleDoctests(node)) ASYNCFUNCTIONDEF = FUNCTIONDEF def LAMBDA(self, node): args =", "locals / function / globals scopes. if isinstance(node.ctx, (ast.Load, ast.AugLoad)):", "see a loop (OK), a function or class # definition", "elif not existing.used and value.redefines(existing): self.report(messages.RedefinedWhileUnused, node, value.name, existing.source) elif", "return item.s elif hasattr(ast, 'Bytes') and isinstance(item, ast.Bytes): return item.s", "* is found def __repr__(self): scope_cls = self.__class__.__name__ return '<%s", "3.3 argannotation = arg_name + 'annotation' annotations.append(getattr(node.args, argannotation)) else: #", "= RAISE = TRYFINALLY = EXEC = \\ EXPR =", "[self.scopeStack[0]] node_offset = self.offset or (0, 0) self.pushScope(DoctestScope) underscore_in_builtins =", "omit=None, _fields_order=_FieldsOrder()): \"\"\" Yield all direct child nodes of *node*,", "list for name in undefined: self.report(messages.UndefinedExport, scope['__all__'].source, name) # mark", "# definition (not OK), for 'continue', a finally block (not", "stack. \"\"\" for handler, scope, offset in deferred: self.scopeStack =", "self.popScope() self.deferFunction(runFunction) def CLASSDEF(self, node): \"\"\" Check names used in", "False def __str__(self): return self.name def __repr__(self): return '<%s object", "(self.scope, node) except KeyError: pass else: return importStarred = importStarred", "[] if undefined: if not scope.importStarred and \\ os.path.basename(self.filename) !=", "created by an import statement. @ivar fullName: The complete name", "# noisily if called after we've run through the deferred", "def source_statement(self): \"\"\"Generate a source statement equivalent to the import.\"\"\"", ") if any(count == 1 for value, count in values.items()):", "isinstance(node.parent, ast.Call)): # we are doing locals() call in current", "FUNCTIONDEF def LAMBDA(self, node): args = [] annotations = []", "return ( compare.__class__ == self.__class__ and compare.name == self.name )", "globally defined name. See test_unused_global. self.messages = [ m for", "export list for name in undefined: self.report(messages.UndefinedExport, scope['__all__'].source, name) #", "item def convert_to_value(item): if isinstance(item, ast.Str): return item.s elif hasattr(ast,", "a submodule import statement. A submodule import is a special", "def popScope(self): self.deadScopes.append(self.scopeStack.pop()) def checkDeadScopes(self): \"\"\" Look at scopes which", "contexts are node instances too, though being constants LOAD =", "24: self.report(messages.TooManyExpressionsInStarredAssignment, node) self.handleChildren(node) LIST = TUPLE def IMPORT(self, node):", "self.offset = node_offset if not underscore_in_builtins: self.builtIns.remove('_') self.popScope() self.scopeStack =", "class Argument(Binding): \"\"\" Represents binding a name as an argument.", "for Lambdas self.handleNode(node.body, node) def checkUnusedAssignments(): \"\"\" Check to see", "some platforms. _MAGIC_GLOBALS = ['__file__', '__builtins__', 'WindowsError'] def getNodeName(node): #", "have the same value it's not going to cause potentially", "used but appear in the value of C{__all__} will not", "sys.pypy_version_info PYPY = True except AttributeError: PYPY = False builtin_vars", "for items in parts: if self.descendantOf(lnode, items, ancestor) ^ \\", "'*' imports as used for each scope binding.used = (self.scope,", "additional checking applied to them. The only C{__all__} assignment that", "if isinstance(n, (ast.FunctionDef, ast.ClassDef)): break # Handle Try/TryFinally difference in", "name afterwards. # # Unless it's been removed already. Then", "If the assignment has value, handle the *value* now. self.handleNode(node.value,", "if '__all__' in scope and isinstance(source, ast.AugAssign): self.names = list(scope['__all__'].names)", "class FunctionScope(Scope): \"\"\" I represent a name scope for a", "results[item] = results.get(item, 0) + 1 return results def iter_child_nodes(node,", "node = node.value if not isinstance(node, ast.Str): return (None, None)", "True self.report(messages.ImportStarUsed, node, module) importation = StarImportation(module, node) else: importation", "# we are doing locals() call in current scope self.scope.usesLocals", "( compare.__class__ == self.__class__ and compare.name == self.name ) def", "needs a unique name, and # may not be the", "scope.importStarred: for binding in scope.values(): if isinstance(binding, StarImportation): binding.used =", "value def getNodeHandler(self, node_class): try: return self._nodeHandlers[node_class] except KeyError: nodeType", "allowing any attribute of the root module to be accessed.", "name) def handleNodeStore(self, node): name = getNodeName(node) if not name:", "isinstance(self.scope, FunctionScope) and name not in self.scope: # for each", "not None: node.lineno += self.offset[0] node.col_offset += self.offset[1] if self.traceTree:", "and value.redefines(existing): self.report(messages.RedefinedWhileUnused, node, value.name, existing.source) elif isinstance(existing, Importation) and", "\"\"\"Return import full name with alias.\"\"\" if self._has_alias(): return self.fullName", "True, 'False': False, 'None': None, } return constants_lookup.get( result.name, result,", "= False module = ('.' * node.level) + (node.module or", "models the Bindings and Scopes. \"\"\" import __future__ import doctest", "not been used. \"\"\" for name, binding in self.items(): if", "LAMBDA(self, node): args = [] annotations = [] if PY2:", "= NOTIN = \\ MATMULT = ignore # additional node", "annotations.append(node.returns) if len(set(args)) < len(args): for (idx, arg) in enumerate(args):", "isn't used. Also, the checker does not consider assignments in", "on_conditional_branch(): # We cannot predict if this conditional branch is", "not isinstance(m, messages.UndefinedName) or m.message_args[0] != node_name] # Bind name", "isDocstring(self, node): \"\"\" Determine if the given node is a", "node_value) # Bind name to non-global scopes, but as already", "self.deferFunction(lambda: self.handleDoctests(node)) for stmt in node.body: self.handleNode(stmt, node) self.popScope() self.addBinding(node,", "created by a submodule import statement. A submodule import is", "uses ast.Try instead of (ast.TryExcept + ast.TryFinally) if PY32: def", "enclosing function scopes and global scope for scope in self.scopeStack[-1::-1]:", "names have been bound and which names have not. See", "NOT = UADD = USUB = \\ EQ = NOTEQ", "in key_indices ) if any(count == 1 for value, count", "loop itself if n_child not in n.orelse: return if isinstance(n,", "module. Implement the central Checker class. Also, it models the", "too, though being constants LOAD = STORE = DEL =", "not all(isinstance(scope, ModuleScope) for scope in self.scopeStack): return False return", "is the new value, a Binding instance \"\"\" # assert", "'.' + self.real_name super(ImportationFrom, self).__init__(name, source, full_name) def __str__(self): \"\"\"Return", "break parent_stmt = self.getParent(node) if isinstance(parent_stmt, (ast.For, ast.comprehension)) or (", "are duplicate keys with different values # If they have", "node): if PY2 or node.name is None: self.handleChildren(node) return #", "constants_lookup.get( result.name, result, ) elif (not PY33) and isinstance(item, ast.NameConstant):", "node) self.handleNode(node.target, node) def TUPLE(self, node): if not PY2 and", "Name node, but # a simple string, creates a local", "the scope at the time this is called will be", "block (not OK), or # the top module scope (not", "self.real_name != self.name: return self.fullName + ' as ' +", "expression contexts are node instances too, though being constants LOAD", "try: handler = self.getNodeHandler(node.__class__) handler(node) finally: self.nodeDepth -= 1 if", "isinstance(node, ast.Str): return (None, None) if PYPY: doctest_lineno = node.lineno", "going to cause potentially # unexpected behaviour so we'll not", "name when it is a submodule import assert '.' in", "`redefines` unless the submodule name is also the same, to", "elif alias.name == '*': # Only Python 2, local import", "ast.Tuple): for exc_type in handler.type.elts: handler_names.append(getNodeName(exc_type)) elif handler.type: handler_names.append(getNodeName(handler.type)) if", "for node in iter_child_nodes(tree, omit=omit): self.handleNode(node, tree) def isLiteralTupleUnpacking(self, node):", "name: return # if the name hasn't already been defined", "node.__class__.__name__) _getDoctestExamples = doctest.DocTestParser().get_examples def handleDoctests(self, node): try: if hasattr(node,", "are two-tuples. The first element is the callable passed to", "isinstance(node.ctx, ast.Del): self.handleNodeDelete(node) else: # must be a Param context", "self.pushScope(DoctestScope) underscore_in_builtins = '_' in self.builtIns if not underscore_in_builtins: self.builtIns.add('_')", "if not underscore_in_builtins: self.builtIns.remove('_') self.popScope() self.scopeStack = saved_stack def ignore(self,", "enumerate(args): if arg in args[:idx]: self.report(messages.DuplicateArgument, node, arg) for child", "Required as 2.6 does not have Counter in collections. \"\"\"", "in SubmoduleImportation about RedefinedWhileUnused return self.fullName == other.fullName return isinstance(other,", "self.report(messages.RedefinedWhileUnused, node, value.name, existing.source) elif isinstance(existing, Importation) and value.redefines(existing): existing.redefined.append(node)", "finally block (not OK), or # the top module scope", "%r from line %r at 0x%x>' % (self.__class__.__name__, self.name, self.source.lineno,", "self.scopeStack.append(scopeClass()) def report(self, messageClass, *args, **kwargs): self.messages.append(messageClass(self.filename, *args, **kwargs)) def", "on https://github.com/PyCQA/pyflakes/pull/59 # We're removing the local name since it's", "self.messages = [] self.filename = filename if builtins: self.builtIns =", "for key, count in key_counts.items() if count > 1 ]", "just after deferred function handlers. \"\"\" self._deferredAssignments.append((callable, self.scopeStack[:], self.offset)) def", "value in scope.values(): if isinstance(value, Importation): used = value.used or", "__init__(self, name, source, module, real_name=None): self.module = module self.real_name =", "return self.name class FutureImportation(ImportationFrom): \"\"\" A binding created by a", "= GT = GTE = IS = ISNOT = IN", "@futuresAllowed.setter def futuresAllowed(self, value): assert value is False if isinstance(self.scope,", "by a from `__future__` import statement. `__future__` imports are implicitly", "builtins module, or # are only present on some platforms.", "the central Checker class. Also, it models the Bindings and", "ExceptHandler node return node.name class Checker(object): \"\"\" I check the", "in value.redefined: if isinstance(self.getParent(node), ast.For): messg = messages.ImportShadowedByLoopVar elif used:", "node) return self.scope.isGenerator = True self.handleNode(node.value, node) AWAIT = YIELDFROM", "self.__class__ and compare.name == self.name ) def __hash__(self): return hash(self.name)", "@property def source_statement(self): \"\"\"Generate a source statement equivalent to the", "node.parent if not hasattr(node, 'elts') and not hasattr(node, 'ctx'): return", "VariableKey(item=item) constants_lookup = { 'True': True, 'False': False, 'None': None,", "= [] for scope in self.scopeStack[-1::-1]: for binding in scope.values():", "= getattr(node.args, arg_name) if not wildcard: continue args.append(wildcard if PY33", "!= []: self.report(messages.AssertTuple, node) self.handleChildren(node) def GLOBAL(self, node): \"\"\" Keep", "limit of 1<<24 expressions after the starred expression, # which", "break existing = scope.get(value.name) if existing and not self.differentForks(node, existing.source):", "is also imported. Python does not restrict which attributes of", "None, } return constants_lookup.get( result.name, result, ) elif (not PY33)", "= messages.RedefinedWhileUnused self.report(messg, node, value.name, value.source) def pushScope(self, scopeClass=FunctionScope): self.scopeStack.append(scopeClass())", "stop) return self.getCommonAncestor(lnode.parent, rnode.parent, stop) def descendantOf(self, node, ancestors, stop):", "existing.source) elif not existing.used and value.redefines(existing): self.report(messages.RedefinedWhileUnused, node, value.name, existing.source)", "print(' ' * self.nodeDepth + node.__class__.__name__) if self.futuresAllowed and not", "[n.body + n.orelse] + [[hdl] for hdl in n.handlers] if", "leading whitespace: ... return if not examples: return # Place", "= d. # Only one starred expression is allowed, and", "class DoctestScope(ModuleScope): \"\"\"Scope for a doctest.\"\"\" # Globally defined names", "import os import sys PY2 = sys.version_info < (3, 0)", "names in 2 return item.value else: return UnhandledKeyType() class Binding(object):", "+= 1 position = (node_lineno + example.lineno + e.lineno, example.indent", "MATMULT = ignore # additional node types COMPREHENSION = KEYWORD", "with different values # If they have the same value", "Place doctest in module scope saved_stack = self.scopeStack self.scopeStack =", "= YIELD def FUNCTIONDEF(self, node): for deco in node.decorator_list: self.handleNode(deco,", "variable AST object. \"\"\" def __init__(self, item): self.name = item.id", "# after leaving the except: block and it's always unbound", "name, binding class GeneratorScope(Scope): pass class ModuleScope(Scope): \"\"\"Scope for a", "if the docstring has backslash doctest_lineno = node.lineno - node.s.count('\\n')", "try: del self.scope[node.name] except KeyError: pass def ANNASSIGN(self, node): if", "PY2 and isinstance(node.ctx, ast.Store): # Python 3 advanced tuple unpacking:", "handler in enumerate(node.handlers): if isinstance(handler.type, ast.Tuple): for exc_type in handler.type.elts:", "= StarImportation(module, node) else: importation = ImportationFrom(name, node, module, alias.name)", "= \\ COMPARE = CALL = REPR = ATTRIBUTE =", "class FunctionDefinition(Definition): pass class ClassDefinition(Definition): pass class ExportBinding(Binding): \"\"\" A", "def YIELD(self, node): if isinstance(self.scope, (ClassScope, ModuleScope)): self.report(messages.YieldOutsideFunction, node) return", "in_generators is not False: in_generators = isinstance(scope, GeneratorScope) # look", "ambiguous '..*' if self.fullName.endswith('.'): return self.source_statement else: return self.name class", "'continue', a finally block (not OK), or # the top", "self.handleNode(node.body, node) def checkUnusedAssignments(): \"\"\" Check to see if any", "do nothing. try: del self.scope[node.name] except KeyError: pass def ANNASSIGN(self,", "= real_name or name if module.endswith('.'): full_name = module +", "node, value.name, existing.source) elif not existing.used and value.redefines(existing): self.report(messages.RedefinedWhileUnused, node,", "self.scopeStack[:], self.offset)) def deferAssignment(self, callable): \"\"\" Schedule an assignment handler", "only happens for names in function # arguments, but these", "pass class ExportBinding(Binding): \"\"\" A binding created by an C{__all__}", "node.args.defaults else: for arg in node.args.args + node.args.kwonlyargs: args.append(arg.arg) annotations.append(arg.annotation)", "ast.For) else: LOOP_TYPES = (ast.While, ast.For, ast.AsyncFor) class _FieldsOrder(dict): \"\"\"Fix", "del self.scope[name] except KeyError: self.report(messages.UndefinedName, node, name) def handleChildren(self, tree,", "= \\ EXPR = ASSIGN = handleChildren PASS = ignore", "in self.scopeStack[global_scope_index + 1:]: scope[node_name] = node_value NONLOCAL = GLOBAL", "reported for them. \"\"\" def __init__(self, name, source, scope): if", "[] super(Importation, self).__init__(name, source) def redefines(self, other): if isinstance(other, SubmoduleImportation):", "time L{deferFunction} was called. @ivar _deferredAssignments: Similar to C{_deferredFunctions}, but", "node) else: # case for Lambdas self.handleNode(node.body, node) def checkUnusedAssignments():", "\"\"\" Schedule an assignment handler to be called just after", "cannot or do not check for duplicates. \"\"\" class VariableKey(object):", "= alias.asname or alias.name importation = Importation(name, node, alias.name) self.addBinding(node,", "omit='body') TRYEXCEPT = TRY def EXCEPTHANDLER(self, node): if PY2 or", "return lnode if (lnode.depth > rnode.depth): return self.getCommonAncestor(lnode.parent, rnode, stop)", "for name, binding in self.scope.unusedAssignments(): self.report(messages.UnusedVariable, binding.source, name) self.deferAssignment(checkUnusedAssignments) if", "are nodes and all items of fields that are lists", "self.traceTree: print(' ' * self.nodeDepth + 'end ' + node.__class__.__name__)", "= getAlternatives(ancestor) if parts: for items in parts: if self.descendantOf(lnode,", "items of fields that are lists of nodes. \"\"\" for", "@ivar globals: Names declared 'global' in this function. \"\"\" usesLocals", "they will be treated as names for export and additional", "elif isinstance(item, ast.Tuple): return tuple(convert_to_value(i) for i in item.elts) elif", "node): self.pushScope(GeneratorScope) self.handleChildren(node) self.popScope() LISTCOMP = handleChildren if PY2 else", "def report(self, messageClass, *args, **kwargs): self.messages.append(messageClass(self.filename, *args, **kwargs)) def getParent(self,", "class ClassDefinition(Definition): pass class ExportBinding(Binding): \"\"\" A binding created by", "stared expression. There is # also a limit of 1<<24", "self[node_class] = fields = self._get_fields(node_class) return fields def counter(items): \"\"\"", "in self.builtIns if not underscore_in_builtins: self.builtIns.add('_') for example in examples:", "a local that is only bound within the scope #", "just before completion. This is used for handling function bodies,", "return [n.body] if isinstance(n, ast.TryExcept): return [n.body + n.orelse] +", "handleChildren def DICT(self, node): # Complain if there are duplicate", "= self.getDocstring(node.body[0]) examples = docstring and self._getDoctestExamples(docstring) except (ValueError, IndexError):", "if on_conditional_branch(): # We cannot predict if this conditional branch", "source or isinstance(source, ast.Import)) package_name = name.split('.')[0] super(SubmoduleImportation, self).__init__(package_name, source)", "'from %s import %s as %s' % (self.module, self.real_name, self.name)", "a generator def unusedAssignments(self): \"\"\" Return a generator for the", "scopes which have been fully examined and report names in", "checker does not consider assignments in tuple/list unpacking to be", "key, ) self.handleChildren(node) def ASSERT(self, node): if isinstance(node.test, ast.Tuple) and", "= -1 for i, n in enumerate(node.elts): if isinstance(n, ast.Starred):", "STR = BYTES = ELLIPSIS = ignore # \"slice\" type", "getNodeName(node): # Returns node.id, or node.name, or None if hasattr(node,", "defaults = node.args.defaults else: for arg in node.args.args + node.args.kwonlyargs:", "a, stop): return True return False def differentForks(self, lnode, rnode):", "if name == '__path__' and os.path.basename(self.filename) == '__init__.py': # the", "which names have not. See L{Assignment} for a special type", "from line %r at 0x%x>' % (self.__class__.__name__, self.name, self.source.lineno, id(self))", "not check for duplicates. \"\"\" class VariableKey(object): \"\"\" A dictionary", "return '<%s object %r from line %r at 0x%x>' %", "the node that this binding was last used. \"\"\" def", "the deferred assignments. self._deferredAssignments = None del self.scopeStack[1:] self.popScope() self.checkDeadScopes()", "self._deferredFunctions.append((callable, self.scopeStack[:], self.offset)) def deferAssignment(self, callable): \"\"\" Schedule an assignment", "name in scope and scope[name].used if used and used[0] is", "checks. \"\"\" nodeDepth = 0 offset = None traceTree =", "which is impossible to test due to memory restrictions, but", "if star_loc >= 1 << 8 or len(node.elts) - star_loc", "self.report(messages.RedefinedInListComp, node, value.name, existing.source) elif not existing.used and value.redefines(existing): self.report(messages.RedefinedWhileUnused,", "local name since it's being unbound # after leaving the", "= node_class._fields if 'iter' in fields: key_first = 'iter'.find elif", "for scope in self.scopeStack[global_scope_index + 1:]: scope[node_name] = node_value NONLOCAL", "if 'decorator_list' not in ast.ClassDef._fields: # Patch the missing attribute", "else: def getNodeType(node_class): return node_class.__name__.upper() # Python >= 3.3 uses", "self.names.append(node.s) super(ExportBinding, self).__init__(name, source) class Scope(dict): importStarred = False #", "name = getNodeName(node) if not name: return in_generators = None", "' as ' + self.name else: return self.fullName class SubmoduleImportation(Importation):", "(lnode.depth < rnode.depth): return self.getCommonAncestor(lnode, rnode.parent, stop) return self.getCommonAncestor(lnode.parent, rnode.parent,", "import statement. @ivar fullName: The complete name given to the", "ast.Str): self.names.append(node.s) super(ExportBinding, self).__init__(name, source) class Scope(dict): importStarred = False", "[n.body + n.orelse] + [[hdl] for hdl in n.handlers] else:", "on_conditional_branch(): \"\"\" Return `True` if node is part of a", "' * self.nodeDepth + node.__class__.__name__) if self.futuresAllowed and not (isinstance(node,", "+ 'end ' + node.__class__.__name__) _getDoctestExamples = doctest.DocTestParser().get_examples def handleDoctests(self,", "CONTINUE def RETURN(self, node): if isinstance(self.scope, (ClassScope, ModuleScope)): self.report(messages.ReturnOutsideFunction, node)", "self.report(messages.YieldOutsideFunction, node) return self.scope.isGenerator = True self.handleNode(node.value, node) AWAIT =", "if isinstance(other, Importation): return self.fullName == other.fullName return super(SubmoduleImportation, self).redefines(other)", "scope and the node that this binding was last used.", "ExportBinding(Binding): \"\"\" A binding created by an C{__all__} assignment. If", "module self.real_name = real_name or name if module.endswith('.'): full_name =", "if self.futuresAllowed and not (isinstance(node, ast.ImportFrom) or self.isDocstring(node)): self.futuresAllowed =", "FUNCTIONDEF(self, node): for deco in node.decorator_list: self.handleNode(deco, node) self.LAMBDA(node) self.addBinding(node,", "an id return node.id if hasattr(node, 'name'): # an ExceptHandler", "# use the name afterwards. # # Unless it's been", "are lists of nodes. \"\"\" for name in _fields_order[node.__class__]: if", "memory restrictions, but we # add it here anyway has_starred", "self.builtIns.union(builtins) self.withDoctest = withDoctest self.scopeStack = [ModuleScope()] self.exceptHandlers = [()]", "is used for handling function bodies, which must be deferred", "alias.asname or alias.name if node.module == '__future__': importation = FutureImportation(name,", "self.used = False def __str__(self): return self.name def __repr__(self): return", "node instances too, though being constants LOAD = STORE =", "we # add it here anyway has_starred = False star_loc", "to them. The only C{__all__} assignment that can be recognized", "e.lineno, example.indent + 4 + (e.offset or 0)) self.report(messages.DoctestSyntaxError, node,", "_customBuiltIns = os.environ.get('PYFLAKES_BUILTINS') if _customBuiltIns: builtIns.update(_customBuiltIns.split(',')) del _customBuiltIns def __init__(self,", "= full_name or name self.redefined = [] super(Importation, self).__init__(name, source)", "with stricter rules. @ivar used: pair of (L{Scope}, node) indicating", "False alwaysUsed = set(['__tracebackhide__', '__traceback_info__', '__traceback_supplement__']) def __init__(self): super(FunctionScope, self).__init__()", "def _in_doctest(self): return (len(self.scopeStack) >= 2 and isinstance(self.scopeStack[1], DoctestScope)) @property", "# Python >= 3.3 uses ast.Try instead of (ast.TryExcept +", "return if not examples: return # Place doctest in module", "doing locals() call in current scope self.scope.usesLocals = True elif", "a stared expression. There is # also a limit of", "(hasattr(lnode, 'parent') and hasattr(rnode, 'parent')): return None if lnode is", "in ('vararg', 'kwarg'): wildcard = getattr(node.args, arg_name) if not wildcard:", "in packages return # protected with a NameError handler? if", "( parent_stmt != node.parent and not self.isLiteralTupleUnpacking(parent_stmt)): binding = Binding(name,", "Handle Try/TryFinally difference in Python < and >= 3.3 if", "in classes are public members if isinstance(scope, ClassScope): continue all_binding", "an unused import warning reported for them. \"\"\" def __init__(self,", "exc_type in handler.type.elts: handler_names.append(getNodeName(exc_type)) elif handler.type: handler_names.append(getNodeName(handler.type)) if handler.type is", "def __init__(self, item): self.name = item.id def __eq__(self, compare): return", "importation = FutureImportation(name, node, self.scope) if alias.name not in __future__.all_feature_names:", "warnings. self.handleNode(node.target, node) self.handleNode(node.annotation, node) if node.value: # If the", "count > 1 ] for key in duplicate_keys: key_indices =", "else: is_name_previously_defined = False self.handleNodeStore(node) self.handleChildren(node) if not is_name_previously_defined: #", "self).__init__(name, source, '__future__') self.used = (scope, source) class Argument(Binding): \"\"\"", "the scope stack at the time L{deferFunction} was called. @ivar", "= ISNOT = IN = NOTIN = \\ MATMULT =", "node): # Walk the tree up until we see a", "= [ convert_to_value(key) for key in node.keys ] key_counts =", "NAMECONSTANT = handleChildren NUM = STR = BYTES = ELLIPSIS", "'NameError' not in self.exceptHandlers[-1]: self.report(messages.UndefinedName, node, name) def handleNodeStore(self, node):", "as globals self.globals = self.alwaysUsed.copy() self.returnValue = None # First", "= USUB = \\ EQ = NOTEQ = LT =", "# Python 2.5 to 3.3 PY34 = sys.version_info < (3,", "__all__ if scope.importStarred: for binding in scope.values(): if isinstance(binding, StarImportation):", "Importation): return self.fullName == other.fullName return super(SubmoduleImportation, self).redefines(other) def __str__(self):", "applied to them. The only C{__all__} assignment that can be", "name, scope[name].source) break parent_stmt = self.getParent(node) if isinstance(parent_stmt, (ast.For, ast.comprehension))", "= (node_lineno + example.lineno + e.lineno, example.indent + 4 +", "if isinstance(node, ast.Str): self.names.append(node.s) super(ExportBinding, self).__init__(name, source) class Scope(dict): importStarred", "scope if it doesn't exist already. global_scope.setdefault(node_name, node_value) # Bind", "self.source = source self.used = False def __str__(self): return self.name", "name) self.deferAssignment(checkUnusedAssignments) if PY32: def checkReturnWithArgumentInsideGenerator(): \"\"\" Check to see", "two. break has_starred = True star_loc = i if star_loc", "isinstance(parent_stmt, (ast.For, ast.comprehension)) or ( parent_stmt != node.parent and not", "= self.scope[value.name].used self.scope[value.name] = value def getNodeHandler(self, node_class): try: return", "unbound # if the except: block is never entered. This", "for scope in self.scopeStack[-1::-1]: for binding in scope.values(): if isinstance(binding,", "of nodes. \"\"\" for name in _fields_order[node.__class__]: if name ==", "is False if isinstance(self.scope, ModuleScope): self.scope._futures_allowed = False @property def", "+ example.indent + 4) self.handleChildren(tree) self.offset = node_offset if not", "= offset handler() def _in_doctest(self): return (len(self.scopeStack) >= 2 and", "compare.__class__ == self.__class__ and compare.name == self.name ) def __hash__(self):", "binding created by an import statement. @ivar fullName: The complete", "def FUNCTIONDEF(self, node): for deco in node.decorator_list: self.handleNode(deco, node) self.LAMBDA(node)", "if PY34: LOOP_TYPES = (ast.While, ast.For) else: LOOP_TYPES = (ast.While,", "WITH = WITHITEM = \\ ASYNCWITH = ASYNCWITHITEM = RAISE", "len(node.handlers) - 1: self.report(messages.DefaultExceptNotLast, handler) # Memorize the except handlers", "and rnode are located on different forks of IF/TRY\"\"\" ancestor", "bind multiple (comma-delimited) names. for node_name in node.names: node_value =", "which is not Tuple, List or Starred while True: node", "'decorator_list' not in ast.ClassDef._fields: # Patch the missing attribute 'decorator_list'", "the first iteration if in_generators is False and isinstance(scope, ClassScope):", "used = value.used or value.name in all_names if not used:", "name, source, full_name=None): self.fullName = full_name or name self.redefined =", "self.handleNode(deco, node) self.LAMBDA(node) self.addBinding(node, FunctionDefinition(node.name, node)) # doctest does not", "isinstance(n, (ast.FunctionDef, ast.ClassDef)): break # Handle Try/TryFinally difference in Python", "None if hasattr(node, 'id'): # One of the many nodes", "if not examples: return # Place doctest in module scope", "messages.UndefinedName) or m.message_args[0] != node_name] # Bind name to global", "module is implicitly imported, without an 'as' clause, and the", "other.fullName return isinstance(other, Definition) and self.name == other.name def _has_alias(self):", "Assignment(node_name, node) # Remove UndefinedName messages already reported for this", "Returns node.id, or node.name, or None if hasattr(node, 'id'): #", "if in_generators is not False: in_generators = isinstance(scope, GeneratorScope) #", "False return True def isDocstring(self, node): \"\"\" Determine if the", "and isinstance(node.value, ast.Str)) def getDocstring(self, node): if isinstance(node, ast.Expr): node", "OK), for 'continue', a finally block (not OK), or #", "= NAMECONSTANT = handleChildren NUM = STR = BYTES =", "found def __repr__(self): scope_cls = self.__class__.__name__ return '<%s at 0x%x", "ast.TryFinally) if PY32: def getAlternatives(n): if isinstance(n, (ast.If, ast.TryFinally)): return", "altered. - `node` is the statement responsible for the change", "values = counter( convert_to_value(node.values[index]) for index in key_indices ) if", "call in current scope self.scope.usesLocals = True elif isinstance(node.ctx, (ast.Store,", "tuple unpacking: a, *b, c = d. # Only one", "instead of (ast.TryExcept + ast.TryFinally) if PY32: def getAlternatives(n): if", "# Each star importation needs a unique name, and #", "if (isinstance(parent_stmt, ast.comprehension) and not isinstance(self.getParent(existing.source), (ast.For, ast.comprehension))): self.report(messages.RedefinedInListComp, node,", "value of a literal list containing literal strings. For example::", "on different forks of IF/TRY\"\"\" ancestor = self.getCommonAncestor(lnode, rnode, self.root)", "1 return (node.s, doctest_lineno) def handleNode(self, node, parent): if node", "global_scope.setdefault(node_name, node_value) # Bind name to non-global scopes, but as", "self.name == other.name class Definition(Binding): \"\"\" A binding that defines", "used by the undefined in __all__ if scope.importStarred: for binding", "self.handleDoctests(node)) ASYNCFUNCTIONDEF = FUNCTIONDEF def LAMBDA(self, node): args = []", "for scope in self.deadScopes: # imports in classes are public", "EQ = NOTEQ = LT = LTE = GT =", "node.keywords: self.handleNode(keywordNode, node) self.pushScope(ClassScope) # doctest does not process doctest", "correct place in the node tree. \"\"\" return isinstance(node, ast.Str)", "<string> has inconsistent # leading whitespace: ... return if not", "self.fullName @property def source_statement(self): return 'import ' + self.fullName class", "ADD = SUB = MULT = DIV = MOD =", "when the submodule import is without an 'as' clause. pyflakes", "position) else: self.offset = (node_offset[0] + node_lineno + example.lineno, node_offset[1]", "= FLOORDIV = INVERT = NOT = UADD = USUB", "node.decorator_list: self.handleNode(deco, node) for baseNode in node.bases: self.handleNode(baseNode, node) if", "if the assignment has a value. # Otherwise it's not", "self.isDocstring(node)): self.futuresAllowed = False self.nodeDepth += 1 node.depth = self.nodeDepth", "getNodeName(node) if not name: return # if the name hasn't", "node, name) def handleNodeStore(self, node): name = getNodeName(node) if not", "self.messages = [ m for m in self.messages if not", "filename='(none)', builtins=None, withDoctest='PYFLAKES_DOCTEST' in os.environ): self._nodeHandlers = {} self._deferredFunctions =", "when import * is found def __repr__(self): scope_cls = self.__class__.__name__", "(0, 0) self.pushScope(DoctestScope) underscore_in_builtins = '_' in self.builtIns if not", "%s>' % (scope_cls, id(self), dict.__repr__(self)) class ClassScope(Scope): pass class FunctionScope(Scope):", "while hasattr(n, 'parent'): n, n_child = n.parent, n if isinstance(n,", "node.parent = parent try: handler = self.getNodeHandler(node.__class__) handler(node) finally: self.nodeDepth", "there are empty lines between the beginning # of the", "if undefined: if not scope.importStarred and \\ os.path.basename(self.filename) != '__init__.py':", "The first element is the callable passed to L{deferFunction}. The", "of *node*, that is, all fields that are nodes and", "if self._has_alias(): return 'import %s as %s' % (self.fullName, self.name)", "None) while current: if isinstance(current, (ast.If, ast.While, ast.IfExp)): return True", "Only for Python3 FunctionDefs is_py3_func = hasattr(node, 'returns') for arg_name", "or len(node.elts) - star_loc - 1 >= 1 << 24:", "ignore # \"slice\" type nodes SLICE = EXTSLICE = INDEX", "def DICT(self, node): # Complain if there are duplicate keys", "None del self.scopeStack[1:] self.popScope() self.checkDeadScopes() def deferFunction(self, callable): \"\"\" Schedule", "the submodule import is without an 'as' clause. pyflakes handles", "is suppressed in `redefines` unless the submodule name is also", "Also, it models the Bindings and Scopes. \"\"\" import __future__", "This is just a reasonable guess. In Python 3.7, docstrings", "iteration if in_generators is False and isinstance(scope, ClassScope): continue try:", "used in a class scope can access the names #", "KeyError: self.report(messages.UndefinedName, node, name) def handleChildren(self, tree, omit=None): for node", "FunctionScope) and name not in self.scope: # for each function", "OK), or # the top module scope (not OK) n", "node is a docstring, as long as it is at", "possible mistakes in the export list for name in undefined:", "node.keys[key_index] if isinstance(key, VariableKey): self.report(messages.MultiValueRepeatedKeyVariable, key_node, key.name) else: self.report( messages.MultiValueRepeatedKeyLiteral,", "L{deferFunction} was called. @ivar _deferredAssignments: Similar to C{_deferredFunctions}, but for", "a module.\"\"\" _futures_allowed = True class DoctestScope(ModuleScope): \"\"\"Scope for a", "as it is at the correct place in the node", "(3, 5) # Python 2.5 to 3.4 try: sys.pypy_version_info PYPY", "== '__all__' and isinstance(self.scope, ModuleScope): binding = ExportBinding(name, node.parent, self.scope)", "BITXOR = BITAND = FLOORDIV = INVERT = NOT =", "alias in node.names: name = alias.asname or alias.name if node.module", "= (ast.While, ast.For, ast.AsyncFor) class _FieldsOrder(dict): \"\"\"Fix order of AST", "\"\"\" class VariableKey(object): \"\"\" A dictionary key which is a", "# unexpected behaviour so we'll not complain. keys = [", "= messages.UnusedImport self.report(messg, value.source, str(value)) for node in value.redefined: if", "node.parent): for scope in self.scopeStack[::-1]: if value.name in scope: break", "deferred assignments. self._deferredAssignments = None del self.scopeStack[1:] self.popScope() self.checkDeadScopes() def", "+ self.name else: return self.fullName class SubmoduleImportation(Importation): \"\"\" A binding", "a name scope for a function. @ivar globals: Names declared", "all_binding: all_names = set(all_binding.names) undefined = all_names.difference(scope) else: all_names =", "self.nodeDepth -= 1 if self.traceTree: print(' ' * self.nodeDepth +", "\"\"\" A dictionary key of a type that we cannot", "self).redefines(other) def __str__(self): return self.fullName @property def source_statement(self): return 'import", "= self._get_fields(node_class) return fields def counter(items): \"\"\" Simplest required implementation", "self.deadScopes.append(self.scopeStack.pop()) def checkDeadScopes(self): \"\"\" Look at scopes which have been", "except KeyError: nodeType = getNodeType(node_class) self._nodeHandlers[node_class] = handler = getattr(self,", "YIELDFROM = YIELD def FUNCTIONDEF(self, node): for deco in node.decorator_list:", "rnode) or not (hasattr(lnode, 'parent') and hasattr(rnode, 'parent')): return None", "getNodeType(node_class): return node_class.__name__.upper() # Python >= 3.3 uses ast.Try instead", "ast.For, ast.AsyncFor) class _FieldsOrder(dict): \"\"\"Fix order of AST node fields.\"\"\"", "REPR = ATTRIBUTE = SUBSCRIPT = \\ STARRED = NAMECONSTANT", "self.real_name super(ImportationFrom, self).__init__(name, source, full_name) def __str__(self): \"\"\"Return import full", "handlers and process the body self.exceptHandlers.append(handler_names) for child in node.body:", "function is a generator. \"\"\" if self.scope.isGenerator and self.scope.returnValue: self.report(messages.ReturnWithArgsInsideGenerator,", "items, ancestor) ^ \\ self.descendantOf(rnode, items, ancestor): return True return", "in examples: try: tree = compile(example.source, \"<doctest>\", \"exec\", ast.PyCF_ONLY_AST) except", "isinstance(field, ast.AST): yield field elif isinstance(field, list): for item in", "module.\"\"\" _futures_allowed = True class DoctestScope(ModuleScope): \"\"\"Scope for a doctest.\"\"\"", "statement responsible for the change - `value` is the new", "key_indices: key_node = node.keys[key_index] if isinstance(key, VariableKey): self.report(messages.MultiValueRepeatedKeyVariable, key_node, key.name)", "additional node types COMPREHENSION = KEYWORD = FORMATTEDVALUE = JOINEDSTR", "return self.fullName + ' as ' + self.name else: return", "not used in this scope, it does not # become", "[i for i, i_key in enumerate(keys) if i_key == key]", "sys.version_info < (3, 5) # Python 2.5 to 3.4 try:", "__init__(self, name, source, scope): super(FutureImportation, self).__init__(name, source, '__future__') self.used =", "as ast if 'decorator_list' not in ast.ClassDef._fields: # Patch the" ]
[ "of screen when any change take place. # Author: Mani", "class AutoScreenshot: def __init__(self, master): self.root = root root.title('Auto Screenshot')", "bg=\"#f44336\", activebackground=\"#ff7043\", activeforeground=\"white\", font=fontRoboto) btn_start.pack(padx=\"10\", pady=\"10\", fill=BOTH) def start(self): #", "one folder if not os.path.exists(directory): os.makedirs(directory) # new folder for", "= grab(bbox=self.cords) time.sleep(1) img2 = grab(bbox=self.cords) # check difference between", "diff = ImageChops.difference(img1, img2) bbox = diff.getbbox() if bbox is", "from PIL import ImageChops import os import time import subprocess,", "os.makedirs(directory) # new folder for storing images for current session", "close button btn_start = Button(root, text=\"Close\", command=self.close) btn_start.config(highlightthickness=0, bd=0, fg=\"white\",", "\"/ScreenShots\" + now + \".png\" img1.save(fname) print(\"First Screenshot taken\") #", "ScreenCords.py and get cordinates cords_point = subprocess.check_output([sys.executable, \"GetScreenCoordinates.py\", \"-l\"]) cord_tuple", "start taking screenshot of next images self.take_screenshots() def take_screenshots(self): #", "quit() if __name__ == \"__main__\": root = Tk() gui =", "taken\") # start taking screenshot of next images self.take_screenshots() def", "store images directory = \"Screenshots\" self.new_folder = directory + \"/\"", "time.sleep(1) img2 = grab(bbox=self.cords) # check difference between images diff", "\"/\" + datetime.now().strftime(\"%Y_%m_%d-%I_%M_%p\") # all images to one folder if", "Run ScreenCords.py and get cordinates cords_point = subprocess.check_output([sys.executable, \"GetScreenCoordinates.py\", \"-l\"])", "bbox = diff.getbbox() if bbox is not None: now =", "import grab from PIL import ImageChops import os import time", "screenshot of screen when any change take place. # Author:", "start(self): # Create folder to store images directory = \"Screenshots\"", "size=16, weight='bold') # project name label projectTitleLabel = Label(root, text=\"Auto", "bg=\"white\", fg=\"#5599ff\") projectTitleLabel.pack(padx=\"10\") # start button btn_start = Button(root, text=\"Start\",", "label projectTitleLabel = Label(root, text=\"Auto Screenshot v1.0.0\") projectTitleLabel.config(font=fontRoboto, bg=\"white\", fg=\"#5599ff\")", "= font.Font(family='Roboto', size=16, weight='bold') # project name label projectTitleLabel =", "command=self.close) btn_start.config(highlightthickness=0, bd=0, fg=\"white\", bg=\"#f44336\", activebackground=\"#ff7043\", activeforeground=\"white\", font=fontRoboto) btn_start.pack(padx=\"10\", pady=\"10\",", "project name label projectTitleLabel = Label(root, text=\"Auto Screenshot v1.0.0\") projectTitleLabel.config(font=fontRoboto,", "# License: MIT from pyscreenshot import grab from PIL import", "(int(cord_tuple[0]), int(cord_tuple[1]), int(cord_tuple[2]), int(cord_tuple[3])) # save first image img1 =", "from pyscreenshot import grab from PIL import ImageChops import os", "fontRoboto = font.Font(family='Roboto', size=16, weight='bold') # project name label projectTitleLabel", "fg=\"white\", bg=\"#f44336\", activebackground=\"#ff7043\", activeforeground=\"white\", font=fontRoboto) btn_start.pack(padx=\"10\", pady=\"10\", fill=BOTH) def start(self):", "images self.take_screenshots() def take_screenshots(self): # grab first and second image", "AutoScreenshot: def __init__(self, master): self.root = root root.title('Auto Screenshot') root.config(bg=\"white\")", "button btn_start = Button(root, text=\"Close\", command=self.close) btn_start.config(highlightthickness=0, bd=0, fg=\"white\", bg=\"#f44336\",", "Mani (Infinyte7) # Date: 26-10-2020 # License: MIT from pyscreenshot", "current session if not os.path.exists(self.new_folder): os.makedirs(self.new_folder) # Run ScreenCords.py and", "fg=\"white\", bg=\"#5fd38d\", activebackground=\"#5fd38d\", activeforeground=\"white\", font=fontRoboto) btn_start.pack(padx=\"10\", fill=BOTH) # close button", "all images to one folder if not os.path.exists(directory): os.makedirs(directory) #", "pyscreenshot import grab from PIL import ImageChops import os import", "print(\"Screenshot taken\") root.after(5, self.take_screenshots) def close(self): quit() if __name__ ==", "Author: Mani (Infinyte7) # Date: 26-10-2020 # License: MIT from", "MIT from pyscreenshot import grab from PIL import ImageChops import", "self.take_screenshots) def close(self): quit() if __name__ == \"__main__\": root =", "directory = \"Screenshots\" self.new_folder = directory + \"/\" + datetime.now().strftime(\"%Y_%m_%d-%I_%M_%p\")", "if not os.path.exists(self.new_folder): os.makedirs(self.new_folder) # Run ScreenCords.py and get cordinates", "= (int(cord_tuple[0]), int(cord_tuple[1]), int(cord_tuple[2]), int(cord_tuple[3])) # save first image img1", "font.Font(family='Roboto', size=16, weight='bold') # project name label projectTitleLabel = Label(root,", "img1 = grab(bbox=self.cords) time.sleep(1) img2 = grab(bbox=self.cords) # check difference", "grab from PIL import ImageChops import os import time import", "os import time import subprocess, sys from datetime import datetime", "and second image img1 = grab(bbox=self.cords) time.sleep(1) img2 = grab(bbox=self.cords)", "images directory = \"Screenshots\" self.new_folder = directory + \"/\" +", "first image img1 = grab(bbox=self.cords) now = datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\") fname =", "from tkinter import font class AutoScreenshot: def __init__(self, master): self.root", "(Infinyte7) # Date: 26-10-2020 # License: MIT from pyscreenshot import", "button btn_start = Button(root, text=\"Start\", command=self.start) btn_start.config(highlightthickness=0, bd=0, fg=\"white\", bg=\"#5fd38d\",", "btn_start.pack(padx=\"10\", fill=BOTH) # close button btn_start = Button(root, text=\"Close\", command=self.close)", "= grab(bbox=self.cords) now = datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\") fname = self.new_folder + \"/ScreenShots\"", "print(\"First Screenshot taken\") # start taking screenshot of next images", "not os.path.exists(self.new_folder): os.makedirs(self.new_folder) # Run ScreenCords.py and get cordinates cords_point", "# start button btn_start = Button(root, text=\"Start\", command=self.start) btn_start.config(highlightthickness=0, bd=0,", "Screenshot # Description: Take screenshot of screen when any change", "self.cords = (int(cord_tuple[0]), int(cord_tuple[1]), int(cord_tuple[2]), int(cord_tuple[3])) # save first image", "not os.path.exists(directory): os.makedirs(directory) # new folder for storing images for", "fname = self.new_folder + \"/ScreenShots\" + now + \".png\" img1.save(fname)", "= self.new_folder + \"/ScreenShots\" + now + \".png\" img1.save(fname) print(\"First", "# Project Name: Auto Screenshot # Description: Take screenshot of", "folder for storing images for current session if not os.path.exists(self.new_folder):", "second image img1 = grab(bbox=self.cords) time.sleep(1) img2 = grab(bbox=self.cords) #", "# Date: 26-10-2020 # License: MIT from pyscreenshot import grab", "storing images for current session if not os.path.exists(self.new_folder): os.makedirs(self.new_folder) #", "fg=\"#5599ff\") projectTitleLabel.pack(padx=\"10\") # start button btn_start = Button(root, text=\"Start\", command=self.start)", "image img1 = grab(bbox=self.cords) time.sleep(1) img2 = grab(bbox=self.cords) # check", "# cordinates for screenshots and compare self.cords = (int(cord_tuple[0]), int(cord_tuple[1]),", "Label(root, text=\"Auto Screenshot v1.0.0\") projectTitleLabel.config(font=fontRoboto, bg=\"white\", fg=\"#5599ff\") projectTitleLabel.pack(padx=\"10\") # start", "import tkinter as tk from tkinter import * from tkinter", "int(cord_tuple[2]), int(cord_tuple[3])) # save first image img1 = grab(bbox=self.cords) now", "cord_tuple = tuple(cords_point.decode(\"utf-8\").rstrip().split(\",\")) # cordinates for screenshots and compare self.cords", "bd=0, fg=\"white\", bg=\"#f44336\", activebackground=\"#ff7043\", activeforeground=\"white\", font=fontRoboto) btn_start.pack(padx=\"10\", pady=\"10\", fill=BOTH) def", "Auto Screenshot # Description: Take screenshot of screen when any", "Button(root, text=\"Close\", command=self.close) btn_start.config(highlightthickness=0, bd=0, fg=\"white\", bg=\"#f44336\", activebackground=\"#ff7043\", activeforeground=\"white\", font=fontRoboto)", "images diff = ImageChops.difference(img1, img2) bbox = diff.getbbox() if bbox", "img1 = grab(bbox=self.cords) now = datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\") fname = self.new_folder +", "for storing images for current session if not os.path.exists(self.new_folder): os.makedirs(self.new_folder)", "btn_start.config(highlightthickness=0, bd=0, fg=\"white\", bg=\"#5fd38d\", activebackground=\"#5fd38d\", activeforeground=\"white\", font=fontRoboto) btn_start.pack(padx=\"10\", fill=BOTH) #", "Screenshot taken\") # start taking screenshot of next images self.take_screenshots()", "# grab first and second image img1 = grab(bbox=self.cords) time.sleep(1)", "\"-l\"]) cord_tuple = tuple(cords_point.decode(\"utf-8\").rstrip().split(\",\")) # cordinates for screenshots and compare", "font class AutoScreenshot: def __init__(self, master): self.root = root root.title('Auto", "root.title('Auto Screenshot') root.config(bg=\"white\") fontRoboto = font.Font(family='Roboto', size=16, weight='bold') # project", "font=fontRoboto) btn_start.pack(padx=\"10\", pady=\"10\", fill=BOTH) def start(self): # Create folder to", "take_screenshots(self): # grab first and second image img1 = grab(bbox=self.cords)", "Name: Auto Screenshot # Description: Take screenshot of screen when", "as tk from tkinter import * from tkinter import font", "\"Screenshots\" self.new_folder = directory + \"/\" + datetime.now().strftime(\"%Y_%m_%d-%I_%M_%p\") # all", "= subprocess.check_output([sys.executable, \"GetScreenCoordinates.py\", \"-l\"]) cord_tuple = tuple(cords_point.decode(\"utf-8\").rstrip().split(\",\")) # cordinates for", "datetime import tkinter as tk from tkinter import * from", "compare self.cords = (int(cord_tuple[0]), int(cord_tuple[1]), int(cord_tuple[2]), int(cord_tuple[3])) # save first", "fname = self.new_folder + \"/ScreenShots\" + now + \".png\" img2.save(fname)", "root.config(bg=\"white\") fontRoboto = font.Font(family='Roboto', size=16, weight='bold') # project name label", "# Run ScreenCords.py and get cordinates cords_point = subprocess.check_output([sys.executable, \"GetScreenCoordinates.py\",", "activebackground=\"#5fd38d\", activeforeground=\"white\", font=fontRoboto) btn_start.pack(padx=\"10\", fill=BOTH) # close button btn_start =", "= diff.getbbox() if bbox is not None: now = datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\")", "get cordinates cords_point = subprocess.check_output([sys.executable, \"GetScreenCoordinates.py\", \"-l\"]) cord_tuple = tuple(cords_point.decode(\"utf-8\").rstrip().split(\",\"))", "cordinates cords_point = subprocess.check_output([sys.executable, \"GetScreenCoordinates.py\", \"-l\"]) cord_tuple = tuple(cords_point.decode(\"utf-8\").rstrip().split(\",\")) #", "close(self): quit() if __name__ == \"__main__\": root = Tk() gui", "tuple(cords_point.decode(\"utf-8\").rstrip().split(\",\")) # cordinates for screenshots and compare self.cords = (int(cord_tuple[0]),", "None: now = datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\") fname = self.new_folder + \"/ScreenShots\" +", "+ \"/ScreenShots\" + now + \".png\" img2.save(fname) print(\"Screenshot taken\") root.after(5,", "session if not os.path.exists(self.new_folder): os.makedirs(self.new_folder) # Run ScreenCords.py and get", "taken\") root.after(5, self.take_screenshots) def close(self): quit() if __name__ == \"__main__\":", "+ \".png\" img2.save(fname) print(\"Screenshot taken\") root.after(5, self.take_screenshots) def close(self): quit()", "btn_start = Button(root, text=\"Start\", command=self.start) btn_start.config(highlightthickness=0, bd=0, fg=\"white\", bg=\"#5fd38d\", activebackground=\"#5fd38d\",", "os.path.exists(directory): os.makedirs(directory) # new folder for storing images for current", "Description: Take screenshot of screen when any change take place.", "weight='bold') # project name label projectTitleLabel = Label(root, text=\"Auto Screenshot", "text=\"Auto Screenshot v1.0.0\") projectTitleLabel.config(font=fontRoboto, bg=\"white\", fg=\"#5599ff\") projectTitleLabel.pack(padx=\"10\") # start button", "\".png\" img2.save(fname) print(\"Screenshot taken\") root.after(5, self.take_screenshots) def close(self): quit() if", "tk from tkinter import * from tkinter import font class", "btn_start.config(highlightthickness=0, bd=0, fg=\"white\", bg=\"#f44336\", activebackground=\"#ff7043\", activeforeground=\"white\", font=fontRoboto) btn_start.pack(padx=\"10\", pady=\"10\", fill=BOTH)", "new folder for storing images for current session if not", "change take place. # Author: Mani (Infinyte7) # Date: 26-10-2020", "# all images to one folder if not os.path.exists(directory): os.makedirs(directory)", "is not None: now = datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\") fname = self.new_folder +", "activeforeground=\"white\", font=fontRoboto) btn_start.pack(padx=\"10\", pady=\"10\", fill=BOTH) def start(self): # Create folder", "Take screenshot of screen when any change take place. #", "# save first image img1 = grab(bbox=self.cords) now = datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\")", "import datetime import tkinter as tk from tkinter import *", "int(cord_tuple[1]), int(cord_tuple[2]), int(cord_tuple[3])) # save first image img1 = grab(bbox=self.cords)", "start button btn_start = Button(root, text=\"Start\", command=self.start) btn_start.config(highlightthickness=0, bd=0, fg=\"white\",", "text=\"Close\", command=self.close) btn_start.config(highlightthickness=0, bd=0, fg=\"white\", bg=\"#f44336\", activebackground=\"#ff7043\", activeforeground=\"white\", font=fontRoboto) btn_start.pack(padx=\"10\",", "bg=\"#5fd38d\", activebackground=\"#5fd38d\", activeforeground=\"white\", font=fontRoboto) btn_start.pack(padx=\"10\", fill=BOTH) # close button btn_start", "images for current session if not os.path.exists(self.new_folder): os.makedirs(self.new_folder) # Run", "= datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\") fname = self.new_folder + \"/ScreenShots\" + now +", "os.makedirs(self.new_folder) # Run ScreenCords.py and get cordinates cords_point = subprocess.check_output([sys.executable,", "datetime.now().strftime(\"%Y_%m_%d-%I_%M_%p\") # all images to one folder if not os.path.exists(directory):", "import os import time import subprocess, sys from datetime import", "to store images directory = \"Screenshots\" self.new_folder = directory +", "pady=\"10\", fill=BOTH) def start(self): # Create folder to store images", "master): self.root = root root.title('Auto Screenshot') root.config(bg=\"white\") fontRoboto = font.Font(family='Roboto',", "Create folder to store images directory = \"Screenshots\" self.new_folder =", "if not os.path.exists(directory): os.makedirs(directory) # new folder for storing images", "img2.save(fname) print(\"Screenshot taken\") root.after(5, self.take_screenshots) def close(self): quit() if __name__", "difference between images diff = ImageChops.difference(img1, img2) bbox = diff.getbbox()", "Button(root, text=\"Start\", command=self.start) btn_start.config(highlightthickness=0, bd=0, fg=\"white\", bg=\"#5fd38d\", activebackground=\"#5fd38d\", activeforeground=\"white\", font=fontRoboto)", "projectTitleLabel = Label(root, text=\"Auto Screenshot v1.0.0\") projectTitleLabel.config(font=fontRoboto, bg=\"white\", fg=\"#5599ff\") projectTitleLabel.pack(padx=\"10\")", "btn_start = Button(root, text=\"Close\", command=self.close) btn_start.config(highlightthickness=0, bd=0, fg=\"white\", bg=\"#f44336\", activebackground=\"#ff7043\",", "ImageChops.difference(img1, img2) bbox = diff.getbbox() if bbox is not None:", "grab(bbox=self.cords) time.sleep(1) img2 = grab(bbox=self.cords) # check difference between images", "tkinter import font class AutoScreenshot: def __init__(self, master): self.root =", "Screenshot v1.0.0\") projectTitleLabel.config(font=fontRoboto, bg=\"white\", fg=\"#5599ff\") projectTitleLabel.pack(padx=\"10\") # start button btn_start", "to one folder if not os.path.exists(directory): os.makedirs(directory) # new folder", "+ \"/ScreenShots\" + now + \".png\" img1.save(fname) print(\"First Screenshot taken\")", "diff.getbbox() if bbox is not None: now = datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\") fname", "projectTitleLabel.pack(padx=\"10\") # start button btn_start = Button(root, text=\"Start\", command=self.start) btn_start.config(highlightthickness=0,", "def close(self): quit() if __name__ == \"__main__\": root = Tk()", "images to one folder if not os.path.exists(directory): os.makedirs(directory) # new", "# new folder for storing images for current session if", "fill=BOTH) def start(self): # Create folder to store images directory", "+ datetime.now().strftime(\"%Y_%m_%d-%I_%M_%p\") # all images to one folder if not", "Date: 26-10-2020 # License: MIT from pyscreenshot import grab from", "img1.save(fname) print(\"First Screenshot taken\") # start taking screenshot of next", "text=\"Start\", command=self.start) btn_start.config(highlightthickness=0, bd=0, fg=\"white\", bg=\"#5fd38d\", activebackground=\"#5fd38d\", activeforeground=\"white\", font=fontRoboto) btn_start.pack(padx=\"10\",", "root.after(5, self.take_screenshots) def close(self): quit() if __name__ == \"__main__\": root", "subprocess.check_output([sys.executable, \"GetScreenCoordinates.py\", \"-l\"]) cord_tuple = tuple(cords_point.decode(\"utf-8\").rstrip().split(\",\")) # cordinates for screenshots", "fill=BOTH) # close button btn_start = Button(root, text=\"Close\", command=self.close) btn_start.config(highlightthickness=0,", "taking screenshot of next images self.take_screenshots() def take_screenshots(self): # grab", "= directory + \"/\" + datetime.now().strftime(\"%Y_%m_%d-%I_%M_%p\") # all images to", "Project Name: Auto Screenshot # Description: Take screenshot of screen", "26-10-2020 # License: MIT from pyscreenshot import grab from PIL", "bd=0, fg=\"white\", bg=\"#5fd38d\", activebackground=\"#5fd38d\", activeforeground=\"white\", font=fontRoboto) btn_start.pack(padx=\"10\", fill=BOTH) # close", "now = datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\") fname = self.new_folder + \"/ScreenShots\" + now", "__init__(self, master): self.root = root root.title('Auto Screenshot') root.config(bg=\"white\") fontRoboto =", "image img1 = grab(bbox=self.cords) now = datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\") fname = self.new_folder", "def __init__(self, master): self.root = root root.title('Auto Screenshot') root.config(bg=\"white\") fontRoboto", "def start(self): # Create folder to store images directory =", "when any change take place. # Author: Mani (Infinyte7) #", "now + \".png\" img2.save(fname) print(\"Screenshot taken\") root.after(5, self.take_screenshots) def close(self):", "now + \".png\" img1.save(fname) print(\"First Screenshot taken\") # start taking", "# close button btn_start = Button(root, text=\"Close\", command=self.close) btn_start.config(highlightthickness=0, bd=0,", "grab first and second image img1 = grab(bbox=self.cords) time.sleep(1) img2", "int(cord_tuple[3])) # save first image img1 = grab(bbox=self.cords) now =", "grab(bbox=self.cords) now = datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\") fname = self.new_folder + \"/ScreenShots\" +", "root root.title('Auto Screenshot') root.config(bg=\"white\") fontRoboto = font.Font(family='Roboto', size=16, weight='bold') #", "= tuple(cords_point.decode(\"utf-8\").rstrip().split(\",\")) # cordinates for screenshots and compare self.cords =", "command=self.start) btn_start.config(highlightthickness=0, bd=0, fg=\"white\", bg=\"#5fd38d\", activebackground=\"#5fd38d\", activeforeground=\"white\", font=fontRoboto) btn_start.pack(padx=\"10\", fill=BOTH)", "screenshot of next images self.take_screenshots() def take_screenshots(self): # grab first", "= Button(root, text=\"Start\", command=self.start) btn_start.config(highlightthickness=0, bd=0, fg=\"white\", bg=\"#5fd38d\", activebackground=\"#5fd38d\", activeforeground=\"white\",", "cords_point = subprocess.check_output([sys.executable, \"GetScreenCoordinates.py\", \"-l\"]) cord_tuple = tuple(cords_point.decode(\"utf-8\").rstrip().split(\",\")) # cordinates", "import * from tkinter import font class AutoScreenshot: def __init__(self,", "import font class AutoScreenshot: def __init__(self, master): self.root = root", "from tkinter import * from tkinter import font class AutoScreenshot:", "PIL import ImageChops import os import time import subprocess, sys", "v1.0.0\") projectTitleLabel.config(font=fontRoboto, bg=\"white\", fg=\"#5599ff\") projectTitleLabel.pack(padx=\"10\") # start button btn_start =", "for current session if not os.path.exists(self.new_folder): os.makedirs(self.new_folder) # Run ScreenCords.py", "datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\") fname = self.new_folder + \"/ScreenShots\" + now + \".png\"", "between images diff = ImageChops.difference(img1, img2) bbox = diff.getbbox() if", "= grab(bbox=self.cords) # check difference between images diff = ImageChops.difference(img1,", "# start taking screenshot of next images self.take_screenshots() def take_screenshots(self):", "take place. # Author: Mani (Infinyte7) # Date: 26-10-2020 #", "def take_screenshots(self): # grab first and second image img1 =", "img2 = grab(bbox=self.cords) # check difference between images diff =", "= root root.title('Auto Screenshot') root.config(bg=\"white\") fontRoboto = font.Font(family='Roboto', size=16, weight='bold')", "License: MIT from pyscreenshot import grab from PIL import ImageChops", "subprocess, sys from datetime import datetime import tkinter as tk", "tkinter as tk from tkinter import * from tkinter import", "cordinates for screenshots and compare self.cords = (int(cord_tuple[0]), int(cord_tuple[1]), int(cord_tuple[2]),", "+ \".png\" img1.save(fname) print(\"First Screenshot taken\") # start taking screenshot", "from datetime import datetime import tkinter as tk from tkinter", "# check difference between images diff = ImageChops.difference(img1, img2) bbox", "\"/ScreenShots\" + now + \".png\" img2.save(fname) print(\"Screenshot taken\") root.after(5, self.take_screenshots)", "screen when any change take place. # Author: Mani (Infinyte7)", "and compare self.cords = (int(cord_tuple[0]), int(cord_tuple[1]), int(cord_tuple[2]), int(cord_tuple[3])) # save", "save first image img1 = grab(bbox=self.cords) now = datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\") fname", "of next images self.take_screenshots() def take_screenshots(self): # grab first and", "\".png\" img1.save(fname) print(\"First Screenshot taken\") # start taking screenshot of", "if __name__ == \"__main__\": root = Tk() gui = AutoScreenshot(root)", "tkinter import * from tkinter import font class AutoScreenshot: def", "Screenshot') root.config(bg=\"white\") fontRoboto = font.Font(family='Roboto', size=16, weight='bold') # project name", "activeforeground=\"white\", font=fontRoboto) btn_start.pack(padx=\"10\", fill=BOTH) # close button btn_start = Button(root,", "font=fontRoboto) btn_start.pack(padx=\"10\", fill=BOTH) # close button btn_start = Button(root, text=\"Close\",", "\"GetScreenCoordinates.py\", \"-l\"]) cord_tuple = tuple(cords_point.decode(\"utf-8\").rstrip().split(\",\")) # cordinates for screenshots and", "grab(bbox=self.cords) # check difference between images diff = ImageChops.difference(img1, img2)", "datetime import datetime import tkinter as tk from tkinter import", "btn_start.pack(padx=\"10\", pady=\"10\", fill=BOTH) def start(self): # Create folder to store", "self.new_folder + \"/ScreenShots\" + now + \".png\" img2.save(fname) print(\"Screenshot taken\")", "self.new_folder + \"/ScreenShots\" + now + \".png\" img1.save(fname) print(\"First Screenshot", "self.root = root root.title('Auto Screenshot') root.config(bg=\"white\") fontRoboto = font.Font(family='Roboto', size=16,", "= ImageChops.difference(img1, img2) bbox = diff.getbbox() if bbox is not", "ImageChops import os import time import subprocess, sys from datetime", "# project name label projectTitleLabel = Label(root, text=\"Auto Screenshot v1.0.0\")", "place. # Author: Mani (Infinyte7) # Date: 26-10-2020 # License:", "sys from datetime import datetime import tkinter as tk from", "first and second image img1 = grab(bbox=self.cords) time.sleep(1) img2 =", "folder if not os.path.exists(directory): os.makedirs(directory) # new folder for storing", "import subprocess, sys from datetime import datetime import tkinter as", "time import subprocess, sys from datetime import datetime import tkinter", "img2) bbox = diff.getbbox() if bbox is not None: now", "__name__ == \"__main__\": root = Tk() gui = AutoScreenshot(root) root.mainloop()", "# Create folder to store images directory = \"Screenshots\" self.new_folder", "not None: now = datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\") fname = self.new_folder + \"/ScreenShots\"", "projectTitleLabel.config(font=fontRoboto, bg=\"white\", fg=\"#5599ff\") projectTitleLabel.pack(padx=\"10\") # start button btn_start = Button(root,", "any change take place. # Author: Mani (Infinyte7) # Date:", "if bbox is not None: now = datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\") fname =", "# Description: Take screenshot of screen when any change take", "# Author: Mani (Infinyte7) # Date: 26-10-2020 # License: MIT", "= Button(root, text=\"Close\", command=self.close) btn_start.config(highlightthickness=0, bd=0, fg=\"white\", bg=\"#f44336\", activebackground=\"#ff7043\", activeforeground=\"white\",", "check difference between images diff = ImageChops.difference(img1, img2) bbox =", "and get cordinates cords_point = subprocess.check_output([sys.executable, \"GetScreenCoordinates.py\", \"-l\"]) cord_tuple =", "import time import subprocess, sys from datetime import datetime import", "folder to store images directory = \"Screenshots\" self.new_folder = directory", "+ \"/\" + datetime.now().strftime(\"%Y_%m_%d-%I_%M_%p\") # all images to one folder", "activebackground=\"#ff7043\", activeforeground=\"white\", font=fontRoboto) btn_start.pack(padx=\"10\", pady=\"10\", fill=BOTH) def start(self): # Create", "* from tkinter import font class AutoScreenshot: def __init__(self, master):", "self.new_folder = directory + \"/\" + datetime.now().strftime(\"%Y_%m_%d-%I_%M_%p\") # all images", "name label projectTitleLabel = Label(root, text=\"Auto Screenshot v1.0.0\") projectTitleLabel.config(font=fontRoboto, bg=\"white\",", "screenshots and compare self.cords = (int(cord_tuple[0]), int(cord_tuple[1]), int(cord_tuple[2]), int(cord_tuple[3])) #", "bbox is not None: now = datetime.now().strftime(\"%Y_%m_%d-%I_%M_%S_%p\") fname = self.new_folder", "os.path.exists(self.new_folder): os.makedirs(self.new_folder) # Run ScreenCords.py and get cordinates cords_point =", "next images self.take_screenshots() def take_screenshots(self): # grab first and second", "= self.new_folder + \"/ScreenShots\" + now + \".png\" img2.save(fname) print(\"Screenshot", "self.take_screenshots() def take_screenshots(self): # grab first and second image img1", "for screenshots and compare self.cords = (int(cord_tuple[0]), int(cord_tuple[1]), int(cord_tuple[2]), int(cord_tuple[3]))", "= \"Screenshots\" self.new_folder = directory + \"/\" + datetime.now().strftime(\"%Y_%m_%d-%I_%M_%p\") #", "directory + \"/\" + datetime.now().strftime(\"%Y_%m_%d-%I_%M_%p\") # all images to one", "= Label(root, text=\"Auto Screenshot v1.0.0\") projectTitleLabel.config(font=fontRoboto, bg=\"white\", fg=\"#5599ff\") projectTitleLabel.pack(padx=\"10\") #", "+ now + \".png\" img1.save(fname) print(\"First Screenshot taken\") # start", "+ now + \".png\" img2.save(fname) print(\"Screenshot taken\") root.after(5, self.take_screenshots) def", "import ImageChops import os import time import subprocess, sys from" ]
[ "= Logger(\"user_system_log\") # 用于用户异常的详细日志打印 user_detail_log = Logger(\"user_detail_log\") # user_detail_log.handlers.append(StderrHandler(bubble=True)) #", "dt = Environment.get_instance().calendar_dt.strftime(DATETIME_FORMAT) except Exception: dt = datetime.now().strftime(DATETIME_FORMAT) log =", "[] user_system_log.handlers = [] def user_print(*args, **kwargs): sep = kwargs.get(\"sep\",", "License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。 # 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”不变,且不得附加任何条件。 #", "end = kwargs.get(\"end\", \"\") message = sep.join(map(str, args)) + end", "msg=to_utf8(record.message), time=record.time, ) if record.formatted_exception: log += \"\\n\" + record.formatted_exception", ") return log user_std_handler = StderrHandler(bubble=True) user_std_handler.formatter = user_std_handler_log_formatter def", "record.formatted_exception: log += \"\\n\" + record.formatted_exception return log return formatter", "user_std_handler_log_formatter def formatter_builder(tag): def formatter(record, handler): log = \"[{formatter_tag}] [{time}]", "Environment.get_instance().calendar_dt.strftime(DATETIME_FORMAT) except Exception: dt = datetime.now().strftime(DATETIME_FORMAT) log = \"{dt} {level}", "2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。 # 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”不变,且不得附加任何条件。 # # * 商业用途(商业用途指个人出于任何商业目的使用本软件,或者法人或其他组织出于任何目的使用本软件): # 未经米筐科技授权,任何个人不得出于任何商业目的使用本软件(包括但不限于向第三方提供、销售、出租、出借、转让本软件、本软件的衍生产品、引用或借鉴了本软件功能或源代码的产品或服务),任何法人或其他组织不得出于任何目的使用本软件,否则米筐科技有权追究相应的知识产权侵权责任。", "user_system_log = Logger(\"user_system_log\") # 用于用户异常的详细日志打印 user_detail_log = Logger(\"user_detail_log\") # user_detail_log.handlers.append(StderrHandler(bubble=True))", "std_log = Logger(\"std_log\") def init_logger(): system_log.handlers = [StderrHandler(bubble=True)] basic_system_log.handlers =", "from logbook import Logger, StderrHandler from rqalpha.utils.py2 import to_utf8 logbook.set_datetime_format(\"local\")", "2.0 许可与本许可冲突之处,以本许可为准。 # 详细的授权流程,请联系 <EMAIL> 获取。 from datetime import datetime", "{level} {msg}\".format( dt=dt, level=record.level_name, msg=to_utf8(record.message), ) return log user_std_handler =", "from rqalpha.environment import Environment try: dt = Environment.get_instance().calendar_dt.strftime(DATETIME_FORMAT) except Exception:", "Apache License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。 # 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”不变,且不得附加任何条件。", "import Environment try: dt = Environment.get_instance().calendar_dt.strftime(DATETIME_FORMAT) except Exception: dt =", "return formatter # loggers # 用户代码logger日志 user_log = Logger(\"user_log\") #", "Logger(\"std_log\") def init_logger(): system_log.handlers = [StderrHandler(bubble=True)] basic_system_log.handlers = [StderrHandler(bubble=True)] std_log.handlers", "user_print(*args, **kwargs): sep = kwargs.get(\"sep\", \" \") end = kwargs.get(\"end\",", "'WARN' __all__ = [ \"user_log\", \"system_log\", \"user_system_log\", ] DATETIME_FORMAT =", "= user_std_handler_log_formatter def formatter_builder(tag): def formatter(record, handler): log = \"[{formatter_tag}]", "system_log.handlers = [StderrHandler(bubble=True)] basic_system_log.handlers = [StderrHandler(bubble=True)] std_log.handlers = [StderrHandler(bubble=True)] user_log.handlers", "{msg}\".format( formatter_tag=tag, level=record.level_name, msg=to_utf8(record.message), time=record.time, ) if record.formatted_exception: log +=", "import to_utf8 logbook.set_datetime_format(\"local\") # patch warn logbook.base._level_names[logbook.base.WARNING] = 'WARN' __all__", "level=record.level_name, msg=to_utf8(record.message), ) return log user_std_handler = StderrHandler(bubble=True) user_std_handler.formatter =", "# 未经米筐科技授权,任何个人不得出于任何商业目的使用本软件(包括但不限于向第三方提供、销售、出租、出借、转让本软件、本软件的衍生产品、引用或借鉴了本软件功能或源代码的产品或服务),任何法人或其他组织不得出于任何目的使用本软件,否则米筐科技有权追究相应的知识产权侵权责任。 # 在此前提下,对本软件的使用同样需要遵守 Apache 2.0 许可,Apache 2.0 许可与本许可冲突之处,以本许可为准。 #", "formatter_builder(tag): def formatter(record, handler): log = \"[{formatter_tag}] [{time}] {level}: {msg}\".format(", "# 在此前提下,对本软件的使用同样需要遵守 Apache 2.0 许可,Apache 2.0 许可与本许可冲突之处,以本许可为准。 # 详细的授权流程,请联系 <EMAIL>", "# 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”) # # 除非遵守当前许可,否则不得使用本软件。 # # *", "\" \") end = kwargs.get(\"end\", \"\") message = sep.join(map(str, args))", "log = \"[{formatter_tag}] [{time}] {level}: {msg}\".format( formatter_tag=tag, level=record.level_name, msg=to_utf8(record.message), time=record.time,", "def formatter(record, handler): log = \"[{formatter_tag}] [{time}] {level}: {msg}\".format( formatter_tag=tag,", "%H:%M:%S.%f\" def user_std_handler_log_formatter(record, handler): from rqalpha.environment import Environment try: dt", "rqalpha.utils.py2 import to_utf8 logbook.set_datetime_format(\"local\") # patch warn logbook.base._level_names[logbook.base.WARNING] = 'WARN'", "# * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件): # 遵守 Apache License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得", "user_detail_log = Logger(\"user_detail_log\") # user_detail_log.handlers.append(StderrHandler(bubble=True)) # 系统日志 system_log = Logger(\"system_log\")", "user_std_handler.formatter = user_std_handler_log_formatter def formatter_builder(tag): def formatter(record, handler): log =", "-*- # 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”) # # 除非遵守当前许可,否则不得使用本软件。 # #", "user_system_log.handlers = [] def user_print(*args, **kwargs): sep = kwargs.get(\"sep\", \"", "warn logbook.base._level_names[logbook.base.WARNING] = 'WARN' __all__ = [ \"user_log\", \"system_log\", \"user_system_log\",", "datetime import logbook from logbook import Logger, StderrHandler from rqalpha.utils.py2", "std_log.handlers = [StderrHandler(bubble=True)] user_log.handlers = [] user_system_log.handlers = [] def", "= 'WARN' __all__ = [ \"user_log\", \"system_log\", \"user_system_log\", ] DATETIME_FORMAT", "Environment try: dt = Environment.get_instance().calendar_dt.strftime(DATETIME_FORMAT) except Exception: dt = datetime.now().strftime(DATETIME_FORMAT)", "= Environment.get_instance().calendar_dt.strftime(DATETIME_FORMAT) except Exception: dt = datetime.now().strftime(DATETIME_FORMAT) log = \"{dt}", "# 遵守 Apache License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。", "dt=dt, level=record.level_name, msg=to_utf8(record.message), ) return log user_std_handler = StderrHandler(bubble=True) user_std_handler.formatter", "除非遵守当前许可,否则不得使用本软件。 # # * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件): # 遵守 Apache License 2.0(下称“Apache", "formatter(record, handler): log = \"[{formatter_tag}] [{time}] {level}: {msg}\".format( formatter_tag=tag, level=record.level_name,", "-*- coding: utf-8 -*- # 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”) # #", "= [StderrHandler(bubble=True)] std_log.handlers = [StderrHandler(bubble=True)] user_log.handlers = [] user_system_log.handlers =", "= \"%Y-%m-%d %H:%M:%S.%f\" def user_std_handler_log_formatter(record, handler): from rqalpha.environment import Environment", "= \"[{formatter_tag}] [{time}] {level}: {msg}\".format( formatter_tag=tag, level=record.level_name, msg=to_utf8(record.message), time=record.time, )", "2019 深圳米筐科技有限公司(下称“米筐科技”) # # 除非遵守当前许可,否则不得使用本软件。 # # * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件): #", "basic_system_log.handlers = [StderrHandler(bubble=True)] std_log.handlers = [StderrHandler(bubble=True)] user_log.handlers = [] user_system_log.handlers", "**kwargs): sep = kwargs.get(\"sep\", \" \") end = kwargs.get(\"end\", \"\")", "__all__ = [ \"user_log\", \"system_log\", \"user_system_log\", ] DATETIME_FORMAT = \"%Y-%m-%d", "\"\\n\" + record.formatted_exception return log return formatter # loggers #", "coding: utf-8 -*- # 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”) # # 除非遵守当前许可,否则不得使用本软件。", "kwargs.get(\"end\", \"\") message = sep.join(map(str, args)) + end user_log.info(message) init_logger()", "utf-8 -*- # 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”) # # 除非遵守当前许可,否则不得使用本软件。 #", "# 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”不变,且不得附加任何条件。 # # * 商业用途(商业用途指个人出于任何商业目的使用本软件,或者法人或其他组织出于任何目的使用本软件): # 未经米筐科技授权,任何个人不得出于任何商业目的使用本软件(包括但不限于向第三方提供、销售、出租、出借、转让本软件、本软件的衍生产品、引用或借鉴了本软件功能或源代码的产品或服务),任何法人或其他组织不得出于任何目的使用本软件,否则米筐科技有权追究相应的知识产权侵权责任。 # 在此前提下,对本软件的使用同样需要遵守", "msg=to_utf8(record.message), ) return log user_std_handler = StderrHandler(bubble=True) user_std_handler.formatter = user_std_handler_log_formatter", "log += \"\\n\" + record.formatted_exception return log return formatter #", "log = \"{dt} {level} {msg}\".format( dt=dt, level=record.level_name, msg=to_utf8(record.message), ) return", "标准输出日志 std_log = Logger(\"std_log\") def init_logger(): system_log.handlers = [StderrHandler(bubble=True)] basic_system_log.handlers", "\"%Y-%m-%d %H:%M:%S.%f\" def user_std_handler_log_formatter(record, handler): from rqalpha.environment import Environment try:", "# -*- coding: utf-8 -*- # 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”) #", "* 商业用途(商业用途指个人出于任何商业目的使用本软件,或者法人或其他组织出于任何目的使用本软件): # 未经米筐科技授权,任何个人不得出于任何商业目的使用本软件(包括但不限于向第三方提供、销售、出租、出借、转让本软件、本软件的衍生产品、引用或借鉴了本软件功能或源代码的产品或服务),任何法人或其他组织不得出于任何目的使用本软件,否则米筐科技有权追究相应的知识产权侵权责任。 # 在此前提下,对本软件的使用同样需要遵守 Apache 2.0 许可,Apache 2.0", "\"{dt} {level} {msg}\".format( dt=dt, level=record.level_name, msg=to_utf8(record.message), ) return log user_std_handler", "return log return formatter # loggers # 用户代码logger日志 user_log =", "用户代码logger日志 user_log = Logger(\"user_log\") # 给用户看的系统日志 user_system_log = Logger(\"user_system_log\") #", "= Logger(\"user_detail_log\") # user_detail_log.handlers.append(StderrHandler(bubble=True)) # 系统日志 system_log = Logger(\"system_log\") basic_system_log", "Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。 # 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”不变,且不得附加任何条件。 # # * 商业用途(商业用途指个人出于任何商业目的使用本软件,或者法人或其他组织出于任何目的使用本软件): #", "logbook import Logger, StderrHandler from rqalpha.utils.py2 import to_utf8 logbook.set_datetime_format(\"local\") #", "user_std_handler_log_formatter(record, handler): from rqalpha.environment import Environment try: dt = Environment.get_instance().calendar_dt.strftime(DATETIME_FORMAT)", "except Exception: dt = datetime.now().strftime(DATETIME_FORMAT) log = \"{dt} {level} {msg}\".format(", "{level}: {msg}\".format( formatter_tag=tag, level=record.level_name, msg=to_utf8(record.message), time=record.time, ) if record.formatted_exception: log", "rqalpha.environment import Environment try: dt = Environment.get_instance().calendar_dt.strftime(DATETIME_FORMAT) except Exception: dt", "许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。 # 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”不变,且不得附加任何条件。 # # * 商业用途(商业用途指个人出于任何商业目的使用本软件,或者法人或其他组织出于任何目的使用本软件):", "= kwargs.get(\"end\", \"\") message = sep.join(map(str, args)) + end user_log.info(message)", "def user_std_handler_log_formatter(record, handler): from rqalpha.environment import Environment try: dt =", "= [StderrHandler(bubble=True)] basic_system_log.handlers = [StderrHandler(bubble=True)] std_log.handlers = [StderrHandler(bubble=True)] user_log.handlers =", "Logger(\"user_log\") # 给用户看的系统日志 user_system_log = Logger(\"user_system_log\") # 用于用户异常的详细日志打印 user_detail_log =", "return log user_std_handler = StderrHandler(bubble=True) user_std_handler.formatter = user_std_handler_log_formatter def formatter_builder(tag):", "if record.formatted_exception: log += \"\\n\" + record.formatted_exception return log return", "= [] def user_print(*args, **kwargs): sep = kwargs.get(\"sep\", \" \")", ") if record.formatted_exception: log += \"\\n\" + record.formatted_exception return log", "formatter_tag=tag, level=record.level_name, msg=to_utf8(record.message), time=record.time, ) if record.formatted_exception: log += \"\\n\"", "# # * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件): # 遵守 Apache License 2.0(下称“Apache 2.0", "def formatter_builder(tag): def formatter(record, handler): log = \"[{formatter_tag}] [{time}] {level}:", "= StderrHandler(bubble=True) user_std_handler.formatter = user_std_handler_log_formatter def formatter_builder(tag): def formatter(record, handler):", "= Logger(\"system_log\") basic_system_log = Logger(\"basic_system_log\") # 标准输出日志 std_log = Logger(\"std_log\")", "获取。 from datetime import datetime import logbook from logbook import", "from datetime import datetime import logbook from logbook import Logger,", "# * 商业用途(商业用途指个人出于任何商业目的使用本软件,或者法人或其他组织出于任何目的使用本软件): # 未经米筐科技授权,任何个人不得出于任何商业目的使用本软件(包括但不限于向第三方提供、销售、出租、出借、转让本软件、本软件的衍生产品、引用或借鉴了本软件功能或源代码的产品或服务),任何法人或其他组织不得出于任何目的使用本软件,否则米筐科技有权追究相应的知识产权侵权责任。 # 在此前提下,对本软件的使用同样需要遵守 Apache 2.0 许可,Apache", "import logbook from logbook import Logger, StderrHandler from rqalpha.utils.py2 import", "StderrHandler from rqalpha.utils.py2 import to_utf8 logbook.set_datetime_format(\"local\") # patch warn logbook.base._level_names[logbook.base.WARNING]", "to_utf8 logbook.set_datetime_format(\"local\") # patch warn logbook.base._level_names[logbook.base.WARNING] = 'WARN' __all__ =", "# 用于用户异常的详细日志打印 user_detail_log = Logger(\"user_detail_log\") # user_detail_log.handlers.append(StderrHandler(bubble=True)) # 系统日志 system_log", "+= \"\\n\" + record.formatted_exception return log return formatter # loggers", "用于用户异常的详细日志打印 user_detail_log = Logger(\"user_detail_log\") # user_detail_log.handlers.append(StderrHandler(bubble=True)) # 系统日志 system_log =", "# 系统日志 system_log = Logger(\"system_log\") basic_system_log = Logger(\"basic_system_log\") # 标准输出日志", "= kwargs.get(\"sep\", \" \") end = kwargs.get(\"end\", \"\") message =", "<EMAIL> 获取。 from datetime import datetime import logbook from logbook", "# # * 商业用途(商业用途指个人出于任何商业目的使用本软件,或者法人或其他组织出于任何目的使用本软件): # 未经米筐科技授权,任何个人不得出于任何商业目的使用本软件(包括但不限于向第三方提供、销售、出租、出借、转让本软件、本软件的衍生产品、引用或借鉴了本软件功能或源代码的产品或服务),任何法人或其他组织不得出于任何目的使用本软件,否则米筐科技有权追究相应的知识产权侵权责任。 # 在此前提下,对本软件的使用同样需要遵守 Apache 2.0", "# 详细的授权流程,请联系 <EMAIL> 获取。 from datetime import datetime import logbook", "[StderrHandler(bubble=True)] basic_system_log.handlers = [StderrHandler(bubble=True)] std_log.handlers = [StderrHandler(bubble=True)] user_log.handlers = []", "版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”) # # 除非遵守当前许可,否则不得使用本软件。 # # * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件):", "\"user_system_log\", ] DATETIME_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\" def user_std_handler_log_formatter(record, handler): from", "Exception: dt = datetime.now().strftime(DATETIME_FORMAT) log = \"{dt} {level} {msg}\".format( dt=dt,", "\"user_log\", \"system_log\", \"user_system_log\", ] DATETIME_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\" def user_std_handler_log_formatter(record,", "= datetime.now().strftime(DATETIME_FORMAT) log = \"{dt} {level} {msg}\".format( dt=dt, level=record.level_name, msg=to_utf8(record.message),", "<reponame>HaidongHe/rqalpha # -*- coding: utf-8 -*- # 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”)", "非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件): # 遵守 Apache License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache 2.0", "给用户看的系统日志 user_system_log = Logger(\"user_system_log\") # 用于用户异常的详细日志打印 user_detail_log = Logger(\"user_detail_log\") #", "user_std_handler = StderrHandler(bubble=True) user_std_handler.formatter = user_std_handler_log_formatter def formatter_builder(tag): def formatter(record,", "handler): log = \"[{formatter_tag}] [{time}] {level}: {msg}\".format( formatter_tag=tag, level=record.level_name, msg=to_utf8(record.message),", "2.0 许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。 # 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”不变,且不得附加任何条件。 # # *", "= Logger(\"user_log\") # 给用户看的系统日志 user_system_log = Logger(\"user_system_log\") # 用于用户异常的详细日志打印 user_detail_log", "Logger(\"basic_system_log\") # 标准输出日志 std_log = Logger(\"std_log\") def init_logger(): system_log.handlers =", "未经米筐科技授权,任何个人不得出于任何商业目的使用本软件(包括但不限于向第三方提供、销售、出租、出借、转让本软件、本软件的衍生产品、引用或借鉴了本软件功能或源代码的产品或服务),任何法人或其他组织不得出于任何目的使用本软件,否则米筐科技有权追究相应的知识产权侵权责任。 # 在此前提下,对本软件的使用同样需要遵守 Apache 2.0 许可,Apache 2.0 许可与本许可冲突之处,以本许可为准。 # 详细的授权流程,请联系", "\"[{formatter_tag}] [{time}] {level}: {msg}\".format( formatter_tag=tag, level=record.level_name, msg=to_utf8(record.message), time=record.time, ) if", "time=record.time, ) if record.formatted_exception: log += \"\\n\" + record.formatted_exception return", "loggers # 用户代码logger日志 user_log = Logger(\"user_log\") # 给用户看的系统日志 user_system_log =", "\") end = kwargs.get(\"end\", \"\") message = sep.join(map(str, args)) +", "# loggers # 用户代码logger日志 user_log = Logger(\"user_log\") # 给用户看的系统日志 user_system_log", "StderrHandler(bubble=True) user_std_handler.formatter = user_std_handler_log_formatter def formatter_builder(tag): def formatter(record, handler): log", "basic_system_log = Logger(\"basic_system_log\") # 标准输出日志 std_log = Logger(\"std_log\") def init_logger():", "def user_print(*args, **kwargs): sep = kwargs.get(\"sep\", \" \") end =", "Logger(\"user_detail_log\") # user_detail_log.handlers.append(StderrHandler(bubble=True)) # 系统日志 system_log = Logger(\"system_log\") basic_system_log =", "try: dt = Environment.get_instance().calendar_dt.strftime(DATETIME_FORMAT) except Exception: dt = datetime.now().strftime(DATETIME_FORMAT) log", "详细的授权流程,请联系 <EMAIL> 获取。 from datetime import datetime import logbook from", "商业用途(商业用途指个人出于任何商业目的使用本软件,或者法人或其他组织出于任何目的使用本软件): # 未经米筐科技授权,任何个人不得出于任何商业目的使用本软件(包括但不限于向第三方提供、销售、出租、出借、转让本软件、本软件的衍生产品、引用或借鉴了本软件功能或源代码的产品或服务),任何法人或其他组织不得出于任何目的使用本软件,否则米筐科技有权追究相应的知识产权侵权责任。 # 在此前提下,对本软件的使用同样需要遵守 Apache 2.0 许可,Apache 2.0 许可与本许可冲突之处,以本许可为准。", "DATETIME_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\" def user_std_handler_log_formatter(record, handler): from rqalpha.environment import", "# patch warn logbook.base._level_names[logbook.base.WARNING] = 'WARN' __all__ = [ \"user_log\",", "+ record.formatted_exception return log return formatter # loggers # 用户代码logger日志", "除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”不变,且不得附加任何条件。 # # * 商业用途(商业用途指个人出于任何商业目的使用本软件,或者法人或其他组织出于任何目的使用本软件): # 未经米筐科技授权,任何个人不得出于任何商业目的使用本软件(包括但不限于向第三方提供、销售、出租、出借、转让本软件、本软件的衍生产品、引用或借鉴了本软件功能或源代码的产品或服务),任何法人或其他组织不得出于任何目的使用本软件,否则米筐科技有权追究相应的知识产权侵权责任。 # 在此前提下,对本软件的使用同样需要遵守 Apache", "# 给用户看的系统日志 user_system_log = Logger(\"user_system_log\") # 用于用户异常的详细日志打印 user_detail_log = Logger(\"user_detail_log\")", "= Logger(\"basic_system_log\") # 标准输出日志 std_log = Logger(\"std_log\") def init_logger(): system_log.handlers", "logbook.set_datetime_format(\"local\") # patch warn logbook.base._level_names[logbook.base.WARNING] = 'WARN' __all__ = [", "user_detail_log.handlers.append(StderrHandler(bubble=True)) # 系统日志 system_log = Logger(\"system_log\") basic_system_log = Logger(\"basic_system_log\") #", "datetime import datetime import logbook from logbook import Logger, StderrHandler", "# user_detail_log.handlers.append(StderrHandler(bubble=True)) # 系统日志 system_log = Logger(\"system_log\") basic_system_log = Logger(\"basic_system_log\")", "= [ \"user_log\", \"system_log\", \"user_system_log\", ] DATETIME_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\"", "log return formatter # loggers # 用户代码logger日志 user_log = Logger(\"user_log\")", "system_log = Logger(\"system_log\") basic_system_log = Logger(\"basic_system_log\") # 标准输出日志 std_log =", "user_log.handlers = [] user_system_log.handlers = [] def user_print(*args, **kwargs): sep", "= Logger(\"std_log\") def init_logger(): system_log.handlers = [StderrHandler(bubble=True)] basic_system_log.handlers = [StderrHandler(bubble=True)]", "2.0 许可,Apache 2.0 许可与本许可冲突之处,以本许可为准。 # 详细的授权流程,请联系 <EMAIL> 获取。 from datetime", "handler): from rqalpha.environment import Environment try: dt = Environment.get_instance().calendar_dt.strftime(DATETIME_FORMAT) except", "Logger(\"system_log\") basic_system_log = Logger(\"basic_system_log\") # 标准输出日志 std_log = Logger(\"std_log\") def", "import datetime import logbook from logbook import Logger, StderrHandler from", "# 标准输出日志 std_log = Logger(\"std_log\") def init_logger(): system_log.handlers = [StderrHandler(bubble=True)]", "\"system_log\", \"user_system_log\", ] DATETIME_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\" def user_std_handler_log_formatter(record, handler):", "] DATETIME_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\" def user_std_handler_log_formatter(record, handler): from rqalpha.environment", "许可,Apache 2.0 许可与本许可冲突之处,以本许可为准。 # 详细的授权流程,请联系 <EMAIL> 获取。 from datetime import", "formatter # loggers # 用户代码logger日志 user_log = Logger(\"user_log\") # 给用户看的系统日志", "dt = datetime.now().strftime(DATETIME_FORMAT) log = \"{dt} {level} {msg}\".format( dt=dt, level=record.level_name,", "[] def user_print(*args, **kwargs): sep = kwargs.get(\"sep\", \" \") end", "logbook.base._level_names[logbook.base.WARNING] = 'WARN' __all__ = [ \"user_log\", \"system_log\", \"user_system_log\", ]", "[ \"user_log\", \"system_log\", \"user_system_log\", ] DATETIME_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\" def", "[{time}] {level}: {msg}\".format( formatter_tag=tag, level=record.level_name, msg=to_utf8(record.message), time=record.time, ) if record.formatted_exception:", "from rqalpha.utils.py2 import to_utf8 logbook.set_datetime_format(\"local\") # patch warn logbook.base._level_names[logbook.base.WARNING] =", "许可与本许可冲突之处,以本许可为准。 # 详细的授权流程,请联系 <EMAIL> 获取。 from datetime import datetime import", "patch warn logbook.base._level_names[logbook.base.WARNING] = 'WARN' __all__ = [ \"user_log\", \"system_log\",", "深圳米筐科技有限公司(下称“米筐科技”) # # 除非遵守当前许可,否则不得使用本软件。 # # * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件): # 遵守", "Apache 2.0 许可,Apache 2.0 许可与本许可冲突之处,以本许可为准。 # 详细的授权流程,请联系 <EMAIL> 获取。 from", "record.formatted_exception return log return formatter # loggers # 用户代码logger日志 user_log", "Logger, StderrHandler from rqalpha.utils.py2 import to_utf8 logbook.set_datetime_format(\"local\") # patch warn", "遵守 Apache License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。 #", "[StderrHandler(bubble=True)] std_log.handlers = [StderrHandler(bubble=True)] user_log.handlers = [] user_system_log.handlers = []", "[StderrHandler(bubble=True)] user_log.handlers = [] user_system_log.handlers = [] def user_print(*args, **kwargs):", "# # 除非遵守当前许可,否则不得使用本软件。 # # * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件): # 遵守 Apache", "sep = kwargs.get(\"sep\", \" \") end = kwargs.get(\"end\", \"\") message", "logbook from logbook import Logger, StderrHandler from rqalpha.utils.py2 import to_utf8", "在此前提下,对本软件的使用同样需要遵守 Apache 2.0 许可,Apache 2.0 许可与本许可冲突之处,以本许可为准。 # 详细的授权流程,请联系 <EMAIL> 获取。", "Logger(\"user_system_log\") # 用于用户异常的详细日志打印 user_detail_log = Logger(\"user_detail_log\") # user_detail_log.handlers.append(StderrHandler(bubble=True)) # 系统日志", "init_logger(): system_log.handlers = [StderrHandler(bubble=True)] basic_system_log.handlers = [StderrHandler(bubble=True)] std_log.handlers = [StderrHandler(bubble=True)]", "{msg}\".format( dt=dt, level=record.level_name, msg=to_utf8(record.message), ) return log user_std_handler = StderrHandler(bubble=True)", "= \"{dt} {level} {msg}\".format( dt=dt, level=record.level_name, msg=to_utf8(record.message), ) return log", "def init_logger(): system_log.handlers = [StderrHandler(bubble=True)] basic_system_log.handlers = [StderrHandler(bubble=True)] std_log.handlers =", "kwargs.get(\"sep\", \" \") end = kwargs.get(\"end\", \"\") message = sep.join(map(str,", "= [] user_system_log.handlers = [] def user_print(*args, **kwargs): sep =", "level=record.level_name, msg=to_utf8(record.message), time=record.time, ) if record.formatted_exception: log += \"\\n\" +", "许可的副本:http://www.apache.org/licenses/LICENSE-2.0。 # 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”不变,且不得附加任何条件。 # # * 商业用途(商业用途指个人出于任何商业目的使用本软件,或者法人或其他组织出于任何目的使用本软件): # 未经米筐科技授权,任何个人不得出于任何商业目的使用本软件(包括但不限于向第三方提供、销售、出租、出借、转让本软件、本软件的衍生产品、引用或借鉴了本软件功能或源代码的产品或服务),任何法人或其他组织不得出于任何目的使用本软件,否则米筐科技有权追究相应的知识产权侵权责任。 #", "* 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件): # 遵守 Apache License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache", "# 用户代码logger日志 user_log = Logger(\"user_log\") # 给用户看的系统日志 user_system_log = Logger(\"user_system_log\")", "系统日志 system_log = Logger(\"system_log\") basic_system_log = Logger(\"basic_system_log\") # 标准输出日志 std_log", "log user_std_handler = StderrHandler(bubble=True) user_std_handler.formatter = user_std_handler_log_formatter def formatter_builder(tag): def", "datetime.now().strftime(DATETIME_FORMAT) log = \"{dt} {level} {msg}\".format( dt=dt, level=record.level_name, msg=to_utf8(record.message), )", "# 除非遵守当前许可,否则不得使用本软件。 # # * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件): # 遵守 Apache License", "user_log = Logger(\"user_log\") # 给用户看的系统日志 user_system_log = Logger(\"user_system_log\") # 用于用户异常的详细日志打印", "= [StderrHandler(bubble=True)] user_log.handlers = [] user_system_log.handlers = [] def user_print(*args,", "2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。 # 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”不变,且不得附加任何条件。 # #", "import Logger, StderrHandler from rqalpha.utils.py2 import to_utf8 logbook.set_datetime_format(\"local\") # patch" ]
[ "in format: user/password@host[:port]/sid[ as {sysdba|sysoper}] ''' import os import logging", "= {} for db in dbs: result[db] = __salt__['pillar.get']('oracle:dbs:' +", "cx_Oracle.connect(user, password, cx_Oracle.makedsn(host, port, sid), mode) conn.outputtypehandler = _unicode_output return", "if HAS_CX_ORACLE else False def _cx_oracle_req(): ''' Fallback function stub", "= __salt__['pillar.get']('oracle:dbs') log.debug('get all ({0}) dbs from pillar'.format(len(pillar_dbs))) return pillar_dbs", "uri_l = uri.rsplit(' as ', 1) if len(uri_l) == 2:", "port, sid), mode) conn.outputtypehandler = _unicode_output return conn @depends('cx_Oracle', fallback_function=_cx_oracle_req)", "bash salt '*' oracle.show_dbs salt '*' oracle.show_dbs my_db ''' if", "my_db ''' if dbs: log.debug('get dbs from pillar: {0}'.format(dbs)) result", "__virtual__(): ''' Load module only if cx_Oracle installed ''' return", "hostport_l[0] port = 1521 log.debug('connect: {0}'.format((user, password, host, port, sid,", "= '.AL32UTF8' conn = cx_Oracle.connect(user, password, cx_Oracle.makedsn(host, port, sid), mode)", "client_version(): ''' Oracle Client Version CLI Example: .. code-block:: bash", "Show Environment used by Oracle Client CLI Example: .. code-block::", "'TNS_ADMIN', 'NLS_LANG'] result = {} for env in envs: if", "else False def _cx_oracle_req(): ''' Fallback function stub ''' return", "', 1) if len(uri_l) == 2: credentials, mode = uri_l", "import logging from salt.utils.decorators import depends log = logging.getLogger(__name__) try:", "result[db] = get_version(db) return result @depends('cx_Oracle', fallback_function=_cx_oracle_req) def client_version(): '''", "Show Pillar segment oracle.* and subitem with notation \"item:subitem\" CLI", "libs need to be in PATH **pillar** .. code-block:: text", "for db in dbs: if db in pillar_dbs: result[db] =", "versions for: {0}'.format(dbs)) for db in dbs: if db in", "hostport_l else: host = hostport_l[0] port = 1521 log.debug('connect: {0}'.format((user,", "PATH: path to Oracle Client libs need to be in", "http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html ''' if default_type in (cx_Oracle.STRING, cx_Oracle.LONG_STRING, cx_Oracle.FIXED_CHAR, cx_Oracle.CLOB): return", "= hostport_l else: host = hostport_l[0] port = 1521 log.debug('connect:", "**pillar** .. code-block:: text oracle.dbs: list of known based oracle.dbs.<db>.uri:", "query): ''' Run SQL query and return result CLI example:", "module provide connections for multiple Oracle DB instances. **OS Environment**", "= hostport_l[0] port = 1521 log.debug('connect: {0}'.format((user, password, host, port,", "= _connect(show_dbs(db)[db]['uri']) return conn.cursor().execute(query).fetchall() def show_dbs(*dbs): ''' Show databases configuration", "''' Oracle DataBase connection module :mainteiner: <NAME> <<EMAIL>> :maturity: new", "'NLS_LANG'] result = {} for env in envs: if env", "''' Fallback function stub ''' return 'Need \"cx_Oracle\" and Oracle", "provide connections for multiple Oracle DB instances. **OS Environment** ..", "force UTF-8 client encoding os.environ['NLS_LANG'] = '.AL32UTF8' conn = cx_Oracle.connect(user,", "hostport, sid = hostportsid.split('/') hostport_l = hostport.split(':') if len(hostport_l) ==", "path to oracle product PATH: path to Oracle Client libs", "dbs from pillar'.format(len(pillar_dbs))) return pillar_dbs @depends('cx_Oracle', fallback_function=_cx_oracle_req) def version(*dbs): '''", "return __salt__['pillar.get']('oracle:' + item) else: return __salt__['pillar.get']('oracle') def show_env(): '''", "db in pillar_dbs: result[db] = get_version(db) else: log.debug('get all({0}) dbs", "installed ''' return __virtualname__ if HAS_CX_ORACLE else False def _cx_oracle_req():", "= user/password@host[:port]/sid[ as {sysdba|sysoper}] Return cx_Oracle.Connection instance ''' # cx_Oracle.Connection()", "default_type in (cx_Oracle.STRING, cx_Oracle.LONG_STRING, cx_Oracle.FIXED_CHAR, cx_Oracle.CLOB): return cursor.var(unicode, size, cursor.arraysize)", "userpass, hostportsid = credentials.split('@') user, password = userpass.split('/') hostport, sid", "as {sysdba|sysoper}] ''' import os import logging from salt.utils.decorators import", "return result @depends('cx_Oracle', fallback_function=_cx_oracle_req) def client_version(): ''' Oracle Client Version", "cx_Oracle :platform: all :configuration: module provide connections for multiple Oracle", "dbs: log.debug('get db versions for: {0}'.format(dbs)) for db in dbs:", "credentials in format: user/password@host[:port]/sid[ as {sysdba|sysoper}] ''' import os import", "fallback_function=_cx_oracle_req) def version(*dbs): ''' Server Version (select banner from v$version)", "\"select * from my_table\" ''' log.debug('run query on {0}: {1}'.format(db,", "Pillar segment oracle.* and subitem with notation \"item:subitem\" CLI Example:", "size, precision, scale): ''' Return strings values as python unicode", "else: host = hostport_l[0] port = 1521 log.debug('connect: {0}'.format((user, password,", "'*' oracle.show_dbs salt '*' oracle.show_dbs my_db ''' if dbs: log.debug('get", "salt '*' oracle.version salt '*' oracle.version my_db ''' pillar_dbs =", "for: {0}'.format(dbs)) for db in dbs: if db in pillar_dbs:", "uri = user/password@host[:port]/sid[ as {sysdba|sysoper}] Return cx_Oracle.Connection instance ''' #", "port = 1521 log.debug('connect: {0}'.format((user, password, host, port, sid, mode)))", "pillar_dbs = __salt__['pillar.get']('oracle:dbs') log.debug('get all ({0}) dbs from pillar'.format(len(pillar_dbs))) return", "HAS_CX_ORACLE else False def _cx_oracle_req(): ''' Fallback function stub '''", "as python unicode string http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html ''' if default_type in (cx_Oracle.STRING,", "''' if default_type in (cx_Oracle.STRING, cx_Oracle.LONG_STRING, cx_Oracle.FIXED_CHAR, cx_Oracle.CLOB): return cursor.var(unicode,", "only if cx_Oracle installed ''' return __virtualname__ if HAS_CX_ORACLE else", "False def _cx_oracle_req(): ''' Fallback function stub ''' return 'Need", "v$version) CLI Example: .. code-block:: bash salt '*' oracle.version salt", "'.AL32UTF8' ''' envs = ['PATH', 'ORACLE_HOME', 'TNS_ADMIN', 'NLS_LANG'] result =", "salt '*' oracle.show_env .. note:: at first _connect() ``NLS_LANG`` will", "credentials.split('@') user, password = userpass.split('/') hostport, sid = hostportsid.split('/') hostport_l", "Example: .. code-block:: bash salt '*' oracle.show_env .. note:: at", "{} for env in envs: if env in os.environ: result[env]", "in run_query(x, \"select banner from v$version order by banner\") ]", "hostportsid = credentials.split('@') user, password = userpass.split('/') hostport, sid =", "x: [ r[0] for r in run_query(x, \"select banner from", "if db in pillar_dbs: result[db] = get_version(db) else: log.debug('get all({0})", "logging from salt.utils.decorators import depends log = logging.getLogger(__name__) try: import", "Client installed for this functin exist' def _unicode_output(cursor, name, default_type,", ".. note:: at first _connect() ``NLS_LANG`` will forced to '.AL32UTF8'", "salt '*' oracle.version my_db ''' pillar_dbs = __salt__['pillar.get']('oracle:dbs') get_version =", "= {'sysdba': 2, 'sysoper': 4} HAS_CX_ORACLE = False __virtualname__ =", "and Oracle Client installed for this functin exist' def _unicode_output(cursor,", "'sysoper': 4} HAS_CX_ORACLE = False __virtualname__ = 'oracle' def __virtual__():", "port, sid, mode))) # force UTF-8 client encoding os.environ['NLS_LANG'] =", "get_version(db) return result @depends('cx_Oracle', fallback_function=_cx_oracle_req) def client_version(): ''' Oracle Client", "= lambda x: [ r[0] for r in run_query(x, \"select", "Return strings values as python unicode string http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html ''' if", "instances. **OS Environment** .. code-block:: text ORACLE_HOME: path to oracle", "query)) conn = _connect(show_dbs(db)[db]['uri']) return conn.cursor().execute(query).fetchall() def show_dbs(*dbs): ''' Show", "will forced to '.AL32UTF8' ''' envs = ['PATH', 'ORACLE_HOME', 'TNS_ADMIN',", "log.debug('connect: {0}'.format((user, password, host, port, sid, mode))) # force UTF-8", "def show_dbs(*dbs): ''' Show databases configuration from pillar. Filter by", "example: .. code-block:: bash salt '*' oracle.run_query my_db \"select *", "Fallback function stub ''' return 'Need \"cx_Oracle\" and Oracle Client", "__salt__['pillar.get']('oracle:' + item) else: return __salt__['pillar.get']('oracle') def show_env(): ''' Show", "default_type, size, precision, scale): ''' Return strings values as python", "for db in dbs: result[db] = __salt__['pillar.get']('oracle:dbs:' + db) return", "uri_l[0] mode = 0 userpass, hostportsid = credentials.split('@') user, password", "sid = hostportsid.split('/') hostport_l = hostport.split(':') if len(hostport_l) == 2:", "CLI Example: .. code-block:: bash salt '*' oracle.show_pillar salt '*'", "oracle.show_dbs my_db ''' if dbs: log.debug('get dbs from pillar: {0}'.format(dbs))", "get_version = lambda x: [ r[0] for r in run_query(x,", "with notation \"item:subitem\" CLI Example: .. code-block:: bash salt '*'", "return 'Need \"cx_Oracle\" and Oracle Client installed for this functin", "as {sysdba|sysoper}] Return cx_Oracle.Connection instance ''' # cx_Oracle.Connection() not support", "== 2: credentials, mode = uri_l mode = MODE[mode] else:", "_connect(show_dbs(db)[db]['uri']) return conn.cursor().execute(query).fetchall() def show_dbs(*dbs): ''' Show databases configuration from", "lambda x: [ r[0] for r in run_query(x, \"select banner", "args .. code-block:: bash salt '*' oracle.show_dbs salt '*' oracle.show_dbs", "dbs versions'.format(len(dbs))) for db in dbs: result[db] = get_version(db) return", "if len(hostport_l) == 2: host, port = hostport_l else: host", "as ', 1) if len(uri_l) == 2: credentials, mode =", "CLI example: .. code-block:: bash salt '*' oracle.run_query my_db \"select", "''' if dbs: log.debug('get dbs from pillar: {0}'.format(dbs)) result =", "product PATH: path to Oracle Client libs need to be", ".. code-block:: bash salt '*' oracle.show_dbs salt '*' oracle.show_dbs my_db", "''' Show Environment used by Oracle Client CLI Example: ..", "Oracle Client libs need to be in PATH **pillar** ..", "stub ''' return 'Need \"cx_Oracle\" and Oracle Client installed for", "result CLI example: .. code-block:: bash salt '*' oracle.run_query my_db", "def _unicode_output(cursor, name, default_type, size, precision, scale): ''' Return strings", "else: pillar_dbs = __salt__['pillar.get']('oracle:dbs') log.debug('get all ({0}) dbs from pillar'.format(len(pillar_dbs)))", "return pillar_dbs @depends('cx_Oracle', fallback_function=_cx_oracle_req) def version(*dbs): ''' Server Version (select", "cx_Oracle.CLOB): return cursor.var(unicode, size, cursor.arraysize) def _connect(uri): ''' uri =", "encoding os.environ['NLS_LANG'] = '.AL32UTF8' conn = cx_Oracle.connect(user, password, cx_Oracle.makedsn(host, port,", "item) else: return __salt__['pillar.get']('oracle') def show_env(): ''' Show Environment used", "'*' oracle.version my_db ''' pillar_dbs = __salt__['pillar.get']('oracle:dbs') get_version = lambda", "password, host, port, sid, mode))) # force UTF-8 client encoding", "'*' oracle.client_version ''' return '.'.join((str(x) for x in cx_Oracle.clientversion())) def", "''' Return strings values as python unicode string http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html '''", "{sysdba|sysoper}] ''' import os import logging from salt.utils.decorators import depends", "dbs from pillar: {0}'.format(dbs)) result = {} for db in", "in (cx_Oracle.STRING, cx_Oracle.LONG_STRING, cx_Oracle.FIXED_CHAR, cx_Oracle.CLOB): return cursor.var(unicode, size, cursor.arraysize) def", "by args .. code-block:: bash salt '*' oracle.show_dbs salt '*'", "Oracle DB instances. **OS Environment** .. code-block:: text ORACLE_HOME: path", "dbs: if db in pillar_dbs: result[db] = get_version(db) else: log.debug('get", "subitem with notation \"item:subitem\" CLI Example: .. code-block:: bash salt", "notation \"item:subitem\" CLI Example: .. code-block:: bash salt '*' oracle.show_pillar", "return result CLI example: .. code-block:: bash salt '*' oracle.run_query", "v$version order by banner\") ] result = {} if dbs:", "= _unicode_output return conn @depends('cx_Oracle', fallback_function=_cx_oracle_req) def run_query(db, query): '''", "values as python unicode string http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html ''' if default_type in", "Return cx_Oracle.Connection instance ''' # cx_Oracle.Connection() not support 'as sysdba'", "python unicode string http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html ''' if default_type in (cx_Oracle.STRING, cx_Oracle.LONG_STRING,", "port = hostport_l else: host = hostport_l[0] port = 1521", "by Oracle Client CLI Example: .. code-block:: bash salt '*'", "in envs: if env in os.environ: result[env] = os.environ[env] return", "and subitem with notation \"item:subitem\" CLI Example: .. code-block:: bash", "= 'oracle' def __virtual__(): ''' Load module only if cx_Oracle", "conn @depends('cx_Oracle', fallback_function=_cx_oracle_req) def run_query(db, query): ''' Run SQL query", "\"select banner from v$version order by banner\") ] result =", "cx_Oracle installed ''' return __virtualname__ if HAS_CX_ORACLE else False def", "'ORACLE_HOME', 'TNS_ADMIN', 'NLS_LANG'] result = {} for env in envs:", "if len(uri_l) == 2: credentials, mode = uri_l mode =", "MODE = { 'sysdba': cx_Oracle.SYSDBA, 'sysoper': cx_Oracle.SYSOPER } HAS_CX_ORACLE =", "{0}'.format((user, password, host, port, sid, mode))) # force UTF-8 client", "from my_table\" ''' log.debug('run query on {0}: {1}'.format(db, query)) conn", "query and return result CLI example: .. code-block:: bash salt", "user, password = userpass.split('/') hostport, sid = hostportsid.split('/') hostport_l =", "sid), mode) conn.outputtypehandler = _unicode_output return conn @depends('cx_Oracle', fallback_function=_cx_oracle_req) def", "for x in cx_Oracle.clientversion())) def show_pillar(item=None): ''' Show Pillar segment", "'Need \"cx_Oracle\" and Oracle Client installed for this functin exist'", "False __virtualname__ = 'oracle' def __virtual__(): ''' Load module only", "result = {} for env in envs: if env in", "Show databases configuration from pillar. Filter by args .. code-block::", "= 1521 log.debug('connect: {0}'.format((user, password, host, port, sid, mode))) #", "Version CLI Example: .. code-block:: bash salt '*' oracle.client_version '''", "{} if dbs: log.debug('get db versions for: {0}'.format(dbs)) for db", "query on {0}: {1}'.format(db, query)) conn = _connect(show_dbs(db)[db]['uri']) return conn.cursor().execute(query).fetchall()", "-*- coding: utf-8 -*- ''' Oracle DataBase connection module :mainteiner:", "import cx_Oracle MODE = { 'sysdba': cx_Oracle.SYSDBA, 'sysoper': cx_Oracle.SYSOPER }", "log.debug('get all({0}) dbs versions'.format(len(dbs))) for db in dbs: result[db] =", "from v$version) CLI Example: .. code-block:: bash salt '*' oracle.version", "on {0}: {1}'.format(db, query)) conn = _connect(show_dbs(db)[db]['uri']) return conn.cursor().execute(query).fetchall() def", "__salt__['pillar.get']('oracle:dbs') get_version = lambda x: [ r[0] for r in", "``NLS_LANG`` will forced to '.AL32UTF8' ''' envs = ['PATH', 'ORACLE_HOME',", "SQL query and return result CLI example: .. code-block:: bash", "Oracle Client Version CLI Example: .. code-block:: bash salt '*'", "True except ImportError: MODE = {'sysdba': 2, 'sysoper': 4} HAS_CX_ORACLE", "'*' oracle.run_query my_db \"select * from my_table\" ''' log.debug('run query", "def _cx_oracle_req(): ''' Fallback function stub ''' return 'Need \"cx_Oracle\"", "__salt__['pillar.get']('oracle') def show_env(): ''' Show Environment used by Oracle Client", "utf-8 -*- ''' Oracle DataBase connection module :mainteiner: <NAME> <<EMAIL>>", "cx_Oracle.Connection instance ''' # cx_Oracle.Connection() not support 'as sysdba' syntax", "return result else: pillar_dbs = __salt__['pillar.get']('oracle:dbs') log.debug('get all ({0}) dbs", "not support 'as sysdba' syntax uri_l = uri.rsplit(' as ',", "from pillar. Filter by args .. code-block:: bash salt '*'", "oracle product PATH: path to Oracle Client libs need to", "segment oracle.* and subitem with notation \"item:subitem\" CLI Example: ..", "salt.utils.decorators import depends log = logging.getLogger(__name__) try: import cx_Oracle MODE", "''' log.debug('run query on {0}: {1}'.format(db, query)) conn = _connect(show_dbs(db)[db]['uri'])", "UTF-8 client encoding os.environ['NLS_LANG'] = '.AL32UTF8' conn = cx_Oracle.connect(user, password,", "= uri_l[0] mode = 0 userpass, hostportsid = credentials.split('@') user,", "{'sysdba': 2, 'sysoper': 4} HAS_CX_ORACLE = False __virtualname__ = 'oracle'", "based oracle.dbs.<db>.uri: connection credentials in format: user/password@host[:port]/sid[ as {sysdba|sysoper}] '''", "''' Server Version (select banner from v$version) CLI Example: ..", "order by banner\") ] result = {} if dbs: log.debug('get", "code-block:: text oracle.dbs: list of known based oracle.dbs.<db>.uri: connection credentials", "= get_version(db) else: log.debug('get all({0}) dbs versions'.format(len(dbs))) for db in", "function stub ''' return 'Need \"cx_Oracle\" and Oracle Client installed", "log = logging.getLogger(__name__) try: import cx_Oracle MODE = { 'sysdba':", "return __virtualname__ if HAS_CX_ORACLE else False def _cx_oracle_req(): ''' Fallback", "{0}: {1}'.format(db, query)) conn = _connect(show_dbs(db)[db]['uri']) return conn.cursor().execute(query).fetchall() def show_dbs(*dbs):", "salt '*' oracle.run_query my_db \"select * from my_table\" ''' log.debug('run", "({0}) dbs from pillar'.format(len(pillar_dbs))) return pillar_dbs @depends('cx_Oracle', fallback_function=_cx_oracle_req) def version(*dbs):", "{0}'.format(dbs)) result = {} for db in dbs: result[db] =", "(select banner from v$version) CLI Example: .. code-block:: bash salt", "cx_Oracle.SYSDBA, 'sysoper': cx_Oracle.SYSOPER } HAS_CX_ORACLE = True except ImportError: MODE", "CLI Example: .. code-block:: bash salt '*' oracle.client_version ''' return", "banner from v$version order by banner\") ] result = {}", "try: import cx_Oracle MODE = { 'sysdba': cx_Oracle.SYSDBA, 'sysoper': cx_Oracle.SYSOPER", "def client_version(): ''' Oracle Client Version CLI Example: .. code-block::", "conn = _connect(show_dbs(db)[db]['uri']) return conn.cursor().execute(query).fetchall() def show_dbs(*dbs): ''' Show databases", "1521 log.debug('connect: {0}'.format((user, password, host, port, sid, mode))) # force", "'*' oracle.version salt '*' oracle.version my_db ''' pillar_dbs = __salt__['pillar.get']('oracle:dbs')", "os.environ['NLS_LANG'] = '.AL32UTF8' conn = cx_Oracle.connect(user, password, cx_Oracle.makedsn(host, port, sid),", "envs = ['PATH', 'ORACLE_HOME', 'TNS_ADMIN', 'NLS_LANG'] result = {} for", "len(uri_l) == 2: credentials, mode = uri_l mode = MODE[mode]", "configuration from pillar. Filter by args .. code-block:: bash salt", "= ['PATH', 'ORACLE_HOME', 'TNS_ADMIN', 'NLS_LANG'] result = {} for env", "name, default_type, size, precision, scale): ''' Return strings values as", "'*' oracle.show_env .. note:: at first _connect() ``NLS_LANG`` will forced", "exist' def _unicode_output(cursor, name, default_type, size, precision, scale): ''' Return", "'sysoper': cx_Oracle.SYSOPER } HAS_CX_ORACLE = True except ImportError: MODE =", "__virtualname__ = 'oracle' def __virtual__(): ''' Load module only if", "Client libs need to be in PATH **pillar** .. code-block::", "'*' oracle.show_pillar dbs:my_db ''' if item: return __salt__['pillar.get']('oracle:' + item)", "sid, mode))) # force UTF-8 client encoding os.environ['NLS_LANG'] = '.AL32UTF8'", "bash salt '*' oracle.client_version ''' return '.'.join((str(x) for x in", "Example: .. code-block:: bash salt '*' oracle.show_pillar salt '*' oracle.show_pillar", "''' return '.'.join((str(x) for x in cx_Oracle.clientversion())) def show_pillar(item=None): '''", "known based oracle.dbs.<db>.uri: connection credentials in format: user/password@host[:port]/sid[ as {sysdba|sysoper}]", "fallback_function=_cx_oracle_req) def client_version(): ''' Oracle Client Version CLI Example: ..", "2: credentials, mode = uri_l mode = MODE[mode] else: credentials", "mode = 0 userpass, hostportsid = credentials.split('@') user, password =", "new :depends: cx_Oracle :platform: all :configuration: module provide connections for", "run_query(x, \"select banner from v$version order by banner\") ] result", "in pillar_dbs: result[db] = get_version(db) else: log.debug('get all({0}) dbs versions'.format(len(dbs)))", "coding: utf-8 -*- ''' Oracle DataBase connection module :mainteiner: <NAME>", "__salt__['pillar.get']('oracle:dbs:' + db) return result else: pillar_dbs = __salt__['pillar.get']('oracle:dbs') log.debug('get", "_connect() ``NLS_LANG`` will forced to '.AL32UTF8' ''' envs = ['PATH',", "= userpass.split('/') hostport, sid = hostportsid.split('/') hostport_l = hostport.split(':') if", "item: return __salt__['pillar.get']('oracle:' + item) else: return __salt__['pillar.get']('oracle') def show_env():", "_unicode_output(cursor, name, default_type, size, precision, scale): ''' Return strings values", "fallback_function=_cx_oracle_req) def run_query(db, query): ''' Run SQL query and return", "Load module only if cx_Oracle installed ''' return __virtualname__ if", "connection module :mainteiner: <NAME> <<EMAIL>> :maturity: new :depends: cx_Oracle :platform:", "show_dbs(*dbs): ''' Show databases configuration from pillar. Filter by args", "salt '*' oracle.show_dbs salt '*' oracle.show_dbs my_db ''' if dbs:", "else: return __salt__['pillar.get']('oracle') def show_env(): ''' Show Environment used by", "bash salt '*' oracle.version salt '*' oracle.version my_db ''' pillar_dbs", "Server Version (select banner from v$version) CLI Example: .. code-block::", "\"cx_Oracle\" and Oracle Client installed for this functin exist' def", "code-block:: bash salt '*' oracle.version salt '*' oracle.version my_db '''", "= { 'sysdba': cx_Oracle.SYSDBA, 'sysoper': cx_Oracle.SYSOPER } HAS_CX_ORACLE = True", "sysdba' syntax uri_l = uri.rsplit(' as ', 1) if len(uri_l)", "= uri_l mode = MODE[mode] else: credentials = uri_l[0] mode", "banner from v$version) CLI Example: .. code-block:: bash salt '*'", "''' pillar_dbs = __salt__['pillar.get']('oracle:dbs') get_version = lambda x: [ r[0]", "my_db \"select * from my_table\" ''' log.debug('run query on {0}:", "path to Oracle Client libs need to be in PATH", "= cx_Oracle.connect(user, password, cx_Oracle.makedsn(host, port, sid), mode) conn.outputtypehandler = _unicode_output", ".. code-block:: bash salt '*' oracle.run_query my_db \"select * from", "Client CLI Example: .. code-block:: bash salt '*' oracle.show_env ..", "'sysdba': cx_Oracle.SYSDBA, 'sysoper': cx_Oracle.SYSOPER } HAS_CX_ORACLE = True except ImportError:", "be in PATH **pillar** .. code-block:: text oracle.dbs: list of", "my_table\" ''' log.debug('run query on {0}: {1}'.format(db, query)) conn =", "support 'as sysdba' syntax uri_l = uri.rsplit(' as ', 1)", "bash salt '*' oracle.run_query my_db \"select * from my_table\" '''", "host, port, sid, mode))) # force UTF-8 client encoding os.environ['NLS_LANG']", "Client Version CLI Example: .. code-block:: bash salt '*' oracle.client_version", "MODE[mode] else: credentials = uri_l[0] mode = 0 userpass, hostportsid", "host, port = hostport_l else: host = hostport_l[0] port =", "''' # cx_Oracle.Connection() not support 'as sysdba' syntax uri_l =", "cx_Oracle.SYSOPER } HAS_CX_ORACLE = True except ImportError: MODE = {'sysdba':", "ORACLE_HOME: path to oracle product PATH: path to Oracle Client", "**OS Environment** .. code-block:: text ORACLE_HOME: path to oracle product", ".. code-block:: bash salt '*' oracle.show_pillar salt '*' oracle.show_pillar dbs:my_db", "''' if item: return __salt__['pillar.get']('oracle:' + item) else: return __salt__['pillar.get']('oracle')", "Filter by args .. code-block:: bash salt '*' oracle.show_dbs salt", "all :configuration: module provide connections for multiple Oracle DB instances.", "scale): ''' Return strings values as python unicode string http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html", "text oracle.dbs: list of known based oracle.dbs.<db>.uri: connection credentials in", "from v$version order by banner\") ] result = {} if", "for multiple Oracle DB instances. **OS Environment** .. code-block:: text", "mode = MODE[mode] else: credentials = uri_l[0] mode = 0", "# force UTF-8 client encoding os.environ['NLS_LANG'] = '.AL32UTF8' conn =", "in cx_Oracle.clientversion())) def show_pillar(item=None): ''' Show Pillar segment oracle.* and", "'.AL32UTF8' conn = cx_Oracle.connect(user, password, cx_Oracle.makedsn(host, port, sid), mode) conn.outputtypehandler", "= True except ImportError: MODE = {'sysdba': 2, 'sysoper': 4}", "''' Show databases configuration from pillar. Filter by args ..", ":configuration: module provide connections for multiple Oracle DB instances. **OS", "envs: if env in os.environ: result[env] = os.environ[env] return result", "uri.rsplit(' as ', 1) if len(uri_l) == 2: credentials, mode", "logging.getLogger(__name__) try: import cx_Oracle MODE = { 'sysdba': cx_Oracle.SYSDBA, 'sysoper':", "format: user/password@host[:port]/sid[ as {sysdba|sysoper}] ''' import os import logging from", "code-block:: bash salt '*' oracle.show_dbs salt '*' oracle.show_dbs my_db '''", "all ({0}) dbs from pillar'.format(len(pillar_dbs))) return pillar_dbs @depends('cx_Oracle', fallback_function=_cx_oracle_req) def", "['PATH', 'ORACLE_HOME', 'TNS_ADMIN', 'NLS_LANG'] result = {} for env in", "return conn @depends('cx_Oracle', fallback_function=_cx_oracle_req) def run_query(db, query): ''' Run SQL", "oracle.run_query my_db \"select * from my_table\" ''' log.debug('run query on", "to be in PATH **pillar** .. code-block:: text oracle.dbs: list", "''' Oracle Client Version CLI Example: .. code-block:: bash salt", "= {} for env in envs: if env in os.environ:", "DB instances. **OS Environment** .. code-block:: text ORACLE_HOME: path to", "(cx_Oracle.STRING, cx_Oracle.LONG_STRING, cx_Oracle.FIXED_CHAR, cx_Oracle.CLOB): return cursor.var(unicode, size, cursor.arraysize) def _connect(uri):", "db in dbs: result[db] = get_version(db) return result @depends('cx_Oracle', fallback_function=_cx_oracle_req)", "show_pillar(item=None): ''' Show Pillar segment oracle.* and subitem with notation", "except ImportError: MODE = {'sysdba': 2, 'sysoper': 4} HAS_CX_ORACLE =", "] result = {} if dbs: log.debug('get db versions for:", "conn.cursor().execute(query).fetchall() def show_dbs(*dbs): ''' Show databases configuration from pillar. Filter", "Example: .. code-block:: bash salt '*' oracle.client_version ''' return '.'.join((str(x)", "if item: return __salt__['pillar.get']('oracle:' + item) else: return __salt__['pillar.get']('oracle') def", "for env in envs: if env in os.environ: result[env] =", "os import logging from salt.utils.decorators import depends log = logging.getLogger(__name__)", "string http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html ''' if default_type in (cx_Oracle.STRING, cx_Oracle.LONG_STRING, cx_Oracle.FIXED_CHAR, cx_Oracle.CLOB):", "db in dbs: if db in pillar_dbs: result[db] = get_version(db)", "banner\") ] result = {} if dbs: log.debug('get db versions", "2, 'sysoper': 4} HAS_CX_ORACLE = False __virtualname__ = 'oracle' def", "# -*- coding: utf-8 -*- ''' Oracle DataBase connection module", "4} HAS_CX_ORACLE = False __virtualname__ = 'oracle' def __virtual__(): '''", "+ item) else: return __salt__['pillar.get']('oracle') def show_env(): ''' Show Environment", "{sysdba|sysoper}] Return cx_Oracle.Connection instance ''' # cx_Oracle.Connection() not support 'as", "hostportsid.split('/') hostport_l = hostport.split(':') if len(hostport_l) == 2: host, port", "in dbs: if db in pillar_dbs: result[db] = get_version(db) else:", "= logging.getLogger(__name__) try: import cx_Oracle MODE = { 'sysdba': cx_Oracle.SYSDBA,", "return conn.cursor().execute(query).fetchall() def show_dbs(*dbs): ''' Show databases configuration from pillar.", "cx_Oracle.Connection() not support 'as sysdba' syntax uri_l = uri.rsplit(' as", "@depends('cx_Oracle', fallback_function=_cx_oracle_req) def run_query(db, query): ''' Run SQL query and", "* from my_table\" ''' log.debug('run query on {0}: {1}'.format(db, query))", "# cx_Oracle.Connection() not support 'as sysdba' syntax uri_l = uri.rsplit('", "Oracle DataBase connection module :mainteiner: <NAME> <<EMAIL>> :maturity: new :depends:", "_cx_oracle_req(): ''' Fallback function stub ''' return 'Need \"cx_Oracle\" and", "functin exist' def _unicode_output(cursor, name, default_type, size, precision, scale): '''", "versions'.format(len(dbs))) for db in dbs: result[db] = get_version(db) return result", "code-block:: bash salt '*' oracle.show_env .. note:: at first _connect()", "Version (select banner from v$version) CLI Example: .. code-block:: bash", "syntax uri_l = uri.rsplit(' as ', 1) if len(uri_l) ==", "= uri.rsplit(' as ', 1) if len(uri_l) == 2: credentials,", "code-block:: bash salt '*' oracle.show_pillar salt '*' oracle.show_pillar dbs:my_db '''", "Oracle Client installed for this functin exist' def _unicode_output(cursor, name,", "= MODE[mode] else: credentials = uri_l[0] mode = 0 userpass,", "''' envs = ['PATH', 'ORACLE_HOME', 'TNS_ADMIN', 'NLS_LANG'] result = {}", "Environment** .. code-block:: text ORACLE_HOME: path to oracle product PATH:", "''' return __virtualname__ if HAS_CX_ORACLE else False def _cx_oracle_req(): '''", "oracle.version my_db ''' pillar_dbs = __salt__['pillar.get']('oracle:dbs') get_version = lambda x:", "if dbs: log.debug('get db versions for: {0}'.format(dbs)) for db in", "cursor.var(unicode, size, cursor.arraysize) def _connect(uri): ''' uri = user/password@host[:port]/sid[ as", "in dbs: result[db] = get_version(db) return result @depends('cx_Oracle', fallback_function=_cx_oracle_req) def", "run_query(db, query): ''' Run SQL query and return result CLI", ".. code-block:: bash salt '*' oracle.show_env .. note:: at first", "''' Run SQL query and return result CLI example: ..", "to oracle product PATH: path to Oracle Client libs need", "{ 'sysdba': cx_Oracle.SYSDBA, 'sysoper': cx_Oracle.SYSOPER } HAS_CX_ORACLE = True except", "at first _connect() ``NLS_LANG`` will forced to '.AL32UTF8' ''' envs", ":depends: cx_Oracle :platform: all :configuration: module provide connections for multiple", "user/password@host[:port]/sid[ as {sysdba|sysoper}] Return cx_Oracle.Connection instance ''' # cx_Oracle.Connection() not", "env in envs: if env in os.environ: result[env] = os.environ[env]", "result @depends('cx_Oracle', fallback_function=_cx_oracle_req) def client_version(): ''' Oracle Client Version CLI", "__virtualname__ if HAS_CX_ORACLE else False def _cx_oracle_req(): ''' Fallback function", "def version(*dbs): ''' Server Version (select banner from v$version) CLI", "= __salt__['pillar.get']('oracle:dbs') get_version = lambda x: [ r[0] for r", "my_db ''' pillar_dbs = __salt__['pillar.get']('oracle:dbs') get_version = lambda x: [", "host = hostport_l[0] port = 1521 log.debug('connect: {0}'.format((user, password, host,", "import os import logging from salt.utils.decorators import depends log =", "password = userpass.split('/') hostport, sid = hostportsid.split('/') hostport_l = hostport.split(':')", "len(hostport_l) == 2: host, port = hostport_l else: host =", "from salt.utils.decorators import depends log = logging.getLogger(__name__) try: import cx_Oracle", "2: host, port = hostport_l else: host = hostport_l[0] port", "= 0 userpass, hostportsid = credentials.split('@') user, password = userpass.split('/')", "result[db] = __salt__['pillar.get']('oracle:dbs:' + db) return result else: pillar_dbs =", "} HAS_CX_ORACLE = True except ImportError: MODE = {'sysdba': 2,", "cx_Oracle.clientversion())) def show_pillar(item=None): ''' Show Pillar segment oracle.* and subitem", "log.debug('get dbs from pillar: {0}'.format(dbs)) result = {} for db", "Oracle Client CLI Example: .. code-block:: bash salt '*' oracle.show_env", "_unicode_output return conn @depends('cx_Oracle', fallback_function=_cx_oracle_req) def run_query(db, query): ''' Run", "and return result CLI example: .. code-block:: bash salt '*'", "dbs: result[db] = get_version(db) return result @depends('cx_Oracle', fallback_function=_cx_oracle_req) def client_version():", "oracle.show_pillar salt '*' oracle.show_pillar dbs:my_db ''' if item: return __salt__['pillar.get']('oracle:'", "oracle.show_env .. note:: at first _connect() ``NLS_LANG`` will forced to", "x in cx_Oracle.clientversion())) def show_pillar(item=None): ''' Show Pillar segment oracle.*", "MODE = {'sysdba': 2, 'sysoper': 4} HAS_CX_ORACLE = False __virtualname__", "= hostport.split(':') if len(hostport_l) == 2: host, port = hostport_l", "result = {} for db in dbs: result[db] = __salt__['pillar.get']('oracle:dbs:'", "import depends log = logging.getLogger(__name__) try: import cx_Oracle MODE =", "= False __virtualname__ = 'oracle' def __virtual__(): ''' Load module", "forced to '.AL32UTF8' ''' envs = ['PATH', 'ORACLE_HOME', 'TNS_ADMIN', 'NLS_LANG']", "oracle.dbs.<db>.uri: connection credentials in format: user/password@host[:port]/sid[ as {sysdba|sysoper}] ''' import", "cx_Oracle.LONG_STRING, cx_Oracle.FIXED_CHAR, cx_Oracle.CLOB): return cursor.var(unicode, size, cursor.arraysize) def _connect(uri): '''", "+ db) return result else: pillar_dbs = __salt__['pillar.get']('oracle:dbs') log.debug('get all", "db in dbs: result[db] = __salt__['pillar.get']('oracle:dbs:' + db) return result", "cursor.arraysize) def _connect(uri): ''' uri = user/password@host[:port]/sid[ as {sysdba|sysoper}] Return", "CLI Example: .. code-block:: bash salt '*' oracle.show_env .. note::", "size, cursor.arraysize) def _connect(uri): ''' uri = user/password@host[:port]/sid[ as {sysdba|sysoper}]", "code-block:: bash salt '*' oracle.client_version ''' return '.'.join((str(x) for x", ".. code-block:: text ORACLE_HOME: path to oracle product PATH: path", "client encoding os.environ['NLS_LANG'] = '.AL32UTF8' conn = cx_Oracle.connect(user, password, cx_Oracle.makedsn(host,", "'as sysdba' syntax uri_l = uri.rsplit(' as ', 1) if", "db versions for: {0}'.format(dbs)) for db in dbs: if db", "to Oracle Client libs need to be in PATH **pillar**", "{0}'.format(dbs)) for db in dbs: if db in pillar_dbs: result[db]", "strings values as python unicode string http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html ''' if default_type", "{1}'.format(db, query)) conn = _connect(show_dbs(db)[db]['uri']) return conn.cursor().execute(query).fetchall() def show_dbs(*dbs): '''", "cx_Oracle MODE = { 'sysdba': cx_Oracle.SYSDBA, 'sysoper': cx_Oracle.SYSOPER } HAS_CX_ORACLE", "code-block:: bash salt '*' oracle.run_query my_db \"select * from my_table\"", "'oracle' def __virtual__(): ''' Load module only if cx_Oracle installed", "<<EMAIL>> :maturity: new :depends: cx_Oracle :platform: all :configuration: module provide", "from pillar'.format(len(pillar_dbs))) return pillar_dbs @depends('cx_Oracle', fallback_function=_cx_oracle_req) def version(*dbs): ''' Server", "by banner\") ] result = {} if dbs: log.debug('get db", "to '.AL32UTF8' ''' envs = ['PATH', 'ORACLE_HOME', 'TNS_ADMIN', 'NLS_LANG'] result", "unicode string http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html ''' if default_type in (cx_Oracle.STRING, cx_Oracle.LONG_STRING, cx_Oracle.FIXED_CHAR,", "databases configuration from pillar. Filter by args .. code-block:: bash", "version(*dbs): ''' Server Version (select banner from v$version) CLI Example:", "''' return 'Need \"cx_Oracle\" and Oracle Client installed for this", "-*- ''' Oracle DataBase connection module :mainteiner: <NAME> <<EMAIL>> :maturity:", "def show_pillar(item=None): ''' Show Pillar segment oracle.* and subitem with", "hostport_l = hostport.split(':') if len(hostport_l) == 2: host, port =", "dbs:my_db ''' if item: return __salt__['pillar.get']('oracle:' + item) else: return", "pillar. Filter by args .. code-block:: bash salt '*' oracle.show_dbs", "first _connect() ``NLS_LANG`` will forced to '.AL32UTF8' ''' envs =", "get_version(db) else: log.debug('get all({0}) dbs versions'.format(len(dbs))) for db in dbs:", "CLI Example: .. code-block:: bash salt '*' oracle.version salt '*'", "pillar_dbs = __salt__['pillar.get']('oracle:dbs') get_version = lambda x: [ r[0] for", "for db in dbs: result[db] = get_version(db) return result @depends('cx_Oracle',", ".. code-block:: text oracle.dbs: list of known based oracle.dbs.<db>.uri: connection", "pillar: {0}'.format(dbs)) result = {} for db in dbs: result[db]", "oracle.client_version ''' return '.'.join((str(x) for x in cx_Oracle.clientversion())) def show_pillar(item=None):", "[ r[0] for r in run_query(x, \"select banner from v$version", "_connect(uri): ''' uri = user/password@host[:port]/sid[ as {sysdba|sysoper}] Return cx_Oracle.Connection instance", "1) if len(uri_l) == 2: credentials, mode = uri_l mode", "Example: .. code-block:: bash salt '*' oracle.version salt '*' oracle.version", "cx_Oracle.FIXED_CHAR, cx_Oracle.CLOB): return cursor.var(unicode, size, cursor.arraysize) def _connect(uri): ''' uri", "= get_version(db) return result @depends('cx_Oracle', fallback_function=_cx_oracle_req) def client_version(): ''' Oracle", "salt '*' oracle.show_pillar dbs:my_db ''' if item: return __salt__['pillar.get']('oracle:' +", "{} for db in dbs: result[db] = __salt__['pillar.get']('oracle:dbs:' + db)", "if cx_Oracle installed ''' return __virtualname__ if HAS_CX_ORACLE else False", "depends log = logging.getLogger(__name__) try: import cx_Oracle MODE = {", "def show_env(): ''' Show Environment used by Oracle Client CLI", "<NAME> <<EMAIL>> :maturity: new :depends: cx_Oracle :platform: all :configuration: module", "installed for this functin exist' def _unicode_output(cursor, name, default_type, size,", "in dbs: result[db] = __salt__['pillar.get']('oracle:dbs:' + db) return result else:", "this functin exist' def _unicode_output(cursor, name, default_type, size, precision, scale):", "from pillar: {0}'.format(dbs)) result = {} for db in dbs:", "conn.outputtypehandler = _unicode_output return conn @depends('cx_Oracle', fallback_function=_cx_oracle_req) def run_query(db, query):", "PATH **pillar** .. code-block:: text oracle.dbs: list of known based", "for r in run_query(x, \"select banner from v$version order by", "''' uri = user/password@host[:port]/sid[ as {sysdba|sysoper}] Return cx_Oracle.Connection instance '''", "else: log.debug('get all({0}) dbs versions'.format(len(dbs))) for db in dbs: result[db]", "connection credentials in format: user/password@host[:port]/sid[ as {sysdba|sysoper}] ''' import os", ":mainteiner: <NAME> <<EMAIL>> :maturity: new :depends: cx_Oracle :platform: all :configuration:", "dbs: result[db] = __salt__['pillar.get']('oracle:dbs:' + db) return result else: pillar_dbs", "mode = uri_l mode = MODE[mode] else: credentials = uri_l[0]", "for this functin exist' def _unicode_output(cursor, name, default_type, size, precision,", ".. code-block:: bash salt '*' oracle.version salt '*' oracle.version my_db", "note:: at first _connect() ``NLS_LANG`` will forced to '.AL32UTF8' '''", "result = {} if dbs: log.debug('get db versions for: {0}'.format(dbs))", "''' import os import logging from salt.utils.decorators import depends log", "= __salt__['pillar.get']('oracle:dbs:' + db) return result else: pillar_dbs = __salt__['pillar.get']('oracle:dbs')", "db) return result else: pillar_dbs = __salt__['pillar.get']('oracle:dbs') log.debug('get all ({0})", "return '.'.join((str(x) for x in cx_Oracle.clientversion())) def show_pillar(item=None): ''' Show", "return __salt__['pillar.get']('oracle') def show_env(): ''' Show Environment used by Oracle", "'*' oracle.show_dbs my_db ''' if dbs: log.debug('get dbs from pillar:", "HAS_CX_ORACLE = True except ImportError: MODE = {'sysdba': 2, 'sysoper':", "__salt__['pillar.get']('oracle:dbs') log.debug('get all ({0}) dbs from pillar'.format(len(pillar_dbs))) return pillar_dbs @depends('cx_Oracle',", "== 2: host, port = hostport_l else: host = hostport_l[0]", "mode) conn.outputtypehandler = _unicode_output return conn @depends('cx_Oracle', fallback_function=_cx_oracle_req) def run_query(db,", "need to be in PATH **pillar** .. code-block:: text oracle.dbs:", "dbs: log.debug('get dbs from pillar: {0}'.format(dbs)) result = {} for", "pillar'.format(len(pillar_dbs))) return pillar_dbs @depends('cx_Oracle', fallback_function=_cx_oracle_req) def version(*dbs): ''' Server Version", "result[db] = get_version(db) else: log.debug('get all({0}) dbs versions'.format(len(dbs))) for db", "pillar_dbs @depends('cx_Oracle', fallback_function=_cx_oracle_req) def version(*dbs): ''' Server Version (select banner", "ImportError: MODE = {'sysdba': 2, 'sysoper': 4} HAS_CX_ORACLE = False", "oracle.show_pillar dbs:my_db ''' if item: return __salt__['pillar.get']('oracle:' + item) else:", "used by Oracle Client CLI Example: .. code-block:: bash salt", "uri_l mode = MODE[mode] else: credentials = uri_l[0] mode =", "def _connect(uri): ''' uri = user/password@host[:port]/sid[ as {sysdba|sysoper}] Return cx_Oracle.Connection", "DataBase connection module :mainteiner: <NAME> <<EMAIL>> :maturity: new :depends: cx_Oracle", "'*' oracle.show_pillar salt '*' oracle.show_pillar dbs:my_db ''' if item: return", "module only if cx_Oracle installed ''' return __virtualname__ if HAS_CX_ORACLE", "def run_query(db, query): ''' Run SQL query and return result", "salt '*' oracle.show_pillar salt '*' oracle.show_pillar dbs:my_db ''' if item:", "HAS_CX_ORACLE = False __virtualname__ = 'oracle' def __virtual__(): ''' Load", "user/password@host[:port]/sid[ as {sysdba|sysoper}] ''' import os import logging from salt.utils.decorators", "password, cx_Oracle.makedsn(host, port, sid), mode) conn.outputtypehandler = _unicode_output return conn", "multiple Oracle DB instances. **OS Environment** .. code-block:: text ORACLE_HOME:", "bash salt '*' oracle.show_env .. note:: at first _connect() ``NLS_LANG``", "if dbs: log.debug('get dbs from pillar: {0}'.format(dbs)) result = {}", "def __virtual__(): ''' Load module only if cx_Oracle installed '''", "0 userpass, hostportsid = credentials.split('@') user, password = userpass.split('/') hostport,", "Environment used by Oracle Client CLI Example: .. code-block:: bash", "instance ''' # cx_Oracle.Connection() not support 'as sysdba' syntax uri_l", "''' Load module only if cx_Oracle installed ''' return __virtualname__", "cx_Oracle.makedsn(host, port, sid), mode) conn.outputtypehandler = _unicode_output return conn @depends('cx_Oracle',", "r[0] for r in run_query(x, \"select banner from v$version order", "''' Show Pillar segment oracle.* and subitem with notation \"item:subitem\"", "userpass.split('/') hostport, sid = hostportsid.split('/') hostport_l = hostport.split(':') if len(hostport_l)", "credentials, mode = uri_l mode = MODE[mode] else: credentials =", "log.debug('run query on {0}: {1}'.format(db, query)) conn = _connect(show_dbs(db)[db]['uri']) return", ".. code-block:: bash salt '*' oracle.client_version ''' return '.'.join((str(x) for", ":maturity: new :depends: cx_Oracle :platform: all :configuration: module provide connections", "log.debug('get all ({0}) dbs from pillar'.format(len(pillar_dbs))) return pillar_dbs @depends('cx_Oracle', fallback_function=_cx_oracle_req)", "oracle.show_dbs salt '*' oracle.show_dbs my_db ''' if dbs: log.debug('get dbs", "= credentials.split('@') user, password = userpass.split('/') hostport, sid = hostportsid.split('/')", "@depends('cx_Oracle', fallback_function=_cx_oracle_req) def version(*dbs): ''' Server Version (select banner from", "= hostportsid.split('/') hostport_l = hostport.split(':') if len(hostport_l) == 2: host,", "pillar_dbs: result[db] = get_version(db) else: log.debug('get all({0}) dbs versions'.format(len(dbs))) for", ":platform: all :configuration: module provide connections for multiple Oracle DB", "salt '*' oracle.show_dbs my_db ''' if dbs: log.debug('get dbs from", "oracle.* and subitem with notation \"item:subitem\" CLI Example: .. code-block::", "in PATH **pillar** .. code-block:: text oracle.dbs: list of known", "connections for multiple Oracle DB instances. **OS Environment** .. code-block::", "text ORACLE_HOME: path to oracle product PATH: path to Oracle", "salt '*' oracle.client_version ''' return '.'.join((str(x) for x in cx_Oracle.clientversion()))", "if default_type in (cx_Oracle.STRING, cx_Oracle.LONG_STRING, cx_Oracle.FIXED_CHAR, cx_Oracle.CLOB): return cursor.var(unicode, size,", "precision, scale): ''' Return strings values as python unicode string", "r in run_query(x, \"select banner from v$version order by banner\")", "conn = cx_Oracle.connect(user, password, cx_Oracle.makedsn(host, port, sid), mode) conn.outputtypehandler =", "credentials = uri_l[0] mode = 0 userpass, hostportsid = credentials.split('@')", "hostport.split(':') if len(hostport_l) == 2: host, port = hostport_l else:", "oracle.dbs: list of known based oracle.dbs.<db>.uri: connection credentials in format:", "Run SQL query and return result CLI example: .. code-block::", "\"item:subitem\" CLI Example: .. code-block:: bash salt '*' oracle.show_pillar salt", "list of known based oracle.dbs.<db>.uri: connection credentials in format: user/password@host[:port]/sid[", "oracle.version salt '*' oracle.version my_db ''' pillar_dbs = __salt__['pillar.get']('oracle:dbs') get_version", "bash salt '*' oracle.show_pillar salt '*' oracle.show_pillar dbs:my_db ''' if", "code-block:: text ORACLE_HOME: path to oracle product PATH: path to", "@depends('cx_Oracle', fallback_function=_cx_oracle_req) def client_version(): ''' Oracle Client Version CLI Example:", "= {} if dbs: log.debug('get db versions for: {0}'.format(dbs)) for", "of known based oracle.dbs.<db>.uri: connection credentials in format: user/password@host[:port]/sid[ as", "mode))) # force UTF-8 client encoding os.environ['NLS_LANG'] = '.AL32UTF8' conn", "result else: pillar_dbs = __salt__['pillar.get']('oracle:dbs') log.debug('get all ({0}) dbs from", "log.debug('get db versions for: {0}'.format(dbs)) for db in dbs: if", "else: credentials = uri_l[0] mode = 0 userpass, hostportsid =", "module :mainteiner: <NAME> <<EMAIL>> :maturity: new :depends: cx_Oracle :platform: all", "show_env(): ''' Show Environment used by Oracle Client CLI Example:", "'.'.join((str(x) for x in cx_Oracle.clientversion())) def show_pillar(item=None): ''' Show Pillar", "all({0}) dbs versions'.format(len(dbs))) for db in dbs: result[db] = get_version(db)", "return cursor.var(unicode, size, cursor.arraysize) def _connect(uri): ''' uri = user/password@host[:port]/sid[" ]
[ "catalog.register pytest.raises( consul.ConsulException, c.catalog.register, 'foo', '10.1.10.11', dc='dc2') assert c.catalog.register( 'n1',", "True time.sleep(40/1000.0) index, nodes = c.health.service(service_name) assert [node['Service']['ID'] for node", "the behavior assert c.kv.put('foo', '1', acquire=s) is True index, data", "c.kv.put('foo', 'bar') c.kv.put('private/foo', 'bar') c_limited = consul.Consul(port=acl_consul.port, token=token) assert c_limited.kv.get('foo')[1]['Value']", "'foobar', service_id='foobar', check=Check.ttl('10s')) time.sleep(40/1000.00) index, checks = c.health.checks('foobar') assert [check['ServiceID']", "assert c.agent.service.deregister('foo') is True def test_catalog(self, consul_port): c = consul.Consul(port=consul_port)", "both nodes are now available index, nodes = c.health.state('passing') assert", "= c.acl.create(rules=rules, token=master_token) assert c.acl.info(token)['Rules'] == rules token2 = c.acl.clone(token,", "'private/foo', 'bar2') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.delete, 'private/foo') # check we can", "= c.health.service('foo1') assert set([ check['ServiceID'] for node in nodes for", "= c.acl.clone(token) assert c.acl.info(token2)['Rules'] == rules assert c.acl.update(token2, name='Foo') ==", "# session.destroy pytest.raises( consul.ConsulException, c.session.destroy, session_id, dc='dc2') assert c.session.destroy(session_id) is", "len(queries) == 1 assert queries[0]['Name'] == query_name \\ and queries[0]['ID']", "'foo:1', 'foo:2']) # but that they aren't passing their health", "'private/foo', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'private/foo', 'bar2', token=token) pytest.raises( consul.ACLPermissionDenied,", "assert data['Value'] == six.b('bar2') def test_kv_put_flags(self, consul_port): c = consul.Consul(port=consul_port)", "is True index, data = c.kv.get('foo') assert data['Value'] == six.b('bar2')", "verify_check_status( 'ttl_check', 'critical', notes='something went boink!') assert c.agent.check.ttl_pass('ttl_check') is True", "verify_and_dereg_check('check_id') http_addr = \"http://127.0.0.1:{0}\".format(consul_port) assert c.agent.check.register( 'http_check', Check.http(http_addr, '10ms')) is", "time.sleep(1) verify_check_status('http_check', 'passing') verify_and_dereg_check('http_check') assert c.agent.check.register( 'http_timeout_check', Check.http(http_addr, '100ms', timeout='2s'))", "'foo', service_id='foo:1', check=Check.ttl('10s')) c.agent.service.register( 'foo', service_id='foo:2', check=Check.ttl('100ms')) time.sleep(40/1000.0) # check", "value def test_event(self, consul_port): c = consul.Consul(port=consul_port) assert c.event.fire(\"fooname\", \"foobody\")", "c = consul.Consul(port=consul_port) # test binary c.kv.put('foo', struct.pack('i', 1000)) index,", "\\ set(['anonymous', master_token]) assert c.acl.info('1'*36) is None compare = [c.acl.info(master_token),", "assert c.catalog.register( 'n1', '10.1.10.11', service={'service': 's1'}, check={'name': 'c1'}) is True", "our server created, so we can ignore it _, nodes", "and str(query['ID']) != '' # retrieve query using id and", "c.health.service('foo') assert nodes == [] # register two nodes, one", "assert [x['Name'] for x in sessions] == ['my-session'] # session.info", "assert c.query.delete(query['ID']) def test_coordinate(self, consul_port): c = consul.Consul(port=consul_port) c.coordinate.nodes() c.coordinate.datacenters()", "nodes = c.health.service('foo') assert nodes == [] # register two", "we can override the client's default token pytest.raises( consul.ACLPermissionDenied, c.kv.get,", "session pytest.raises(consul.NotFound, c.session.renew, '1'*36) session = c.session.renew(s) assert session['Behavior'] ==", "ID assert 'ID' in query \\ and query['ID'] is not", "[node['Service']['ID'] for node in nodes] == ['foo:1', 'foo:2'] # check", "notes='all hunky dory!') is True verify_check_status('ttl_check', 'passing', notes='all hunky dory!')", "c.agent.service.register(\"foo-1\", token=token) index, data = c.health.service('foo-1', token=token) assert data[0]['Service']['ID'] ==", "is False assert c.kv.put('foo', 'bar', cas=0) is True index, data", "assert http.uri('/v1/kv') == 'http://127.0.0.1:8500/v1/kv' assert http.uri('/v1/kv', params={'index': 1}) == \\", "consul.Consul(port=consul_port) c.kv.put('foo1', '1') c.kv.put('foo2', '2') c.kv.put('foo3', '3') index, data =", "in nodes] == [service_name] # Clean up tasks assert c.agent.service.deregister(service_name)", "c.kv.delete, 'foo', token=token) assert c.kv.get('private/foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c.kv.get,", "= agent_self['Stats']['consul']['leader_addr'] peers = c.status.peers() assert addr_port in peers, \\", "c.session.destroy(s1) c.session.destroy(s2) def test_kv_keys_only(self, consul_port): c = consul.Consul(port=consul_port) assert c.kv.put('bar',", "x in acls]) == \\ set(['anonymous', master_token]) assert c.acl.info('foo') is", "assert [x['Name'] == 'fooname' for x in events] assert [x['Payload']", "tag='tag:foo:1') assert [node['Service']['ID'] for node in nodes] == ['foo:1'] #", "data = c.kv.get('foo') assert data['Flags'] == 50 def test_kv_recurse(self, consul_port):", "c.agent.check.ttl_pass('service:foo:1') c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0) # both nodes are now available index,", "c.kv.put('foo', 'bar', cas=50) is False assert c.kv.put('foo', 'bar', cas=0) is", "== 1 leader = False voter = False for server", "sessions] == ['my-session'] # session.destroy pytest.raises( consul.ConsulException, c.session.destroy, session_id, dc='dc2')", "assert [ v['Address'] for k, v in c.agent.services().items() if k", "check=Check.ttl('100ms')) time.sleep(40/1000.0) # check the nodes show for the /health/state/any", "= c.agent.members(wan=True) for x in wan_members: assert 'dc1' in x['Name']", "== 1 assert not x['Name'] is None assert not x['Tags']", "'foo', 'bar2') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.delete, 'foo') assert c.kv.get('private/foo')[1]['Value'] == six.b('bar')", "ttl, the other shorter c.agent.service.register( 'foo', service_id='foo:1', check=Check.ttl('10s')) c.agent.service.register( 'foo',", "time.sleep(40/1000.0) checks_post = c.agent.checks() assert '_service_maintenance:foo' not in checks_post.keys() #", "in c.agent.services().items() if k == 'foo'][0] == '10.10.10.1' assert c.agent.service.deregister('foo')", "c.kv.delete('foo2') is True index, data = c.kv.get('foo', recurse=True) assert [x['Key']", "check the nodes weren't removed _, nodes = c.catalog.nodes() nodes.remove(current)", "'foo', 'bar2', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'foo', token=token) assert c.kv.get('private/foo')[1]['Value']", "c.agent.service.register, \"bar-1\", token=token) c.agent.service.register(\"foo-1\", token=token) index, data = c.health.service('foo-1', token=token)", "test_kv_acquire_release(self, consul_port): c = consul.Consul(port=consul_port) pytest.raises( consul.ConsulException, c.kv.put, 'foo', 'bar',", "c = consul.Consul(port=consul_port) index, nodes = c.health.service(\"foo1\") assert nodes ==", "as `None` c.kv.put('foo', '') index, data = c.kv.get('foo') assert data['Value']", "test setting notes on a check c.agent.check.register('check', Check.ttl('1s'), notes='foo') assert", "def test_agent_register_enable_tag_override(self, consul_port): c = consul.Consul(port=consul_port) index, nodes = c.health.service(\"foo1\")", "set(['Member', 'Stats', 'Config', 'Coord', 'DebugConfig', 'Meta']) def test_agent_services(self, consul_port): c", "# check unencoded values raises assert pytest.raises(AssertionError, c.kv.put, 'foo', {1:", "== ['foobar'] assert [check['CheckID'] for check in checks] == ['service:foobar']", "c = consul.Consul(port=consul_port) c.kv.put('foo1', '1') c.kv.put('foo2', '2') c.kv.put('foo3', '3') index,", "is False assert c.kv.put('foo', '1', acquire=s1) is True assert c.kv.put('foo',", "r = c.txn.put([d]) assert r[\"Results\"][0][\"KV\"][\"Value\"] == value def test_event(self, consul_port):", "set(c.agent.self().keys()) == set(['Member', 'Stats', 'Config', 'Coord', 'DebugConfig', 'Meta']) def test_agent_services(self,", "assert c.kv.put('base/base/foo', '5') is True index, data = c.kv.get('base/', keys=True,", "show for the /health/service endpoint index, nodes = c.health.service('foo') assert", "sessions] == ['my-session'] # session.info pytest.raises( consul.ConsulException, c.session.info, session_id, dc='dc2')", "data = c.kv.get('foo/', recurse=True) assert len(data) == 1 c.kv.put('foo/bar1', '1')", "is True index, data = c.kv.get('foo', recurse=True) assert data is", "list but it was not present\".format(addr_port) def test_query(self, consul_port): c", "consul.ConsulException, c.catalog.deregister, 'n2', dc='dc2') assert c.catalog.deregister('n1', check_id='c1') is True assert", "\"get\", \"Key\": \"asdf\"}} r = c.txn.put([d]) assert r[\"Results\"][0][\"KV\"][\"Value\"] == value", "members = c.agent.members() for x in members: assert x['Status'] ==", "assert c.kv.put('foo', 'bar', cas=0) is True index, data = c.kv.get('foo')", "c.kv.put('foo', 'bar') c.kv.put('private/foo', 'bar') assert c.kv.get('foo', token=token)[1]['Value'] == six.b('bar') pytest.raises(", "== [] c.agent.service.register('foo', enable_tag_override=True) assert c.agent.services()['foo']['EnableTagOverride'] # Cleanup tasks c.agent.check.deregister('foo')", "c.kv.put('foo', '2', release=s1) is True c.session.destroy(s1) c.session.destroy(s2) def test_kv_keys_only(self, consul_port):", "is True assert set(c.agent.services().keys()) == set(['foo']) assert c.agent.service.deregister('foo') is True", "True index, data = c.kv.get('foo') assert data['Value'] == six.b('bar2') def", "consul.ConsulException, c.session.node, node, dc='dc2') _, sessions = c.session.node(node) assert [x['Name']", "not data # clean up assert c.agent.service.deregister('foo-1') is True c.acl.destroy(token,", "assert c.kv.get('private/foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c.kv.get, 'private/foo', token=token) pytest.raises(", "token=master_token) assert c.acl.info(token)['Rules'] == rules token2 = c.acl.clone(token, token=master_token) assert", "== six.b('bar') pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'foo', 'bar2', token=token) pytest.raises( consul.ACLPermissionDenied,", "test_health_service(self, consul_port): c = consul.Consul(port=consul_port) # check there are no", "== compare rules = \"\"\" key \"\" { policy =", "assert [x['Key'] for x in data] == [ 'foo/', 'foo/bar1',", "False assert c.kv.get('foo') == (index, data) assert c.kv.delete('foo', cas=data['ModifyIndex']) is", "c.agent.service.register('foo') is True assert set(c.agent.services().keys()) == set(['foo']) assert c.agent.service.deregister('foo') is", "!= '' # retrieve query using id and name queries", "recurse=True) is True index, data = c.kv.get('foo', recurse=True) assert data", "'4') is True assert c.kv.put('base/foo', '1') is True assert c.kv.put('base/base/foo',", "= c.health.service(\"foo1\") assert nodes == [] pytest.raises(consul.std.base.ConsulException, c.agent.check.register, 'foo', Check.ttl('100ms'),", "== [] def test_agent_checks_service_id(self, consul_port): c = consul.Consul(port=consul_port) c.agent.service.register('foo1') time.sleep(40/1000.0)", "c.status.leader() addr_port = agent_self['Stats']['consul']['leader_addr'] assert leader == addr_port, \\ \"Leader", "= consul.Consul(port=consul_port) assert c.kv.put('foo', 'bar') is True index, data =", "c = consul.Consul(port=consul_port) index, data = c.kv.get('foo') assert data is", "def test_coordinate(self, consul_port): c = consul.Consul(port=consul_port) c.coordinate.nodes() c.coordinate.datacenters() assert set(c.coordinate.datacenters()[0].keys())", "data) assert c.kv.delete('foo', cas=data['ModifyIndex']) is True index, data = c.kv.get('foo')", "index, data = c.kv.get('foo') assert data['Flags'] == 50 def test_kv_recurse(self,", "assert pytest.raises(AssertionError, c.kv.put, 'foo', {1: 2}) def test_kv_put_cas(self, consul_port): c", "test_agent_checks_service_id(self, consul_port): c = consul.Consul(port=consul_port) c.agent.service.register('foo1') time.sleep(40/1000.0) index, nodes =", "notes='its not quite right') is True verify_check_status('ttl_check', 'warning', 'its not", "'ttl_check', notes='something went boink!') is True verify_check_status( 'ttl_check', 'critical', notes='something", "the other shorter c.agent.service.register( 'foo', service_id='foo:1', check=Check.ttl('10s')) c.agent.service.register( 'foo', service_id='foo:2',", "assert node in [check[\"Node\"] for check in checks] def test_health_checks(self,", "data = c.health.service('bar-1', token=token) assert not data # clean up", "in data] == [ 'foo/', 'foo/bar1', 'foo/bar2', 'foo/bar3'] assert [x['Value']", "query['ID'] # explain query assert c.query.explain(query_name)['Query'] # delete query assert", "# wait for ttl to expire time.sleep(120/1000.0) verify_check_status('ttl_check', 'critical') verify_and_dereg_check('ttl_check')", "False assert c.kv.put('foo', '2', release=s2) is False assert c.kv.put('foo', '2',", "c.kv.get('foo') assert data['Value'] == six.b('bar') def test_kv_wait(self, consul_port): c =", "c.agent.service.deregister('foo') is True def test_catalog(self, consul_port): c = consul.Consul(port=consul_port) #", "= c.agent.self() addr_port = agent_self['Stats']['consul']['leader_addr'] peers = c.status.peers() assert addr_port", "None index, session = c.session.info(session_id) assert session['Name'] == 'my-session' #", "None def test_kv_delete_cas(self, consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo', 'bar') index,", "c.kv.get('foo', token=token)[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'foo', 'bar2', token=token)", "pytest.raises(consul.ACLPermissionDenied, c.acl.create) pytest.raises(consul.ACLPermissionDenied, c.acl.update, 'anonymous') pytest.raises(consul.ACLPermissionDenied, c.acl.clone, 'anonymous') pytest.raises(consul.ACLPermissionDenied, c.acl.destroy,", "'bar2', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'private/foo', token=token) # test token", "for the /health/service endpoint index, nodes = c.health.service('foo') assert [node['Service']['ID']", "c.acl.destroy(token, token=master_token) acls = c.acl.list(token=master_token) assert set([x['ID'] for x in", "base64 import operator import struct import time import pytest import", "struct import time import pytest import six import consul import", "session.create pytest.raises(consul.ConsulException, c.session.create, node='n2') pytest.raises(consul.ConsulException, c.session.create, dc='dc2') session_id = c.session.create('my-session')", "consul.Consul(port=acl_consul.port) pytest.raises(consul.ACLPermissionDenied, c.acl.list) pytest.raises(consul.ACLPermissionDenied, c.acl.create) pytest.raises(consul.ACLPermissionDenied, c.acl.update, 'anonymous') pytest.raises(consul.ACLPermissionDenied, c.acl.clone,", "'_node_maintenance' not in checks_post.keys() def test_agent_members(self, consul_port): c = consul.Consul(port=consul_port)", "'AreaID']) def test_operator(self, consul_port): c = consul.Consul(port=consul_port) config = c.operator.raft_config()", "Check.http(http_addr, '100ms', timeout='2s')) is True verify_and_dereg_check('http_timeout_check') assert c.agent.check.register('ttl_check', Check.ttl('100ms')) is", "test_kv_wait(self, consul_port): c = consul.Consul(port=consul_port) assert c.kv.put('foo', 'bar') is True", "assert c.kv.delete('foo2') is True index, data = c.kv.get('foo', recurse=True) assert", "c.health.service('foo') assert [node['Service']['ID'] for node in nodes] == ['foo:1', 'foo:2']", "\\ set(['anonymous', master_token]) def test_status_leader(self, consul_port): c = consul.Consul(port=consul_port) agent_self", "assert data['Value'] == six.b('bar') # test empty-string comes back as", "== 'my-session' # session.node node = session['Node'] pytest.raises( consul.ConsulException, c.session.node,", "index, data = c.kv.get('foo') assert c.kv.delete('foo', cas=data['ModifyIndex']-1) is False assert", "assert set(node['Services'].keys()) == set(['s1', 's2']) _, node = c.catalog.node('n3') assert", "is True # check the nodes weren't removed _, nodes", "= {\"KV\": {\"Verb\": \"get\", \"Key\": \"asdf\"}} r = c.txn.put([d]) assert", "check c.agent.check.register('check', Check.ttl('1s'), notes='foo') assert c.agent.checks()['check']['Notes'] == 'foo' c.agent.check.deregister('check') assert", "'bar') index, data = c.kv.get('foo') assert c.kv.delete('foo', cas=data['ModifyIndex']-1) is False", "c.agent.check.deregister('foo') is True time.sleep(40/1000.0) assert c.agent.service.deregister('foo1') is True time.sleep(40/1000.0) def", "nodes = c.health.service('foo1') assert set([ check['ServiceID'] for node in nodes", "session.info pytest.raises( consul.ConsulException, c.session.info, session_id, dc='dc2') index, session = c.session.info('1'*36)", "None c.kv.put('foo', 'bar') c.kv.put('private/foo', 'bar') c_limited = consul.Consul(port=acl_consul.port, token=token) assert", "data = c.kv.get('foo/', recurse=True) assert [x['Key'] for x in data]", "def test_agent_checks(self, consul_port): c = consul.Consul(port=consul_port) def verify_and_dereg_check(check_id): assert set(c.agent.checks().keys())", "is True index, data = c.kv.get('foo') assert c.kv.put('foo', 'bar2', cas=data['ModifyIndex']-1)", "set(['s1', 's2']) _, node = c.catalog.node('n3') assert node is None", "nodes = c.health.service(\"foo1\") assert nodes == [] c.agent.service.register('foo', enable_tag_override=True) assert", "master_token]) def test_acl_implicit_token_use(self, acl_consul): # configure client to use the", "check={'name': 'c1'}) is True assert c.catalog.register( 'n1', '10.1.10.11', service={'service': 's2'})", "test_service_dereg_issue_156(self, consul_port): # https://github.com/cablehead/python-consul/issues/156 service_name = 'app#127.0.0.1#3000' c = consul.Consul(port=consul_port)", "= consul.Consul(port=consul_port) c.kv.put('foo', 'bar') index, data = c.kv.get('foo') assert data['Flags']", "passing=True) assert nodes == [] # ping the two node's", "c.health.service(\"foo1\") assert nodes == [] pytest.raises(consul.std.base.ConsulException, c.agent.check.register, 'foo', Check.ttl('100ms'), service_id='foo1')", "pytest.raises(consul.ACLPermissionDenied, c.acl.clone, 'anonymous') pytest.raises(consul.ACLPermissionDenied, c.acl.destroy, 'anonymous') def test_acl_explict_token_use(self, acl_consul): c", "token=token) # test token pass through for service registration pytest.raises(", "two nodes, one with a long ttl, the other shorter", "assert [x['Payload'] == 'foobody' for x in events] def test_event_targeted(self,", "True def test_catalog(self, consul_port): c = consul.Consul(port=consul_port) # grab the", "service 'foo' index, nodes = c.health.service('foo') assert nodes == []", "pytest.raises(consul.NotFound, c.session.renew, '1'*36) session = c.session.renew(s) assert session['Behavior'] == 'delete'", "empty queries = c.query.list() assert queries == [] # create", "nodes == [] c.agent.service.register('foo', enable_tag_override=True) assert c.agent.services()['foo']['EnableTagOverride'] # Cleanup tasks", "assert set([ check['CheckID'] for node in nodes for check in", "== [service_name] # Clean up tasks assert c.agent.service.deregister(service_name) is True", "== 1 current = nodes[0] # test catalog.datacenters assert c.catalog.datacenters()", "nodes = c.health.state('any') assert [node['ServiceID'] for node in nodes] ==", "set( ['', 'foo:1']) # ping the failed node's health check", "tasks c.agent.check.deregister('foo') def test_agent_service_maintenance(self, consul_port): c = consul.Consul(port=consul_port) c.agent.service.register('foo', check=Check.ttl('100ms'))", "not present\".format(addr_port) def test_query(self, consul_port): c = consul.Consul(port=consul_port) # check", "c.query.create(query_service, query_name) # assert response contains query ID assert 'ID'", "assert c.acl.info('1'*36) is None compare = [c.acl.info(master_token), c.acl.info('anonymous')] compare.sort(key=operator.itemgetter('ID')) assert", "assert c.acl.info(token2)['Name'] == 'Foo' assert c.acl.destroy(token2, token=master_token) is True assert", "data = c.kv.get('foo') assert data['Value'] is None # test None", "assert c.acl.update(token2, name='Foo', token=master_token) == token2 assert c.acl.info(token2)['Name'] == 'Foo'", "cas=data['ModifyIndex']) is True index, data = c.kv.get('foo') assert data['Value'] ==", "shorter c.agent.service.register( 'foo', service_id='foo:1', check=Check.ttl('10s')) c.agent.service.register( 'foo', service_id='foo:2', check=Check.ttl('100ms')) time.sleep(40/1000.0)", "== rules token2 = c.acl.clone(token) assert c.acl.info(token2)['Rules'] == rules assert", "test_query(self, consul_port): c = consul.Consul(port=consul_port) # check that query list", "'') index, data = c.kv.get('foo') assert data['Value'] is None #", "# Cleanup tasks c.agent.check.deregister('foo') def test_agent_service_maintenance(self, consul_port): c = consul.Consul(port=consul_port)", "nodes.remove(current) assert [x['Node'] for x in nodes] == ['n1', 'n2']", "# check the nodes show for the /health/state/any endpoint index,", "r[\"Results\"][0][\"KV\"][\"Value\"] == value def test_event(self, consul_port): c = consul.Consul(port=consul_port) assert", "nodes = c.health.service('foo', passing=True) assert nodes == [] # ping", "== ['base/base/', 'base/foo'] def test_transaction(self, consul_port): c = consul.Consul(port=consul_port) value", "consul_port): c = consul.Consul(port=consul_port) assert c.kv.put('foo', 'bar') is True index,", "is None # test catalog.service pytest.raises( consul.ConsulException, c.catalog.service, 's1', dc='dc2')", "<filename>tests/test_std.py import base64 import operator import struct import time import", "True verify_and_dereg_check('http_timeout_check') assert c.agent.check.register('ttl_check', Check.ttl('100ms')) is True assert c.agent.check.ttl_warn('ttl_check') is", "c.acl.update(token2, name='Foo', token=master_token) == token2 assert c.acl.info(token2)['Name'] == 'Foo' assert", "'ttl_check', 'critical', notes='something went boink!') assert c.agent.check.ttl_pass('ttl_check') is True verify_check_status('ttl_check',", "assert c.query.explain(query_name)['Query'] # delete query assert c.query.delete(query['ID']) def test_coordinate(self, consul_port):", "== set(['n1', 'n2']) _, nodes = c.catalog.service('s1', tag='master') assert set([x['Node']", "== set(['n1']) # cleanup assert c.catalog.deregister('n1') is True assert c.catalog.deregister('n2')", "nodes] == ['n1', 'n2'] # test catalog.services pytest.raises(consul.ConsulException, c.catalog.services, dc='dc2')", "c.catalog.service, 's1', dc='dc2') _, nodes = c.catalog.service('s1') assert set([x['Node'] for", "in events] def test_agent_checks(self, consul_port): c = consul.Consul(port=consul_port) def verify_and_dereg_check(check_id):", "node = session['Node'] pytest.raises( consul.ConsulException, c.session.node, node, dc='dc2') _, sessions", "c = consul.Consul(port=acl_consul.port) master_token = acl_consul.token acls = c.acl.list(token=master_token) assert", "c.health.state('passing') assert set([node['ServiceID'] for node in nodes]) == set( ['',", "assert '_node_maintenance' not in checks_post.keys() def test_agent_members(self, consul_port): c =", "[x['Key'] for x in data] == [ 'foo/', 'foo/bar1', 'foo/bar2',", "assert [x['Node'] for x in nodes] == [] def test_health_service(self,", "token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'private/foo', 'bar2', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete,", "data is None def test_kv_acquire_release(self, consul_port): c = consul.Consul(port=consul_port) pytest.raises(", "in data] == ['foo1', 'foo2', 'foo3'] assert c.kv.delete('foo2') is True", "'check name', Check.script('/bin/true', 10), check_id='check_id') is True verify_and_dereg_check('check_id') http_addr =", "is None # test None c.kv.put('foo', None) index, data =", "assert c.acl.info(token2)['Rules'] == rules assert c.acl.update(token2, name='Foo') == token2 assert", "assert data is None def test_kv_delete_cas(self, consul_port): c = consul.Consul(port=consul_port)", "= c.status.peers() assert addr_port in peers, \\ \"Expected value '{0}'", "\"\"\" token = c.acl.create(rules=rules) assert c.acl.info(token)['Rules'] == rules token2 =", "assert index == check def test_kv_encoding(self, consul_port): c = consul.Consul(port=consul_port)", "data] == ['foo1', 'foo3'] assert c.kv.delete('foo', recurse=True) is True index,", "\\ set(['anonymous', master_token]) assert c.acl.info('foo') is None compare = [c.acl.info(master_token),", "query = c.query.create(query_service, query_name) # assert response contains query ID", "not quite right') assert c.agent.check.ttl_fail('ttl_check') is True verify_check_status('ttl_check', 'critical') assert", "recurse=True) assert [x['Key'] for x in data] == ['foo1', 'foo3']", "'Coordinates', 'AreaID']) def test_operator(self, consul_port): c = consul.Consul(port=consul_port) config =", "release=s1) is True c.session.destroy(s1) c.session.destroy(s2) def test_kv_keys_only(self, consul_port): c =", "checks_post.keys() def test_agent_members(self, consul_port): c = consul.Consul(port=consul_port) members = c.agent.members()", "nodes]) == set(['n2']) # test catalog.deregister pytest.raises( consul.ConsulException, c.catalog.deregister, 'n2',", "== [''] def test_health_node(self, consul_port): c = consul.Consul(port=consul_port) # grab", "assert 'test' == checks_pre['_node_maintenance']['Notes'] c.agent.maintenance('false') time.sleep(40/1000.0) checks_post = c.agent.checks() assert", "check there are no nodes for the service 'foo' index,", "nodes]) == set(['n1']) # cleanup assert c.catalog.deregister('n1') is True assert", "service_id='foo:1', check=Check.ttl('10s')) c.agent.service.register( 'foo', service_id='foo:2', check=Check.ttl('100ms')) time.sleep(40/1000.0) # check the", "= c.kv.get('foo') assert data['Flags'] == 0 assert c.kv.put('foo', 'bar', flags=50)", "notes='something went boink!') is True verify_check_status( 'ttl_check', 'critical', notes='something went", "TestHTTPClient(object): def test_uri(self): http = consul.std.HTTPClient() assert http.uri('/v1/kv') == 'http://127.0.0.1:8500/v1/kv'", "check that query list is empty queries = c.query.list() assert", "len(data) == 1 c.kv.put('foo/bar1', '1') c.kv.put('foo/bar2', '2') c.kv.put('foo/bar3', '3') index,", "query['ID'] is not None \\ and str(query['ID']) != '' #", "= c.catalog.service('s1') assert set([x['Node'] for x in nodes]) == set(['n1',", "index, nodes = c.health.service('foo1') assert set([ check['ServiceID'] for node in", "[], 'consul': []} # test catalog.node pytest.raises(consul.ConsulException, c.catalog.node, 'n1', dc='dc2')", "assert c.agent.check.deregister(check_id) is True assert set(c.agent.checks().keys()) == set([]) def verify_check_status(check_id,", "c.kv.get('foo') assert data is None def test_kv_acquire_release(self, consul_port): c =", "= consul.Consul(port=acl_consul.port, token=token) assert c_limited.kv.get('foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.put,", "are no nodes for the service 'foo' index, nodes =", "c.acl.info(token)['Rules'] == rules token2 = c.acl.clone(token) assert c.acl.info(token2)['Rules'] == rules", "unencoded values raises assert pytest.raises(AssertionError, c.kv.put, 'foo', {1: 2}) def", "server in config[\"Servers\"]: if server[\"Leader\"]: leader = True if server[\"Voter\"]:", "the nodes show for the /health/service endpoint index, nodes =", "'n2'] # check n2's s1 service was removed though _,", "assert '_node_maintenance' in checks_pre.keys() assert 'test' == checks_pre['_node_maintenance']['Notes'] c.agent.maintenance('false') time.sleep(40/1000.0)", "time.sleep(40/1000.0) index, nodes = c.health.service('foo') assert nodes == [] def", "c.agent.self()['Member'] in members wan_members = c.agent.members(wan=True) for x in wan_members:", "time.sleep(40/1000.0) assert c.agent.service.deregister('foo1') is True time.sleep(40/1000.0) def test_agent_register_check_no_service_id(self, consul_port): c", "consul.Consul(port=consul_port) assert c.agent.service.register('foo') is True assert set(c.agent.services().keys()) == set(['foo']) assert", "[node['Service']['ID'] for node in nodes] == [] def test_agent_checks_service_id(self, consul_port):", "import struct import time import pytest import six import consul", "node['Checks']]) == set(['foo1', '']) assert set([ check['CheckID'] for node in", "assert nodes == [] pytest.raises(consul.std.base.ConsulException, c.agent.check.register, 'foo', Check.ttl('100ms'), service_id='foo1') time.sleep(40/1000.0)", "# both nodes are now available index, nodes = c.health.state('passing')", "= c.health.service('foo', passing=True) assert nodes == [] # ping the", "c = consul.Consul(port=acl_consul.port, token=acl_consul.token) master_token = acl_consul.token acls = c.acl.list()", "consul.Consul(port=consul_port) # check that query list is empty queries =", "nodes == [] pytest.raises(consul.std.base.ConsulException, c.agent.check.register, 'foo', Check.ttl('100ms'), service_id='foo1') time.sleep(40/1000.0) assert", "assert len(nodes) == 1 current = nodes[0] # test catalog.datacenters", "== set([]) def verify_check_status(check_id, status, notes=None): checks = c.agent.checks() assert", "available index, nodes = c.health.service('foo', passing=True) assert [node['Service']['ID'] for node", "def test_agent_node_maintenance(self, consul_port): c = consul.Consul(port=consul_port) c.agent.maintenance('true', \"test\") time.sleep(40/1000.0) checks_pre", "pytest.raises(consul.ConsulException, c.catalog.services, dc='dc2') _, services = c.catalog.services() assert services ==", "the nodes weren't removed _, nodes = c.catalog.nodes() nodes.remove(current) assert", "v['Address'] for k, v in c.agent.services().items() if k == 'foo'][0]", "nodes are available index, nodes = c.health.state('passing') assert set([node['ServiceID'] for", "c = consul.Consul(port=consul_port) s = c.session.create(behavior='delete', ttl=20) # attempt to", "s1 service was removed though _, nodes = c.catalog.service('s1') assert", "one node available index, nodes = c.health.service('foo', passing=True) assert [node['Service']['ID']", "\\ \"in peer list but it was not present\".format(addr_port) def", "for x in acls]) == \\ set(['anonymous', master_token]) def test_status_leader(self,", "consul.Consul(port=consul_port) members = c.agent.members() for x in members: assert x['Status']", "nodes] == ['foo:1', 'foo:2'] # wait until the short ttl", "test catalog.deregister pytest.raises( consul.ConsulException, c.catalog.deregister, 'n2', dc='dc2') assert c.catalog.deregister('n1', check_id='c1')", "def test_acl_explict_token_use(self, acl_consul): c = consul.Consul(port=acl_consul.port) master_token = acl_consul.token acls", "'foo', '10.1.10.11', dc='dc2') assert c.catalog.register( 'n1', '10.1.10.11', service={'service': 's1'}, check={'name':", "check['CheckID'] for node in nodes for check in node['Checks']]) ==", "the nodes c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2') time.sleep(40/1000.0) index, nodes = c.health.service('foo') assert", "assert [x['Key'] for x in data] == ['foo1', 'foo3'] assert", "x in sessions] == ['my-session'] # session.info pytest.raises( consul.ConsulException, c.session.info,", "in node['Checks']]) == set(['foo', 'serfHealth']) # Clean up tasks assert", "removed though _, nodes = c.catalog.service('s1') assert set([x['Node'] for x", "string is for the Serf Health Status check, which has", "is for the Serf Health Status check, which has an", "True assert c.kv.put('base/foo', '1') is True assert c.kv.put('base/base/foo', '5') is", "[x['Name'] == 'fooname' for x in events] assert [x['Payload'] ==", "assert c.kv.get('private/foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.get, 'private/foo') pytest.raises( consul.ACLPermissionDenied,", "def test_operator(self, consul_port): c = consul.Consul(port=consul_port) config = c.operator.raft_config() assert", "['foo:1', 'foo:2'] # but that they aren't passing their health", "is True verify_and_dereg_check('http_timeout_check') assert c.agent.check.register('ttl_check', Check.ttl('100ms')) is True assert c.agent.check.ttl_warn('ttl_check')", "== check def test_kv_encoding(self, consul_port): c = consul.Consul(port=consul_port) # test", "assert sessions == [] def test_session_delete_ttl_renew(self, consul_port): c = consul.Consul(port=consul_port)", "checks[check_id]['Output'] == notes # test setting notes on a check", "c.kv.put('foo', 'bar') is True index, data = c.kv.get('foo') assert data['Value']", "None) index, data = c.kv.get('foo/', recurse=True) assert len(data) == 1", "= c.catalog.node('n1') assert set(node['Services'].keys()) == set(['s1', 's2']) _, node =", "named query query_service = 'foo' query_name = 'fooquery' query =", "pytest.raises( consul.ConsulException, c.catalog.deregister, 'n2', dc='dc2') assert c.catalog.deregister('n1', check_id='c1') is True", "checks = c.health.checks('foobar') assert len(checks) == 0 def test_session(self, consul_port):", "c.agent.services()['foo']['EnableTagOverride'] # Cleanup tasks c.agent.check.deregister('foo') def test_agent_service_maintenance(self, consul_port): c =", "(1000,) # test unicode c.kv.put('foo', u'bar') index, data = c.kv.get('foo')", "== \\ set(['anonymous', master_token]) assert c.acl.info('1'*36) is None compare =", "nodes]) == set( ['', 'foo:1', 'foo:2']) # but that they", "a check c.agent.check.register('check', Check.ttl('1s'), notes='foo') assert c.agent.checks()['check']['Notes'] == 'foo' c.agent.check.deregister('check')", "tasks assert c.agent.service.deregister(service_name) is True time.sleep(40/1000.0) index, nodes = c.health.service(service_name)", "node in nodes] == ['foo:1'] # ping the failed node's", "assert c.kv.put('foo', 'bar') is True index, data = c.kv.get('foo') check,", "client to use the master token by default c =", "for node in nodes] == [service_name] # Clean up tasks", "c.kv.put('foo3', '3') index, data = c.kv.get('foo', recurse=True) assert [x['Key'] for", "# session.create pytest.raises(consul.ConsulException, c.session.create, node='n2') pytest.raises(consul.ConsulException, c.session.create, dc='dc2') session_id =", "== set([check_id]) assert c.agent.check.deregister(check_id) is True assert set(c.agent.checks().keys()) == set([])", "nodes = c.catalog.nodes() assert len(nodes) == 1 current = nodes[0]", "pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'private/foo', 'bar2', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'private/foo',", "only one node available index, nodes = c.health.state('passing') assert set([node['ServiceID']", "== [] def test_health_service(self, consul_port): c = consul.Consul(port=consul_port) # check", "node in nodes] == [''] def test_health_node(self, consul_port): c =", "not quite right') is True verify_check_status('ttl_check', 'warning', 'its not quite", "v in c.agent.services().items() if k == 'foo'][0] == '10.10.10.1' assert", "data = c.kv.get('foo') assert data['Value'] == six.b('1') c.session.destroy(s) index, data", "'2', release=s1) is True c.session.destroy(s1) c.session.destroy(s2) def test_kv_keys_only(self, consul_port): c", "['', 'foo:1', 'foo:2']) # wait until the short ttl node", "by default c = consul.Consul(port=acl_consul.port, token=acl_consul.token) master_token = acl_consul.token acls", "test_kv_put_flags(self, consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo', 'bar') index, data =", "assert c.kv.put('foo', '1', release='foo') is False assert c.kv.put('foo', '2', release=s2)", "import consul.std Check = consul.Check class TestHTTPClient(object): def test_uri(self): http", "name node = c.agent.self()['Config']['NodeName'] index, checks = c.health.node(node) assert node", "c.kv.get('foo') assert data['Flags'] == 50 def test_kv_recurse(self, consul_port): c =", "queries = c.query.list() assert queries == [] # create a", "verify_check_status('ttl_check', 'warning', 'its not quite right') assert c.agent.check.ttl_fail('ttl_check') is True", "True index, data = c.kv.get('foo') check, data = c.kv.get('foo', index=index,", "c = consul.Consul(port=consul_port) assert c.event.fire(\"fooname\", \"foobody\") index, events = c.event.list(name=\"othername\")", "verify_check_status('ttl_check', 'warning') assert c.agent.check.ttl_warn( 'ttl_check', notes='its not quite right') is", "assert not data # clean up assert c.agent.service.deregister('foo-1') is True", "pytest.raises( consul.ACLPermissionDenied, c_limited.kv.get, 'private/foo') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.put, 'private/foo', 'bar2') pytest.raises(", "= 'app#127.0.0.1#3000' c = consul.Consul(port=consul_port) c.agent.service.register(service_name) time.sleep(80/1000.0) index, nodes =", "'foo:2']) # but that they aren't passing their health check", "test_acl_permission_denied(self, acl_consul): c = consul.Consul(port=acl_consul.port) pytest.raises(consul.ACLPermissionDenied, c.acl.list) pytest.raises(consul.ACLPermissionDenied, c.acl.create) pytest.raises(consul.ACLPermissionDenied,", "} \"\"\" token = c.acl.create(rules=rules, token=master_token) assert c.acl.info(token)['Rules'] == rules", "c.kv.get('foo') == (index, data) assert c.kv.delete('foo', cas=data['ModifyIndex']) is True index,", "test_agent_service_maintenance(self, consul_port): c = consul.Consul(port=consul_port) c.agent.service.register('foo', check=Check.ttl('100ms')) time.sleep(40/1000.0) c.agent.service.maintenance('foo', 'true',", "= c.health.service('foo-1', token=token) assert data[0]['Service']['ID'] == \"foo-1\" index, data =", "is True verify_and_dereg_check('script_check') assert c.agent.check.register( 'check name', Check.script('/bin/true', 10), check_id='check_id')", "Check.script('/bin/true', 10)) is True verify_and_dereg_check('script_check') assert c.agent.check.register( 'check name', Check.script('/bin/true',", "c = consul.Consul(port=consul_port) members = c.agent.members() for x in members:", "c.acl.list(token=master_token) assert set([x['ID'] for x in acls]) == \\ set(['anonymous',", "policy = \"read\" } \"\"\" token = c.acl.create(rules=rules, token=master_token) assert", "== [ None, six.b('1'), six.b('2'), six.b('3')] def test_kv_delete(self, consul_port): c", "def verify_and_dereg_check(check_id): assert set(c.agent.checks().keys()) == set([check_id]) assert c.agent.check.deregister(check_id) is True", "nodes = c.health.state('any') assert set([node['ServiceID'] for node in nodes]) ==", "to use the master token by default c = consul.Consul(port=acl_consul.port,", "test_health_state(self, consul_port): c = consul.Consul(port=consul_port) # The empty string is", "True index, data = c.kv.get('foo') assert data['Value'] == six.b('bar') def", "c.txn.put([d]) assert r[\"Errors\"] is None d = {\"KV\": {\"Verb\": \"get\",", "= c.kv.get('foo') assert data['Value'] is None # test None c.kv.put('foo',", "def test_transaction(self, consul_port): c = consul.Consul(port=consul_port) value = base64.b64encode(b\"1\").decode(\"utf8\") d", "value \" \\ \"was {1}\".format(leader, addr_port) def test_status_peers(self, consul_port): c", "\"\"\" token = c.acl.create(rules=rules, token=master_token) assert c.acl.info(token)['Rules'] == rules token2", "\"was {1}\".format(leader, addr_port) def test_status_peers(self, consul_port): c = consul.Consul(port=consul_port) agent_self", "{\"Verb\": \"set\", \"Key\": \"asdf\", \"Value\": value}} r = c.txn.put([d]) assert", "'bar2') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.delete, 'foo') assert c.kv.get('private/foo')[1]['Value'] == six.b('bar') pytest.raises(", "n2's s1 service was removed though _, nodes = c.catalog.service('s1')", "c.acl.list) pytest.raises(consul.ACLPermissionDenied, c.acl.create) pytest.raises(consul.ACLPermissionDenied, c.acl.update, 'anonymous') pytest.raises(consul.ACLPermissionDenied, c.acl.clone, 'anonymous') pytest.raises(consul.ACLPermissionDenied,", "'http://127.0.0.1:8500/v1/kv' assert http.uri('/v1/kv', params={'index': 1}) == \\ 'http://127.0.0.1:8500/v1/kv?index=1' class TestConsul(object):", "node in nodes] == ['foo:1', 'foo:2'] # but that they", "'foo', 'bar', acquire='foo') s1 = c.session.create() s2 = c.session.create() assert", "c.kv.put('foo', 'bar', cas=0) is True index, data = c.kv.get('foo') assert", "def test_agent_register_check_no_service_id(self, consul_port): c = consul.Consul(port=consul_port) index, nodes = c.health.service(\"foo1\")", "status if notes: assert checks[check_id]['Output'] == notes # test setting", "index == check def test_kv_encoding(self, consul_port): c = consul.Consul(port=consul_port) #", "= base64.b64encode(b\"1\").decode(\"utf8\") d = {\"KV\": {\"Verb\": \"set\", \"Key\": \"asdf\", \"Value\":", "== {'s1': [u'master'], 's2': [], 'consul': []} # test catalog.node", "check unencoded values raises assert pytest.raises(AssertionError, c.kv.put, 'foo', {1: 2})", "assert data['Value'] == six.b('1') c.session.destroy(s) index, data = c.kv.get('foo') assert", "str(query['ID']) != '' # retrieve query using id and name", "'']) assert set([ check['CheckID'] for node in nodes for check", "both nodes are available index, nodes = c.health.state('passing') assert set([node['ServiceID']", "assert 'test' == checks_pre['_service_maintenance:foo']['Notes'] c.agent.service.maintenance('foo', 'false') time.sleep(40/1000.0) checks_post = c.agent.checks()", "c.kv.put('bar', '4') is True assert c.kv.put('base/foo', '1') is True assert", "release=s2) is False assert c.kv.put('foo', '2', release=s1) is True c.session.destroy(s1)", "query assert c.query.delete(query['ID']) def test_coordinate(self, consul_port): c = consul.Consul(port=consul_port) c.coordinate.nodes()", "Clean up tasks assert c.agent.service.deregister(service_name) is True time.sleep(40/1000.0) index, nodes", "for check in checks] == ['service:foobar'] c.agent.service.deregister('foobar') time.sleep(40/1000.0) index, checks", "= {\"KV\": {\"Verb\": \"set\", \"Key\": \"asdf\", \"Value\": value}} r =", "'anonymous') pytest.raises(consul.ACLPermissionDenied, c.acl.clone, 'anonymous') pytest.raises(consul.ACLPermissionDenied, c.acl.destroy, 'anonymous') def test_acl_explict_token_use(self, acl_consul):", "\\ and str(query['ID']) != '' # retrieve query using id", "c_limited.kv.put, 'foo', 'bar2') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.delete, 'foo') assert c.kv.get('private/foo')[1]['Value'] ==", "for x in data] == [ 'foo/', 'foo/bar1', 'foo/bar2', 'foo/bar3']", "is None def test_kv_acquire_release(self, consul_port): c = consul.Consul(port=consul_port) pytest.raises( consul.ConsulException,", "x in nodes] == [] def test_health_service(self, consul_port): c =", "c.kv.put('foo', '1', release='foo') is False assert c.kv.put('foo', '2', release=s2) is", "# session.list pytest.raises(consul.ConsulException, c.session.list, dc='dc2') _, sessions = c.session.list() assert", "in acls]) == \\ set(['anonymous', master_token]) def test_acl_implicit_token_use(self, acl_consul): #", "'ttl_check', notes='all hunky dory!') is True verify_check_status('ttl_check', 'passing', notes='all hunky", "[] index, events = c.event.list(name=\"fooname\") assert [x['Name'] == 'fooname' for", "assert addr_port in peers, \\ \"Expected value '{0}' \" \\", "consul_port): c = consul.Consul(port=consul_port) # grab local node name node", "pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'foo', 'bar2', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'foo',", "consul_port): c = consul.Consul(port=consul_port) pytest.raises(consul.ACLDisabled, c.acl.list) pytest.raises(consul.ACLDisabled, c.acl.info, '1'*36) pytest.raises(consul.ACLDisabled,", "node available index, nodes = c.health.state('passing') assert set([node['ServiceID'] for node", "True assert c.catalog.register( 'n1', '10.1.10.11', service={'service': 's2'}) is True assert", "# check the nodes weren't removed _, nodes = c.catalog.nodes()", "== ['foo1'] c.agent.check.register('foo', Check.ttl('100ms'), service_id='foo1') time.sleep(40/1000.0) index, nodes = c.health.service('foo1')", "name='Foo', token=master_token) == token2 assert c.acl.info(token2)['Name'] == 'Foo' assert c.acl.destroy(token2,", "[]} # test catalog.node pytest.raises(consul.ConsulException, c.catalog.node, 'n1', dc='dc2') _, node", "_, sessions = c.session.node(node) assert [x['Name'] for x in sessions]", "== ['n1', 'n2'] # test catalog.services pytest.raises(consul.ConsulException, c.catalog.services, dc='dc2') _,", "None \\ and str(query['ID']) != '' # retrieve query using", "= c.catalog.nodes() assert len(nodes) == 1 current = nodes[0] #", "# test address param assert c.agent.service.register('foo', address='10.10.10.1') is True assert", "test_catalog(self, consul_port): c = consul.Consul(port=consul_port) # grab the node our", "assert c.kv.put('foo', '2', acquire=s2) is False assert c.kv.put('foo', '1', acquire=s1)", "check=Check.ttl('10s')) time.sleep(40/1000.00) index, checks = c.health.checks('foobar') assert [check['ServiceID'] for check", "assert data == [] index, data = c.health.service('bar-1', token=token) assert", "# deregister the nodes c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2') time.sleep(40/1000.0) index, nodes =", "# wait until the short ttl node fails time.sleep(120/1000.0) #", "'Meta']) def test_agent_services(self, consul_port): c = consul.Consul(port=consul_port) assert c.agent.service.register('foo') is", "data = c.kv.get('foo') assert c.kv.delete('foo', cas=data['ModifyIndex']-1) is False assert c.kv.get('foo')", "set(c.agent.checks().keys()) == set([check_id]) assert c.agent.check.deregister(check_id) is True assert set(c.agent.checks().keys()) ==", "== ['foo:1'] # ping the failed node's health check c.agent.check.ttl_pass('service:foo:2')", "_, nodes = c.catalog.service('s1', tag='master') assert set([x['Node'] for x in", "c.health.state('any') assert [node['ServiceID'] for node in nodes] == [''] def", "'n1', dc='dc2') _, node = c.catalog.node('n1') assert set(node['Services'].keys()) == set(['s1',", "empty string is for the Serf Health Status check, which", "events = c.event.list(name=\"fooname\") assert [x['Name'] == 'fooname' for x in", "= consul.Consul(port=consul_port) members = c.agent.members() for x in members: assert", "test_acl_implicit_token_use(self, acl_consul): # configure client to use the master token", "unicode c.kv.put('foo', u'bar') index, data = c.kv.get('foo') assert data['Value'] ==", "index, nodes = c.health.service('foo') assert nodes == [] # register", "= c.kv.get('foo') assert data['Value'] == six.b('bar') # test empty-string comes", "data = c.kv.get('foo') assert c.kv.put('foo', 'bar2', cas=data['ModifyIndex']-1) is False assert", "in nodes]) == set(['n2']) # test catalog.deregister pytest.raises( consul.ConsulException, c.catalog.deregister,", "/health/state/any endpoint index, nodes = c.health.state('any') assert set([node['ServiceID'] for node", "consul.Consul(port=consul_port) agent_self = c.agent.self() addr_port = agent_self['Stats']['consul']['leader_addr'] peers = c.status.peers()", "c.agent.service.register('foo1') time.sleep(40/1000.0) index, nodes = c.health.service('foo1') assert [node['Service']['ID'] for node", "_, nodes = c.catalog.service('s1') assert set([x['Node'] for x in nodes])", "c.acl.update, 'anonymous') pytest.raises(consul.ACLPermissionDenied, c.acl.clone, 'anonymous') pytest.raises(consul.ACLPermissionDenied, c.acl.destroy, 'anonymous') def test_acl_explict_token_use(self,", "index, events = c.event.list() assert [x['Name'] == 'fooname' for x", "test_acl_explict_token_use(self, acl_consul): c = consul.Consul(port=acl_consul.port) master_token = acl_consul.token acls =", "== six.b('bar') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.put, 'foo', 'bar2') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.delete,", "queries != [] \\ and len(queries) == 1 assert queries[0]['Name']", "is True _, sessions = c.session.list() assert sessions == []", "# test None c.kv.put('foo', None) index, data = c.kv.get('foo') assert", "{ policy = \"write\" } service \"bar-\" { policy =", "in nodes] == ['foo:1', 'foo:2'] # check that tag works", "index, nodes = c.health.service(\"foo1\") assert nodes == [] pytest.raises(consul.std.base.ConsulException, c.agent.check.register,", "nodes = c.health.service('foo', passing=True) assert [node['Service']['ID'] for node in nodes]", "# test catalog.service pytest.raises( consul.ConsulException, c.catalog.service, 's1', dc='dc2') _, nodes", "== 0 def test_session(self, consul_port): c = consul.Consul(port=consul_port) # session.create", "nodes, one with a long ttl, the other shorter c.agent.service.register(", "'foo') assert c.kv.get('private/foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.get, 'private/foo') pytest.raises(", "is None def test_kv_delete_cas(self, consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo', 'bar')", "works index, nodes = c.health.service('foo', tag='tag:foo:1') assert [node['Service']['ID'] for node", "test_transaction(self, consul_port): c = consul.Consul(port=consul_port) value = base64.b64encode(b\"1\").decode(\"utf8\") d =", "[check[\"Node\"] for check in checks] def test_health_checks(self, consul_port): c =", "for check in node['Checks']]) == set(['foo', 'serfHealth']) # Clean up", "# but that they aren't passing their health check index,", "data is None def test_acl_disabled(self, consul_port): c = consul.Consul(port=consul_port) pytest.raises(consul.ACLDisabled,", "c.kv.put('foo', 'bar') index, data = c.kv.get('foo') assert c.kv.delete('foo', cas=data['ModifyIndex']-1) is", "'passing', notes='all hunky dory!') # wait for ttl to expire", "in nodes] == ['foo1'] c.agent.check.register('foo', Check.ttl('100ms'), service_id='foo1') time.sleep(40/1000.0) index, nodes", "acls]) == \\ set(['anonymous', master_token]) assert c.acl.info('1'*36) is None compare", "['service:foobar'] c.agent.service.deregister('foobar') time.sleep(40/1000.0) index, checks = c.health.checks('foobar') assert len(checks) ==", "assert c.kv.put('foo', 'bar2', cas=data['ModifyIndex']-1) is False assert c.kv.put('foo', 'bar2', cas=data['ModifyIndex'])", "ttl=20) # attempt to renew an unknown session pytest.raises(consul.NotFound, c.session.renew,", "'foo', Check.ttl('100ms'), service_id='foo1') time.sleep(40/1000.0) assert c.agent.checks() == {} # Cleanup", "checks = c.health.node(node) assert node in [check[\"Node\"] for check in", "time.sleep(40/1000.0) index, nodes = c.health.state('any') assert [node['ServiceID'] for node in", "token=token) assert c.kv.get('private/foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c.kv.get, 'private/foo', token=token)", "short ttl node fails time.sleep(120/1000.0) # only one node available", "assert data['Value'] is None # check unencoded values raises assert", "# ping the failed node's health check c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0) #", "acls = c.acl.list() assert set([x['ID'] for x in acls]) ==", "10), check_id='check_id') is True verify_and_dereg_check('check_id') http_addr = \"http://127.0.0.1:{0}\".format(consul_port) assert c.agent.check.register(", "'bar') is True index, data = c.kv.get('foo') assert data['Value'] ==", "are available index, nodes = c.health.service('foo', passing=True) assert [node['Service']['ID'] for", "== 50 def test_kv_recurse(self, consul_port): c = consul.Consul(port=consul_port) index, data", "= True if server[\"Voter\"]: voter = True assert leader assert", "== set(['Member', 'Stats', 'Config', 'Coord', 'DebugConfig', 'Meta']) def test_agent_services(self, consul_port):", "nodes] == ['n1', 'n2'] # check n2's s1 service was", "'foo' query_name = 'fooquery' query = c.query.create(query_service, query_name) # assert", "data == ['base/base/', 'base/foo'] def test_transaction(self, consul_port): c = consul.Consul(port=consul_port)", "session['Node'] pytest.raises( consul.ConsulException, c.session.node, node, dc='dc2') _, sessions = c.session.node(node)", "assert c.agent.check.register( 'http_timeout_check', Check.http(http_addr, '100ms', timeout='2s')) is True verify_and_dereg_check('http_timeout_check') assert", "== query_name \\ and queries[0]['ID'] == query['ID'] # explain query", "'10.1.10.11', service={'service': 's1'}, check={'name': 'c1'}) is True assert c.catalog.register( 'n1',", "= c.query.get(query['ID']) assert queries != [] \\ and len(queries) ==", "== set( ['', 'foo:1', 'foo:2']) # wait until the short", "\" \\ \"in peer list but it was not present\".format(addr_port)", "the /health/service endpoint index, nodes = c.health.service('foo') assert [node['Service']['ID'] for", "two node's health check c.agent.check.ttl_pass('service:foo:1') c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0) # both nodes", "[node['ServiceID'] for node in nodes] == [''] # register two", "# session.info pytest.raises( consul.ConsulException, c.session.info, session_id, dc='dc2') index, session =", "dc='dc2') index, session = c.session.info('1'*36) assert session is None index,", "test_kv_delete(self, consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo1', '1') c.kv.put('foo2', '2') c.kv.put('foo3',", "['dc1'] # test catalog.register pytest.raises( consul.ConsulException, c.catalog.register, 'foo', '10.1.10.11', dc='dc2')", "== six.b('bar2') def test_kv_put_flags(self, consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo', 'bar')", "consul.ConsulException, c.catalog.service, 's1', dc='dc2') _, nodes = c.catalog.service('s1') assert set([x['Node']", "in acls]) == \\ set(['anonymous', master_token]) def test_status_leader(self, consul_port): c", "assert data is None def test_acl_disabled(self, consul_port): c = consul.Consul(port=consul_port)", "trying out the behavior assert c.kv.put('foo', '1', acquire=s) is True", "is True assert set(c.agent.services().keys()) == set() # test address param", "== ['foo:1', 'foo:2'] # wait until the short ttl node", "assert set([x['Node'] for x in nodes]) == set(['n1']) # cleanup", "data] == [ 'foo/', 'foo/bar1', 'foo/bar2', 'foo/bar3'] assert [x['Value'] for", "http_addr = \"http://127.0.0.1:{0}\".format(consul_port) assert c.agent.check.register( 'http_check', Check.http(http_addr, '10ms')) is True", "'bar', cas=0) is True index, data = c.kv.get('foo') assert c.kv.put('foo',", "'foo'][0] == '10.10.10.1' assert c.agent.service.deregister('foo') is True def test_catalog(self, consul_port):", "acl_consul.token acls = c.acl.list() assert set([x['ID'] for x in acls])", "Check.script('/bin/true', 10), check_id='check_id') is True verify_and_dereg_check('check_id') http_addr = \"http://127.0.0.1:{0}\".format(consul_port) assert", "'private/foo', token=token ) pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'private/foo', 'bar2', token=token) pytest.raises(", "c.agent.service.register( 'foo', service_id='foo:1', check=Check.ttl('10s')) c.agent.service.register( 'foo', service_id='foo:2', check=Check.ttl('100ms')) time.sleep(40/1000.0) #", "(index, data) assert c.kv.delete('foo', cas=data['ModifyIndex']) is True index, data =", "c.agent.service.deregister('foo') is True assert set(c.agent.services().keys()) == set() # test address", "consul_port): c = consul.Consul(port=consul_port) # The empty string is for", "c.kv.get('foo') assert c.kv.delete('foo', cas=data['ModifyIndex']-1) is False assert c.kv.get('foo') == (index,", "token2 = c.acl.clone(token) assert c.acl.info(token2)['Rules'] == rules assert c.acl.update(token2, name='Foo')", "leader = True if server[\"Voter\"]: voter = True assert leader", "'critical') assert c.agent.check.ttl_fail( 'ttl_check', notes='something went boink!') is True verify_check_status(", "token2 = c.acl.clone(token, token=master_token) assert c.acl.info(token2)['Rules'] == rules assert c.acl.update(token2,", "consul.Consul(port=consul_port) c.agent.service.register('foo1') time.sleep(40/1000.0) index, nodes = c.health.service('foo1') assert [node['Service']['ID'] for", "six.b('bar2') def test_kv_put_flags(self, consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo', 'bar') index,", "'its not quite right') assert c.agent.check.ttl_fail('ttl_check') is True verify_check_status('ttl_check', 'critical')", "= c.acl.clone(token, token=master_token) assert c.acl.info(token2)['Rules'] == rules assert c.acl.update(token2, name='Foo',", "server created, so we can ignore it _, nodes =", "in checks] == ['service:foobar'] c.agent.service.deregister('foobar') time.sleep(40/1000.0) index, checks = c.health.checks('foobar')", "[] # register two nodes, one with a long ttl,", "the nodes show for the /health/state/any endpoint index, nodes =", "is True _, nodes = c.catalog.nodes() nodes.remove(current) assert [x['Node'] for", "'foo', service_id='foo:2', check=Check.ttl('100ms')) time.sleep(40/1000.0) # check the nodes show for", "is True time.sleep(40/1000.0) def test_agent_register_check_no_service_id(self, consul_port): c = consul.Consul(port=consul_port) index,", "c = consul.Consul(port=consul_port) c.coordinate.nodes() c.coordinate.datacenters() assert set(c.coordinate.datacenters()[0].keys()) == \\ set(['Datacenter',", "= c.query.create(query_service, query_name) # assert response contains query ID assert", "x in sessions] == ['my-session'] # session.destroy pytest.raises( consul.ConsulException, c.session.destroy,", "c.agent.check.register('foo', Check.ttl('100ms'), service_id='foo1') time.sleep(40/1000.0) index, nodes = c.health.service('foo1') assert set([", "node in nodes]) == set( ['', 'foo:1', 'foo:2']) # deregister", "# Cleanup c.agent.service.deregister('foo') time.sleep(40/1000.0) def test_agent_node_maintenance(self, consul_port): c = consul.Consul(port=consul_port)", "checks_post.keys() # Cleanup c.agent.service.deregister('foo') time.sleep(40/1000.0) def test_agent_node_maintenance(self, consul_port): c =", "time.sleep(40/1000.0) def test_agent_node_maintenance(self, consul_port): c = consul.Consul(port=consul_port) c.agent.maintenance('true', \"test\") time.sleep(40/1000.0)", "notes on a check c.agent.check.register('check', Check.ttl('1s'), notes='foo') assert c.agent.checks()['check']['Notes'] ==", "six.b('bar') # test empty-string comes back as `None` c.kv.put('foo', '')", "queries[0]['Name'] == query_name \\ and queries[0]['ID'] == query['ID'] # explain", "def test_kv_wait(self, consul_port): c = consul.Consul(port=consul_port) assert c.kv.put('foo', 'bar') is", "c.kv.delete, 'private/foo', token=token) # test token pass through for service", "in nodes] == ['n1', 'n2'] # check n2's s1 service", "index, data = c.kv.get('foo') assert data is None def test_kv_acquire_release(self,", "\" \\ \"was {1}\".format(leader, addr_port) def test_status_peers(self, consul_port): c =", "c.kv.get('foo') assert data is None def test_acl_disabled(self, consul_port): c =", "\"Value\": value}} r = c.txn.put([d]) assert r[\"Errors\"] is None d", "= consul.Consul(port=consul_port) c.agent.service.register( 'foobar', service_id='foobar', check=Check.ttl('10s')) time.sleep(40/1000.00) index, checks =", "tag='master') assert set([x['Node'] for x in nodes]) == set(['n2']) #", "c.session.create('my-session') # session.list pytest.raises(consul.ConsulException, c.session.list, dc='dc2') _, sessions = c.session.list()", "{0}, expected value \" \\ \"was {1}\".format(leader, addr_port) def test_status_peers(self,", "'http://127.0.0.1:8500/v1/kv?index=1' class TestConsul(object): def test_kv(self, consul_port): c = consul.Consul(port=consul_port) index,", "pytest.raises(consul.ConsulException, c.catalog.node, 'n1', dc='dc2') _, node = c.catalog.node('n1') assert set(node['Services'].keys())", "c.agent.service.deregister('foobar') time.sleep(40/1000.0) index, checks = c.health.checks('foobar') assert len(checks) == 0", "= consul.Consul(port=acl_consul.port) pytest.raises(consul.ACLPermissionDenied, c.acl.list) pytest.raises(consul.ACLPermissionDenied, c.acl.create) pytest.raises(consul.ACLPermissionDenied, c.acl.update, 'anonymous') pytest.raises(consul.ACLPermissionDenied,", "check c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0) # check both nodes are available index,", "query_name) # assert response contains query ID assert 'ID' in", "index, session = c.session.info('1'*36) assert session is None index, session", "check=Check.ttl('10s'), tags=['tag:foo:1']) c.agent.service.register( 'foo', service_id='foo:2', check=Check.ttl('100ms')) time.sleep(40/1000.0) # check the", "'app#127.0.0.1#3000' c = consul.Consul(port=consul_port) c.agent.service.register(service_name) time.sleep(80/1000.0) index, nodes = c.health.service(service_name)", "True assert c.catalog.deregister('n2') is True _, nodes = c.catalog.nodes() nodes.remove(current)", "50 def test_kv_recurse(self, consul_port): c = consul.Consul(port=consul_port) index, data =", "['my-session'] # session.info pytest.raises( consul.ConsulException, c.session.info, session_id, dc='dc2') index, session", "== 'delete' assert session['TTL'] == '20s' # trying out the", "it was not present\".format(addr_port) def test_query(self, consul_port): c = consul.Consul(port=consul_port)", "def test_acl_disabled(self, consul_port): c = consul.Consul(port=consul_port) pytest.raises(consul.ACLDisabled, c.acl.list) pytest.raises(consul.ACLDisabled, c.acl.info,", "acquire=s2) is False assert c.kv.put('foo', '1', acquire=s1) is True assert", "= c.event.list(name=\"fooname\") assert [x['Name'] == 'fooname' for x in events]", "def test_kv_acquire_release(self, consul_port): c = consul.Consul(port=consul_port) pytest.raises( consul.ConsulException, c.kv.put, 'foo',", "data['Value'] == six.b('bar') # test empty-string comes back as `None`", "health check c.agent.check.ttl_pass('service:foo:1') c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0) # both nodes are now", "an # empty ServiceID index, nodes = c.health.state('any') assert [node['ServiceID']", "consul.Consul(port=consul_port) index, nodes = c.health.service(\"foo1\") assert nodes == [] c.agent.service.register('foo',", "for x in data] == ['foo1', 'foo2', 'foo3'] assert c.kv.delete('foo2')", "[] c.agent.service.register('foo', enable_tag_override=True) assert c.agent.services()['foo']['EnableTagOverride'] # Cleanup tasks c.agent.check.deregister('foo') def", "'1') is True assert c.kv.put('base/base/foo', '5') is True index, data", "x in acls]) == \\ set(['anonymous', master_token]) def test_acl_implicit_token_use(self, acl_consul):", "d = {\"KV\": {\"Verb\": \"get\", \"Key\": \"asdf\"}} r = c.txn.put([d])", "c.kv.put('foo', u'bar') index, data = c.kv.get('foo') assert data['Value'] == six.b('bar')", "short ttl node fails time.sleep(2200/1000.0) # only one node available", "import base64 import operator import struct import time import pytest", "present\".format(addr_port) def test_query(self, consul_port): c = consul.Consul(port=consul_port) # check that", "consul_port): # https://github.com/cablehead/python-consul/issues/156 service_name = 'app#127.0.0.1#3000' c = consul.Consul(port=consul_port) c.agent.service.register(service_name)", "consul_port): c = consul.Consul(port=consul_port) c.agent.service.register('foo', check=Check.ttl('100ms')) time.sleep(40/1000.0) c.agent.service.maintenance('foo', 'true', \"test\")", "assert c.kv.put('base/foo', '1') is True assert c.kv.put('base/base/foo', '5') is True", "only one node available index, nodes = c.health.service('foo', passing=True) assert", "= \"write\" } service \"bar-\" { policy = \"read\" }", "[x['Name'] for x in sessions] == ['my-session'] # session.info pytest.raises(", "token2 assert c.acl.info(token2)['Name'] == 'Foo' assert c.acl.destroy(token2) is True assert", "in members: assert x['Status'] == 1 assert not x['Name'] is", "in events] def test_event_targeted(self, consul_port): c = consul.Consul(port=consul_port) assert c.event.fire(\"fooname\",", "assert set([x['ID'] for x in acls]) == \\ set(['anonymous', master_token])", "c.agent.check.deregister('foo') def test_agent_service_maintenance(self, consul_port): c = consul.Consul(port=consul_port) c.agent.service.register('foo', check=Check.ttl('100ms')) time.sleep(40/1000.0)", "== checks_pre['_node_maintenance']['Notes'] c.agent.maintenance('false') time.sleep(40/1000.0) checks_post = c.agent.checks() assert '_node_maintenance' not", "c = consul.Consul(port=consul_port) assert c.kv.put('foo', 'bar') is True index, data", "endpoint index, nodes = c.health.service('foo') assert [node['Service']['ID'] for node in", "pytest.raises(consul.ACLDisabled, c.acl.clone, 'foo') pytest.raises(consul.ACLDisabled, c.acl.destroy, 'foo') def test_acl_permission_denied(self, acl_consul): c", "c.operator.raft_config() assert config[\"Index\"] == 1 leader = False voter =", "= consul.Consul(port=consul_port) s = c.session.create(behavior='delete', ttl=20) # attempt to renew", "time.sleep(40/1000.0) # both nodes are now available index, nodes =", "verify_and_dereg_check(check_id): assert set(c.agent.checks().keys()) == set([check_id]) assert c.agent.check.deregister(check_id) is True assert", "node fails time.sleep(120/1000.0) # only one node available index, nodes", "pytest.raises(consul.ConsulException, c.session.create, node='n2') pytest.raises(consul.ConsulException, c.session.create, dc='dc2') session_id = c.session.create('my-session') #", "r = c.txn.put([d]) assert r[\"Errors\"] is None d = {\"KV\":", "== ['foo1', 'foo2', 'foo3'] assert c.kv.delete('foo2') is True index, data", "client's default token pytest.raises( consul.ACLPermissionDenied, c.kv.get, 'private/foo', token=token ) pytest.raises(", "compare = [c.acl.info(master_token), c.acl.info('anonymous')] compare.sort(key=operator.itemgetter('ID')) assert acls == compare rules", "= agent_self['Stats']['consul']['leader_addr'] assert leader == addr_port, \\ \"Leader value was", "'bar') c.kv.put('private/foo', 'bar') assert c.kv.get('foo', token=token)[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied,", "== 'foobody' for x in events] def test_agent_checks(self, consul_port): c", "c.agent.check.ttl_fail( 'ttl_check', notes='something went boink!') is True verify_check_status( 'ttl_check', 'critical',", "wan_members: assert 'dc1' in x['Name'] def test_agent_self(self, consul_port): c =", "consul.Consul(port=consul_port) # grab local node name node = c.agent.self()['Config']['NodeName'] index,", "== 'http://127.0.0.1:8500/v1/kv' assert http.uri('/v1/kv', params={'index': 1}) == \\ 'http://127.0.0.1:8500/v1/kv?index=1' class", "assert c.kv.put('foo', 'bar', cas=50) is False assert c.kv.put('foo', 'bar', cas=0)", "'foo/bar1', 'foo/bar2', 'foo/bar3'] assert [x['Value'] for x in data] ==", "consul_port): c = consul.Consul(port=consul_port) c.coordinate.nodes() c.coordinate.datacenters() assert set(c.coordinate.datacenters()[0].keys()) == \\", "c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2') time.sleep(40/1000.0) index, nodes = c.health.state('any') assert [node['ServiceID'] for", "= c.txn.put([d]) assert r[\"Errors\"] is None d = {\"KV\": {\"Verb\":", "an unknown session pytest.raises(consul.NotFound, c.session.renew, '1'*36) session = c.session.renew(s) assert", "c.session.create() assert c.kv.put('foo', '1', acquire=s1) is True assert c.kv.put('foo', '2',", "test catalog.nodes pytest.raises(consul.ConsulException, c.catalog.nodes, dc='dc2') _, nodes = c.catalog.nodes() nodes.remove(current)", "Health Status check, which has an # empty ServiceID index,", "test empty-string comes back as `None` c.kv.put('foo', '') index, data", "session_id = c.session.create('my-session') # session.list pytest.raises(consul.ConsulException, c.session.list, dc='dc2') _, sessions", "long ttl, the other shorter c.agent.service.register( 'foo', service_id='foo:1', check=Check.ttl('10s'), tags=['tag:foo:1'])", "c.health.service('bar-1', token=token) assert not data # clean up assert c.agent.service.deregister('foo-1')", "assert data['Flags'] == 50 def test_kv_recurse(self, consul_port): c = consul.Consul(port=consul_port)", "= c.catalog.node('n3') assert node is None # test catalog.service pytest.raises(", "} service \"foo-\" { policy = \"write\" } service \"bar-\"", "consul.Consul(port=consul_port) assert c.kv.put('bar', '4') is True assert c.kv.put('base/foo', '1') is", "# test catalog.datacenters assert c.catalog.datacenters() == ['dc1'] # test catalog.register", "a long ttl, the other shorter c.agent.service.register( 'foo', service_id='foo:1', check=Check.ttl('10s'))", "== (1000,) # test unicode c.kv.put('foo', u'bar') index, data =", "True verify_and_dereg_check('check_id') http_addr = \"http://127.0.0.1:{0}\".format(consul_port) assert c.agent.check.register( 'http_check', Check.http(http_addr, '10ms'))", "# both nodes are now available index, nodes = c.health.service('foo',", "pytest.raises( consul.ConsulException, c.catalog.register, 'foo', '10.1.10.11', dc='dc2') assert c.catalog.register( 'n1', '10.1.10.11',", "c.agent.check.register('check', Check.ttl('1s'), notes='foo') assert c.agent.checks()['check']['Notes'] == 'foo' c.agent.check.deregister('check') assert set(c.agent.checks().keys())", "# https://github.com/cablehead/python-consul/issues/156 service_name = 'app#127.0.0.1#3000' c = consul.Consul(port=consul_port) c.agent.service.register(service_name) time.sleep(80/1000.0)", "agent_self = c.agent.self() addr_port = agent_self['Stats']['consul']['leader_addr'] peers = c.status.peers() assert", "Check.ttl('100ms'), service_id='foo1') time.sleep(40/1000.0) index, nodes = c.health.service('foo1') assert set([ check['ServiceID']", "assert c.catalog.deregister('n1') is True assert c.catalog.deregister('n2') is True _, nodes", "c.agent.checks() == {} # Cleanup tasks c.agent.check.deregister('foo') time.sleep(40/1000.0) def test_agent_register_enable_tag_override(self,", "override the client's default token pytest.raises( consul.ACLPermissionDenied, c.kv.get, 'private/foo', token=token", "c.acl.info(token2)['Name'] == 'Foo' assert c.acl.destroy(token2) is True assert c.acl.info(token2) is", "time.sleep(40/1000.0) def test_agent_register_check_no_service_id(self, consul_port): c = consul.Consul(port=consul_port) index, nodes =", "= c.agent.self() leader = c.status.leader() addr_port = agent_self['Stats']['consul']['leader_addr'] assert leader", "check, data = c.kv.get('foo', index=index, wait='20ms') assert index == check", "c.session.list() assert sessions == [] def test_session_delete_ttl_renew(self, consul_port): c =", "assert session['TTL'] == '20s' # trying out the behavior assert", "c.kv.put('foo', 'bar') index, data = c.kv.get('foo') assert data['Flags'] == 0", "http.uri('/v1/kv', params={'index': 1}) == \\ 'http://127.0.0.1:8500/v1/kv?index=1' class TestConsul(object): def test_kv(self,", "tasks assert c.agent.check.deregister('foo') is True time.sleep(40/1000.0) assert c.agent.service.deregister('foo1') is True", "None c.kv.put('foo', 'bar') c.kv.put('private/foo', 'bar') assert c.kv.get('foo', token=token)[1]['Value'] == six.b('bar')", "nodes] == ['foo:1', 'foo:2'] # check that tag works index,", "dory!') # wait for ttl to expire time.sleep(120/1000.0) verify_check_status('ttl_check', 'critical')", "== [] pytest.raises(consul.std.base.ConsulException, c.agent.check.register, 'foo', Check.ttl('100ms'), service_id='foo1') time.sleep(40/1000.0) assert c.agent.checks()", "checks_pre = c.agent.checks() assert '_node_maintenance' in checks_pre.keys() assert 'test' ==", "current = nodes[0] # test catalog.datacenters assert c.catalog.datacenters() == ['dc1']", "and name queries = c.query.get(query['ID']) assert queries != [] \\", "'DebugConfig', 'Meta']) def test_agent_services(self, consul_port): c = consul.Consul(port=consul_port) assert c.agent.service.register('foo')", "None def test_acl_disabled(self, consul_port): c = consul.Consul(port=consul_port) pytest.raises(consul.ACLDisabled, c.acl.list) pytest.raises(consul.ACLDisabled,", "checks_post = c.agent.checks() assert '_service_maintenance:foo' not in checks_post.keys() # Cleanup", "for x in nodes]) == set(['n1', 'n2']) _, nodes =", "c = consul.Consul(port=consul_port) value = base64.b64encode(b\"1\").decode(\"utf8\") d = {\"KV\": {\"Verb\":", "pytest.raises(consul.ACLDisabled, c.acl.list) pytest.raises(consul.ACLDisabled, c.acl.info, '1'*36) pytest.raises(consul.ACLDisabled, c.acl.create) pytest.raises(consul.ACLDisabled, c.acl.update, 'foo')", "pytest.raises(consul.ACLDisabled, c.acl.destroy, 'foo') def test_acl_permission_denied(self, acl_consul): c = consul.Consul(port=acl_consul.port) pytest.raises(consul.ACLPermissionDenied,", "'foo' c.agent.check.deregister('check') assert set(c.agent.checks().keys()) == set([]) assert c.agent.check.register( 'script_check', Check.script('/bin/true',", "service_id='s1') is True # check the nodes weren't removed _,", "# check the nodes show for the /health/service endpoint index,", "health check c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0) # check both nodes are available", "c.kv.put('foo', 'bar', flags=50) is True index, data = c.kv.get('foo') assert", "assert c.acl.info(token)['Rules'] == rules token2 = c.acl.clone(token) assert c.acl.info(token2)['Rules'] ==", "consul_port): c = consul.Consul(port=consul_port) c.agent.service.register('foo1') time.sleep(40/1000.0) index, nodes = c.health.service('foo1')", "== set(['foo', 'serfHealth']) # Clean up tasks assert c.agent.check.deregister('foo') is", "c.session.destroy(session_id) is True _, sessions = c.session.list() assert sessions ==", "a new named query query_service = 'foo' query_name = 'fooquery'", "assert c.kv.delete('foo', cas=data['ModifyIndex']-1) is False assert c.kv.get('foo') == (index, data)", "test_health_checks(self, consul_port): c = consul.Consul(port=consul_port) c.agent.service.register( 'foobar', service_id='foobar', check=Check.ttl('10s')) time.sleep(40/1000.00)", "is True verify_check_status('ttl_check', 'warning') assert c.agent.check.ttl_warn( 'ttl_check', notes='its not quite", "assert c.agent.check.ttl_fail( 'ttl_check', notes='something went boink!') is True verify_check_status( 'ttl_check',", "for service registration pytest.raises( consul.ACLPermissionDenied, c.agent.service.register, \"bar-1\", token=token) c.agent.service.register(\"foo-1\", token=token)", "is not None \\ and str(query['ID']) != '' # retrieve", "c.kv.get('foo', recurse=True) assert data is None def test_kv_delete_cas(self, consul_port): c", "c.agent.service.register('foo', enable_tag_override=True) assert c.agent.services()['foo']['EnableTagOverride'] # Cleanup tasks c.agent.check.deregister('foo') def test_agent_service_maintenance(self,", "passing their health check index, nodes = c.health.state('passing') assert [node['ServiceID']", "c = consul.Consul(port=consul_port) c.agent.service.register('foo', check=Check.ttl('100ms')) time.sleep(40/1000.0) c.agent.service.maintenance('foo', 'true', \"test\") time.sleep(40/1000.0)", "assert not x['Tags'] is None assert c.agent.self()['Member'] in members wan_members", "= consul.Consul(port=consul_port) pytest.raises( consul.ConsulException, c.kv.put, 'foo', 'bar', acquire='foo') s1 =", "assert set(c.agent.checks().keys()) == set([]) def verify_check_status(check_id, status, notes=None): checks =", "data['Value'] == six.b('1') c.session.destroy(s) index, data = c.kv.get('foo') assert data", "'foo:2'] # check that tag works index, nodes = c.health.service('foo',", "assert set([node['ServiceID'] for node in nodes]) == set( ['', 'foo:1'])", "import time import pytest import six import consul import consul.std", "index, nodes = c.health.service('foo1') assert [node['Service']['ID'] for node in nodes]", "check both nodes are available index, nodes = c.health.service('foo', passing=True)", "u'bar') index, data = c.kv.get('foo') assert data['Value'] == six.b('bar') #", "is True assert c.catalog.deregister('n2', service_id='s1') is True # check the", "raises assert pytest.raises(AssertionError, c.kv.put, 'foo', {1: 2}) def test_kv_put_cas(self, consul_port):", "= c.health.state('passing') assert [node['ServiceID'] for node in nodes] != 'foo'", "service \"foo-\" { policy = \"write\" } service \"bar-\" {", "node = c.catalog.node('n3') assert node is None # test catalog.service", "c.session.node, node, dc='dc2') _, sessions = c.session.node(node) assert [x['Name'] for", "def test_catalog(self, consul_port): c = consul.Consul(port=consul_port) # grab the node", "in nodes] == ['foo:1', 'foo:2'] # but that they aren't", "== set(['foo1', '']) assert set([ check['CheckID'] for node in nodes", "['master']}) is True # test catalog.nodes pytest.raises(consul.ConsulException, c.catalog.nodes, dc='dc2') _,", "in nodes] == [] def test_agent_checks_service_id(self, consul_port): c = consul.Consul(port=consul_port)", "token by default c = consul.Consul(port=acl_consul.port, token=acl_consul.token) master_token = acl_consul.token", "set([x['Node'] for x in nodes]) == set(['n1', 'n2']) _, nodes", "consul_port): c = consul.Consul(port=consul_port) # check there are no nodes", "{ policy = \"deny\" } service \"foo-\" { policy =", "index, data = c.kv.get('foo') assert struct.unpack('i', data['Value']) == (1000,) #", "test_uri(self): http = consul.std.HTTPClient() assert http.uri('/v1/kv') == 'http://127.0.0.1:8500/v1/kv' assert http.uri('/v1/kv',", "for x in members: assert x['Status'] == 1 assert not", "consul_port): c = consul.Consul(port=consul_port) assert c.agent.service.register('foo') is True assert set(c.agent.services().keys())", "['my-session'] # session.destroy pytest.raises( consul.ConsulException, c.session.destroy, session_id, dc='dc2') assert c.session.destroy(session_id)", "== six.b('bar') pytest.raises( consul.ACLPermissionDenied, c.kv.get, 'private/foo', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.put,", "c.acl.info(token2)['Rules'] == rules assert c.acl.update(token2, name='Foo', token=master_token) == token2 assert", "for node in nodes] == ['foo:1', 'foo:2'] # check that", "c.acl.create(rules=rules, token=master_token) assert c.acl.info(token)['Rules'] == rules token2 = c.acl.clone(token, token=master_token)", "'3') index, data = c.kv.get('foo/', recurse=True) assert [x['Key'] for x", "for node in nodes] == ['foo1'] c.agent.check.register('foo', Check.ttl('100ms'), service_id='foo1') time.sleep(40/1000.0)", "pytest.raises(consul.ACLPermissionDenied, c.acl.list) pytest.raises(consul.ACLPermissionDenied, c.acl.create) pytest.raises(consul.ACLPermissionDenied, c.acl.update, 'anonymous') pytest.raises(consul.ACLPermissionDenied, c.acl.clone, 'anonymous')", "consul.std.HTTPClient() assert http.uri('/v1/kv') == 'http://127.0.0.1:8500/v1/kv' assert http.uri('/v1/kv', params={'index': 1}) ==", "assert '_service_maintenance:foo' not in checks_post.keys() # Cleanup c.agent.service.deregister('foo') time.sleep(40/1000.0) def", "c.kv.put('foo', '2', release=s2) is False assert c.kv.put('foo', '2', release=s1) is", "deregister the nodes c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2') time.sleep(40/1000.0) index, nodes = c.health.state('any')", "'foo:2']) # deregister the nodes c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2') time.sleep(40/1000.0) index, nodes", "= c.agent.checks() assert '_node_maintenance' not in checks_post.keys() def test_agent_members(self, consul_port):", "index, data = c.kv.get('foo') assert data['Value'] == six.b('1') c.session.destroy(s) index,", "c.session.info, session_id, dc='dc2') index, session = c.session.info('1'*36) assert session is", "c.catalog.deregister('n1', check_id='c1') is True assert c.catalog.deregister('n2', service_id='s1') is True #", "pytest.raises( consul.ACLPermissionDenied, c_limited.kv.delete, 'foo') assert c.kv.get('private/foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied,", "the Serf Health Status check, which has an # empty", "dc='dc2') _, sessions = c.session.list() assert [x['Name'] for x in", "node in nodes for check in node['Checks']]) == set(['foo', 'serfHealth'])", "= c.session.node(node) assert [x['Name'] for x in sessions] == ['my-session']", "consul.Consul(port=acl_consul.port, token=token) assert c_limited.kv.get('foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.put, 'foo',", "session is None index, session = c.session.info(session_id) assert session['Name'] ==", "True index, data = c.kv.get('foo') assert data['Value'] == six.b('1') c.session.destroy(s)", "# test binary c.kv.put('foo', struct.pack('i', 1000)) index, data = c.kv.get('foo')", "c.agent.check.register( 'http_timeout_check', Check.http(http_addr, '100ms', timeout='2s')) is True verify_and_dereg_check('http_timeout_check') assert c.agent.check.register('ttl_check',", "consul_port): c = consul.Consul(port=consul_port) # test binary c.kv.put('foo', struct.pack('i', 1000))", "c.catalog.node('n1') assert set(node['Services'].keys()) == set(['s1', 's2']) _, node = c.catalog.node('n3')", "\"private/\" { policy = \"deny\" } \"\"\" token = c.acl.create(rules=rules)", "available index, nodes = c.health.state('passing') assert set([node['ServiceID'] for node in", "= consul.Consul(port=consul_port) c.kv.put('foo1', '1') c.kv.put('foo2', '2') c.kv.put('foo3', '3') index, data", "assert struct.unpack('i', data['Value']) == (1000,) # test unicode c.kv.put('foo', u'bar')", "index, nodes = c.health.state('any') assert set([node['ServiceID'] for node in nodes])", "pytest.raises(consul.ACLDisabled, c.acl.create) pytest.raises(consul.ACLDisabled, c.acl.update, 'foo') pytest.raises(consul.ACLDisabled, c.acl.clone, 'foo') pytest.raises(consul.ACLDisabled, c.acl.destroy,", "acl_consul.token acls = c.acl.list(token=master_token) assert set([x['ID'] for x in acls])", "pytest.raises(consul.ConsulException, c.session.list, dc='dc2') _, sessions = c.session.list() assert [x['Name'] for", "assert c.kv.delete('foo', recurse=True) is True index, data = c.kv.get('foo', recurse=True)", "consul import consul.std Check = consul.Check class TestHTTPClient(object): def test_uri(self):", "nodes = c.health.service('foo', tag='tag:foo:1') assert [node['Service']['ID'] for node in nodes]", "index, data = c.kv.get('foo') assert c.kv.put('foo', 'bar2', cas=data['ModifyIndex']-1) is False", "\"test\") time.sleep(40/1000.0) checks_pre = c.agent.checks() assert '_node_maintenance' in checks_pre.keys() assert", "catalog.deregister pytest.raises( consul.ConsulException, c.catalog.deregister, 'n2', dc='dc2') assert c.catalog.deregister('n1', check_id='c1') is", "consul.ACLPermissionDenied, c.agent.service.register, \"bar-1\", token=token) c.agent.service.register(\"foo-1\", token=token) index, data = c.health.service('foo-1',", "Check.http(http_addr, '10ms')) is True time.sleep(1) verify_check_status('http_check', 'passing') verify_and_dereg_check('http_check') assert c.agent.check.register(", "c.agent.service.maintenance('foo', 'true', \"test\") time.sleep(40/1000.0) checks_pre = c.agent.checks() assert '_service_maintenance:foo' in", "c.health.state('any') assert [node['ServiceID'] for node in nodes] == [''] #", "token=token) index, data = c.health.service('foo-1', token=token) assert data[0]['Service']['ID'] == \"foo-1\"", "assert c.acl.destroy(token2) is True assert c.acl.info(token2) is None c.kv.put('foo', 'bar')", "# The empty string is for the Serf Health Status", "pytest.raises(consul.ACLDisabled, c.acl.update, 'foo') pytest.raises(consul.ACLDisabled, c.acl.clone, 'foo') pytest.raises(consul.ACLDisabled, c.acl.destroy, 'foo') def", "queries = c.query.get(query['ID']) assert queries != [] \\ and len(queries)", "False for server in config[\"Servers\"]: if server[\"Leader\"]: leader = True", "def test_health_checks(self, consul_port): c = consul.Consul(port=consul_port) c.agent.service.register( 'foobar', service_id='foobar', check=Check.ttl('10s'))", "c.agent.check.register( 'script_check', Check.script('/bin/true', 10)) is True verify_and_dereg_check('script_check') assert c.agent.check.register( 'check", "{\"KV\": {\"Verb\": \"set\", \"Key\": \"asdf\", \"Value\": value}} r = c.txn.put([d])", "session.node node = session['Node'] pytest.raises( consul.ConsulException, c.session.node, node, dc='dc2') _,", "c.session.renew(s) assert session['Behavior'] == 'delete' assert session['TTL'] == '20s' #", "== ['my-session'] # session.info pytest.raises( consul.ConsulException, c.session.info, session_id, dc='dc2') index,", "c = consul.Consul(port=consul_port) # grab the node our server created,", "c.agent.service.register(service_name) time.sleep(80/1000.0) index, nodes = c.health.service(service_name) assert [node['Service']['ID'] for node", "= c.health.service('foo1') assert [node['Service']['ID'] for node in nodes] == ['foo1']", "c.session.list() assert [x['Name'] for x in sessions] == ['my-session'] #", "'bar2', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'foo', token=token) assert c.kv.get('private/foo')[1]['Value'] ==", "are available index, nodes = c.health.state('passing') assert set([node['ServiceID'] for node", "in nodes]) == set(['n1', 'n2']) _, nodes = c.catalog.service('s1', tag='master')", "data] == ['foo1', 'foo2', 'foo3'] assert c.kv.delete('foo2') is True index,", "= c.agent.self()['Config']['NodeName'] index, checks = c.health.node(node) assert node in [check[\"Node\"]", "in acls]) == \\ set(['anonymous', master_token]) assert c.acl.info('foo') is None", "events = c.event.list(name=\"othername\") assert events == [] index, events =", "= c.kv.get('foo') assert data['Value'] == six.b('bar') def test_kv_wait(self, consul_port): c", "= c.health.service('foo') assert nodes == [] # register two nodes,", "= c.session.renew(s) assert session['Behavior'] == 'delete' assert session['TTL'] == '20s'", "c.acl.info, '1'*36) pytest.raises(consul.ACLDisabled, c.acl.create) pytest.raises(consul.ACLDisabled, c.acl.update, 'foo') pytest.raises(consul.ACLDisabled, c.acl.clone, 'foo')", "members: assert x['Status'] == 1 assert not x['Name'] is None", "is False assert c.kv.put('foo', '2', release=s2) is False assert c.kv.put('foo',", "= consul.Consul(port=consul_port) # session.create pytest.raises(consul.ConsulException, c.session.create, node='n2') pytest.raises(consul.ConsulException, c.session.create, dc='dc2')", "is True time.sleep(40/1000.0) assert c.agent.service.deregister('foo1') is True time.sleep(40/1000.0) def test_agent_register_check_no_service_id(self,", "import pytest import six import consul import consul.std Check =", "queries == [] # create a new named query query_service", "consul.Consul(port=consul_port) index, nodes = c.health.service(\"foo1\") assert nodes == [] pytest.raises(consul.std.base.ConsulException,", "assert session['Name'] == 'my-session' # session.node node = session['Node'] pytest.raises(", "data = c.kv.get('foo', index=index, wait='20ms') assert index == check def", "attempt to renew an unknown session pytest.raises(consul.NotFound, c.session.renew, '1'*36) session", "\\ \"was {1}\".format(leader, addr_port) def test_status_peers(self, consul_port): c = consul.Consul(port=consul_port)", "\"foobody\") index, events = c.event.list() assert [x['Name'] == 'fooname' for", "# grab the node our server created, so we can", "data = c.kv.get('foo') assert data is None def test_kv_acquire_release(self, consul_port):", "time.sleep(40/1000.0) index, nodes = c.health.service('foo1') assert [node['Service']['ID'] for node in", "c.kv.get('private/foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.get, 'private/foo') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.put,", "True assert c.kv.put('foo', '1', release='foo') is False assert c.kv.put('foo', '2',", "set(node['Services'].keys()) == set(['s1', 's2']) _, node = c.catalog.node('n3') assert node", "nodes = c.health.state('passing') assert [node['ServiceID'] for node in nodes] !=", "c.kv.get, 'private/foo', token=token ) pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'private/foo', 'bar2', token=token)", "c.kv.get('foo') assert data is None assert c.kv.put('foo', 'bar') is True", "in checks_post.keys() def test_agent_members(self, consul_port): c = consul.Consul(port=consul_port) members =", "six.b('2'), six.b('3')] def test_kv_delete(self, consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo1', '1')", "= acl_consul.token acls = c.acl.list() assert set([x['ID'] for x in", "assert response contains query ID assert 'ID' in query \\", "set(['n2']) # test catalog.deregister pytest.raises( consul.ConsulException, c.catalog.deregister, 'n2', dc='dc2') assert", "c.kv.put('foo', 'bar2', cas=data['ModifyIndex']-1) is False assert c.kv.put('foo', 'bar2', cas=data['ModifyIndex']) is", "in events] assert [x['Payload'] == 'foobody' for x in events]", "in data] == ['foo1', 'foo3'] assert c.kv.delete('foo', recurse=True) is True", "[] # ping the two node's health check c.agent.check.ttl_pass('service:foo:1') c.agent.check.ttl_pass('service:foo:2')", "= \"read\" } \"\"\" token = c.acl.create(rules=rules, token=master_token) assert c.acl.info(token)['Rules']", "consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo', 'bar') index, data = c.kv.get('foo')", "== \\ 'http://127.0.0.1:8500/v1/kv?index=1' class TestConsul(object): def test_kv(self, consul_port): c =", "session = c.session.info(session_id) assert session['Name'] == 'my-session' # session.node node", "the service 'foo' index, nodes = c.health.service('foo') assert nodes ==", "with a long ttl, the other shorter c.agent.service.register( 'foo', service_id='foo:1',", "c.session.node(node) assert [x['Name'] for x in sessions] == ['my-session'] #", "'20s' # trying out the behavior assert c.kv.put('foo', '1', acquire=s)", "'Stats', 'Config', 'Coord', 'DebugConfig', 'Meta']) def test_agent_services(self, consul_port): c =", "wait='20ms') assert index == check def test_kv_encoding(self, consul_port): c =", "consul.Consul(port=consul_port) assert c.event.fire(\"fooname\", \"foobody\") index, events = c.event.list() assert [x['Name']", "in nodes] == [''] def test_health_node(self, consul_port): c = consul.Consul(port=consul_port)", "health check index, nodes = c.health.service('foo', passing=True) assert nodes ==", "s2 = c.session.create() assert c.kv.put('foo', '1', acquire=s1) is True assert", "c.catalog.service('s1') assert set([x['Node'] for x in nodes]) == set(['n1']) #", "in nodes]) == set( ['', 'foo:1']) # ping the failed", "consul_port): c = consul.Consul(port=consul_port) assert c.event.fire(\"fooname\", \"foobody\") index, events =", "c.catalog.nodes() assert len(nodes) == 1 current = nodes[0] # test", "checks] == ['foobar'] assert [check['CheckID'] for check in checks] ==", "consul.Consul(port=consul_port) config = c.operator.raft_config() assert config[\"Index\"] == 1 leader =", "True # check the nodes weren't removed _, nodes =", "consul.Consul(port=consul_port) s = c.session.create(behavior='delete', ttl=20) # attempt to renew an", "is True index, data = c.kv.get('foo') assert data is None", "= c.kv.get('foo') assert data['Value'] == six.b('bar2') def test_kv_put_flags(self, consul_port): c", "but it was not present\".format(addr_port) def test_query(self, consul_port): c =", "c.agent.checks() assert '_service_maintenance:foo' in checks_pre.keys() assert 'test' == checks_pre['_service_maintenance:foo']['Notes'] c.agent.service.maintenance('foo',", "token=master_token) acls = c.acl.list(token=master_token) assert set([x['ID'] for x in acls])", "test_acl_disabled(self, consul_port): c = consul.Consul(port=consul_port) pytest.raises(consul.ACLDisabled, c.acl.list) pytest.raises(consul.ACLDisabled, c.acl.info, '1'*36)", "assert data['Value'] == six.b('bar') def test_kv_wait(self, consul_port): c = consul.Consul(port=consul_port)", "assert c.catalog.datacenters() == ['dc1'] # test catalog.register pytest.raises( consul.ConsulException, c.catalog.register,", "binary c.kv.put('foo', struct.pack('i', 1000)) index, data = c.kv.get('foo') assert struct.unpack('i',", "events] assert [x['Payload'] == 'foobody' for x in events] def", "[ v['Address'] for k, v in c.agent.services().items() if k ==", "sessions = c.session.list() assert [x['Name'] for x in sessions] ==", "== ['my-session'] # session.destroy pytest.raises( consul.ConsulException, c.session.destroy, session_id, dc='dc2') assert", "is True verify_check_status('ttl_check', 'critical') assert c.agent.check.ttl_fail( 'ttl_check', notes='something went boink!')", "assert nodes == [] def test_health_state(self, consul_port): c = consul.Consul(port=consul_port)", "True index, data = c.kv.get('foo', recurse=True) assert [x['Key'] for x", "[node['Service']['ID'] for node in nodes] == [service_name] # Clean up", "service registration pytest.raises( consul.ACLPermissionDenied, c.agent.service.register, \"bar-1\", token=token) c.agent.service.register(\"foo-1\", token=token) index,", "catalog.services pytest.raises(consul.ConsulException, c.catalog.services, dc='dc2') _, services = c.catalog.services() assert services", "# explain query assert c.query.explain(query_name)['Query'] # delete query assert c.query.delete(query['ID'])", "compare.sort(key=operator.itemgetter('ID')) assert acls == compare rules = \"\"\" key \"\"", "# check n2's s1 service was removed though _, nodes", "struct.pack('i', 1000)) index, data = c.kv.get('foo') assert struct.unpack('i', data['Value']) ==", "consul.Consul(port=consul_port) # test binary c.kv.put('foo', struct.pack('i', 1000)) index, data =", "c.agent.check.register, 'foo', Check.ttl('100ms'), service_id='foo1') time.sleep(40/1000.0) assert c.agent.checks() == {} #", "== set(['n2']) # test catalog.deregister pytest.raises( consul.ConsulException, c.catalog.deregister, 'n2', dc='dc2')", "= c.kv.get('foo', recurse=True) assert [x['Key'] for x in data] ==", "for x in acls]) == \\ set(['anonymous', master_token]) def test_acl_implicit_token_use(self,", "= c.session.info(session_id) assert session['Name'] == 'my-session' # session.node node =", "consul.Consul(port=consul_port) agent_self = c.agent.self() leader = c.status.leader() addr_port = agent_self['Stats']['consul']['leader_addr']", "default c = consul.Consul(port=acl_consul.port, token=acl_consul.token) master_token = acl_consul.token acls =", "'foo3'] assert c.kv.delete('foo2') is True index, data = c.kv.get('foo', recurse=True)", "up c.acl.destroy(token) acls = c.acl.list() assert set([x['ID'] for x in", "consul.Consul(port=consul_port) c.agent.service.register( 'foobar', service_id='foobar', check=Check.ttl('10s')) time.sleep(40/1000.00) index, checks = c.health.checks('foobar')", "c.kv.get('foo') assert data['Value'] is None # test None c.kv.put('foo', None)", "None # test None c.kv.put('foo', None) index, data = c.kv.get('foo')", "for x in events] def test_agent_checks(self, consul_port): c = consul.Consul(port=consul_port)", "check=Check.ttl('100ms')) time.sleep(40/1000.0) c.agent.service.maintenance('foo', 'true', \"test\") time.sleep(40/1000.0) checks_pre = c.agent.checks() assert", "time.sleep(40/1000.00) index, checks = c.health.checks('foobar') assert [check['ServiceID'] for check in", "= consul.Consul(port=consul_port) assert c.kv.put('bar', '4') is True assert c.kv.put('base/foo', '1')", "data['Flags'] == 50 def test_kv_recurse(self, consul_port): c = consul.Consul(port=consul_port) index,", "True assert [ v['Address'] for k, v in c.agent.services().items() if", "data = c.kv.get('foo', recurse=True) assert [x['Key'] for x in data]", "True index, data = c.kv.get('foo', recurse=True) assert data is None", "in nodes] == [] def test_health_service(self, consul_port): c = consul.Consul(port=consul_port)", "nodes]) == set(['n1', 'n2']) _, nodes = c.catalog.service('s1', tag='master') assert", "dc='dc2') assert c.session.destroy(session_id) is True _, sessions = c.session.list() assert", "six.b('1'), six.b('2'), six.b('3')] def test_kv_delete(self, consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo1',", "nodes show for the /health/state/any endpoint index, nodes = c.health.state('any')", "c.kv.put('foo', None) index, data = c.kv.get('foo') assert data['Value'] is None", "'Foo' assert c.acl.destroy(token2, token=master_token) is True assert c.acl.info(token2) is None", "assert c.acl.info('foo') is None compare = [c.acl.info(master_token), c.acl.info('anonymous')] compare.sort(key=operator.itemgetter('ID')) assert", "c.health.service('foo-1', token=token) assert data[0]['Service']['ID'] == \"foo-1\" index, data = c.health.checks('foo-1',", "is True assert c.kv.put('foo', '1', release='foo') is False assert c.kv.put('foo',", "policy = \"write\" } service \"bar-\" { policy = \"read\"", "c.session.destroy, session_id, dc='dc2') assert c.session.destroy(session_id) is True _, sessions =", "key \"private/\" { policy = \"deny\" } \"\"\" token =", "\"\" { policy = \"read\" } key \"private/\" { policy", "is True time.sleep(40/1000.0) index, nodes = c.health.service(service_name) assert [node['Service']['ID'] for", "consul.Consul(port=consul_port) pytest.raises(consul.ACLDisabled, c.acl.list) pytest.raises(consul.ACLDisabled, c.acl.info, '1'*36) pytest.raises(consul.ACLDisabled, c.acl.create) pytest.raises(consul.ACLDisabled, c.acl.update,", "= \"deny\" } service \"foo-\" { policy = \"write\" }", "\"set\", \"Key\": \"asdf\", \"Value\": value}} r = c.txn.put([d]) assert r[\"Errors\"]", "no nodes for the service 'foo' index, nodes = c.health.service('foo')", "check_id='c1') is True assert c.catalog.deregister('n2', service_id='s1') is True # check", "[x['Payload'] == 'foobody' for x in events] def test_agent_checks(self, consul_port):", "in node['Checks']]) == set(['foo1', '']) assert set([ check['CheckID'] for node", "nodes = c.health.service(service_name) assert [node['Service']['ID'] for node in nodes] ==", "x in acls]) == \\ set(['anonymous', master_token]) def test_status_leader(self, consul_port):", "assert set([ check['ServiceID'] for node in nodes for check in", "so we can ignore it _, nodes = c.catalog.nodes() assert", "c.catalog.datacenters() == ['dc1'] # test catalog.register pytest.raises( consul.ConsulException, c.catalog.register, 'foo',", "data == [] index, data = c.health.service('bar-1', token=token) assert not", "c.query.get(query['ID']) assert queries != [] \\ and len(queries) == 1", "aren't passing their health check index, nodes = c.health.state('passing') assert", "== addr_port, \\ \"Leader value was {0}, expected value \"", "ping the two node's health check c.agent.check.ttl_pass('service:foo:1') c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0) #", "c.kv.get('foo') assert data['Value'] == six.b('1') c.session.destroy(s) index, data = c.kv.get('foo')", "'critical') verify_and_dereg_check('ttl_check') def test_service_dereg_issue_156(self, consul_port): # https://github.com/cablehead/python-consul/issues/156 service_name = 'app#127.0.0.1#3000'", "nodes are now available index, nodes = c.health.state('passing') assert set([node['ServiceID']", "x in nodes]) == set(['n1', 'n2']) _, nodes = c.catalog.service('s1',", "'n2'] # test catalog.services pytest.raises(consul.ConsulException, c.catalog.services, dc='dc2') _, services =", "c.session.create() s2 = c.session.create() assert c.kv.put('foo', '1', acquire=s1) is True", "assert c.kv.put('foo', '1', acquire=s1) is True assert c.kv.put('foo', '2', acquire=s2)", "check the nodes show for the /health/state/any endpoint index, nodes", "keys=True, separator='/') assert data == ['base/base/', 'base/foo'] def test_transaction(self, consul_port):", "token=acl_consul.token) master_token = acl_consul.token acls = c.acl.list() assert set([x['ID'] for", "node in nodes]) == set( ['', 'foo:1', 'foo:2']) # wait", "acquire=s1) is True assert c.kv.put('foo', '1', release='foo') is False assert", "for check in node['Checks']]) == set(['foo1', '']) assert set([ check['CheckID']", "\\ 'http://127.0.0.1:8500/v1/kv?index=1' class TestConsul(object): def test_kv(self, consul_port): c = consul.Consul(port=consul_port)", "node in [check[\"Node\"] for check in checks] def test_health_checks(self, consul_port):", "node in nodes] == ['foo:1', 'foo:2'] # check that tag", "def verify_check_status(check_id, status, notes=None): checks = c.agent.checks() assert checks[check_id]['Status'] ==", "# session.node node = session['Node'] pytest.raises( consul.ConsulException, c.session.node, node, dc='dc2')", "index, session = c.session.info(session_id) assert session['Name'] == 'my-session' # session.node", "token=token) # clean up c.acl.destroy(token) acls = c.acl.list() assert set([x['ID']", "c.agent.service.register('foo', check=Check.ttl('100ms')) time.sleep(40/1000.0) c.agent.service.maintenance('foo', 'true', \"test\") time.sleep(40/1000.0) checks_pre = c.agent.checks()", "\\ \"Expected value '{0}' \" \\ \"in peer list but", "ignore it _, nodes = c.catalog.nodes() assert len(nodes) == 1", "= c.txn.put([d]) assert r[\"Results\"][0][\"KV\"][\"Value\"] == value def test_event(self, consul_port): c", "tag works index, nodes = c.health.service('foo', tag='tag:foo:1') assert [node['Service']['ID'] for", "consul_port): c = consul.Consul(port=consul_port) value = base64.b64encode(b\"1\").decode(\"utf8\") d = {\"KV\":", "c = consul.Consul(port=consul_port) c.agent.service.register( 'foobar', service_id='foobar', check=Check.ttl('10s')) time.sleep(40/1000.00) index, checks", "data = c.kv.get('base/', keys=True, separator='/') assert data == ['base/base/', 'base/foo']", "c = consul.Consul(port=consul_port) assert c.agent.service.register('foo') is True assert set(c.agent.services().keys()) ==", "\\ and queries[0]['ID'] == query['ID'] # explain query assert c.query.explain(query_name)['Query']", "'foo3'] assert c.kv.delete('foo', recurse=True) is True index, data = c.kv.get('foo',", "c.health.checks('foo-1', token=token) assert data == [] index, data = c.health.service('bar-1',", "index, data = c.kv.get('foo') assert data['Value'] == six.b('bar2') def test_kv_put_flags(self,", "# clean up c.acl.destroy(token) acls = c.acl.list() assert set([x['ID'] for", "checks_pre['_service_maintenance:foo']['Notes'] c.agent.service.maintenance('foo', 'false') time.sleep(40/1000.0) checks_post = c.agent.checks() assert '_service_maintenance:foo' not", "= c.session.create('my-session') # session.list pytest.raises(consul.ConsulException, c.session.list, dc='dc2') _, sessions =", "c.acl.list) pytest.raises(consul.ACLDisabled, c.acl.info, '1'*36) pytest.raises(consul.ACLDisabled, c.acl.create) pytest.raises(consul.ACLDisabled, c.acl.update, 'foo') pytest.raises(consul.ACLDisabled,", "if k == 'foo'][0] == '10.10.10.1' assert c.agent.service.deregister('foo') is True", "params={'index': 1}) == \\ 'http://127.0.0.1:8500/v1/kv?index=1' class TestConsul(object): def test_kv(self, consul_port):", "cas=50) is False assert c.kv.put('foo', 'bar', cas=0) is True index,", "set( ['', 'foo:1', 'foo:2']) # wait until the short ttl", "[x['Key'] for x in data] == ['foo1', 'foo2', 'foo3'] assert", "addr_port = agent_self['Stats']['consul']['leader_addr'] peers = c.status.peers() assert addr_port in peers,", "= c.agent.checks() assert '_service_maintenance:foo' in checks_pre.keys() assert 'test' == checks_pre['_service_maintenance:foo']['Notes']", "True index, data = c.kv.get('base/', keys=True, separator='/') assert data ==", "the nodes c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2') time.sleep(40/1000.0) index, nodes = c.health.state('any') assert", "index, checks = c.health.checks('foobar') assert [check['ServiceID'] for check in checks]", "query list is empty queries = c.query.list() assert queries ==", "c.kv.get('foo') check, data = c.kv.get('foo', index=index, wait='20ms') assert index ==", "boink!') is True verify_check_status( 'ttl_check', 'critical', notes='something went boink!') assert", "\"private/\" { policy = \"deny\" } service \"foo-\" { policy", "check we can override the client's default token pytest.raises( consul.ACLPermissionDenied,", "set(['anonymous', master_token]) assert c.acl.info('1'*36) is None compare = [c.acl.info(master_token), c.acl.info('anonymous')]", "assert c.acl.info(token2)['Name'] == 'Foo' assert c.acl.destroy(token2) is True assert c.acl.info(token2)", "but that they aren't passing their health check index, nodes", "nodes] == [''] # register two nodes, one with a", "index, nodes = c.health.service('foo', tag='tag:foo:1') assert [node['Service']['ID'] for node in", "assert len(checks) == 0 def test_session(self, consul_port): c = consul.Consul(port=consul_port)", "= c.health.node(node) assert node in [check[\"Node\"] for check in checks]", "check_id='check_id') is True verify_and_dereg_check('check_id') http_addr = \"http://127.0.0.1:{0}\".format(consul_port) assert c.agent.check.register( 'http_check',", "node name node = c.agent.self()['Config']['NodeName'] index, checks = c.health.node(node) assert", "== 'foobody' for x in events] def test_event_targeted(self, consul_port): c", "passing=True) assert [node['Service']['ID'] for node in nodes] == ['foo:1', 'foo:2']", "nodes] == [] def test_health_service(self, consul_port): c = consul.Consul(port=consul_port) #", "False assert c.kv.put('foo', '1', acquire=s1) is True assert c.kv.put('foo', '1',", "for node in nodes]) == set( ['', 'foo:1', 'foo:2']) #", "'bar') c_limited = consul.Consul(port=acl_consul.port, token=token) assert c_limited.kv.get('foo')[1]['Value'] == six.b('bar') pytest.raises(", "'Coord', 'DebugConfig', 'Meta']) def test_agent_services(self, consul_port): c = consul.Consul(port=consul_port) assert", "token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'foo', token=token) assert c.kv.get('private/foo')[1]['Value'] == six.b('bar')", "test catalog.services pytest.raises(consul.ConsulException, c.catalog.services, dc='dc2') _, services = c.catalog.services() assert", "up tasks assert c.agent.check.deregister('foo') is True time.sleep(40/1000.0) assert c.agent.service.deregister('foo1') is", "assert len(data) == 1 c.kv.put('foo/bar1', '1') c.kv.put('foo/bar2', '2') c.kv.put('foo/bar3', '3')", "= c.kv.get('foo') assert data is None def test_kv_acquire_release(self, consul_port): c", "test_agent_services(self, consul_port): c = consul.Consul(port=consul_port) assert c.agent.service.register('foo') is True assert", "['foo:1'] # deregister the nodes c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2') time.sleep(40/1000.0) index, nodes", "None c.kv.put('foo', None) index, data = c.kv.get('foo') assert data['Value'] is", "node in nodes] == [''] # register two nodes, one", "assert acls == compare rules = \"\"\" key \"\" {", "policy = \"deny\" } service \"foo-\" { policy = \"write\"", "== rules assert c.acl.update(token2, name='Foo') == token2 assert c.acl.info(token2)['Name'] ==", "assert c.agent.checks()['check']['Notes'] == 'foo' c.agent.check.deregister('check') assert set(c.agent.checks().keys()) == set([]) assert", "c.kv.get('foo', recurse=True) assert [x['Key'] for x in data] == ['foo1',", "c.agent.members() for x in members: assert x['Status'] == 1 assert", "= c.health.checks('foobar') assert [check['ServiceID'] for check in checks] == ['foobar']", "True _, nodes = c.catalog.nodes() nodes.remove(current) assert [x['Node'] for x", "'bar', cas=50) is False assert c.kv.put('foo', 'bar', cas=0) is True", "'bar', flags=50) is True index, data = c.kv.get('foo') assert data['Flags']", "'test' == checks_pre['_service_maintenance:foo']['Notes'] c.agent.service.maintenance('foo', 'false') time.sleep(40/1000.0) checks_post = c.agent.checks() assert", "k, v in c.agent.services().items() if k == 'foo'][0] == '10.10.10.1'", "= c.query.list() assert queries == [] # create a new", "c.kv.put('base/foo', '1') is True assert c.kv.put('base/base/foo', '5') is True index,", "data = c.kv.get('foo') assert data['Value'] == six.b('bar') def test_kv_wait(self, consul_port):", "assert [check['CheckID'] for check in checks] == ['service:foobar'] c.agent.service.deregister('foobar') time.sleep(40/1000.0)", "consul.Consul(port=consul_port) assert c.event.fire(\"fooname\", \"foobody\") index, events = c.event.list(name=\"othername\") assert events", "node in nodes for check in node['Checks']]) == set(['foo1', ''])", "index, data = c.kv.get('foo') assert data['Flags'] == 0 assert c.kv.put('foo',", "'dc1' in x['Name'] def test_agent_self(self, consul_port): c = consul.Consul(port=consul_port) assert", "assert events == [] index, events = c.event.list(name=\"fooname\") assert [x['Name']", "= consul.Consul(port=consul_port) pytest.raises(consul.ACLDisabled, c.acl.list) pytest.raises(consul.ACLDisabled, c.acl.info, '1'*36) pytest.raises(consul.ACLDisabled, c.acl.create) pytest.raises(consul.ACLDisabled,", "[node['Service']['ID'] for node in nodes] == ['foo:1', 'foo:2'] # wait", "'2', release=s2) is False assert c.kv.put('foo', '2', release=s1) is True", "c.catalog.services() assert services == {'s1': [u'master'], 's2': [], 'consul': []}", "assert c.acl.info(token2) is None c.kv.put('foo', 'bar') c.kv.put('private/foo', 'bar') c_limited =", "index=index, wait='20ms') assert index == check def test_kv_encoding(self, consul_port): c", "c.query.delete(query['ID']) def test_coordinate(self, consul_port): c = consul.Consul(port=consul_port) c.coordinate.nodes() c.coordinate.datacenters() assert", "data = c.kv.get('foo') check, data = c.kv.get('foo', index=index, wait='20ms') assert", "'fooname' for x in events] assert [x['Payload'] == 'foobody' for", "c.acl.clone(token) assert c.acl.info(token2)['Rules'] == rules assert c.acl.update(token2, name='Foo') == token2", "in checks] def test_health_checks(self, consul_port): c = consul.Consul(port=consul_port) c.agent.service.register( 'foobar',", "c_limited.kv.get, 'private/foo') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.put, 'private/foo', 'bar2') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.delete,", "consul.Consul(port=consul_port) value = base64.b64encode(b\"1\").decode(\"utf8\") d = {\"KV\": {\"Verb\": \"set\", \"Key\":", "create a new named query query_service = 'foo' query_name =", "in nodes]) == set( ['', 'foo:1', 'foo:2']) # but that", "is True index, data = c.kv.get('foo', recurse=True) assert [x['Key'] for", "c.kv.delete('foo', recurse=True) is True index, data = c.kv.get('foo', recurse=True) assert", "# only one node available index, nodes = c.health.service('foo', passing=True)", "# attempt to renew an unknown session pytest.raises(consul.NotFound, c.session.renew, '1'*36)", "[x['Payload'] == 'foobody' for x in events] def test_event_targeted(self, consul_port):", "can ignore it _, nodes = c.catalog.nodes() assert len(nodes) ==", "'warning', 'its not quite right') assert c.agent.check.ttl_fail('ttl_check') is True verify_check_status('ttl_check',", "# test catalog.services pytest.raises(consul.ConsulException, c.catalog.services, dc='dc2') _, services = c.catalog.services()", "assert set([x['Node'] for x in nodes]) == set(['n1', 'n2']) _,", "is False assert c.kv.put('foo', '2', release=s1) is True c.session.destroy(s1) c.session.destroy(s2)", "'1'*36) pytest.raises(consul.ACLDisabled, c.acl.create) pytest.raises(consul.ACLDisabled, c.acl.update, 'foo') pytest.raises(consul.ACLDisabled, c.acl.clone, 'foo') pytest.raises(consul.ACLDisabled,", "passing=True) assert [node['Service']['ID'] for node in nodes] == ['foo:1'] #", "time.sleep(40/1000.0) checks_pre = c.agent.checks() assert '_node_maintenance' in checks_pre.keys() assert 'test'", "registration pytest.raises( consul.ACLPermissionDenied, c.agent.service.register, \"bar-1\", token=token) c.agent.service.register(\"foo-1\", token=token) index, data", "acls = c.acl.list(token=master_token) assert set([x['ID'] for x in acls]) ==", "c.health.checks('foobar') assert len(checks) == 0 def test_session(self, consul_port): c =", "assert c.acl.info(token2) is None c.kv.put('foo', 'bar') c.kv.put('private/foo', 'bar') assert c.kv.get('foo',", "'{0}' \" \\ \"in peer list but it was not", "data['Value']) == (1000,) # test unicode c.kv.put('foo', u'bar') index, data", "{\"Verb\": \"get\", \"Key\": \"asdf\"}} r = c.txn.put([d]) assert r[\"Results\"][0][\"KV\"][\"Value\"] ==", "True verify_check_status('ttl_check', 'passing') assert c.agent.check.ttl_pass( 'ttl_check', notes='all hunky dory!') is", "== ['foo:1', 'foo:2'] # but that they aren't passing their", "nodes] == ['foo:1'] # ping the failed node's health check", "assert c.agent.check.ttl_fail('ttl_check') is True verify_check_status('ttl_check', 'critical') assert c.agent.check.ttl_fail( 'ttl_check', notes='something", "token=token) assert not data # clean up assert c.agent.service.deregister('foo-1') is", "data is None c.kv.put('foo/', None) index, data = c.kv.get('foo/', recurse=True)", "class TestHTTPClient(object): def test_uri(self): http = consul.std.HTTPClient() assert http.uri('/v1/kv') ==", "def test_session(self, consul_port): c = consul.Consul(port=consul_port) # session.create pytest.raises(consul.ConsulException, c.session.create,", "assert config[\"Index\"] == 1 leader = False voter = False", "token=token ) pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'private/foo', 'bar2', token=token) pytest.raises( consul.ACLPermissionDenied,", "assert [node['ServiceID'] for node in nodes] != 'foo' # ping", "check index, nodes = c.health.state('passing') assert [node['ServiceID'] for node in", "nodes show for the /health/service endpoint index, nodes = c.health.service('foo')", "c.catalog.services, dc='dc2') _, services = c.catalog.services() assert services == {'s1':", "if notes: assert checks[check_id]['Output'] == notes # test setting notes", "assert c.agent.checks() == {} # Cleanup tasks c.agent.check.deregister('foo') time.sleep(40/1000.0) def", "time.sleep(40/1000.0) index, nodes = c.health.service(service_name) assert [node['Service']['ID'] for node in", "# test catalog.nodes pytest.raises(consul.ConsulException, c.catalog.nodes, dc='dc2') _, nodes = c.catalog.nodes()", "== [] # register two nodes, one with a long", "c.session.list, dc='dc2') _, sessions = c.session.list() assert [x['Name'] for x", "== ['dc1'] # test catalog.register pytest.raises( consul.ConsulException, c.catalog.register, 'foo', '10.1.10.11',", "test address param assert c.agent.service.register('foo', address='10.10.10.1') is True assert [", "verify_and_dereg_check('http_timeout_check') assert c.agent.check.register('ttl_check', Check.ttl('100ms')) is True assert c.agent.check.ttl_warn('ttl_check') is True", "not x['Tags'] is None assert c.agent.self()['Member'] in members wan_members =", "nodes are available index, nodes = c.health.service('foo', passing=True) assert [node['Service']['ID']", "base64.b64encode(b\"1\").decode(\"utf8\") d = {\"KV\": {\"Verb\": \"set\", \"Key\": \"asdf\", \"Value\": value}}", "nodes = c.catalog.nodes() nodes.remove(current) assert [x['Node'] for x in nodes]", "dc='dc2') session_id = c.session.create('my-session') # session.list pytest.raises(consul.ConsulException, c.session.list, dc='dc2') _,", "= consul.Consul(port=consul_port) c.kv.put('foo', 'bar') index, data = c.kv.get('foo') assert c.kv.delete('foo',", "dc='dc2') _, sessions = c.session.node(node) assert [x['Name'] for x in", "= nodes[0] # test catalog.datacenters assert c.catalog.datacenters() == ['dc1'] #", "is True index, data = c.kv.get('foo') assert data['Flags'] == 50", "is True index, data = c.kv.get('foo') assert data['Value'] == six.b('bar')", "config = c.operator.raft_config() assert config[\"Index\"] == 1 leader = False", "c = consul.Consul(port=consul_port) assert c.event.fire(\"fooname\", \"foobody\") index, events = c.event.list()", "'n2', '10.1.10.12', service={'service': 's1', 'tags': ['master']}) is True # test", "assert queries[0]['Name'] == query_name \\ and queries[0]['ID'] == query['ID'] #", "x['Status'] == 1 assert not x['Name'] is None assert not", "consul.ACLPermissionDenied, c_limited.kv.delete, 'foo') assert c.kv.get('private/foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.get,", "'foo' index, nodes = c.health.service('foo') assert nodes == [] #", "tags=['tag:foo:1']) c.agent.service.register( 'foo', service_id='foo:2', check=Check.ttl('100ms')) time.sleep(40/1000.0) # check the nodes", "assert c.kv.delete('foo', cas=data['ModifyIndex']) is True index, data = c.kv.get('foo') assert", "nodes = c.catalog.service('s1') assert set([x['Node'] for x in nodes]) ==", "'test' == checks_pre['_node_maintenance']['Notes'] c.agent.maintenance('false') time.sleep(40/1000.0) checks_post = c.agent.checks() assert '_node_maintenance'", "'bar', acquire='foo') s1 = c.session.create() s2 = c.session.create() assert c.kv.put('foo',", "grab local node name node = c.agent.self()['Config']['NodeName'] index, checks =", "for x in data] == [ None, six.b('1'), six.b('2'), six.b('3')]", "show for the /health/state/any endpoint index, nodes = c.health.state('any') assert", "time.sleep(40/1000.0) # check both nodes are available index, nodes =", "c.kv.get('foo') assert c.kv.put('foo', 'bar2', cas=data['ModifyIndex']-1) is False assert c.kv.put('foo', 'bar2',", "== \\ set(['anonymous', master_token]) assert c.acl.info('foo') is None compare =", "c = consul.Consul(port=consul_port) # check that query list is empty", "assert c.kv.put('foo', '2', release=s1) is True c.session.destroy(s1) c.session.destroy(s2) def test_kv_keys_only(self,", "server[\"Leader\"]: leader = True if server[\"Voter\"]: voter = True assert", "service_id='foo1') time.sleep(40/1000.0) assert c.agent.checks() == {} # Cleanup tasks c.agent.check.deregister('foo')", "== token2 assert c.acl.info(token2)['Name'] == 'Foo' assert c.acl.destroy(token2, token=master_token) is", "def test_health_state(self, consul_port): c = consul.Consul(port=consul_port) # The empty string", "== '10.10.10.1' assert c.agent.service.deregister('foo') is True def test_catalog(self, consul_port): c", "'2') c.kv.put('foo/bar3', '3') index, data = c.kv.get('foo/', recurse=True) assert [x['Key']", "c.agent.checks() assert '_node_maintenance' not in checks_post.keys() def test_agent_members(self, consul_port): c", "aren't passing their health check index, nodes = c.health.service('foo', passing=True)", "long ttl, the other shorter c.agent.service.register( 'foo', service_id='foo:1', check=Check.ttl('10s')) c.agent.service.register(", "'private/foo', 'bar2', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'private/foo', token=token) # clean", "check in checks] == ['service:foobar'] c.agent.service.deregister('foobar') time.sleep(40/1000.0) index, checks =", "assert c.acl.update(token2, name='Foo') == token2 assert c.acl.info(token2)['Name'] == 'Foo' assert", "True assert c.catalog.register( 'n2', '10.1.10.12', service={'service': 's1', 'tags': ['master']}) is", "master_token]) def test_status_leader(self, consul_port): c = consul.Consul(port=consul_port) agent_self = c.agent.self()", "consul.ConsulException, c.session.info, session_id, dc='dc2') index, session = c.session.info('1'*36) assert session", "consul_port): c = consul.Consul(port=consul_port) assert set(c.agent.self().keys()) == set(['Member', 'Stats', 'Config',", "nodes]) == set( ['', 'foo:1', 'foo:2']) # deregister the nodes", "consul_port): c = consul.Consul(port=consul_port) s = c.session.create(behavior='delete', ttl=20) # attempt", "pytest.raises( consul.ConsulException, c.session.node, node, dc='dc2') _, sessions = c.session.node(node) assert", "for x in nodes]) == set(['n2']) # test catalog.deregister pytest.raises(", "assert set(c.agent.services().keys()) == set() # test address param assert c.agent.service.register('foo',", "in members wan_members = c.agent.members(wan=True) for x in wan_members: assert", "enable_tag_override=True) assert c.agent.services()['foo']['EnableTagOverride'] # Cleanup tasks c.agent.check.deregister('foo') def test_agent_service_maintenance(self, consul_port):", "c = consul.Consul(port=consul_port) c.agent.service.register('foo1') time.sleep(40/1000.0) index, nodes = c.health.service('foo1') assert", "[node['Service']['ID'] for node in nodes] == ['foo1'] c.agent.check.register('foo', Check.ttl('100ms'), service_id='foo1')", "Check.ttl('1s'), notes='foo') assert c.agent.checks()['check']['Notes'] == 'foo' c.agent.check.deregister('check') assert set(c.agent.checks().keys()) ==", "checks = c.health.checks('foobar') assert [check['ServiceID'] for check in checks] ==", "= 'fooquery' query = c.query.create(query_service, query_name) # assert response contains", "= c.catalog.service('s1', tag='master') assert set([x['Node'] for x in nodes]) ==", "data = c.kv.get('foo') assert data['Value'] == six.b('bar2') def test_kv_put_flags(self, consul_port):", "x in acls]) == \\ set(['anonymous', master_token]) assert c.acl.info('1'*36) is", "verify_and_dereg_check('ttl_check') def test_service_dereg_issue_156(self, consul_port): # https://github.com/cablehead/python-consul/issues/156 service_name = 'app#127.0.0.1#3000' c", "c.event.fire(\"fooname\", \"foobody\") index, events = c.event.list(name=\"othername\") assert events == []", "is True verify_check_status('ttl_check', 'passing', notes='all hunky dory!') # wait for", "is None c.kv.put('foo/', None) index, data = c.kv.get('foo/', recurse=True) assert", "node's health check c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0) # check both nodes are", "check n2's s1 service was removed though _, nodes =", "pass through for service registration pytest.raises( consul.ACLPermissionDenied, c.agent.service.register, \"bar-1\", token=token)", "import consul import consul.std Check = consul.Check class TestHTTPClient(object): def", "False assert c.kv.put('foo', 'bar2', cas=data['ModifyIndex']) is True index, data =", "c.kv.put('foo', '1', acquire=s1) is True assert c.kv.put('foo', '1', release='foo') is", "that query list is empty queries = c.query.list() assert queries", "is None assert c.agent.self()['Member'] in members wan_members = c.agent.members(wan=True) for", "Cleanup tasks c.agent.check.deregister('foo') def test_agent_service_maintenance(self, consul_port): c = consul.Consul(port=consul_port) c.agent.service.register('foo',", "c.catalog.register( 'n1', '10.1.10.11', service={'service': 's2'}) is True assert c.catalog.register( 'n2',", "== [] index, events = c.event.list(name=\"fooname\") assert [x['Name'] == 'fooname'", "[node['Service']['ID'] for node in nodes] == ['foo:1'] # ping the", "c.event.list(name=\"othername\") assert events == [] index, events = c.event.list(name=\"fooname\") assert", "= c.agent.checks() assert checks[check_id]['Status'] == status if notes: assert checks[check_id]['Output']", "query \\ and query['ID'] is not None \\ and str(query['ID'])", "their health check index, nodes = c.health.service('foo', passing=True) assert nodes", "'warning') assert c.agent.check.ttl_warn( 'ttl_check', notes='its not quite right') is True", "c.session.create, dc='dc2') session_id = c.session.create('my-session') # session.list pytest.raises(consul.ConsulException, c.session.list, dc='dc2')", "assert c_limited.kv.get('foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.put, 'foo', 'bar2') pytest.raises(", "sessions = c.session.list() assert sessions == [] def test_session_delete_ttl_renew(self, consul_port):", "== six.b('bar') def test_kv_wait(self, consul_port): c = consul.Consul(port=consul_port) assert c.kv.put('foo',", "# delete query assert c.query.delete(query['ID']) def test_coordinate(self, consul_port): c =", "nodes = c.health.service(\"foo1\") assert nodes == [] pytest.raises(consul.std.base.ConsulException, c.agent.check.register, 'foo',", "in data] == [ None, six.b('1'), six.b('2'), six.b('3')] def test_kv_delete(self,", "c.coordinate.datacenters() assert set(c.coordinate.datacenters()[0].keys()) == \\ set(['Datacenter', 'Coordinates', 'AreaID']) def test_operator(self,", "c.catalog.register( 'n1', '10.1.10.11', service={'service': 's1'}, check={'name': 'c1'}) is True assert", "health check index, nodes = c.health.state('passing') assert [node['ServiceID'] for node", "for x in events] assert [x['Payload'] == 'foobody' for x", "c = consul.Consul(port=consul_port) pytest.raises(consul.ACLDisabled, c.acl.list) pytest.raises(consul.ACLDisabled, c.acl.info, '1'*36) pytest.raises(consul.ACLDisabled, c.acl.create)", "pytest.raises( consul.ACLPermissionDenied, c.kv.get, 'private/foo', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'private/foo', 'bar2',", "# Cleanup tasks c.agent.check.deregister('foo') time.sleep(40/1000.0) def test_agent_register_enable_tag_override(self, consul_port): c =", "notes=None): checks = c.agent.checks() assert checks[check_id]['Status'] == status if notes:", "= c.session.info('1'*36) assert session is None index, session = c.session.info(session_id)", "one with a long ttl, the other shorter c.agent.service.register( 'foo',", "c.kv.put('foo', 'bar') is True index, data = c.kv.get('foo') check, data", "sessions = c.session.node(node) assert [x['Name'] for x in sessions] ==", "time.sleep(40/1000.0) index, checks = c.health.checks('foobar') assert len(checks) == 0 def", "c.agent.service.register( 'foo', service_id='foo:1', check=Check.ttl('10s'), tags=['tag:foo:1']) c.agent.service.register( 'foo', service_id='foo:2', check=Check.ttl('100ms')) time.sleep(40/1000.0)", "is True assert c.catalog.register( 'n2', '10.1.10.12', service={'service': 's1', 'tags': ['master']})", "the /health/state/any endpoint index, nodes = c.health.state('any') assert set([node['ServiceID'] for", "check=Check.ttl('10s')) c.agent.service.register( 'foo', service_id='foo:2', check=Check.ttl('100ms')) time.sleep(40/1000.0) # check the nodes", "in peers, \\ \"Expected value '{0}' \" \\ \"in peer", "= c.kv.get('foo/', recurse=True) assert data is None c.kv.put('foo/', None) index,", "pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'private/foo', token=token) # test token pass through", "addr_port = agent_self['Stats']['consul']['leader_addr'] assert leader == addr_port, \\ \"Leader value", "True assert c.acl.info(token2) is None c.kv.put('foo', 'bar') c.kv.put('private/foo', 'bar') assert", "consul_port): c = consul.Consul(port=consul_port) c.agent.service.register( 'foobar', service_id='foobar', check=Check.ttl('10s')) time.sleep(40/1000.00) index,", "which has an # empty ServiceID index, nodes = c.health.state('any')", "check index, nodes = c.health.service('foo', passing=True) assert nodes == []", "is empty queries = c.query.list() assert queries == [] #", "c.agent.check.ttl_warn( 'ttl_check', notes='its not quite right') is True verify_check_status('ttl_check', 'warning',", "assert [x['Payload'] == 'foobody' for x in events] def test_agent_checks(self,", "c.acl.update(token2, name='Foo') == token2 assert c.acl.info(token2)['Name'] == 'Foo' assert c.acl.destroy(token2)", "assert http.uri('/v1/kv', params={'index': 1}) == \\ 'http://127.0.0.1:8500/v1/kv?index=1' class TestConsul(object): def", "Cleanup c.agent.service.deregister('foo') time.sleep(40/1000.0) def test_agent_node_maintenance(self, consul_port): c = consul.Consul(port=consul_port) c.agent.maintenance('true',", "token2 assert c.acl.info(token2)['Name'] == 'Foo' assert c.acl.destroy(token2, token=master_token) is True", "param assert c.agent.service.register('foo', address='10.10.10.1') is True assert [ v['Address'] for", "cas=data['ModifyIndex']-1) is False assert c.kv.get('foo') == (index, data) assert c.kv.delete('foo',", "data['Value'] == six.b('bar2') def test_kv_put_flags(self, consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo',", "\\ and query['ID'] is not None \\ and str(query['ID']) !=", "'foo:1']) # ping the failed node's health check c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0)", "it _, nodes = c.catalog.nodes() assert len(nodes) == 1 current", "consul.Consul(port=consul_port) index, data = c.kv.get('foo') assert data is None assert", "1 assert not x['Name'] is None assert not x['Tags'] is", "nodes]) == set( ['', 'foo:1', 'foo:2']) # wait until the", "def test_kv_keys_only(self, consul_port): c = consul.Consul(port=consul_port) assert c.kv.put('bar', '4') is", "index, data = c.kv.get('foo') check, data = c.kv.get('foo', index=index, wait='20ms')", "c.agent.check.register( 'check name', Check.script('/bin/true', 10), check_id='check_id') is True verify_and_dereg_check('check_id') http_addr", "c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2') time.sleep(40/1000.0) index, nodes = c.health.service('foo') assert nodes ==", "!= 'foo' # ping the two node's health check c.agent.check.ttl_pass('service:foo:1')", "data['Value'] == six.b('bar') def test_kv_wait(self, consul_port): c = consul.Consul(port=consul_port) assert", "pytest.raises(consul.ACLPermissionDenied, c.acl.destroy, 'anonymous') def test_acl_explict_token_use(self, acl_consul): c = consul.Consul(port=acl_consul.port) master_token", "checks[check_id]['Status'] == status if notes: assert checks[check_id]['Output'] == notes #", "= c.event.list(name=\"othername\") assert events == [] index, events = c.event.list(name=\"fooname\")", "{1: 2}) def test_kv_put_cas(self, consul_port): c = consul.Consul(port=consul_port) assert c.kv.put('foo',", "has an # empty ServiceID index, nodes = c.health.state('any') assert", "True c.acl.destroy(token, token=master_token) acls = c.acl.list(token=master_token) assert set([x['ID'] for x", "for node in nodes]) == set( ['', 'foo:1']) # ping", "c.acl.destroy, 'foo') def test_acl_permission_denied(self, acl_consul): c = consul.Consul(port=acl_consul.port) pytest.raises(consul.ACLPermissionDenied, c.acl.list)", "= c.agent.checks() assert '_node_maintenance' in checks_pre.keys() assert 'test' == checks_pre['_node_maintenance']['Notes']", "status, notes=None): checks = c.agent.checks() assert checks[check_id]['Status'] == status if", "def test_event_targeted(self, consul_port): c = consul.Consul(port=consul_port) assert c.event.fire(\"fooname\", \"foobody\") index,", "master_token]) assert c.acl.info('1'*36) is None compare = [c.acl.info(master_token), c.acl.info('anonymous')] compare.sort(key=operator.itemgetter('ID'))", "c.agent.check.deregister('foo') time.sleep(40/1000.0) def test_agent_register_enable_tag_override(self, consul_port): c = consul.Consul(port=consul_port) index, nodes", "{ policy = \"read\" } key \"private/\" { policy =", "= c.kv.get('foo') assert data['Flags'] == 50 def test_kv_recurse(self, consul_port): c", "def test_status_peers(self, consul_port): c = consul.Consul(port=consul_port) agent_self = c.agent.self() addr_port", "data = c.kv.get('foo') assert data['Value'] == six.b('bar') # test empty-string", "service_id='foo:2', check=Check.ttl('100ms')) time.sleep(40/1000.0) # check the nodes show for the", "checks] == ['service:foobar'] c.agent.service.deregister('foobar') time.sleep(40/1000.0) index, checks = c.health.checks('foobar') assert", "assert data is None assert c.kv.put('foo', 'bar') is True index,", "time.sleep(40/1000.0) assert c.agent.checks() == {} # Cleanup tasks c.agent.check.deregister('foo') time.sleep(40/1000.0)", "in sessions] == ['my-session'] # session.info pytest.raises( consul.ConsulException, c.session.info, session_id,", "== ['n1', 'n2'] # check n2's s1 service was removed", "the master token by default c = consul.Consul(port=acl_consul.port, token=acl_consul.token) master_token", "None) index, data = c.kv.get('foo') assert data['Value'] is None #", "consul.ACLPermissionDenied, c.kv.get, 'private/foo', token=token ) pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'private/foo', 'bar2',", "check c.agent.check.ttl_pass('service:foo:1') c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0) # both nodes are now available", "c.catalog.nodes, dc='dc2') _, nodes = c.catalog.nodes() nodes.remove(current) assert [x['Node'] for", "assert c.agent.check.register( 'script_check', Check.script('/bin/true', 10)) is True verify_and_dereg_check('script_check') assert c.agent.check.register(", "notes='all hunky dory!') # wait for ttl to expire time.sleep(120/1000.0)", "c.kv.get('foo') assert data['Flags'] == 0 assert c.kv.put('foo', 'bar', flags=50) is", "nodes] == [] def test_agent_checks_service_id(self, consul_port): c = consul.Consul(port=consul_port) c.agent.service.register('foo1')", "'foo', token=token) assert c.kv.get('private/foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c.kv.get, 'private/foo',", "def test_service_dereg_issue_156(self, consul_port): # https://github.com/cablehead/python-consul/issues/156 service_name = 'app#127.0.0.1#3000' c =", "[''] # register two nodes, one with a long ttl,", "_, services = c.catalog.services() assert services == {'s1': [u'master'], 's2':", "'script_check', Check.script('/bin/true', 10)) is True verify_and_dereg_check('script_check') assert c.agent.check.register( 'check name',", "# check both nodes are available index, nodes = c.health.state('passing')", "c.agent.services().items() if k == 'foo'][0] == '10.10.10.1' assert c.agent.service.deregister('foo') is", "c.acl.info(token)['Rules'] == rules token2 = c.acl.clone(token, token=master_token) assert c.acl.info(token2)['Rules'] ==", "master token by default c = consul.Consul(port=acl_consul.port, token=acl_consul.token) master_token =", "consul.Consul(port=consul_port) c.coordinate.nodes() c.coordinate.datacenters() assert set(c.coordinate.datacenters()[0].keys()) == \\ set(['Datacenter', 'Coordinates', 'AreaID'])", "acl_consul): c = consul.Consul(port=acl_consul.port) master_token = acl_consul.token acls = c.acl.list(token=master_token)", "index, data = c.kv.get('foo') assert data is None def test_acl_disabled(self,", "['n1', 'n2'] # test catalog.services pytest.raises(consul.ConsulException, c.catalog.services, dc='dc2') _, services", "six.b('3')] def test_kv_delete(self, consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo1', '1') c.kv.put('foo2',", "c.health.service(service_name) assert [node['Service']['ID'] for node in nodes] == [] def", "in checks] == ['foobar'] assert [check['CheckID'] for check in checks]", "notes: assert checks[check_id]['Output'] == notes # test setting notes on", "assert x['Status'] == 1 assert not x['Name'] is None assert", "def test_health_node(self, consul_port): c = consul.Consul(port=consul_port) # grab local node", "c.kv.put('foo', 'bar2', cas=data['ModifyIndex']) is True index, data = c.kv.get('foo') assert", "c = consul.Consul(port=consul_port) index, data = c.kv.get('foo/', recurse=True) assert data", "c.agent.service.deregister('foo') time.sleep(40/1000.0) def test_agent_node_maintenance(self, consul_port): c = consul.Consul(port=consul_port) c.agent.maintenance('true', \"test\")", "for node in nodes] != 'foo' # ping the two", "True index, data = c.kv.get('foo') assert c.kv.put('foo', 'bar2', cas=data['ModifyIndex']-1) is", "for x in sessions] == ['my-session'] # session.destroy pytest.raises( consul.ConsulException,", "= consul.Consul(port=consul_port) c.agent.service.register(service_name) time.sleep(80/1000.0) index, nodes = c.health.service(service_name) assert [node['Service']['ID']", "index, data = c.health.service('foo-1', token=token) assert data[0]['Service']['ID'] == \"foo-1\" index,", "data = c.kv.get('foo') assert struct.unpack('i', data['Value']) == (1000,) # test", "# assert response contains query ID assert 'ID' in query", "check in checks] == ['foobar'] assert [check['CheckID'] for check in", "is True assert c.catalog.register( 'n1', '10.1.10.11', service={'service': 's2'}) is True", "assert session['Behavior'] == 'delete' assert session['TTL'] == '20s' # trying", "grab the node our server created, so we can ignore", "service_id='foo1') time.sleep(40/1000.0) index, nodes = c.health.service('foo1') assert set([ check['ServiceID'] for", "acquire=s) is True index, data = c.kv.get('foo') assert data['Value'] ==", "= c.kv.get('foo') assert c.kv.put('foo', 'bar2', cas=data['ModifyIndex']-1) is False assert c.kv.put('foo',", "fails time.sleep(2200/1000.0) # only one node available index, nodes =", "node in nodes] == ['foo1'] c.agent.check.register('foo', Check.ttl('100ms'), service_id='foo1') time.sleep(40/1000.0) index,", "[] pytest.raises(consul.std.base.ConsulException, c.agent.check.register, 'foo', Check.ttl('100ms'), service_id='foo1') time.sleep(40/1000.0) assert c.agent.checks() ==", "and len(queries) == 1 assert queries[0]['Name'] == query_name \\ and", "c.health.service('foo1') assert [node['Service']['ID'] for node in nodes] == ['foo1'] c.agent.check.register('foo',", "[x['Name'] for x in sessions] == ['my-session'] # session.destroy pytest.raises(", "assert c.kv.put('bar', '4') is True assert c.kv.put('base/foo', '1') is True", "https://github.com/cablehead/python-consul/issues/156 service_name = 'app#127.0.0.1#3000' c = consul.Consul(port=consul_port) c.agent.service.register(service_name) time.sleep(80/1000.0) index,", "c.agent.checks()['check']['Notes'] == 'foo' c.agent.check.deregister('check') assert set(c.agent.checks().keys()) == set([]) assert c.agent.check.register(", "assert c.agent.check.ttl_pass('ttl_check') is True verify_check_status('ttl_check', 'passing') assert c.agent.check.ttl_pass( 'ttl_check', notes='all", "x in events] def test_agent_checks(self, consul_port): c = consul.Consul(port=consul_port) def", "assert c.agent.service.deregister('foo1') is True time.sleep(40/1000.0) def test_agent_register_check_no_service_id(self, consul_port): c =", "test_kv_recurse(self, consul_port): c = consul.Consul(port=consul_port) index, data = c.kv.get('foo/', recurse=True)", "'foo') pytest.raises(consul.ACLDisabled, c.acl.destroy, 'foo') def test_acl_permission_denied(self, acl_consul): c = consul.Consul(port=acl_consul.port)", "'my-session' # session.node node = session['Node'] pytest.raises( consul.ConsulException, c.session.node, node,", "passing their health check index, nodes = c.health.service('foo', passing=True) assert", "'foo/bar3'] assert [x['Value'] for x in data] == [ None,", "\"foo-1\" index, data = c.health.checks('foo-1', token=token) assert data == []", "dory!') is True verify_check_status('ttl_check', 'passing', notes='all hunky dory!') # wait", "c.health.service(service_name) assert [node['Service']['ID'] for node in nodes] == [service_name] #", "test_agent_self(self, consul_port): c = consul.Consul(port=consul_port) assert set(c.agent.self().keys()) == set(['Member', 'Stats',", "assert set(c.agent.services().keys()) == set(['foo']) assert c.agent.service.deregister('foo') is True assert set(c.agent.services().keys())", "assert c.catalog.deregister('n2', service_id='s1') is True # check the nodes weren't", "assert c.agent.check.register( 'http_check', Check.http(http_addr, '10ms')) is True time.sleep(1) verify_check_status('http_check', 'passing')", "\"foobody\") index, events = c.event.list(name=\"othername\") assert events == [] index,", "= c.kv.get('foo') assert data['Value'] == six.b('1') c.session.destroy(s) index, data =", "# trying out the behavior assert c.kv.put('foo', '1', acquire=s) is", "that tag works index, nodes = c.health.service('foo', tag='tag:foo:1') assert [node['Service']['ID']", "and query['ID'] is not None \\ and str(query['ID']) != ''", "not in checks_post.keys() def test_agent_members(self, consul_port): c = consul.Consul(port=consul_port) members", "= c.session.create() s2 = c.session.create() assert c.kv.put('foo', '1', acquire=s1) is", "# test token pass through for service registration pytest.raises( consul.ACLPermissionDenied,", "we can ignore it _, nodes = c.catalog.nodes() assert len(nodes)", "'delete' assert session['TTL'] == '20s' # trying out the behavior", "six.b('bar') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.get, 'private/foo') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.put, 'private/foo', 'bar2')", "= False for server in config[\"Servers\"]: if server[\"Leader\"]: leader =", "node['Checks']]) == set(['foo', 'serfHealth']) # Clean up tasks assert c.agent.check.deregister('foo')", "clean up assert c.agent.service.deregister('foo-1') is True c.acl.destroy(token, token=master_token) acls =", "c.acl.info(token2)['Rules'] == rules assert c.acl.update(token2, name='Foo') == token2 assert c.acl.info(token2)['Name']", "consul.ACLPermissionDenied, c.kv.put, 'private/foo', 'bar2', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'private/foo', token=token)", "session_id, dc='dc2') index, session = c.session.info('1'*36) assert session is None", "consul.Consul(port=consul_port) def verify_and_dereg_check(check_id): assert set(c.agent.checks().keys()) == set([check_id]) assert c.agent.check.deregister(check_id) is", "nodes.remove(current) assert [x['Node'] for x in nodes] == [] def", "= consul.Consul(port=consul_port) assert c.event.fire(\"fooname\", \"foobody\") index, events = c.event.list() assert", "c.query.explain(query_name)['Query'] # delete query assert c.query.delete(query['ID']) def test_coordinate(self, consul_port): c", "'tags': ['master']}) is True # test catalog.nodes pytest.raises(consul.ConsulException, c.catalog.nodes, dc='dc2')", "pytest.raises(consul.ConsulException, c.session.create, dc='dc2') session_id = c.session.create('my-session') # session.list pytest.raises(consul.ConsulException, c.session.list,", "== 'Foo' assert c.acl.destroy(token2, token=master_token) is True assert c.acl.info(token2) is", "is True assert c.acl.info(token2) is None c.kv.put('foo', 'bar') c.kv.put('private/foo', 'bar')", "retrieve query using id and name queries = c.query.get(query['ID']) assert", "True c.session.destroy(s1) c.session.destroy(s2) def test_kv_keys_only(self, consul_port): c = consul.Consul(port=consul_port) assert", "c.agent.service.maintenance('foo', 'false') time.sleep(40/1000.0) checks_post = c.agent.checks() assert '_service_maintenance:foo' not in", "[u'master'], 's2': [], 'consul': []} # test catalog.node pytest.raises(consul.ConsulException, c.catalog.node,", "pytest.raises(AssertionError, c.kv.put, 'foo', {1: 2}) def test_kv_put_cas(self, consul_port): c =", "x in events] def test_event_targeted(self, consul_port): c = consul.Consul(port=consul_port) assert", "their health check index, nodes = c.health.state('passing') assert [node['ServiceID'] for", "def test_status_leader(self, consul_port): c = consul.Consul(port=consul_port) agent_self = c.agent.self() leader", "'private/foo', token=token) # test token pass through for service registration", "c.health.checks('foobar') assert [check['ServiceID'] for check in checks] == ['foobar'] assert", "index, nodes = c.health.service('foo') assert nodes == [] def test_health_state(self,", "index, nodes = c.health.state('passing') assert set([node['ServiceID'] for node in nodes])", "assert c.event.fire(\"fooname\", \"foobody\") index, events = c.event.list() assert [x['Name'] ==", "checks_pre['_node_maintenance']['Notes'] c.agent.maintenance('false') time.sleep(40/1000.0) checks_post = c.agent.checks() assert '_node_maintenance' not in", "== rules assert c.acl.update(token2, name='Foo', token=master_token) == token2 assert c.acl.info(token2)['Name']", "leader = c.status.leader() addr_port = agent_self['Stats']['consul']['leader_addr'] assert leader == addr_port,", "expected value \" \\ \"was {1}\".format(leader, addr_port) def test_status_peers(self, consul_port):", "assert c.agent.service.register('foo') is True assert set(c.agent.services().keys()) == set(['foo']) assert c.agent.service.deregister('foo')", "[node['ServiceID'] for node in nodes] == [''] def test_health_node(self, consul_port):", "node, dc='dc2') _, sessions = c.session.node(node) assert [x['Name'] for x", "time.sleep(40/1000.0) # check the nodes show for the /health/state/any endpoint", "pytest.raises(consul.ConsulException, c.catalog.nodes, dc='dc2') _, nodes = c.catalog.nodes() nodes.remove(current) assert [x['Node']", "c.agent.checks() assert '_node_maintenance' in checks_pre.keys() assert 'test' == checks_pre['_node_maintenance']['Notes'] c.agent.maintenance('false')", "= c.health.service('foo') assert [node['Service']['ID'] for node in nodes] == ['foo:1',", "checks = c.agent.checks() assert checks[check_id]['Status'] == status if notes: assert", "master_token = acl_consul.token acls = c.acl.list() assert set([x['ID'] for x", "def test_agent_service_maintenance(self, consul_port): c = consul.Consul(port=consul_port) c.agent.service.register('foo', check=Check.ttl('100ms')) time.sleep(40/1000.0) c.agent.service.maintenance('foo',", "= consul.Consul(port=consul_port) def verify_and_dereg_check(check_id): assert set(c.agent.checks().keys()) == set([check_id]) assert c.agent.check.deregister(check_id)", "events] def test_event_targeted(self, consul_port): c = consul.Consul(port=consul_port) assert c.event.fire(\"fooname\", \"foobody\")", "assert services == {'s1': [u'master'], 's2': [], 'consul': []} #", "verify_check_status('http_check', 'passing') verify_and_dereg_check('http_check') assert c.agent.check.register( 'http_timeout_check', Check.http(http_addr, '100ms', timeout='2s')) is", "'foobody' for x in events] def test_agent_checks(self, consul_port): c =", "c.agent.service.deregister('foo:2') time.sleep(40/1000.0) index, nodes = c.health.state('any') assert [node['ServiceID'] for node", "c.agent.self() leader = c.status.leader() addr_port = agent_self['Stats']['consul']['leader_addr'] assert leader ==", "c.kv.put, 'foo', 'bar', acquire='foo') s1 = c.session.create() s2 = c.session.create()", "\"\"\" key \"\" { policy = \"read\" } key \"private/\"", "assert c.catalog.deregister('n2') is True _, nodes = c.catalog.nodes() nodes.remove(current) assert", "for the Serf Health Status check, which has an #", "} key \"private/\" { policy = \"deny\" } service \"foo-\"", "Check.ttl('100ms')) is True assert c.agent.check.ttl_warn('ttl_check') is True verify_check_status('ttl_check', 'warning') assert", "endpoint index, nodes = c.health.state('any') assert set([node['ServiceID'] for node in", "assert c.kv.get('foo', token=token)[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'foo', 'bar2',", "\"deny\" } service \"foo-\" { policy = \"write\" } service", "c.kv.put('foo/', None) index, data = c.kv.get('foo/', recurse=True) assert len(data) ==", "test_session_delete_ttl_renew(self, consul_port): c = consul.Consul(port=consul_port) s = c.session.create(behavior='delete', ttl=20) #", "query_name = 'fooquery' query = c.query.create(query_service, query_name) # assert response", "{'s1': [u'master'], 's2': [], 'consul': []} # test catalog.node pytest.raises(consul.ConsulException,", "in sessions] == ['my-session'] # session.destroy pytest.raises( consul.ConsulException, c.session.destroy, session_id,", "= consul.Consul(port=consul_port) config = c.operator.raft_config() assert config[\"Index\"] == 1 leader", "def test_agent_checks_service_id(self, consul_port): c = consul.Consul(port=consul_port) c.agent.service.register('foo1') time.sleep(40/1000.0) index, nodes", "c.kv.get('foo', index=index, wait='20ms') assert index == check def test_kv_encoding(self, consul_port):", "c = consul.Consul(port=consul_port) assert c.kv.put('bar', '4') is True assert c.kv.put('base/foo',", "['', 'foo:1', 'foo:2']) # deregister the nodes c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2') time.sleep(40/1000.0)", "nodes c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2') time.sleep(40/1000.0) index, nodes = c.health.state('any') assert [node['ServiceID']", "not None \\ and str(query['ID']) != '' # retrieve query", "wait for ttl to expire time.sleep(120/1000.0) verify_check_status('ttl_check', 'critical') verify_and_dereg_check('ttl_check') def", "'1') c.kv.put('foo2', '2') c.kv.put('foo3', '3') index, data = c.kv.get('foo', recurse=True)", "Serf Health Status check, which has an # empty ServiceID", "== [] def test_session_delete_ttl_renew(self, consul_port): c = consul.Consul(port=consul_port) s =", "assert c.agent.check.deregister('foo') is True time.sleep(40/1000.0) assert c.agent.service.deregister('foo1') is True time.sleep(40/1000.0)", "'foo:2'] # but that they aren't passing their health check", "c = consul.Consul(port=consul_port) agent_self = c.agent.self() leader = c.status.leader() addr_port", "c.agent.check.register('ttl_check', Check.ttl('100ms')) is True assert c.agent.check.ttl_warn('ttl_check') is True verify_check_status('ttl_check', 'warning')", "= consul.Consul(port=consul_port) assert c.kv.put('foo', 'bar', cas=50) is False assert c.kv.put('foo',", "== six.b('bar') # test empty-string comes back as `None` c.kv.put('foo',", "pytest.raises(consul.std.base.ConsulException, c.agent.check.register, 'foo', Check.ttl('100ms'), service_id='foo1') time.sleep(40/1000.0) assert c.agent.checks() == {}", "c = consul.Consul(port=consul_port) assert set(c.agent.self().keys()) == set(['Member', 'Stats', 'Config', 'Coord',", "c.kv.get('foo/', recurse=True) assert [x['Key'] for x in data] == [", "assert '_service_maintenance:foo' in checks_pre.keys() assert 'test' == checks_pre['_service_maintenance:foo']['Notes'] c.agent.service.maintenance('foo', 'false')", "c.kv.get('foo/', recurse=True) assert data is None c.kv.put('foo/', None) index, data", "= c.kv.get('foo') assert struct.unpack('i', data['Value']) == (1000,) # test unicode", "assert set(c.agent.checks().keys()) == set([]) assert c.agent.check.register( 'script_check', Check.script('/bin/true', 10)) is", "[check['ServiceID'] for check in checks] == ['foobar'] assert [check['CheckID'] for", "data] == [ None, six.b('1'), six.b('2'), six.b('3')] def test_kv_delete(self, consul_port):", "nodes] == ['foo1'] c.agent.check.register('foo', Check.ttl('100ms'), service_id='foo1') time.sleep(40/1000.0) index, nodes =", "query_service = 'foo' query_name = 'fooquery' query = c.query.create(query_service, query_name)", "[''] def test_health_node(self, consul_port): c = consul.Consul(port=consul_port) # grab local", "'foo2', 'foo3'] assert c.kv.delete('foo2') is True index, data = c.kv.get('foo',", "nodes == [] # register two nodes, one with a", "boink!') assert c.agent.check.ttl_pass('ttl_check') is True verify_check_status('ttl_check', 'passing') assert c.agent.check.ttl_pass( 'ttl_check',", "set(c.coordinate.datacenters()[0].keys()) == \\ set(['Datacenter', 'Coordinates', 'AreaID']) def test_operator(self, consul_port): c", "consul_port): c = consul.Consul(port=consul_port) index, data = c.kv.get('foo/', recurse=True) assert", "= c.acl.list() assert set([x['ID'] for x in acls]) == \\", "consul_port): c = consul.Consul(port=consul_port) pytest.raises( consul.ConsulException, c.kv.put, 'foo', 'bar', acquire='foo')", "pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'private/foo', token=token) # clean up c.acl.destroy(token) acls", "c.event.list() assert [x['Name'] == 'fooname' for x in events] assert", "s1 = c.session.create() s2 = c.session.create() assert c.kv.put('foo', '1', acquire=s1)", "for node in nodes for check in node['Checks']]) == set(['foo1',", "x['Name'] def test_agent_self(self, consul_port): c = consul.Consul(port=consul_port) assert set(c.agent.self().keys()) ==", "is True # test catalog.nodes pytest.raises(consul.ConsulException, c.catalog.nodes, dc='dc2') _, nodes", "c.session.info(session_id) assert session['Name'] == 'my-session' # session.node node = session['Node']", "[] def test_health_state(self, consul_port): c = consul.Consul(port=consul_port) # The empty", "data is None assert c.kv.put('foo', 'bar') is True index, data", "id and name queries = c.query.get(query['ID']) assert queries != []", "index, nodes = c.health.state('any') assert [node['ServiceID'] for node in nodes]", "x in nodes] == ['n1', 'n2'] # check n2's s1", "_, nodes = c.catalog.nodes() assert len(nodes) == 1 current =", "== {} # Cleanup tasks c.agent.check.deregister('foo') time.sleep(40/1000.0) def test_agent_register_enable_tag_override(self, consul_port):", "index, data = c.kv.get('foo/', recurse=True) assert data is None c.kv.put('foo/',", "= consul.Consul(port=consul_port) c.coordinate.nodes() c.coordinate.datacenters() assert set(c.coordinate.datacenters()[0].keys()) == \\ set(['Datacenter', 'Coordinates',", "cas=0) is True index, data = c.kv.get('foo') assert c.kv.put('foo', 'bar2',", "that they aren't passing their health check index, nodes =", "= consul.Consul(port=consul_port) # test binary c.kv.put('foo', struct.pack('i', 1000)) index, data", "consul.Consul(port=acl_consul.port) master_token = acl_consul.token acls = c.acl.list(token=master_token) assert set([x['ID'] for", "c.acl.info(token2)['Name'] == 'Foo' assert c.acl.destroy(token2, token=master_token) is True assert c.acl.info(token2)", "shorter c.agent.service.register( 'foo', service_id='foo:1', check=Check.ttl('10s'), tags=['tag:foo:1']) c.agent.service.register( 'foo', service_id='foo:2', check=Check.ttl('100ms'))", "test_kv_encoding(self, consul_port): c = consul.Consul(port=consul_port) # test binary c.kv.put('foo', struct.pack('i',", "out the behavior assert c.kv.put('foo', '1', acquire=s) is True index,", "policy = \"deny\" } \"\"\" token = c.acl.create(rules=rules) assert c.acl.info(token)['Rules']", "index, data = c.kv.get('foo/', recurse=True) assert [x['Key'] for x in", "import operator import struct import time import pytest import six", "assert c.kv.get('foo') == (index, data) assert c.kv.delete('foo', cas=data['ModifyIndex']) is True", "= c.catalog.services() assert services == {'s1': [u'master'], 's2': [], 'consul':", "for node in nodes] == ['foo:1'] # deregister the nodes", "consul.Consul(port=consul_port) # session.create pytest.raises(consul.ConsulException, c.session.create, node='n2') pytest.raises(consul.ConsulException, c.session.create, dc='dc2') session_id", "session['TTL'] == '20s' # trying out the behavior assert c.kv.put('foo',", "pytest.raises( consul.ACLPermissionDenied, c.kv.get, 'private/foo', token=token ) pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'private/foo',", "consul.Consul(port=consul_port) c.kv.put('foo', 'bar') index, data = c.kv.get('foo') assert data['Flags'] ==", "in acls]) == \\ set(['anonymous', master_token]) assert c.acl.info('1'*36) is None", "consul.Consul(port=consul_port) c.agent.maintenance('true', \"test\") time.sleep(40/1000.0) checks_pre = c.agent.checks() assert '_node_maintenance' in", "= consul.Consul(port=consul_port) assert c.event.fire(\"fooname\", \"foobody\") index, events = c.event.list(name=\"othername\") assert", "assert c.agent.service.deregister(service_name) is True time.sleep(40/1000.0) index, nodes = c.health.service(service_name) assert", "= c.session.list() assert [x['Name'] for x in sessions] == ['my-session']", "c.agent.members(wan=True) for x in wan_members: assert 'dc1' in x['Name'] def", "[service_name] # Clean up tasks assert c.agent.service.deregister(service_name) is True time.sleep(40/1000.0)", "checks] def test_health_checks(self, consul_port): c = consul.Consul(port=consul_port) c.agent.service.register( 'foobar', service_id='foobar',", "'bar') is True index, data = c.kv.get('foo') check, data =", "pytest.raises( consul.ACLPermissionDenied, c_limited.kv.put, 'foo', 'bar2') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.delete, 'foo') assert", "in x['Name'] def test_agent_self(self, consul_port): c = consul.Consul(port=consul_port) assert set(c.agent.self().keys())", "in nodes for check in node['Checks']]) == set(['foo1', '']) assert", "nodes for check in node['Checks']]) == set(['foo1', '']) assert set([", "recurse=True) assert [x['Key'] for x in data] == [ 'foo/',", "def test_kv_put_cas(self, consul_port): c = consul.Consul(port=consul_port) assert c.kv.put('foo', 'bar', cas=50)", "# configure client to use the master token by default", "test_event_targeted(self, consul_port): c = consul.Consul(port=consul_port) assert c.event.fire(\"fooname\", \"foobody\") index, events", "value = base64.b64encode(b\"1\").decode(\"utf8\") d = {\"KV\": {\"Verb\": \"set\", \"Key\": \"asdf\",", "leader = False voter = False for server in config[\"Servers\"]:", "True assert c.kv.put('base/base/foo', '5') is True index, data = c.kv.get('base/',", "assert nodes == [] c.agent.service.register('foo', enable_tag_override=True) assert c.agent.services()['foo']['EnableTagOverride'] # Cleanup", "set( ['', 'foo:1', 'foo:2']) # but that they aren't passing", "test_kv_delete_cas(self, consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo', 'bar') index, data =", "assert c.agent.check.ttl_warn('ttl_check') is True verify_check_status('ttl_check', 'warning') assert c.agent.check.ttl_warn( 'ttl_check', notes='its", "is True verify_check_status( 'ttl_check', 'critical', notes='something went boink!') assert c.agent.check.ttl_pass('ttl_check')", "c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0) # check both nodes are available index, nodes", "True _, sessions = c.session.list() assert sessions == [] def", "assert c.agent.check.ttl_warn( 'ttl_check', notes='its not quite right') is True verify_check_status('ttl_check',", "# test empty-string comes back as `None` c.kv.put('foo', '') index,", "= consul.Consul(port=consul_port) # The empty string is for the Serf", "for node in nodes for check in node['Checks']]) == set(['foo',", "c.agent.check.ttl_warn('ttl_check') is True verify_check_status('ttl_check', 'warning') assert c.agent.check.ttl_warn( 'ttl_check', notes='its not", "1}) == \\ 'http://127.0.0.1:8500/v1/kv?index=1' class TestConsul(object): def test_kv(self, consul_port): c", "data = c.kv.get('foo') assert data is None assert c.kv.put('foo', 'bar')", "node in nodes]) == set( ['', 'foo:1']) # ping the", "peer list but it was not present\".format(addr_port) def test_query(self, consul_port):", "node in nodes] == [service_name] # Clean up tasks assert", "assert [check['ServiceID'] for check in checks] == ['foobar'] assert [check['CheckID']", "was {0}, expected value \" \\ \"was {1}\".format(leader, addr_port) def", "'1'*36) session = c.session.renew(s) assert session['Behavior'] == 'delete' assert session['TTL']", "c.agent.check.ttl_fail('ttl_check') is True verify_check_status('ttl_check', 'critical') assert c.agent.check.ttl_fail( 'ttl_check', notes='something went", "consul.Consul(port=acl_consul.port, token=acl_consul.token) master_token = acl_consul.token acls = c.acl.list() assert set([x['ID']", "{} # Cleanup tasks c.agent.check.deregister('foo') time.sleep(40/1000.0) def test_agent_register_enable_tag_override(self, consul_port): c", "c.catalog.deregister('n2') is True _, nodes = c.catalog.nodes() nodes.remove(current) assert [x['Node']", "== six.b('bar') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.get, 'private/foo') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.put, 'private/foo',", "test_kv_keys_only(self, consul_port): c = consul.Consul(port=consul_port) assert c.kv.put('bar', '4') is True", "'1', acquire=s) is True index, data = c.kv.get('foo') assert data['Value']", "token=master_token) is True assert c.acl.info(token2) is None c.kv.put('foo', 'bar') c.kv.put('private/foo',", "'base/foo'] def test_transaction(self, consul_port): c = consul.Consul(port=consul_port) value = base64.b64encode(b\"1\").decode(\"utf8\")", "ping the failed node's health check c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0) # check", "c.kv.put('foo', '1', acquire=s) is True index, data = c.kv.get('foo') assert", "set([check_id]) assert c.agent.check.deregister(check_id) is True assert set(c.agent.checks().keys()) == set([]) def", "nodes[0] # test catalog.datacenters assert c.catalog.datacenters() == ['dc1'] # test", "c.acl.create(rules=rules) assert c.acl.info(token)['Rules'] == rules token2 = c.acl.clone(token) assert c.acl.info(token2)['Rules']", "c.status.peers() assert addr_port in peers, \\ \"Expected value '{0}' \"", "is True assert c.agent.check.ttl_warn('ttl_check') is True verify_check_status('ttl_check', 'warning') assert c.agent.check.ttl_warn(", "= consul.Consul(port=consul_port) value = base64.b64encode(b\"1\").decode(\"utf8\") d = {\"KV\": {\"Verb\": \"set\",", "== \\ set(['Datacenter', 'Coordinates', 'AreaID']) def test_operator(self, consul_port): c =", "c.kv.put('foo', struct.pack('i', 1000)) index, data = c.kv.get('foo') assert struct.unpack('i', data['Value'])", "sessions == [] def test_session_delete_ttl_renew(self, consul_port): c = consul.Consul(port=consul_port) s", "in nodes] == ['n1', 'n2'] # test catalog.services pytest.raises(consul.ConsulException, c.catalog.services,", "c.health.service('foo') assert nodes == [] def test_health_state(self, consul_port): c =", "# test catalog.node pytest.raises(consul.ConsulException, c.catalog.node, 'n1', dc='dc2') _, node =", "== query['ID'] # explain query assert c.query.explain(query_name)['Query'] # delete query", "consul.ACLPermissionDenied, c.kv.put, 'foo', 'bar2', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'foo', token=token)", "= c.acl.create(rules=rules) assert c.acl.info(token)['Rules'] == rules token2 = c.acl.clone(token) assert", "c.kv.put('foo', '') index, data = c.kv.get('foo') assert data['Value'] is None", "for node in nodes] == [''] # register two nodes,", "agent_self['Stats']['consul']['leader_addr'] peers = c.status.peers() assert addr_port in peers, \\ \"Expected", "'n1', '10.1.10.11', service={'service': 's2'}) is True assert c.catalog.register( 'n2', '10.1.10.12',", "'s2'}) is True assert c.catalog.register( 'n2', '10.1.10.12', service={'service': 's1', 'tags':", "in query \\ and query['ID'] is not None \\ and", "= \"http://127.0.0.1:{0}\".format(consul_port) assert c.agent.check.register( 'http_check', Check.http(http_addr, '10ms')) is True time.sleep(1)", "[x['Node'] for x in nodes] == ['n1', 'n2'] # test", "r[\"Errors\"] is None d = {\"KV\": {\"Verb\": \"get\", \"Key\": \"asdf\"}}", "if server[\"Leader\"]: leader = True if server[\"Voter\"]: voter = True", "configure client to use the master token by default c", "`None` c.kv.put('foo', '') index, data = c.kv.get('foo') assert data['Value'] is", "was removed though _, nodes = c.catalog.service('s1') assert set([x['Node'] for", "assert data['Value'] is None # test None c.kv.put('foo', None) index,", "x in events] assert [x['Payload'] == 'foobody' for x in", "c.catalog.nodes() nodes.remove(current) assert [x['Node'] for x in nodes] == []", "pytest import six import consul import consul.std Check = consul.Check", "consul_port): c = consul.Consul(port=consul_port) agent_self = c.agent.self() addr_port = agent_self['Stats']['consul']['leader_addr']", "k == 'foo'][0] == '10.10.10.1' assert c.agent.service.deregister('foo') is True def", "'foo') def test_acl_permission_denied(self, acl_consul): c = consul.Consul(port=acl_consul.port) pytest.raises(consul.ACLPermissionDenied, c.acl.list) pytest.raises(consul.ACLPermissionDenied,", "leader == addr_port, \\ \"Leader value was {0}, expected value", "token=token) c.agent.service.register(\"foo-1\", token=token) index, data = c.health.service('foo-1', token=token) assert data[0]['Service']['ID']", "are now available index, nodes = c.health.service('foo', passing=True) assert [node['Service']['ID']", "catalog.node pytest.raises(consul.ConsulException, c.catalog.node, 'n1', dc='dc2') _, node = c.catalog.node('n1') assert", "[c.acl.info(master_token), c.acl.info('anonymous')] compare.sort(key=operator.itemgetter('ID')) assert acls == compare rules = \"\"\"", "assert c.kv.put('foo', 'bar2', cas=data['ModifyIndex']) is True index, data = c.kv.get('foo')", "default token pytest.raises( consul.ACLPermissionDenied, c.kv.get, 'private/foo', token=token ) pytest.raises( consul.ACLPermissionDenied,", "verify_check_status('ttl_check', 'passing') assert c.agent.check.ttl_pass( 'ttl_check', notes='all hunky dory!') is True", "assert c.agent.service.register('foo', address='10.10.10.1') is True assert [ v['Address'] for k,", "value '{0}' \" \\ \"in peer list but it was", "assert set(c.coordinate.datacenters()[0].keys()) == \\ set(['Datacenter', 'Coordinates', 'AreaID']) def test_operator(self, consul_port):", "assert c.agent.service.deregister('foo-1') is True c.acl.destroy(token, token=master_token) acls = c.acl.list(token=master_token) assert", "consul_port): c = consul.Consul(port=consul_port) def verify_and_dereg_check(check_id): assert set(c.agent.checks().keys()) == set([check_id])", "consul.ACLPermissionDenied, c.kv.get, 'private/foo', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'private/foo', 'bar2', token=token)", "True verify_check_status('ttl_check', 'warning', 'its not quite right') assert c.agent.check.ttl_fail('ttl_check') is", "c.kv.put('foo', '1', acquire=s1) is True assert c.kv.put('foo', '2', acquire=s2) is", "time.sleep(120/1000.0) # only one node available index, nodes = c.health.service('foo',", "contains query ID assert 'ID' in query \\ and query['ID']", "on a check c.agent.check.register('check', Check.ttl('1s'), notes='foo') assert c.agent.checks()['check']['Notes'] == 'foo'", "hunky dory!') is True verify_check_status('ttl_check', 'passing', notes='all hunky dory!') #", "= consul.Check class TestHTTPClient(object): def test_uri(self): http = consul.std.HTTPClient() assert", "False assert c.kv.put('foo', '2', release=s1) is True c.session.destroy(s1) c.session.destroy(s2) def", "time import pytest import six import consul import consul.std Check", "is True time.sleep(1) verify_check_status('http_check', 'passing') verify_and_dereg_check('http_check') assert c.agent.check.register( 'http_timeout_check', Check.http(http_addr,", "c = consul.Consul(port=consul_port) c.agent.service.register(service_name) time.sleep(80/1000.0) index, nodes = c.health.service(service_name) assert", "service={'service': 's2'}) is True assert c.catalog.register( 'n2', '10.1.10.12', service={'service': 's1',", "'foo' # ping the two node's health check c.agent.check.ttl_pass('service:foo:1') c.agent.check.ttl_pass('service:foo:2')", "for check in checks] == ['foobar'] assert [check['CheckID'] for check", "= c.session.create(behavior='delete', ttl=20) # attempt to renew an unknown session", "consul_port): c = consul.Consul(port=consul_port) index, nodes = c.health.service(\"foo1\") assert nodes", "'bar2', cas=data['ModifyIndex']) is True index, data = c.kv.get('foo') assert data['Value']", "s = c.session.create(behavior='delete', ttl=20) # attempt to renew an unknown", "data = c.kv.get('foo', recurse=True) assert data is None def test_kv_delete_cas(self,", "acquire=s1) is True assert c.kv.put('foo', '2', acquire=s2) is False assert", "c.catalog.nodes() nodes.remove(current) assert [x['Node'] for x in nodes] == ['n1',", "c.kv.put('foo1', '1') c.kv.put('foo2', '2') c.kv.put('foo3', '3') index, data = c.kv.get('foo',", "= c.operator.raft_config() assert config[\"Index\"] == 1 leader = False voter", "service_name = 'app#127.0.0.1#3000' c = consul.Consul(port=consul_port) c.agent.service.register(service_name) time.sleep(80/1000.0) index, nodes", "c.health.service(\"foo1\") assert nodes == [] c.agent.service.register('foo', enable_tag_override=True) assert c.agent.services()['foo']['EnableTagOverride'] #", "consul.Consul(port=consul_port) assert c.kv.put('foo', 'bar') is True index, data = c.kv.get('foo')", "== ['foo:1'] # deregister the nodes c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2') time.sleep(40/1000.0) index,", "assert r[\"Results\"][0][\"KV\"][\"Value\"] == value def test_event(self, consul_port): c = consul.Consul(port=consul_port)", "[node['Service']['ID'] for node in nodes] == ['foo:1', 'foo:2'] # but", "c.acl.info('1'*36) is None compare = [c.acl.info(master_token), c.acl.info('anonymous')] compare.sort(key=operator.itemgetter('ID')) assert acls", "wait until the short ttl node fails time.sleep(120/1000.0) # only", "check the nodes show for the /health/service endpoint index, nodes", "ttl node fails time.sleep(120/1000.0) # only one node available index,", "= c.health.service(service_name) assert [node['Service']['ID'] for node in nodes] == [service_name]", "assert [x['Value'] for x in data] == [ None, six.b('1'),", "None assert not x['Tags'] is None assert c.agent.self()['Member'] in members", "c.session.renew, '1'*36) session = c.session.renew(s) assert session['Behavior'] == 'delete' assert", "is True assert c.catalog.deregister('n2') is True _, nodes = c.catalog.nodes()", "'foo:2'] # wait until the short ttl node fails time.sleep(120/1000.0)", "the node our server created, so we can ignore it", "c.coordinate.nodes() c.coordinate.datacenters() assert set(c.coordinate.datacenters()[0].keys()) == \\ set(['Datacenter', 'Coordinates', 'AreaID']) def", "pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'foo', token=token) assert c.kv.get('private/foo')[1]['Value'] == six.b('bar') pytest.raises(", "x in data] == ['foo1', 'foo2', 'foo3'] assert c.kv.delete('foo2') is", "c.session.destroy(s2) def test_kv_keys_only(self, consul_port): c = consul.Consul(port=consul_port) assert c.kv.put('bar', '4')", "checks_pre = c.agent.checks() assert '_service_maintenance:foo' in checks_pre.keys() assert 'test' ==", "True assert c.kv.put('foo', '2', acquire=s2) is False assert c.kv.put('foo', '1',", "test catalog.node pytest.raises(consul.ConsulException, c.catalog.node, 'n1', dc='dc2') _, node = c.catalog.node('n1')", "token=token)[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'foo', 'bar2', token=token) pytest.raises(", "def test_kv_put_flags(self, consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo', 'bar') index, data", "[x['Key'] for x in data] == ['foo1', 'foo3'] assert c.kv.delete('foo',", "acls]) == \\ set(['anonymous', master_token]) def test_status_leader(self, consul_port): c =", "acl_consul): c = consul.Consul(port=acl_consul.port) pytest.raises(consul.ACLPermissionDenied, c.acl.list) pytest.raises(consul.ACLPermissionDenied, c.acl.create) pytest.raises(consul.ACLPermissionDenied, c.acl.update,", "set([x['ID'] for x in acls]) == \\ set(['anonymous', master_token]) assert", "['foobar'] assert [check['CheckID'] for check in checks] == ['service:foobar'] c.agent.service.deregister('foobar')", "assert session is None index, session = c.session.info(session_id) assert session['Name']", "'foobody' for x in events] def test_event_targeted(self, consul_port): c =", "for check in checks] def test_health_checks(self, consul_port): c = consul.Consul(port=consul_port)", "acl_consul): # configure client to use the master token by", "_, node = c.catalog.node('n3') assert node is None # test", "_, sessions = c.session.list() assert sessions == [] def test_session_delete_ttl_renew(self,", "token = c.acl.create(rules=rules) assert c.acl.info(token)['Rules'] == rules token2 = c.acl.clone(token)", "= c.kv.get('foo', recurse=True) assert data is None def test_kv_delete_cas(self, consul_port):", "service={'service': 's1'}, check={'name': 'c1'}) is True assert c.catalog.register( 'n1', '10.1.10.11',", "pytest.raises(consul.ACLPermissionDenied, c.acl.update, 'anonymous') pytest.raises(consul.ACLPermissionDenied, c.acl.clone, 'anonymous') pytest.raises(consul.ACLPermissionDenied, c.acl.destroy, 'anonymous') def", "assert checks[check_id]['Output'] == notes # test setting notes on a", "node in nodes]) == set( ['', 'foo:1', 'foo:2']) # but", "verify_check_status(check_id, status, notes=None): checks = c.agent.checks() assert checks[check_id]['Status'] == status", "True verify_check_status( 'ttl_check', 'critical', notes='something went boink!') assert c.agent.check.ttl_pass('ttl_check') is", "consul.Consul(port=consul_port) assert set(c.agent.self().keys()) == set(['Member', 'Stats', 'Config', 'Coord', 'DebugConfig', 'Meta'])", "for node in nodes] == ['foo:1', 'foo:2'] # but that", "len(checks) == 0 def test_session(self, consul_port): c = consul.Consul(port=consul_port) #", "1000)) index, data = c.kv.get('foo') assert struct.unpack('i', data['Value']) == (1000,)", "= c.kv.get('foo/', recurse=True) assert [x['Key'] for x in data] ==", "c.kv.get, 'private/foo', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'private/foo', 'bar2', token=token) pytest.raises(", "in config[\"Servers\"]: if server[\"Leader\"]: leader = True if server[\"Voter\"]: voter", "in nodes]) == set( ['', 'foo:1', 'foo:2']) # deregister the", "addr_port, \\ \"Leader value was {0}, expected value \" \\", "nodes == [] # ping the two node's health check", "[x['Node'] for x in nodes] == ['n1', 'n2'] # check", "clean up c.acl.destroy(token) acls = c.acl.list() assert set([x['ID'] for x", "'10.1.10.11', dc='dc2') assert c.catalog.register( 'n1', '10.1.10.11', service={'service': 's1'}, check={'name': 'c1'})", "ttl node fails time.sleep(2200/1000.0) # only one node available index,", "in nodes] == ['foo:1', 'foo:2'] # wait until the short", "struct.unpack('i', data['Value']) == (1000,) # test unicode c.kv.put('foo', u'bar') index,", "empty ServiceID index, nodes = c.health.state('any') assert [node['ServiceID'] for node", "c.agent.service.deregister('foo-1') is True c.acl.destroy(token, token=master_token) acls = c.acl.list(token=master_token) assert set([x['ID']", "def test_acl_implicit_token_use(self, acl_consul): # configure client to use the master", "c.acl.info(token2) is None c.kv.put('foo', 'bar') c.kv.put('private/foo', 'bar') c_limited = consul.Consul(port=acl_consul.port,", "'private/foo') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.put, 'private/foo', 'bar2') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.delete, 'private/foo')", "c.agent.checks() assert checks[check_id]['Status'] == status if notes: assert checks[check_id]['Output'] ==", "{1}\".format(leader, addr_port) def test_status_peers(self, consul_port): c = consul.Consul(port=consul_port) agent_self =", "x['Tags'] is None assert c.agent.self()['Member'] in members wan_members = c.agent.members(wan=True)", "['foo1', 'foo3'] assert c.kv.delete('foo', recurse=True) is True index, data =", "c.kv.get('base/', keys=True, separator='/') assert data == ['base/base/', 'base/foo'] def test_transaction(self,", "set(['foo']) assert c.agent.service.deregister('foo') is True assert set(c.agent.services().keys()) == set() #", "index, events = c.event.list(name=\"othername\") assert events == [] index, events", "addr_port) def test_status_peers(self, consul_port): c = consul.Consul(port=consul_port) agent_self = c.agent.self()", "is True assert set(c.agent.checks().keys()) == set([]) def verify_check_status(check_id, status, notes=None):", "'bar2', cas=data['ModifyIndex']-1) is False assert c.kv.put('foo', 'bar2', cas=data['ModifyIndex']) is True", "test catalog.register pytest.raises( consul.ConsulException, c.catalog.register, 'foo', '10.1.10.11', dc='dc2') assert c.catalog.register(", "time.sleep(40/1000.0) index, nodes = c.health.service('foo1') assert set([ check['ServiceID'] for node", "'ttl_check', notes='its not quite right') is True verify_check_status('ttl_check', 'warning', 'its", "query using id and name queries = c.query.get(query['ID']) assert queries", "assert c.acl.info(token)['Rules'] == rules token2 = c.acl.clone(token, token=master_token) assert c.acl.info(token2)['Rules']", "a long ttl, the other shorter c.agent.service.register( 'foo', service_id='foo:1', check=Check.ttl('10s'),", "c.kv.put('base/base/foo', '5') is True index, data = c.kv.get('base/', keys=True, separator='/')", "they aren't passing their health check index, nodes = c.health.service('foo',", "for the /health/state/any endpoint index, nodes = c.health.state('any') assert set([node['ServiceID']", "session['Name'] == 'my-session' # session.node node = session['Node'] pytest.raises( consul.ConsulException,", "one node available index, nodes = c.health.state('passing') assert set([node['ServiceID'] for", "c.kv.delete('foo', cas=data['ModifyIndex']) is True index, data = c.kv.get('foo') assert data", "check['ServiceID'] for node in nodes for check in node['Checks']]) ==", "== set() # test address param assert c.agent.service.register('foo', address='10.10.10.1') is", "c.catalog.deregister('n1') is True assert c.catalog.deregister('n2') is True _, nodes =", "index, nodes = c.health.state('passing') assert [node['ServiceID'] for node in nodes]", "['foo:1'] # ping the failed node's health check c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0)", "def test_agent_members(self, consul_port): c = consul.Consul(port=consul_port) members = c.agent.members() for", "== '20s' # trying out the behavior assert c.kv.put('foo', '1',", "node's health check c.agent.check.ttl_pass('service:foo:1') c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0) # both nodes are", "assert c.catalog.register( 'n1', '10.1.10.11', service={'service': 's2'}) is True assert c.catalog.register(", "assert data['Flags'] == 0 assert c.kv.put('foo', 'bar', flags=50) is True", "\"write\" } service \"bar-\" { policy = \"read\" } \"\"\"", "'bar') index, data = c.kv.get('foo') assert data['Flags'] == 0 assert", "'private/foo', token=token) # clean up c.acl.destroy(token) acls = c.acl.list() assert", "node fails time.sleep(2200/1000.0) # only one node available index, nodes", "now available index, nodes = c.health.service('foo', passing=True) assert [node['Service']['ID'] for", "\"bar-1\", token=token) c.agent.service.register(\"foo-1\", token=token) index, data = c.health.service('foo-1', token=token) assert", "_, node = c.catalog.node('n1') assert set(node['Services'].keys()) == set(['s1', 's2']) _,", "for x in data] == ['foo1', 'foo3'] assert c.kv.delete('foo', recurse=True)", "assert c.event.fire(\"fooname\", \"foobody\") index, events = c.event.list(name=\"othername\") assert events ==", "nodes for check in node['Checks']]) == set(['foo', 'serfHealth']) # Clean", "assert data == ['base/base/', 'base/foo'] def test_transaction(self, consul_port): c =", "c.acl.clone(token, token=master_token) assert c.acl.info(token2)['Rules'] == rules assert c.acl.update(token2, name='Foo', token=master_token)", "# wait until the short ttl node fails time.sleep(2200/1000.0) #", "c.health.service('foo', passing=True) assert nodes == [] # ping the two", "until the short ttl node fails time.sleep(120/1000.0) # only one", "\\ set(['Datacenter', 'Coordinates', 'AreaID']) def test_operator(self, consul_port): c = consul.Consul(port=consul_port)", "\"read\" } \"\"\" token = c.acl.create(rules=rules, token=master_token) assert c.acl.info(token)['Rules'] ==", "c.agent.service.register('foo', address='10.10.10.1') is True assert [ v['Address'] for k, v", "'10.10.10.1' assert c.agent.service.deregister('foo') is True def test_catalog(self, consul_port): c =", "= consul.std.HTTPClient() assert http.uri('/v1/kv') == 'http://127.0.0.1:8500/v1/kv' assert http.uri('/v1/kv', params={'index': 1})", "'foo/bar2', 'foo/bar3'] assert [x['Value'] for x in data] == [", "True time.sleep(40/1000.0) def test_agent_register_check_no_service_id(self, consul_port): c = consul.Consul(port=consul_port) index, nodes", "checks_pre.keys() assert 'test' == checks_pre['_service_maintenance:foo']['Notes'] c.agent.service.maintenance('foo', 'false') time.sleep(40/1000.0) checks_post =", "nodes = c.health.state('passing') assert set([node['ServiceID'] for node in nodes]) ==", "ttl to expire time.sleep(120/1000.0) verify_check_status('ttl_check', 'critical') verify_and_dereg_check('ttl_check') def test_service_dereg_issue_156(self, consul_port):", "'foo') pytest.raises(consul.ACLDisabled, c.acl.clone, 'foo') pytest.raises(consul.ACLDisabled, c.acl.destroy, 'foo') def test_acl_permission_denied(self, acl_consul):", "= consul.Consul(port=consul_port) assert set(c.agent.self().keys()) == set(['Member', 'Stats', 'Config', 'Coord', 'DebugConfig',", "assert set(c.agent.self().keys()) == set(['Member', 'Stats', 'Config', 'Coord', 'DebugConfig', 'Meta']) def", "'3') index, data = c.kv.get('foo', recurse=True) assert [x['Key'] for x", "wait until the short ttl node fails time.sleep(2200/1000.0) # only", "c.agent.self() addr_port = agent_self['Stats']['consul']['leader_addr'] peers = c.status.peers() assert addr_port in", "in [check[\"Node\"] for check in checks] def test_health_checks(self, consul_port): c", "is True verify_and_dereg_check('check_id') http_addr = \"http://127.0.0.1:{0}\".format(consul_port) assert c.agent.check.register( 'http_check', Check.http(http_addr,", "c.kv.delete('foo', cas=data['ModifyIndex']-1) is False assert c.kv.get('foo') == (index, data) assert", "service was removed though _, nodes = c.catalog.service('s1') assert set([x['Node']", "data # clean up assert c.agent.service.deregister('foo-1') is True c.acl.destroy(token, token=master_token)", "# check both nodes are available index, nodes = c.health.service('foo',", "[ 'foo/', 'foo/bar1', 'foo/bar2', 'foo/bar3'] assert [x['Value'] for x in", "== 'Foo' assert c.acl.destroy(token2) is True assert c.acl.info(token2) is None", "None d = {\"KV\": {\"Verb\": \"get\", \"Key\": \"asdf\"}} r =", "for node in nodes] == [] def test_agent_checks_service_id(self, consul_port): c", "== ['foo1', 'foo3'] assert c.kv.delete('foo', recurse=True) is True index, data", "set(['foo', 'serfHealth']) # Clean up tasks assert c.agent.check.deregister('foo') is True", "up tasks assert c.agent.service.deregister(service_name) is True time.sleep(40/1000.0) index, nodes =", "nodes = c.catalog.service('s1', tag='master') assert set([x['Node'] for x in nodes])", "c.agent.check.deregister(check_id) is True assert set(c.agent.checks().keys()) == set([]) def verify_check_status(check_id, status,", "rules = \"\"\" key \"\" { policy = \"read\" }", "http.uri('/v1/kv') == 'http://127.0.0.1:8500/v1/kv' assert http.uri('/v1/kv', params={'index': 1}) == \\ 'http://127.0.0.1:8500/v1/kv?index=1'", "consul_port): c = consul.Consul(port=consul_port) index, data = c.kv.get('foo') assert data", "behavior assert c.kv.put('foo', '1', acquire=s) is True index, data =", "is True verify_check_status('ttl_check', 'warning', 'its not quite right') assert c.agent.check.ttl_fail('ttl_check')", "acls]) == \\ set(['anonymous', master_token]) assert c.acl.info('foo') is None compare", "set([x['Node'] for x in nodes]) == set(['n1']) # cleanup assert", "is None c.kv.put('foo', 'bar') c.kv.put('private/foo', 'bar') assert c.kv.get('foo', token=token)[1]['Value'] ==", "c.acl.clone, 'foo') pytest.raises(consul.ACLDisabled, c.acl.destroy, 'foo') def test_acl_permission_denied(self, acl_consul): c =", "assert c.session.destroy(session_id) is True _, sessions = c.session.list() assert sessions", "# only one node available index, nodes = c.health.state('passing') assert", "= c.catalog.service('s1') assert set([x['Node'] for x in nodes]) == set(['n1'])", "index, checks = c.health.checks('foobar') assert len(checks) == 0 def test_session(self,", "assert queries != [] \\ and len(queries) == 1 assert", "assert queries == [] # create a new named query", "test_agent_node_maintenance(self, consul_port): c = consul.Consul(port=consul_port) c.agent.maintenance('true', \"test\") time.sleep(40/1000.0) checks_pre =", "test None c.kv.put('foo', None) index, data = c.kv.get('foo') assert data['Value']", "c.kv.delete, 'private/foo', token=token) # clean up c.acl.destroy(token) acls = c.acl.list()", "c.kv.put('foo', '2', acquire=s2) is False assert c.kv.put('foo', '1', acquire=s1) is", "c.txn.put([d]) assert r[\"Results\"][0][\"KV\"][\"Value\"] == value def test_event(self, consul_port): c =", "consul.Consul(port=consul_port) c.agent.service.register(service_name) time.sleep(80/1000.0) index, nodes = c.health.service(service_name) assert [node['Service']['ID'] for", "= c.health.service(\"foo1\") assert nodes == [] c.agent.service.register('foo', enable_tag_override=True) assert c.agent.services()['foo']['EnableTagOverride']", "node='n2') pytest.raises(consul.ConsulException, c.session.create, dc='dc2') session_id = c.session.create('my-session') # session.list pytest.raises(consul.ConsulException,", "assert [node['Service']['ID'] for node in nodes] == [] def test_agent_checks_service_id(self,", "pytest.raises( consul.ConsulException, c.catalog.service, 's1', dc='dc2') _, nodes = c.catalog.service('s1') assert", "nodes = c.health.service('foo1') assert [node['Service']['ID'] for node in nodes] ==", "== checks_pre['_service_maintenance:foo']['Notes'] c.agent.service.maintenance('foo', 'false') time.sleep(40/1000.0) checks_post = c.agent.checks() assert '_service_maintenance:foo'", "assert c.kv.put('foo', 'bar', flags=50) is True index, data = c.kv.get('foo')", "= consul.Consul(port=consul_port) agent_self = c.agent.self() leader = c.status.leader() addr_port =", "index, events = c.event.list(name=\"fooname\") assert [x['Name'] == 'fooname' for x", "c.acl.info('anonymous')] compare.sort(key=operator.itemgetter('ID')) assert acls == compare rules = \"\"\" key", "1 assert queries[0]['Name'] == query_name \\ and queries[0]['ID'] == query['ID']", "== [ 'foo/', 'foo/bar1', 'foo/bar2', 'foo/bar3'] assert [x['Value'] for x", "= c.kv.get('foo') check, data = c.kv.get('foo', index=index, wait='20ms') assert index", "c.kv.get('foo') assert data['Value'] is None # check unencoded values raises", "} key \"private/\" { policy = \"deny\" } \"\"\" token", "'s1', dc='dc2') _, nodes = c.catalog.service('s1') assert set([x['Node'] for x", "right') assert c.agent.check.ttl_fail('ttl_check') is True verify_check_status('ttl_check', 'critical') assert c.agent.check.ttl_fail( 'ttl_check',", "assert c.catalog.register( 'n2', '10.1.10.12', service={'service': 's1', 'tags': ['master']}) is True", "check in node['Checks']]) == set(['foo', 'serfHealth']) # Clean up tasks", "notes='foo') assert c.agent.checks()['check']['Notes'] == 'foo' c.agent.check.deregister('check') assert set(c.agent.checks().keys()) == set([])", "\"deny\" } \"\"\" token = c.acl.create(rules=rules) assert c.acl.info(token)['Rules'] == rules", "test_kv(self, consul_port): c = consul.Consul(port=consul_port) index, data = c.kv.get('foo') assert", "six.b('bar') pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'foo', 'bar2', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete,", "is None # check unencoded values raises assert pytest.raises(AssertionError, c.kv.put,", "test_agent_register_check_no_service_id(self, consul_port): c = consul.Consul(port=consul_port) index, nodes = c.health.service(\"foo1\") assert", "Check.ttl('100ms'), service_id='foo1') time.sleep(40/1000.0) assert c.agent.checks() == {} # Cleanup tasks", "None, six.b('1'), six.b('2'), six.b('3')] def test_kv_delete(self, consul_port): c = consul.Consul(port=consul_port)", "== set(['s1', 's2']) _, node = c.catalog.node('n3') assert node is", ") pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'private/foo', 'bar2', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete,", "= c.kv.get('foo', index=index, wait='20ms') assert index == check def test_kv_encoding(self,", "token pytest.raises( consul.ACLPermissionDenied, c.kv.get, 'private/foo', token=token ) pytest.raises( consul.ACLPermissionDenied, c.kv.put,", "= [c.acl.info(master_token), c.acl.info('anonymous')] compare.sort(key=operator.itemgetter('ID')) assert acls == compare rules =", "x in nodes]) == set(['n1']) # cleanup assert c.catalog.deregister('n1') is", "set(['anonymous', master_token]) def test_acl_implicit_token_use(self, acl_consul): # configure client to use", "in checks_post.keys() # Cleanup c.agent.service.deregister('foo') time.sleep(40/1000.0) def test_agent_node_maintenance(self, consul_port): c", "for x in sessions] == ['my-session'] # session.info pytest.raises( consul.ConsulException,", "agent_self = c.agent.self() leader = c.status.leader() addr_port = agent_self['Stats']['consul']['leader_addr'] assert", "verify_check_status('ttl_check', 'passing', notes='all hunky dory!') # wait for ttl to", "consul.ACLPermissionDenied, c.kv.delete, 'private/foo', token=token) # clean up c.acl.destroy(token) acls =", "events = c.event.list() assert [x['Name'] == 'fooname' for x in", "[ None, six.b('1'), six.b('2'), six.b('3')] def test_kv_delete(self, consul_port): c =", "# check that query list is empty queries = c.query.list()", "d = {\"KV\": {\"Verb\": \"set\", \"Key\": \"asdf\", \"Value\": value}} r", "'_service_maintenance:foo' in checks_pre.keys() assert 'test' == checks_pre['_service_maintenance:foo']['Notes'] c.agent.service.maintenance('foo', 'false') time.sleep(40/1000.0)", "nodes] == [service_name] # Clean up tasks assert c.agent.service.deregister(service_name) is", "# grab local node name node = c.agent.self()['Config']['NodeName'] index, checks", "query assert c.query.explain(query_name)['Query'] # delete query assert c.query.delete(query['ID']) def test_coordinate(self,", "True assert c.catalog.deregister('n2', service_id='s1') is True # check the nodes", "time.sleep(40/1000.0) def test_agent_register_enable_tag_override(self, consul_port): c = consul.Consul(port=consul_port) index, nodes =", "'n2']) _, nodes = c.catalog.service('s1', tag='master') assert set([x['Node'] for x", "c.kv.put('foo/bar3', '3') index, data = c.kv.get('foo/', recurse=True) assert [x['Key'] for", "c.session.create, node='n2') pytest.raises(consul.ConsulException, c.session.create, dc='dc2') session_id = c.session.create('my-session') # session.list", "'s2']) _, node = c.catalog.node('n3') assert node is None #", "node in nodes] == ['foo:1'] # deregister the nodes c.agent.service.deregister('foo:1')", "None c.kv.put('foo/', None) index, data = c.kv.get('foo/', recurse=True) assert len(data)", "c.health.service('foo', passing=True) assert [node['Service']['ID'] for node in nodes] == ['foo:1',", "['foo1', 'foo2', 'foo3'] assert c.kv.delete('foo2') is True index, data =", "[] index, data = c.health.service('bar-1', token=token) assert not data #", "c = consul.Consul(port=consul_port) # grab local node name node =", "is True index, data = c.kv.get('foo') assert data['Value'] == six.b('1')", "c.catalog.deregister('n2', service_id='s1') is True # check the nodes weren't removed", "x in data] == [ 'foo/', 'foo/bar1', 'foo/bar2', 'foo/bar3'] assert", "test_status_peers(self, consul_port): c = consul.Consul(port=consul_port) agent_self = c.agent.self() addr_port =", "consul_port): c = consul.Consul(port=consul_port) assert c.kv.put('foo', 'bar', cas=50) is False", "config[\"Index\"] == 1 leader = False voter = False for", "'5') is True index, data = c.kv.get('base/', keys=True, separator='/') assert", "['base/base/', 'base/foo'] def test_transaction(self, consul_port): c = consul.Consul(port=consul_port) value =", "set() # test address param assert c.agent.service.register('foo', address='10.10.10.1') is True", "Cleanup tasks c.agent.check.deregister('foo') time.sleep(40/1000.0) def test_agent_register_enable_tag_override(self, consul_port): c = consul.Consul(port=consul_port)", "test_health_node(self, consul_port): c = consul.Consul(port=consul_port) # grab local node name", "'http_timeout_check', Check.http(http_addr, '100ms', timeout='2s')) is True verify_and_dereg_check('http_timeout_check') assert c.agent.check.register('ttl_check', Check.ttl('100ms'))", "== \\ set(['anonymous', master_token]) def test_status_leader(self, consul_port): c = consul.Consul(port=consul_port)", "assert data is None c.kv.put('foo/', None) index, data = c.kv.get('foo/',", "assert c.kv.put('foo', '2', release=s2) is False assert c.kv.put('foo', '2', release=s1)", "c.agent.service.register( 'foobar', service_id='foobar', check=Check.ttl('10s')) time.sleep(40/1000.00) index, checks = c.health.checks('foobar') assert", "is False assert c.kv.put('foo', 'bar2', cas=data['ModifyIndex']) is True index, data", "assert c.agent.check.register( 'check name', Check.script('/bin/true', 10), check_id='check_id') is True verify_and_dereg_check('check_id')", "# retrieve query using id and name queries = c.query.get(query['ID'])", "recurse=True) assert [x['Key'] for x in data] == ['foo1', 'foo2',", "index, data = c.kv.get('foo', recurse=True) assert data is None def", "def test_kv_delete_cas(self, consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo', 'bar') index, data", "quite right') assert c.agent.check.ttl_fail('ttl_check') is True verify_check_status('ttl_check', 'critical') assert c.agent.check.ttl_fail(", "def test_agent_self(self, consul_port): c = consul.Consul(port=consul_port) assert set(c.agent.self().keys()) == set(['Member',", "'2') c.kv.put('foo3', '3') index, data = c.kv.get('foo', recurse=True) assert [x['Key']", "to expire time.sleep(120/1000.0) verify_check_status('ttl_check', 'critical') verify_and_dereg_check('ttl_check') def test_service_dereg_issue_156(self, consul_port): #", "c.catalog.deregister, 'n2', dc='dc2') assert c.catalog.deregister('n1', check_id='c1') is True assert c.catalog.deregister('n2',", "\"Key\": \"asdf\", \"Value\": value}} r = c.txn.put([d]) assert r[\"Errors\"] is", "using id and name queries = c.query.get(query['ID']) assert queries !=", "import six import consul import consul.std Check = consul.Check class", "consul_port): c = consul.Consul(port=consul_port) members = c.agent.members() for x in", "c.session.create(behavior='delete', ttl=20) # attempt to renew an unknown session pytest.raises(consul.NotFound,", "= consul.Consul(port=consul_port) c.agent.service.register('foo1') time.sleep(40/1000.0) index, nodes = c.health.service('foo1') assert [node['Service']['ID']", "c.catalog.service('s1') assert set([x['Node'] for x in nodes]) == set(['n1', 'n2'])", "== 1 assert queries[0]['Name'] == query_name \\ and queries[0]['ID'] ==", "consul.ACLPermissionDenied, c_limited.kv.put, 'foo', 'bar2') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.delete, 'foo') assert c.kv.get('private/foo')[1]['Value']", "== set( ['', 'foo:1']) # ping the failed node's health", "== (index, data) assert c.kv.delete('foo', cas=data['ModifyIndex']) is True index, data", "= acl_consul.token acls = c.acl.list(token=master_token) assert set([x['ID'] for x in", "for x in acls]) == \\ set(['anonymous', master_token]) assert c.acl.info('foo')", "deregister the nodes c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2') time.sleep(40/1000.0) index, nodes = c.health.service('foo')", "node in nodes] == ['foo:1', 'foo:2'] # wait until the", "[x['Node'] for x in nodes] == [] def test_health_service(self, consul_port):", "# check there are no nodes for the service 'foo'", "= c.catalog.nodes() nodes.remove(current) assert [x['Node'] for x in nodes] ==", "peers = c.status.peers() assert addr_port in peers, \\ \"Expected value", "in nodes] != 'foo' # ping the two node's health", "data = c.health.service('foo-1', token=token) assert data[0]['Service']['ID'] == \"foo-1\" index, data", "c.kv.put('foo2', '2') c.kv.put('foo3', '3') index, data = c.kv.get('foo', recurse=True) assert", "# create a new named query query_service = 'foo' query_name", "== token2 assert c.acl.info(token2)['Name'] == 'Foo' assert c.acl.destroy(token2) is True", "c.event.list(name=\"fooname\") assert [x['Name'] == 'fooname' for x in events] assert", "= consul.Consul(port=consul_port) index, data = c.kv.get('foo/', recurse=True) assert data is", "c.health.service('foo', passing=True) assert [node['Service']['ID'] for node in nodes] == ['foo:1']", "x in members: assert x['Status'] == 1 assert not x['Name']", "check def test_kv_encoding(self, consul_port): c = consul.Consul(port=consul_port) # test binary", "# test setting notes on a check c.agent.check.register('check', Check.ttl('1s'), notes='foo')", "queries[0]['ID'] == query['ID'] # explain query assert c.query.explain(query_name)['Query'] # delete", "None assert c.agent.self()['Member'] in members wan_members = c.agent.members(wan=True) for x", "== 'foo'][0] == '10.10.10.1' assert c.agent.service.deregister('foo') is True def test_catalog(self,", "!= [] \\ and len(queries) == 1 assert queries[0]['Name'] ==", "pytest.raises( consul.ConsulException, c.kv.put, 'foo', 'bar', acquire='foo') s1 = c.session.create() s2", "assert [node['Service']['ID'] for node in nodes] == ['foo:1', 'foo:2'] #", "def test_uri(self): http = consul.std.HTTPClient() assert http.uri('/v1/kv') == 'http://127.0.0.1:8500/v1/kv' assert", "\"asdf\", \"Value\": value}} r = c.txn.put([d]) assert r[\"Errors\"] is None", "# register two nodes, one with a long ttl, the", "= c.health.service('foo', tag='tag:foo:1') assert [node['Service']['ID'] for node in nodes] ==", "'bar2', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'private/foo', token=token) # clean up", "== set([]) assert c.agent.check.register( 'script_check', Check.script('/bin/true', 10)) is True verify_and_dereg_check('script_check')", "data = c.health.checks('foo-1', token=token) assert data == [] index, data", "\"Expected value '{0}' \" \\ \"in peer list but it", "session_id, dc='dc2') assert c.session.destroy(session_id) is True _, sessions = c.session.list()", "'foo:1', 'foo:2']) # wait until the short ttl node fails", "x in wan_members: assert 'dc1' in x['Name'] def test_agent_self(self, consul_port):", "'private/foo', 'bar2', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'private/foo', token=token) # test", "None assert c.kv.put('foo', 'bar') is True index, data = c.kv.get('foo')", "release='foo') is False assert c.kv.put('foo', '2', release=s2) is False assert", "'s1'}, check={'name': 'c1'}) is True assert c.catalog.register( 'n1', '10.1.10.11', service={'service':", "set(['n1']) # cleanup assert c.catalog.deregister('n1') is True assert c.catalog.deregister('n2') is", "[] # create a new named query query_service = 'foo'", "query ID assert 'ID' in query \\ and query['ID'] is", "['n1', 'n2'] # check n2's s1 service was removed though", "service \"bar-\" { policy = \"read\" } \"\"\" token =", "= c.agent.checks() assert '_service_maintenance:foo' not in checks_post.keys() # Cleanup c.agent.service.deregister('foo')", "'2', acquire=s2) is False assert c.kv.put('foo', '1', acquire=s1) is True", "wan_members = c.agent.members(wan=True) for x in wan_members: assert 'dc1' in", "acls == compare rules = \"\"\" key \"\" { policy", "value}} r = c.txn.put([d]) assert r[\"Errors\"] is None d =", "c.agent.check.deregister('check') assert set(c.agent.checks().keys()) == set([]) assert c.agent.check.register( 'script_check', Check.script('/bin/true', 10))", "consul.Consul(port=consul_port) c.kv.put('foo', 'bar') index, data = c.kv.get('foo') assert c.kv.delete('foo', cas=data['ModifyIndex']-1)", "test_session(self, consul_port): c = consul.Consul(port=consul_port) # session.create pytest.raises(consul.ConsulException, c.session.create, node='n2')", "= c.health.service(service_name) assert [node['Service']['ID'] for node in nodes] == []", "nodes] == ['foo:1', 'foo:2'] # but that they aren't passing", "six.b('bar') pytest.raises( consul.ACLPermissionDenied, c.kv.get, 'private/foo', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'private/foo',", "def test_query(self, consul_port): c = consul.Consul(port=consul_port) # check that query", "test_kv_put_cas(self, consul_port): c = consul.Consul(port=consul_port) assert c.kv.put('foo', 'bar', cas=50) is", "time.sleep(40/1000.0) c.agent.service.maintenance('foo', 'true', \"test\") time.sleep(40/1000.0) checks_pre = c.agent.checks() assert '_service_maintenance:foo'", "name', Check.script('/bin/true', 10), check_id='check_id') is True verify_and_dereg_check('check_id') http_addr = \"http://127.0.0.1:{0}\".format(consul_port)", "consul.Consul(port=consul_port) index, data = c.kv.get('foo/', recurse=True) assert data is None", "True index, data = c.kv.get('foo') assert data['Flags'] == 50 def", "'1') c.kv.put('foo/bar2', '2') c.kv.put('foo/bar3', '3') index, data = c.kv.get('foo/', recurse=True)", "token=token) assert data[0]['Service']['ID'] == \"foo-1\" index, data = c.health.checks('foo-1', token=token)", "= consul.Consul(port=consul_port) # grab the node our server created, so", "= c.health.state('any') assert [node['ServiceID'] for node in nodes] == ['']", "= c.kv.get('foo') assert data is None def test_acl_disabled(self, consul_port): c", "token=token) assert data == [] index, data = c.health.service('bar-1', token=token)", "index, data = c.kv.get('foo') assert data['Value'] is None # check", "True verify_and_dereg_check('script_check') assert c.agent.check.register( 'check name', Check.script('/bin/true', 10), check_id='check_id') is", "node = c.catalog.node('n1') assert set(node['Services'].keys()) == set(['s1', 's2']) _, node", "the other shorter c.agent.service.register( 'foo', service_id='foo:1', check=Check.ttl('10s'), tags=['tag:foo:1']) c.agent.service.register( 'foo',", "c.agent.service.deregister('foo:2') time.sleep(40/1000.0) index, nodes = c.health.service('foo') assert nodes == []", "== set(['foo']) assert c.agent.service.deregister('foo') is True assert set(c.agent.services().keys()) == set()", "for node in nodes] == ['foo:1'] # ping the failed", "# check that tag works index, nodes = c.health.service('foo', tag='tag:foo:1')", "nodes]) == set( ['', 'foo:1']) # ping the failed node's", "} service \"bar-\" { policy = \"read\" } \"\"\" token", "test_operator(self, consul_port): c = consul.Consul(port=consul_port) config = c.operator.raft_config() assert config[\"Index\"]", "pytest.raises(consul.ACLDisabled, c.acl.info, '1'*36) pytest.raises(consul.ACLDisabled, c.acl.create) pytest.raises(consul.ACLDisabled, c.acl.update, 'foo') pytest.raises(consul.ACLDisabled, c.acl.clone,", "consul_port): c = consul.Consul(port=consul_port) agent_self = c.agent.self() leader = c.status.leader()", "acquire='foo') s1 = c.session.create() s2 = c.session.create() assert c.kv.put('foo', '1',", "c = consul.Consul(port=consul_port) def verify_and_dereg_check(check_id): assert set(c.agent.checks().keys()) == set([check_id]) assert", "class TestConsul(object): def test_kv(self, consul_port): c = consul.Consul(port=consul_port) index, data", "= False voter = False for server in config[\"Servers\"]: if", "right') is True verify_check_status('ttl_check', 'warning', 'its not quite right') assert", "assert c.agent.check.ttl_pass( 'ttl_check', notes='all hunky dory!') is True verify_check_status('ttl_check', 'passing',", "session = c.session.renew(s) assert session['Behavior'] == 'delete' assert session['TTL'] ==", "# cleanup assert c.catalog.deregister('n1') is True assert c.catalog.deregister('n2') is True", "for x in acls]) == \\ set(['anonymous', master_token]) assert c.acl.info('1'*36)", "assert [node['Service']['ID'] for node in nodes] == ['foo:1'] # ping", "node is None # test catalog.service pytest.raises( consul.ConsulException, c.catalog.service, 's1',", "= c.event.list() assert [x['Name'] == 'fooname' for x in events]", "for x in wan_members: assert 'dc1' in x['Name'] def test_agent_self(self,", "back as `None` c.kv.put('foo', '') index, data = c.kv.get('foo') assert", "check both nodes are available index, nodes = c.health.state('passing') assert", "'foo', service_id='foo:1', check=Check.ttl('10s'), tags=['tag:foo:1']) c.agent.service.register( 'foo', service_id='foo:2', check=Check.ttl('100ms')) time.sleep(40/1000.0) #", "the client's default token pytest.raises( consul.ACLPermissionDenied, c.kv.get, 'private/foo', token=token )", "cleanup assert c.catalog.deregister('n1') is True assert c.catalog.deregister('n2') is True _,", "compare rules = \"\"\" key \"\" { policy = \"read\"", "set([node['ServiceID'] for node in nodes]) == set( ['', 'foo:1']) #", "timeout='2s')) is True verify_and_dereg_check('http_timeout_check') assert c.agent.check.register('ttl_check', Check.ttl('100ms')) is True assert", "is True verify_check_status('ttl_check', 'passing') assert c.agent.check.ttl_pass( 'ttl_check', notes='all hunky dory!')", "= c.kv.get('foo') assert data is None assert c.kv.put('foo', 'bar') is", "session = c.session.info('1'*36) assert session is None index, session =", "Check = consul.Check class TestHTTPClient(object): def test_uri(self): http = consul.std.HTTPClient()", "recurse=True) assert len(data) == 1 c.kv.put('foo/bar1', '1') c.kv.put('foo/bar2', '2') c.kv.put('foo/bar3',", "= c.kv.get('base/', keys=True, separator='/') assert data == ['base/base/', 'base/foo'] def", "x in data] == [ None, six.b('1'), six.b('2'), six.b('3')] def", "{ policy = \"read\" } \"\"\" token = c.acl.create(rules=rules, token=master_token)", "== [] index, data = c.health.service('bar-1', token=token) assert not data", "c.agent.check.register( 'http_check', Check.http(http_addr, '10ms')) is True time.sleep(1) verify_check_status('http_check', 'passing') verify_and_dereg_check('http_check')", "c.acl.destroy(token2) is True assert c.acl.info(token2) is None c.kv.put('foo', 'bar') c.kv.put('private/foo',", "c.acl.destroy, 'anonymous') def test_acl_explict_token_use(self, acl_consul): c = consul.Consul(port=acl_consul.port) master_token =", "is True c.acl.destroy(token, token=master_token) acls = c.acl.list(token=master_token) assert set([x['ID'] for", "= consul.Consul(port=acl_consul.port, token=acl_consul.token) master_token = acl_consul.token acls = c.acl.list() assert", "assert [node['ServiceID'] for node in nodes] == [''] def test_health_node(self,", "'bar') assert c.kv.get('foo', token=token)[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c.kv.put, 'foo',", "expire time.sleep(120/1000.0) verify_check_status('ttl_check', 'critical') verify_and_dereg_check('ttl_check') def test_service_dereg_issue_156(self, consul_port): # https://github.com/cablehead/python-consul/issues/156", "index, data = c.kv.get('foo', recurse=True) assert [x['Key'] for x in", "= consul.Consul(port=consul_port) c.agent.service.register('foo', check=Check.ttl('100ms')) time.sleep(40/1000.0) c.agent.service.maintenance('foo', 'true', \"test\") time.sleep(40/1000.0) checks_pre", "consul_port): c = consul.Consul(port=consul_port) c.agent.maintenance('true', \"test\") time.sleep(40/1000.0) checks_pre = c.agent.checks()", "in checks_pre.keys() assert 'test' == checks_pre['_node_maintenance']['Notes'] c.agent.maintenance('false') time.sleep(40/1000.0) checks_post =", "'n2', dc='dc2') assert c.catalog.deregister('n1', check_id='c1') is True assert c.catalog.deregister('n2', service_id='s1')", "c.acl.destroy(token) acls = c.acl.list() assert set([x['ID'] for x in acls])", "index, data = c.kv.get('foo/', recurse=True) assert len(data) == 1 c.kv.put('foo/bar1',", "== notes # test setting notes on a check c.agent.check.register('check',", "pytest.raises( consul.ACLPermissionDenied, c_limited.kv.put, 'private/foo', 'bar2') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.delete, 'private/foo') #", "assert c.acl.info(token2)['Rules'] == rules assert c.acl.update(token2, name='Foo', token=master_token) == token2", "= consul.Consul(port=consul_port) agent_self = c.agent.self() addr_port = agent_self['Stats']['consul']['leader_addr'] peers =", "= c.session.create() assert c.kv.put('foo', '1', acquire=s1) is True assert c.kv.put('foo',", "events == [] index, events = c.event.list(name=\"fooname\") assert [x['Name'] ==", "nodes = c.health.service('foo') assert nodes == [] def test_health_state(self, consul_port):", "True verify_check_status('ttl_check', 'warning') assert c.agent.check.ttl_warn( 'ttl_check', notes='its not quite right')", "node our server created, so we can ignore it _,", "'critical', notes='something went boink!') assert c.agent.check.ttl_pass('ttl_check') is True verify_check_status('ttl_check', 'passing')", "consul_port): c = consul.Consul(port=consul_port) # grab the node our server", "index, nodes = c.health.service('foo', passing=True) assert nodes == [] #", "query_name \\ and queries[0]['ID'] == query['ID'] # explain query assert", "data = c.kv.get('foo/', recurse=True) assert data is None c.kv.put('foo/', None)", "token=master_token) assert c.acl.info(token2)['Rules'] == rules assert c.acl.update(token2, name='Foo', token=master_token) ==", "\"in peer list but it was not present\".format(addr_port) def test_query(self,", "# test catalog.deregister pytest.raises( consul.ConsulException, c.catalog.deregister, 'n2', dc='dc2') assert c.catalog.deregister('n1',", "ServiceID index, nodes = c.health.state('any') assert [node['ServiceID'] for node in", "node = c.agent.self()['Config']['NodeName'] index, checks = c.health.node(node) assert node in", "'fooquery' query = c.query.create(query_service, query_name) # assert response contains query", "'false') time.sleep(40/1000.0) checks_post = c.agent.checks() assert '_service_maintenance:foo' not in checks_post.keys()", "index, data = c.kv.get('foo') assert data is None assert c.kv.put('foo',", "'Config', 'Coord', 'DebugConfig', 'Meta']) def test_agent_services(self, consul_port): c = consul.Consul(port=consul_port)", "is None d = {\"KV\": {\"Verb\": \"get\", \"Key\": \"asdf\"}} r", "def test_event(self, consul_port): c = consul.Consul(port=consul_port) assert c.event.fire(\"fooname\", \"foobody\") index,", "def test_agent_services(self, consul_port): c = consul.Consul(port=consul_port) assert c.agent.service.register('foo') is True", "c.agent.maintenance('true', \"test\") time.sleep(40/1000.0) checks_pre = c.agent.checks() assert '_node_maintenance' in checks_pre.keys()", "== rules token2 = c.acl.clone(token, token=master_token) assert c.acl.info(token2)['Rules'] == rules", "both nodes are available index, nodes = c.health.service('foo', passing=True) assert", "setting notes on a check c.agent.check.register('check', Check.ttl('1s'), notes='foo') assert c.agent.checks()['check']['Notes']", "consul.ConsulException, c.kv.put, 'foo', 'bar', acquire='foo') s1 = c.session.create() s2 =", "assert c.agent.self()['Member'] in members wan_members = c.agent.members(wan=True) for x in", "assert 'dc1' in x['Name'] def test_agent_self(self, consul_port): c = consul.Consul(port=consul_port)", "in nodes] == ['foo:1'] # deregister the nodes c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2')", "test_agent_register_enable_tag_override(self, consul_port): c = consul.Consul(port=consul_port) index, nodes = c.health.service(\"foo1\") assert", "check in checks] def test_health_checks(self, consul_port): c = consul.Consul(port=consul_port) c.agent.service.register(", "checks_post = c.agent.checks() assert '_node_maintenance' not in checks_post.keys() def test_agent_members(self,", "c.session.info('1'*36) assert session is None index, session = c.session.info(session_id) assert", "token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'private/foo', token=token) # clean up c.acl.destroy(token)", "c.catalog.register, 'foo', '10.1.10.11', dc='dc2') assert c.catalog.register( 'n1', '10.1.10.11', service={'service': 's1'},", "consul.Consul(port=consul_port) # check there are no nodes for the service", "set(['foo1', '']) assert set([ check['CheckID'] for node in nodes for", "services == {'s1': [u'master'], 's2': [], 'consul': []} # test", "1 leader = False voter = False for server in", "flags=50) is True index, data = c.kv.get('foo') assert data['Flags'] ==", "consul.ACLPermissionDenied, c.kv.delete, 'foo', token=token) assert c.kv.get('private/foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied,", "rules assert c.acl.update(token2, name='Foo', token=master_token) == token2 assert c.acl.info(token2)['Name'] ==", "c = consul.Consul(port=consul_port) assert c.kv.put('foo', 'bar', cas=50) is False assert", "time.sleep(120/1000.0) verify_check_status('ttl_check', 'critical') verify_and_dereg_check('ttl_check') def test_service_dereg_issue_156(self, consul_port): # https://github.com/cablehead/python-consul/issues/156 service_name", "= c.kv.get('foo') assert c.kv.delete('foo', cas=data['ModifyIndex']-1) is False assert c.kv.get('foo') ==", "assert c.kv.put('foo', 'bar') is True index, data = c.kv.get('foo') assert", "node available index, nodes = c.health.service('foo', passing=True) assert [node['Service']['ID'] for", "c_limited = consul.Consul(port=acl_consul.port, token=token) assert c_limited.kv.get('foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied,", "= c.health.service('foo') assert nodes == [] def test_health_state(self, consul_port): c", "dc='dc2') _, nodes = c.catalog.nodes() nodes.remove(current) assert [x['Node'] for x", "is True index, data = c.kv.get('base/', keys=True, separator='/') assert data", "assert set(c.agent.checks().keys()) == set([check_id]) assert c.agent.check.deregister(check_id) is True assert set(c.agent.checks().keys())", "in nodes for check in node['Checks']]) == set(['foo', 'serfHealth']) #", "c.kv.get('foo') assert struct.unpack('i', data['Value']) == (1000,) # test unicode c.kv.put('foo',", "test_agent_checks(self, consul_port): c = consul.Consul(port=consul_port) def verify_and_dereg_check(check_id): assert set(c.agent.checks().keys()) ==", "up assert c.agent.service.deregister('foo-1') is True c.acl.destroy(token, token=master_token) acls = c.acl.list(token=master_token)", "assert [x['Key'] for x in data] == ['foo1', 'foo2', 'foo3']", "True verify_check_status('ttl_check', 'critical') assert c.agent.check.ttl_fail( 'ttl_check', notes='something went boink!') is", "set([]) def verify_check_status(check_id, status, notes=None): checks = c.agent.checks() assert checks[check_id]['Status']", "'1', acquire=s1) is True assert c.kv.put('foo', '2', acquire=s2) is False", "== set( ['', 'foo:1', 'foo:2']) # deregister the nodes c.agent.service.deregister('foo:1')", "Status check, which has an # empty ServiceID index, nodes", "c.event.fire(\"fooname\", \"foobody\") index, events = c.event.list() assert [x['Name'] == 'fooname'", "check that tag works index, nodes = c.health.service('foo', tag='tag:foo:1') assert", "data['Flags'] == 0 assert c.kv.put('foo', 'bar', flags=50) is True index,", "is True assert c.kv.put('foo', '2', acquire=s2) is False assert c.kv.put('foo',", "'' # retrieve query using id and name queries =", "local node name node = c.agent.self()['Config']['NodeName'] index, checks = c.health.node(node)", "def test_kv_encoding(self, consul_port): c = consul.Consul(port=consul_port) # test binary c.kv.put('foo',", "assert set([node['ServiceID'] for node in nodes]) == set( ['', 'foo:1',", "recurse=True) assert data is None c.kv.put('foo/', None) index, data =", "None compare = [c.acl.info(master_token), c.acl.info('anonymous')] compare.sort(key=operator.itemgetter('ID')) assert acls == compare", "== ['service:foobar'] c.agent.service.deregister('foobar') time.sleep(40/1000.0) index, checks = c.health.checks('foobar') assert len(checks)", "= consul.Consul(port=consul_port) index, nodes = c.health.service(\"foo1\") assert nodes == []", "for x in nodes] == ['n1', 'n2'] # test catalog.services", "token=token) assert c_limited.kv.get('foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.put, 'foo', 'bar2')", "unknown session pytest.raises(consul.NotFound, c.session.renew, '1'*36) session = c.session.renew(s) assert session['Behavior']", "len(nodes) == 1 current = nodes[0] # test catalog.datacenters assert", "def test_session_delete_ttl_renew(self, consul_port): c = consul.Consul(port=consul_port) s = c.session.create(behavior='delete', ttl=20)", "for node in nodes] == ['foo:1', 'foo:2'] # wait until", "'10.1.10.12', service={'service': 's1', 'tags': ['master']}) is True # test catalog.nodes", "= c.health.checks('foo-1', token=token) assert data == [] index, data =", "set([x['Node'] for x in nodes]) == set(['n2']) # test catalog.deregister", "verify_and_dereg_check('http_check') assert c.agent.check.register( 'http_timeout_check', Check.http(http_addr, '100ms', timeout='2s')) is True verify_and_dereg_check('http_timeout_check')", "test_event(self, consul_port): c = consul.Consul(port=consul_port) assert c.event.fire(\"fooname\", \"foobody\") index, events", "= c.health.state('any') assert set([node['ServiceID'] for node in nodes]) == set(", "0 assert c.kv.put('foo', 'bar', flags=50) is True index, data =", "c.health.state('passing') assert [node['ServiceID'] for node in nodes] != 'foo' #", "c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0) # both nodes are now available index, nodes", "six.b('bar') def test_kv_wait(self, consul_port): c = consul.Consul(port=consul_port) assert c.kv.put('foo', 'bar')", "went boink!') assert c.agent.check.ttl_pass('ttl_check') is True verify_check_status('ttl_check', 'passing') assert c.agent.check.ttl_pass(", "c.acl.create) pytest.raises(consul.ACLPermissionDenied, c.acl.update, 'anonymous') pytest.raises(consul.ACLPermissionDenied, c.acl.clone, 'anonymous') pytest.raises(consul.ACLPermissionDenied, c.acl.destroy, 'anonymous')", "members wan_members = c.agent.members(wan=True) for x in wan_members: assert 'dc1'", "values raises assert pytest.raises(AssertionError, c.kv.put, 'foo', {1: 2}) def test_kv_put_cas(self,", "c.kv.put, 'foo', {1: 2}) def test_kv_put_cas(self, consul_port): c = consul.Consul(port=consul_port)", "set(['Datacenter', 'Coordinates', 'AreaID']) def test_operator(self, consul_port): c = consul.Consul(port=consul_port) config", "{\"KV\": {\"Verb\": \"get\", \"Key\": \"asdf\"}} r = c.txn.put([d]) assert r[\"Results\"][0][\"KV\"][\"Value\"]", "is True assert c.kv.put('base/base/foo', '5') is True index, data =", "data = c.kv.get('foo') assert data['Flags'] == 0 assert c.kv.put('foo', 'bar',", "config[\"Servers\"]: if server[\"Leader\"]: leader = True if server[\"Voter\"]: voter =", "node in nodes] != 'foo' # ping the two node's", "explain query assert c.query.explain(query_name)['Query'] # delete query assert c.query.delete(query['ID']) def", "assert c.agent.services()['foo']['EnableTagOverride'] # Cleanup tasks c.agent.check.deregister('foo') def test_agent_service_maintenance(self, consul_port): c", "= c.session.list() assert sessions == [] def test_session_delete_ttl_renew(self, consul_port): c", "= consul.Consul(port=consul_port) assert c.agent.service.register('foo') is True assert set(c.agent.services().keys()) == set(['foo'])", "the two node's health check c.agent.check.ttl_pass('service:foo:1') c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0) # both", "six.b('bar') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.put, 'foo', 'bar2') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.delete, 'foo')", "'foo:2']) # wait until the short ttl node fails time.sleep(2200/1000.0)", "nodes] == [''] def test_health_node(self, consul_port): c = consul.Consul(port=consul_port) #", "acls]) == \\ set(['anonymous', master_token]) def test_acl_implicit_token_use(self, acl_consul): # configure", "def test_kv(self, consul_port): c = consul.Consul(port=consul_port) index, data = c.kv.get('foo')", "'foo:1', 'foo:2']) # deregister the nodes c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2') time.sleep(40/1000.0) index,", "was not present\".format(addr_port) def test_query(self, consul_port): c = consul.Consul(port=consul_port) #", "[node['ServiceID'] for node in nodes] != 'foo' # ping the", "the failed node's health check c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0) # check both", "created, so we can ignore it _, nodes = c.catalog.nodes()", "['foo1'] c.agent.check.register('foo', Check.ttl('100ms'), service_id='foo1') time.sleep(40/1000.0) index, nodes = c.health.service('foo1') assert", "check=Check.ttl('100ms')) time.sleep(40/1000.0) # check the nodes show for the /health/service", "True assert set(c.agent.checks().keys()) == set([]) def verify_check_status(check_id, status, notes=None): checks", "empty-string comes back as `None` c.kv.put('foo', '') index, data =", "dc='dc2') _, nodes = c.catalog.service('s1') assert set([x['Node'] for x in", "c.kv.put, 'private/foo', 'bar2', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'private/foo', token=token) #", "False assert c.kv.put('foo', 'bar', cas=0) is True index, data =", "service={'service': 's1', 'tags': ['master']}) is True # test catalog.nodes pytest.raises(consul.ConsulException,", "[] def test_agent_checks_service_id(self, consul_port): c = consul.Consul(port=consul_port) c.agent.service.register('foo1') time.sleep(40/1000.0) index,", "notes='something went boink!') assert c.agent.check.ttl_pass('ttl_check') is True verify_check_status('ttl_check', 'passing') assert", "= \"read\" } key \"private/\" { policy = \"deny\" }", "set(['n1', 'n2']) _, nodes = c.catalog.service('s1', tag='master') assert set([x['Node'] for", "True index, data = c.kv.get('foo') assert data is None def", "are now available index, nodes = c.health.state('passing') assert set([node['ServiceID'] for", "verify_check_status('ttl_check', 'critical') assert c.agent.check.ttl_fail( 'ttl_check', notes='something went boink!') is True", "in nodes] == ['foo:1'] # ping the failed node's health", "checks_pre.keys() assert 'test' == checks_pre['_node_maintenance']['Notes'] c.agent.maintenance('false') time.sleep(40/1000.0) checks_post = c.agent.checks()", "'foo', {1: 2}) def test_kv_put_cas(self, consul_port): c = consul.Consul(port=consul_port) assert", "name='Foo') == token2 assert c.acl.info(token2)['Name'] == 'Foo' assert c.acl.destroy(token2) is", "six.b('1') c.session.destroy(s) index, data = c.kv.get('foo') assert data is None", "consul.ACLPermissionDenied, c_limited.kv.put, 'private/foo', 'bar2') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.delete, 'private/foo') # check", "hunky dory!') # wait for ttl to expire time.sleep(120/1000.0) verify_check_status('ttl_check',", "nodes weren't removed _, nodes = c.catalog.nodes() nodes.remove(current) assert [x['Node']", "weren't removed _, nodes = c.catalog.nodes() nodes.remove(current) assert [x['Node'] for", "c.catalog.register( 'n2', '10.1.10.12', service={'service': 's1', 'tags': ['master']}) is True #", "dc='dc2') assert c.catalog.deregister('n1', check_id='c1') is True assert c.catalog.deregister('n2', service_id='s1') is", "token=master_token) == token2 assert c.acl.info(token2)['Name'] == 'Foo' assert c.acl.destroy(token2, token=master_token)", "master_token = acl_consul.token acls = c.acl.list(token=master_token) assert set([x['ID'] for x", "c_limited.kv.get('foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.put, 'foo', 'bar2') pytest.raises( consul.ACLPermissionDenied,", "# empty ServiceID index, nodes = c.health.state('any') assert [node['ServiceID'] for", "in nodes]) == set( ['', 'foo:1', 'foo:2']) # wait until", "assert c.agent.check.register('ttl_check', Check.ttl('100ms')) is True assert c.agent.check.ttl_warn('ttl_check') is True verify_check_status('ttl_check',", "2}) def test_kv_put_cas(self, consul_port): c = consul.Consul(port=consul_port) assert c.kv.put('foo', 'bar',", "other shorter c.agent.service.register( 'foo', service_id='foo:1', check=Check.ttl('10s'), tags=['tag:foo:1']) c.agent.service.register( 'foo', service_id='foo:2',", "c.agent.checks() assert '_service_maintenance:foo' not in checks_post.keys() # Cleanup c.agent.service.deregister('foo') time.sleep(40/1000.0)", "c = consul.Consul(port=consul_port) c.kv.put('foo', 'bar') index, data = c.kv.get('foo') assert", "# test catalog.register pytest.raises( consul.ConsulException, c.catalog.register, 'foo', '10.1.10.11', dc='dc2') assert", "test_status_leader(self, consul_port): c = consul.Consul(port=consul_port) agent_self = c.agent.self() leader =", "c.kv.get('foo') assert data['Value'] == six.b('bar') # test empty-string comes back", "list is empty queries = c.query.list() assert queries == []", "== 'fooname' for x in events] assert [x['Payload'] == 'foobody'", "time.sleep(40/1000.0) checks_pre = c.agent.checks() assert '_service_maintenance:foo' in checks_pre.keys() assert 'test'", "data = c.kv.get('foo') assert data['Value'] is None # check unencoded", "index, data = c.kv.get('foo') assert data['Value'] == six.b('bar') def test_kv_wait(self,", "test unicode c.kv.put('foo', u'bar') index, data = c.kv.get('foo') assert data['Value']", "c.agent.self()['Config']['NodeName'] index, checks = c.health.node(node) assert node in [check[\"Node\"] for", "set([node['ServiceID'] for node in nodes]) == set( ['', 'foo:1', 'foo:2'])", "= consul.Consul(port=consul_port) # check there are no nodes for the", "c.agent.maintenance('false') time.sleep(40/1000.0) checks_post = c.agent.checks() assert '_node_maintenance' not in checks_post.keys()", "c.agent.service.deregister('foo1') is True time.sleep(40/1000.0) def test_agent_register_check_no_service_id(self, consul_port): c = consul.Consul(port=consul_port)", "assert 'ID' in query \\ and query['ID'] is not None", "'1', acquire=s1) is True assert c.kv.put('foo', '1', release='foo') is False", "index, nodes = c.health.service(service_name) assert [node['Service']['ID'] for node in nodes]", "None # check unencoded values raises assert pytest.raises(AssertionError, c.kv.put, 'foo',", "x['Name'] is None assert not x['Tags'] is None assert c.agent.self()['Member']", "delete query assert c.query.delete(query['ID']) def test_coordinate(self, consul_port): c = consul.Consul(port=consul_port)", "separator='/') assert data == ['base/base/', 'base/foo'] def test_transaction(self, consul_port): c", "x in data] == ['foo1', 'foo3'] assert c.kv.delete('foo', recurse=True) is", "test token pass through for service registration pytest.raises( consul.ACLPermissionDenied, c.agent.service.register,", "data is None def test_kv_delete_cas(self, consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo',", "10)) is True verify_and_dereg_check('script_check') assert c.agent.check.register( 'check name', Check.script('/bin/true', 10),", "{ policy = \"deny\" } \"\"\" token = c.acl.create(rules=rules) assert", "'bar2') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.delete, 'private/foo') # check we can override", "set(c.agent.services().keys()) == set() # test address param assert c.agent.service.register('foo', address='10.10.10.1')", "set(c.agent.services().keys()) == set(['foo']) assert c.agent.service.deregister('foo') is True assert set(c.agent.services().keys()) ==", "[] def test_health_service(self, consul_port): c = consul.Consul(port=consul_port) # check there", "new named query query_service = 'foo' query_name = 'fooquery' query", "test binary c.kv.put('foo', struct.pack('i', 1000)) index, data = c.kv.get('foo') assert", "in nodes]) == set(['n1']) # cleanup assert c.catalog.deregister('n1') is True", "assert [node['Service']['ID'] for node in nodes] == ['foo1'] c.agent.check.register('foo', Check.ttl('100ms'),", "= consul.Consul(port=consul_port) # grab local node name node = c.agent.self()['Config']['NodeName']", "True time.sleep(40/1000.0) assert c.agent.service.deregister('foo1') is True time.sleep(40/1000.0) def test_agent_register_check_no_service_id(self, consul_port):", "c.kv.get('private/foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c.kv.get, 'private/foo', token=token) pytest.raises( consul.ACLPermissionDenied,", "c.health.service('foo1') assert set([ check['ServiceID'] for node in nodes for check", "index, data = c.health.service('bar-1', token=token) assert not data # clean", "True assert set(c.agent.services().keys()) == set(['foo']) assert c.agent.service.deregister('foo') is True assert", "recurse=True) assert data is None def test_kv_delete_cas(self, consul_port): c =", "'anonymous') def test_acl_explict_token_use(self, acl_consul): c = consul.Consul(port=acl_consul.port) master_token = acl_consul.token", "== [] def test_health_state(self, consul_port): c = consul.Consul(port=consul_port) # The", "rules token2 = c.acl.clone(token) assert c.acl.info(token2)['Rules'] == rules assert c.acl.update(token2,", "c_limited.kv.put, 'private/foo', 'bar2') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.delete, 'private/foo') # check we", "consul.ACLPermissionDenied, c_limited.kv.delete, 'private/foo') # check we can override the client's", "consul_port): c = consul.Consul(port=consul_port) config = c.operator.raft_config() assert config[\"Index\"] ==", "c.catalog.node, 'n1', dc='dc2') _, node = c.catalog.node('n1') assert set(node['Services'].keys()) ==", "_, nodes = c.catalog.nodes() nodes.remove(current) assert [x['Node'] for x in", "= c.acl.list(token=master_token) assert set([x['ID'] for x in acls]) == \\", "c = consul.Consul(port=consul_port) # session.create pytest.raises(consul.ConsulException, c.session.create, node='n2') pytest.raises(consul.ConsulException, c.session.create,", "assert set([x['Node'] for x in nodes]) == set(['n2']) # test", "voter = False for server in config[\"Servers\"]: if server[\"Leader\"]: leader", "\\ and len(queries) == 1 assert queries[0]['Name'] == query_name \\", "in nodes] == [''] # register two nodes, one with", "c.acl.create) pytest.raises(consul.ACLDisabled, c.acl.update, 'foo') pytest.raises(consul.ACLDisabled, c.acl.clone, 'foo') pytest.raises(consul.ACLDisabled, c.acl.destroy, 'foo')", "nodes are now available index, nodes = c.health.service('foo', passing=True) assert", "= consul.Consul(port=consul_port) c.agent.maintenance('true', \"test\") time.sleep(40/1000.0) checks_pre = c.agent.checks() assert '_node_maintenance'", "True time.sleep(1) verify_check_status('http_check', 'passing') verify_and_dereg_check('http_check') assert c.agent.check.register( 'http_timeout_check', Check.http(http_addr, '100ms',", "c.agent.check.ttl_pass( 'ttl_check', notes='all hunky dory!') is True verify_check_status('ttl_check', 'passing', notes='all", "True assert c.agent.check.ttl_warn('ttl_check') is True verify_check_status('ttl_check', 'warning') assert c.agent.check.ttl_warn( 'ttl_check',", "address param assert c.agent.service.register('foo', address='10.10.10.1') is True assert [ v['Address']", "consul.ConsulException, c.catalog.register, 'foo', '10.1.10.11', dc='dc2') assert c.catalog.register( 'n1', '10.1.10.11', service={'service':", "data['Value'] is None # test None c.kv.put('foo', None) index, data", "data['Value'] is None # check unencoded values raises assert pytest.raises(AssertionError,", "master_token]) assert c.acl.info('foo') is None compare = [c.acl.info(master_token), c.acl.info('anonymous')] compare.sort(key=operator.itemgetter('ID'))", "'ID' in query \\ and query['ID'] is not None \\", "the short ttl node fails time.sleep(2200/1000.0) # only one node", "is False assert c.kv.get('foo') == (index, data) assert c.kv.delete('foo', cas=data['ModifyIndex'])", "index, nodes = c.health.service('foo', passing=True) assert [node['Service']['ID'] for node in", "pytest.raises( consul.ConsulException, c.session.destroy, session_id, dc='dc2') assert c.session.destroy(session_id) is True _,", "== 0 assert c.kv.put('foo', 'bar', flags=50) is True index, data", "'s1', 'tags': ['master']}) is True # test catalog.nodes pytest.raises(consul.ConsulException, c.catalog.nodes,", "= consul.Consul(port=consul_port) index, data = c.kv.get('foo') assert data is None", "index, data = c.kv.get('foo') assert data['Value'] is None # test", "is None assert c.kv.put('foo', 'bar') is True index, data =", "assert not x['Name'] is None assert not x['Tags'] is None", "def test_health_service(self, consul_port): c = consul.Consul(port=consul_port) # check there are", "= c.status.leader() addr_port = agent_self['Stats']['consul']['leader_addr'] assert leader == addr_port, \\", "def test_kv_delete(self, consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo1', '1') c.kv.put('foo2', '2')", "verify_check_status('ttl_check', 'critical') verify_and_dereg_check('ttl_check') def test_service_dereg_issue_156(self, consul_port): # https://github.com/cablehead/python-consul/issues/156 service_name =", "nodes == [] def test_health_state(self, consul_port): c = consul.Consul(port=consul_port) #", "True verify_check_status('ttl_check', 'passing', notes='all hunky dory!') # wait for ttl", "set( ['', 'foo:1', 'foo:2']) # deregister the nodes c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2')", "== six.b('1') c.session.destroy(s) index, data = c.kv.get('foo') assert data is", "'http_check', Check.http(http_addr, '10ms')) is True time.sleep(1) verify_check_status('http_check', 'passing') verify_and_dereg_check('http_check') assert", "def test_kv_recurse(self, consul_port): c = consul.Consul(port=consul_port) index, data = c.kv.get('foo/',", "for the service 'foo' index, nodes = c.health.service('foo') assert nodes", "== value def test_event(self, consul_port): c = consul.Consul(port=consul_port) assert c.event.fire(\"fooname\",", "assert data[0]['Service']['ID'] == \"foo-1\" index, data = c.health.checks('foo-1', token=token) assert", "for x in nodes] == [] def test_health_service(self, consul_port): c", "both nodes are now available index, nodes = c.health.service('foo', passing=True)", "# Clean up tasks assert c.agent.service.deregister(service_name) is True time.sleep(40/1000.0) index,", "pytest.raises( consul.ConsulException, c.session.info, session_id, dc='dc2') index, session = c.session.info('1'*36) assert", "test_coordinate(self, consul_port): c = consul.Consul(port=consul_port) c.coordinate.nodes() c.coordinate.datacenters() assert set(c.coordinate.datacenters()[0].keys()) ==", "time.sleep(40/1000.0) # check the nodes show for the /health/service endpoint", "c.kv.put, 'foo', 'bar2', token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'foo', token=token) assert", "catalog.nodes pytest.raises(consul.ConsulException, c.catalog.nodes, dc='dc2') _, nodes = c.catalog.nodes() nodes.remove(current) assert", "value was {0}, expected value \" \\ \"was {1}\".format(leader, addr_port)", "c.acl.list() assert set([x['ID'] for x in acls]) == \\ set(['anonymous',", "assert c.kv.put('foo', '1', acquire=s1) is True assert c.kv.put('foo', '1', release='foo')", "[] def test_session_delete_ttl_renew(self, consul_port): c = consul.Consul(port=consul_port) s = c.session.create(behavior='delete',", "0 def test_session(self, consul_port): c = consul.Consul(port=consul_port) # session.create pytest.raises(consul.ConsulException,", "'n1', '10.1.10.11', service={'service': 's1'}, check={'name': 'c1'}) is True assert c.catalog.register(", "test_agent_members(self, consul_port): c = consul.Consul(port=consul_port) members = c.agent.members() for x", "went boink!') is True verify_check_status( 'ttl_check', 'critical', notes='something went boink!')", "= consul.Consul(port=acl_consul.port) master_token = acl_consul.token acls = c.acl.list(token=master_token) assert set([x['ID']", "assert nodes == [] # register two nodes, one with", "failed node's health check c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0) # check both nodes", "= c.agent.members() for x in members: assert x['Status'] == 1", "dc='dc2') assert c.catalog.register( 'n1', '10.1.10.11', service={'service': 's1'}, check={'name': 'c1'}) is", "session.list pytest.raises(consul.ConsulException, c.session.list, dc='dc2') _, sessions = c.session.list() assert [x['Name']", "token = c.acl.create(rules=rules, token=master_token) assert c.acl.info(token)['Rules'] == rules token2 =", "== \\ set(['anonymous', master_token]) def test_acl_implicit_token_use(self, acl_consul): # configure client", "peers, \\ \"Expected value '{0}' \" \\ \"in peer list", "quite right') is True verify_check_status('ttl_check', 'warning', 'its not quite right')", "is None assert not x['Tags'] is None assert c.agent.self()['Member'] in", "'anonymous') pytest.raises(consul.ACLPermissionDenied, c.acl.destroy, 'anonymous') def test_acl_explict_token_use(self, acl_consul): c = consul.Consul(port=acl_consul.port)", "== status if notes: assert checks[check_id]['Output'] == notes # test", "consul.ConsulException, c.session.destroy, session_id, dc='dc2') assert c.session.destroy(session_id) is True _, sessions", "c = consul.Consul(port=consul_port) agent_self = c.agent.self() addr_port = agent_self['Stats']['consul']['leader_addr'] peers", "c.catalog.service('s1', tag='master') assert set([x['Node'] for x in nodes]) == set(['n2'])", "c.session.destroy(s) index, data = c.kv.get('foo') assert data is None def", "pytest.raises( consul.ACLPermissionDenied, c.agent.service.register, \"bar-1\", token=token) c.agent.service.register(\"foo-1\", token=token) index, data =", "'10.1.10.11', service={'service': 's2'}) is True assert c.catalog.register( 'n2', '10.1.10.12', service={'service':", "True assert set(c.agent.services().keys()) == set() # test address param assert", "True assert c.acl.info(token2) is None c.kv.put('foo', 'bar') c.kv.put('private/foo', 'bar') c_limited", "'s2': [], 'consul': []} # test catalog.node pytest.raises(consul.ConsulException, c.catalog.node, 'n1',", "c.health.state('any') assert set([node['ServiceID'] for node in nodes]) == set( ['',", "addr_port in peers, \\ \"Expected value '{0}' \" \\ \"in", "though _, nodes = c.catalog.service('s1') assert set([x['Node'] for x in", "rules token2 = c.acl.clone(token, token=master_token) assert c.acl.info(token2)['Rules'] == rules assert", "TestConsul(object): def test_kv(self, consul_port): c = consul.Consul(port=consul_port) index, data =", "= consul.Consul(port=consul_port) # check that query list is empty queries", "c.health.node(node) assert node in [check[\"Node\"] for check in checks] def", "['foo:1', 'foo:2'] # check that tag works index, nodes =", "assert c.kv.put('foo', '1', acquire=s) is True index, data = c.kv.get('foo')", "set(['anonymous', master_token]) def test_status_leader(self, consul_port): c = consul.Consul(port=consul_port) agent_self =", "= \"deny\" } \"\"\" token = c.acl.create(rules=rules) assert c.acl.info(token)['Rules'] ==", "service_id='foobar', check=Check.ttl('10s')) time.sleep(40/1000.00) index, checks = c.health.checks('foobar') assert [check['ServiceID'] for", "'serfHealth']) # Clean up tasks assert c.agent.check.deregister('foo') is True time.sleep(40/1000.0)", "session['Behavior'] == 'delete' assert session['TTL'] == '20s' # trying out", "Clean up tasks assert c.agent.check.deregister('foo') is True time.sleep(40/1000.0) assert c.agent.service.deregister('foo1')", "\"Key\": \"asdf\"}} r = c.txn.put([d]) assert r[\"Results\"][0][\"KV\"][\"Value\"] == value def", "nodes for the service 'foo' index, nodes = c.health.service('foo') assert", "\"Leader value was {0}, expected value \" \\ \"was {1}\".format(leader,", "data[0]['Service']['ID'] == \"foo-1\" index, data = c.health.checks('foo-1', token=token) assert data", "= c.kv.get('foo/', recurse=True) assert len(data) == 1 c.kv.put('foo/bar1', '1') c.kv.put('foo/bar2',", "assert nodes == [] # ping the two node's health", "'_service_maintenance:foo' not in checks_post.keys() # Cleanup c.agent.service.deregister('foo') time.sleep(40/1000.0) def test_agent_node_maintenance(self,", "assert [node['Service']['ID'] for node in nodes] == [service_name] # Clean", "'consul': []} # test catalog.node pytest.raises(consul.ConsulException, c.catalog.node, 'n1', dc='dc2') _,", "consul.Consul(port=consul_port) pytest.raises( consul.ConsulException, c.kv.put, 'foo', 'bar', acquire='foo') s1 = c.session.create()", "= c.health.service('bar-1', token=token) assert not data # clean up assert", "\\ set(['anonymous', master_token]) def test_acl_implicit_token_use(self, acl_consul): # configure client to", "[x['Value'] for x in data] == [ None, six.b('1'), six.b('2'),", "1 c.kv.put('foo/bar1', '1') c.kv.put('foo/bar2', '2') c.kv.put('foo/bar3', '3') index, data =", "index, checks = c.health.node(node) assert node in [check[\"Node\"] for check", "= c.health.state('passing') assert set([node['ServiceID'] for node in nodes]) == set(", "assert checks[check_id]['Status'] == status if notes: assert checks[check_id]['Output'] == notes", "= c.health.checks('foobar') assert len(checks) == 0 def test_session(self, consul_port): c", "c_limited.kv.delete, 'private/foo') # check we can override the client's default", "\"test\") time.sleep(40/1000.0) checks_pre = c.agent.checks() assert '_service_maintenance:foo' in checks_pre.keys() assert", "\"bar-\" { policy = \"read\" } \"\"\" token = c.acl.create(rules=rules,", "for x in nodes]) == set(['n1']) # cleanup assert c.catalog.deregister('n1')", "'passing') verify_and_dereg_check('http_check') assert c.agent.check.register( 'http_timeout_check', Check.http(http_addr, '100ms', timeout='2s')) is True", "set([ check['CheckID'] for node in nodes for check in node['Checks']])", "not x['Name'] is None assert not x['Tags'] is None assert", "they aren't passing their health check index, nodes = c.health.state('passing')", "consul.ACLPermissionDenied, c.kv.delete, 'private/foo', token=token) # test token pass through for", "set([]) assert c.agent.check.register( 'script_check', Check.script('/bin/true', 10)) is True verify_and_dereg_check('script_check') assert", "verify_and_dereg_check('script_check') assert c.agent.check.register( 'check name', Check.script('/bin/true', 10), check_id='check_id') is True", "'private/foo') # check we can override the client's default token", "check, which has an # empty ServiceID index, nodes =", "= session['Node'] pytest.raises( consul.ConsulException, c.session.node, node, dc='dc2') _, sessions =", "check in node['Checks']]) == set(['foo1', '']) assert set([ check['CheckID'] for", "\"http://127.0.0.1:{0}\".format(consul_port) assert c.agent.check.register( 'http_check', Check.http(http_addr, '10ms')) is True time.sleep(1) verify_check_status('http_check',", "c.agent.check.ttl_pass('ttl_check') is True verify_check_status('ttl_check', 'passing') assert c.agent.check.ttl_pass( 'ttl_check', notes='all hunky", "c.acl.destroy(token2, token=master_token) is True assert c.acl.info(token2) is None c.kv.put('foo', 'bar')", "consul.Consul(port=consul_port) # The empty string is for the Serf Health", "http = consul.std.HTTPClient() assert http.uri('/v1/kv') == 'http://127.0.0.1:8500/v1/kv' assert http.uri('/v1/kv', params={'index':", "test catalog.datacenters assert c.catalog.datacenters() == ['dc1'] # test catalog.register pytest.raises(", "six import consul import consul.std Check = consul.Check class TestHTTPClient(object):", "x in nodes] == ['n1', 'n2'] # test catalog.services pytest.raises(consul.ConsulException,", "[check['CheckID'] for check in checks] == ['service:foobar'] c.agent.service.deregister('foobar') time.sleep(40/1000.0) index,", "set([ check['ServiceID'] for node in nodes for check in node['Checks']])", "\"asdf\"}} r = c.txn.put([d]) assert r[\"Results\"][0][\"KV\"][\"Value\"] == value def test_event(self,", "'Foo' assert c.acl.destroy(token2) is True assert c.acl.info(token2) is None c.kv.put('foo',", "c = consul.Consul(port=consul_port) config = c.operator.raft_config() assert config[\"Index\"] == 1", "for ttl to expire time.sleep(120/1000.0) verify_check_status('ttl_check', 'critical') verify_and_dereg_check('ttl_check') def test_service_dereg_issue_156(self,", "c.kv.get('foo/', recurse=True) assert len(data) == 1 c.kv.put('foo/bar1', '1') c.kv.put('foo/bar2', '2')", "assert c.catalog.deregister('n1', check_id='c1') is True assert c.catalog.deregister('n2', service_id='s1') is True", "fails time.sleep(120/1000.0) # only one node available index, nodes =", "== [''] # register two nodes, one with a long", "c.agent.service.deregister(service_name) is True time.sleep(40/1000.0) index, nodes = c.health.service(service_name) assert [node['Service']['ID']", "== ['foo:1', 'foo:2'] # check that tag works index, nodes", "== [] # create a new named query query_service =", "agent_self['Stats']['consul']['leader_addr'] assert leader == addr_port, \\ \"Leader value was {0},", "query query_service = 'foo' query_name = 'fooquery' query = c.query.create(query_service,", "consul.ACLPermissionDenied, c_limited.kv.get, 'private/foo') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.put, 'private/foo', 'bar2') pytest.raises( consul.ACLPermissionDenied,", "\"read\" } key \"private/\" { policy = \"deny\" } service", "test catalog.service pytest.raises( consul.ConsulException, c.catalog.service, 's1', dc='dc2') _, nodes =", "== 'foo' c.agent.check.deregister('check') assert set(c.agent.checks().keys()) == set([]) assert c.agent.check.register( 'script_check',", "True if server[\"Voter\"]: voter = True assert leader assert voter", "there are no nodes for the service 'foo' index, nodes", "nodes c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2') time.sleep(40/1000.0) index, nodes = c.health.service('foo') assert nodes", "assert data is None def test_kv_acquire_release(self, consul_port): c = consul.Consul(port=consul_port)", "not in checks_post.keys() # Cleanup c.agent.service.deregister('foo') time.sleep(40/1000.0) def test_agent_node_maintenance(self, consul_port):", "response contains query ID assert 'ID' in query \\ and", "['', 'foo:1', 'foo:2']) # but that they aren't passing their", "renew an unknown session pytest.raises(consul.NotFound, c.session.renew, '1'*36) session = c.session.renew(s)", "\"read\" } key \"private/\" { policy = \"deny\" } \"\"\"", "time.sleep(2200/1000.0) # only one node available index, nodes = c.health.state('passing')", "use the master token by default c = consul.Consul(port=acl_consul.port, token=acl_consul.token)", "'bar') c.kv.put('private/foo', 'bar') c_limited = consul.Consul(port=acl_consul.port, token=token) assert c_limited.kv.get('foo')[1]['Value'] ==", "'foo/', 'foo/bar1', 'foo/bar2', 'foo/bar3'] assert [x['Value'] for x in data]", "'10ms')) is True time.sleep(1) verify_check_status('http_check', 'passing') verify_and_dereg_check('http_check') assert c.agent.check.register( 'http_timeout_check',", "# check we can override the client's default token pytest.raises(", "/health/service endpoint index, nodes = c.health.service('foo') assert [node['Service']['ID'] for node", "services = c.catalog.services() assert services == {'s1': [u'master'], 's2': [],", "'c1'}) is True assert c.catalog.register( 'n1', '10.1.10.11', service={'service': 's2'}) is", "c.kv.put('private/foo', 'bar') c_limited = consul.Consul(port=acl_consul.port, token=token) assert c_limited.kv.get('foo')[1]['Value'] == six.b('bar')", "# test unicode c.kv.put('foo', u'bar') index, data = c.kv.get('foo') assert", "assert c.agent.service.deregister('foo') is True assert set(c.agent.services().keys()) == set() # test", "is True index, data = c.kv.get('foo') check, data = c.kv.get('foo',", "assert [x['Name'] for x in sessions] == ['my-session'] # session.destroy", "consul.Consul(port=consul_port) c.agent.service.register('foo', check=Check.ttl('100ms')) time.sleep(40/1000.0) c.agent.service.maintenance('foo', 'true', \"test\") time.sleep(40/1000.0) checks_pre =", "c.agent.service.register( 'foo', service_id='foo:2', check=Check.ttl('100ms')) time.sleep(40/1000.0) # check the nodes show", "c.health.service('foo', tag='tag:foo:1') assert [node['Service']['ID'] for node in nodes] == ['foo:1']", "index, nodes = c.health.service(\"foo1\") assert nodes == [] c.agent.service.register('foo', enable_tag_override=True)", "# clean up assert c.agent.service.deregister('foo-1') is True c.acl.destroy(token, token=master_token) acls", "and queries[0]['ID'] == query['ID'] # explain query assert c.query.explain(query_name)['Query'] #", "} \"\"\" token = c.acl.create(rules=rules) assert c.acl.info(token)['Rules'] == rules token2", "c = consul.Consul(port=consul_port) c.agent.maintenance('true', \"test\") time.sleep(40/1000.0) checks_pre = c.agent.checks() assert", "x in nodes]) == set(['n2']) # test catalog.deregister pytest.raises( consul.ConsulException,", "now available index, nodes = c.health.state('passing') assert set([node['ServiceID'] for node", "catalog.datacenters assert c.catalog.datacenters() == ['dc1'] # test catalog.register pytest.raises( consul.ConsulException,", "['foo:1', 'foo:2'] # wait until the short ttl node fails", "is None compare = [c.acl.info(master_token), c.acl.info('anonymous')] compare.sort(key=operator.itemgetter('ID')) assert acls ==", "service_id='foo:1', check=Check.ttl('10s'), tags=['tag:foo:1']) c.agent.service.register( 'foo', service_id='foo:2', check=Check.ttl('100ms')) time.sleep(40/1000.0) # check", "assert leader == addr_port, \\ \"Leader value was {0}, expected", "None def test_kv_acquire_release(self, consul_port): c = consul.Consul(port=consul_port) pytest.raises( consul.ConsulException, c.kv.put,", "'true', \"test\") time.sleep(40/1000.0) checks_pre = c.agent.checks() assert '_service_maintenance:foo' in checks_pre.keys()", "time.sleep(40/1000.0) checks_post = c.agent.checks() assert '_node_maintenance' not in checks_post.keys() def", "nodes] == ['foo:1'] # deregister the nodes c.agent.service.deregister('foo:1') c.agent.service.deregister('foo:2') time.sleep(40/1000.0)", "['', 'foo:1']) # ping the failed node's health check c.agent.check.ttl_pass('service:foo:2')", "c = consul.Consul(port=consul_port) # check there are no nodes for", "pytest.raises( consul.ACLPermissionDenied, c_limited.kv.delete, 'private/foo') # check we can override the", "= c.health.service('foo', passing=True) assert [node['Service']['ID'] for node in nodes] ==", "to renew an unknown session pytest.raises(consul.NotFound, c.session.renew, '1'*36) session =", "set(c.agent.checks().keys()) == set([]) def verify_check_status(check_id, status, notes=None): checks = c.agent.checks()", "node in nodes] == [] def test_agent_checks_service_id(self, consul_port): c =", "consul_port): c = consul.Consul(port=consul_port) c.kv.put('foo1', '1') c.kv.put('foo2', '2') c.kv.put('foo3', '3')", "# Clean up tasks assert c.agent.check.deregister('foo') is True time.sleep(40/1000.0) assert", "c.query.list() assert queries == [] # create a new named", "events] def test_agent_checks(self, consul_port): c = consul.Consul(port=consul_port) def verify_and_dereg_check(check_id): assert", "\"foo-\" { policy = \"write\" } service \"bar-\" { policy", "name queries = c.query.get(query['ID']) assert queries != [] \\ and", "assert node is None # test catalog.service pytest.raises( consul.ConsulException, c.catalog.service,", "time.sleep(80/1000.0) index, nodes = c.health.service(service_name) assert [node['Service']['ID'] for node in", "assert [node['ServiceID'] for node in nodes] == [''] # register", "for k, v in c.agent.services().items() if k == 'foo'][0] ==", "True # test catalog.nodes pytest.raises(consul.ConsulException, c.catalog.nodes, dc='dc2') _, nodes =", "tasks c.agent.check.deregister('foo') time.sleep(40/1000.0) def test_agent_register_enable_tag_override(self, consul_port): c = consul.Consul(port=consul_port) index,", "can override the client's default token pytest.raises( consul.ACLPermissionDenied, c.kv.get, 'private/foo',", "is True assert c.kv.put('base/foo', '1') is True assert c.kv.put('base/base/foo', '5')", "consul_port): c = consul.Consul(port=consul_port) # check that query list is", "removed _, nodes = c.catalog.nodes() nodes.remove(current) assert [x['Node'] for x", "is None index, session = c.session.info(session_id) assert session['Name'] == 'my-session'", "== [] # ping the two node's health check c.agent.check.ttl_pass('service:foo:1')", "rules assert c.acl.update(token2, name='Foo') == token2 assert c.acl.info(token2)['Name'] == 'Foo'", "None # test catalog.service pytest.raises( consul.ConsulException, c.catalog.service, 's1', dc='dc2') _,", "for x in nodes] == ['n1', 'n2'] # check n2's", "== set( ['', 'foo:1', 'foo:2']) # but that they aren't", "= 'foo' query_name = 'fooquery' query = c.query.create(query_service, query_name) #", "set([x['ID'] for x in acls]) == \\ set(['anonymous', master_token]) def", "c = consul.Consul(port=consul_port) pytest.raises( consul.ConsulException, c.kv.put, 'foo', 'bar', acquire='foo') s1", "False voter = False for server in config[\"Servers\"]: if server[\"Leader\"]:", "the short ttl node fails time.sleep(120/1000.0) # only one node", "index, data = c.health.checks('foo-1', token=token) assert data == [] index,", "catalog.service pytest.raises( consul.ConsulException, c.catalog.service, 's1', dc='dc2') _, nodes = c.catalog.service('s1')", "in wan_members: assert 'dc1' in x['Name'] def test_agent_self(self, consul_port): c", "= c.kv.get('foo') assert data['Value'] is None # check unencoded values", "dc='dc2') _, node = c.catalog.node('n1') assert set(node['Services'].keys()) == set(['s1', 's2'])", "# ping the two node's health check c.agent.check.ttl_pass('service:foo:1') c.agent.check.ttl_pass('service:foo:2') time.sleep(40/1000.0)", "consul_port): c = consul.Consul(port=consul_port) assert c.kv.put('bar', '4') is True assert", "index, data = c.kv.get('base/', keys=True, separator='/') assert data == ['base/base/',", "for node in nodes] == [''] def test_health_node(self, consul_port): c", "c_limited.kv.delete, 'foo') assert c.kv.get('private/foo')[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c_limited.kv.get, 'private/foo')", "consul.Consul(port=consul_port) assert c.kv.put('foo', 'bar', cas=50) is False assert c.kv.put('foo', 'bar',", "set(['anonymous', master_token]) assert c.acl.info('foo') is None compare = [c.acl.info(master_token), c.acl.info('anonymous')]", "[node['Service']['ID'] for node in nodes] == ['foo:1'] # deregister the", "dc='dc2') _, services = c.catalog.services() assert services == {'s1': [u'master'],", "is True c.session.destroy(s1) c.session.destroy(s2) def test_kv_keys_only(self, consul_port): c = consul.Consul(port=consul_port)", "c = consul.Consul(port=acl_consul.port) pytest.raises(consul.ACLPermissionDenied, c.acl.list) pytest.raises(consul.ACLPermissionDenied, c.acl.create) pytest.raises(consul.ACLPermissionDenied, c.acl.update, 'anonymous')", "set(c.agent.checks().keys()) == set([]) assert c.agent.check.register( 'script_check', Check.script('/bin/true', 10)) is True", "key \"\" { policy = \"read\" } key \"private/\" {", "c.acl.info('foo') is None compare = [c.acl.info(master_token), c.acl.info('anonymous')] compare.sort(key=operator.itemgetter('ID')) assert acls", "is None def test_acl_disabled(self, consul_port): c = consul.Consul(port=consul_port) pytest.raises(consul.ACLDisabled, c.acl.list)", "cas=data['ModifyIndex']) is True index, data = c.kv.get('foo') assert data is", "for x in events] def test_event_targeted(self, consul_port): c = consul.Consul(port=consul_port)", "ttl, the other shorter c.agent.service.register( 'foo', service_id='foo:1', check=Check.ttl('10s'), tags=['tag:foo:1']) c.agent.service.register(", "[] \\ and len(queries) == 1 assert queries[0]['Name'] == query_name", "def test_acl_permission_denied(self, acl_consul): c = consul.Consul(port=acl_consul.port) pytest.raises(consul.ACLPermissionDenied, c.acl.list) pytest.raises(consul.ACLPermissionDenied, c.acl.create)", "'100ms', timeout='2s')) is True verify_and_dereg_check('http_timeout_check') assert c.agent.check.register('ttl_check', Check.ttl('100ms')) is True", "c.catalog.node('n3') assert node is None # test catalog.service pytest.raises( consul.ConsulException,", "assert c.acl.destroy(token2, token=master_token) is True assert c.acl.info(token2) is None c.kv.put('foo',", "for server in config[\"Servers\"]: if server[\"Leader\"]: leader = True if", "in checks_pre.keys() assert 'test' == checks_pre['_service_maintenance:foo']['Notes'] c.agent.service.maintenance('foo', 'false') time.sleep(40/1000.0) checks_post", "c.kv.put('private/foo', 'bar') assert c.kv.get('foo', token=token)[1]['Value'] == six.b('bar') pytest.raises( consul.ACLPermissionDenied, c.kv.put,", "policy = \"read\" } key \"private/\" { policy = \"deny\"", "= \"\"\" key \"\" { policy = \"read\" } key", "'1', release='foo') is False assert c.kv.put('foo', '2', release=s2) is False", "operator import struct import time import pytest import six import", "'_node_maintenance' in checks_pre.keys() assert 'test' == checks_pre['_node_maintenance']['Notes'] c.agent.maintenance('false') time.sleep(40/1000.0) checks_post", "1 current = nodes[0] # test catalog.datacenters assert c.catalog.datacenters() ==", "index, data = c.kv.get('foo') assert data['Value'] == six.b('bar') # test", "consul.Check class TestHTTPClient(object): def test_uri(self): http = consul.std.HTTPClient() assert http.uri('/v1/kv')", "consul_port): c = consul.Consul(port=consul_port) # session.create pytest.raises(consul.ConsulException, c.session.create, node='n2') pytest.raises(consul.ConsulException,", "index, nodes = c.health.service('foo') assert [node['Service']['ID'] for node in nodes]", "assert [x['Node'] for x in nodes] == ['n1', 'n2'] #", "assert [node['Service']['ID'] for node in nodes] == ['foo:1'] # deregister", "assert r[\"Errors\"] is None d = {\"KV\": {\"Verb\": \"get\", \"Key\":", "consul.std Check = consul.Check class TestHTTPClient(object): def test_uri(self): http =", "c = consul.Consul(port=consul_port) # The empty string is for the", "c.kv.put('foo/bar1', '1') c.kv.put('foo/bar2', '2') c.kv.put('foo/bar3', '3') index, data = c.kv.get('foo/',", "token=token) pytest.raises( consul.ACLPermissionDenied, c.kv.delete, 'private/foo', token=token) # test token pass", "c.kv.put('foo/bar2', '2') c.kv.put('foo/bar3', '3') index, data = c.kv.get('foo/', recurse=True) assert", "data = c.kv.get('foo') assert data is None def test_acl_disabled(self, consul_port):", "is True assert [ v['Address'] for k, v in c.agent.services().items()", "token pass through for service registration pytest.raises( consul.ACLPermissionDenied, c.agent.service.register, \"bar-1\",", "== 1 c.kv.put('foo/bar1', '1') c.kv.put('foo/bar2', '2') c.kv.put('foo/bar3', '3') index, data", "nodes] != 'foo' # ping the two node's health check", "c.acl.update, 'foo') pytest.raises(consul.ACLDisabled, c.acl.clone, 'foo') pytest.raises(consul.ACLDisabled, c.acl.destroy, 'foo') def test_acl_permission_denied(self,", "key \"private/\" { policy = \"deny\" } service \"foo-\" {", "'passing') assert c.agent.check.ttl_pass( 'ttl_check', notes='all hunky dory!') is True verify_check_status('ttl_check',", "c.kv.get('foo') assert data['Value'] == six.b('bar2') def test_kv_put_flags(self, consul_port): c =", "address='10.10.10.1') is True assert [ v['Address'] for k, v in", "is None c.kv.put('foo', 'bar') c.kv.put('private/foo', 'bar') c_limited = consul.Consul(port=acl_consul.port, token=token)", "comes back as `None` c.kv.put('foo', '') index, data = c.kv.get('foo')", "The empty string is for the Serf Health Status check,", "is True def test_catalog(self, consul_port): c = consul.Consul(port=consul_port) # grab", "_, sessions = c.session.list() assert [x['Name'] for x in sessions]", "other shorter c.agent.service.register( 'foo', service_id='foo:1', check=Check.ttl('10s')) c.agent.service.register( 'foo', service_id='foo:2', check=Check.ttl('100ms'))", "c.acl.info(token2) is None c.kv.put('foo', 'bar') c.kv.put('private/foo', 'bar') assert c.kv.get('foo', token=token)[1]['Value']", "nodes = c.health.service('foo') assert [node['Service']['ID'] for node in nodes] ==", "== \"foo-1\" index, data = c.health.checks('foo-1', token=token) assert data ==", "\\ \"Leader value was {0}, expected value \" \\ \"was", "session.destroy pytest.raises( consul.ConsulException, c.session.destroy, session_id, dc='dc2') assert c.session.destroy(session_id) is True", "cas=data['ModifyIndex']-1) is False assert c.kv.put('foo', 'bar2', cas=data['ModifyIndex']) is True index,", "consul.Consul(port=consul_port) # grab the node our server created, so we", "register two nodes, one with a long ttl, the other", "notes # test setting notes on a check c.agent.check.register('check', Check.ttl('1s'),", "until the short ttl node fails time.sleep(2200/1000.0) # only one", "through for service registration pytest.raises( consul.ACLPermissionDenied, c.agent.service.register, \"bar-1\", token=token) c.agent.service.register(\"foo-1\",", "c.acl.clone, 'anonymous') pytest.raises(consul.ACLPermissionDenied, c.acl.destroy, 'anonymous') def test_acl_explict_token_use(self, acl_consul): c =" ]
[ "int(math.sqrt(n))+1,2)) tot = 1 dia = 0 for side_length in", "False if n % 2 == 0 and n >", "2 == 0 and n > 2: return False return", "side_length**2 for i in range(4): if is_prime(hi-i*side_length+i): dia = dia+1", "1: return False if n % 2 == 0 and", "= dia+1 tot = tot+4 if dia/tot < 0.1: print(side_length)", "= 1 dia = 0 for side_length in range(3,100001,2): hi", "if n == 1: return False if n % 2", "dia = 0 for side_length in range(3,100001,2): hi = side_length**2", "tot = 1 dia = 0 for side_length in range(3,100001,2):", "range(4): if is_prime(hi-i*side_length+i): dia = dia+1 tot = tot+4 if", "0 for side_length in range(3,100001,2): hi = side_length**2 for i", "all(n % i for i in range(3, int(math.sqrt(n))+1,2)) tot =", "in range(3, int(math.sqrt(n))+1,2)) tot = 1 dia = 0 for", "range(3,100001,2): hi = side_length**2 for i in range(4): if is_prime(hi-i*side_length+i):", "i for i in range(3, int(math.sqrt(n))+1,2)) tot = 1 dia", "<filename>Q58/sol.py import math def is_prime(n): if n == 1: return", "return False if n % 2 == 0 and n", "for side_length in range(3,100001,2): hi = side_length**2 for i in", "hi = side_length**2 for i in range(4): if is_prime(hi-i*side_length+i): dia", "== 0 and n > 2: return False return all(n", "% i for i in range(3, int(math.sqrt(n))+1,2)) tot = 1", "dia = dia+1 tot = tot+4 if dia/tot < 0.1:", "if n % 2 == 0 and n > 2:", "range(3, int(math.sqrt(n))+1,2)) tot = 1 dia = 0 for side_length", "import math def is_prime(n): if n == 1: return False", "1 dia = 0 for side_length in range(3,100001,2): hi =", "False return all(n % i for i in range(3, int(math.sqrt(n))+1,2))", "i in range(3, int(math.sqrt(n))+1,2)) tot = 1 dia = 0", "n == 1: return False if n % 2 ==", "in range(4): if is_prime(hi-i*side_length+i): dia = dia+1 tot = tot+4", "is_prime(hi-i*side_length+i): dia = dia+1 tot = tot+4 if dia/tot <", "dia+1 tot = tot+4 if dia/tot < 0.1: print(side_length) break", "is_prime(n): if n == 1: return False if n %", "n > 2: return False return all(n % i for", "for i in range(4): if is_prime(hi-i*side_length+i): dia = dia+1 tot", "== 1: return False if n % 2 == 0", "math def is_prime(n): if n == 1: return False if", "if is_prime(hi-i*side_length+i): dia = dia+1 tot = tot+4 if dia/tot", "n % 2 == 0 and n > 2: return", "% 2 == 0 and n > 2: return False", "= 0 for side_length in range(3,100001,2): hi = side_length**2 for", "and n > 2: return False return all(n % i", "0 and n > 2: return False return all(n %", "i in range(4): if is_prime(hi-i*side_length+i): dia = dia+1 tot =", "def is_prime(n): if n == 1: return False if n", "2: return False return all(n % i for i in", "return False return all(n % i for i in range(3,", "return all(n % i for i in range(3, int(math.sqrt(n))+1,2)) tot", "> 2: return False return all(n % i for i", "in range(3,100001,2): hi = side_length**2 for i in range(4): if", "for i in range(3, int(math.sqrt(n))+1,2)) tot = 1 dia =", "side_length in range(3,100001,2): hi = side_length**2 for i in range(4):", "= side_length**2 for i in range(4): if is_prime(hi-i*side_length+i): dia =" ]
[ "одежды. Основная сущность (класс) этого проекта — одежда, которая может", "классы для основных классов проекта, проверить на практике работу декоратора", "(V/6.5 + 0.5), для костюма (2 * H + 0.3).", "для основных классов проекта, проверить на практике работу декоратора @property.", "(для пальто) и рост (для костюма). Это могут быть обычные", "Coat(Clothes): def __init__(self, h): self.h = h @property def need_material(self):", "self.h + 0.3) if __name__ == '__main__': print(task) objects =", "__init__(self, v): self.v = v @property def need_material(self): return (self.v", "костюм. У этих типов одежды существуют параметры: размер (для пальто)", "одежды использовать формулы: для пальто (V/6.5 + 0.5), для костюма", "] need_material = 0 for obj in objects: if isinstance(obj,", "raise NotImplementedError(\"Необходимо переопределить метод\") class Costume(Clothes): def __init__(self, v): self.v", "общий подсчет расхода ткани. Проверить на практике полученные на этом", "need_material(self): return (self.v / 6.5 + 0.5) class Coat(Clothes): def", "@property def need_material(self): return (self.v / 6.5 + 0.5) class", "def __init__(self, h): self.h = h @property def need_material(self): return", "определенное название. К типам одежды в этом проекте относятся пальто", "need_material = 0 for obj in objects: if isinstance(obj, Clothes):", "class Clothes: @property def need_material(self): raise NotImplementedError(\"Необходимо переопределить метод\") class", "Clothes: @property def need_material(self): raise NotImplementedError(\"Необходимо переопределить метод\") class Costume(Clothes):", "H + 0.3). Проверить работу этих методов на реальных данных.", "проекта — одежда, которая может иметь определенное название. К типам", "и рост (для костюма). Это могут быть обычные числа: V", "типу одежды использовать формулы: для пальто (V/6.5 + 0.5), для", "''' class Clothes: @property def need_material(self): raise NotImplementedError(\"Необходимо переопределить метод\")", "данных. Реализовать общий подсчет расхода ткани. Проверить на практике полученные", "практике полученные на этом уроке знания: реализовать абстрактные классы для", "на практике полученные на этом уроке знания: реализовать абстрактные классы", "метод\") class Costume(Clothes): def __init__(self, v): self.v = v @property", "= ''' Реализовать проект расчета суммарного расхода ткани на производство", "— одежда, которая может иметь определенное название. К типам одежды", "по каждому типу одежды использовать формулы: для пальто (V/6.5 +", "которая может иметь определенное название. К типам одежды в этом", "6.5 + 0.5) class Coat(Clothes): def __init__(self, h): self.h =", "+ 0.5) class Coat(Clothes): def __init__(self, h): self.h = h", "классов проекта, проверить на практике работу декоратора @property. ''' class", "(self.v / 6.5 + 0.5) class Coat(Clothes): def __init__(self, h):", "расчета суммарного расхода ткани на производство одежды. Основная сущность (класс)", "размер (для пальто) и рост (для костюма). Это могут быть", "работу этих методов на реальных данных. Реализовать общий подсчет расхода", "NotImplementedError(\"Необходимо переопределить метод\") class Costume(Clothes): def __init__(self, v): self.v =", "* H + 0.3). Проверить работу этих методов на реальных", "производство одежды. Основная сущность (класс) этого проекта — одежда, которая", "одежды в этом проекте относятся пальто и костюм. У этих", "может иметь определенное название. К типам одежды в этом проекте", "одежда, которая может иметь определенное название. К типам одежды в", "полученные на этом уроке знания: реализовать абстрактные классы для основных", "этого проекта — одежда, которая может иметь определенное название. К", "абстрактные классы для основных классов проекта, проверить на практике работу", "+ 0.3). Проверить работу этих методов на реальных данных. Реализовать", "иметь определенное название. К типам одежды в этом проекте относятся", "этих типов одежды существуют параметры: размер (для пальто) и рост", "сущность (класс) этого проекта — одежда, которая может иметь определенное", "на производство одежды. Основная сущность (класс) этого проекта — одежда,", "К типам одежды в этом проекте относятся пальто и костюм.", "каждому типу одежды использовать формулы: для пальто (V/6.5 + 0.5),", "обычные числа: V и H, соответственно. Для определения расхода ткани", "class Coat(Clothes): def __init__(self, h): self.h = h @property def", "= 0 for obj in objects: if isinstance(obj, Clothes): need_material", "Реализовать проект расчета суммарного расхода ткани на производство одежды. Основная", "ткани по каждому типу одежды использовать формулы: для пальто (V/6.5", "need_material(self): return (2 * self.h + 0.3) if __name__ ==", "проекте относятся пальто и костюм. У этих типов одежды существуют", "расхода ткани по каждому типу одежды использовать формулы: для пальто", "0.3). Проверить работу этих методов на реальных данных. Реализовать общий", "на этом уроке знания: реализовать абстрактные классы для основных классов", "Coat(32), 'test', True, Costume(87), Coat(32) ] need_material = 0 for", "'test', True, Costume(87), Coat(32) ] need_material = 0 for obj", "уроке знания: реализовать абстрактные классы для основных классов проекта, проверить", "V и H, соответственно. Для определения расхода ткани по каждому", "и H, соответственно. Для определения расхода ткани по каждому типу", "пальто) и рост (для костюма). Это могут быть обычные числа:", "основных классов проекта, проверить на практике работу декоратора @property. '''", "Это могут быть обычные числа: V и H, соответственно. Для", "ткани на производство одежды. Основная сущность (класс) этого проекта —", "проекта, проверить на практике работу декоратора @property. ''' class Clothes:", "костюма (2 * H + 0.3). Проверить работу этих методов", "соответственно. Для определения расхода ткани по каждому типу одежды использовать", "Реализовать общий подсчет расхода ткани. Проверить на практике полученные на", "одежды существуют параметры: размер (для пальто) и рост (для костюма).", "= [ 231, 22, Coat(32), 'test', True, Costume(87), Coat(32) ]", "типов одежды существуют параметры: размер (для пальто) и рост (для", "def __init__(self, v): self.v = v @property def need_material(self): return", "пальто и костюм. У этих типов одежды существуют параметры: размер", "Основная сущность (класс) этого проекта — одежда, которая может иметь", "Для определения расхода ткани по каждому типу одежды использовать формулы:", "реальных данных. Реализовать общий подсчет расхода ткани. Проверить на практике", "@property. ''' class Clothes: @property def need_material(self): raise NotImplementedError(\"Необходимо переопределить", "для костюма (2 * H + 0.3). Проверить работу этих", "@property def need_material(self): raise NotImplementedError(\"Необходимо переопределить метод\") class Costume(Clothes): def", "в этом проекте относятся пальто и костюм. У этих типов", "(2 * self.h + 0.3) if __name__ == '__main__': print(task)", "'__main__': print(task) objects = [ 231, 22, Coat(32), 'test', True,", "__init__(self, h): self.h = h @property def need_material(self): return (2", "знания: реализовать абстрактные классы для основных классов проекта, проверить на", "Проверить на практике полученные на этом уроке знания: реализовать абстрактные", "проверить на практике работу декоратора @property. ''' class Clothes: @property", "этом уроке знания: реализовать абстрактные классы для основных классов проекта,", "параметры: размер (для пальто) и рост (для костюма). Это могут", "0 for obj in objects: if isinstance(obj, Clothes): need_material +=", "self.v = v @property def need_material(self): return (self.v / 6.5", "на реальных данных. Реализовать общий подсчет расхода ткани. Проверить на", "for obj in objects: if isinstance(obj, Clothes): need_material += obj.need_material", "''' Реализовать проект расчета суммарного расхода ткани на производство одежды.", "(для костюма). Это могут быть обычные числа: V и H,", "для пальто (V/6.5 + 0.5), для костюма (2 * H", "формулы: для пальто (V/6.5 + 0.5), для костюма (2 *", "Проверить работу этих методов на реальных данных. Реализовать общий подсчет", "этом проекте относятся пальто и костюм. У этих типов одежды", "need_material(self): raise NotImplementedError(\"Необходимо переопределить метод\") class Costume(Clothes): def __init__(self, v):", "[ 231, 22, Coat(32), 'test', True, Costume(87), Coat(32) ] need_material", "H, соответственно. Для определения расхода ткани по каждому типу одежды", "v): self.v = v @property def need_material(self): return (self.v /", "v @property def need_material(self): return (self.v / 6.5 + 0.5)", "суммарного расхода ткани на производство одежды. Основная сущность (класс) этого", "+ 0.3) if __name__ == '__main__': print(task) objects = [", "def need_material(self): raise NotImplementedError(\"Необходимо переопределить метод\") class Costume(Clothes): def __init__(self,", "__name__ == '__main__': print(task) objects = [ 231, 22, Coat(32),", "могут быть обычные числа: V и H, соответственно. Для определения", "task = ''' Реализовать проект расчета суммарного расхода ткани на", "расхода ткани. Проверить на практике полученные на этом уроке знания:", "ткани. Проверить на практике полученные на этом уроке знания: реализовать", "True, Costume(87), Coat(32) ] need_material = 0 for obj in", "h): self.h = h @property def need_material(self): return (2 *", "obj in objects: if isinstance(obj, Clothes): need_material += obj.need_material print(need_material)", "подсчет расхода ткани. Проверить на практике полученные на этом уроке", "(2 * H + 0.3). Проверить работу этих методов на", "0.3) if __name__ == '__main__': print(task) objects = [ 231,", "быть обычные числа: V и H, соответственно. Для определения расхода", "этих методов на реальных данных. Реализовать общий подсчет расхода ткани.", "return (2 * self.h + 0.3) if __name__ == '__main__':", "название. К типам одежды в этом проекте относятся пальто и", "+ 0.5), для костюма (2 * H + 0.3). Проверить", "проект расчета суммарного расхода ткани на производство одежды. Основная сущность", "@property def need_material(self): return (2 * self.h + 0.3) if", "def need_material(self): return (self.v / 6.5 + 0.5) class Coat(Clothes):", "и костюм. У этих типов одежды существуют параметры: размер (для", "= h @property def need_material(self): return (2 * self.h +", "пальто (V/6.5 + 0.5), для костюма (2 * H +", "существуют параметры: размер (для пальто) и рост (для костюма). Это", "относятся пальто и костюм. У этих типов одежды существуют параметры:", "переопределить метод\") class Costume(Clothes): def __init__(self, v): self.v = v", "определения расхода ткани по каждому типу одежды использовать формулы: для", "self.h = h @property def need_material(self): return (2 * self.h", "костюма). Это могут быть обычные числа: V и H, соответственно.", "if __name__ == '__main__': print(task) objects = [ 231, 22,", "Coat(32) ] need_material = 0 for obj in objects: if", "0.5), для костюма (2 * H + 0.3). Проверить работу", "0.5) class Coat(Clothes): def __init__(self, h): self.h = h @property", "декоратора @property. ''' class Clothes: @property def need_material(self): raise NotImplementedError(\"Необходимо", "h @property def need_material(self): return (2 * self.h + 0.3)", "* self.h + 0.3) if __name__ == '__main__': print(task) objects", "== '__main__': print(task) objects = [ 231, 22, Coat(32), 'test',", "/ 6.5 + 0.5) class Coat(Clothes): def __init__(self, h): self.h", "Costume(87), Coat(32) ] need_material = 0 for obj in objects:", "class Costume(Clothes): def __init__(self, v): self.v = v @property def", "= v @property def need_material(self): return (self.v / 6.5 +", "на практике работу декоратора @property. ''' class Clothes: @property def", "практике работу декоратора @property. ''' class Clothes: @property def need_material(self):", "У этих типов одежды существуют параметры: размер (для пальто) и", "def need_material(self): return (2 * self.h + 0.3) if __name__", "использовать формулы: для пальто (V/6.5 + 0.5), для костюма (2", "Costume(Clothes): def __init__(self, v): self.v = v @property def need_material(self):", "print(task) objects = [ 231, 22, Coat(32), 'test', True, Costume(87),", "22, Coat(32), 'test', True, Costume(87), Coat(32) ] need_material = 0", "return (self.v / 6.5 + 0.5) class Coat(Clothes): def __init__(self,", "расхода ткани на производство одежды. Основная сущность (класс) этого проекта", "работу декоратора @property. ''' class Clothes: @property def need_material(self): raise", "(класс) этого проекта — одежда, которая может иметь определенное название.", "231, 22, Coat(32), 'test', True, Costume(87), Coat(32) ] need_material =", "типам одежды в этом проекте относятся пальто и костюм. У", "objects = [ 231, 22, Coat(32), 'test', True, Costume(87), Coat(32)", "реализовать абстрактные классы для основных классов проекта, проверить на практике", "числа: V и H, соответственно. Для определения расхода ткани по", "методов на реальных данных. Реализовать общий подсчет расхода ткани. Проверить", "рост (для костюма). Это могут быть обычные числа: V и" ]
[ "request.replace(config.fanart.api_key, 'XXX'), 'DEBUG') headers = {'Accept': 'application/json'} _request = urllib2.Request(request,", "def __request(request): log('Send Fanart Request: ' + request.replace(config.fanart.api_key, 'XXX'), 'DEBUG')", "__request(req) except urllib2.HTTPError: n += 1 try_again = True log('Ooops..", "except urllib2.HTTPError: n += 1 try_again = True log('Ooops.. FanartTV", "try_again = True n = 0 while try_again and n", "from core.helpers.logger import log, LogLevel @Cached def __request(request): log('Send Fanart", "'DEBUG') headers = {'Accept': 'application/json'} _request = urllib2.Request(request, headers=headers) response_body", "urllib2.HTTPError: n += 1 try_again = True log('Ooops.. FanartTV Error", "'application/json'} _request = urllib2.Request(request, headers=headers) response_body = urllib2.urlopen(_request).read() result =", "FanartTV Error - Try again', LogLevel.Warning) time.sleep(2) def get_movie(tmdb_id): return", "= urllib2.urlopen(_request).read() result = json.loads(response_body) return result def _get(video_type, movie_id,", "0 while try_again and n < 10: try: return __request(req)", "from core.helpers.config import config from core.helpers.logger import log, LogLevel @Cached", "@Cached def __request(request): log('Send Fanart Request: ' + request.replace(config.fanart.api_key, 'XXX'),", "+= 1 try_again = True log('Ooops.. FanartTV Error - Try", "log('Send Fanart Request: ' + request.replace(config.fanart.api_key, 'XXX'), 'DEBUG') headers =", "try: return __request(req) except urllib2.HTTPError: n += 1 try_again =", "return result def _get(video_type, movie_id, output_format='JSON'): req = '{0}{1}/{2}/{3}/{4}'.format(config.fanart.url_base, video_type,", "= True log('Ooops.. FanartTV Error - Try again', LogLevel.Warning) time.sleep(2)", "again', LogLevel.Warning) time.sleep(2) def get_movie(tmdb_id): return _get(video_type='movie', movie_id=tmdb_id) def get_show(tvdb_id):", "core.helpers.logger import log, LogLevel @Cached def __request(request): log('Send Fanart Request:", "time.sleep(2) def get_movie(tmdb_id): return _get(video_type='movie', movie_id=tmdb_id) def get_show(tvdb_id): return _get(video_type='series',", "core.helpers.config import config from core.helpers.logger import log, LogLevel @Cached def", "+ request.replace(config.fanart.api_key, 'XXX'), 'DEBUG') headers = {'Accept': 'application/json'} _request =", "n += 1 try_again = True log('Ooops.. FanartTV Error -", "= urllib2.Request(request, headers=headers) response_body = urllib2.urlopen(_request).read() result = json.loads(response_body) return", "- Try again', LogLevel.Warning) time.sleep(2) def get_movie(tmdb_id): return _get(video_type='movie', movie_id=tmdb_id)", "while try_again and n < 10: try: return __request(req) except", "'XXX'), 'DEBUG') headers = {'Accept': 'application/json'} _request = urllib2.Request(request, headers=headers)", "video_type, config.fanart.api_key, movie_id, output_format) try_again = True n = 0", "output_format) try_again = True n = 0 while try_again and", "config from core.helpers.logger import log, LogLevel @Cached def __request(request): log('Send", "req = '{0}{1}/{2}/{3}/{4}'.format(config.fanart.url_base, video_type, config.fanart.api_key, movie_id, output_format) try_again = True", "LogLevel.Warning) time.sleep(2) def get_movie(tmdb_id): return _get(video_type='movie', movie_id=tmdb_id) def get_show(tvdb_id): return", "headers=headers) response_body = urllib2.urlopen(_request).read() result = json.loads(response_body) return result def", "movie_id, output_format) try_again = True n = 0 while try_again", "urllib2 import json import time from core.helpers.decorator import Cached from", "_request = urllib2.Request(request, headers=headers) response_body = urllib2.urlopen(_request).read() result = json.loads(response_body)", "result def _get(video_type, movie_id, output_format='JSON'): req = '{0}{1}/{2}/{3}/{4}'.format(config.fanart.url_base, video_type, config.fanart.api_key,", "import Cached from core.helpers.config import config from core.helpers.logger import log,", "import time from core.helpers.decorator import Cached from core.helpers.config import config", "'{0}{1}/{2}/{3}/{4}'.format(config.fanart.url_base, video_type, config.fanart.api_key, movie_id, output_format) try_again = True n =", "def _get(video_type, movie_id, output_format='JSON'): req = '{0}{1}/{2}/{3}/{4}'.format(config.fanart.url_base, video_type, config.fanart.api_key, movie_id,", "= '{0}{1}/{2}/{3}/{4}'.format(config.fanart.url_base, video_type, config.fanart.api_key, movie_id, output_format) try_again = True n", "def get_movie(tmdb_id): return _get(video_type='movie', movie_id=tmdb_id) def get_show(tvdb_id): return _get(video_type='series', movie_id=tvdb_id)", "try_again = True log('Ooops.. FanartTV Error - Try again', LogLevel.Warning)", "_get(video_type, movie_id, output_format='JSON'): req = '{0}{1}/{2}/{3}/{4}'.format(config.fanart.url_base, video_type, config.fanart.api_key, movie_id, output_format)", "' + request.replace(config.fanart.api_key, 'XXX'), 'DEBUG') headers = {'Accept': 'application/json'} _request", "and n < 10: try: return __request(req) except urllib2.HTTPError: n", "output_format='JSON'): req = '{0}{1}/{2}/{3}/{4}'.format(config.fanart.url_base, video_type, config.fanart.api_key, movie_id, output_format) try_again =", "Request: ' + request.replace(config.fanart.api_key, 'XXX'), 'DEBUG') headers = {'Accept': 'application/json'}", "__request(request): log('Send Fanart Request: ' + request.replace(config.fanart.api_key, 'XXX'), 'DEBUG') headers", "headers = {'Accept': 'application/json'} _request = urllib2.Request(request, headers=headers) response_body =", "= {'Accept': 'application/json'} _request = urllib2.Request(request, headers=headers) response_body = urllib2.urlopen(_request).read()", "log('Ooops.. FanartTV Error - Try again', LogLevel.Warning) time.sleep(2) def get_movie(tmdb_id):", "import log, LogLevel @Cached def __request(request): log('Send Fanart Request: '", "import json import time from core.helpers.decorator import Cached from core.helpers.config", "<gh_stars>0 import urllib2 import json import time from core.helpers.decorator import", "< 10: try: return __request(req) except urllib2.HTTPError: n += 1", "= 0 while try_again and n < 10: try: return", "1 try_again = True log('Ooops.. FanartTV Error - Try again',", "import urllib2 import json import time from core.helpers.decorator import Cached", "import config from core.helpers.logger import log, LogLevel @Cached def __request(request):", "urllib2.urlopen(_request).read() result = json.loads(response_body) return result def _get(video_type, movie_id, output_format='JSON'):", "return __request(req) except urllib2.HTTPError: n += 1 try_again = True", "urllib2.Request(request, headers=headers) response_body = urllib2.urlopen(_request).read() result = json.loads(response_body) return result", "core.helpers.decorator import Cached from core.helpers.config import config from core.helpers.logger import", "result = json.loads(response_body) return result def _get(video_type, movie_id, output_format='JSON'): req", "= json.loads(response_body) return result def _get(video_type, movie_id, output_format='JSON'): req =", "log, LogLevel @Cached def __request(request): log('Send Fanart Request: ' +", "json.loads(response_body) return result def _get(video_type, movie_id, output_format='JSON'): req = '{0}{1}/{2}/{3}/{4}'.format(config.fanart.url_base,", "n = 0 while try_again and n < 10: try:", "= True n = 0 while try_again and n <", "from core.helpers.decorator import Cached from core.helpers.config import config from core.helpers.logger", "True log('Ooops.. FanartTV Error - Try again', LogLevel.Warning) time.sleep(2) def", "response_body = urllib2.urlopen(_request).read() result = json.loads(response_body) return result def _get(video_type,", "config.fanart.api_key, movie_id, output_format) try_again = True n = 0 while", "{'Accept': 'application/json'} _request = urllib2.Request(request, headers=headers) response_body = urllib2.urlopen(_request).read() result", "movie_id, output_format='JSON'): req = '{0}{1}/{2}/{3}/{4}'.format(config.fanart.url_base, video_type, config.fanart.api_key, movie_id, output_format) try_again", "LogLevel @Cached def __request(request): log('Send Fanart Request: ' + request.replace(config.fanart.api_key,", "True n = 0 while try_again and n < 10:", "time from core.helpers.decorator import Cached from core.helpers.config import config from", "json import time from core.helpers.decorator import Cached from core.helpers.config import", "Try again', LogLevel.Warning) time.sleep(2) def get_movie(tmdb_id): return _get(video_type='movie', movie_id=tmdb_id) def", "n < 10: try: return __request(req) except urllib2.HTTPError: n +=", "Fanart Request: ' + request.replace(config.fanart.api_key, 'XXX'), 'DEBUG') headers = {'Accept':", "10: try: return __request(req) except urllib2.HTTPError: n += 1 try_again", "try_again and n < 10: try: return __request(req) except urllib2.HTTPError:", "Error - Try again', LogLevel.Warning) time.sleep(2) def get_movie(tmdb_id): return _get(video_type='movie',", "Cached from core.helpers.config import config from core.helpers.logger import log, LogLevel" ]
[ "| |averagely colourful | 45 | |quite colourful | 59", "from math import log10, sqrt import cv2 import numpy as", "Returns ------- PSNR score ''' mse = np.mean((original - compressed)", "et al., section 7 rg = R - G yb", "M def main(): import matplotlib.pyplot as plt original = cv2.imread(\"test_imgs/original_image.png\")", "import matplotlib.pyplot as plt original = cv2.imread(\"test_imgs/original_image.png\") compressed = cv2.imread(\"test_imgs/compressed_image1.png\",", "| 82 | |extremely colourful | 109 | ----------------------------- \"\"\"", "|not colourful | 0 | |slightly colorful | 15 |", "= cv2.imread(\"test_imgs/original_image.png\") compressed = cv2.imread(\"test_imgs/compressed_image1.png\", 1) value = PSNR(original, compressed)", "compressed) ** 2) if(mse == 0): # MSE is zero", "---------- img : cv2 RGB image Returns ------- M :", "psnr = 20 * log10(max_pixel / sqrt(mse)) return psnr def", "* log10(max_pixel / sqrt(mse)) return psnr def colourfulnessMetric(img): \"\"\" Created", "Peak signal to noise ratio between a ground truth image", "10:55:16 2021 @author: Yucheng Parameters ---------- img : cv2 RGB", ": colourness metric ----------------------------- |not colourful | 0 | |slightly", "| 0 | |slightly colorful | 15 | |moderately colourful", "noise is present in the signal . # Therefore PSNR", "sqrt(mse)) return psnr def colourfulnessMetric(img): \"\"\" Created on Mon Nov", "- compressed) ** 2) if(mse == 0): # MSE is", "as plt original = cv2.imread(\"test_imgs/original_image.png\") compressed = cv2.imread(\"test_imgs/compressed_image1.png\", 1) value", "return 100 max_pixel = 255.0 psnr = 20 * log10(max_pixel", "img2 = cv2.imread(\"rainbow.jpg\") # opens as BGR img2 = cv2.cvtColor(img2,", "cv2.imread(\"test_imgs/compressed_image1.png\", 1) value = PSNR(original, compressed) print(f\"PSNR value is {value}", "in the signal . # Therefore PSNR have no importance.", "------- M : colourness metric ----------------------------- |not colourful | 0", "15 | |moderately colourful | 33 | |averagely colourful |", "1) value = PSNR(original, compressed) print(f\"PSNR value is {value} dB\")", "ground truth image and predicted image. see https://www.geeksforgeeks.org/python-peak-signal-to-noise-ratio-psnr/ for reference", "Parameters ---------- true image (cv2 image) predicted image (cv2 image)", "Created on Mon Nov 15 10:55:16 2021 @author: Yucheng Parameters", "|highly colourful | 82 | |extremely colourful | 109 |", "np.sqrt(np.mean(rg)**2 + np.mean(yb)**2) M = sigma_rgyb + 0.3 * mu_rgyb", "2) if(mse == 0): # MSE is zero means no", "image (cv2 image) predicted image (cv2 image) Returns ------- PSNR", "psnr def colourfulnessMetric(img): \"\"\" Created on Mon Nov 15 10:55:16", "# Get RGB components R,G,B = cv2.split(img.astype(\"float\")) # colourfulness metric", "** 2) if(mse == 0): # MSE is zero means", "(R+G) - B sigma_rgyb = np.sqrt(np.var(rg) + np.var(yb)) mu_rgyb =", "colourful | 33 | |averagely colourful | 45 | |quite", "cv2.split(img.astype(\"float\")) # colourfulness metric from Hasler et al., section 7", "colourful | 82 | |extremely colourful | 109 | -----------------------------", "PSNR(original, compressed): ''' Calculates the Peak signal to noise ratio", "predicted image (cv2 image) Returns ------- PSNR score ''' mse", "----------------------------- \"\"\" # Get RGB components R,G,B = cv2.split(img.astype(\"float\")) #", "= cv2.split(img.astype(\"float\")) # colourfulness metric from Hasler et al., section", "colourness metric ----------------------------- |not colourful | 0 | |slightly colorful", "dB\") img2 = cv2.imread(\"rainbow.jpg\") # opens as BGR img2 =", "colourful | 59 | |highly colourful | 82 | |extremely", "+ 0.3 * mu_rgyb return M def main(): import matplotlib.pyplot", "the Peak signal to noise ratio between a ground truth", "is {value} dB\") img2 = cv2.imread(\"rainbow.jpg\") # opens as BGR", "img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB) plt.imshow(img2[:,:,:]) plt.show() M = colourfulnessMetric(img2) print(M)", "import cv2 import numpy as np def PSNR(original, compressed): '''", "img : cv2 RGB image Returns ------- M : colourness", "is present in the signal . # Therefore PSNR have", "| |highly colourful | 82 | |extremely colourful | 109", "np.mean(yb)**2) M = sigma_rgyb + 0.3 * mu_rgyb return M", "Get RGB components R,G,B = cv2.split(img.astype(\"float\")) # colourfulness metric from", "# Therefore PSNR have no importance. return 100 max_pixel =", "Therefore PSNR have no importance. return 100 max_pixel = 255.0", "PSNR(original, compressed) print(f\"PSNR value is {value} dB\") img2 = cv2.imread(\"rainbow.jpg\")", "return psnr def colourfulnessMetric(img): \"\"\" Created on Mon Nov 15", "metric ----------------------------- |not colourful | 0 | |slightly colorful |", "= 255.0 psnr = 20 * log10(max_pixel / sqrt(mse)) return", "/ sqrt(mse)) return psnr def colourfulnessMetric(img): \"\"\" Created on Mon", "image. see https://www.geeksforgeeks.org/python-peak-signal-to-noise-ratio-psnr/ for reference Parameters ---------- true image (cv2", "log10, sqrt import cv2 import numpy as np def PSNR(original,", "- G yb = (1/2) * (R+G) - B sigma_rgyb", "truth image and predicted image. see https://www.geeksforgeeks.org/python-peak-signal-to-noise-ratio-psnr/ for reference Parameters", "score ''' mse = np.mean((original - compressed) ** 2) if(mse", "section 7 rg = R - G yb = (1/2)", "109 | ----------------------------- \"\"\" # Get RGB components R,G,B =", "(1/2) * (R+G) - B sigma_rgyb = np.sqrt(np.var(rg) + np.var(yb))", "colorful | 15 | |moderately colourful | 33 | |averagely", "mse = np.mean((original - compressed) ** 2) if(mse == 0):", "colourfulness metric from Hasler et al., section 7 rg =", "and predicted image. see https://www.geeksforgeeks.org/python-peak-signal-to-noise-ratio-psnr/ for reference Parameters ---------- true", "zero means no noise is present in the signal .", "|moderately colourful | 33 | |averagely colourful | 45 |", "image) Returns ------- PSNR score ''' mse = np.mean((original -", "| 59 | |highly colourful | 82 | |extremely colourful", "\"\"\" # Get RGB components R,G,B = cv2.split(img.astype(\"float\")) # colourfulness", "7 rg = R - G yb = (1/2) *", "compressed) print(f\"PSNR value is {value} dB\") img2 = cv2.imread(\"rainbow.jpg\") #", "''' mse = np.mean((original - compressed) ** 2) if(mse ==", "(cv2 image) Returns ------- PSNR score ''' mse = np.mean((original", "MSE is zero means no noise is present in the", "colourful | 45 | |quite colourful | 59 | |highly", "RGB components R,G,B = cv2.split(img.astype(\"float\")) # colourfulness metric from Hasler", "plt original = cv2.imread(\"test_imgs/original_image.png\") compressed = cv2.imread(\"test_imgs/compressed_image1.png\", 1) value =", ": cv2 RGB image Returns ------- M : colourness metric", "----------------------------- |not colourful | 0 | |slightly colorful | 15", "<reponame>AndreasLH/Image-Colourization from math import log10, sqrt import cv2 import numpy", "image Returns ------- M : colourness metric ----------------------------- |not colourful", "a ground truth image and predicted image. see https://www.geeksforgeeks.org/python-peak-signal-to-noise-ratio-psnr/ for", "(cv2 image) predicted image (cv2 image) Returns ------- PSNR score", "main(): import matplotlib.pyplot as plt original = cv2.imread(\"test_imgs/original_image.png\") compressed =", "= cv2.cvtColor(img2, cv2.COLOR_BGR2RGB) plt.imshow(img2[:,:,:]) plt.show() M = colourfulnessMetric(img2) print(M) if", "Mon Nov 15 10:55:16 2021 @author: Yucheng Parameters ---------- img", "ratio between a ground truth image and predicted image. see", "have no importance. return 100 max_pixel = 255.0 psnr =", "true image (cv2 image) predicted image (cv2 image) Returns -------", "100 max_pixel = 255.0 psnr = 20 * log10(max_pixel /", "np def PSNR(original, compressed): ''' Calculates the Peak signal to", "compressed = cv2.imread(\"test_imgs/compressed_image1.png\", 1) value = PSNR(original, compressed) print(f\"PSNR value", "sqrt import cv2 import numpy as np def PSNR(original, compressed):", "between a ground truth image and predicted image. see https://www.geeksforgeeks.org/python-peak-signal-to-noise-ratio-psnr/", "| |slightly colorful | 15 | |moderately colourful | 33", "return M def main(): import matplotlib.pyplot as plt original =", "0): # MSE is zero means no noise is present", "from Hasler et al., section 7 rg = R -", "== 0): # MSE is zero means no noise is", "0.3 * mu_rgyb return M def main(): import matplotlib.pyplot as", "= cv2.imread(\"rainbow.jpg\") # opens as BGR img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)", "|averagely colourful | 45 | |quite colourful | 59 |", "PSNR score ''' mse = np.mean((original - compressed) ** 2)", "| |extremely colourful | 109 | ----------------------------- \"\"\" # Get", "= PSNR(original, compressed) print(f\"PSNR value is {value} dB\") img2 =", "RGB image Returns ------- M : colourness metric ----------------------------- |not", "rg = R - G yb = (1/2) * (R+G)", "= 20 * log10(max_pixel / sqrt(mse)) return psnr def colourfulnessMetric(img):", "max_pixel = 255.0 psnr = 20 * log10(max_pixel / sqrt(mse))", "+ np.mean(yb)**2) M = sigma_rgyb + 0.3 * mu_rgyb return", "G yb = (1/2) * (R+G) - B sigma_rgyb =", "value = PSNR(original, compressed) print(f\"PSNR value is {value} dB\") img2", "log10(max_pixel / sqrt(mse)) return psnr def colourfulnessMetric(img): \"\"\" Created on", "| |quite colourful | 59 | |highly colourful | 82", "sigma_rgyb = np.sqrt(np.var(rg) + np.var(yb)) mu_rgyb = np.sqrt(np.mean(rg)**2 + np.mean(yb)**2)", "20 * log10(max_pixel / sqrt(mse)) return psnr def colourfulnessMetric(img): \"\"\"", "| 15 | |moderately colourful | 33 | |averagely colourful", "to noise ratio between a ground truth image and predicted", "\"\"\" Created on Mon Nov 15 10:55:16 2021 @author: Yucheng", "82 | |extremely colourful | 109 | ----------------------------- \"\"\" #", "| ----------------------------- \"\"\" # Get RGB components R,G,B = cv2.split(img.astype(\"float\"))", "M = sigma_rgyb + 0.3 * mu_rgyb return M def", "Nov 15 10:55:16 2021 @author: Yucheng Parameters ---------- img :", "Yucheng Parameters ---------- img : cv2 RGB image Returns -------", "numpy as np def PSNR(original, compressed): ''' Calculates the Peak", "= R - G yb = (1/2) * (R+G) -", "| 45 | |quite colourful | 59 | |highly colourful", "is zero means no noise is present in the signal", "45 | |quite colourful | 59 | |highly colourful |", "mu_rgyb return M def main(): import matplotlib.pyplot as plt original", "https://www.geeksforgeeks.org/python-peak-signal-to-noise-ratio-psnr/ for reference Parameters ---------- true image (cv2 image) predicted", "math import log10, sqrt import cv2 import numpy as np", "------- PSNR score ''' mse = np.mean((original - compressed) **", "sigma_rgyb + 0.3 * mu_rgyb return M def main(): import", "cv2 RGB image Returns ------- M : colourness metric -----------------------------", "| 109 | ----------------------------- \"\"\" # Get RGB components R,G,B", "255.0 psnr = 20 * log10(max_pixel / sqrt(mse)) return psnr", "colourful | 109 | ----------------------------- \"\"\" # Get RGB components", "np.sqrt(np.var(rg) + np.var(yb)) mu_rgyb = np.sqrt(np.mean(rg)**2 + np.mean(yb)**2) M =", "if(mse == 0): # MSE is zero means no noise", "Returns ------- M : colourness metric ----------------------------- |not colourful |", "def main(): import matplotlib.pyplot as plt original = cv2.imread(\"test_imgs/original_image.png\") compressed", "= cv2.imread(\"test_imgs/compressed_image1.png\", 1) value = PSNR(original, compressed) print(f\"PSNR value is", "B sigma_rgyb = np.sqrt(np.var(rg) + np.var(yb)) mu_rgyb = np.sqrt(np.mean(rg)**2 +", "cv2 import numpy as np def PSNR(original, compressed): ''' Calculates", "for reference Parameters ---------- true image (cv2 image) predicted image", "= np.sqrt(np.var(rg) + np.var(yb)) mu_rgyb = np.sqrt(np.mean(rg)**2 + np.mean(yb)**2) M", "see https://www.geeksforgeeks.org/python-peak-signal-to-noise-ratio-psnr/ for reference Parameters ---------- true image (cv2 image)", "np.mean((original - compressed) ** 2) if(mse == 0): # MSE", "Parameters ---------- img : cv2 RGB image Returns ------- M", "image and predicted image. see https://www.geeksforgeeks.org/python-peak-signal-to-noise-ratio-psnr/ for reference Parameters ----------", "matplotlib.pyplot as plt original = cv2.imread(\"test_imgs/original_image.png\") compressed = cv2.imread(\"test_imgs/compressed_image1.png\", 1)", "@author: Yucheng Parameters ---------- img : cv2 RGB image Returns", "cv2.imread(\"rainbow.jpg\") # opens as BGR img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB) plt.imshow(img2[:,:,:])", "cv2.COLOR_BGR2RGB) plt.imshow(img2[:,:,:]) plt.show() M = colourfulnessMetric(img2) print(M) if __name__ ==", "plt.show() M = colourfulnessMetric(img2) print(M) if __name__ == \"__main__\": main()", "Calculates the Peak signal to noise ratio between a ground", "= sigma_rgyb + 0.3 * mu_rgyb return M def main():", "0 | |slightly colorful | 15 | |moderately colourful |", "= np.mean((original - compressed) ** 2) if(mse == 0): #", "components R,G,B = cv2.split(img.astype(\"float\")) # colourfulness metric from Hasler et", "R,G,B = cv2.split(img.astype(\"float\")) # colourfulness metric from Hasler et al.,", "reference Parameters ---------- true image (cv2 image) predicted image (cv2", "on Mon Nov 15 10:55:16 2021 @author: Yucheng Parameters ----------", ". # Therefore PSNR have no importance. return 100 max_pixel", "noise ratio between a ground truth image and predicted image.", "M : colourness metric ----------------------------- |not colourful | 0 |", "2021 @author: Yucheng Parameters ---------- img : cv2 RGB image", "| |moderately colourful | 33 | |averagely colourful | 45", "predicted image. see https://www.geeksforgeeks.org/python-peak-signal-to-noise-ratio-psnr/ for reference Parameters ---------- true image", "|extremely colourful | 109 | ----------------------------- \"\"\" # Get RGB", "* mu_rgyb return M def main(): import matplotlib.pyplot as plt", "original = cv2.imread(\"test_imgs/original_image.png\") compressed = cv2.imread(\"test_imgs/compressed_image1.png\", 1) value = PSNR(original,", "R - G yb = (1/2) * (R+G) - B", "33 | |averagely colourful | 45 | |quite colourful |", "# MSE is zero means no noise is present in", "signal . # Therefore PSNR have no importance. return 100", "''' Calculates the Peak signal to noise ratio between a", "image) predicted image (cv2 image) Returns ------- PSNR score '''", "present in the signal . # Therefore PSNR have no", "# colourfulness metric from Hasler et al., section 7 rg", "plt.imshow(img2[:,:,:]) plt.show() M = colourfulnessMetric(img2) print(M) if __name__ == \"__main__\":", "Hasler et al., section 7 rg = R - G", "---------- true image (cv2 image) predicted image (cv2 image) Returns", "the signal . # Therefore PSNR have no importance. return", "| 33 | |averagely colourful | 45 | |quite colourful", "value is {value} dB\") img2 = cv2.imread(\"rainbow.jpg\") # opens as", "means no noise is present in the signal . #", "def PSNR(original, compressed): ''' Calculates the Peak signal to noise", "= np.sqrt(np.mean(rg)**2 + np.mean(yb)**2) M = sigma_rgyb + 0.3 *", "15 10:55:16 2021 @author: Yucheng Parameters ---------- img : cv2", "cv2.cvtColor(img2, cv2.COLOR_BGR2RGB) plt.imshow(img2[:,:,:]) plt.show() M = colourfulnessMetric(img2) print(M) if __name__", "- B sigma_rgyb = np.sqrt(np.var(rg) + np.var(yb)) mu_rgyb = np.sqrt(np.mean(rg)**2", "print(f\"PSNR value is {value} dB\") img2 = cv2.imread(\"rainbow.jpg\") # opens", "= (1/2) * (R+G) - B sigma_rgyb = np.sqrt(np.var(rg) +", "as BGR img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB) plt.imshow(img2[:,:,:]) plt.show() M =", "import numpy as np def PSNR(original, compressed): ''' Calculates the", "# opens as BGR img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB) plt.imshow(img2[:,:,:]) plt.show()", "cv2.imread(\"test_imgs/original_image.png\") compressed = cv2.imread(\"test_imgs/compressed_image1.png\", 1) value = PSNR(original, compressed) print(f\"PSNR", "colourful | 0 | |slightly colorful | 15 | |moderately", "import log10, sqrt import cv2 import numpy as np def", "|quite colourful | 59 | |highly colourful | 82 |", "def colourfulnessMetric(img): \"\"\" Created on Mon Nov 15 10:55:16 2021", "metric from Hasler et al., section 7 rg = R", "importance. return 100 max_pixel = 255.0 psnr = 20 *", "as np def PSNR(original, compressed): ''' Calculates the Peak signal", "PSNR have no importance. return 100 max_pixel = 255.0 psnr", "np.var(yb)) mu_rgyb = np.sqrt(np.mean(rg)**2 + np.mean(yb)**2) M = sigma_rgyb +", "compressed): ''' Calculates the Peak signal to noise ratio between", "59 | |highly colourful | 82 | |extremely colourful |", "signal to noise ratio between a ground truth image and", "image (cv2 image) Returns ------- PSNR score ''' mse =", "|slightly colorful | 15 | |moderately colourful | 33 |", "* (R+G) - B sigma_rgyb = np.sqrt(np.var(rg) + np.var(yb)) mu_rgyb", "{value} dB\") img2 = cv2.imread(\"rainbow.jpg\") # opens as BGR img2", "al., section 7 rg = R - G yb =", "no noise is present in the signal . # Therefore", "yb = (1/2) * (R+G) - B sigma_rgyb = np.sqrt(np.var(rg)", "mu_rgyb = np.sqrt(np.mean(rg)**2 + np.mean(yb)**2) M = sigma_rgyb + 0.3", "BGR img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB) plt.imshow(img2[:,:,:]) plt.show() M = colourfulnessMetric(img2)", "no importance. return 100 max_pixel = 255.0 psnr = 20", "colourfulnessMetric(img): \"\"\" Created on Mon Nov 15 10:55:16 2021 @author:", "+ np.var(yb)) mu_rgyb = np.sqrt(np.mean(rg)**2 + np.mean(yb)**2) M = sigma_rgyb", "opens as BGR img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB) plt.imshow(img2[:,:,:]) plt.show() M" ]
[ "pass def test_fake_instance_is_valid(insight): # Should not raise ValidationError insight.full_clean() def", "import pytest from django.core.exceptions import ValidationError from django.db import DataError", "pass def test_create_new_instance_using_model_factory(insight): pass def test_fake_instance_is_valid(insight): # Should not raise", "import ValidationError from django.db import DataError from .factories import InsightFactory", "pytestmark = pytest.mark.django_db def test_create_new_fake_visitor_instance_using_factory(visitor): pass def test_create_new_instance_using_model_factory(insight): pass def", "is working the way it should.\"\"\" import pytest from django.core.exceptions", "\"\"\"Test insight model is working the way it should.\"\"\" import", "test_create_new_fake_visitor_instance_using_factory(visitor): pass def test_create_new_instance_using_model_factory(insight): pass def test_fake_instance_is_valid(insight): # Should not", "def test_create_new_instance_using_model_factory(insight): pass def test_fake_instance_is_valid(insight): # Should not raise ValidationError", "model is working the way it should.\"\"\" import pytest from", "assert isinstance(insight.id, int) assert insight.time is not None def test_invalid_ip_address():", ".factories import InsightFactory pytestmark = pytest.mark.django_db def test_create_new_fake_visitor_instance_using_factory(visitor): pass def", "raise ValidationError insight.full_clean() def test_fake_instance_have_right_fields(insight): assert isinstance(insight.id, int) assert insight.time", "django.db import DataError from .factories import InsightFactory pytestmark = pytest.mark.django_db", "DataError from .factories import InsightFactory pytestmark = pytest.mark.django_db def test_create_new_fake_visitor_instance_using_factory(visitor):", "working the way it should.\"\"\" import pytest from django.core.exceptions import", "int) assert insight.time is not None def test_invalid_ip_address(): with pytest.raises(DataError):", "django.core.exceptions import ValidationError from django.db import DataError from .factories import", "from django.db import DataError from .factories import InsightFactory pytestmark =", "from .factories import InsightFactory pytestmark = pytest.mark.django_db def test_create_new_fake_visitor_instance_using_factory(visitor): pass", "import DataError from .factories import InsightFactory pytestmark = pytest.mark.django_db def", "InsightFactory pytestmark = pytest.mark.django_db def test_create_new_fake_visitor_instance_using_factory(visitor): pass def test_create_new_instance_using_model_factory(insight): pass", "# Should not raise ValidationError insight.full_clean() def test_fake_instance_have_right_fields(insight): assert isinstance(insight.id,", "def test_fake_instance_have_right_fields(insight): assert isinstance(insight.id, int) assert insight.time is not None", "pytest from django.core.exceptions import ValidationError from django.db import DataError from", "Should not raise ValidationError insight.full_clean() def test_fake_instance_have_right_fields(insight): assert isinstance(insight.id, int)", "way it should.\"\"\" import pytest from django.core.exceptions import ValidationError from", "def test_create_new_fake_visitor_instance_using_factory(visitor): pass def test_create_new_instance_using_model_factory(insight): pass def test_fake_instance_is_valid(insight): # Should", "isinstance(insight.id, int) assert insight.time is not None def test_invalid_ip_address(): with", "insight model is working the way it should.\"\"\" import pytest", "from django.core.exceptions import ValidationError from django.db import DataError from .factories", "assert insight.time is not None def test_invalid_ip_address(): with pytest.raises(DataError): InsightFactory(visitor__ip_address=\"invalid", "should.\"\"\" import pytest from django.core.exceptions import ValidationError from django.db import", "def test_fake_instance_is_valid(insight): # Should not raise ValidationError insight.full_clean() def test_fake_instance_have_right_fields(insight):", "= pytest.mark.django_db def test_create_new_fake_visitor_instance_using_factory(visitor): pass def test_create_new_instance_using_model_factory(insight): pass def test_fake_instance_is_valid(insight):", "test_create_new_instance_using_model_factory(insight): pass def test_fake_instance_is_valid(insight): # Should not raise ValidationError insight.full_clean()", "ValidationError from django.db import DataError from .factories import InsightFactory pytestmark", "None def test_invalid_ip_address(): with pytest.raises(DataError): InsightFactory(visitor__ip_address=\"invalid ip\") def test_valid_fake_ip_v6_address(faker): InsightFactory(visitor__ip_address=faker.ipv6())", "insight.time is not None def test_invalid_ip_address(): with pytest.raises(DataError): InsightFactory(visitor__ip_address=\"invalid ip\")", "not None def test_invalid_ip_address(): with pytest.raises(DataError): InsightFactory(visitor__ip_address=\"invalid ip\") def test_valid_fake_ip_v6_address(faker):", "is not None def test_invalid_ip_address(): with pytest.raises(DataError): InsightFactory(visitor__ip_address=\"invalid ip\") def", "pytest.mark.django_db def test_create_new_fake_visitor_instance_using_factory(visitor): pass def test_create_new_instance_using_model_factory(insight): pass def test_fake_instance_is_valid(insight): #", "insight.full_clean() def test_fake_instance_have_right_fields(insight): assert isinstance(insight.id, int) assert insight.time is not", "<filename>redirink/insights/tests/test_models.py \"\"\"Test insight model is working the way it should.\"\"\"", "the way it should.\"\"\" import pytest from django.core.exceptions import ValidationError", "ValidationError insight.full_clean() def test_fake_instance_have_right_fields(insight): assert isinstance(insight.id, int) assert insight.time is", "test_fake_instance_is_valid(insight): # Should not raise ValidationError insight.full_clean() def test_fake_instance_have_right_fields(insight): assert", "import InsightFactory pytestmark = pytest.mark.django_db def test_create_new_fake_visitor_instance_using_factory(visitor): pass def test_create_new_instance_using_model_factory(insight):", "test_fake_instance_have_right_fields(insight): assert isinstance(insight.id, int) assert insight.time is not None def", "not raise ValidationError insight.full_clean() def test_fake_instance_have_right_fields(insight): assert isinstance(insight.id, int) assert", "it should.\"\"\" import pytest from django.core.exceptions import ValidationError from django.db" ]
[ "(disabled test) \"test-dream-challenge-synapaseLoginTest\", # legacy (disabled test) \"test-prod-checkAllProjectsBucketAccessTest\", # prod", "test) \"test-regressions-generateTestData\", # legacy (disabled test) \"test-regressions-queryPerformanceTest\", # legacy (disabled", "= test_script[0 : test_script.index(\".\")] test_suite = f\"test-{suite_folder}-{test_script_without_extension}\" test_suites.append(test_suite) return test_suites", "full_path_to_test_js[-2] # print(f'## suite_folder: {suite_folder}') test_script = full_path_to_test_js[-1] # print(f'##", "if \"pre-release\" in line: continue elif \".js\" in line: full_path_to_test_js", "# long-running test \"test-portal-dataUploadTest\", # SUPER long-running test \"test-portal-indexingPageTest\", #", "main(): test_suites = collect_test_suites_from_codeceptjs_dryrun() for ts in test_suites: if ts", "\"test-apis-dbgapTest\", # not thread-safe \"test-google-googleDataAccessTest\", # not thread-safe \"test-google-googleServiceAccountRemovalTest\", #", "test \"test-google-googleServiceAccountTest\", # long-running test \"test-google-googleServiceAccountKeyTest\", # long-running test \"test-portal-dataUploadTest\",", "# SUPER long-running test \"test-portal-indexingPageTest\", # long-running test \"test-apis-metadataIngestionTest\", #", "line.split(\"/\") suite_folder = full_path_to_test_js[-2] # print(f'## suite_folder: {suite_folder}') test_script =", "# not thread-safe \"test-smokeTests-brainTests\", # manual (executable test) \"test-batch-GoogleBucketManifestGenerationTest\", #", "test_suites = collect_test_suites_from_codeceptjs_dryrun() for ts in test_suites: if ts not", "# manual (executable test) \"test-portal-discoveryPageTestPlan\", # manual (executable test) \"test-portal-dashboardReportsTest\",", "manual (executable test) \"test-portal-terraExportWarningTestPlan\", # manual (executable test) \"test-pelican-exportPfbTest\", #", "(disabled test) \"test-dream-challenge-DCgen3clientTest\", # legacy (disabled test) \"test-dream-challenge-synapaseLoginTest\", # legacy", "(executable test) \"test-apis-dcfDataReplicationTest\", # manual (executable test) \"test-portal-exportPfbToWorkspaceTest\", # manual", "ts not in test_suites_that_cant_run_in_parallel: print(ts) # print(f\"## ## test_suites: {test_suites}\")", "# print(f\"## test_suites size: {len(test_suites)}\") if __name__ == \"__main__\": main()", "@donot \"test-batch-S3BucketManifestGenerationTest\", # @donot \"test-portal-dataguidOrgTest\", # @donot \"test-mariner-marinerIntegrationTest\", # @donot", "long-running test ] def collect_test_suites_from_codeceptjs_dryrun(): my_env = os.environ.copy() bashCommand =", "= \"npx codeceptjs dry-run\" process = subprocess.Popen( bashCommand.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE,", "output, error = process.communicate() test_suites = [] for line in", "\"test-mariner-marinerIntegrationTest\", # @donot \"test-suites-fail\", # special suite to force failures", "<reponame>uc-cdis/gen3-qa<gh_stars>1-10 import os import subprocess test_suites_that_cant_run_in_parallel = [ \"test-apis-dbgapTest\", #", "subprocess test_suites_that_cant_run_in_parallel = [ \"test-apis-dbgapTest\", # not thread-safe \"test-google-googleDataAccessTest\", #", "pre-release test suites if \"pre-release\" in line: continue elif \".js\"", "# manual (executable test) \"test-apis-dcfDataReplicationTest\", # manual (executable test) \"test-portal-exportPfbToWorkspaceTest\",", "{test_suites}\") # print(f\"## test_suites size: {len(test_suites)}\") if __name__ == \"__main__\":", "long-running test \"test-google-googleServiceAccountTest\", # long-running test \"test-google-googleServiceAccountKeyTest\", # long-running test", "# print(f'### line: {line}') # ignore pre-release test suites if", "\"test-suites-fail\", # special suite to force failures for invalid test", "\"test-guppy-nestedAggTest\", # manual (executable test) \"test-portal-404pageTest\", # manual (executable test)", "suites if \"pre-release\" in line: continue elif \".js\" in line:", ") output, error = process.communicate() test_suites = [] for line", "legacy (disabled test) \"test-dream-challenge-DCgen3clientTest\", # legacy (disabled test) \"test-dream-challenge-synapaseLoginTest\", #", "test) \"test-apis-dcfDataReplicationTest\", # manual (executable test) \"test-portal-exportPfbToWorkspaceTest\", # manual (executable", "f\"test-{suite_folder}-{test_script_without_extension}\" test_suites.append(test_suite) return test_suites def main(): test_suites = collect_test_suites_from_codeceptjs_dryrun() for", "(executable test) \"test-portal-dashboardReportsTest\", # manual (executable test) \"test-guppy-nestedAggTest\", # manual", "= [] for line in output.splitlines(): line = line.decode(\"utf-8\") #", "manual (executable test) \"test-portal-404pageTest\", # manual (executable test) \"test-apis-dcfDataReplicationTest\", #", "for invalid test labels \"test-portal-roleBasedUITest\", # manual (executable test) \"test-portal-limitedFilePFBExportTestPlan\",", "test) \"test-portal-tieredAccessTest\", # manual (executable test) \"test-portal-discoveryPageTestPlan\", # manual (executable", "\"test-prod-checkAllProjectsBucketAccessTest\", # prod test \"test-portal-pfbExportTest\", # nightly build test \"test-apis-etlTest\",", "@donot \"test-portal-dataguidOrgTest\", # @donot \"test-mariner-marinerIntegrationTest\", # @donot \"test-suites-fail\", # special", "\"test-portal-dashboardReportsTest\", # manual (executable test) \"test-guppy-nestedAggTest\", # manual (executable test)", "ignore pre-release test suites if \"pre-release\" in line: continue elif", "# legacy (disabled test) \"test-regressions-queryPerformanceTest\", # legacy (disabled test) \"test-regressions-submissionPerformanceTest\",", "= full_path_to_test_js[-2] # print(f'## suite_folder: {suite_folder}') test_script = full_path_to_test_js[-1] #", "manual (executable test) \"test-portal-discoveryPageTestPlan\", # manual (executable test) \"test-portal-dashboardReportsTest\", #", "my_env = os.environ.copy() bashCommand = \"npx codeceptjs dry-run\" process =", "\"test-regressions-generateTestData\", # legacy (disabled test) \"test-regressions-queryPerformanceTest\", # legacy (disabled test)", "thread-safe \"test-google-googleDataAccessTest\", # not thread-safe \"test-google-googleServiceAccountRemovalTest\", # not thread-safe \"test-guppy-guppyTest\",", "\"test-apis-metadataIngestionTest\", # long-running test \"test-apis-auditServiceTest\" # long-running test ] def", "line in output.splitlines(): line = line.decode(\"utf-8\") # print(f'### line: {line}')", "# print(f'## test_script: {test_script}') test_script_without_extension = test_script[0 : test_script.index(\".\")] test_suite", "(executable test) \"test-portal-limitedFilePFBExportTestPlan\", # manual (executable test) \"test-access-accessGUITest\", # manual", "not ready \"test-regressions-exportPerformanceTest\", # legacy (disabled test) \"test-regressions-generateTestData\", # legacy", "{suite_folder}') test_script = full_path_to_test_js[-1] # print(f'## test_script: {test_script}') test_script_without_extension =", "test_suites: if ts not in test_suites_that_cant_run_in_parallel: print(ts) # print(f\"## ##", "manual (executable test) \"test-portal-dashboardReportsTest\", # manual (executable test) \"test-guppy-nestedAggTest\", #", "# manual (executable test) \"test-access-accessGUITest\", # manual (executable test) \"test-portal-tieredAccessTest\",", "test_suites: {test_suites}\") # print(f\"## test_suites size: {len(test_suites)}\") if __name__ ==", "stderr=subprocess.PIPE, env=my_env ) output, error = process.communicate() test_suites = []", "\"test-apis-etlTest\", # long-running test \"test-apis-centralizedAuth\", # long-running test \"test-google-googleServiceAccountTest\", #", "\"test-regressions-submissionPerformanceTest\", # legacy (disabled test) \"test-dream-challenge-DCgen3clientTest\", # legacy (disabled test)", "ts in test_suites: if ts not in test_suites_that_cant_run_in_parallel: print(ts) #", "# legacy (disabled test) \"test-prod-checkAllProjectsBucketAccessTest\", # prod test \"test-portal-pfbExportTest\", #", "test) \"test-dream-challenge-synapaseLoginTest\", # legacy (disabled test) \"test-prod-checkAllProjectsBucketAccessTest\", # prod test", "\"test-apis-centralizedAuth\", # long-running test \"test-google-googleServiceAccountTest\", # long-running test \"test-google-googleServiceAccountKeyTest\", #", "long-running test \"test-google-googleServiceAccountKeyTest\", # long-running test \"test-portal-dataUploadTest\", # SUPER long-running", "print(f'### line: {line}') # ignore pre-release test suites if \"pre-release\"", "test_suite = f\"test-{suite_folder}-{test_script_without_extension}\" test_suites.append(test_suite) return test_suites def main(): test_suites =", "# manual (executable test) \"test-portal-homepageChartNodesExecutableTestPlan\",# manual (executable test) \"test-portal-profilePageTest\", #", "not in test_suites_that_cant_run_in_parallel: print(ts) # print(f\"## ## test_suites: {test_suites}\") #", "test) \"test-access-accessGUITest\", # manual (executable test) \"test-portal-tieredAccessTest\", # manual (executable", "(executable test) \"test-portal-profilePageTest\", # manual (executable test) \"test-portal-terraExportWarningTestPlan\", # manual", "\"test-google-googleServiceAccountKeyTest\", # long-running test \"test-portal-dataUploadTest\", # SUPER long-running test \"test-portal-indexingPageTest\",", "\"test-google-googleServiceAccountTest\", # long-running test \"test-google-googleServiceAccountKeyTest\", # long-running test \"test-portal-dataUploadTest\", #", "print(f'## test_script: {test_script}') test_script_without_extension = test_script[0 : test_script.index(\".\")] test_suite =", "not thread-safe \"test-guppy-guppyTest\", # not thread-safe \"test-smokeTests-brainTests\", # manual (executable", "suite to force failures for invalid test labels \"test-portal-roleBasedUITest\", #", "# legacy (disabled test) \"test-dream-challenge-DCgen3clientTest\", # legacy (disabled test) \"test-dream-challenge-synapaseLoginTest\",", "{test_script}') test_script_without_extension = test_script[0 : test_script.index(\".\")] test_suite = f\"test-{suite_folder}-{test_script_without_extension}\" test_suites.append(test_suite)", "suite_folder: {suite_folder}') test_script = full_path_to_test_js[-1] # print(f'## test_script: {test_script}') test_script_without_extension", "bashCommand = \"npx codeceptjs dry-run\" process = subprocess.Popen( bashCommand.split(), stdout=subprocess.PIPE,", "line = line.decode(\"utf-8\") # print(f'### line: {line}') # ignore pre-release", "(executable test) \"test-portal-homepageChartNodesExecutableTestPlan\",# manual (executable test) \"test-portal-profilePageTest\", # manual (executable", "\"test-portal-profilePageTest\", # manual (executable test) \"test-portal-terraExportWarningTestPlan\", # manual (executable test)", "test) \"test-regressions-queryPerformanceTest\", # legacy (disabled test) \"test-regressions-submissionPerformanceTest\", # legacy (disabled", "# manual (executable test) \"test-portal-tieredAccessTest\", # manual (executable test) \"test-portal-discoveryPageTestPlan\",", "test \"test-apis-etlTest\", # long-running test \"test-apis-centralizedAuth\", # long-running test \"test-google-googleServiceAccountTest\",", "# @donot \"test-mariner-marinerIntegrationTest\", # @donot \"test-suites-fail\", # special suite to", "line: continue elif \".js\" in line: full_path_to_test_js = line.split(\"/\") suite_folder", "in line: full_path_to_test_js = line.split(\"/\") suite_folder = full_path_to_test_js[-2] # print(f'##", "long-running test \"test-portal-indexingPageTest\", # long-running test \"test-apis-metadataIngestionTest\", # long-running test", "legacy (disabled test) \"test-prod-checkAllProjectsBucketAccessTest\", # prod test \"test-portal-pfbExportTest\", # nightly", "test \"test-apis-centralizedAuth\", # long-running test \"test-google-googleServiceAccountTest\", # long-running test \"test-google-googleServiceAccountKeyTest\",", "\"test-apis-auditServiceTest\" # long-running test ] def collect_test_suites_from_codeceptjs_dryrun(): my_env = os.environ.copy()", "in test_suites: if ts not in test_suites_that_cant_run_in_parallel: print(ts) # print(f\"##", "test) \"test-portal-limitedFilePFBExportTestPlan\", # manual (executable test) \"test-access-accessGUITest\", # manual (executable", "[] for line in output.splitlines(): line = line.decode(\"utf-8\") # print(f'###", "\"test-portal-pfbExportTest\", # nightly build test \"test-apis-etlTest\", # long-running test \"test-apis-centralizedAuth\",", "dry-run\" process = subprocess.Popen( bashCommand.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env ) output,", "\"test-portal-roleBasedUITest\", # manual (executable test) \"test-portal-limitedFilePFBExportTestPlan\", # manual (executable test)", "manual (executable test) \"test-portal-profilePageTest\", # manual (executable test) \"test-portal-terraExportWarningTestPlan\", #", "# not thread-safe \"test-guppy-guppyTest\", # not thread-safe \"test-smokeTests-brainTests\", # manual", "to force failures for invalid test labels \"test-portal-roleBasedUITest\", # manual", "= os.environ.copy() bashCommand = \"npx codeceptjs dry-run\" process = subprocess.Popen(", "print(f'## suite_folder: {suite_folder}') test_script = full_path_to_test_js[-1] # print(f'## test_script: {test_script}')", "manual (executable test) \"test-access-accessGUITest\", # manual (executable test) \"test-portal-tieredAccessTest\", #", "\"test-regressions-exportPerformanceTest\", # legacy (disabled test) \"test-regressions-generateTestData\", # legacy (disabled test)", "= f\"test-{suite_folder}-{test_script_without_extension}\" test_suites.append(test_suite) return test_suites def main(): test_suites = collect_test_suites_from_codeceptjs_dryrun()", "\"test-portal-404pageTest\", # manual (executable test) \"test-apis-dcfDataReplicationTest\", # manual (executable test)", "test \"test-google-googleServiceAccountKeyTest\", # long-running test \"test-portal-dataUploadTest\", # SUPER long-running test", "invalid test labels \"test-portal-roleBasedUITest\", # manual (executable test) \"test-portal-limitedFilePFBExportTestPlan\", #", "def collect_test_suites_from_codeceptjs_dryrun(): my_env = os.environ.copy() bashCommand = \"npx codeceptjs dry-run\"", "= subprocess.Popen( bashCommand.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env ) output, error =", "test) \"test-pelican-exportPfbTest\", # not ready \"test-regressions-exportPerformanceTest\", # legacy (disabled test)", "# long-running test \"test-apis-centralizedAuth\", # long-running test \"test-google-googleServiceAccountTest\", # long-running", "test_script[0 : test_script.index(\".\")] test_suite = f\"test-{suite_folder}-{test_script_without_extension}\" test_suites.append(test_suite) return test_suites def", "# legacy (disabled test) \"test-dream-challenge-synapaseLoginTest\", # legacy (disabled test) \"test-prod-checkAllProjectsBucketAccessTest\",", "\"test-portal-dataguidOrgTest\", # @donot \"test-mariner-marinerIntegrationTest\", # @donot \"test-suites-fail\", # special suite", "stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env ) output, error = process.communicate() test_suites =", "(disabled test) \"test-regressions-submissionPerformanceTest\", # legacy (disabled test) \"test-dream-challenge-DCgen3clientTest\", # legacy", "process.communicate() test_suites = [] for line in output.splitlines(): line =", "import subprocess test_suites_that_cant_run_in_parallel = [ \"test-apis-dbgapTest\", # not thread-safe \"test-google-googleDataAccessTest\",", "# manual (executable test) \"test-guppy-nestedAggTest\", # manual (executable test) \"test-portal-404pageTest\",", "for ts in test_suites: if ts not in test_suites_that_cant_run_in_parallel: print(ts)", "\"test-portal-terraExportWarningTestPlan\", # manual (executable test) \"test-pelican-exportPfbTest\", # not ready \"test-regressions-exportPerformanceTest\",", "= full_path_to_test_js[-1] # print(f'## test_script: {test_script}') test_script_without_extension = test_script[0 :", "force failures for invalid test labels \"test-portal-roleBasedUITest\", # manual (executable", "# legacy (disabled test) \"test-regressions-generateTestData\", # legacy (disabled test) \"test-regressions-queryPerformanceTest\",", "thread-safe \"test-google-googleServiceAccountRemovalTest\", # not thread-safe \"test-guppy-guppyTest\", # not thread-safe \"test-smokeTests-brainTests\",", "thread-safe \"test-guppy-guppyTest\", # not thread-safe \"test-smokeTests-brainTests\", # manual (executable test)", "\"test-portal-discoveryPageTestPlan\", # manual (executable test) \"test-portal-dashboardReportsTest\", # manual (executable test)", "continue elif \".js\" in line: full_path_to_test_js = line.split(\"/\") suite_folder =", "\"test-portal-limitedFilePFBExportTestPlan\", # manual (executable test) \"test-access-accessGUITest\", # manual (executable test)", "build test \"test-apis-etlTest\", # long-running test \"test-apis-centralizedAuth\", # long-running test", "= [ \"test-apis-dbgapTest\", # not thread-safe \"test-google-googleDataAccessTest\", # not thread-safe", "test_suites_that_cant_run_in_parallel: print(ts) # print(f\"## ## test_suites: {test_suites}\") # print(f\"## test_suites", "(executable test) \"test-pelican-exportPfbTest\", # not ready \"test-regressions-exportPerformanceTest\", # legacy (disabled", "(disabled test) \"test-prod-checkAllProjectsBucketAccessTest\", # prod test \"test-portal-pfbExportTest\", # nightly build", "test) \"test-regressions-submissionPerformanceTest\", # legacy (disabled test) \"test-dream-challenge-DCgen3clientTest\", # legacy (disabled", "test) \"test-portal-exportPfbToWorkspaceTest\", # manual (executable test) \"test-portal-homepageChartNodesExecutableTestPlan\",# manual (executable test)", "long-running test \"test-apis-metadataIngestionTest\", # long-running test \"test-apis-auditServiceTest\" # long-running test", "test labels \"test-portal-roleBasedUITest\", # manual (executable test) \"test-portal-limitedFilePFBExportTestPlan\", # manual", "# manual (executable test) \"test-batch-GoogleBucketManifestGenerationTest\", # @donot \"test-batch-S3BucketManifestGenerationTest\", # @donot", "# manual (executable test) \"test-portal-exportPfbToWorkspaceTest\", # manual (executable test) \"test-portal-homepageChartNodesExecutableTestPlan\",#", "\"test-portal-homepageChartNodesExecutableTestPlan\",# manual (executable test) \"test-portal-profilePageTest\", # manual (executable test) \"test-portal-terraExportWarningTestPlan\",", "labels \"test-portal-roleBasedUITest\", # manual (executable test) \"test-portal-limitedFilePFBExportTestPlan\", # manual (executable", "test_script: {test_script}') test_script_without_extension = test_script[0 : test_script.index(\".\")] test_suite = f\"test-{suite_folder}-{test_script_without_extension}\"", "# not thread-safe \"test-google-googleServiceAccountRemovalTest\", # not thread-safe \"test-guppy-guppyTest\", # not", "# not thread-safe \"test-google-googleDataAccessTest\", # not thread-safe \"test-google-googleServiceAccountRemovalTest\", # not", "test \"test-apis-metadataIngestionTest\", # long-running test \"test-apis-auditServiceTest\" # long-running test ]", "= line.split(\"/\") suite_folder = full_path_to_test_js[-2] # print(f'## suite_folder: {suite_folder}') test_script", "in test_suites_that_cant_run_in_parallel: print(ts) # print(f\"## ## test_suites: {test_suites}\") # print(f\"##", "\"test-smokeTests-brainTests\", # manual (executable test) \"test-batch-GoogleBucketManifestGenerationTest\", # @donot \"test-batch-S3BucketManifestGenerationTest\", #", "# special suite to force failures for invalid test labels", "\"test-batch-GoogleBucketManifestGenerationTest\", # @donot \"test-batch-S3BucketManifestGenerationTest\", # @donot \"test-portal-dataguidOrgTest\", # @donot \"test-mariner-marinerIntegrationTest\",", "\"test-portal-exportPfbToWorkspaceTest\", # manual (executable test) \"test-portal-homepageChartNodesExecutableTestPlan\",# manual (executable test) \"test-portal-profilePageTest\",", "output.splitlines(): line = line.decode(\"utf-8\") # print(f'### line: {line}') # ignore", "line: {line}') # ignore pre-release test suites if \"pre-release\" in", "# ignore pre-release test suites if \"pre-release\" in line: continue", "codeceptjs dry-run\" process = subprocess.Popen( bashCommand.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env )", "# manual (executable test) \"test-portal-404pageTest\", # manual (executable test) \"test-apis-dcfDataReplicationTest\",", "if ts not in test_suites_that_cant_run_in_parallel: print(ts) # print(f\"## ## test_suites:", "(disabled test) \"test-regressions-queryPerformanceTest\", # legacy (disabled test) \"test-regressions-submissionPerformanceTest\", # legacy", "(disabled test) \"test-regressions-generateTestData\", # legacy (disabled test) \"test-regressions-queryPerformanceTest\", # legacy", "test \"test-portal-indexingPageTest\", # long-running test \"test-apis-metadataIngestionTest\", # long-running test \"test-apis-auditServiceTest\"", "\"test-regressions-queryPerformanceTest\", # legacy (disabled test) \"test-regressions-submissionPerformanceTest\", # legacy (disabled test)", "print(f\"## ## test_suites: {test_suites}\") # print(f\"## test_suites size: {len(test_suites)}\") if", "manual (executable test) \"test-portal-limitedFilePFBExportTestPlan\", # manual (executable test) \"test-access-accessGUITest\", #", "os.environ.copy() bashCommand = \"npx codeceptjs dry-run\" process = subprocess.Popen( bashCommand.split(),", "# @donot \"test-suites-fail\", # special suite to force failures for", "long-running test \"test-apis-auditServiceTest\" # long-running test ] def collect_test_suites_from_codeceptjs_dryrun(): my_env", "manual (executable test) \"test-apis-dcfDataReplicationTest\", # manual (executable test) \"test-portal-exportPfbToWorkspaceTest\", #", "line.decode(\"utf-8\") # print(f'### line: {line}') # ignore pre-release test suites", "thread-safe \"test-smokeTests-brainTests\", # manual (executable test) \"test-batch-GoogleBucketManifestGenerationTest\", # @donot \"test-batch-S3BucketManifestGenerationTest\",", "\"test-guppy-guppyTest\", # not thread-safe \"test-smokeTests-brainTests\", # manual (executable test) \"test-batch-GoogleBucketManifestGenerationTest\",", "# @donot \"test-batch-S3BucketManifestGenerationTest\", # @donot \"test-portal-dataguidOrgTest\", # @donot \"test-mariner-marinerIntegrationTest\", #", "# print(f'## suite_folder: {suite_folder}') test_script = full_path_to_test_js[-1] # print(f'## test_script:", "def main(): test_suites = collect_test_suites_from_codeceptjs_dryrun() for ts in test_suites: if", "legacy (disabled test) \"test-regressions-generateTestData\", # legacy (disabled test) \"test-regressions-queryPerformanceTest\", #", "print(ts) # print(f\"## ## test_suites: {test_suites}\") # print(f\"## test_suites size:", "## test_suites: {test_suites}\") # print(f\"## test_suites size: {len(test_suites)}\") if __name__", "# long-running test \"test-google-googleServiceAccountTest\", # long-running test \"test-google-googleServiceAccountKeyTest\", # long-running", "test_suites = [] for line in output.splitlines(): line = line.decode(\"utf-8\")", "\".js\" in line: full_path_to_test_js = line.split(\"/\") suite_folder = full_path_to_test_js[-2] #", "bashCommand.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env ) output, error = process.communicate() test_suites", "# print(f\"## ## test_suites: {test_suites}\") # print(f\"## test_suites size: {len(test_suites)}\")", "[ \"test-apis-dbgapTest\", # not thread-safe \"test-google-googleDataAccessTest\", # not thread-safe \"test-google-googleServiceAccountRemovalTest\",", "\"test-portal-tieredAccessTest\", # manual (executable test) \"test-portal-discoveryPageTestPlan\", # manual (executable test)", "(executable test) \"test-portal-404pageTest\", # manual (executable test) \"test-apis-dcfDataReplicationTest\", # manual", "manual (executable test) \"test-batch-GoogleBucketManifestGenerationTest\", # @donot \"test-batch-S3BucketManifestGenerationTest\", # @donot \"test-portal-dataguidOrgTest\",", "(executable test) \"test-portal-terraExportWarningTestPlan\", # manual (executable test) \"test-pelican-exportPfbTest\", # not", "full_path_to_test_js = line.split(\"/\") suite_folder = full_path_to_test_js[-2] # print(f'## suite_folder: {suite_folder}')", "\"test-batch-S3BucketManifestGenerationTest\", # @donot \"test-portal-dataguidOrgTest\", # @donot \"test-mariner-marinerIntegrationTest\", # @donot \"test-suites-fail\",", "# long-running test ] def collect_test_suites_from_codeceptjs_dryrun(): my_env = os.environ.copy() bashCommand", "in line: continue elif \".js\" in line: full_path_to_test_js = line.split(\"/\")", "\"test-google-googleDataAccessTest\", # not thread-safe \"test-google-googleServiceAccountRemovalTest\", # not thread-safe \"test-guppy-guppyTest\", #", "\"test-portal-indexingPageTest\", # long-running test \"test-apis-metadataIngestionTest\", # long-running test \"test-apis-auditServiceTest\" #", "test) \"test-portal-discoveryPageTestPlan\", # manual (executable test) \"test-portal-dashboardReportsTest\", # manual (executable", "\"test-pelican-exportPfbTest\", # not ready \"test-regressions-exportPerformanceTest\", # legacy (disabled test) \"test-regressions-generateTestData\",", "# prod test \"test-portal-pfbExportTest\", # nightly build test \"test-apis-etlTest\", #", "# not ready \"test-regressions-exportPerformanceTest\", # legacy (disabled test) \"test-regressions-generateTestData\", #", "# long-running test \"test-apis-auditServiceTest\" # long-running test ] def collect_test_suites_from_codeceptjs_dryrun():", "{line}') # ignore pre-release test suites if \"pre-release\" in line:", "manual (executable test) \"test-portal-tieredAccessTest\", # manual (executable test) \"test-portal-discoveryPageTestPlan\", #", "import os import subprocess test_suites_that_cant_run_in_parallel = [ \"test-apis-dbgapTest\", # not", "= process.communicate() test_suites = [] for line in output.splitlines(): line", "test_script.index(\".\")] test_suite = f\"test-{suite_folder}-{test_script_without_extension}\" test_suites.append(test_suite) return test_suites def main(): test_suites", "test_script_without_extension = test_script[0 : test_script.index(\".\")] test_suite = f\"test-{suite_folder}-{test_script_without_extension}\" test_suites.append(test_suite) return", "manual (executable test) \"test-portal-exportPfbToWorkspaceTest\", # manual (executable test) \"test-portal-homepageChartNodesExecutableTestPlan\",# manual", "test) \"test-portal-dashboardReportsTest\", # manual (executable test) \"test-guppy-nestedAggTest\", # manual (executable", "test \"test-portal-pfbExportTest\", # nightly build test \"test-apis-etlTest\", # long-running test", "# @donot \"test-portal-dataguidOrgTest\", # @donot \"test-mariner-marinerIntegrationTest\", # @donot \"test-suites-fail\", #", "test_script = full_path_to_test_js[-1] # print(f'## test_script: {test_script}') test_script_without_extension = test_script[0", "# manual (executable test) \"test-portal-dashboardReportsTest\", # manual (executable test) \"test-guppy-nestedAggTest\",", "test_suites.append(test_suite) return test_suites def main(): test_suites = collect_test_suites_from_codeceptjs_dryrun() for ts", "prod test \"test-portal-pfbExportTest\", # nightly build test \"test-apis-etlTest\", # long-running", "\"test-google-googleServiceAccountRemovalTest\", # not thread-safe \"test-guppy-guppyTest\", # not thread-safe \"test-smokeTests-brainTests\", #", "line: full_path_to_test_js = line.split(\"/\") suite_folder = full_path_to_test_js[-2] # print(f'## suite_folder:", "@donot \"test-suites-fail\", # special suite to force failures for invalid", "for line in output.splitlines(): line = line.decode(\"utf-8\") # print(f'### line:", "special suite to force failures for invalid test labels \"test-portal-roleBasedUITest\",", "return test_suites def main(): test_suites = collect_test_suites_from_codeceptjs_dryrun() for ts in", "test) \"test-portal-profilePageTest\", # manual (executable test) \"test-portal-terraExportWarningTestPlan\", # manual (executable", "\"test-apis-dcfDataReplicationTest\", # manual (executable test) \"test-portal-exportPfbToWorkspaceTest\", # manual (executable test)", "# legacy (disabled test) \"test-regressions-submissionPerformanceTest\", # legacy (disabled test) \"test-dream-challenge-DCgen3clientTest\",", "not thread-safe \"test-google-googleDataAccessTest\", # not thread-safe \"test-google-googleServiceAccountRemovalTest\", # not thread-safe", "failures for invalid test labels \"test-portal-roleBasedUITest\", # manual (executable test)", "# manual (executable test) \"test-portal-limitedFilePFBExportTestPlan\", # manual (executable test) \"test-access-accessGUITest\",", "(executable test) \"test-portal-exportPfbToWorkspaceTest\", # manual (executable test) \"test-portal-homepageChartNodesExecutableTestPlan\",# manual (executable", "test) \"test-portal-404pageTest\", # manual (executable test) \"test-apis-dcfDataReplicationTest\", # manual (executable", "test) \"test-portal-homepageChartNodesExecutableTestPlan\",# manual (executable test) \"test-portal-profilePageTest\", # manual (executable test)", "# manual (executable test) \"test-pelican-exportPfbTest\", # not ready \"test-regressions-exportPerformanceTest\", #", "test) \"test-dream-challenge-DCgen3clientTest\", # legacy (disabled test) \"test-dream-challenge-synapaseLoginTest\", # legacy (disabled", "\"test-dream-challenge-synapaseLoginTest\", # legacy (disabled test) \"test-prod-checkAllProjectsBucketAccessTest\", # prod test \"test-portal-pfbExportTest\",", "test) \"test-portal-terraExportWarningTestPlan\", # manual (executable test) \"test-pelican-exportPfbTest\", # not ready", "long-running test \"test-apis-centralizedAuth\", # long-running test \"test-google-googleServiceAccountTest\", # long-running test", "long-running test \"test-portal-dataUploadTest\", # SUPER long-running test \"test-portal-indexingPageTest\", # long-running", "# nightly build test \"test-apis-etlTest\", # long-running test \"test-apis-centralizedAuth\", #", "\"test-portal-dataUploadTest\", # SUPER long-running test \"test-portal-indexingPageTest\", # long-running test \"test-apis-metadataIngestionTest\",", "# long-running test \"test-apis-metadataIngestionTest\", # long-running test \"test-apis-auditServiceTest\" # long-running", "test \"test-portal-dataUploadTest\", # SUPER long-running test \"test-portal-indexingPageTest\", # long-running test", "nightly build test \"test-apis-etlTest\", # long-running test \"test-apis-centralizedAuth\", # long-running", "manual (executable test) \"test-portal-homepageChartNodesExecutableTestPlan\",# manual (executable test) \"test-portal-profilePageTest\", # manual", "collect_test_suites_from_codeceptjs_dryrun(): my_env = os.environ.copy() bashCommand = \"npx codeceptjs dry-run\" process", "manual (executable test) \"test-pelican-exportPfbTest\", # not ready \"test-regressions-exportPerformanceTest\", # legacy", "env=my_env ) output, error = process.communicate() test_suites = [] for", "= line.decode(\"utf-8\") # print(f'### line: {line}') # ignore pre-release test", "(executable test) \"test-portal-discoveryPageTestPlan\", # manual (executable test) \"test-portal-dashboardReportsTest\", # manual", "legacy (disabled test) \"test-regressions-submissionPerformanceTest\", # legacy (disabled test) \"test-dream-challenge-DCgen3clientTest\", #", "\"test-access-accessGUITest\", # manual (executable test) \"test-portal-tieredAccessTest\", # manual (executable test)", "(executable test) \"test-portal-tieredAccessTest\", # manual (executable test) \"test-portal-discoveryPageTestPlan\", # manual", "test) \"test-guppy-nestedAggTest\", # manual (executable test) \"test-portal-404pageTest\", # manual (executable", "SUPER long-running test \"test-portal-indexingPageTest\", # long-running test \"test-apis-metadataIngestionTest\", # long-running", "full_path_to_test_js[-1] # print(f'## test_script: {test_script}') test_script_without_extension = test_script[0 : test_script.index(\".\")]", "elif \".js\" in line: full_path_to_test_js = line.split(\"/\") suite_folder = full_path_to_test_js[-2]", "@donot \"test-mariner-marinerIntegrationTest\", # @donot \"test-suites-fail\", # special suite to force", "test_suites def main(): test_suites = collect_test_suites_from_codeceptjs_dryrun() for ts in test_suites:", "not thread-safe \"test-smokeTests-brainTests\", # manual (executable test) \"test-batch-GoogleBucketManifestGenerationTest\", # @donot", "not thread-safe \"test-google-googleServiceAccountRemovalTest\", # not thread-safe \"test-guppy-guppyTest\", # not thread-safe", "(executable test) \"test-access-accessGUITest\", # manual (executable test) \"test-portal-tieredAccessTest\", # manual", "subprocess.Popen( bashCommand.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env ) output, error = process.communicate()", "\"pre-release\" in line: continue elif \".js\" in line: full_path_to_test_js =", "test_suites_that_cant_run_in_parallel = [ \"test-apis-dbgapTest\", # not thread-safe \"test-google-googleDataAccessTest\", # not", "test ] def collect_test_suites_from_codeceptjs_dryrun(): my_env = os.environ.copy() bashCommand = \"npx", "(executable test) \"test-batch-GoogleBucketManifestGenerationTest\", # @donot \"test-batch-S3BucketManifestGenerationTest\", # @donot \"test-portal-dataguidOrgTest\", #", "= collect_test_suites_from_codeceptjs_dryrun() for ts in test_suites: if ts not in", "collect_test_suites_from_codeceptjs_dryrun() for ts in test_suites: if ts not in test_suites_that_cant_run_in_parallel:", "manual (executable test) \"test-guppy-nestedAggTest\", # manual (executable test) \"test-portal-404pageTest\", #", "test suites if \"pre-release\" in line: continue elif \".js\" in", "test) \"test-prod-checkAllProjectsBucketAccessTest\", # prod test \"test-portal-pfbExportTest\", # nightly build test", "ready \"test-regressions-exportPerformanceTest\", # legacy (disabled test) \"test-regressions-generateTestData\", # legacy (disabled", "legacy (disabled test) \"test-regressions-queryPerformanceTest\", # legacy (disabled test) \"test-regressions-submissionPerformanceTest\", #", ": test_script.index(\".\")] test_suite = f\"test-{suite_folder}-{test_script_without_extension}\" test_suites.append(test_suite) return test_suites def main():", "test \"test-apis-auditServiceTest\" # long-running test ] def collect_test_suites_from_codeceptjs_dryrun(): my_env =", "os import subprocess test_suites_that_cant_run_in_parallel = [ \"test-apis-dbgapTest\", # not thread-safe", "\"npx codeceptjs dry-run\" process = subprocess.Popen( bashCommand.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env", "process = subprocess.Popen( bashCommand.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env ) output, error", "(executable test) \"test-guppy-nestedAggTest\", # manual (executable test) \"test-portal-404pageTest\", # manual", "# manual (executable test) \"test-portal-terraExportWarningTestPlan\", # manual (executable test) \"test-pelican-exportPfbTest\",", "] def collect_test_suites_from_codeceptjs_dryrun(): my_env = os.environ.copy() bashCommand = \"npx codeceptjs", "legacy (disabled test) \"test-dream-challenge-synapaseLoginTest\", # legacy (disabled test) \"test-prod-checkAllProjectsBucketAccessTest\", #", "error = process.communicate() test_suites = [] for line in output.splitlines():", "test) \"test-batch-GoogleBucketManifestGenerationTest\", # @donot \"test-batch-S3BucketManifestGenerationTest\", # @donot \"test-portal-dataguidOrgTest\", # @donot", "\"test-dream-challenge-DCgen3clientTest\", # legacy (disabled test) \"test-dream-challenge-synapaseLoginTest\", # legacy (disabled test)", "in output.splitlines(): line = line.decode(\"utf-8\") # print(f'### line: {line}') #", "suite_folder = full_path_to_test_js[-2] # print(f'## suite_folder: {suite_folder}') test_script = full_path_to_test_js[-1]", "# long-running test \"test-google-googleServiceAccountKeyTest\", # long-running test \"test-portal-dataUploadTest\", # SUPER" ]
[ "DruidQueryExecutor, SqliteQueryExecutor, SnowflakeQueryExecutor, ) from .executors.bigquery import BigQueryQueryExecutor ALL_PLUGIN_EXECUTORS =", "ALL_PLUGIN_EXECUTORS = import_plugin(\"executor_plugin\", \"ALL_PLUGIN_EXECUTORS\", []) ALL_EXECUTORS = [ HiveQueryExecutor, PrestoQueryExecutor,", "BigQueryQueryExecutor ALL_PLUGIN_EXECUTORS = import_plugin(\"executor_plugin\", \"ALL_PLUGIN_EXECUTORS\", []) ALL_EXECUTORS = [ HiveQueryExecutor,", "\"ALL_PLUGIN_EXECUTORS\", []) ALL_EXECUTORS = [ HiveQueryExecutor, PrestoQueryExecutor, MysqlQueryExecutor, DruidQueryExecutor, SqliteQueryExecutor,", "DruidQueryExecutor, SqliteQueryExecutor, BigQueryQueryExecutor, SnowflakeQueryExecutor, ] + ALL_PLUGIN_EXECUTORS def get_executor_class(language: str,", "in ALL_EXECUTORS: if ( executor.EXECUTOR_LANGUAGE() == language and executor.EXECUTOR_NAME() ==", "return executor raise ValueError(f\"Unknown executor {name} with language {language}\") #", ".executors.hive import HiveQueryExecutor from .executors.presto import PrestoQueryExecutor from .executors.sqlalchemy import", "from .executors.sqlalchemy import ( MysqlQueryExecutor, DruidQueryExecutor, SqliteQueryExecutor, SnowflakeQueryExecutor, ) from", "raise ValueError(f\"Unknown executor {name} with language {language}\") # Re-export parse_exception", "MysqlQueryExecutor, DruidQueryExecutor, SqliteQueryExecutor, BigQueryQueryExecutor, SnowflakeQueryExecutor, ] + ALL_PLUGIN_EXECUTORS def get_executor_class(language:", "str): for executor in ALL_EXECUTORS: if ( executor.EXECUTOR_LANGUAGE() == language", "] + ALL_PLUGIN_EXECUTORS def get_executor_class(language: str, name: str): for executor", ".executors.bigquery import BigQueryQueryExecutor ALL_PLUGIN_EXECUTORS = import_plugin(\"executor_plugin\", \"ALL_PLUGIN_EXECUTORS\", []) ALL_EXECUTORS =", "ValueError(f\"Unknown executor {name} with language {language}\") # Re-export parse_exception parse_exception", "ALL_EXECUTORS = [ HiveQueryExecutor, PrestoQueryExecutor, MysqlQueryExecutor, DruidQueryExecutor, SqliteQueryExecutor, BigQueryQueryExecutor, SnowflakeQueryExecutor,", "[]) ALL_EXECUTORS = [ HiveQueryExecutor, PrestoQueryExecutor, MysqlQueryExecutor, DruidQueryExecutor, SqliteQueryExecutor, BigQueryQueryExecutor,", "ALL_EXECUTORS: if ( executor.EXECUTOR_LANGUAGE() == language and executor.EXECUTOR_NAME() == name", "str, name: str): for executor in ALL_EXECUTORS: if ( executor.EXECUTOR_LANGUAGE()", "if ( executor.EXECUTOR_LANGUAGE() == language and executor.EXECUTOR_NAME() == name ):", "SqliteQueryExecutor, SnowflakeQueryExecutor, ) from .executors.bigquery import BigQueryQueryExecutor ALL_PLUGIN_EXECUTORS = import_plugin(\"executor_plugin\",", "lib.utils.plugin import import_plugin from .base_executor import parse_exception from .executors.hive import", "( MysqlQueryExecutor, DruidQueryExecutor, SqliteQueryExecutor, SnowflakeQueryExecutor, ) from .executors.bigquery import BigQueryQueryExecutor", "from .base_executor import parse_exception from .executors.hive import HiveQueryExecutor from .executors.presto", "parse_exception from .executors.hive import HiveQueryExecutor from .executors.presto import PrestoQueryExecutor from", "HiveQueryExecutor from .executors.presto import PrestoQueryExecutor from .executors.sqlalchemy import ( MysqlQueryExecutor,", "import BigQueryQueryExecutor ALL_PLUGIN_EXECUTORS = import_plugin(\"executor_plugin\", \"ALL_PLUGIN_EXECUTORS\", []) ALL_EXECUTORS = [", ".base_executor import parse_exception from .executors.hive import HiveQueryExecutor from .executors.presto import", "import_plugin(\"executor_plugin\", \"ALL_PLUGIN_EXECUTORS\", []) ALL_EXECUTORS = [ HiveQueryExecutor, PrestoQueryExecutor, MysqlQueryExecutor, DruidQueryExecutor,", "HiveQueryExecutor, PrestoQueryExecutor, MysqlQueryExecutor, DruidQueryExecutor, SqliteQueryExecutor, BigQueryQueryExecutor, SnowflakeQueryExecutor, ] + ALL_PLUGIN_EXECUTORS", "def get_executor_class(language: str, name: str): for executor in ALL_EXECUTORS: if", "executor in ALL_EXECUTORS: if ( executor.EXECUTOR_LANGUAGE() == language and executor.EXECUTOR_NAME()", "PrestoQueryExecutor from .executors.sqlalchemy import ( MysqlQueryExecutor, DruidQueryExecutor, SqliteQueryExecutor, SnowflakeQueryExecutor, )", "import parse_exception from .executors.hive import HiveQueryExecutor from .executors.presto import PrestoQueryExecutor", "language and executor.EXECUTOR_NAME() == name ): return executor raise ValueError(f\"Unknown", "executor raise ValueError(f\"Unknown executor {name} with language {language}\") # Re-export", "= [ HiveQueryExecutor, PrestoQueryExecutor, MysqlQueryExecutor, DruidQueryExecutor, SqliteQueryExecutor, BigQueryQueryExecutor, SnowflakeQueryExecutor, ]", "from .executors.bigquery import BigQueryQueryExecutor ALL_PLUGIN_EXECUTORS = import_plugin(\"executor_plugin\", \"ALL_PLUGIN_EXECUTORS\", []) ALL_EXECUTORS", "import HiveQueryExecutor from .executors.presto import PrestoQueryExecutor from .executors.sqlalchemy import (", "and executor.EXECUTOR_NAME() == name ): return executor raise ValueError(f\"Unknown executor", "BigQueryQueryExecutor, SnowflakeQueryExecutor, ] + ALL_PLUGIN_EXECUTORS def get_executor_class(language: str, name: str):", "get_executor_class(language: str, name: str): for executor in ALL_EXECUTORS: if (", "from lib.utils.plugin import import_plugin from .base_executor import parse_exception from .executors.hive", "name: str): for executor in ALL_EXECUTORS: if ( executor.EXECUTOR_LANGUAGE() ==", "executor.EXECUTOR_NAME() == name ): return executor raise ValueError(f\"Unknown executor {name}", "+ ALL_PLUGIN_EXECUTORS def get_executor_class(language: str, name: str): for executor in", "SqliteQueryExecutor, BigQueryQueryExecutor, SnowflakeQueryExecutor, ] + ALL_PLUGIN_EXECUTORS def get_executor_class(language: str, name:", "import import_plugin from .base_executor import parse_exception from .executors.hive import HiveQueryExecutor", "executor.EXECUTOR_LANGUAGE() == language and executor.EXECUTOR_NAME() == name ): return executor", "MysqlQueryExecutor, DruidQueryExecutor, SqliteQueryExecutor, SnowflakeQueryExecutor, ) from .executors.bigquery import BigQueryQueryExecutor ALL_PLUGIN_EXECUTORS", "import ( MysqlQueryExecutor, DruidQueryExecutor, SqliteQueryExecutor, SnowflakeQueryExecutor, ) from .executors.bigquery import", "name ): return executor raise ValueError(f\"Unknown executor {name} with language", "): return executor raise ValueError(f\"Unknown executor {name} with language {language}\")", "import_plugin from .base_executor import parse_exception from .executors.hive import HiveQueryExecutor from", "SnowflakeQueryExecutor, ] + ALL_PLUGIN_EXECUTORS def get_executor_class(language: str, name: str): for", "= import_plugin(\"executor_plugin\", \"ALL_PLUGIN_EXECUTORS\", []) ALL_EXECUTORS = [ HiveQueryExecutor, PrestoQueryExecutor, MysqlQueryExecutor,", "[ HiveQueryExecutor, PrestoQueryExecutor, MysqlQueryExecutor, DruidQueryExecutor, SqliteQueryExecutor, BigQueryQueryExecutor, SnowflakeQueryExecutor, ] +", "from .executors.presto import PrestoQueryExecutor from .executors.sqlalchemy import ( MysqlQueryExecutor, DruidQueryExecutor,", "SnowflakeQueryExecutor, ) from .executors.bigquery import BigQueryQueryExecutor ALL_PLUGIN_EXECUTORS = import_plugin(\"executor_plugin\", \"ALL_PLUGIN_EXECUTORS\",", ".executors.sqlalchemy import ( MysqlQueryExecutor, DruidQueryExecutor, SqliteQueryExecutor, SnowflakeQueryExecutor, ) from .executors.bigquery", "ALL_PLUGIN_EXECUTORS def get_executor_class(language: str, name: str): for executor in ALL_EXECUTORS:", "( executor.EXECUTOR_LANGUAGE() == language and executor.EXECUTOR_NAME() == name ): return", "== language and executor.EXECUTOR_NAME() == name ): return executor raise", "== name ): return executor raise ValueError(f\"Unknown executor {name} with", "import PrestoQueryExecutor from .executors.sqlalchemy import ( MysqlQueryExecutor, DruidQueryExecutor, SqliteQueryExecutor, SnowflakeQueryExecutor,", ".executors.presto import PrestoQueryExecutor from .executors.sqlalchemy import ( MysqlQueryExecutor, DruidQueryExecutor, SqliteQueryExecutor,", "PrestoQueryExecutor, MysqlQueryExecutor, DruidQueryExecutor, SqliteQueryExecutor, BigQueryQueryExecutor, SnowflakeQueryExecutor, ] + ALL_PLUGIN_EXECUTORS def", ") from .executors.bigquery import BigQueryQueryExecutor ALL_PLUGIN_EXECUTORS = import_plugin(\"executor_plugin\", \"ALL_PLUGIN_EXECUTORS\", [])", "from .executors.hive import HiveQueryExecutor from .executors.presto import PrestoQueryExecutor from .executors.sqlalchemy", "for executor in ALL_EXECUTORS: if ( executor.EXECUTOR_LANGUAGE() == language and" ]
[ "PYPI_COLOURS = itertools.cycle((Colours.yellow, Colours.blue, Colours.white)) ILLEGAL_CHARACTERS = re.compile(r\"[^-_.a-zA-Z0-9]+\") INVALID_INPUT_DELETE_DELAY =", "package.\" log.trace(f\"Error when fetching PyPi package: {response.status}.\") if error: error_message", "\"\"\"Cog for getting information about PyPi packages.\"\"\" def __init__(self, bot:", "embed.set_thumbnail(url=PYPI_ICON) error = True if characters := re.search(ILLEGAL_CHARACTERS, package): embed.description", "disnake import Embed, NotFound from disnake.ext.commands import Cog, Context, command", "= True if characters := re.search(ILLEGAL_CHARACTERS, package): embed.description = f\"Illegal", "be completely empty, or just whitespace. if summary and not", "\"Package could not be found.\" elif response.status == 200 and", "your PyPi package.\" log.trace(f\"Error when fetching PyPi package: {response.status}.\") if", "could be completely empty, or just whitespace. if summary and", "class PyPi(Cog): \"\"\"Cog for getting information about PyPi packages.\"\"\" def", "if summary and not summary.isspace(): embed.description = summary else: embed.description", "import itertools import random import re from contextlib import suppress", "await ctx.send(embed=embed) await wait_for_deletion(error_message, (ctx.author.id,), timeout=INVALID_INPUT_DELETE_DELAY) # Make sure that", "self.bot = bot @command(name=\"pypi\", aliases=(\"package\", \"pack\", \"pip\")) async def get_package_info(self,", "from contextlib import suppress from disnake import Embed, NotFound from", "__init__(self, bot: Bot): self.bot = bot @command(name=\"pypi\", aliases=(\"package\", \"pack\", \"pip\"))", "information about a specific package from PyPI.\"\"\" embed = Embed(title=random.choice(NEGATIVE_REPLIES),", "we won't cause a ghost-ping by deleting the message if", "message if not (ctx.message.mentions or ctx.message.role_mentions): with suppress(NotFound): await ctx.message.delete()", "contextlib import suppress from disnake import Embed, NotFound from disnake.ext.commands", "NEGATIVE_REPLIES, RedirectOutput from bot.log import get_logger from bot.utils.messages import wait_for_deletion", "info[\"package_url\"] embed.colour = next(PYPI_COLOURS) summary = escape_markdown(info[\"summary\"]) # Summary could", "ctx.message.delete() await error_message.delete() else: await ctx.send(embed=embed) def setup(bot: Bot) ->", "re.compile(r\"[^-_.a-zA-Z0-9]+\") INVALID_INPUT_DELETE_DELAY = RedirectOutput.delete_delay log = get_logger(__name__) class PyPi(Cog): \"\"\"Cog", "about a specific package from PyPI.\"\"\" embed = Embed(title=random.choice(NEGATIVE_REPLIES), colour=Colours.soft_red)", "-> None: \"\"\"Provide information about a specific package from PyPI.\"\"\"", "embed.title = f\"{info['name']} v{info['version']}\" embed.url = info[\"package_url\"] embed.colour = next(PYPI_COLOURS)", "await error_message.delete() else: await ctx.send(embed=embed) def setup(bot: Bot) -> None:", "from PyPI.\"\"\" embed = Embed(title=random.choice(NEGATIVE_REPLIES), colour=Colours.soft_red) embed.set_thumbnail(url=PYPI_ICON) error = True", "= \"Package could not be found.\" elif response.status == 200", "sure that we won't cause a ghost-ping by deleting the", "error when fetching your PyPi package.\" log.trace(f\"Error when fetching PyPi", "== 200 and response.content_type == \"application/json\": response_json = await response.json()", "a ghost-ping by deleting the message if not (ctx.message.mentions or", "into command: '{escape_markdown(characters.group(0))}'\" else: async with self.bot.http_session.get(URL.format(package=package)) as response: if", "Colours.white)) ILLEGAL_CHARACTERS = re.compile(r\"[^-_.a-zA-Z0-9]+\") INVALID_INPUT_DELETE_DELAY = RedirectOutput.delete_delay log = get_logger(__name__)", "command from disnake.utils import escape_markdown from bot.bot import Bot from", "URL = \"https://pypi.org/pypi/{package}/json\" PYPI_ICON = \"https://cdn.discordapp.com/emojis/766274397257334814.png\" PYPI_COLOURS = itertools.cycle((Colours.yellow, Colours.blue,", "for getting information about PyPi packages.\"\"\" def __init__(self, bot: Bot):", "= \"https://pypi.org/pypi/{package}/json\" PYPI_ICON = \"https://cdn.discordapp.com/emojis/766274397257334814.png\" PYPI_COLOURS = itertools.cycle((Colours.yellow, Colours.blue, Colours.white))", "import Colours, NEGATIVE_REPLIES, RedirectOutput from bot.log import get_logger from bot.utils.messages", "and response.content_type == \"application/json\": response_json = await response.json() info =", "with self.bot.http_session.get(URL.format(package=package)) as response: if response.status == 404: embed.description =", "= \"https://cdn.discordapp.com/emojis/766274397257334814.png\" PYPI_COLOURS = itertools.cycle((Colours.yellow, Colours.blue, Colours.white)) ILLEGAL_CHARACTERS = re.compile(r\"[^-_.a-zA-Z0-9]+\")", "== 404: embed.description = \"Package could not be found.\" elif", "await response.json() info = response_json[\"info\"] embed.title = f\"{info['name']} v{info['version']}\" embed.url", "summary else: embed.description = \"No summary provided.\" error = False", "# Make sure that we won't cause a ghost-ping by", "if error: error_message = await ctx.send(embed=embed) await wait_for_deletion(error_message, (ctx.author.id,), timeout=INVALID_INPUT_DELETE_DELAY)", "summary = escape_markdown(info[\"summary\"]) # Summary could be completely empty, or", "Summary could be completely empty, or just whitespace. if summary", "info = response_json[\"info\"] embed.title = f\"{info['name']} v{info['version']}\" embed.url = info[\"package_url\"]", "= summary else: embed.description = \"No summary provided.\" error =", "bot.log import get_logger from bot.utils.messages import wait_for_deletion URL = \"https://pypi.org/pypi/{package}/json\"", "NotFound from disnake.ext.commands import Cog, Context, command from disnake.utils import", "True if characters := re.search(ILLEGAL_CHARACTERS, package): embed.description = f\"Illegal character(s)", "just whitespace. if summary and not summary.isspace(): embed.description = summary", "was an error when fetching your PyPi package.\" log.trace(f\"Error when", "Cog, Context, command from disnake.utils import escape_markdown from bot.bot import", "\"https://cdn.discordapp.com/emojis/766274397257334814.png\" PYPI_COLOURS = itertools.cycle((Colours.yellow, Colours.blue, Colours.white)) ILLEGAL_CHARACTERS = re.compile(r\"[^-_.a-zA-Z0-9]+\") INVALID_INPUT_DELETE_DELAY", "completely empty, or just whitespace. if summary and not summary.isspace():", "suppress from disnake import Embed, NotFound from disnake.ext.commands import Cog,", "deleting the message if not (ctx.message.mentions or ctx.message.role_mentions): with suppress(NotFound):", "def setup(bot: Bot) -> None: \"\"\"Load the PyPi cog.\"\"\" bot.add_cog(PyPi(bot))", "\"\"\"Provide information about a specific package from PyPI.\"\"\" embed =", "Context, command from disnake.utils import escape_markdown from bot.bot import Bot", "found.\" elif response.status == 200 and response.content_type == \"application/json\": response_json", "PyPi package.\" log.trace(f\"Error when fetching PyPi package: {response.status}.\") if error:", "when fetching your PyPi package.\" log.trace(f\"Error when fetching PyPi package:", "aliases=(\"package\", \"pack\", \"pip\")) async def get_package_info(self, ctx: Context, package: str)", "re.search(ILLEGAL_CHARACTERS, package): embed.description = f\"Illegal character(s) passed into command: '{escape_markdown(characters.group(0))}'\"", "else: embed.description = \"There was an error when fetching your", "with suppress(NotFound): await ctx.message.delete() await error_message.delete() else: await ctx.send(embed=embed) def", "import Bot from bot.constants import Colours, NEGATIVE_REPLIES, RedirectOutput from bot.log", "async def get_package_info(self, ctx: Context, package: str) -> None: \"\"\"Provide", "= itertools.cycle((Colours.yellow, Colours.blue, Colours.white)) ILLEGAL_CHARACTERS = re.compile(r\"[^-_.a-zA-Z0-9]+\") INVALID_INPUT_DELETE_DELAY = RedirectOutput.delete_delay", "error = True if characters := re.search(ILLEGAL_CHARACTERS, package): embed.description =", "RedirectOutput from bot.log import get_logger from bot.utils.messages import wait_for_deletion URL", "# Summary could be completely empty, or just whitespace. if", "embed.url = info[\"package_url\"] embed.colour = next(PYPI_COLOURS) summary = escape_markdown(info[\"summary\"]) #", "import suppress from disnake import Embed, NotFound from disnake.ext.commands import", "characters := re.search(ILLEGAL_CHARACTERS, package): embed.description = f\"Illegal character(s) passed into", "embed = Embed(title=random.choice(NEGATIVE_REPLIES), colour=Colours.soft_red) embed.set_thumbnail(url=PYPI_ICON) error = True if characters", "else: embed.description = \"No summary provided.\" error = False else:", "not (ctx.message.mentions or ctx.message.role_mentions): with suppress(NotFound): await ctx.message.delete() await error_message.delete()", "= f\"Illegal character(s) passed into command: '{escape_markdown(characters.group(0))}'\" else: async with", "Make sure that we won't cause a ghost-ping by deleting", "\"There was an error when fetching your PyPi package.\" log.trace(f\"Error", "package from PyPI.\"\"\" embed = Embed(title=random.choice(NEGATIVE_REPLIES), colour=Colours.soft_red) embed.set_thumbnail(url=PYPI_ICON) error =", "a specific package from PyPI.\"\"\" embed = Embed(title=random.choice(NEGATIVE_REPLIES), colour=Colours.soft_red) embed.set_thumbnail(url=PYPI_ICON)", "information about PyPi packages.\"\"\" def __init__(self, bot: Bot): self.bot =", "command: '{escape_markdown(characters.group(0))}'\" else: async with self.bot.http_session.get(URL.format(package=package)) as response: if response.status", "about PyPi packages.\"\"\" def __init__(self, bot: Bot): self.bot = bot", "empty, or just whitespace. if summary and not summary.isspace(): embed.description", "= \"There was an error when fetching your PyPi package.\"", "wait_for_deletion URL = \"https://pypi.org/pypi/{package}/json\" PYPI_ICON = \"https://cdn.discordapp.com/emojis/766274397257334814.png\" PYPI_COLOURS = itertools.cycle((Colours.yellow,", "\"pip\")) async def get_package_info(self, ctx: Context, package: str) -> None:", "= get_logger(__name__) class PyPi(Cog): \"\"\"Cog for getting information about PyPi", "fetching PyPi package: {response.status}.\") if error: error_message = await ctx.send(embed=embed)", "await ctx.send(embed=embed) def setup(bot: Bot) -> None: \"\"\"Load the PyPi", "package: str) -> None: \"\"\"Provide information about a specific package", "or ctx.message.role_mentions): with suppress(NotFound): await ctx.message.delete() await error_message.delete() else: await", "and not summary.isspace(): embed.description = summary else: embed.description = \"No", "PyPi package: {response.status}.\") if error: error_message = await ctx.send(embed=embed) await", ":= re.search(ILLEGAL_CHARACTERS, package): embed.description = f\"Illegal character(s) passed into command:", "Embed(title=random.choice(NEGATIVE_REPLIES), colour=Colours.soft_red) embed.set_thumbnail(url=PYPI_ICON) error = True if characters := re.search(ILLEGAL_CHARACTERS,", "summary.isspace(): embed.description = summary else: embed.description = \"No summary provided.\"", "<filename>bot/exts/info/pypi.py import itertools import random import re from contextlib import", "= next(PYPI_COLOURS) summary = escape_markdown(info[\"summary\"]) # Summary could be completely", "ctx: Context, package: str) -> None: \"\"\"Provide information about a", "bot.constants import Colours, NEGATIVE_REPLIES, RedirectOutput from bot.log import get_logger from", "\"No summary provided.\" error = False else: embed.description = \"There", "response: if response.status == 404: embed.description = \"Package could not", "error_message.delete() else: await ctx.send(embed=embed) def setup(bot: Bot) -> None: \"\"\"Load", "character(s) passed into command: '{escape_markdown(characters.group(0))}'\" else: async with self.bot.http_session.get(URL.format(package=package)) as", "could not be found.\" elif response.status == 200 and response.content_type", "be found.\" elif response.status == 200 and response.content_type == \"application/json\":", "embed.description = \"Package could not be found.\" elif response.status ==", "from bot.bot import Bot from bot.constants import Colours, NEGATIVE_REPLIES, RedirectOutput", "if characters := re.search(ILLEGAL_CHARACTERS, package): embed.description = f\"Illegal character(s) passed", "{response.status}.\") if error: error_message = await ctx.send(embed=embed) await wait_for_deletion(error_message, (ctx.author.id,),", "won't cause a ghost-ping by deleting the message if not", "suppress(NotFound): await ctx.message.delete() await error_message.delete() else: await ctx.send(embed=embed) def setup(bot:", "bot.bot import Bot from bot.constants import Colours, NEGATIVE_REPLIES, RedirectOutput from", "= await ctx.send(embed=embed) await wait_for_deletion(error_message, (ctx.author.id,), timeout=INVALID_INPUT_DELETE_DELAY) # Make sure", "whitespace. if summary and not summary.isspace(): embed.description = summary else:", "bot.utils.messages import wait_for_deletion URL = \"https://pypi.org/pypi/{package}/json\" PYPI_ICON = \"https://cdn.discordapp.com/emojis/766274397257334814.png\" PYPI_COLOURS", "import Embed, NotFound from disnake.ext.commands import Cog, Context, command from", "passed into command: '{escape_markdown(characters.group(0))}'\" else: async with self.bot.http_session.get(URL.format(package=package)) as response:", "itertools.cycle((Colours.yellow, Colours.blue, Colours.white)) ILLEGAL_CHARACTERS = re.compile(r\"[^-_.a-zA-Z0-9]+\") INVALID_INPUT_DELETE_DELAY = RedirectOutput.delete_delay log", "ctx.send(embed=embed) def setup(bot: Bot) -> None: \"\"\"Load the PyPi cog.\"\"\"", "ghost-ping by deleting the message if not (ctx.message.mentions or ctx.message.role_mentions):", "= await response.json() info = response_json[\"info\"] embed.title = f\"{info['name']} v{info['version']}\"", "def get_package_info(self, ctx: Context, package: str) -> None: \"\"\"Provide information", "getting information about PyPi packages.\"\"\" def __init__(self, bot: Bot): self.bot", "error_message = await ctx.send(embed=embed) await wait_for_deletion(error_message, (ctx.author.id,), timeout=INVALID_INPUT_DELETE_DELAY) # Make", "when fetching PyPi package: {response.status}.\") if error: error_message = await", "an error when fetching your PyPi package.\" log.trace(f\"Error when fetching", "colour=Colours.soft_red) embed.set_thumbnail(url=PYPI_ICON) error = True if characters := re.search(ILLEGAL_CHARACTERS, package):", "Bot from bot.constants import Colours, NEGATIVE_REPLIES, RedirectOutput from bot.log import", "PYPI_ICON = \"https://cdn.discordapp.com/emojis/766274397257334814.png\" PYPI_COLOURS = itertools.cycle((Colours.yellow, Colours.blue, Colours.white)) ILLEGAL_CHARACTERS =", "PyPi packages.\"\"\" def __init__(self, bot: Bot): self.bot = bot @command(name=\"pypi\",", "= escape_markdown(info[\"summary\"]) # Summary could be completely empty, or just", "that we won't cause a ghost-ping by deleting the message", "itertools import random import re from contextlib import suppress from", "from disnake.utils import escape_markdown from bot.bot import Bot from bot.constants", "= bot @command(name=\"pypi\", aliases=(\"package\", \"pack\", \"pip\")) async def get_package_info(self, ctx:", "async with self.bot.http_session.get(URL.format(package=package)) as response: if response.status == 404: embed.description", "embed.description = summary else: embed.description = \"No summary provided.\" error", "not be found.\" elif response.status == 200 and response.content_type ==", "escape_markdown(info[\"summary\"]) # Summary could be completely empty, or just whitespace.", "if response.status == 404: embed.description = \"Package could not be", "from disnake import Embed, NotFound from disnake.ext.commands import Cog, Context,", "= f\"{info['name']} v{info['version']}\" embed.url = info[\"package_url\"] embed.colour = next(PYPI_COLOURS) summary", "Context, package: str) -> None: \"\"\"Provide information about a specific", "None: \"\"\"Provide information about a specific package from PyPI.\"\"\" embed", "Embed, NotFound from disnake.ext.commands import Cog, Context, command from disnake.utils", "'{escape_markdown(characters.group(0))}'\" else: async with self.bot.http_session.get(URL.format(package=package)) as response: if response.status ==", "response.status == 404: embed.description = \"Package could not be found.\"", "from bot.constants import Colours, NEGATIVE_REPLIES, RedirectOutput from bot.log import get_logger", "\"application/json\": response_json = await response.json() info = response_json[\"info\"] embed.title =", "response_json = await response.json() info = response_json[\"info\"] embed.title = f\"{info['name']}", "== \"application/json\": response_json = await response.json() info = response_json[\"info\"] embed.title", "or just whitespace. if summary and not summary.isspace(): embed.description =", "error = False else: embed.description = \"There was an error", "@command(name=\"pypi\", aliases=(\"package\", \"pack\", \"pip\")) async def get_package_info(self, ctx: Context, package:", "as response: if response.status == 404: embed.description = \"Package could", "not summary.isspace(): embed.description = summary else: embed.description = \"No summary", "error: error_message = await ctx.send(embed=embed) await wait_for_deletion(error_message, (ctx.author.id,), timeout=INVALID_INPUT_DELETE_DELAY) #", "ctx.send(embed=embed) await wait_for_deletion(error_message, (ctx.author.id,), timeout=INVALID_INPUT_DELETE_DELAY) # Make sure that we", "await ctx.message.delete() await error_message.delete() else: await ctx.send(embed=embed) def setup(bot: Bot)", "response.content_type == \"application/json\": response_json = await response.json() info = response_json[\"info\"]", "= RedirectOutput.delete_delay log = get_logger(__name__) class PyPi(Cog): \"\"\"Cog for getting", "summary provided.\" error = False else: embed.description = \"There was", "RedirectOutput.delete_delay log = get_logger(__name__) class PyPi(Cog): \"\"\"Cog for getting information", "next(PYPI_COLOURS) summary = escape_markdown(info[\"summary\"]) # Summary could be completely empty,", "wait_for_deletion(error_message, (ctx.author.id,), timeout=INVALID_INPUT_DELETE_DELAY) # Make sure that we won't cause", "log = get_logger(__name__) class PyPi(Cog): \"\"\"Cog for getting information about", "import Cog, Context, command from disnake.utils import escape_markdown from bot.bot", "(ctx.message.mentions or ctx.message.role_mentions): with suppress(NotFound): await ctx.message.delete() await error_message.delete() else:", "await wait_for_deletion(error_message, (ctx.author.id,), timeout=INVALID_INPUT_DELETE_DELAY) # Make sure that we won't", "from disnake.ext.commands import Cog, Context, command from disnake.utils import escape_markdown", "response_json[\"info\"] embed.title = f\"{info['name']} v{info['version']}\" embed.url = info[\"package_url\"] embed.colour =", "(ctx.author.id,), timeout=INVALID_INPUT_DELETE_DELAY) # Make sure that we won't cause a", "\"pack\", \"pip\")) async def get_package_info(self, ctx: Context, package: str) ->", "import random import re from contextlib import suppress from disnake", "self.bot.http_session.get(URL.format(package=package)) as response: if response.status == 404: embed.description = \"Package", "elif response.status == 200 and response.content_type == \"application/json\": response_json =", "import escape_markdown from bot.bot import Bot from bot.constants import Colours,", "response.status == 200 and response.content_type == \"application/json\": response_json = await", "disnake.utils import escape_markdown from bot.bot import Bot from bot.constants import", "embed.description = \"There was an error when fetching your PyPi", "bot @command(name=\"pypi\", aliases=(\"package\", \"pack\", \"pip\")) async def get_package_info(self, ctx: Context,", "= response_json[\"info\"] embed.title = f\"{info['name']} v{info['version']}\" embed.url = info[\"package_url\"] embed.colour", "from bot.log import get_logger from bot.utils.messages import wait_for_deletion URL =", "404: embed.description = \"Package could not be found.\" elif response.status", "the message if not (ctx.message.mentions or ctx.message.role_mentions): with suppress(NotFound): await", "get_package_info(self, ctx: Context, package: str) -> None: \"\"\"Provide information about", "else: async with self.bot.http_session.get(URL.format(package=package)) as response: if response.status == 404:", "log.trace(f\"Error when fetching PyPi package: {response.status}.\") if error: error_message =", "= Embed(title=random.choice(NEGATIVE_REPLIES), colour=Colours.soft_red) embed.set_thumbnail(url=PYPI_ICON) error = True if characters :=", "cause a ghost-ping by deleting the message if not (ctx.message.mentions", "random import re from contextlib import suppress from disnake import", "from bot.utils.messages import wait_for_deletion URL = \"https://pypi.org/pypi/{package}/json\" PYPI_ICON = \"https://cdn.discordapp.com/emojis/766274397257334814.png\"", "v{info['version']}\" embed.url = info[\"package_url\"] embed.colour = next(PYPI_COLOURS) summary = escape_markdown(info[\"summary\"])", "= info[\"package_url\"] embed.colour = next(PYPI_COLOURS) summary = escape_markdown(info[\"summary\"]) # Summary", "embed.description = \"No summary provided.\" error = False else: embed.description", "= False else: embed.description = \"There was an error when", "False else: embed.description = \"There was an error when fetching", "packages.\"\"\" def __init__(self, bot: Bot): self.bot = bot @command(name=\"pypi\", aliases=(\"package\",", "escape_markdown from bot.bot import Bot from bot.constants import Colours, NEGATIVE_REPLIES,", "disnake.ext.commands import Cog, Context, command from disnake.utils import escape_markdown from", "response.json() info = response_json[\"info\"] embed.title = f\"{info['name']} v{info['version']}\" embed.url =", "ctx.message.role_mentions): with suppress(NotFound): await ctx.message.delete() await error_message.delete() else: await ctx.send(embed=embed)", "PyPi(Cog): \"\"\"Cog for getting information about PyPi packages.\"\"\" def __init__(self,", "timeout=INVALID_INPUT_DELETE_DELAY) # Make sure that we won't cause a ghost-ping", "PyPI.\"\"\" embed = Embed(title=random.choice(NEGATIVE_REPLIES), colour=Colours.soft_red) embed.set_thumbnail(url=PYPI_ICON) error = True if", "re from contextlib import suppress from disnake import Embed, NotFound", "str) -> None: \"\"\"Provide information about a specific package from", "if not (ctx.message.mentions or ctx.message.role_mentions): with suppress(NotFound): await ctx.message.delete() await", "ILLEGAL_CHARACTERS = re.compile(r\"[^-_.a-zA-Z0-9]+\") INVALID_INPUT_DELETE_DELAY = RedirectOutput.delete_delay log = get_logger(__name__) class", "embed.colour = next(PYPI_COLOURS) summary = escape_markdown(info[\"summary\"]) # Summary could be", "bot: Bot): self.bot = bot @command(name=\"pypi\", aliases=(\"package\", \"pack\", \"pip\")) async", "summary and not summary.isspace(): embed.description = summary else: embed.description =", "200 and response.content_type == \"application/json\": response_json = await response.json() info", "by deleting the message if not (ctx.message.mentions or ctx.message.role_mentions): with", "else: await ctx.send(embed=embed) def setup(bot: Bot) -> None: \"\"\"Load the", "embed.description = f\"Illegal character(s) passed into command: '{escape_markdown(characters.group(0))}'\" else: async", "get_logger(__name__) class PyPi(Cog): \"\"\"Cog for getting information about PyPi packages.\"\"\"", "import get_logger from bot.utils.messages import wait_for_deletion URL = \"https://pypi.org/pypi/{package}/json\" PYPI_ICON", "f\"{info['name']} v{info['version']}\" embed.url = info[\"package_url\"] embed.colour = next(PYPI_COLOURS) summary =", "def __init__(self, bot: Bot): self.bot = bot @command(name=\"pypi\", aliases=(\"package\", \"pack\",", "get_logger from bot.utils.messages import wait_for_deletion URL = \"https://pypi.org/pypi/{package}/json\" PYPI_ICON =", "provided.\" error = False else: embed.description = \"There was an", "= \"No summary provided.\" error = False else: embed.description =", "Colours, NEGATIVE_REPLIES, RedirectOutput from bot.log import get_logger from bot.utils.messages import", "Colours.blue, Colours.white)) ILLEGAL_CHARACTERS = re.compile(r\"[^-_.a-zA-Z0-9]+\") INVALID_INPUT_DELETE_DELAY = RedirectOutput.delete_delay log =", "import re from contextlib import suppress from disnake import Embed,", "package: {response.status}.\") if error: error_message = await ctx.send(embed=embed) await wait_for_deletion(error_message,", "f\"Illegal character(s) passed into command: '{escape_markdown(characters.group(0))}'\" else: async with self.bot.http_session.get(URL.format(package=package))", "fetching your PyPi package.\" log.trace(f\"Error when fetching PyPi package: {response.status}.\")", "import wait_for_deletion URL = \"https://pypi.org/pypi/{package}/json\" PYPI_ICON = \"https://cdn.discordapp.com/emojis/766274397257334814.png\" PYPI_COLOURS =", "Bot): self.bot = bot @command(name=\"pypi\", aliases=(\"package\", \"pack\", \"pip\")) async def", "INVALID_INPUT_DELETE_DELAY = RedirectOutput.delete_delay log = get_logger(__name__) class PyPi(Cog): \"\"\"Cog for", "package): embed.description = f\"Illegal character(s) passed into command: '{escape_markdown(characters.group(0))}'\" else:", "= re.compile(r\"[^-_.a-zA-Z0-9]+\") INVALID_INPUT_DELETE_DELAY = RedirectOutput.delete_delay log = get_logger(__name__) class PyPi(Cog):", "specific package from PyPI.\"\"\" embed = Embed(title=random.choice(NEGATIVE_REPLIES), colour=Colours.soft_red) embed.set_thumbnail(url=PYPI_ICON) error", "\"https://pypi.org/pypi/{package}/json\" PYPI_ICON = \"https://cdn.discordapp.com/emojis/766274397257334814.png\" PYPI_COLOURS = itertools.cycle((Colours.yellow, Colours.blue, Colours.white)) ILLEGAL_CHARACTERS" ]
[ "current_user.can(permission): abort(403) return f(*args, **kwargs) return decorated_function return decorator def", "decorated_function(*args,**kwargs): if not current_user.can(permission): abort(403) return f(*args,**kwargs) return decorated_function return", "wraps from flask import abort from flask_login import current_user from", "if not current_user.can(permission): abort(403) return f(*args,**kwargs) return decorated_function return decorator", "not current_user.can(permission): abort(403) return f(*args, **kwargs) return decorated_function return decorator", "abort(403) return f(*args,**kwargs) return decorated_function return decorator def admin_required(f): return", "not current_user.can(permission): abort(403) return f(*args,**kwargs) return decorated_function return decorator def", "from flask_login import current_user from .models import Permission <<<<<<< HEAD", "def decorated_function(*args,**kwargs): if not current_user.can(permission): abort(403) return f(*args,**kwargs) return decorated_function", "def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not", "@wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return f(*args,", "**kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER)(f) =======", "return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER)(f) ======= def", "<<<<<<< HEAD def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs):", "abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f):", "return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return", "from functools import wraps from flask import abort from flask_login", "permission_required(Permission.ADMINISTER)(f) ======= def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args,**kwargs): if", "decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return", "**kwargs): if not current_user.can(permission): abort(403) return f(*args, **kwargs) return decorated_function", "return f(*args,**kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER)(f)", "return decorator def admin_required(f): return permission_required(Permission.ADMINISTER)(f) ======= def permission_required(permission): def", ".models import Permission <<<<<<< HEAD def permission_required(permission): def decorator(f): @wraps(f)", "abort from flask_login import current_user from .models import Permission <<<<<<<", "permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission):", "if not current_user.can(permission): abort(403) return f(*args, **kwargs) return decorated_function return", "return permission_required(Permission.ADMINISTER)(f) ======= def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args,**kwargs):", "======= def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args,**kwargs): if not", "current_user.can(permission): abort(403) return f(*args,**kwargs) return decorated_function return decorator def admin_required(f):", "f(*args,**kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER)(f) >>>>>>>", "def admin_required(f): return permission_required(Permission.ADMINISTER)(f) ======= def permission_required(permission): def decorator(f): @wraps(f)", "import abort from flask_login import current_user from .models import Permission", "from .models import Permission <<<<<<< HEAD def permission_required(permission): def decorator(f):", "decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER)(f) ======= def permission_required(permission):", "Permission <<<<<<< HEAD def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args,", "current_user from .models import Permission <<<<<<< HEAD def permission_required(permission): def", "def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403)", "decorator(f): @wraps(f) def decorated_function(*args,**kwargs): if not current_user.can(permission): abort(403) return f(*args,**kwargs)", "admin_required(f): return permission_required(Permission.ADMINISTER)(f) ======= def permission_required(permission): def decorator(f): @wraps(f) def", "@wraps(f) def decorated_function(*args,**kwargs): if not current_user.can(permission): abort(403) return f(*args,**kwargs) return", "f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER)(f)", "decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return f(*args, **kwargs) return", "from flask import abort from flask_login import current_user from .models", "import current_user from .models import Permission <<<<<<< HEAD def permission_required(permission):", "def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args,**kwargs): if not current_user.can(permission):", "import wraps from flask import abort from flask_login import current_user", "functools import wraps from flask import abort from flask_login import", "HEAD def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if", "return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER)(f) >>>>>>> 17-app-1", "flask_login import current_user from .models import Permission <<<<<<< HEAD def", "def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return f(*args, **kwargs)", "import Permission <<<<<<< HEAD def permission_required(permission): def decorator(f): @wraps(f) def", "def decorator(f): @wraps(f) def decorated_function(*args,**kwargs): if not current_user.can(permission): abort(403) return", "flask import abort from flask_login import current_user from .models import", "permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args,**kwargs): if not current_user.can(permission): abort(403)", "decorator def admin_required(f): return permission_required(Permission.ADMINISTER)(f) ======= def permission_required(permission): def decorator(f):" ]
[ "# @Author : Fangyang # @Software : PyCharm import sys", "# -*- coding:utf-8 -*- # @Datetime : 2019/11/14 上午2:26 #", "import QApplication import pyqtgraph as pg import numpy as np", "1000)) plotWidget = pg.plot(title='Three plot curves') for i in range(3):", "<reponame>jojoquant/jnpy # !/usr/bin/env python3 # -*- coding:utf-8 -*- # @Datetime", "3)) status = app.exec_() sys.exit(status) if __name__ == '__main__': pass", "@Datetime : 2019/11/14 上午2:26 # @Author : Fangyang # @Software", "-*- # @Datetime : 2019/11/14 上午2:26 # @Author : Fangyang", "import pyqtgraph as pg import numpy as np app =", "np app = QApplication(sys.argv) x = np.arange(1000) y = np.random.normal(size=(3,", "y = np.random.normal(size=(3, 1000)) plotWidget = pg.plot(title='Three plot curves') for", "plotWidget = pg.plot(title='Three plot curves') for i in range(3): plotWidget.plot(x,", "pen=(i, 3)) status = app.exec_() sys.exit(status) if __name__ == '__main__':", "QApplication(sys.argv) x = np.arange(1000) y = np.random.normal(size=(3, 1000)) plotWidget =", "pg import numpy as np app = QApplication(sys.argv) x =", "# @Software : PyCharm import sys from PyQt5.QtWidgets import QApplication", "-*- coding:utf-8 -*- # @Datetime : 2019/11/14 上午2:26 # @Author", "= pg.plot(title='Three plot curves') for i in range(3): plotWidget.plot(x, y[i],", "# @Datetime : 2019/11/14 上午2:26 # @Author : Fangyang #", ": 2019/11/14 上午2:26 # @Author : Fangyang # @Software :", "= np.random.normal(size=(3, 1000)) plotWidget = pg.plot(title='Three plot curves') for i", "PyCharm import sys from PyQt5.QtWidgets import QApplication import pyqtgraph as", "curves') for i in range(3): plotWidget.plot(x, y[i], pen=(i, 3)) status", "pyqtgraph as pg import numpy as np app = QApplication(sys.argv)", "for i in range(3): plotWidget.plot(x, y[i], pen=(i, 3)) status =", "y[i], pen=(i, 3)) status = app.exec_() sys.exit(status) if __name__ ==", "python3 # -*- coding:utf-8 -*- # @Datetime : 2019/11/14 上午2:26", "2019/11/14 上午2:26 # @Author : Fangyang # @Software : PyCharm", "np.arange(1000) y = np.random.normal(size=(3, 1000)) plotWidget = pg.plot(title='Three plot curves')", "PyQt5.QtWidgets import QApplication import pyqtgraph as pg import numpy as", "x = np.arange(1000) y = np.random.normal(size=(3, 1000)) plotWidget = pg.plot(title='Three", "in range(3): plotWidget.plot(x, y[i], pen=(i, 3)) status = app.exec_() sys.exit(status)", "np.random.normal(size=(3, 1000)) plotWidget = pg.plot(title='Three plot curves') for i in", "i in range(3): plotWidget.plot(x, y[i], pen=(i, 3)) status = app.exec_()", "import sys from PyQt5.QtWidgets import QApplication import pyqtgraph as pg", "app = QApplication(sys.argv) x = np.arange(1000) y = np.random.normal(size=(3, 1000))", "@Software : PyCharm import sys from PyQt5.QtWidgets import QApplication import", "import numpy as np app = QApplication(sys.argv) x = np.arange(1000)", "= np.arange(1000) y = np.random.normal(size=(3, 1000)) plotWidget = pg.plot(title='Three plot", "!/usr/bin/env python3 # -*- coding:utf-8 -*- # @Datetime : 2019/11/14", "@Author : Fangyang # @Software : PyCharm import sys from", "上午2:26 # @Author : Fangyang # @Software : PyCharm import", "QApplication import pyqtgraph as pg import numpy as np app", "Fangyang # @Software : PyCharm import sys from PyQt5.QtWidgets import", "as pg import numpy as np app = QApplication(sys.argv) x", "numpy as np app = QApplication(sys.argv) x = np.arange(1000) y", "plotWidget.plot(x, y[i], pen=(i, 3)) status = app.exec_() sys.exit(status) if __name__", ": Fangyang # @Software : PyCharm import sys from PyQt5.QtWidgets", "sys from PyQt5.QtWidgets import QApplication import pyqtgraph as pg import", "as np app = QApplication(sys.argv) x = np.arange(1000) y =", "= QApplication(sys.argv) x = np.arange(1000) y = np.random.normal(size=(3, 1000)) plotWidget", "pg.plot(title='Three plot curves') for i in range(3): plotWidget.plot(x, y[i], pen=(i,", "coding:utf-8 -*- # @Datetime : 2019/11/14 上午2:26 # @Author :", ": PyCharm import sys from PyQt5.QtWidgets import QApplication import pyqtgraph", "range(3): plotWidget.plot(x, y[i], pen=(i, 3)) status = app.exec_() sys.exit(status) if", "# !/usr/bin/env python3 # -*- coding:utf-8 -*- # @Datetime :", "plot curves') for i in range(3): plotWidget.plot(x, y[i], pen=(i, 3))", "from PyQt5.QtWidgets import QApplication import pyqtgraph as pg import numpy" ]
[ "Config from .cython_generator import ( CythonGenerator, get_func_definition ) from .ext_module", "Scan, elementwise ) from .profile import ( get_profile_info, named_profile, profile,", ") from .translator import ( CConverter, CStructHelper, OpenCLConverter, detect_type, ocl_detect_type,", "from .types import KnownType, annotate, declare from .utils import ArgumentParser", "print_profile, profile_kernel, ProfileContext, profile2csv ) from .translator import ( CConverter,", "Reduction, Scan, elementwise ) from .profile import ( get_profile_info, named_profile,", "get_func_definition ) from .ext_module import ExtModule from .extern import Extern", "OpenCLConverter, detect_type, ocl_detect_type, py2c ) from .types import KnownType, annotate,", "from .ext_module import ExtModule from .extern import Extern from .low_level", "import Extern from .low_level import Kernel, LocalMem, Cython, cast from", ".ast_utils import (get_symbols, get_assigned, get_unknown_names_and_calls, has_return, has_node) from .config import", "( Elementwise, Reduction, Scan, elementwise ) from .profile import (", "( CythonGenerator, get_func_definition ) from .ext_module import ExtModule from .extern", "import (get_symbols, get_assigned, get_unknown_names_and_calls, has_return, has_node) from .config import get_config,", ".extern import Extern from .low_level import Kernel, LocalMem, Cython, cast", "detect_type, ocl_detect_type, py2c ) from .types import KnownType, annotate, declare", "( CConverter, CStructHelper, OpenCLConverter, detect_type, ocl_detect_type, py2c ) from .types", "wrap from .ast_utils import (get_symbols, get_assigned, get_unknown_names_and_calls, has_return, has_node) from", "from .ast_utils import (get_symbols, get_assigned, get_unknown_names_and_calls, has_return, has_node) from .config", "has_return, has_node) from .config import get_config, set_config, use_config, Config from", "( get_profile_info, named_profile, profile, profile_ctx, print_profile, profile_kernel, ProfileContext, profile2csv )", "ocl_detect_type, py2c ) from .types import KnownType, annotate, declare from", "from .cython_generator import ( CythonGenerator, get_func_definition ) from .ext_module import", "Cython, cast from .parallel import ( Elementwise, Reduction, Scan, elementwise", "named_profile, profile, profile_ctx, print_profile, profile_kernel, ProfileContext, profile2csv ) from .translator", "py2c ) from .types import KnownType, annotate, declare from .utils", ") from .types import KnownType, annotate, declare from .utils import", "import ( Elementwise, Reduction, Scan, elementwise ) from .profile import", "CythonGenerator, get_func_definition ) from .ext_module import ExtModule from .extern import", ".translator import ( CConverter, CStructHelper, OpenCLConverter, detect_type, ocl_detect_type, py2c )", ") from .ext_module import ExtModule from .extern import Extern from", "cast from .parallel import ( Elementwise, Reduction, Scan, elementwise )", "ExtModule from .extern import Extern from .low_level import Kernel, LocalMem,", "import get_config, set_config, use_config, Config from .cython_generator import ( CythonGenerator,", ".profile import ( get_profile_info, named_profile, profile, profile_ctx, print_profile, profile_kernel, ProfileContext,", "elementwise ) from .profile import ( get_profile_info, named_profile, profile, profile_ctx,", ") from .profile import ( get_profile_info, named_profile, profile, profile_ctx, print_profile,", "import Array, wrap from .ast_utils import (get_symbols, get_assigned, get_unknown_names_and_calls, has_return,", ".ext_module import ExtModule from .extern import Extern from .low_level import", ".low_level import Kernel, LocalMem, Cython, cast from .parallel import (", ".cython_generator import ( CythonGenerator, get_func_definition ) from .ext_module import ExtModule", "from .extern import Extern from .low_level import Kernel, LocalMem, Cython,", "ProfileContext, profile2csv ) from .translator import ( CConverter, CStructHelper, OpenCLConverter,", "Kernel, LocalMem, Cython, cast from .parallel import ( Elementwise, Reduction,", "from .profile import ( get_profile_info, named_profile, profile, profile_ctx, print_profile, profile_kernel,", "CConverter, CStructHelper, OpenCLConverter, detect_type, ocl_detect_type, py2c ) from .types import", "from .translator import ( CConverter, CStructHelper, OpenCLConverter, detect_type, ocl_detect_type, py2c", "Extern from .low_level import Kernel, LocalMem, Cython, cast from .parallel", "(get_symbols, get_assigned, get_unknown_names_and_calls, has_return, has_node) from .config import get_config, set_config,", ".array import Array, wrap from .ast_utils import (get_symbols, get_assigned, get_unknown_names_and_calls,", "get_profile_info, named_profile, profile, profile_ctx, print_profile, profile_kernel, ProfileContext, profile2csv ) from", "set_config, use_config, Config from .cython_generator import ( CythonGenerator, get_func_definition )", "Array, wrap from .ast_utils import (get_symbols, get_assigned, get_unknown_names_and_calls, has_return, has_node)", "import ExtModule from .extern import Extern from .low_level import Kernel,", "from .config import get_config, set_config, use_config, Config from .cython_generator import", ".config import get_config, set_config, use_config, Config from .cython_generator import (", "get_config, set_config, use_config, Config from .cython_generator import ( CythonGenerator, get_func_definition", "from .low_level import Kernel, LocalMem, Cython, cast from .parallel import", "use_config, Config from .cython_generator import ( CythonGenerator, get_func_definition ) from", "from .array import Array, wrap from .ast_utils import (get_symbols, get_assigned,", "import Kernel, LocalMem, Cython, cast from .parallel import ( Elementwise,", "from .parallel import ( Elementwise, Reduction, Scan, elementwise ) from", "import ( get_profile_info, named_profile, profile, profile_ctx, print_profile, profile_kernel, ProfileContext, profile2csv", "import ( CConverter, CStructHelper, OpenCLConverter, detect_type, ocl_detect_type, py2c ) from", "CStructHelper, OpenCLConverter, detect_type, ocl_detect_type, py2c ) from .types import KnownType,", "LocalMem, Cython, cast from .parallel import ( Elementwise, Reduction, Scan,", "profile, profile_ctx, print_profile, profile_kernel, ProfileContext, profile2csv ) from .translator import", "has_node) from .config import get_config, set_config, use_config, Config from .cython_generator", "profile_ctx, print_profile, profile_kernel, ProfileContext, profile2csv ) from .translator import (", "profile2csv ) from .translator import ( CConverter, CStructHelper, OpenCLConverter, detect_type,", "Elementwise, Reduction, Scan, elementwise ) from .profile import ( get_profile_info,", "import ( CythonGenerator, get_func_definition ) from .ext_module import ExtModule from", "get_assigned, get_unknown_names_and_calls, has_return, has_node) from .config import get_config, set_config, use_config,", "profile_kernel, ProfileContext, profile2csv ) from .translator import ( CConverter, CStructHelper,", "get_unknown_names_and_calls, has_return, has_node) from .config import get_config, set_config, use_config, Config", ".parallel import ( Elementwise, Reduction, Scan, elementwise ) from .profile" ]