hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
f7256c23b14e3bf3204687769f2e778d96ed7ed4
2,818
py
Python
MA cross.py
0xTDF/Quant-Trading-Strategy-Backtesting-Framework
d77089bab3513013d456819e9790e67e44adec8e
[ "MIT" ]
1
2022-03-25T07:50:15.000Z
2022-03-25T07:50:15.000Z
MA cross.py
Elisik/Quant-Trading-Strategy-Backtesting-Framework
d77089bab3513013d456819e9790e67e44adec8e
[ "MIT" ]
null
null
null
MA cross.py
Elisik/Quant-Trading-Strategy-Backtesting-Framework
d77089bab3513013d456819e9790e67e44adec8e
[ "MIT" ]
null
null
null
import backtrader as bt import backtrader.analyzers as bta from datetime import datetime import matplotlib.pyplot as plt import yfinance class MaCrossStrategy(bt.Strategy): # signal generator def __init__(self): ma_fast = bt.ind.SMA(period = 10) ma_slow = bt.ind.SMA(period = 20) self.crossover = bt.ind.CrossOver(ma_fast, ma_slow) # executes order from the signals def next(self): if not self.position: if self.crossover > 0: self.buy() elif self.crossover < 0: self.close() cerebro = bt.Cerebro() # pulls price data from yahoo finance data = bt.feeds.YahooFinanceCSVData(dataname='BTC-USD.csv') # converts to log chart data.plotinfo.plotlog = True # adds data to engine cerebro.adddata(data) # adds strategy to engine cerebro.addstrategy(MaCrossStrategy) # sets starting capital cerebro.broker.setcash(1000.0) # sets size per trade cerebro.addsizer(bt.sizers.PercentSizer, percents = 10) # analysis cerebro.addanalyzer(bta.SharpeRatio, _name = "sharpe") cerebro.addanalyzer(bta.Transactions, _name = "trans") cerebro.addanalyzer(bta.TradeAnalyzer, _name = "trades") # runs back test back = cerebro.run() print(cerebro.broker.getvalue()) # useful output data sharpeRatio = back[0].analyzers.sharpe.get_analysis() print(sharpeRatio) transactions = back[0].analyzers.trans.get_analysis() #print(transactions) tradeAnalyzer = back[0].analyzers.trades.get_analysis() #print(tradeAnalyzer) # colour scheme of plot plt.style.use('fivethirtyeight') plt.rcParams["figure.figsize"] = (10, 6) plt.rcParams['lines.linewidth'] = 1 SIZE = 7 plt.rcParams['axes.labelsize'] = SIZE plt.rcParams['ytick.labelsize'] = SIZE plt.rcParams['xtick.labelsize'] = SIZE plt.rcParams["font.size"] = SIZE COLOR = '1' plt.rcParams['text.color'] = COLOR plt.rcParams['axes.labelcolor'] = COLOR plt.rcParams['xtick.color'] = COLOR plt.rcParams['ytick.color'] = COLOR plt.rcParams['grid.linewidth']=0.1 plt.rcParams['grid.color']="#101622" plt.rcParams['lines.color']="0.5" plt.rcParams['axes.edgecolor']="0.2" plt.rcParams['axes.linewidth']=0.5 plt.rcParams['figure.facecolor']="#101622" plt.rcParams['axes.facecolor']="#101622" plt.rcParams["savefig.dpi"]=120 dpi = plt.rcParams["savefig.dpi"] width = 1080 height = 1920 plt.rcParams['figure.figsize'] = height/dpi, width/dpi plt.rcParams["savefig.facecolor"] ="#101622" plt.rcParams["savefig.edgecolor"]="#101622" plt.rcParams['legend.fontsize'] = SIZE plt.rcParams['legend.title_fontsize'] = SIZE + 1 plt.rcParams['legend.labelspacing'] =0.25 plt.rcParams['image.cmap']='tab10' cerebro.plot(style = 'candle',barup='white', bardown='#1973c2',volume = False) plt.show()
26.584906
79
0.694109
import backtrader as bt import backtrader.analyzers as bta from datetime import datetime import matplotlib.pyplot as plt import yfinance class MaCrossStrategy(bt.Strategy): def __init__(self): ma_fast = bt.ind.SMA(period = 10) ma_slow = bt.ind.SMA(period = 20) self.crossover = bt.ind.CrossOver(ma_fast, ma_slow) def next(self): if not self.position: if self.crossover > 0: self.buy() elif self.crossover < 0: self.close() cerebro = bt.Cerebro() data = bt.feeds.YahooFinanceCSVData(dataname='BTC-USD.csv') data.plotinfo.plotlog = True cerebro.adddata(data) cerebro.addstrategy(MaCrossStrategy) cerebro.broker.setcash(1000.0) cerebro.addsizer(bt.sizers.PercentSizer, percents = 10) cerebro.addanalyzer(bta.SharpeRatio, _name = "sharpe") cerebro.addanalyzer(bta.Transactions, _name = "trans") cerebro.addanalyzer(bta.TradeAnalyzer, _name = "trades") back = cerebro.run() print(cerebro.broker.getvalue()) sharpeRatio = back[0].analyzers.sharpe.get_analysis() print(sharpeRatio) transactions = back[0].analyzers.trans.get_analysis() tradeAnalyzer = back[0].analyzers.trades.get_analysis() plt.style.use('fivethirtyeight') plt.rcParams["figure.figsize"] = (10, 6) plt.rcParams['lines.linewidth'] = 1 SIZE = 7 plt.rcParams['axes.labelsize'] = SIZE plt.rcParams['ytick.labelsize'] = SIZE plt.rcParams['xtick.labelsize'] = SIZE plt.rcParams["font.size"] = SIZE COLOR = '1' plt.rcParams['text.color'] = COLOR plt.rcParams['axes.labelcolor'] = COLOR plt.rcParams['xtick.color'] = COLOR plt.rcParams['ytick.color'] = COLOR plt.rcParams['grid.linewidth']=0.1 plt.rcParams['grid.color']="#101622" plt.rcParams['lines.color']="0.5" plt.rcParams['axes.edgecolor']="0.2" plt.rcParams['axes.linewidth']=0.5 plt.rcParams['figure.facecolor']="#101622" plt.rcParams['axes.facecolor']="#101622" plt.rcParams["savefig.dpi"]=120 dpi = plt.rcParams["savefig.dpi"] width = 1080 height = 1920 plt.rcParams['figure.figsize'] = height/dpi, width/dpi plt.rcParams["savefig.facecolor"] ="#101622" plt.rcParams["savefig.edgecolor"]="#101622" plt.rcParams['legend.fontsize'] = SIZE plt.rcParams['legend.title_fontsize'] = SIZE + 1 plt.rcParams['legend.labelspacing'] =0.25 plt.rcParams['image.cmap']='tab10' cerebro.plot(style = 'candle',barup='white', bardown='#1973c2',volume = False) plt.show()
true
true
f7256d283ba52ce9290a4bd6ce811edcc7a1208a
8,082
py
Python
juriscraper/opinions/united_states_backscrapers/federal_appellate/ca5.py
drewsilcock/juriscraper
706a05f739e10f22b81b9bb16767415d810e49d1
[ "BSD-2-Clause" ]
null
null
null
juriscraper/opinions/united_states_backscrapers/federal_appellate/ca5.py
drewsilcock/juriscraper
706a05f739e10f22b81b9bb16767415d810e49d1
[ "BSD-2-Clause" ]
null
null
null
juriscraper/opinions/united_states_backscrapers/federal_appellate/ca5.py
drewsilcock/juriscraper
706a05f739e10f22b81b9bb16767415d810e49d1
[ "BSD-2-Clause" ]
null
null
null
from lxml import html from datetime import datetime, timedelta, date from dateutil.rrule import DAILY, rrule from selenium.common.exceptions import NoSuchElementException from juriscraper.AbstractSite import logger from juriscraper.OpinionSiteWebDriven import OpinionSiteWebDriven class Site(OpinionSiteWebDriven): def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.url = "http://www.ca5.uscourts.gov/electronic-case-filing/case-information/current-opinions" self.court_id = self.__module__ self.interval = 5 self.case_date = datetime.today() self.back_scrape_iterable = [ i.date() for i in rrule( DAILY, interval=self.interval, # Every interval days dtstart=date(1992, 5, 14), until=date(2015, 1, 1), ) ] self.uses_selenium = True def _download(self, request_dict={}): if self.test_mode_enabled(): html_tree_list = [ super(Site, self)._download(request_dict=request_dict) ] self.records_nr = len( html_tree_list[0].xpath( "//tr[contains(concat('', @id, ''), 'ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00')]" ) ) return html_tree_list else: logger.info("Running Selenium browser...") self.initiate_webdriven_session() self.wait_for_id("ctl00_Body_C010_ctl00_ctl00_endDate_dateInput") start_date = self.webdriver.find_element_by_id( "ctl00_Body_C010_ctl00_ctl00_startDate_dateInput" ) start_date.send_keys( (self.case_date - timedelta(days=self.interval)).strftime( "%m/%d/%Y" ) ) end_date = self.webdriver.find_element_by_id( "ctl00_Body_C010_ctl00_ctl00_endDate_dateInput" ) end_date.send_keys(self.case_date.strftime("%m/%d/%Y")) submit = self.webdriver.find_element_by_id( "Body_C010_ctl00_ctl00_btnSearch" ) submit.click() self.wait_for_id( "ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00" ) self.status = 200 try: nr_of_pages = self.webdriver.find_element_by_xpath( '//div[contains(concat(" ", @class, " "), "rgInfoPart")]/strong[2]' ) records_nr = self.webdriver.find_element_by_xpath( '//div[contains(concat(" ", @class, " "), "rgInfoPart")]/strong[1]' ) self.records_nr = int(records_nr.text) nr_of_pages = int(nr_of_pages.text) except NoSuchElementException: try: self.records_nr = len( self.webdriver.find_elements_by_xpath( "//tr[contains(concat('', @id, ''), 'ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00')]" ) ) nr_of_pages = 1 except NoSuchElementException: self.webdriver.quit() return [] html_pages = [] logger.info( "records: {}, pages: {}".format(self.records_nr, nr_of_pages) ) if nr_of_pages == 1: text = self.webdriver.page_source self.webdriver.quit() html_tree = html.fromstring(text) html_tree.make_links_absolute(self.url) remove_anchors = lambda url: url.split("#")[0] html_tree.rewrite_links(remove_anchors) html_pages.append(html_tree) else: logger.info( "Paginating through %s pages of results." % nr_of_pages ) logger.info(" Getting page 1") text = self.webdriver.page_source html_tree = html.fromstring(text) html_tree.make_links_absolute(self.url) remove_anchors = lambda url: url.split("#")[0] html_tree.rewrite_links(remove_anchors) html_pages.append(html_tree) for i in range(nr_of_pages - 1): logger.info(" Getting page %s" % (i + 2)) next_page = self.webdriver.find_element_by_class_name( "rgPageNext" ) next_page.click() self.webdriver.implicitly_wait(5) text = self.webdriver.page_source html_tree = html.fromstring(text) html_tree.make_links_absolute(self.url) remove_anchors = lambda url: url.split("#")[0] html_tree.rewrite_links(remove_anchors) html_pages.append(html_tree) self.webdriver.quit() return html_pages def _get_case_names(self): case_names = [] for html_tree in self.html: page_records_count = self._get_opinion_count(html_tree) for record in range(page_records_count): path = "id('ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00__{n}')/td[4]/text()".format( n=record ) case_names.append(html_tree.xpath(path)[0]) return case_names def _get_download_urls(self): for html_tree in self.html: page_records_count = self._get_opinion_count(html_tree) for record in range(page_records_count): path = "id('ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00__{n}')/td[2]/a/@href".format( n=record ) yield html_tree.xpath(path)[0] def _get_case_dates(self): for html_tree in self.html: page_records_count = self._get_opinion_count(html_tree) for record in range(page_records_count): path = "id('ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00__{n}')/td[3]/text()".format( n=record ) yield datetime.strptime(html_tree.xpath(path)[0], "%m/%d/%Y") def _get_docket_numbers(self): for html_tree in self.html: page_records_count = self._get_opinion_count(html_tree) for record in range(page_records_count): path = "id('ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00__{n}')/td[2]/a/text()".format( n=record ) yield html_tree.xpath(path)[0] def _get_precedential_statuses(self): for html_tree in self.html: page_records_count = self._get_opinion_count(html_tree) for record in range(page_records_count): path = "id('ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00__{n}')/td[5]/text()".format( n=record ) yield "Unpublished" if "unpub" in html_tree.xpath(path)[ 0 ] else "Published" @staticmethod def _get_opinion_count(html_tree): return int( html_tree.xpath( "count(//tr[contains(concat('', @id, ''), 'ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00')])" ) ) def _download_backwards(self, d): self.case_date = d logger.info( "Running backscraper with date range: %s to %s" % ( self.case_date - timedelta(days=self.interval), self.case_date, ) ) self.html = self._download() if self.html is not None: # Setting status is important because it prevents the download # function from being run a second time by the parse method. self.status = 200
39.23301
118
0.548627
from lxml import html from datetime import datetime, timedelta, date from dateutil.rrule import DAILY, rrule from selenium.common.exceptions import NoSuchElementException from juriscraper.AbstractSite import logger from juriscraper.OpinionSiteWebDriven import OpinionSiteWebDriven class Site(OpinionSiteWebDriven): def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.url = "http://www.ca5.uscourts.gov/electronic-case-filing/case-information/current-opinions" self.court_id = self.__module__ self.interval = 5 self.case_date = datetime.today() self.back_scrape_iterable = [ i.date() for i in rrule( DAILY, interval=self.interval, dtstart=date(1992, 5, 14), until=date(2015, 1, 1), ) ] self.uses_selenium = True def _download(self, request_dict={}): if self.test_mode_enabled(): html_tree_list = [ super(Site, self)._download(request_dict=request_dict) ] self.records_nr = len( html_tree_list[0].xpath( "//tr[contains(concat('', @id, ''), 'ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00')]" ) ) return html_tree_list else: logger.info("Running Selenium browser...") self.initiate_webdriven_session() self.wait_for_id("ctl00_Body_C010_ctl00_ctl00_endDate_dateInput") start_date = self.webdriver.find_element_by_id( "ctl00_Body_C010_ctl00_ctl00_startDate_dateInput" ) start_date.send_keys( (self.case_date - timedelta(days=self.interval)).strftime( "%m/%d/%Y" ) ) end_date = self.webdriver.find_element_by_id( "ctl00_Body_C010_ctl00_ctl00_endDate_dateInput" ) end_date.send_keys(self.case_date.strftime("%m/%d/%Y")) submit = self.webdriver.find_element_by_id( "Body_C010_ctl00_ctl00_btnSearch" ) submit.click() self.wait_for_id( "ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00" ) self.status = 200 try: nr_of_pages = self.webdriver.find_element_by_xpath( '//div[contains(concat(" ", @class, " "), "rgInfoPart")]/strong[2]' ) records_nr = self.webdriver.find_element_by_xpath( '//div[contains(concat(" ", @class, " "), "rgInfoPart")]/strong[1]' ) self.records_nr = int(records_nr.text) nr_of_pages = int(nr_of_pages.text) except NoSuchElementException: try: self.records_nr = len( self.webdriver.find_elements_by_xpath( "//tr[contains(concat('', @id, ''), 'ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00')]" ) ) nr_of_pages = 1 except NoSuchElementException: self.webdriver.quit() return [] html_pages = [] logger.info( "records: {}, pages: {}".format(self.records_nr, nr_of_pages) ) if nr_of_pages == 1: text = self.webdriver.page_source self.webdriver.quit() html_tree = html.fromstring(text) html_tree.make_links_absolute(self.url) remove_anchors = lambda url: url.split("#")[0] html_tree.rewrite_links(remove_anchors) html_pages.append(html_tree) else: logger.info( "Paginating through %s pages of results." % nr_of_pages ) logger.info(" Getting page 1") text = self.webdriver.page_source html_tree = html.fromstring(text) html_tree.make_links_absolute(self.url) remove_anchors = lambda url: url.split("#")[0] html_tree.rewrite_links(remove_anchors) html_pages.append(html_tree) for i in range(nr_of_pages - 1): logger.info(" Getting page %s" % (i + 2)) next_page = self.webdriver.find_element_by_class_name( "rgPageNext" ) next_page.click() self.webdriver.implicitly_wait(5) text = self.webdriver.page_source html_tree = html.fromstring(text) html_tree.make_links_absolute(self.url) remove_anchors = lambda url: url.split("#")[0] html_tree.rewrite_links(remove_anchors) html_pages.append(html_tree) self.webdriver.quit() return html_pages def _get_case_names(self): case_names = [] for html_tree in self.html: page_records_count = self._get_opinion_count(html_tree) for record in range(page_records_count): path = "id('ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00__{n}')/td[4]/text()".format( n=record ) case_names.append(html_tree.xpath(path)[0]) return case_names def _get_download_urls(self): for html_tree in self.html: page_records_count = self._get_opinion_count(html_tree) for record in range(page_records_count): path = "id('ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00__{n}')/td[2]/a/@href".format( n=record ) yield html_tree.xpath(path)[0] def _get_case_dates(self): for html_tree in self.html: page_records_count = self._get_opinion_count(html_tree) for record in range(page_records_count): path = "id('ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00__{n}')/td[3]/text()".format( n=record ) yield datetime.strptime(html_tree.xpath(path)[0], "%m/%d/%Y") def _get_docket_numbers(self): for html_tree in self.html: page_records_count = self._get_opinion_count(html_tree) for record in range(page_records_count): path = "id('ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00__{n}')/td[2]/a/text()".format( n=record ) yield html_tree.xpath(path)[0] def _get_precedential_statuses(self): for html_tree in self.html: page_records_count = self._get_opinion_count(html_tree) for record in range(page_records_count): path = "id('ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00__{n}')/td[5]/text()".format( n=record ) yield "Unpublished" if "unpub" in html_tree.xpath(path)[ 0 ] else "Published" @staticmethod def _get_opinion_count(html_tree): return int( html_tree.xpath( "count(//tr[contains(concat('', @id, ''), 'ctl00_Body_C010_ctl00_ctl00_radGridOpinions_ctl00')])" ) ) def _download_backwards(self, d): self.case_date = d logger.info( "Running backscraper with date range: %s to %s" % ( self.case_date - timedelta(days=self.interval), self.case_date, ) ) self.html = self._download() if self.html is not None: self.status = 200
true
true
f7256de9d9a438b0f395aac6da42babe3f3800f4
11,937
py
Python
tests/integration/test_polymorphic_parts/test.py
monadbobo/ClickHouse
73b0f8db8c327a1d63cc7ebcc56087a3f9866dae
[ "Apache-2.0" ]
3
2021-09-14T08:36:18.000Z
2022-02-24T02:55:38.000Z
tests/integration/test_polymorphic_parts/test.py
monadbobo/ClickHouse
73b0f8db8c327a1d63cc7ebcc56087a3f9866dae
[ "Apache-2.0" ]
1
2020-04-04T04:25:47.000Z
2020-04-04T04:25:47.000Z
tests/integration/test_polymorphic_parts/test.py
monadbobo/ClickHouse
73b0f8db8c327a1d63cc7ebcc56087a3f9866dae
[ "Apache-2.0" ]
1
2020-05-18T11:31:48.000Z
2020-05-18T11:31:48.000Z
import time import pytest import random import string from helpers.test_tools import TSV from helpers.test_tools import assert_eq_with_retry from helpers.cluster import ClickHouseCluster cluster = ClickHouseCluster(__file__) def get_random_array(): return [random.randint(0, 1000) % 1000 for _ in range(random.randint(0, 1000))] def get_random_string(): length = random.randint(0, 1000) return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(length)) def insert_random_data(table, node, size): data = [ '(' + ','.join(( "'2019-10-11'", str(i), "'" + get_random_string() + "'", str(get_random_array()))) + ')' for i in range(size) ] node.query("INSERT INTO {} VALUES {}".format(table, ','.join(data))) def create_tables(name, nodes, node_settings, shard): for i, (node, settings) in enumerate(zip(nodes, node_settings)): node.query( ''' CREATE TABLE {name}(date Date, id UInt32, s String, arr Array(Int32)) ENGINE = ReplicatedMergeTree('/clickhouse/tables/test/{shard}/{name}', '{repl}') PARTITION BY toYYYYMM(date) ORDER BY id SETTINGS index_granularity = {index_granularity}, index_granularity_bytes = {index_granularity_bytes}, min_rows_for_wide_part = {min_rows_for_wide_part}, min_bytes_for_wide_part = {min_bytes_for_wide_part} '''.format(name=name, shard=shard, repl=i, **settings)) def create_tables_old_format(name, nodes, shard): for i, node in enumerate(nodes): node.query( ''' CREATE TABLE {name}(date Date, id UInt32, s String, arr Array(Int32)) ENGINE = ReplicatedMergeTree('/clickhouse/tables/test/{shard}/{name}', '{repl}', date, id, 64) '''.format(name=name, shard=shard, repl=i)) node1 = cluster.add_instance('node1', config_dir="configs", with_zookeeper=True) node2 = cluster.add_instance('node2', config_dir="configs", with_zookeeper=True) settings_default = {'index_granularity' : 64, 'index_granularity_bytes' : 10485760, 'min_rows_for_wide_part' : 512, 'min_bytes_for_wide_part' : 0} settings_not_adaptive = {'index_granularity' : 64, 'index_granularity_bytes' : 0, 'min_rows_for_wide_part' : 512, 'min_bytes_for_wide_part' : 0} node3 = cluster.add_instance('node3', config_dir="configs", with_zookeeper=True) node4 = cluster.add_instance('node4', config_dir="configs", main_configs=['configs/no_leader.xml'], with_zookeeper=True) settings_compact = {'index_granularity' : 64, 'index_granularity_bytes' : 10485760, 'min_rows_for_wide_part' : 512, 'min_bytes_for_wide_part' : 0} settings_wide = {'index_granularity' : 64, 'index_granularity_bytes' : 10485760, 'min_rows_for_wide_part' : 0, 'min_bytes_for_wide_part' : 0} node5 = cluster.add_instance('node5', config_dir='configs', main_configs=['configs/compact_parts.xml'], with_zookeeper=True) node6 = cluster.add_instance('node6', config_dir='configs', main_configs=['configs/compact_parts.xml'], with_zookeeper=True) @pytest.fixture(scope="module") def start_cluster(): try: cluster.start() create_tables('polymorphic_table', [node1, node2], [settings_default, settings_default], "shard1") create_tables('non_adaptive_table', [node1, node2], [settings_not_adaptive, settings_default], "shard1") create_tables('polymorphic_table_compact', [node3, node4], [settings_compact, settings_wide], "shard2") create_tables('polymorphic_table_wide', [node3, node4], [settings_wide, settings_compact], "shard2") create_tables_old_format('polymorphic_table', [node5, node6], "shard3") yield cluster finally: cluster.shutdown() @pytest.mark.parametrize( ('first_node', 'second_node'), [ (node1, node2), (node5, node6) ] ) def test_polymorphic_parts_basics(start_cluster, first_node, second_node): first_node.query("SYSTEM STOP MERGES") second_node.query("SYSTEM STOP MERGES") for size in [300, 300, 600]: insert_random_data('polymorphic_table', first_node, size) second_node.query("SYSTEM SYNC REPLICA polymorphic_table", timeout=20) assert first_node.query("SELECT count() FROM polymorphic_table") == "1200\n" assert second_node.query("SELECT count() FROM polymorphic_table") == "1200\n" expected = "Compact\t2\nWide\t1\n" assert TSV(first_node.query("SELECT part_type, count() FROM system.parts " \ "WHERE table = 'polymorphic_table' AND active GROUP BY part_type ORDER BY part_type")) == TSV(expected) assert TSV(second_node.query("SELECT part_type, count() FROM system.parts " \ "WHERE table = 'polymorphic_table' AND active GROUP BY part_type ORDER BY part_type")) == TSV(expected) first_node.query("SYSTEM START MERGES") second_node.query("SYSTEM START MERGES") for _ in range(40): insert_random_data('polymorphic_table', first_node, 10) insert_random_data('polymorphic_table', second_node, 10) first_node.query("SYSTEM SYNC REPLICA polymorphic_table", timeout=20) second_node.query("SYSTEM SYNC REPLICA polymorphic_table", timeout=20) assert first_node.query("SELECT count() FROM polymorphic_table") == "2000\n" assert second_node.query("SELECT count() FROM polymorphic_table") == "2000\n" first_node.query("OPTIMIZE TABLE polymorphic_table FINAL") second_node.query("SYSTEM SYNC REPLICA polymorphic_table", timeout=20) assert first_node.query("SELECT count() FROM polymorphic_table") == "2000\n" assert second_node.query("SELECT count() FROM polymorphic_table") == "2000\n" assert first_node.query("SELECT DISTINCT part_type FROM system.parts WHERE table = 'polymorphic_table' AND active") == "Wide\n" assert second_node.query("SELECT DISTINCT part_type FROM system.parts WHERE table = 'polymorphic_table' AND active") == "Wide\n" # Check alters and mutations also work first_node.query("ALTER TABLE polymorphic_table ADD COLUMN ss String") first_node.query("ALTER TABLE polymorphic_table UPDATE ss = toString(id) WHERE 1") second_node.query("SYSTEM SYNC REPLICA polymorphic_table", timeout=20) first_node.query("SELECT count(ss) FROM polymorphic_table") == "2000\n" first_node.query("SELECT uniqExact(ss) FROM polymorphic_table") == "600\n" second_node.query("SELECT count(ss) FROM polymorphic_table") == "2000\n" second_node.query("SELECT uniqExact(ss) FROM polymorphic_table") == "600\n" # Check that follower replicas create parts of the same type, which leader has chosen at merge. @pytest.mark.parametrize( ('table', 'part_type'), [ ('polymorphic_table_compact', 'Compact'), ('polymorphic_table_wide', 'Wide') ] ) def test_different_part_types_on_replicas(start_cluster, table, part_type): leader = node3 follower = node4 assert leader.query("SELECT is_leader FROM system.replicas WHERE table = '{}'".format(table)) == "1\n" assert node4.query("SELECT is_leader FROM system.replicas WHERE table = '{}'".format(table)) == "0\n" for _ in range(3): insert_random_data(table, leader, 100) leader.query("OPTIMIZE TABLE {} FINAL".format(table)) follower.query("SYSTEM SYNC REPLICA {}".format(table), timeout=20) expected = "{}\t1\n".format(part_type) assert TSV(leader.query("SELECT part_type, count() FROM system.parts " \ "WHERE table = '{}' AND active GROUP BY part_type ORDER BY part_type".format(table))) == TSV(expected) assert TSV(follower.query("SELECT part_type, count() FROM system.parts " \ "WHERE table = '{}' AND active GROUP BY part_type ORDER BY part_type".format(table))) == TSV(expected) node7 = cluster.add_instance('node7', config_dir="configs", with_zookeeper=True, image='yandex/clickhouse-server:19.17.8.54', stay_alive=True, with_installed_binary=True) node8 = cluster.add_instance('node8', config_dir="configs", with_zookeeper=True) settings7 = {'index_granularity' : 64, 'index_granularity_bytes' : 10485760} settings8 = {'index_granularity' : 64, 'index_granularity_bytes' : 10485760, 'min_rows_for_wide_part' : 512, 'min_bytes_for_wide_part' : 0} @pytest.fixture(scope="module") def start_cluster_diff_versions(): try: for name in ['polymorphic_table', 'polymorphic_table_2']: cluster.start() node7.query( ''' CREATE TABLE {name}(date Date, id UInt32, s String, arr Array(Int32)) ENGINE = ReplicatedMergeTree('/clickhouse/tables/test/shard5/{name}', '1') PARTITION BY toYYYYMM(date) ORDER BY id SETTINGS index_granularity = {index_granularity}, index_granularity_bytes = {index_granularity_bytes} '''.format(name=name, **settings7) ) node8.query( ''' CREATE TABLE {name}(date Date, id UInt32, s String, arr Array(Int32)) ENGINE = ReplicatedMergeTree('/clickhouse/tables/test/shard5/{name}', '2') PARTITION BY toYYYYMM(date) ORDER BY id SETTINGS index_granularity = {index_granularity}, index_granularity_bytes = {index_granularity_bytes}, min_rows_for_wide_part = {min_rows_for_wide_part}, min_bytes_for_wide_part = {min_bytes_for_wide_part} '''.format(name=name, **settings8) ) yield cluster finally: cluster.shutdown() @pytest.mark.skip(reason="compatability is temporary broken") def test_polymorphic_parts_diff_versions(start_cluster_diff_versions): # Check that replication with Wide parts works between different versions. node_old = node7 node_new = node8 insert_random_data('polymorphic_table', node7, 100) node8.query("SYSTEM SYNC REPLICA polymorphic_table", timeout=20) assert node8.query("SELECT count() FROM polymorphic_table") == "100\n" assert node8.query("SELECT DISTINCT part_type FROM system.parts WHERE table = 'polymorphic_table' and active") == "Wide\n" @pytest.mark.skip(reason="compatability is temporary broken") def test_polymorphic_parts_diff_versions_2(start_cluster_diff_versions): # Replication doesn't work on old version if part is created in compact format, because # this version doesn't know anything about it. It's considered to be ok. node_old = node7 node_new = node8 insert_random_data('polymorphic_table_2', node_new, 100) assert node_new.query("SELECT count() FROM polymorphic_table_2") == "100\n" assert node_old.query("SELECT count() FROM polymorphic_table_2") == "0\n" with pytest.raises(Exception): node_old.query("SYSTEM SYNC REPLICA polymorphic_table_2", timeout=3) node_old.restart_with_latest_version() node_old.query("SYSTEM SYNC REPLICA polymorphic_table_2", timeout=20) # Works after update assert node_old.query("SELECT count() FROM polymorphic_table_2") == "100\n" assert node_old.query("SELECT DISTINCT part_type FROM system.parts WHERE table = 'polymorphic_table_2' and active") == "Compact\n" def test_polymorphic_parts_non_adaptive(start_cluster): node1.query("SYSTEM STOP MERGES") node2.query("SYSTEM STOP MERGES") insert_random_data('non_adaptive_table', node1, 100) node2.query("SYSTEM SYNC REPLICA non_adaptive_table", timeout=20) insert_random_data('non_adaptive_table', node2, 100) node1.query("SYSTEM SYNC REPLICA non_adaptive_table", timeout=20) assert TSV(node1.query("SELECT part_type, count() FROM system.parts " \ "WHERE table = 'non_adaptive_table' AND active GROUP BY part_type ORDER BY part_type")) == TSV("Wide\t2\n") assert TSV(node2.query("SELECT part_type, count() FROM system.parts " \ "WHERE table = 'non_adaptive_table' AND active GROUP BY part_type ORDER BY part_type")) == TSV("Wide\t2\n") assert node1.contains_in_log("<Warning> default.non_adaptive_table: Table can't create parts with adaptive granularity")
45.387833
170
0.70981
import time import pytest import random import string from helpers.test_tools import TSV from helpers.test_tools import assert_eq_with_retry from helpers.cluster import ClickHouseCluster cluster = ClickHouseCluster(__file__) def get_random_array(): return [random.randint(0, 1000) % 1000 for _ in range(random.randint(0, 1000))] def get_random_string(): length = random.randint(0, 1000) return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(length)) def insert_random_data(table, node, size): data = [ '(' + ','.join(( "'2019-10-11'", str(i), "'" + get_random_string() + "'", str(get_random_array()))) + ')' for i in range(size) ] node.query("INSERT INTO {} VALUES {}".format(table, ','.join(data))) def create_tables(name, nodes, node_settings, shard): for i, (node, settings) in enumerate(zip(nodes, node_settings)): node.query( ''' CREATE TABLE {name}(date Date, id UInt32, s String, arr Array(Int32)) ENGINE = ReplicatedMergeTree('/clickhouse/tables/test/{shard}/{name}', '{repl}') PARTITION BY toYYYYMM(date) ORDER BY id SETTINGS index_granularity = {index_granularity}, index_granularity_bytes = {index_granularity_bytes}, min_rows_for_wide_part = {min_rows_for_wide_part}, min_bytes_for_wide_part = {min_bytes_for_wide_part} '''.format(name=name, shard=shard, repl=i, **settings)) def create_tables_old_format(name, nodes, shard): for i, node in enumerate(nodes): node.query( ''' CREATE TABLE {name}(date Date, id UInt32, s String, arr Array(Int32)) ENGINE = ReplicatedMergeTree('/clickhouse/tables/test/{shard}/{name}', '{repl}', date, id, 64) '''.format(name=name, shard=shard, repl=i)) node1 = cluster.add_instance('node1', config_dir="configs", with_zookeeper=True) node2 = cluster.add_instance('node2', config_dir="configs", with_zookeeper=True) settings_default = {'index_granularity' : 64, 'index_granularity_bytes' : 10485760, 'min_rows_for_wide_part' : 512, 'min_bytes_for_wide_part' : 0} settings_not_adaptive = {'index_granularity' : 64, 'index_granularity_bytes' : 0, 'min_rows_for_wide_part' : 512, 'min_bytes_for_wide_part' : 0} node3 = cluster.add_instance('node3', config_dir="configs", with_zookeeper=True) node4 = cluster.add_instance('node4', config_dir="configs", main_configs=['configs/no_leader.xml'], with_zookeeper=True) settings_compact = {'index_granularity' : 64, 'index_granularity_bytes' : 10485760, 'min_rows_for_wide_part' : 512, 'min_bytes_for_wide_part' : 0} settings_wide = {'index_granularity' : 64, 'index_granularity_bytes' : 10485760, 'min_rows_for_wide_part' : 0, 'min_bytes_for_wide_part' : 0} node5 = cluster.add_instance('node5', config_dir='configs', main_configs=['configs/compact_parts.xml'], with_zookeeper=True) node6 = cluster.add_instance('node6', config_dir='configs', main_configs=['configs/compact_parts.xml'], with_zookeeper=True) @pytest.fixture(scope="module") def start_cluster(): try: cluster.start() create_tables('polymorphic_table', [node1, node2], [settings_default, settings_default], "shard1") create_tables('non_adaptive_table', [node1, node2], [settings_not_adaptive, settings_default], "shard1") create_tables('polymorphic_table_compact', [node3, node4], [settings_compact, settings_wide], "shard2") create_tables('polymorphic_table_wide', [node3, node4], [settings_wide, settings_compact], "shard2") create_tables_old_format('polymorphic_table', [node5, node6], "shard3") yield cluster finally: cluster.shutdown() @pytest.mark.parametrize( ('first_node', 'second_node'), [ (node1, node2), (node5, node6) ] ) def test_polymorphic_parts_basics(start_cluster, first_node, second_node): first_node.query("SYSTEM STOP MERGES") second_node.query("SYSTEM STOP MERGES") for size in [300, 300, 600]: insert_random_data('polymorphic_table', first_node, size) second_node.query("SYSTEM SYNC REPLICA polymorphic_table", timeout=20) assert first_node.query("SELECT count() FROM polymorphic_table") == "1200\n" assert second_node.query("SELECT count() FROM polymorphic_table") == "1200\n" expected = "Compact\t2\nWide\t1\n" assert TSV(first_node.query("SELECT part_type, count() FROM system.parts " \ "WHERE table = 'polymorphic_table' AND active GROUP BY part_type ORDER BY part_type")) == TSV(expected) assert TSV(second_node.query("SELECT part_type, count() FROM system.parts " \ "WHERE table = 'polymorphic_table' AND active GROUP BY part_type ORDER BY part_type")) == TSV(expected) first_node.query("SYSTEM START MERGES") second_node.query("SYSTEM START MERGES") for _ in range(40): insert_random_data('polymorphic_table', first_node, 10) insert_random_data('polymorphic_table', second_node, 10) first_node.query("SYSTEM SYNC REPLICA polymorphic_table", timeout=20) second_node.query("SYSTEM SYNC REPLICA polymorphic_table", timeout=20) assert first_node.query("SELECT count() FROM polymorphic_table") == "2000\n" assert second_node.query("SELECT count() FROM polymorphic_table") == "2000\n" first_node.query("OPTIMIZE TABLE polymorphic_table FINAL") second_node.query("SYSTEM SYNC REPLICA polymorphic_table", timeout=20) assert first_node.query("SELECT count() FROM polymorphic_table") == "2000\n" assert second_node.query("SELECT count() FROM polymorphic_table") == "2000\n" assert first_node.query("SELECT DISTINCT part_type FROM system.parts WHERE table = 'polymorphic_table' AND active") == "Wide\n" assert second_node.query("SELECT DISTINCT part_type FROM system.parts WHERE table = 'polymorphic_table' AND active") == "Wide\n" first_node.query("ALTER TABLE polymorphic_table ADD COLUMN ss String") first_node.query("ALTER TABLE polymorphic_table UPDATE ss = toString(id) WHERE 1") second_node.query("SYSTEM SYNC REPLICA polymorphic_table", timeout=20) first_node.query("SELECT count(ss) FROM polymorphic_table") == "2000\n" first_node.query("SELECT uniqExact(ss) FROM polymorphic_table") == "600\n" second_node.query("SELECT count(ss) FROM polymorphic_table") == "2000\n" second_node.query("SELECT uniqExact(ss) FROM polymorphic_table") == "600\n" @pytest.mark.parametrize( ('table', 'part_type'), [ ('polymorphic_table_compact', 'Compact'), ('polymorphic_table_wide', 'Wide') ] ) def test_different_part_types_on_replicas(start_cluster, table, part_type): leader = node3 follower = node4 assert leader.query("SELECT is_leader FROM system.replicas WHERE table = '{}'".format(table)) == "1\n" assert node4.query("SELECT is_leader FROM system.replicas WHERE table = '{}'".format(table)) == "0\n" for _ in range(3): insert_random_data(table, leader, 100) leader.query("OPTIMIZE TABLE {} FINAL".format(table)) follower.query("SYSTEM SYNC REPLICA {}".format(table), timeout=20) expected = "{}\t1\n".format(part_type) assert TSV(leader.query("SELECT part_type, count() FROM system.parts " \ "WHERE table = '{}' AND active GROUP BY part_type ORDER BY part_type".format(table))) == TSV(expected) assert TSV(follower.query("SELECT part_type, count() FROM system.parts " \ "WHERE table = '{}' AND active GROUP BY part_type ORDER BY part_type".format(table))) == TSV(expected) node7 = cluster.add_instance('node7', config_dir="configs", with_zookeeper=True, image='yandex/clickhouse-server:19.17.8.54', stay_alive=True, with_installed_binary=True) node8 = cluster.add_instance('node8', config_dir="configs", with_zookeeper=True) settings7 = {'index_granularity' : 64, 'index_granularity_bytes' : 10485760} settings8 = {'index_granularity' : 64, 'index_granularity_bytes' : 10485760, 'min_rows_for_wide_part' : 512, 'min_bytes_for_wide_part' : 0} @pytest.fixture(scope="module") def start_cluster_diff_versions(): try: for name in ['polymorphic_table', 'polymorphic_table_2']: cluster.start() node7.query( ''' CREATE TABLE {name}(date Date, id UInt32, s String, arr Array(Int32)) ENGINE = ReplicatedMergeTree('/clickhouse/tables/test/shard5/{name}', '1') PARTITION BY toYYYYMM(date) ORDER BY id SETTINGS index_granularity = {index_granularity}, index_granularity_bytes = {index_granularity_bytes} '''.format(name=name, **settings7) ) node8.query( ''' CREATE TABLE {name}(date Date, id UInt32, s String, arr Array(Int32)) ENGINE = ReplicatedMergeTree('/clickhouse/tables/test/shard5/{name}', '2') PARTITION BY toYYYYMM(date) ORDER BY id SETTINGS index_granularity = {index_granularity}, index_granularity_bytes = {index_granularity_bytes}, min_rows_for_wide_part = {min_rows_for_wide_part}, min_bytes_for_wide_part = {min_bytes_for_wide_part} '''.format(name=name, **settings8) ) yield cluster finally: cluster.shutdown() @pytest.mark.skip(reason="compatability is temporary broken") def test_polymorphic_parts_diff_versions(start_cluster_diff_versions): node_old = node7 node_new = node8 insert_random_data('polymorphic_table', node7, 100) node8.query("SYSTEM SYNC REPLICA polymorphic_table", timeout=20) assert node8.query("SELECT count() FROM polymorphic_table") == "100\n" assert node8.query("SELECT DISTINCT part_type FROM system.parts WHERE table = 'polymorphic_table' and active") == "Wide\n" @pytest.mark.skip(reason="compatability is temporary broken") def test_polymorphic_parts_diff_versions_2(start_cluster_diff_versions): # this version doesn't know anything about it. It's considered to be ok. node_old = node7 node_new = node8 insert_random_data('polymorphic_table_2', node_new, 100) assert node_new.query("SELECT count() FROM polymorphic_table_2") == "100\n" assert node_old.query("SELECT count() FROM polymorphic_table_2") == "0\n" with pytest.raises(Exception): node_old.query("SYSTEM SYNC REPLICA polymorphic_table_2", timeout=3) node_old.restart_with_latest_version() node_old.query("SYSTEM SYNC REPLICA polymorphic_table_2", timeout=20) # Works after update assert node_old.query("SELECT count() FROM polymorphic_table_2") == "100\n" assert node_old.query("SELECT DISTINCT part_type FROM system.parts WHERE table = 'polymorphic_table_2' and active") == "Compact\n" def test_polymorphic_parts_non_adaptive(start_cluster): node1.query("SYSTEM STOP MERGES") node2.query("SYSTEM STOP MERGES") insert_random_data('non_adaptive_table', node1, 100) node2.query("SYSTEM SYNC REPLICA non_adaptive_table", timeout=20) insert_random_data('non_adaptive_table', node2, 100) node1.query("SYSTEM SYNC REPLICA non_adaptive_table", timeout=20) assert TSV(node1.query("SELECT part_type, count() FROM system.parts " \ "WHERE table = 'non_adaptive_table' AND active GROUP BY part_type ORDER BY part_type")) == TSV("Wide\t2\n") assert TSV(node2.query("SELECT part_type, count() FROM system.parts " \ "WHERE table = 'non_adaptive_table' AND active GROUP BY part_type ORDER BY part_type")) == TSV("Wide\t2\n") assert node1.contains_in_log("<Warning> default.non_adaptive_table: Table can't create parts with adaptive granularity")
true
true
f7256dea781fbaf1c92c2fd539b3e3cfbad4cd6e
214
py
Python
Lectures/9 - Matlib/test.py
JensRL/PPaNM
a28d9826d24c821cbc35a2e5fb5c478118f1e693
[ "MIT" ]
null
null
null
Lectures/9 - Matlib/test.py
JensRL/PPaNM
a28d9826d24c821cbc35a2e5fb5c478118f1e693
[ "MIT" ]
null
null
null
Lectures/9 - Matlib/test.py
JensRL/PPaNM
a28d9826d24c821cbc35a2e5fb5c478118f1e693
[ "MIT" ]
null
null
null
import math import scipy.integrate as integrate ncalls = 0 def f(x): global ncalls ncalls +=1 return math.log(x)/math.sqrt(x) result = integrate.quad(f,0,1) print("result=", result, "ncalls =",ncalls)
214
214
0.682243
import math import scipy.integrate as integrate ncalls = 0 def f(x): global ncalls ncalls +=1 return math.log(x)/math.sqrt(x) result = integrate.quad(f,0,1) print("result=", result, "ncalls =",ncalls)
true
true
f7256e40446cfaf2d265b8165ba99a61224d4a30
1,336
py
Python
apache2/htdocs/syntax/string4.py
tigerish009/mampstack-8.0.0-0
d4d0550e0d29d850ebd9a2b70c3f16641de0e1bf
[ "Apache-2.0" ]
null
null
null
apache2/htdocs/syntax/string4.py
tigerish009/mampstack-8.0.0-0
d4d0550e0d29d850ebd9a2b70c3f16641de0e1bf
[ "Apache-2.0" ]
null
null
null
apache2/htdocs/syntax/string4.py
tigerish009/mampstack-8.0.0-0
d4d0550e0d29d850ebd9a2b70c3f16641de0e1bf
[ "Apache-2.0" ]
null
null
null
#positional formatting print('to {}.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry sstandard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. {} It was popularised {} in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of {} Lorem Ipsum.'.format('egoing', 12, 'egoing', 'egoing')) #named placeholder print('to {name}.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry sstandard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. {age:d} It was popularised {name} in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of {name} Lorem Ipsum.'.format(name='apple!!!!!!!', age=11111))
222.666667
653
0.797156
print('to {}.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry sstandard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. {} It was popularised {} in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of {} Lorem Ipsum.'.format('egoing', 12, 'egoing', 'egoing')) print('to {name}.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry sstandard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. {age:d} It was popularised {name} in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of {name} Lorem Ipsum.'.format(name='apple!!!!!!!', age=11111))
true
true
f7256ea03f1ba9c7d22b3e985d8dc7af2edfcdc4
2,525
py
Python
bentoml/adapters/dataframe_output.py
d3m0n-r00t/BentoML
e5c53b821369f5391de9ab3a20ecad5db9e77202
[ "Apache-2.0" ]
null
null
null
bentoml/adapters/dataframe_output.py
d3m0n-r00t/BentoML
e5c53b821369f5391de9ab3a20ecad5db9e77202
[ "Apache-2.0" ]
null
null
null
bentoml/adapters/dataframe_output.py
d3m0n-r00t/BentoML
e5c53b821369f5391de9ab3a20ecad5db9e77202
[ "Apache-2.0" ]
null
null
null
import json from typing import Sequence from bentoml.adapters.json_output import JsonOutput from bentoml.types import InferenceError, InferenceResult, InferenceTask from bentoml.utils.dataframe_util import PANDAS_DATAFRAME_TO_JSON_ORIENT_OPTIONS def df_to_json(result, pandas_dataframe_orient="records"): import pandas as pd assert ( pandas_dataframe_orient in PANDAS_DATAFRAME_TO_JSON_ORIENT_OPTIONS ), f"unknown pandas dataframe orient '{pandas_dataframe_orient}'" if isinstance(result, pd.DataFrame): return result.to_json(orient=pandas_dataframe_orient) if isinstance(result, pd.Series): return pd.DataFrame(result).to_json(orient=pandas_dataframe_orient) return json.dumps(result) class DataframeOutput(JsonOutput): """ Converts result of user defined API function into specific output. Args: cors (str): The value of the Access-Control-Allow-Origin header set in the AWS Lambda response object. Default is "*". If set to None, the header will not be set. """ BATCH_MODE_SUPPORTED = True def __init__(self, output_orient='records', **kwargs): super().__init__(**kwargs) self.output_orient = output_orient assert self.output_orient in PANDAS_DATAFRAME_TO_JSON_ORIENT_OPTIONS, ( f"Invalid 'output_orient'='{self.orient}', valid options are " f"{PANDAS_DATAFRAME_TO_JSON_ORIENT_OPTIONS}" ) @property def config(self): base_config = super(DataframeOutput, self).config return dict(base_config, output_orient=self.output_orient) @property def pip_dependencies(self): """ :return: List of PyPI package names required by this OutputAdapter """ return ['pandas'] def pack_user_func_return_value( self, return_result, tasks: Sequence[InferenceTask] ) -> Sequence[InferenceResult[str]]: rv = [] i = 0 for task in tasks: if task.batch is None: result = return_result[i : i + 1] i += 1 else: result = return_result[i : i + task.batch] i += task.batch try: result = df_to_json(result, self.output_orient) rv.append(InferenceResult(http_status=200, data=result)) except Exception as e: # pylint: disable=broad-except rv.append(InferenceError(err_msg=str(e), http_status=500)) return rv
33.666667
82
0.65901
import json from typing import Sequence from bentoml.adapters.json_output import JsonOutput from bentoml.types import InferenceError, InferenceResult, InferenceTask from bentoml.utils.dataframe_util import PANDAS_DATAFRAME_TO_JSON_ORIENT_OPTIONS def df_to_json(result, pandas_dataframe_orient="records"): import pandas as pd assert ( pandas_dataframe_orient in PANDAS_DATAFRAME_TO_JSON_ORIENT_OPTIONS ), f"unknown pandas dataframe orient '{pandas_dataframe_orient}'" if isinstance(result, pd.DataFrame): return result.to_json(orient=pandas_dataframe_orient) if isinstance(result, pd.Series): return pd.DataFrame(result).to_json(orient=pandas_dataframe_orient) return json.dumps(result) class DataframeOutput(JsonOutput): BATCH_MODE_SUPPORTED = True def __init__(self, output_orient='records', **kwargs): super().__init__(**kwargs) self.output_orient = output_orient assert self.output_orient in PANDAS_DATAFRAME_TO_JSON_ORIENT_OPTIONS, ( f"Invalid 'output_orient'='{self.orient}', valid options are " f"{PANDAS_DATAFRAME_TO_JSON_ORIENT_OPTIONS}" ) @property def config(self): base_config = super(DataframeOutput, self).config return dict(base_config, output_orient=self.output_orient) @property def pip_dependencies(self): return ['pandas'] def pack_user_func_return_value( self, return_result, tasks: Sequence[InferenceTask] ) -> Sequence[InferenceResult[str]]: rv = [] i = 0 for task in tasks: if task.batch is None: result = return_result[i : i + 1] i += 1 else: result = return_result[i : i + task.batch] i += task.batch try: result = df_to_json(result, self.output_orient) rv.append(InferenceResult(http_status=200, data=result)) except Exception as e: rv.append(InferenceError(err_msg=str(e), http_status=500)) return rv
true
true
f7256eb9c87e025bed52453bc1d07f3c08e79dcc
1,581
py
Python
samples/generated_samples/vmmigration_v1_generated_vm_migration_create_source_sync.py
renovate-bot/python-vmmigration
80a2cf46a21f516899da818a7aec0f2a67222047
[ "Apache-2.0" ]
null
null
null
samples/generated_samples/vmmigration_v1_generated_vm_migration_create_source_sync.py
renovate-bot/python-vmmigration
80a2cf46a21f516899da818a7aec0f2a67222047
[ "Apache-2.0" ]
10
2021-11-18T10:47:48.000Z
2022-03-07T15:48:54.000Z
samples/generated_samples/vmmigration_v1_generated_vm_migration_create_source_sync.py
renovate-bot/python-vmmigration
80a2cf46a21f516899da818a7aec0f2a67222047
[ "Apache-2.0" ]
1
2022-01-29T08:15:02.000Z
2022-01-29T08:15:02.000Z
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for CreateSource # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-vm-migration # [START vmmigration_v1_generated_VmMigration_CreateSource_sync] from google.cloud import vmmigration_v1 def sample_create_source(): # Create a client client = vmmigration_v1.VmMigrationClient() # Initialize request argument(s) request = vmmigration_v1.CreateSourceRequest( parent="parent_value", source_id="source_id_value", ) # Make the request operation = client.create_source(request=request) print("Waiting for operation to complete...") response = operation.result() # Handle the response print(response) # [END vmmigration_v1_generated_VmMigration_CreateSource_sync]
31
85
0.752056
from google.cloud import vmmigration_v1 def sample_create_source(): client = vmmigration_v1.VmMigrationClient() request = vmmigration_v1.CreateSourceRequest( parent="parent_value", source_id="source_id_value", ) operation = client.create_source(request=request) print("Waiting for operation to complete...") response = operation.result() print(response)
true
true
f7256ed5b108211f2458fd64f6a79da2e72b170a
62,996
py
Python
site-packages/sklearn/linear_model/_stochastic_gradient.py
linusg/Pyto
eab3c3e093a8cace53d5b9425d1af2f535d456ee
[ "MIT" ]
2
2020-08-25T13:55:00.000Z
2020-08-25T16:36:03.000Z
site-packages/sklearn/linear_model/_stochastic_gradient.py
linusg/Pyto
eab3c3e093a8cace53d5b9425d1af2f535d456ee
[ "MIT" ]
1
2020-04-25T20:36:07.000Z
2020-04-25T20:36:07.000Z
site-packages/sklearn/linear_model/_stochastic_gradient.py
Wristlebane/Pyto
901ac307b68486d8289105c159ca702318bea5b0
[ "MIT" ]
null
null
null
# Authors: Peter Prettenhofer <peter.prettenhofer@gmail.com> (main author) # Mathieu Blondel (partial_fit support) # # License: BSD 3 clause """Classification and regression using Stochastic Gradient Descent (SGD).""" import numpy as np import warnings from abc import ABCMeta, abstractmethod from joblib import Parallel, delayed from ..base import clone, is_classifier from ._base import LinearClassifierMixin, SparseCoefMixin from ._base import make_dataset from ..base import BaseEstimator, RegressorMixin from ..utils import check_array, check_random_state, check_X_y from ..utils.extmath import safe_sparse_dot from ..utils.multiclass import _check_partial_fit_first_call from ..utils.validation import check_is_fitted, _check_sample_weight from ..exceptions import ConvergenceWarning from ..model_selection import StratifiedShuffleSplit, ShuffleSplit from ._sgd_fast import plain_sgd, average_sgd from ..utils import compute_class_weight from ._sgd_fast import Hinge from ._sgd_fast import SquaredHinge from ._sgd_fast import Log from ._sgd_fast import ModifiedHuber from ._sgd_fast import SquaredLoss from ._sgd_fast import Huber from ._sgd_fast import EpsilonInsensitive from ._sgd_fast import SquaredEpsilonInsensitive from ..utils.fixes import _joblib_parallel_args LEARNING_RATE_TYPES = {"constant": 1, "optimal": 2, "invscaling": 3, "adaptive": 4, "pa1": 5, "pa2": 6} PENALTY_TYPES = {"none": 0, "l2": 2, "l1": 1, "elasticnet": 3} DEFAULT_EPSILON = 0.1 # Default value of ``epsilon`` parameter. MAX_INT = np.iinfo(np.int32).max class _ValidationScoreCallback: """Callback for early stopping based on validation score""" def __init__(self, estimator, X_val, y_val, sample_weight_val, classes=None): self.estimator = clone(estimator) self.estimator.t_ = 1 # to pass check_is_fitted if classes is not None: self.estimator.classes_ = classes self.X_val = X_val self.y_val = y_val self.sample_weight_val = sample_weight_val def __call__(self, coef, intercept): est = self.estimator est.coef_ = coef.reshape(1, -1) est.intercept_ = np.atleast_1d(intercept) return est.score(self.X_val, self.y_val, self.sample_weight_val) class BaseSGD(SparseCoefMixin, BaseEstimator, metaclass=ABCMeta): """Base class for SGD classification and regression.""" def __init__(self, loss, penalty='l2', alpha=0.0001, C=1.0, l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=1e-3, shuffle=True, verbose=0, epsilon=0.1, random_state=None, learning_rate="optimal", eta0=0.0, power_t=0.5, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, warm_start=False, average=False): self.loss = loss self.penalty = penalty self.learning_rate = learning_rate self.epsilon = epsilon self.alpha = alpha self.C = C self.l1_ratio = l1_ratio self.fit_intercept = fit_intercept self.shuffle = shuffle self.random_state = random_state self.verbose = verbose self.eta0 = eta0 self.power_t = power_t self.early_stopping = early_stopping self.validation_fraction = validation_fraction self.n_iter_no_change = n_iter_no_change self.warm_start = warm_start self.average = average self.max_iter = max_iter self.tol = tol # current tests expect init to do parameter validation # but we are not allowed to set attributes self._validate_params() def set_params(self, **kwargs): super().set_params(**kwargs) self._validate_params() return self @abstractmethod def fit(self, X, y): """Fit model.""" def _validate_params(self, for_partial_fit=False): """Validate input params. """ if not isinstance(self.shuffle, bool): raise ValueError("shuffle must be either True or False") if not isinstance(self.early_stopping, bool): raise ValueError("early_stopping must be either True or False") if self.early_stopping and for_partial_fit: raise ValueError("early_stopping should be False with partial_fit") if self.max_iter is not None and self.max_iter <= 0: raise ValueError("max_iter must be > zero. Got %f" % self.max_iter) if not (0.0 <= self.l1_ratio <= 1.0): raise ValueError("l1_ratio must be in [0, 1]") if self.alpha < 0.0: raise ValueError("alpha must be >= 0") if self.n_iter_no_change < 1: raise ValueError("n_iter_no_change must be >= 1") if not (0.0 < self.validation_fraction < 1.0): raise ValueError("validation_fraction must be in range (0, 1)") if self.learning_rate in ("constant", "invscaling", "adaptive"): if self.eta0 <= 0.0: raise ValueError("eta0 must be > 0") if self.learning_rate == "optimal" and self.alpha == 0: raise ValueError("alpha must be > 0 since " "learning_rate is 'optimal'. alpha is used " "to compute the optimal learning rate.") # raises ValueError if not registered self._get_penalty_type(self.penalty) self._get_learning_rate_type(self.learning_rate) if self.loss not in self.loss_functions: raise ValueError("The loss %s is not supported. " % self.loss) def _get_loss_function(self, loss): """Get concrete ``LossFunction`` object for str ``loss``. """ try: loss_ = self.loss_functions[loss] loss_class, args = loss_[0], loss_[1:] if loss in ('huber', 'epsilon_insensitive', 'squared_epsilon_insensitive'): args = (self.epsilon, ) return loss_class(*args) except KeyError: raise ValueError("The loss %s is not supported. " % loss) def _get_learning_rate_type(self, learning_rate): try: return LEARNING_RATE_TYPES[learning_rate] except KeyError: raise ValueError("learning rate %s " "is not supported. " % learning_rate) def _get_penalty_type(self, penalty): penalty = str(penalty).lower() try: return PENALTY_TYPES[penalty] except KeyError: raise ValueError("Penalty %s is not supported. " % penalty) def _allocate_parameter_mem(self, n_classes, n_features, coef_init=None, intercept_init=None): """Allocate mem for parameters; initialize if provided.""" if n_classes > 2: # allocate coef_ for multi-class if coef_init is not None: coef_init = np.asarray(coef_init, order="C") if coef_init.shape != (n_classes, n_features): raise ValueError("Provided ``coef_`` does not match " "dataset. ") self.coef_ = coef_init else: self.coef_ = np.zeros((n_classes, n_features), dtype=np.float64, order="C") # allocate intercept_ for multi-class if intercept_init is not None: intercept_init = np.asarray(intercept_init, order="C") if intercept_init.shape != (n_classes, ): raise ValueError("Provided intercept_init " "does not match dataset.") self.intercept_ = intercept_init else: self.intercept_ = np.zeros(n_classes, dtype=np.float64, order="C") else: # allocate coef_ for binary problem if coef_init is not None: coef_init = np.asarray(coef_init, dtype=np.float64, order="C") coef_init = coef_init.ravel() if coef_init.shape != (n_features,): raise ValueError("Provided coef_init does not " "match dataset.") self.coef_ = coef_init else: self.coef_ = np.zeros(n_features, dtype=np.float64, order="C") # allocate intercept_ for binary problem if intercept_init is not None: intercept_init = np.asarray(intercept_init, dtype=np.float64) if intercept_init.shape != (1,) and intercept_init.shape != (): raise ValueError("Provided intercept_init " "does not match dataset.") self.intercept_ = intercept_init.reshape(1,) else: self.intercept_ = np.zeros(1, dtype=np.float64, order="C") # initialize average parameters if self.average > 0: self.standard_coef_ = self.coef_ self.standard_intercept_ = self.intercept_ self.average_coef_ = np.zeros(self.coef_.shape, dtype=np.float64, order="C") self.average_intercept_ = np.zeros(self.standard_intercept_.shape, dtype=np.float64, order="C") def _make_validation_split(self, y): """Split the dataset between training set and validation set. Parameters ---------- y : array, shape (n_samples, ) Target values. Returns ------- validation_mask : array, shape (n_samples, ) Equal to 1 on the validation set, 0 on the training set. """ n_samples = y.shape[0] validation_mask = np.zeros(n_samples, dtype=np.uint8) if not self.early_stopping: # use the full set for training, with an empty validation set return validation_mask if is_classifier(self): splitter_type = StratifiedShuffleSplit else: splitter_type = ShuffleSplit cv = splitter_type(test_size=self.validation_fraction, random_state=self.random_state) idx_train, idx_val = next(cv.split(np.zeros(shape=(y.shape[0], 1)), y)) if idx_train.shape[0] == 0 or idx_val.shape[0] == 0: raise ValueError( "Splitting %d samples into a train set and a validation set " "with validation_fraction=%r led to an empty set (%d and %d " "samples). Please either change validation_fraction, increase " "number of samples, or disable early_stopping." % (n_samples, self.validation_fraction, idx_train.shape[0], idx_val.shape[0])) validation_mask[idx_val] = 1 return validation_mask def _make_validation_score_cb(self, validation_mask, X, y, sample_weight, classes=None): if not self.early_stopping: return None return _ValidationScoreCallback( self, X[validation_mask], y[validation_mask], sample_weight[validation_mask], classes=classes) def _prepare_fit_binary(est, y, i): """Initialization for fit_binary. Returns y, coef, intercept, average_coef, average_intercept. """ y_i = np.ones(y.shape, dtype=np.float64, order="C") y_i[y != est.classes_[i]] = -1.0 average_intercept = 0 average_coef = None if len(est.classes_) == 2: if not est.average: coef = est.coef_.ravel() intercept = est.intercept_[0] else: coef = est.standard_coef_.ravel() intercept = est.standard_intercept_[0] average_coef = est.average_coef_.ravel() average_intercept = est.average_intercept_[0] else: if not est.average: coef = est.coef_[i] intercept = est.intercept_[i] else: coef = est.standard_coef_[i] intercept = est.standard_intercept_[i] average_coef = est.average_coef_[i] average_intercept = est.average_intercept_[i] return y_i, coef, intercept, average_coef, average_intercept def fit_binary(est, i, X, y, alpha, C, learning_rate, max_iter, pos_weight, neg_weight, sample_weight, validation_mask=None, random_state=None): """Fit a single binary classifier. The i'th class is considered the "positive" class. Parameters ---------- est : Estimator object The estimator to fit i : int Index of the positive class X : numpy array or sparse matrix of shape [n_samples,n_features] Training data y : numpy array of shape [n_samples, ] Target values alpha : float The regularization parameter C : float Maximum step size for passive aggressive learning_rate : string The learning rate. Accepted values are 'constant', 'optimal', 'invscaling', 'pa1' and 'pa2'. max_iter : int The maximum number of iterations (epochs) pos_weight : float The weight of the positive class neg_weight : float The weight of the negative class sample_weight : numpy array of shape [n_samples, ] The weight of each sample validation_mask : numpy array of shape [n_samples, ] or None Precomputed validation mask in case _fit_binary is called in the context of a one-vs-rest reduction. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. """ # if average is not true, average_coef, and average_intercept will be # unused y_i, coef, intercept, average_coef, average_intercept = \ _prepare_fit_binary(est, y, i) assert y_i.shape[0] == y.shape[0] == sample_weight.shape[0] random_state = check_random_state(random_state) dataset, intercept_decay = make_dataset( X, y_i, sample_weight, random_state=random_state) penalty_type = est._get_penalty_type(est.penalty) learning_rate_type = est._get_learning_rate_type(learning_rate) if validation_mask is None: validation_mask = est._make_validation_split(y_i) classes = np.array([-1, 1], dtype=y_i.dtype) validation_score_cb = est._make_validation_score_cb( validation_mask, X, y_i, sample_weight, classes=classes) # numpy mtrand expects a C long which is a signed 32 bit integer under # Windows seed = random_state.randint(MAX_INT) tol = est.tol if est.tol is not None else -np.inf if not est.average: result = plain_sgd(coef, intercept, est.loss_function_, penalty_type, alpha, C, est.l1_ratio, dataset, validation_mask, est.early_stopping, validation_score_cb, int(est.n_iter_no_change), max_iter, tol, int(est.fit_intercept), int(est.verbose), int(est.shuffle), seed, pos_weight, neg_weight, learning_rate_type, est.eta0, est.power_t, est.t_, intercept_decay) else: standard_coef, standard_intercept, average_coef, average_intercept, \ n_iter_ = average_sgd(coef, intercept, average_coef, average_intercept, est.loss_function_, penalty_type, alpha, C, est.l1_ratio, dataset, validation_mask, est.early_stopping, validation_score_cb, int(est.n_iter_no_change), max_iter, tol, int(est.fit_intercept), int(est.verbose), int(est.shuffle), seed, pos_weight, neg_weight, learning_rate_type, est.eta0, est.power_t, est.t_, intercept_decay, est.average) if len(est.classes_) == 2: est.average_intercept_[0] = average_intercept else: est.average_intercept_[i] = average_intercept result = standard_coef, standard_intercept, n_iter_ return result class BaseSGDClassifier(LinearClassifierMixin, BaseSGD, metaclass=ABCMeta): loss_functions = { "hinge": (Hinge, 1.0), "squared_hinge": (SquaredHinge, 1.0), "perceptron": (Hinge, 0.0), "log": (Log, ), "modified_huber": (ModifiedHuber, ), "squared_loss": (SquaredLoss, ), "huber": (Huber, DEFAULT_EPSILON), "epsilon_insensitive": (EpsilonInsensitive, DEFAULT_EPSILON), "squared_epsilon_insensitive": (SquaredEpsilonInsensitive, DEFAULT_EPSILON), } @abstractmethod def __init__(self, loss="hinge", penalty='l2', alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=1e-3, shuffle=True, verbose=0, epsilon=DEFAULT_EPSILON, n_jobs=None, random_state=None, learning_rate="optimal", eta0=0.0, power_t=0.5, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, class_weight=None, warm_start=False, average=False): super().__init__( loss=loss, penalty=penalty, alpha=alpha, l1_ratio=l1_ratio, fit_intercept=fit_intercept, max_iter=max_iter, tol=tol, shuffle=shuffle, verbose=verbose, epsilon=epsilon, random_state=random_state, learning_rate=learning_rate, eta0=eta0, power_t=power_t, early_stopping=early_stopping, validation_fraction=validation_fraction, n_iter_no_change=n_iter_no_change, warm_start=warm_start, average=average) self.class_weight = class_weight self.n_jobs = n_jobs def _partial_fit(self, X, y, alpha, C, loss, learning_rate, max_iter, classes, sample_weight, coef_init, intercept_init): X, y = check_X_y(X, y, 'csr', dtype=np.float64, order="C", accept_large_sparse=False) n_samples, n_features = X.shape _check_partial_fit_first_call(self, classes) n_classes = self.classes_.shape[0] # Allocate datastructures from input arguments self._expanded_class_weight = compute_class_weight(self.class_weight, self.classes_, y) sample_weight = _check_sample_weight(sample_weight, X) if getattr(self, "coef_", None) is None or coef_init is not None: self._allocate_parameter_mem(n_classes, n_features, coef_init, intercept_init) elif n_features != self.coef_.shape[-1]: raise ValueError("Number of features %d does not match previous " "data %d." % (n_features, self.coef_.shape[-1])) self.loss_function_ = self._get_loss_function(loss) if not hasattr(self, "t_"): self.t_ = 1.0 # delegate to concrete training procedure if n_classes > 2: self._fit_multiclass(X, y, alpha=alpha, C=C, learning_rate=learning_rate, sample_weight=sample_weight, max_iter=max_iter) elif n_classes == 2: self._fit_binary(X, y, alpha=alpha, C=C, learning_rate=learning_rate, sample_weight=sample_weight, max_iter=max_iter) else: raise ValueError( "The number of classes has to be greater than one;" " got %d class" % n_classes) return self def _fit(self, X, y, alpha, C, loss, learning_rate, coef_init=None, intercept_init=None, sample_weight=None): self._validate_params() if hasattr(self, "classes_"): self.classes_ = None X, y = check_X_y(X, y, 'csr', dtype=np.float64, order="C", accept_large_sparse=False) # labels can be encoded as float, int, or string literals # np.unique sorts in asc order; largest class id is positive class classes = np.unique(y) if self.warm_start and hasattr(self, "coef_"): if coef_init is None: coef_init = self.coef_ if intercept_init is None: intercept_init = self.intercept_ else: self.coef_ = None self.intercept_ = None if self.average > 0: self.standard_coef_ = self.coef_ self.standard_intercept_ = self.intercept_ self.average_coef_ = None self.average_intercept_ = None # Clear iteration count for multiple call to fit. self.t_ = 1.0 self._partial_fit(X, y, alpha, C, loss, learning_rate, self.max_iter, classes, sample_weight, coef_init, intercept_init) if (self.tol is not None and self.tol > -np.inf and self.n_iter_ == self.max_iter): warnings.warn("Maximum number of iteration reached before " "convergence. Consider increasing max_iter to " "improve the fit.", ConvergenceWarning) return self def _fit_binary(self, X, y, alpha, C, sample_weight, learning_rate, max_iter): """Fit a binary classifier on X and y. """ coef, intercept, n_iter_ = fit_binary(self, 1, X, y, alpha, C, learning_rate, max_iter, self._expanded_class_weight[1], self._expanded_class_weight[0], sample_weight, random_state=self.random_state) self.t_ += n_iter_ * X.shape[0] self.n_iter_ = n_iter_ # need to be 2d if self.average > 0: if self.average <= self.t_ - 1: self.coef_ = self.average_coef_.reshape(1, -1) self.intercept_ = self.average_intercept_ else: self.coef_ = self.standard_coef_.reshape(1, -1) self.standard_intercept_ = np.atleast_1d(intercept) self.intercept_ = self.standard_intercept_ else: self.coef_ = coef.reshape(1, -1) # intercept is a float, need to convert it to an array of length 1 self.intercept_ = np.atleast_1d(intercept) def _fit_multiclass(self, X, y, alpha, C, learning_rate, sample_weight, max_iter): """Fit a multi-class classifier by combining binary classifiers Each binary classifier predicts one class versus all others. This strategy is called OvA (One versus All) or OvR (One versus Rest). """ # Precompute the validation split using the multiclass labels # to ensure proper balancing of the classes. validation_mask = self._make_validation_split(y) # Use joblib to fit OvA in parallel. # Pick the random seed for each job outside of fit_binary to avoid # sharing the estimator random state between threads which could lead # to non-deterministic behavior random_state = check_random_state(self.random_state) seeds = random_state.randint(MAX_INT, size=len(self.classes_)) result = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, **_joblib_parallel_args(require="sharedmem"))( delayed(fit_binary)(self, i, X, y, alpha, C, learning_rate, max_iter, self._expanded_class_weight[i], 1., sample_weight, validation_mask=validation_mask, random_state=seed) for i, seed in enumerate(seeds)) # take the maximum of n_iter_ over every binary fit n_iter_ = 0. for i, (_, intercept, n_iter_i) in enumerate(result): self.intercept_[i] = intercept n_iter_ = max(n_iter_, n_iter_i) self.t_ += n_iter_ * X.shape[0] self.n_iter_ = n_iter_ if self.average > 0: if self.average <= self.t_ - 1.0: self.coef_ = self.average_coef_ self.intercept_ = self.average_intercept_ else: self.coef_ = self.standard_coef_ self.standard_intercept_ = np.atleast_1d(self.intercept_) self.intercept_ = self.standard_intercept_ def partial_fit(self, X, y, classes=None, sample_weight=None): """Perform one epoch of stochastic gradient descent on given samples. Internally, this method uses ``max_iter = 1``. Therefore, it is not guaranteed that a minimum of the cost function is reached after calling it once. Matters such as objective convergence and early stopping should be handled by the user. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Subset of the training data y : numpy array, shape (n_samples,) Subset of the target values classes : array, shape (n_classes,) Classes across all calls to partial_fit. Can be obtained by via `np.unique(y_all)`, where y_all is the target vector of the entire dataset. This argument is required for the first call to partial_fit and can be omitted in the subsequent calls. Note that y doesn't need to contain all labels in `classes`. sample_weight : array-like, shape (n_samples,), optional Weights applied to individual samples. If not provided, uniform weights are assumed. Returns ------- self : returns an instance of self. """ self._validate_params(for_partial_fit=True) if self.class_weight in ['balanced']: raise ValueError("class_weight '{0}' is not supported for " "partial_fit. In order to use 'balanced' weights," " use compute_class_weight('{0}', classes, y). " "In place of y you can us a large enough sample " "of the full training set target to properly " "estimate the class frequency distributions. " "Pass the resulting weights as the class_weight " "parameter.".format(self.class_weight)) return self._partial_fit(X, y, alpha=self.alpha, C=1.0, loss=self.loss, learning_rate=self.learning_rate, max_iter=1, classes=classes, sample_weight=sample_weight, coef_init=None, intercept_init=None) def fit(self, X, y, coef_init=None, intercept_init=None, sample_weight=None): """Fit linear model with Stochastic Gradient Descent. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data y : numpy array, shape (n_samples,) Target values coef_init : array, shape (n_classes, n_features) The initial coefficients to warm-start the optimization. intercept_init : array, shape (n_classes,) The initial intercept to warm-start the optimization. sample_weight : array-like, shape (n_samples,), optional Weights applied to individual samples. If not provided, uniform weights are assumed. These weights will be multiplied with class_weight (passed through the constructor) if class_weight is specified Returns ------- self : returns an instance of self. """ return self._fit(X, y, alpha=self.alpha, C=1.0, loss=self.loss, learning_rate=self.learning_rate, coef_init=coef_init, intercept_init=intercept_init, sample_weight=sample_weight) class SGDClassifier(BaseSGDClassifier): """Linear classifiers (SVM, logistic regression, a.o.) with SGD training. This estimator implements regularized linear models with stochastic gradient descent (SGD) learning: the gradient of the loss is estimated each sample at a time and the model is updated along the way with a decreasing strength schedule (aka learning rate). SGD allows minibatch (online/out-of-core) learning, see the partial_fit method. For best results using the default learning rate schedule, the data should have zero mean and unit variance. This implementation works with data represented as dense or sparse arrays of floating point values for the features. The model it fits can be controlled with the loss parameter; by default, it fits a linear support vector machine (SVM). The regularizer is a penalty added to the loss function that shrinks model parameters towards the zero vector using either the squared euclidean norm L2 or the absolute norm L1 or a combination of both (Elastic Net). If the parameter update crosses the 0.0 value because of the regularizer, the update is truncated to 0.0 to allow for learning sparse models and achieve online feature selection. Read more in the :ref:`User Guide <sgd>`. Parameters ---------- loss : str, default: 'hinge' The loss function to be used. Defaults to 'hinge', which gives a linear SVM. The possible options are 'hinge', 'log', 'modified_huber', 'squared_hinge', 'perceptron', or a regression loss: 'squared_loss', 'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'. The 'log' loss gives logistic regression, a probabilistic classifier. 'modified_huber' is another smooth loss that brings tolerance to outliers as well as probability estimates. 'squared_hinge' is like hinge but is quadratically penalized. 'perceptron' is the linear loss used by the perceptron algorithm. The other losses are designed for regression but can be useful in classification as well; see SGDRegressor for a description. penalty : str, 'none', 'l2', 'l1', or 'elasticnet' The penalty (aka regularization term) to be used. Defaults to 'l2' which is the standard regularizer for linear SVM models. 'l1' and 'elasticnet' might bring sparsity to the model (feature selection) not achievable with 'l2'. alpha : float Constant that multiplies the regularization term. Defaults to 0.0001. Also used to compute learning_rate when set to 'optimal'. l1_ratio : float The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1. l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1. Defaults to 0.15. fit_intercept : bool Whether the intercept should be estimated or not. If False, the data is assumed to be already centered. Defaults to True. max_iter : int, optional (default=1000) The maximum number of passes over the training data (aka epochs). It only impacts the behavior in the ``fit`` method, and not the :meth:`partial_fit` method. .. versionadded:: 0.19 tol : float or None, optional (default=1e-3) The stopping criterion. If it is not None, the iterations will stop when (loss > best_loss - tol) for ``n_iter_no_change`` consecutive epochs. .. versionadded:: 0.19 shuffle : bool, optional Whether or not the training data should be shuffled after each epoch. Defaults to True. verbose : integer, default=0 The verbosity level epsilon : float, default=0.1 Epsilon in the epsilon-insensitive loss functions; only if `loss` is 'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'. For 'huber', determines the threshold at which it becomes less important to get the prediction exactly right. For epsilon-insensitive, any differences between the current prediction and the correct label are ignored if they are less than this threshold. n_jobs : int or None, optional (default=None) The number of CPUs to use to do the OVA (One Versus All, for multi-class problems) computation. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. random_state : int, RandomState instance or None, optional (default=None) The seed of the pseudo random number generator to use when shuffling the data. If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. learning_rate : string, optional The learning rate schedule: 'constant': eta = eta0 'optimal': [default] eta = 1.0 / (alpha * (t + t0)) where t0 is chosen by a heuristic proposed by Leon Bottou. 'invscaling': eta = eta0 / pow(t, power_t) 'adaptive': eta = eta0, as long as the training keeps decreasing. Each time n_iter_no_change consecutive epochs fail to decrease the training loss by tol or fail to increase validation score by tol if early_stopping is True, the current learning rate is divided by 5. eta0 : double The initial learning rate for the 'constant', 'invscaling' or 'adaptive' schedules. The default value is 0.0 as eta0 is not used by the default schedule 'optimal'. power_t : double The exponent for inverse scaling learning rate [default 0.5]. early_stopping : bool, default=False Whether to use early stopping to terminate training when validation score is not improving. If set to True, it will automatically set aside a stratified fraction of training data as validation and terminate training when validation score is not improving by at least tol for n_iter_no_change consecutive epochs. .. versionadded:: 0.20 validation_fraction : float, default=0.1 The proportion of training data to set aside as validation set for early stopping. Must be between 0 and 1. Only used if early_stopping is True. .. versionadded:: 0.20 n_iter_no_change : int, default=5 Number of iterations with no improvement to wait before early stopping. .. versionadded:: 0.20 class_weight : dict, {class_label: weight} or "balanced" or None, optional Preset for the class_weight fit parameter. Weights associated with classes. If not given, all classes are supposed to have weight one. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))`` warm_start : bool, default=False When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. See :term:`the Glossary <warm_start>`. Repeatedly calling fit or partial_fit when warm_start is True can result in a different solution than when calling fit a single time because of the way the data is shuffled. If a dynamic learning rate is used, the learning rate is adapted depending on the number of samples already seen. Calling ``fit`` resets this counter, while ``partial_fit`` will result in increasing the existing counter. average : bool or int, default=False When set to True, computes the averaged SGD weights and stores the result in the ``coef_`` attribute. If set to an int greater than 1, averaging will begin once the total number of samples seen reaches average. So ``average=10`` will begin averaging after seeing 10 samples. Attributes ---------- coef_ : array, shape (1, n_features) if n_classes == 2 else (n_classes,\ n_features) Weights assigned to the features. intercept_ : array, shape (1,) if n_classes == 2 else (n_classes,) Constants in decision function. n_iter_ : int The actual number of iterations to reach the stopping criterion. For multiclass fits, it is the maximum over every binary fit. loss_function_ : concrete ``LossFunction`` classes_ : array of shape (n_classes,) t_ : int Number of weight updates performed during training. Same as ``(n_iter_ * n_samples)``. Examples -------- >>> import numpy as np >>> from sklearn import linear_model >>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) >>> Y = np.array([1, 1, 2, 2]) >>> clf = linear_model.SGDClassifier(max_iter=1000, tol=1e-3) >>> clf.fit(X, Y) SGDClassifier() >>> print(clf.predict([[-0.8, -1]])) [1] See also -------- sklearn.svm.LinearSVC, LogisticRegression, Perceptron """ def __init__(self, loss="hinge", penalty='l2', alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=1e-3, shuffle=True, verbose=0, epsilon=DEFAULT_EPSILON, n_jobs=None, random_state=None, learning_rate="optimal", eta0=0.0, power_t=0.5, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, class_weight=None, warm_start=False, average=False): super().__init__( loss=loss, penalty=penalty, alpha=alpha, l1_ratio=l1_ratio, fit_intercept=fit_intercept, max_iter=max_iter, tol=tol, shuffle=shuffle, verbose=verbose, epsilon=epsilon, n_jobs=n_jobs, random_state=random_state, learning_rate=learning_rate, eta0=eta0, power_t=power_t, early_stopping=early_stopping, validation_fraction=validation_fraction, n_iter_no_change=n_iter_no_change, class_weight=class_weight, warm_start=warm_start, average=average) def _check_proba(self): if self.loss not in ("log", "modified_huber"): raise AttributeError("probability estimates are not available for" " loss=%r" % self.loss) @property def predict_proba(self): """Probability estimates. This method is only available for log loss and modified Huber loss. Multiclass probability estimates are derived from binary (one-vs.-rest) estimates by simple normalization, as recommended by Zadrozny and Elkan. Binary probability estimates for loss="modified_huber" are given by (clip(decision_function(X), -1, 1) + 1) / 2. For other loss functions it is necessary to perform proper probability calibration by wrapping the classifier with :class:`sklearn.calibration.CalibratedClassifierCV` instead. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Returns ------- array, shape (n_samples, n_classes) Returns the probability of the sample for each class in the model, where classes are ordered as they are in `self.classes_`. References ---------- Zadrozny and Elkan, "Transforming classifier scores into multiclass probability estimates", SIGKDD'02, http://www.research.ibm.com/people/z/zadrozny/kdd2002-Transf.pdf The justification for the formula in the loss="modified_huber" case is in the appendix B in: http://jmlr.csail.mit.edu/papers/volume2/zhang02c/zhang02c.pdf """ self._check_proba() return self._predict_proba def _predict_proba(self, X): check_is_fitted(self) if self.loss == "log": return self._predict_proba_lr(X) elif self.loss == "modified_huber": binary = (len(self.classes_) == 2) scores = self.decision_function(X) if binary: prob2 = np.ones((scores.shape[0], 2)) prob = prob2[:, 1] else: prob = scores np.clip(scores, -1, 1, prob) prob += 1. prob /= 2. if binary: prob2[:, 0] -= prob prob = prob2 else: # the above might assign zero to all classes, which doesn't # normalize neatly; work around this to produce uniform # probabilities prob_sum = prob.sum(axis=1) all_zero = (prob_sum == 0) if np.any(all_zero): prob[all_zero, :] = 1 prob_sum[all_zero] = len(self.classes_) # normalize prob /= prob_sum.reshape((prob.shape[0], -1)) return prob else: raise NotImplementedError("predict_(log_)proba only supported when" " loss='log' or loss='modified_huber' " "(%r given)" % self.loss) @property def predict_log_proba(self): """Log of probability estimates. This method is only available for log loss and modified Huber loss. When loss="modified_huber", probability estimates may be hard zeros and ones, so taking the logarithm is not possible. See ``predict_proba`` for details. Parameters ---------- X : array-like, shape (n_samples, n_features) Returns ------- T : array-like, shape (n_samples, n_classes) Returns the log-probability of the sample for each class in the model, where classes are ordered as they are in `self.classes_`. """ self._check_proba() return self._predict_log_proba def _predict_log_proba(self, X): return np.log(self.predict_proba(X)) class BaseSGDRegressor(RegressorMixin, BaseSGD): loss_functions = { "squared_loss": (SquaredLoss, ), "huber": (Huber, DEFAULT_EPSILON), "epsilon_insensitive": (EpsilonInsensitive, DEFAULT_EPSILON), "squared_epsilon_insensitive": (SquaredEpsilonInsensitive, DEFAULT_EPSILON), } @abstractmethod def __init__(self, loss="squared_loss", penalty="l2", alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=1e-3, shuffle=True, verbose=0, epsilon=DEFAULT_EPSILON, random_state=None, learning_rate="invscaling", eta0=0.01, power_t=0.25, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, warm_start=False, average=False): super().__init__( loss=loss, penalty=penalty, alpha=alpha, l1_ratio=l1_ratio, fit_intercept=fit_intercept, max_iter=max_iter, tol=tol, shuffle=shuffle, verbose=verbose, epsilon=epsilon, random_state=random_state, learning_rate=learning_rate, eta0=eta0, power_t=power_t, early_stopping=early_stopping, validation_fraction=validation_fraction, n_iter_no_change=n_iter_no_change, warm_start=warm_start, average=average) def _partial_fit(self, X, y, alpha, C, loss, learning_rate, max_iter, sample_weight, coef_init, intercept_init): X, y = check_X_y(X, y, "csr", copy=False, order='C', dtype=np.float64, accept_large_sparse=False) y = y.astype(np.float64, copy=False) n_samples, n_features = X.shape sample_weight = _check_sample_weight(sample_weight, X) # Allocate datastructures from input arguments if getattr(self, "coef_", None) is None: self._allocate_parameter_mem(1, n_features, coef_init, intercept_init) elif n_features != self.coef_.shape[-1]: raise ValueError("Number of features %d does not match previous " "data %d." % (n_features, self.coef_.shape[-1])) if self.average > 0 and getattr(self, "average_coef_", None) is None: self.average_coef_ = np.zeros(n_features, dtype=np.float64, order="C") self.average_intercept_ = np.zeros(1, dtype=np.float64, order="C") self._fit_regressor(X, y, alpha, C, loss, learning_rate, sample_weight, max_iter) return self def partial_fit(self, X, y, sample_weight=None): """Perform one epoch of stochastic gradient descent on given samples. Internally, this method uses ``max_iter = 1``. Therefore, it is not guaranteed that a minimum of the cost function is reached after calling it once. Matters such as objective convergence and early stopping should be handled by the user. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Subset of training data y : numpy array of shape (n_samples,) Subset of target values sample_weight : array-like, shape (n_samples,), optional Weights applied to individual samples. If not provided, uniform weights are assumed. Returns ------- self : returns an instance of self. """ self._validate_params(for_partial_fit=True) return self._partial_fit(X, y, self.alpha, C=1.0, loss=self.loss, learning_rate=self.learning_rate, max_iter=1, sample_weight=sample_weight, coef_init=None, intercept_init=None) def _fit(self, X, y, alpha, C, loss, learning_rate, coef_init=None, intercept_init=None, sample_weight=None): self._validate_params() if self.warm_start and getattr(self, "coef_", None) is not None: if coef_init is None: coef_init = self.coef_ if intercept_init is None: intercept_init = self.intercept_ else: self.coef_ = None self.intercept_ = None if self.average > 0: self.standard_intercept_ = self.intercept_ self.standard_coef_ = self.coef_ self.average_coef_ = None self.average_intercept_ = None # Clear iteration count for multiple call to fit. self.t_ = 1.0 self._partial_fit(X, y, alpha, C, loss, learning_rate, self.max_iter, sample_weight, coef_init, intercept_init) if (self.tol is not None and self.tol > -np.inf and self.n_iter_ == self.max_iter): warnings.warn("Maximum number of iteration reached before " "convergence. Consider increasing max_iter to " "improve the fit.", ConvergenceWarning) return self def fit(self, X, y, coef_init=None, intercept_init=None, sample_weight=None): """Fit linear model with Stochastic Gradient Descent. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data y : numpy array, shape (n_samples,) Target values coef_init : array, shape (n_features,) The initial coefficients to warm-start the optimization. intercept_init : array, shape (1,) The initial intercept to warm-start the optimization. sample_weight : array-like, shape (n_samples,), optional Weights applied to individual samples (1. for unweighted). Returns ------- self : returns an instance of self. """ return self._fit(X, y, alpha=self.alpha, C=1.0, loss=self.loss, learning_rate=self.learning_rate, coef_init=coef_init, intercept_init=intercept_init, sample_weight=sample_weight) def _decision_function(self, X): """Predict using the linear model Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Returns ------- array, shape (n_samples,) Predicted target values per element in X. """ check_is_fitted(self) X = check_array(X, accept_sparse='csr') scores = safe_sparse_dot(X, self.coef_.T, dense_output=True) + self.intercept_ return scores.ravel() def predict(self, X): """Predict using the linear model Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Returns ------- array, shape (n_samples,) Predicted target values per element in X. """ return self._decision_function(X) def _fit_regressor(self, X, y, alpha, C, loss, learning_rate, sample_weight, max_iter): dataset, intercept_decay = make_dataset(X, y, sample_weight) loss_function = self._get_loss_function(loss) penalty_type = self._get_penalty_type(self.penalty) learning_rate_type = self._get_learning_rate_type(learning_rate) if not hasattr(self, "t_"): self.t_ = 1.0 validation_mask = self._make_validation_split(y) validation_score_cb = self._make_validation_score_cb( validation_mask, X, y, sample_weight) random_state = check_random_state(self.random_state) # numpy mtrand expects a C long which is a signed 32 bit integer under # Windows seed = random_state.randint(0, np.iinfo(np.int32).max) tol = self.tol if self.tol is not None else -np.inf if self.average > 0: self.standard_coef_, self.standard_intercept_, \ self.average_coef_, self.average_intercept_, self.n_iter_ =\ average_sgd(self.standard_coef_, self.standard_intercept_[0], self.average_coef_, self.average_intercept_[0], loss_function, penalty_type, alpha, C, self.l1_ratio, dataset, validation_mask, self.early_stopping, validation_score_cb, int(self.n_iter_no_change), max_iter, tol, int(self.fit_intercept), int(self.verbose), int(self.shuffle), seed, 1.0, 1.0, learning_rate_type, self.eta0, self.power_t, self.t_, intercept_decay, self.average) self.average_intercept_ = np.atleast_1d(self.average_intercept_) self.standard_intercept_ = np.atleast_1d(self.standard_intercept_) self.t_ += self.n_iter_ * X.shape[0] if self.average <= self.t_ - 1.0: self.coef_ = self.average_coef_ self.intercept_ = self.average_intercept_ else: self.coef_ = self.standard_coef_ self.intercept_ = self.standard_intercept_ else: self.coef_, self.intercept_, self.n_iter_ = \ plain_sgd(self.coef_, self.intercept_[0], loss_function, penalty_type, alpha, C, self.l1_ratio, dataset, validation_mask, self.early_stopping, validation_score_cb, int(self.n_iter_no_change), max_iter, tol, int(self.fit_intercept), int(self.verbose), int(self.shuffle), seed, 1.0, 1.0, learning_rate_type, self.eta0, self.power_t, self.t_, intercept_decay) self.t_ += self.n_iter_ * X.shape[0] self.intercept_ = np.atleast_1d(self.intercept_) class SGDRegressor(BaseSGDRegressor): """Linear model fitted by minimizing a regularized empirical loss with SGD SGD stands for Stochastic Gradient Descent: the gradient of the loss is estimated each sample at a time and the model is updated along the way with a decreasing strength schedule (aka learning rate). The regularizer is a penalty added to the loss function that shrinks model parameters towards the zero vector using either the squared euclidean norm L2 or the absolute norm L1 or a combination of both (Elastic Net). If the parameter update crosses the 0.0 value because of the regularizer, the update is truncated to 0.0 to allow for learning sparse models and achieve online feature selection. This implementation works with data represented as dense numpy arrays of floating point values for the features. Read more in the :ref:`User Guide <sgd>`. Parameters ---------- loss : str, default: 'squared_loss' The loss function to be used. The possible values are 'squared_loss', 'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive' The 'squared_loss' refers to the ordinary least squares fit. 'huber' modifies 'squared_loss' to focus less on getting outliers correct by switching from squared to linear loss past a distance of epsilon. 'epsilon_insensitive' ignores errors less than epsilon and is linear past that; this is the loss function used in SVR. 'squared_epsilon_insensitive' is the same but becomes squared loss past a tolerance of epsilon. penalty : str, 'none', 'l2', 'l1', or 'elasticnet' The penalty (aka regularization term) to be used. Defaults to 'l2' which is the standard regularizer for linear SVM models. 'l1' and 'elasticnet' might bring sparsity to the model (feature selection) not achievable with 'l2'. alpha : float Constant that multiplies the regularization term. Defaults to 0.0001 Also used to compute learning_rate when set to 'optimal'. l1_ratio : float The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1. l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1. Defaults to 0.15. fit_intercept : bool Whether the intercept should be estimated or not. If False, the data is assumed to be already centered. Defaults to True. max_iter : int, optional (default=1000) The maximum number of passes over the training data (aka epochs). It only impacts the behavior in the ``fit`` method, and not the :meth:`partial_fit` method. .. versionadded:: 0.19 tol : float or None, optional (default=1e-3) The stopping criterion. If it is not None, the iterations will stop when (loss > best_loss - tol) for ``n_iter_no_change`` consecutive epochs. .. versionadded:: 0.19 shuffle : bool, optional Whether or not the training data should be shuffled after each epoch. Defaults to True. verbose : integer, default=0 The verbosity level. epsilon : float, default=0.1 Epsilon in the epsilon-insensitive loss functions; only if `loss` is 'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'. For 'huber', determines the threshold at which it becomes less important to get the prediction exactly right. For epsilon-insensitive, any differences between the current prediction and the correct label are ignored if they are less than this threshold. random_state : int, RandomState instance or None, optional (default=None) The seed of the pseudo random number generator to use when shuffling the data. If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. learning_rate : string, optional The learning rate schedule: 'constant': eta = eta0 'optimal': eta = 1.0 / (alpha * (t + t0)) where t0 is chosen by a heuristic proposed by Leon Bottou. 'invscaling': [default] eta = eta0 / pow(t, power_t) 'adaptive': eta = eta0, as long as the training keeps decreasing. Each time n_iter_no_change consecutive epochs fail to decrease the training loss by tol or fail to increase validation score by tol if early_stopping is True, the current learning rate is divided by 5. eta0 : double The initial learning rate for the 'constant', 'invscaling' or 'adaptive' schedules. The default value is 0.01. power_t : double The exponent for inverse scaling learning rate [default 0.25]. early_stopping : bool, default=False Whether to use early stopping to terminate training when validation score is not improving. If set to True, it will automatically set aside a fraction of training data as validation and terminate training when validation score is not improving by at least tol for n_iter_no_change consecutive epochs. .. versionadded:: 0.20 validation_fraction : float, default=0.1 The proportion of training data to set aside as validation set for early stopping. Must be between 0 and 1. Only used if early_stopping is True. .. versionadded:: 0.20 n_iter_no_change : int, default=5 Number of iterations with no improvement to wait before early stopping. .. versionadded:: 0.20 warm_start : bool, default=False When set to True, reuse the solution of the previous call to fit as initialization, otherwise, just erase the previous solution. See :term:`the Glossary <warm_start>`. Repeatedly calling fit or partial_fit when warm_start is True can result in a different solution than when calling fit a single time because of the way the data is shuffled. If a dynamic learning rate is used, the learning rate is adapted depending on the number of samples already seen. Calling ``fit`` resets this counter, while ``partial_fit`` will result in increasing the existing counter. average : bool or int, default=False When set to True, computes the averaged SGD weights and stores the result in the ``coef_`` attribute. If set to an int greater than 1, averaging will begin once the total number of samples seen reaches average. So ``average=10`` will begin averaging after seeing 10 samples. Attributes ---------- coef_ : array, shape (n_features,) Weights assigned to the features. intercept_ : array, shape (1,) The intercept term. average_coef_ : array, shape (n_features,) Averaged weights assigned to the features. average_intercept_ : array, shape (1,) The averaged intercept term. n_iter_ : int The actual number of iterations to reach the stopping criterion. t_ : int Number of weight updates performed during training. Same as ``(n_iter_ * n_samples)``. Examples -------- >>> import numpy as np >>> from sklearn import linear_model >>> n_samples, n_features = 10, 5 >>> rng = np.random.RandomState(0) >>> y = rng.randn(n_samples) >>> X = rng.randn(n_samples, n_features) >>> clf = linear_model.SGDRegressor(max_iter=1000, tol=1e-3) >>> clf.fit(X, y) SGDRegressor() See also -------- Ridge, ElasticNet, Lasso, sklearn.svm.SVR """ def __init__(self, loss="squared_loss", penalty="l2", alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=1e-3, shuffle=True, verbose=0, epsilon=DEFAULT_EPSILON, random_state=None, learning_rate="invscaling", eta0=0.01, power_t=0.25, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, warm_start=False, average=False): super().__init__( loss=loss, penalty=penalty, alpha=alpha, l1_ratio=l1_ratio, fit_intercept=fit_intercept, max_iter=max_iter, tol=tol, shuffle=shuffle, verbose=verbose, epsilon=epsilon, random_state=random_state, learning_rate=learning_rate, eta0=eta0, power_t=power_t, early_stopping=early_stopping, validation_fraction=validation_fraction, n_iter_no_change=n_iter_no_change, warm_start=warm_start, average=average)
41.254748
79
0.604308
import numpy as np import warnings from abc import ABCMeta, abstractmethod from joblib import Parallel, delayed from ..base import clone, is_classifier from ._base import LinearClassifierMixin, SparseCoefMixin from ._base import make_dataset from ..base import BaseEstimator, RegressorMixin from ..utils import check_array, check_random_state, check_X_y from ..utils.extmath import safe_sparse_dot from ..utils.multiclass import _check_partial_fit_first_call from ..utils.validation import check_is_fitted, _check_sample_weight from ..exceptions import ConvergenceWarning from ..model_selection import StratifiedShuffleSplit, ShuffleSplit from ._sgd_fast import plain_sgd, average_sgd from ..utils import compute_class_weight from ._sgd_fast import Hinge from ._sgd_fast import SquaredHinge from ._sgd_fast import Log from ._sgd_fast import ModifiedHuber from ._sgd_fast import SquaredLoss from ._sgd_fast import Huber from ._sgd_fast import EpsilonInsensitive from ._sgd_fast import SquaredEpsilonInsensitive from ..utils.fixes import _joblib_parallel_args LEARNING_RATE_TYPES = {"constant": 1, "optimal": 2, "invscaling": 3, "adaptive": 4, "pa1": 5, "pa2": 6} PENALTY_TYPES = {"none": 0, "l2": 2, "l1": 1, "elasticnet": 3} DEFAULT_EPSILON = 0.1 MAX_INT = np.iinfo(np.int32).max class _ValidationScoreCallback: def __init__(self, estimator, X_val, y_val, sample_weight_val, classes=None): self.estimator = clone(estimator) self.estimator.t_ = 1 if classes is not None: self.estimator.classes_ = classes self.X_val = X_val self.y_val = y_val self.sample_weight_val = sample_weight_val def __call__(self, coef, intercept): est = self.estimator est.coef_ = coef.reshape(1, -1) est.intercept_ = np.atleast_1d(intercept) return est.score(self.X_val, self.y_val, self.sample_weight_val) class BaseSGD(SparseCoefMixin, BaseEstimator, metaclass=ABCMeta): def __init__(self, loss, penalty='l2', alpha=0.0001, C=1.0, l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=1e-3, shuffle=True, verbose=0, epsilon=0.1, random_state=None, learning_rate="optimal", eta0=0.0, power_t=0.5, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, warm_start=False, average=False): self.loss = loss self.penalty = penalty self.learning_rate = learning_rate self.epsilon = epsilon self.alpha = alpha self.C = C self.l1_ratio = l1_ratio self.fit_intercept = fit_intercept self.shuffle = shuffle self.random_state = random_state self.verbose = verbose self.eta0 = eta0 self.power_t = power_t self.early_stopping = early_stopping self.validation_fraction = validation_fraction self.n_iter_no_change = n_iter_no_change self.warm_start = warm_start self.average = average self.max_iter = max_iter self.tol = tol self._validate_params() def set_params(self, **kwargs): super().set_params(**kwargs) self._validate_params() return self @abstractmethod def fit(self, X, y): def _validate_params(self, for_partial_fit=False): if not isinstance(self.shuffle, bool): raise ValueError("shuffle must be either True or False") if not isinstance(self.early_stopping, bool): raise ValueError("early_stopping must be either True or False") if self.early_stopping and for_partial_fit: raise ValueError("early_stopping should be False with partial_fit") if self.max_iter is not None and self.max_iter <= 0: raise ValueError("max_iter must be > zero. Got %f" % self.max_iter) if not (0.0 <= self.l1_ratio <= 1.0): raise ValueError("l1_ratio must be in [0, 1]") if self.alpha < 0.0: raise ValueError("alpha must be >= 0") if self.n_iter_no_change < 1: raise ValueError("n_iter_no_change must be >= 1") if not (0.0 < self.validation_fraction < 1.0): raise ValueError("validation_fraction must be in range (0, 1)") if self.learning_rate in ("constant", "invscaling", "adaptive"): if self.eta0 <= 0.0: raise ValueError("eta0 must be > 0") if self.learning_rate == "optimal" and self.alpha == 0: raise ValueError("alpha must be > 0 since " "learning_rate is 'optimal'. alpha is used " "to compute the optimal learning rate.") self._get_penalty_type(self.penalty) self._get_learning_rate_type(self.learning_rate) if self.loss not in self.loss_functions: raise ValueError("The loss %s is not supported. " % self.loss) def _get_loss_function(self, loss): try: loss_ = self.loss_functions[loss] loss_class, args = loss_[0], loss_[1:] if loss in ('huber', 'epsilon_insensitive', 'squared_epsilon_insensitive'): args = (self.epsilon, ) return loss_class(*args) except KeyError: raise ValueError("The loss %s is not supported. " % loss) def _get_learning_rate_type(self, learning_rate): try: return LEARNING_RATE_TYPES[learning_rate] except KeyError: raise ValueError("learning rate %s " "is not supported. " % learning_rate) def _get_penalty_type(self, penalty): penalty = str(penalty).lower() try: return PENALTY_TYPES[penalty] except KeyError: raise ValueError("Penalty %s is not supported. " % penalty) def _allocate_parameter_mem(self, n_classes, n_features, coef_init=None, intercept_init=None): if n_classes > 2: if coef_init is not None: coef_init = np.asarray(coef_init, order="C") if coef_init.shape != (n_classes, n_features): raise ValueError("Provided ``coef_`` does not match " "dataset. ") self.coef_ = coef_init else: self.coef_ = np.zeros((n_classes, n_features), dtype=np.float64, order="C") if intercept_init is not None: intercept_init = np.asarray(intercept_init, order="C") if intercept_init.shape != (n_classes, ): raise ValueError("Provided intercept_init " "does not match dataset.") self.intercept_ = intercept_init else: self.intercept_ = np.zeros(n_classes, dtype=np.float64, order="C") else: if coef_init is not None: coef_init = np.asarray(coef_init, dtype=np.float64, order="C") coef_init = coef_init.ravel() if coef_init.shape != (n_features,): raise ValueError("Provided coef_init does not " "match dataset.") self.coef_ = coef_init else: self.coef_ = np.zeros(n_features, dtype=np.float64, order="C") if intercept_init is not None: intercept_init = np.asarray(intercept_init, dtype=np.float64) if intercept_init.shape != (1,) and intercept_init.shape != (): raise ValueError("Provided intercept_init " "does not match dataset.") self.intercept_ = intercept_init.reshape(1,) else: self.intercept_ = np.zeros(1, dtype=np.float64, order="C") if self.average > 0: self.standard_coef_ = self.coef_ self.standard_intercept_ = self.intercept_ self.average_coef_ = np.zeros(self.coef_.shape, dtype=np.float64, order="C") self.average_intercept_ = np.zeros(self.standard_intercept_.shape, dtype=np.float64, order="C") def _make_validation_split(self, y): n_samples = y.shape[0] validation_mask = np.zeros(n_samples, dtype=np.uint8) if not self.early_stopping: return validation_mask if is_classifier(self): splitter_type = StratifiedShuffleSplit else: splitter_type = ShuffleSplit cv = splitter_type(test_size=self.validation_fraction, random_state=self.random_state) idx_train, idx_val = next(cv.split(np.zeros(shape=(y.shape[0], 1)), y)) if idx_train.shape[0] == 0 or idx_val.shape[0] == 0: raise ValueError( "Splitting %d samples into a train set and a validation set " "with validation_fraction=%r led to an empty set (%d and %d " "samples). Please either change validation_fraction, increase " "number of samples, or disable early_stopping." % (n_samples, self.validation_fraction, idx_train.shape[0], idx_val.shape[0])) validation_mask[idx_val] = 1 return validation_mask def _make_validation_score_cb(self, validation_mask, X, y, sample_weight, classes=None): if not self.early_stopping: return None return _ValidationScoreCallback( self, X[validation_mask], y[validation_mask], sample_weight[validation_mask], classes=classes) def _prepare_fit_binary(est, y, i): y_i = np.ones(y.shape, dtype=np.float64, order="C") y_i[y != est.classes_[i]] = -1.0 average_intercept = 0 average_coef = None if len(est.classes_) == 2: if not est.average: coef = est.coef_.ravel() intercept = est.intercept_[0] else: coef = est.standard_coef_.ravel() intercept = est.standard_intercept_[0] average_coef = est.average_coef_.ravel() average_intercept = est.average_intercept_[0] else: if not est.average: coef = est.coef_[i] intercept = est.intercept_[i] else: coef = est.standard_coef_[i] intercept = est.standard_intercept_[i] average_coef = est.average_coef_[i] average_intercept = est.average_intercept_[i] return y_i, coef, intercept, average_coef, average_intercept def fit_binary(est, i, X, y, alpha, C, learning_rate, max_iter, pos_weight, neg_weight, sample_weight, validation_mask=None, random_state=None): y_i, coef, intercept, average_coef, average_intercept = \ _prepare_fit_binary(est, y, i) assert y_i.shape[0] == y.shape[0] == sample_weight.shape[0] random_state = check_random_state(random_state) dataset, intercept_decay = make_dataset( X, y_i, sample_weight, random_state=random_state) penalty_type = est._get_penalty_type(est.penalty) learning_rate_type = est._get_learning_rate_type(learning_rate) if validation_mask is None: validation_mask = est._make_validation_split(y_i) classes = np.array([-1, 1], dtype=y_i.dtype) validation_score_cb = est._make_validation_score_cb( validation_mask, X, y_i, sample_weight, classes=classes) seed = random_state.randint(MAX_INT) tol = est.tol if est.tol is not None else -np.inf if not est.average: result = plain_sgd(coef, intercept, est.loss_function_, penalty_type, alpha, C, est.l1_ratio, dataset, validation_mask, est.early_stopping, validation_score_cb, int(est.n_iter_no_change), max_iter, tol, int(est.fit_intercept), int(est.verbose), int(est.shuffle), seed, pos_weight, neg_weight, learning_rate_type, est.eta0, est.power_t, est.t_, intercept_decay) else: standard_coef, standard_intercept, average_coef, average_intercept, \ n_iter_ = average_sgd(coef, intercept, average_coef, average_intercept, est.loss_function_, penalty_type, alpha, C, est.l1_ratio, dataset, validation_mask, est.early_stopping, validation_score_cb, int(est.n_iter_no_change), max_iter, tol, int(est.fit_intercept), int(est.verbose), int(est.shuffle), seed, pos_weight, neg_weight, learning_rate_type, est.eta0, est.power_t, est.t_, intercept_decay, est.average) if len(est.classes_) == 2: est.average_intercept_[0] = average_intercept else: est.average_intercept_[i] = average_intercept result = standard_coef, standard_intercept, n_iter_ return result class BaseSGDClassifier(LinearClassifierMixin, BaseSGD, metaclass=ABCMeta): loss_functions = { "hinge": (Hinge, 1.0), "squared_hinge": (SquaredHinge, 1.0), "perceptron": (Hinge, 0.0), "log": (Log, ), "modified_huber": (ModifiedHuber, ), "squared_loss": (SquaredLoss, ), "huber": (Huber, DEFAULT_EPSILON), "epsilon_insensitive": (EpsilonInsensitive, DEFAULT_EPSILON), "squared_epsilon_insensitive": (SquaredEpsilonInsensitive, DEFAULT_EPSILON), } @abstractmethod def __init__(self, loss="hinge", penalty='l2', alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=1e-3, shuffle=True, verbose=0, epsilon=DEFAULT_EPSILON, n_jobs=None, random_state=None, learning_rate="optimal", eta0=0.0, power_t=0.5, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, class_weight=None, warm_start=False, average=False): super().__init__( loss=loss, penalty=penalty, alpha=alpha, l1_ratio=l1_ratio, fit_intercept=fit_intercept, max_iter=max_iter, tol=tol, shuffle=shuffle, verbose=verbose, epsilon=epsilon, random_state=random_state, learning_rate=learning_rate, eta0=eta0, power_t=power_t, early_stopping=early_stopping, validation_fraction=validation_fraction, n_iter_no_change=n_iter_no_change, warm_start=warm_start, average=average) self.class_weight = class_weight self.n_jobs = n_jobs def _partial_fit(self, X, y, alpha, C, loss, learning_rate, max_iter, classes, sample_weight, coef_init, intercept_init): X, y = check_X_y(X, y, 'csr', dtype=np.float64, order="C", accept_large_sparse=False) n_samples, n_features = X.shape _check_partial_fit_first_call(self, classes) n_classes = self.classes_.shape[0] self._expanded_class_weight = compute_class_weight(self.class_weight, self.classes_, y) sample_weight = _check_sample_weight(sample_weight, X) if getattr(self, "coef_", None) is None or coef_init is not None: self._allocate_parameter_mem(n_classes, n_features, coef_init, intercept_init) elif n_features != self.coef_.shape[-1]: raise ValueError("Number of features %d does not match previous " "data %d." % (n_features, self.coef_.shape[-1])) self.loss_function_ = self._get_loss_function(loss) if not hasattr(self, "t_"): self.t_ = 1.0 if n_classes > 2: self._fit_multiclass(X, y, alpha=alpha, C=C, learning_rate=learning_rate, sample_weight=sample_weight, max_iter=max_iter) elif n_classes == 2: self._fit_binary(X, y, alpha=alpha, C=C, learning_rate=learning_rate, sample_weight=sample_weight, max_iter=max_iter) else: raise ValueError( "The number of classes has to be greater than one;" " got %d class" % n_classes) return self def _fit(self, X, y, alpha, C, loss, learning_rate, coef_init=None, intercept_init=None, sample_weight=None): self._validate_params() if hasattr(self, "classes_"): self.classes_ = None X, y = check_X_y(X, y, 'csr', dtype=np.float64, order="C", accept_large_sparse=False) classes = np.unique(y) if self.warm_start and hasattr(self, "coef_"): if coef_init is None: coef_init = self.coef_ if intercept_init is None: intercept_init = self.intercept_ else: self.coef_ = None self.intercept_ = None if self.average > 0: self.standard_coef_ = self.coef_ self.standard_intercept_ = self.intercept_ self.average_coef_ = None self.average_intercept_ = None self.t_ = 1.0 self._partial_fit(X, y, alpha, C, loss, learning_rate, self.max_iter, classes, sample_weight, coef_init, intercept_init) if (self.tol is not None and self.tol > -np.inf and self.n_iter_ == self.max_iter): warnings.warn("Maximum number of iteration reached before " "convergence. Consider increasing max_iter to " "improve the fit.", ConvergenceWarning) return self def _fit_binary(self, X, y, alpha, C, sample_weight, learning_rate, max_iter): coef, intercept, n_iter_ = fit_binary(self, 1, X, y, alpha, C, learning_rate, max_iter, self._expanded_class_weight[1], self._expanded_class_weight[0], sample_weight, random_state=self.random_state) self.t_ += n_iter_ * X.shape[0] self.n_iter_ = n_iter_ if self.average > 0: if self.average <= self.t_ - 1: self.coef_ = self.average_coef_.reshape(1, -1) self.intercept_ = self.average_intercept_ else: self.coef_ = self.standard_coef_.reshape(1, -1) self.standard_intercept_ = np.atleast_1d(intercept) self.intercept_ = self.standard_intercept_ else: self.coef_ = coef.reshape(1, -1) self.intercept_ = np.atleast_1d(intercept) def _fit_multiclass(self, X, y, alpha, C, learning_rate, sample_weight, max_iter): validation_mask = self._make_validation_split(y) random_state = check_random_state(self.random_state) seeds = random_state.randint(MAX_INT, size=len(self.classes_)) result = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, **_joblib_parallel_args(require="sharedmem"))( delayed(fit_binary)(self, i, X, y, alpha, C, learning_rate, max_iter, self._expanded_class_weight[i], 1., sample_weight, validation_mask=validation_mask, random_state=seed) for i, seed in enumerate(seeds)) n_iter_ = 0. for i, (_, intercept, n_iter_i) in enumerate(result): self.intercept_[i] = intercept n_iter_ = max(n_iter_, n_iter_i) self.t_ += n_iter_ * X.shape[0] self.n_iter_ = n_iter_ if self.average > 0: if self.average <= self.t_ - 1.0: self.coef_ = self.average_coef_ self.intercept_ = self.average_intercept_ else: self.coef_ = self.standard_coef_ self.standard_intercept_ = np.atleast_1d(self.intercept_) self.intercept_ = self.standard_intercept_ def partial_fit(self, X, y, classes=None, sample_weight=None): self._validate_params(for_partial_fit=True) if self.class_weight in ['balanced']: raise ValueError("class_weight '{0}' is not supported for " "partial_fit. In order to use 'balanced' weights," " use compute_class_weight('{0}', classes, y). " "In place of y you can us a large enough sample " "of the full training set target to properly " "estimate the class frequency distributions. " "Pass the resulting weights as the class_weight " "parameter.".format(self.class_weight)) return self._partial_fit(X, y, alpha=self.alpha, C=1.0, loss=self.loss, learning_rate=self.learning_rate, max_iter=1, classes=classes, sample_weight=sample_weight, coef_init=None, intercept_init=None) def fit(self, X, y, coef_init=None, intercept_init=None, sample_weight=None): return self._fit(X, y, alpha=self.alpha, C=1.0, loss=self.loss, learning_rate=self.learning_rate, coef_init=coef_init, intercept_init=intercept_init, sample_weight=sample_weight) class SGDClassifier(BaseSGDClassifier): def __init__(self, loss="hinge", penalty='l2', alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=1e-3, shuffle=True, verbose=0, epsilon=DEFAULT_EPSILON, n_jobs=None, random_state=None, learning_rate="optimal", eta0=0.0, power_t=0.5, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, class_weight=None, warm_start=False, average=False): super().__init__( loss=loss, penalty=penalty, alpha=alpha, l1_ratio=l1_ratio, fit_intercept=fit_intercept, max_iter=max_iter, tol=tol, shuffle=shuffle, verbose=verbose, epsilon=epsilon, n_jobs=n_jobs, random_state=random_state, learning_rate=learning_rate, eta0=eta0, power_t=power_t, early_stopping=early_stopping, validation_fraction=validation_fraction, n_iter_no_change=n_iter_no_change, class_weight=class_weight, warm_start=warm_start, average=average) def _check_proba(self): if self.loss not in ("log", "modified_huber"): raise AttributeError("probability estimates are not available for" " loss=%r" % self.loss) @property def predict_proba(self): self._check_proba() return self._predict_proba def _predict_proba(self, X): check_is_fitted(self) if self.loss == "log": return self._predict_proba_lr(X) elif self.loss == "modified_huber": binary = (len(self.classes_) == 2) scores = self.decision_function(X) if binary: prob2 = np.ones((scores.shape[0], 2)) prob = prob2[:, 1] else: prob = scores np.clip(scores, -1, 1, prob) prob += 1. prob /= 2. if binary: prob2[:, 0] -= prob prob = prob2 else: # normalize neatly; work around this to produce uniform # probabilities prob_sum = prob.sum(axis=1) all_zero = (prob_sum == 0) if np.any(all_zero): prob[all_zero, :] = 1 prob_sum[all_zero] = len(self.classes_) # normalize prob /= prob_sum.reshape((prob.shape[0], -1)) return prob else: raise NotImplementedError("predict_(log_)proba only supported when" " loss='log' or loss='modified_huber' " "(%r given)" % self.loss) @property def predict_log_proba(self): self._check_proba() return self._predict_log_proba def _predict_log_proba(self, X): return np.log(self.predict_proba(X)) class BaseSGDRegressor(RegressorMixin, BaseSGD): loss_functions = { "squared_loss": (SquaredLoss, ), "huber": (Huber, DEFAULT_EPSILON), "epsilon_insensitive": (EpsilonInsensitive, DEFAULT_EPSILON), "squared_epsilon_insensitive": (SquaredEpsilonInsensitive, DEFAULT_EPSILON), } @abstractmethod def __init__(self, loss="squared_loss", penalty="l2", alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=1e-3, shuffle=True, verbose=0, epsilon=DEFAULT_EPSILON, random_state=None, learning_rate="invscaling", eta0=0.01, power_t=0.25, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, warm_start=False, average=False): super().__init__( loss=loss, penalty=penalty, alpha=alpha, l1_ratio=l1_ratio, fit_intercept=fit_intercept, max_iter=max_iter, tol=tol, shuffle=shuffle, verbose=verbose, epsilon=epsilon, random_state=random_state, learning_rate=learning_rate, eta0=eta0, power_t=power_t, early_stopping=early_stopping, validation_fraction=validation_fraction, n_iter_no_change=n_iter_no_change, warm_start=warm_start, average=average) def _partial_fit(self, X, y, alpha, C, loss, learning_rate, max_iter, sample_weight, coef_init, intercept_init): X, y = check_X_y(X, y, "csr", copy=False, order='C', dtype=np.float64, accept_large_sparse=False) y = y.astype(np.float64, copy=False) n_samples, n_features = X.shape sample_weight = _check_sample_weight(sample_weight, X) # Allocate datastructures from input arguments if getattr(self, "coef_", None) is None: self._allocate_parameter_mem(1, n_features, coef_init, intercept_init) elif n_features != self.coef_.shape[-1]: raise ValueError("Number of features %d does not match previous " "data %d." % (n_features, self.coef_.shape[-1])) if self.average > 0 and getattr(self, "average_coef_", None) is None: self.average_coef_ = np.zeros(n_features, dtype=np.float64, order="C") self.average_intercept_ = np.zeros(1, dtype=np.float64, order="C") self._fit_regressor(X, y, alpha, C, loss, learning_rate, sample_weight, max_iter) return self def partial_fit(self, X, y, sample_weight=None): self._validate_params(for_partial_fit=True) return self._partial_fit(X, y, self.alpha, C=1.0, loss=self.loss, learning_rate=self.learning_rate, max_iter=1, sample_weight=sample_weight, coef_init=None, intercept_init=None) def _fit(self, X, y, alpha, C, loss, learning_rate, coef_init=None, intercept_init=None, sample_weight=None): self._validate_params() if self.warm_start and getattr(self, "coef_", None) is not None: if coef_init is None: coef_init = self.coef_ if intercept_init is None: intercept_init = self.intercept_ else: self.coef_ = None self.intercept_ = None if self.average > 0: self.standard_intercept_ = self.intercept_ self.standard_coef_ = self.coef_ self.average_coef_ = None self.average_intercept_ = None # Clear iteration count for multiple call to fit. self.t_ = 1.0 self._partial_fit(X, y, alpha, C, loss, learning_rate, self.max_iter, sample_weight, coef_init, intercept_init) if (self.tol is not None and self.tol > -np.inf and self.n_iter_ == self.max_iter): warnings.warn("Maximum number of iteration reached before " "convergence. Consider increasing max_iter to " "improve the fit.", ConvergenceWarning) return self def fit(self, X, y, coef_init=None, intercept_init=None, sample_weight=None): return self._fit(X, y, alpha=self.alpha, C=1.0, loss=self.loss, learning_rate=self.learning_rate, coef_init=coef_init, intercept_init=intercept_init, sample_weight=sample_weight) def _decision_function(self, X): check_is_fitted(self) X = check_array(X, accept_sparse='csr') scores = safe_sparse_dot(X, self.coef_.T, dense_output=True) + self.intercept_ return scores.ravel() def predict(self, X): return self._decision_function(X) def _fit_regressor(self, X, y, alpha, C, loss, learning_rate, sample_weight, max_iter): dataset, intercept_decay = make_dataset(X, y, sample_weight) loss_function = self._get_loss_function(loss) penalty_type = self._get_penalty_type(self.penalty) learning_rate_type = self._get_learning_rate_type(learning_rate) if not hasattr(self, "t_"): self.t_ = 1.0 validation_mask = self._make_validation_split(y) validation_score_cb = self._make_validation_score_cb( validation_mask, X, y, sample_weight) random_state = check_random_state(self.random_state) # numpy mtrand expects a C long which is a signed 32 bit integer under # Windows seed = random_state.randint(0, np.iinfo(np.int32).max) tol = self.tol if self.tol is not None else -np.inf if self.average > 0: self.standard_coef_, self.standard_intercept_, \ self.average_coef_, self.average_intercept_, self.n_iter_ =\ average_sgd(self.standard_coef_, self.standard_intercept_[0], self.average_coef_, self.average_intercept_[0], loss_function, penalty_type, alpha, C, self.l1_ratio, dataset, validation_mask, self.early_stopping, validation_score_cb, int(self.n_iter_no_change), max_iter, tol, int(self.fit_intercept), int(self.verbose), int(self.shuffle), seed, 1.0, 1.0, learning_rate_type, self.eta0, self.power_t, self.t_, intercept_decay, self.average) self.average_intercept_ = np.atleast_1d(self.average_intercept_) self.standard_intercept_ = np.atleast_1d(self.standard_intercept_) self.t_ += self.n_iter_ * X.shape[0] if self.average <= self.t_ - 1.0: self.coef_ = self.average_coef_ self.intercept_ = self.average_intercept_ else: self.coef_ = self.standard_coef_ self.intercept_ = self.standard_intercept_ else: self.coef_, self.intercept_, self.n_iter_ = \ plain_sgd(self.coef_, self.intercept_[0], loss_function, penalty_type, alpha, C, self.l1_ratio, dataset, validation_mask, self.early_stopping, validation_score_cb, int(self.n_iter_no_change), max_iter, tol, int(self.fit_intercept), int(self.verbose), int(self.shuffle), seed, 1.0, 1.0, learning_rate_type, self.eta0, self.power_t, self.t_, intercept_decay) self.t_ += self.n_iter_ * X.shape[0] self.intercept_ = np.atleast_1d(self.intercept_) class SGDRegressor(BaseSGDRegressor): def __init__(self, loss="squared_loss", penalty="l2", alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=1e-3, shuffle=True, verbose=0, epsilon=DEFAULT_EPSILON, random_state=None, learning_rate="invscaling", eta0=0.01, power_t=0.25, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, warm_start=False, average=False): super().__init__( loss=loss, penalty=penalty, alpha=alpha, l1_ratio=l1_ratio, fit_intercept=fit_intercept, max_iter=max_iter, tol=tol, shuffle=shuffle, verbose=verbose, epsilon=epsilon, random_state=random_state, learning_rate=learning_rate, eta0=eta0, power_t=power_t, early_stopping=early_stopping, validation_fraction=validation_fraction, n_iter_no_change=n_iter_no_change, warm_start=warm_start, average=average)
true
true
f7256edb1cd981f4d5a110f018a377b55aa4f7c7
1,246
py
Python
Model prediction/app.py
choudhury722k/English-to-French-translator
e792ce92adbdd3100d73d9d8aebc109cc7c560d7
[ "MIT" ]
null
null
null
Model prediction/app.py
choudhury722k/English-to-French-translator
e792ce92adbdd3100d73d9d8aebc109cc7c560d7
[ "MIT" ]
null
null
null
Model prediction/app.py
choudhury722k/English-to-French-translator
e792ce92adbdd3100d73d9d8aebc109cc7c560d7
[ "MIT" ]
null
null
null
from re import X from flask import Flask,render_template,url_for,request from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras import models import numpy as np import pickle french_tokenizer = pickle.load(open('french_tokenizer.pickle', 'rb')) english_tokenizer = pickle.load(open('english_tokenizer.pickle', 'rb')) model = models.load_model("translator_model.h5") y_id_to_word = {value: key for key, value in french_tokenizer.word_index.items()} y_id_to_word[0] = '<PAD>' #y_id_to_word app = Flask(__name__) @app.route('/') def hello_World(): return "Hello Soumya" @app.route('/translator', methods = ['GET', 'POST']) def eng_to_french(): message = request.args.get("message") sentence = [english_tokenizer.word_index[word] for word in message.split()] #sentence sentence = pad_sequences([sentence], maxlen=15, padding='post') sentences = np.array([sentence[0]]) predictions = model.predict(sentences, len(sentences)) x = ' '.join([y_id_to_word[np.argmax(x)] for x in predictions[0]]) if '<PAD>' in x: x=x.replace('<PAD>','') print(x) return x if __name__ == '__main__': app.run(debug=True)
31.948718
81
0.719904
from re import X from flask import Flask,render_template,url_for,request from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras import models import numpy as np import pickle french_tokenizer = pickle.load(open('french_tokenizer.pickle', 'rb')) english_tokenizer = pickle.load(open('english_tokenizer.pickle', 'rb')) model = models.load_model("translator_model.h5") y_id_to_word = {value: key for key, value in french_tokenizer.word_index.items()} y_id_to_word[0] = '<PAD>' app = Flask(__name__) @app.route('/') def hello_World(): return "Hello Soumya" @app.route('/translator', methods = ['GET', 'POST']) def eng_to_french(): message = request.args.get("message") sentence = [english_tokenizer.word_index[word] for word in message.split()] sentence = pad_sequences([sentence], maxlen=15, padding='post') sentences = np.array([sentence[0]]) predictions = model.predict(sentences, len(sentences)) x = ' '.join([y_id_to_word[np.argmax(x)] for x in predictions[0]]) if '<PAD>' in x: x=x.replace('<PAD>','') print(x) return x if __name__ == '__main__': app.run(debug=True)
true
true
f7256eedcf3a758fc0b86618617827425e34c972
438
py
Python
carpyncho2/carpyncho/steps/prepare_pawprint_to_sync.py
carpyncho/yeolde_carpyncho
fba72ebf9d4a3e4e4ea18160310058c6812a0457
[ "BSD-3-Clause" ]
null
null
null
carpyncho2/carpyncho/steps/prepare_pawprint_to_sync.py
carpyncho/yeolde_carpyncho
fba72ebf9d4a3e4e4ea18160310058c6812a0457
[ "BSD-3-Clause" ]
2
2020-06-05T19:37:26.000Z
2020-06-05T19:40:38.000Z
carpyncho2/carpyncho/steps/prepare_pawprint_to_sync.py
carpyncho/yeolde_carpyncho
fba72ebf9d4a3e4e4ea18160310058c6812a0457
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- from corral import run from ..models import PawprintXTile class PreparePawprintToSync(run.Step): model = PawprintXTile conditions = [ PawprintXTile.status == "raw", PawprintXTile.tile.has(status="loaded"), PawprintXTile.pawprint.has(status="loaded") ] limit = 500 groups = ["match"] def process(self, pxt): pxt.status = "pending"
19.909091
51
0.630137
from corral import run from ..models import PawprintXTile class PreparePawprintToSync(run.Step): model = PawprintXTile conditions = [ PawprintXTile.status == "raw", PawprintXTile.tile.has(status="loaded"), PawprintXTile.pawprint.has(status="loaded") ] limit = 500 groups = ["match"] def process(self, pxt): pxt.status = "pending"
true
true
f7256fad4dd4f8677f2d6bac3cf8110e20ecf681
423
py
Python
mysite/mysite/development_settings.py
timmahrt/gamecorpus
6ce170f3d590475a320410c9d937039555207ee9
[ "MIT" ]
null
null
null
mysite/mysite/development_settings.py
timmahrt/gamecorpus
6ce170f3d590475a320410c9d937039555207ee9
[ "MIT" ]
null
null
null
mysite/mysite/development_settings.py
timmahrt/gamecorpus
6ce170f3d590475a320410c9d937039555207ee9
[ "MIT" ]
null
null
null
from mysite.common_settings import * SECRET_KEY = "aje#lg$7!t!tc5*i%ittn(to%5#5%vjvi*oc=ib25wx%+##_b+" DEBUG = True ALLOWED_HOSTS = ["*"] # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": "game_corpus_db", "HOST": "127.0.0.1", "USER": "tmahrt", "PASSWORD": "12345678", } }
21.15
65
0.591017
from mysite.common_settings import * SECRET_KEY = "aje#lg$7!t!tc5*i%ittn(to%5#5%vjvi*oc=ib25wx%+##_b+" DEBUG = True ALLOWED_HOSTS = ["*"] S = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": "game_corpus_db", "HOST": "127.0.0.1", "USER": "tmahrt", "PASSWORD": "12345678", } }
true
true
f725707d1175e051257c22b78d93284af9b6061b
4,819
py
Python
catalyst/engines/tests/test_parallel.py
alxmamaev/catalyst
d05120c68fbc5174ff74297d29c0fc00d7e94924
[ "Apache-2.0" ]
1
2021-03-02T12:06:32.000Z
2021-03-02T12:06:32.000Z
catalyst/engines/tests/test_parallel.py
alxmamaev/catalyst
d05120c68fbc5174ff74297d29c0fc00d7e94924
[ "Apache-2.0" ]
null
null
null
catalyst/engines/tests/test_parallel.py
alxmamaev/catalyst
d05120c68fbc5174ff74297d29c0fc00d7e94924
[ "Apache-2.0" ]
null
null
null
# flake8: noqa from typing import Any, Dict, List import logging from tempfile import TemporaryDirectory from pytest import mark import torch from torch.utils.data import DataLoader from catalyst.callbacks import CheckpointCallback, CriterionCallback, OptimizerCallback from catalyst.core.runner import IRunner from catalyst.engines import DataParallelEngine from catalyst.engines.torch import DeviceEngine from catalyst.loggers import ConsoleLogger, CSVLogger from catalyst.runners.config import SupervisedConfigRunner from catalyst.settings import IS_CUDA_AVAILABLE, NUM_CUDA_DEVICES from .misc import DataParallelTypeChecker, DummyDataset, DummyModel, LossMinimizationCallback logger = logging.getLogger(__name__) class CustomRunner(IRunner): def __init__(self, logdir): super().__init__() self._logdir = logdir def get_engine(self): return DataParallelEngine() def get_callbacks(self, stage: str): return { "criterion": CriterionCallback( metric_key="loss", input_key="logits", target_key="targets" ), "optimizer": OptimizerCallback(metric_key="loss"), # "scheduler": dl.SchedulerCallback(loader_key="valid", metric_key="loss"), "checkpoint": CheckpointCallback( self._logdir, loader_key="valid", metric_key="loss", minimize=True, save_n_best=3 ), "test_nn_parallel_data_parallel": DataParallelTypeChecker(), "test_loss_minimization": LossMinimizationCallback("loss", logger=logger), } @property def stages(self) -> "Iterable[str]": return ["train"] def get_stage_len(self, stage: str) -> int: return 10 def get_loaders(self, stage: str) -> "OrderedDict[str, DataLoader]": dataset = DummyDataset(6) loader = DataLoader(dataset, batch_size=4) return {"train": loader, "valid": loader} def get_model(self, stage: str): return DummyModel(4, 2) def get_criterion(self, stage: str): return torch.nn.MSELoss() def get_optimizer(self, model, stage: str): return torch.optim.Adam(model.parameters()) def get_scheduler(self, optimizer, stage: str): return None def get_trial(self): return None def get_loggers(self): return {"console": ConsoleLogger(), "csv": CSVLogger(logdir=self._logdir)} def handle_batch(self, batch): x, y = batch logits = self.model(x) self.batch = {"features": x, "targets": y, "logits": logits} def train_from_runner(): with TemporaryDirectory() as logdir: runner = CustomRunner(logdir) runner.run() def train_from_config(): with TemporaryDirectory() as logdir: dataset = DummyDataset(6) runner = SupervisedConfigRunner( config={ "args": {"logdir": logdir}, "model": {"_target_": "DummyModel", "in_features": 4, "out_features": 2}, "engine": {"_target_": "DataParallelEngine"}, "args": {"logdir": logdir}, "stages": { "stage1": { "num_epochs": 10, "loaders": {"batch_size": 4, "num_workers": 0}, "criterion": {"_target_": "MSELoss"}, "optimizer": {"_target_": "Adam", "lr": 1e-3}, "callbacks": { "criterion": { "_target_": "CriterionCallback", "metric_key": "loss", "input_key": "logits", "target_key": "targets", }, "optimizer": {"_target_": "OptimizerCallback", "metric_key": "loss"}, "test_nn_parallel_data_parallel": { "_target_": "DataParallelTypeChecker" }, "test_loss_minimization": { "_target_": "LossMinimizationCallback", "key": "loss", }, }, }, }, } ) runner.get_datasets = lambda *args, **kwargs: { "train": dataset, "valid": dataset, } runner.run() @mark.skipif(not IS_CUDA_AVAILABLE, reason="CUDA device is not available") def test_experiment_parallel_engine_with_cuda(): train_from_runner() # @mark.skip("Config experiment is in development phase!") @mark.skipif(not IS_CUDA_AVAILABLE, reason="CUDA device is not available") def test_config_experiment_engine_with_cuda(): train_from_config()
34.421429
97
0.573563
from typing import Any, Dict, List import logging from tempfile import TemporaryDirectory from pytest import mark import torch from torch.utils.data import DataLoader from catalyst.callbacks import CheckpointCallback, CriterionCallback, OptimizerCallback from catalyst.core.runner import IRunner from catalyst.engines import DataParallelEngine from catalyst.engines.torch import DeviceEngine from catalyst.loggers import ConsoleLogger, CSVLogger from catalyst.runners.config import SupervisedConfigRunner from catalyst.settings import IS_CUDA_AVAILABLE, NUM_CUDA_DEVICES from .misc import DataParallelTypeChecker, DummyDataset, DummyModel, LossMinimizationCallback logger = logging.getLogger(__name__) class CustomRunner(IRunner): def __init__(self, logdir): super().__init__() self._logdir = logdir def get_engine(self): return DataParallelEngine() def get_callbacks(self, stage: str): return { "criterion": CriterionCallback( metric_key="loss", input_key="logits", target_key="targets" ), "optimizer": OptimizerCallback(metric_key="loss"), "checkpoint": CheckpointCallback( self._logdir, loader_key="valid", metric_key="loss", minimize=True, save_n_best=3 ), "test_nn_parallel_data_parallel": DataParallelTypeChecker(), "test_loss_minimization": LossMinimizationCallback("loss", logger=logger), } @property def stages(self) -> "Iterable[str]": return ["train"] def get_stage_len(self, stage: str) -> int: return 10 def get_loaders(self, stage: str) -> "OrderedDict[str, DataLoader]": dataset = DummyDataset(6) loader = DataLoader(dataset, batch_size=4) return {"train": loader, "valid": loader} def get_model(self, stage: str): return DummyModel(4, 2) def get_criterion(self, stage: str): return torch.nn.MSELoss() def get_optimizer(self, model, stage: str): return torch.optim.Adam(model.parameters()) def get_scheduler(self, optimizer, stage: str): return None def get_trial(self): return None def get_loggers(self): return {"console": ConsoleLogger(), "csv": CSVLogger(logdir=self._logdir)} def handle_batch(self, batch): x, y = batch logits = self.model(x) self.batch = {"features": x, "targets": y, "logits": logits} def train_from_runner(): with TemporaryDirectory() as logdir: runner = CustomRunner(logdir) runner.run() def train_from_config(): with TemporaryDirectory() as logdir: dataset = DummyDataset(6) runner = SupervisedConfigRunner( config={ "args": {"logdir": logdir}, "model": {"_target_": "DummyModel", "in_features": 4, "out_features": 2}, "engine": {"_target_": "DataParallelEngine"}, "args": {"logdir": logdir}, "stages": { "stage1": { "num_epochs": 10, "loaders": {"batch_size": 4, "num_workers": 0}, "criterion": {"_target_": "MSELoss"}, "optimizer": {"_target_": "Adam", "lr": 1e-3}, "callbacks": { "criterion": { "_target_": "CriterionCallback", "metric_key": "loss", "input_key": "logits", "target_key": "targets", }, "optimizer": {"_target_": "OptimizerCallback", "metric_key": "loss"}, "test_nn_parallel_data_parallel": { "_target_": "DataParallelTypeChecker" }, "test_loss_minimization": { "_target_": "LossMinimizationCallback", "key": "loss", }, }, }, }, } ) runner.get_datasets = lambda *args, **kwargs: { "train": dataset, "valid": dataset, } runner.run() @mark.skipif(not IS_CUDA_AVAILABLE, reason="CUDA device is not available") def test_experiment_parallel_engine_with_cuda(): train_from_runner() @mark.skipif(not IS_CUDA_AVAILABLE, reason="CUDA device is not available") def test_config_experiment_engine_with_cuda(): train_from_config()
true
true
f72572a5ded8e8384c8775f3509841aff1d8e01a
1,939
py
Python
tests/test_issues/test_issue_25.py
cmungall/PyShEx
43026c4b0393362e770b868794c5d9071e691d6f
[ "CC0-1.0" ]
25
2018-01-11T10:59:16.000Z
2021-07-02T03:44:02.000Z
tests/test_issues/test_issue_25.py
cmungall/PyShEx
43026c4b0393362e770b868794c5d9071e691d6f
[ "CC0-1.0" ]
66
2018-03-12T01:12:02.000Z
2022-03-18T07:56:31.000Z
tests/test_issues/test_issue_25.py
cmungall/PyShEx
43026c4b0393362e770b868794c5d9071e691d6f
[ "CC0-1.0" ]
12
2018-04-06T11:29:40.000Z
2021-12-17T22:48:07.000Z
import os import unittest from contextlib import redirect_stdout, redirect_stderr from io import StringIO from pyshex.shex_evaluator import evaluate_cli data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'data')) validation_dir = os.path.join(data_dir, 'validation') rdffile = os.path.join(validation_dir, 'simple.ttl') shexfile = os.path.join(validation_dir, 'simple.shex') class Issue25TestCase(unittest.TestCase): def test_nostart(self): outf = StringIO() with(redirect_stdout(outf)): evaluate_cli(f"{rdffile} {shexfile} -A".split()) self.assertEqual("""Errors: Focus: None Start: None Reason: START node is not specified""", outf.getvalue().strip()) def test_all_nodes(self): outf = StringIO() with(redirect_stderr(outf)): evaluate_cli(f"{rdffile} {shexfile} -s http://example.org/shapes/S".split()) self.assertEqual('Error: You must specify one or more graph focus nodes, supply a SPARQL query, ' 'or use the "-A" option', outf.getvalue().strip()) outf = StringIO() with(redirect_stdout(outf)): evaluate_cli(f"{rdffile} {shexfile} -A -s http://example.org/shapes/S".split()) self.assertEqual("""Errors: Focus: http://a.example/s1 Start: http://example.org/shapes/S Reason: Testing :s1 against shape http://example.org/shapes/S No matching triples found for predicate :s4 Focus: http://a.example/s2 Start: http://example.org/shapes/S Reason: Testing :s2 against shape http://example.org/shapes/S No matching triples found for predicate :s4 Focus: http://a.example/s3 Start: http://example.org/shapes/S Reason: Testing :s3 against shape http://example.org/shapes/S No matching triples found for predicate :s4""", outf.getvalue().strip()) if __name__ == '__main__': unittest.main()
35.254545
105
0.66426
import os import unittest from contextlib import redirect_stdout, redirect_stderr from io import StringIO from pyshex.shex_evaluator import evaluate_cli data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'data')) validation_dir = os.path.join(data_dir, 'validation') rdffile = os.path.join(validation_dir, 'simple.ttl') shexfile = os.path.join(validation_dir, 'simple.shex') class Issue25TestCase(unittest.TestCase): def test_nostart(self): outf = StringIO() with(redirect_stdout(outf)): evaluate_cli(f"{rdffile} {shexfile} -A".split()) self.assertEqual("""Errors: Focus: None Start: None Reason: START node is not specified""", outf.getvalue().strip()) def test_all_nodes(self): outf = StringIO() with(redirect_stderr(outf)): evaluate_cli(f"{rdffile} {shexfile} -s http://example.org/shapes/S".split()) self.assertEqual('Error: You must specify one or more graph focus nodes, supply a SPARQL query, ' 'or use the "-A" option', outf.getvalue().strip()) outf = StringIO() with(redirect_stdout(outf)): evaluate_cli(f"{rdffile} {shexfile} -A -s http://example.org/shapes/S".split()) self.assertEqual("""Errors: Focus: http://a.example/s1 Start: http://example.org/shapes/S Reason: Testing :s1 against shape http://example.org/shapes/S No matching triples found for predicate :s4 Focus: http://a.example/s2 Start: http://example.org/shapes/S Reason: Testing :s2 against shape http://example.org/shapes/S No matching triples found for predicate :s4 Focus: http://a.example/s3 Start: http://example.org/shapes/S Reason: Testing :s3 against shape http://example.org/shapes/S No matching triples found for predicate :s4""", outf.getvalue().strip()) if __name__ == '__main__': unittest.main()
true
true
f725742c34d7363a4d55d7cc29936dc1953858f7
3,975
py
Python
cpp/build-support/lint_cpp_cli.py
LuoZijun/arrow
8219a8b878d9344fe73e07def34a18a71a8f85a8
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0" ]
1
2020-09-15T16:47:08.000Z
2020-09-15T16:47:08.000Z
cpp/build-support/lint_cpp_cli.py
LuoZijun/arrow
8219a8b878d9344fe73e07def34a18a71a8f85a8
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0" ]
3
2018-10-25T13:52:14.000Z
2018-10-27T08:44:27.000Z
cpp/build-support/lint_cpp_cli.py
LuoZijun/arrow
8219a8b878d9344fe73e07def34a18a71a8f85a8
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0" ]
10
2019-03-18T08:19:16.000Z
2020-09-15T09:05:39.000Z
#!/usr/bin/env python # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import argparse import re import os parser = argparse.ArgumentParser( description="Check for illegal headers for C++/CLI applications") parser.add_argument("source_path", help="Path to source code") arguments = parser.parse_args() _STRIP_COMMENT_REGEX = re.compile('(.+)?(?=//)') _NULLPTR_REGEX = re.compile(r'.*\bnullptr\b.*') _RETURN_NOT_OK_REGEX = re.compile(r'.*\sRETURN_NOT_OK.*') _ASSIGN_OR_RAISE_REGEX = re.compile(r'.*\sASSIGN_OR_RAISE.*') def _paths(paths): return [p.strip().replace('/', os.path.sep) for p in paths.splitlines()] def _strip_comments(line): m = _STRIP_COMMENT_REGEX.match(line) if not m: return line else: return m.group(0) def lint_file(path): fail_rules = [ # rule, error message, rule-specific exclusions list (lambda x: '<mutex>' in x, 'Uses <mutex>', []), (lambda x: '<iostream>' in x, 'Uses <iostream>', []), (lambda x: re.match(_NULLPTR_REGEX, x), 'Uses nullptr', []), (lambda x: re.match(_RETURN_NOT_OK_REGEX, x), 'Use ARROW_RETURN_NOT_OK in header files', _paths('''\ arrow/status.h test arrow/util/hash.h arrow/python/util''')), (lambda x: re.match(_ASSIGN_OR_RAISE_REGEX, x), 'Use ARROW_ASSIGN_OR_RAISE in header files', _paths('''\ arrow/result_internal.h test ''')) ] with open(path) as f: for i, line in enumerate(f): stripped_line = _strip_comments(line) for rule, why, rule_exclusions in fail_rules: if any([True for excl in rule_exclusions if excl in path]): continue if rule(stripped_line): yield path, why, i, line EXCLUSIONS = _paths('''\ arrow/python/iterators.h arrow/util/hashing.h arrow/util/macros.h arrow/util/parallel.h arrow/vendored arrow/visitor_inline.h gandiva/cache.h gandiva/jni jni/ test internal _generated''') def lint_files(): for dirpath, _, filenames in os.walk(arguments.source_path): for filename in filenames: full_path = os.path.join(dirpath, filename) exclude = False for exclusion in EXCLUSIONS: if exclusion in full_path: exclude = True break if exclude: continue # Lint file name, except for pkgconfig templates if not filename.endswith('.pc.in'): if '-' in filename: why = ("Please user underscores, not hyphens, " "in source file names") yield full_path, why, 0, full_path # Only run on header files if filename.endswith('.h'): for _ in lint_file(full_path): yield _ if __name__ == '__main__': failures = list(lint_files()) for path, why, i, line in failures: print('File {0} failed C++/CLI lint check: {1}\n' 'Line {2}: {3}'.format(path, why, i + 1, line)) if failures: exit(1)
31.054688
76
0.610063
import argparse import re import os parser = argparse.ArgumentParser( description="Check for illegal headers for C++/CLI applications") parser.add_argument("source_path", help="Path to source code") arguments = parser.parse_args() _STRIP_COMMENT_REGEX = re.compile('(.+)?(?=//)') _NULLPTR_REGEX = re.compile(r'.*\bnullptr\b.*') _RETURN_NOT_OK_REGEX = re.compile(r'.*\sRETURN_NOT_OK.*') _ASSIGN_OR_RAISE_REGEX = re.compile(r'.*\sASSIGN_OR_RAISE.*') def _paths(paths): return [p.strip().replace('/', os.path.sep) for p in paths.splitlines()] def _strip_comments(line): m = _STRIP_COMMENT_REGEX.match(line) if not m: return line else: return m.group(0) def lint_file(path): fail_rules = [ (lambda x: '<mutex>' in x, 'Uses <mutex>', []), (lambda x: '<iostream>' in x, 'Uses <iostream>', []), (lambda x: re.match(_NULLPTR_REGEX, x), 'Uses nullptr', []), (lambda x: re.match(_RETURN_NOT_OK_REGEX, x), 'Use ARROW_RETURN_NOT_OK in header files', _paths('''\ arrow/status.h test arrow/util/hash.h arrow/python/util''')), (lambda x: re.match(_ASSIGN_OR_RAISE_REGEX, x), 'Use ARROW_ASSIGN_OR_RAISE in header files', _paths('''\ arrow/result_internal.h test ''')) ] with open(path) as f: for i, line in enumerate(f): stripped_line = _strip_comments(line) for rule, why, rule_exclusions in fail_rules: if any([True for excl in rule_exclusions if excl in path]): continue if rule(stripped_line): yield path, why, i, line EXCLUSIONS = _paths('''\ arrow/python/iterators.h arrow/util/hashing.h arrow/util/macros.h arrow/util/parallel.h arrow/vendored arrow/visitor_inline.h gandiva/cache.h gandiva/jni jni/ test internal _generated''') def lint_files(): for dirpath, _, filenames in os.walk(arguments.source_path): for filename in filenames: full_path = os.path.join(dirpath, filename) exclude = False for exclusion in EXCLUSIONS: if exclusion in full_path: exclude = True break if exclude: continue if not filename.endswith('.pc.in'): if '-' in filename: why = ("Please user underscores, not hyphens, " "in source file names") yield full_path, why, 0, full_path if filename.endswith('.h'): for _ in lint_file(full_path): yield _ if __name__ == '__main__': failures = list(lint_files()) for path, why, i, line in failures: print('File {0} failed C++/CLI lint check: {1}\n' 'Line {2}: {3}'.format(path, why, i + 1, line)) if failures: exit(1)
true
true
f72574687e5a2e271c479e18ac1e881bdf5eae75
578
py
Python
azure-mgmt-consumption/azure/mgmt/consumption/models/consumption_management_client_enums.py
v-Ajnava/azure-sdk-for-python
a1f6f80eb5869c5b710e8bfb66146546697e2a6f
[ "MIT" ]
4
2016-06-17T23:25:29.000Z
2022-03-30T22:37:45.000Z
azure-mgmt-consumption/azure/mgmt/consumption/models/consumption_management_client_enums.py
v-Ajnava/azure-sdk-for-python
a1f6f80eb5869c5b710e8bfb66146546697e2a6f
[ "MIT" ]
2
2016-09-30T21:40:24.000Z
2017-11-10T18:16:18.000Z
azure-mgmt-consumption/azure/mgmt/consumption/models/consumption_management_client_enums.py
v-Ajnava/azure-sdk-for-python
a1f6f80eb5869c5b710e8bfb66146546697e2a6f
[ "MIT" ]
3
2016-05-03T20:49:46.000Z
2017-10-05T21:05:27.000Z
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from enum import Enum class Datagrain(Enum): daily_grain = "daily" monthly_grain = "monthly"
30.421053
76
0.550173
from enum import Enum class Datagrain(Enum): daily_grain = "daily" monthly_grain = "monthly"
true
true
f725747bf99d90df726266e21ecdd3c5dc730fc5
16,227
py
Python
pyfarm/models/core/mixins.py
guidow/pyfarm-master
d41c8f1eb5bfefb8400d400bcecadf197bcfb80a
[ "Apache-2.0" ]
null
null
null
pyfarm/models/core/mixins.py
guidow/pyfarm-master
d41c8f1eb5bfefb8400d400bcecadf197bcfb80a
[ "Apache-2.0" ]
null
null
null
pyfarm/models/core/mixins.py
guidow/pyfarm-master
d41c8f1eb5bfefb8400d400bcecadf197bcfb80a
[ "Apache-2.0" ]
null
null
null
# No shebang line, this module is meant to be imported # # Copyright 2013 Oliver Palmer # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Mixin Classes ============= Module containing mixins which can be used by multiple models. """ from datetime import datetime from collections import namedtuple try: from httplib import INTERNAL_SERVER_ERROR except ImportError: from http.client import INTERNAL_SERVER_ERROR from sqlalchemy.orm import validates, class_mapper from pyfarm.core.enums import _WorkState, Values, PY2 from pyfarm.core.logger import getLogger from pyfarm.models.core.types import IPAddress from pyfarm.master.config import config logger = getLogger("models.mixin") # stores information about a model's columns # and relationships ModelTypes = namedtuple( "ModelTypes", ("primary_keys", "autoincrementing", "columns", "required", "relationships", "mappings")) class ValidatePriorityMixin(object): """ Mixin that adds a `state` column and uses a class level `STATE_ENUM` attribute to assist in validation. """ MIN_PRIORITY = config.get("queue_min_priority") MAX_PRIORITY = config.get("queue_max_priority") if MAX_PRIORITY <= MIN_PRIORITY: raise AssertionError( "`queue_min_priority` must be <= `queue_max_priority`") @validates("priority") def validate_priority(self, key, value): """ensures the value provided to priority is valid""" if value is None or self.MIN_PRIORITY <= value <= self.MAX_PRIORITY: return value err_args = (key, self.MIN_PRIORITY, self.MAX_PRIORITY, value) raise ValueError( "%s must be between %s and %s, got %s instead" % err_args) @validates("attempts") def validate_attempts(self, key, value): """ensures the number of attempts provided is valid""" if value is None or value >= 0: return value raise ValueError("%s cannot be less than zero" % key) class ValidateWorkStateMixin(object): STATE_ENUM = NotImplemented def validate_state(self, key, value): """Ensures that ``value`` is a member of ``STATE_ENUM``""" assert self.STATE_ENUM is not NotImplemented if value not in self.STATE_ENUM: raise ValueError("`%s` is not a valid state" % value) return value @validates("state") def validate_state_column(self, key, value): """validates the state column""" return self.validate_state(key, value) class WorkStateChangedMixin(object): """ Mixin which adds a static method to be used when the model state changes """ @staticmethod def state_changed(target, new_value, old_value, initiator): """update the datetime objects depending on the new value""" if (new_value == _WorkState.RUNNING and (old_value not in [_WorkState.RUNNING, _WorkState.PAUSED] or target.time_started == None)): target.time_started = datetime.utcnow() target.time_finished = None elif new_value in (_WorkState.DONE, _WorkState.FAILED): target.time_finished = datetime.utcnow() class UtilityMixins(object): """ Mixins which can be used to produce dictionaries of existing data. :const dict DICT_CONVERT_COLUMN: A dictionary containing key value pairs of attribute names and a function to retrieve the attribute. The function should take a single input and return the value itself. Optionally, you can also use the ``NotImplemented`` object to exclude some columns from the results. """ DICT_CONVERT_COLUMN = {} def _to_dict_column(self, name): """ Default method used by :meth:`.to_dict` to convert a column to a standard value. """ value = getattr(self, name) if isinstance(value, Values): return value.str elif isinstance(value, IPAddress): return str(value) else: return value def _to_dict_relationship(self, name): """ Default method used by :meth:`.to_dict` to convert a relationship to a standard value. In the event this method does not know how to unpack a relationship it will raise a ``NotImplementedError`` """ relation = getattr(self.__class__, name) relation_object = getattr(self, name) if relation_object is None: return if relation.property.uselist: out = [] for relationship in relation_object: if name == "tags": out.append(relationship.tag) elif name == "projects": out.append(relationship.name) elif name == "software": out.append(relationship.name) elif name == "versions": out.append({"id": relationship.id, "version": relationship.version, "rank": relationship.rank}) elif name == "software_versions": out.append({"id": relationship.id, "software": relationship.software.software, "version": relationship.version, "rank": relationship.rank}) elif name in ("jobs", "agents"): out.append(relationship.id) elif name == "software_requirements": out.append({"software_id": relationship.software_id, "software": relationship.software.software, "min_version_id": relationship.min_version_id, "min_version": (relationship.min_version.version if relationship.min_version else None), "max_version_id": relationship.max_version_id, "max_version": (relationship.max_version.version if relationship.max_version else None)}) elif name in ("tasks", "tasks_queued", "tasks_done", "tasks_failed"): out.append({"id": relationship.id, "frame": relationship.frame, "state": str(relationship.state)}) elif name == "notified_users": out.append({"id": relationship.user_id, "username": relationship.user.username, "email": relationship.user.email, "on_success": relationship.on_success, "on_failure": relationship.on_failure, "on_deletion": relationship.on_deletion}) elif name == "parents": out.append({"id": relationship.id, "title": relationship.title}) elif name == "children": out.append({"id": relationship.id, "title": relationship.title}) elif name == "tag_requirements": out.append({"tag": relationship.tag.tag, "negate": relationship.negate}) elif name == "gpus": out.append({"fullname": relationship.fullname}) elif name == "disks": out.append({"mountpoint": relationship.mountpoint, "size": relationship.size, "free": relationship.free}) else: raise NotImplementedError( "don't know how to unpack relationships for `%s`" % name) else: if name == "software": out = {"software": relation_object.software, "id": relation_object.id} elif name == "jobtype_version": out = {"version": relation_object.version, "jobtype": relation_object.jobtype.name} elif name in ("min_version", "max_version"): out = {"id": relation_object.id, "version": relation_object.version} elif name == "job": out = {"id": relation_object.id, "title": relation_object.title} elif name == "agent": out = {"id": relation_object.id, "hostname": relation_object.hostname, "remote_ip": str(relation_object.remote_ip), "port": relation_object.port} elif name == "parent": out = {"id": relation_object.id, "name": relation_object.name, "priority": relation_object.priority, "weight": relation_object.weight, "maximum_agents": relation_object.maximum_agents, "minimum_agents": relation_object.minimum_agents} elif name == "user": out = relation_object.username elif name == "main_jobtype": out = relation_object.name else: raise NotImplementedError( "don't know how to unpack relationships for `%s`" % name) return out def to_dict(self, unpack_relationships=True): """ Produce a dictionary of existing data in the table :type unpack_relationships: list, tuple, set, bool :param unpack_relationships: If ``True`` then unpack all relationships. If ``unpack_relationships`` is an iterable such as a list or tuple object then only unpack those relationships. """ if not isinstance(self.DICT_CONVERT_COLUMN, dict): raise TypeError( "expected %s.DICT_CONVERT_COLUMN to " "be a dictionary" % self.__class__.__name__) results = {} types = self.types() # first convert all the non-relationship columns for name in types.columns: converter = self.DICT_CONVERT_COLUMN.get( name, self._to_dict_column) if converter is NotImplemented: continue elif not callable(converter): raise TypeError( "converter function for %s was not callable" % name) else: results[name] = converter(name) # unpack all relationships if unpack_relationships is True: relationships = types.relationships # unpack the intersection of the requested relationships # and the real relationships elif isinstance(unpack_relationships, (list, set, tuple)): relationships = set(unpack_relationships) & types.relationships else: relationships = set() for name in relationships: converter = self.DICT_CONVERT_COLUMN.get( name, self._to_dict_relationship) if converter is NotImplemented: continue elif not callable(converter): raise TypeError( "converter function for %s was not callable" % name) else: results[name] = converter(name) return results @classmethod def to_schema(cls): """ Produce a dictionary which represents the table's schema in a basic format """ result = {} for name in cls.types().columns: column = cls.__table__.c[name] try: column.type.python_type except NotImplementedError: result[name] = column.type.__class__.__name__ else: result[name] = str(column.type) return result @classmethod def types(cls): """ A classmethod that constructs a ``namedtuple`` object with four attributes: * primary_keys - set of all primary key(s) names * autoincrementing - set of all columns which have autoincrement set * columns - set of all column names * required - set of all required columns (non-nullable wo/defaults) * relationships - not columns themselves but do store relationships * mappings - contains a dictionary with each field mapping to a Python type """ mapper = class_mapper(cls) primary_keys = set() autoincrementing = set() columns = set() required = set() relationships = set( name for name, column in mapper.relationships.items()) # TODO: it's possible though unlikely, based on our current tables, # that a relationship this could be some other than a list type_mapping = dict((name, list) for name in relationships) # create sets for all true columns, primary keys, # and required columns for name, column in mapper.c.items(): columns.add(name) if column.primary_key: primary_keys.add(name) if column.autoincrement: autoincrementing.add(name) if column.primary_key and not column.autoincrement: required.add(name) if not column.nullable and column.default is None: required.add(name) # get the Python type(s) try: python_types = column.type.python_type except NotImplementedError: # custom type object python_types = column.type.json_types # if we're using Python 2.x be sure that we include # a couple of extra types that could potentially # come in with a request if PY2 and python_types is str: # pylint: disable=undefined-variable python_types = (python_types, unicode) elif PY2 and python_types is int: # pylint: disable=undefined-variable python_types = (python_types, long) type_mapping[name] = python_types return ModelTypes( primary_keys=primary_keys, autoincrementing=autoincrementing, columns=columns, required=required, relationships=relationships, mappings=type_mapping) class ReprMixin(object): """ Mixin which allows model classes to to convert columns into a more easily read object format. :cvar tuple REPR_COLUMNS: the columns to convert :cvar dict REPR_CONVERT_COLUMN: optional dictionary containing columns names and functions for converting to a more readable string format """ REPR_COLUMNS = NotImplemented REPR_CONVERT_COLUMN = {} def __repr__(self): if self.REPR_COLUMNS is NotImplemented: return super(ReprMixin, self).__repr__() column_data = [] for name in self.REPR_COLUMNS: convert = self.REPR_CONVERT_COLUMN.get(name, repr) try: column_data.append( "%s=%s" % (name, convert(getattr(self, name)))) except AttributeError: logger.warning("%s has no such column %s" % ( self.__class__.__name__, repr(name))) return "%s(%s)" % (self.__class__.__name__, ", ".join(column_data))
37.21789
81
0.570038
from datetime import datetime from collections import namedtuple try: from httplib import INTERNAL_SERVER_ERROR except ImportError: from http.client import INTERNAL_SERVER_ERROR from sqlalchemy.orm import validates, class_mapper from pyfarm.core.enums import _WorkState, Values, PY2 from pyfarm.core.logger import getLogger from pyfarm.models.core.types import IPAddress from pyfarm.master.config import config logger = getLogger("models.mixin") # and relationships ModelTypes = namedtuple( "ModelTypes", ("primary_keys", "autoincrementing", "columns", "required", "relationships", "mappings")) class ValidatePriorityMixin(object): MIN_PRIORITY = config.get("queue_min_priority") MAX_PRIORITY = config.get("queue_max_priority") if MAX_PRIORITY <= MIN_PRIORITY: raise AssertionError( "`queue_min_priority` must be <= `queue_max_priority`") @validates("priority") def validate_priority(self, key, value): if value is None or self.MIN_PRIORITY <= value <= self.MAX_PRIORITY: return value err_args = (key, self.MIN_PRIORITY, self.MAX_PRIORITY, value) raise ValueError( "%s must be between %s and %s, got %s instead" % err_args) @validates("attempts") def validate_attempts(self, key, value): if value is None or value >= 0: return value raise ValueError("%s cannot be less than zero" % key) class ValidateWorkStateMixin(object): STATE_ENUM = NotImplemented def validate_state(self, key, value): assert self.STATE_ENUM is not NotImplemented if value not in self.STATE_ENUM: raise ValueError("`%s` is not a valid state" % value) return value @validates("state") def validate_state_column(self, key, value): return self.validate_state(key, value) class WorkStateChangedMixin(object): @staticmethod def state_changed(target, new_value, old_value, initiator): if (new_value == _WorkState.RUNNING and (old_value not in [_WorkState.RUNNING, _WorkState.PAUSED] or target.time_started == None)): target.time_started = datetime.utcnow() target.time_finished = None elif new_value in (_WorkState.DONE, _WorkState.FAILED): target.time_finished = datetime.utcnow() class UtilityMixins(object): DICT_CONVERT_COLUMN = {} def _to_dict_column(self, name): value = getattr(self, name) if isinstance(value, Values): return value.str elif isinstance(value, IPAddress): return str(value) else: return value def _to_dict_relationship(self, name): relation = getattr(self.__class__, name) relation_object = getattr(self, name) if relation_object is None: return if relation.property.uselist: out = [] for relationship in relation_object: if name == "tags": out.append(relationship.tag) elif name == "projects": out.append(relationship.name) elif name == "software": out.append(relationship.name) elif name == "versions": out.append({"id": relationship.id, "version": relationship.version, "rank": relationship.rank}) elif name == "software_versions": out.append({"id": relationship.id, "software": relationship.software.software, "version": relationship.version, "rank": relationship.rank}) elif name in ("jobs", "agents"): out.append(relationship.id) elif name == "software_requirements": out.append({"software_id": relationship.software_id, "software": relationship.software.software, "min_version_id": relationship.min_version_id, "min_version": (relationship.min_version.version if relationship.min_version else None), "max_version_id": relationship.max_version_id, "max_version": (relationship.max_version.version if relationship.max_version else None)}) elif name in ("tasks", "tasks_queued", "tasks_done", "tasks_failed"): out.append({"id": relationship.id, "frame": relationship.frame, "state": str(relationship.state)}) elif name == "notified_users": out.append({"id": relationship.user_id, "username": relationship.user.username, "email": relationship.user.email, "on_success": relationship.on_success, "on_failure": relationship.on_failure, "on_deletion": relationship.on_deletion}) elif name == "parents": out.append({"id": relationship.id, "title": relationship.title}) elif name == "children": out.append({"id": relationship.id, "title": relationship.title}) elif name == "tag_requirements": out.append({"tag": relationship.tag.tag, "negate": relationship.negate}) elif name == "gpus": out.append({"fullname": relationship.fullname}) elif name == "disks": out.append({"mountpoint": relationship.mountpoint, "size": relationship.size, "free": relationship.free}) else: raise NotImplementedError( "don't know how to unpack relationships for `%s`" % name) else: if name == "software": out = {"software": relation_object.software, "id": relation_object.id} elif name == "jobtype_version": out = {"version": relation_object.version, "jobtype": relation_object.jobtype.name} elif name in ("min_version", "max_version"): out = {"id": relation_object.id, "version": relation_object.version} elif name == "job": out = {"id": relation_object.id, "title": relation_object.title} elif name == "agent": out = {"id": relation_object.id, "hostname": relation_object.hostname, "remote_ip": str(relation_object.remote_ip), "port": relation_object.port} elif name == "parent": out = {"id": relation_object.id, "name": relation_object.name, "priority": relation_object.priority, "weight": relation_object.weight, "maximum_agents": relation_object.maximum_agents, "minimum_agents": relation_object.minimum_agents} elif name == "user": out = relation_object.username elif name == "main_jobtype": out = relation_object.name else: raise NotImplementedError( "don't know how to unpack relationships for `%s`" % name) return out def to_dict(self, unpack_relationships=True): if not isinstance(self.DICT_CONVERT_COLUMN, dict): raise TypeError( "expected %s.DICT_CONVERT_COLUMN to " "be a dictionary" % self.__class__.__name__) results = {} types = self.types() # first convert all the non-relationship columns for name in types.columns: converter = self.DICT_CONVERT_COLUMN.get( name, self._to_dict_column) if converter is NotImplemented: continue elif not callable(converter): raise TypeError( "converter function for %s was not callable" % name) else: results[name] = converter(name) # unpack all relationships if unpack_relationships is True: relationships = types.relationships # unpack the intersection of the requested relationships # and the real relationships elif isinstance(unpack_relationships, (list, set, tuple)): relationships = set(unpack_relationships) & types.relationships else: relationships = set() for name in relationships: converter = self.DICT_CONVERT_COLUMN.get( name, self._to_dict_relationship) if converter is NotImplemented: continue elif not callable(converter): raise TypeError( "converter function for %s was not callable" % name) else: results[name] = converter(name) return results @classmethod def to_schema(cls): result = {} for name in cls.types().columns: column = cls.__table__.c[name] try: column.type.python_type except NotImplementedError: result[name] = column.type.__class__.__name__ else: result[name] = str(column.type) return result @classmethod def types(cls): mapper = class_mapper(cls) primary_keys = set() autoincrementing = set() columns = set() required = set() relationships = set( name for name, column in mapper.relationships.items()) # TODO: it's possible though unlikely, based on our current tables, type_mapping = dict((name, list) for name in relationships) for name, column in mapper.c.items(): columns.add(name) if column.primary_key: primary_keys.add(name) if column.autoincrement: autoincrementing.add(name) if column.primary_key and not column.autoincrement: required.add(name) if not column.nullable and column.default is None: required.add(name) try: python_types = column.type.python_type except NotImplementedError: python_types = column.type.json_types # a couple of extra types that could potentially # come in with a request if PY2 and python_types is str: # pylint: disable=undefined-variable python_types = (python_types, unicode) elif PY2 and python_types is int: # pylint: disable=undefined-variable python_types = (python_types, long) type_mapping[name] = python_types return ModelTypes( primary_keys=primary_keys, autoincrementing=autoincrementing, columns=columns, required=required, relationships=relationships, mappings=type_mapping) class ReprMixin(object): REPR_COLUMNS = NotImplemented REPR_CONVERT_COLUMN = {} def __repr__(self): if self.REPR_COLUMNS is NotImplemented: return super(ReprMixin, self).__repr__() column_data = [] for name in self.REPR_COLUMNS: convert = self.REPR_CONVERT_COLUMN.get(name, repr) try: column_data.append( "%s=%s" % (name, convert(getattr(self, name)))) except AttributeError: logger.warning("%s has no such column %s" % ( self.__class__.__name__, repr(name))) return "%s(%s)" % (self.__class__.__name__, ", ".join(column_data))
true
true
f7257517d39b2f8675741bc3a48ae828e67d5468
495
py
Python
src/commercetools/services/abstract.py
labd/commercetools-python-sdk
d8ec285f08d56ede2e4cad45c74833f5b609ab5c
[ "MIT" ]
15
2018-11-02T14:35:52.000Z
2022-03-16T07:51:44.000Z
src/commercetools/services/abstract.py
lime-green/commercetools-python-sdk
63b77f6e5abe43e2b3ebbf3cdbbe00c7cf80dca6
[ "MIT" ]
84
2018-11-02T12:50:32.000Z
2022-03-22T01:25:54.000Z
src/commercetools/services/abstract.py
lime-green/commercetools-python-sdk
63b77f6e5abe43e2b3ebbf3cdbbe00c7cf80dca6
[ "MIT" ]
13
2019-01-03T09:16:50.000Z
2022-02-15T18:37:19.000Z
import typing from marshmallow.base import SchemaABC if typing.TYPE_CHECKING: from commercetools.client import Client class AbstractService: def __init__(self, client: "Client") -> None: self._client = client self._schemas: typing.Dict[str, SchemaABC] = {} def _serialize_params(self, params, schema) -> typing.Dict[str, str]: if schema not in self._schemas: self._schemas[schema] = schema() return self._schemas[schema].dump(params)
27.5
73
0.684848
import typing from marshmallow.base import SchemaABC if typing.TYPE_CHECKING: from commercetools.client import Client class AbstractService: def __init__(self, client: "Client") -> None: self._client = client self._schemas: typing.Dict[str, SchemaABC] = {} def _serialize_params(self, params, schema) -> typing.Dict[str, str]: if schema not in self._schemas: self._schemas[schema] = schema() return self._schemas[schema].dump(params)
true
true
f72576ba10ecc45859e387a54131b2e173076e5e
13,744
py
Python
pinpayments/tests/models.py
branchup/django-pinpayments
e342970c6309facf35b804de9994d326abaa094f
[ "Unlicense" ]
null
null
null
pinpayments/tests/models.py
branchup/django-pinpayments
e342970c6309facf35b804de9994d326abaa094f
[ "Unlicense" ]
null
null
null
pinpayments/tests/models.py
branchup/django-pinpayments
e342970c6309facf35b804de9994d326abaa094f
[ "Unlicense" ]
null
null
null
""" Ensure that the models work as intended """ import json from django.conf import settings from django.contrib.auth.models import User from django.test import TestCase from django.test.utils import override_settings from mock import patch from pinpayments.models import ( ConfigError, CustomerToken, PinError, PinTransaction ) from requests import Response ENV_MISSING_SECRET = { 'test': { 'key': 'key1', 'host': 'test-api.pin.net.au', }, } ENV_MISSING_HOST = { 'test': { 'key': 'key1', 'secret': 'secret1', }, } class FakeResponse(Response): def __init__(self, status_code, content): super(FakeResponse, self).__init__() self.status_code = status_code self._content = content class CustomerTokenTests(TestCase): # Need to override the setting so we can delete it, not sure why. @override_settings(PIN_DEFAULT_ENVIRONMENT=None) def test_default_environment(self): """ Unset PIN_DEFAULT_ENVIRONMENT to test that the environment defaults to 'test'. """ del settings.PIN_DEFAULT_ENVIRONMENT token = CustomerToken() token.user = User.objects.create() token.environment = None token.save() self.assertEqual(token.environment, 'test') class CreateFromCardTokenTests(TestCase): """ Test the creation of customer tokens from card tokens """ def setUp(self): """ Common setup for methods """ super(CreateFromCardTokenTests, self).setUp() self.user = User.objects.create() self.response_data = json.dumps({ 'response': { 'token': '1234', 'email': 'test@example.com', 'created_at': '2012-06-22T06:27:33Z', 'card': { 'token': '54321', 'display_number': 'XXXX-XXXX-XXXX-0000', 'scheme': 'master', 'expiry_month': 6, 'expiry_year': 2017, 'name': 'Roland Robot', 'address_line1': '42 Sevenoaks St', 'address_line2': None, 'address_city': 'Lathlain', 'address_postcode': '6454', 'address_state': 'WA', 'address_country': 'Australia', 'primary': None, } } }) self.response_error = json.dumps({ 'error': 'invalid_resource', 'error_description': 'One or more parameters were missing or invalid.' }) @patch('requests.post') def test_default_environment(self, mock_request): """ return a default environment """ mock_request.return_value = FakeResponse(200, self.response_data) token = CustomerToken.create_from_card_token('1234', self.user) self.assertEqual(token.environment, 'test') @override_settings(PIN_ENVIRONMENTS={}) @patch('requests.post') def test_valid_environment(self, mock_request): """ Check errors are raised with no environments """ mock_request.return_value = FakeResponse(200, self.response_data) with self.assertRaises(ConfigError): CustomerToken.create_from_card_token( '1234', self.user, environment='test' ) @override_settings(PIN_ENVIRONMENTS=ENV_MISSING_SECRET) @patch('requests.post') def test_secret_set(self, mock_request): """ Check errors are raised when the secret is not set """ mock_request.return_value = FakeResponse(200, self.response_data) with self.assertRaises(ConfigError): CustomerToken.create_from_card_token( '1234', self.user, environment='test' ) @override_settings(PIN_ENVIRONMENTS=ENV_MISSING_HOST) @patch('requests.post') def test_host_set(self, mock_request): """ Check errors are raised when the host is not set """ mock_request.return_value = FakeResponse(200, self.response_data) with self.assertRaises(ConfigError): CustomerToken.create_from_card_token( '1234', self.user, environment='test' ) @patch('requests.post') def test_response_not_json(self, mock_request): """ Validate non-json response """ mock_request.return_value = FakeResponse(200, '') with self.assertRaises(PinError): CustomerToken.create_from_card_token( '1234', self.user, environment='test' ) @patch('requests.post') def test_response_error(self, mock_request): """ Validate generic error response """ mock_request.return_value = FakeResponse(200, self.response_error) with self.assertRaises(PinError): CustomerToken.create_from_card_token( '1234', self.user, environment='test' ) @patch('requests.post') def test_response_success(self, mock_request): """ Validate successful response """ mock_request.return_value = FakeResponse(200, self.response_data) customer = CustomerToken.create_from_card_token( '1234', self.user, environment='test' ) self.assertIsInstance(customer, CustomerToken) self.assertEqual(customer.user, self.user) self.assertEqual(customer.token, '1234') self.assertEqual(customer.environment, 'test') self.assertEqual(customer.card_number, 'XXXX-XXXX-XXXX-0000') self.assertEqual(customer.card_type, 'master') class PinTransactionTests(TestCase): """ Transaction construction/init related tests """ def setUp(self): """ Common setup for methods """ super(PinTransactionTests, self).setUp() self.transaction = PinTransaction() self.transaction.card_token = '12345' self.transaction.ip_address = '127.0.0.1' self.transaction.amount = 500 self.transaction.currency = 'AUD' self.transaction.email_address = 'test@example.com' self.transaction.environment = 'test' # Need to override the setting so we can delete it, not sure why. @override_settings(PIN_DEFAULT_ENVIRONMENT=None) def test_save_defaults(self): """ Unset PIN_DEFAULT_ENVIRONMENT to test that the environment defaults to 'test'. """ del settings.PIN_DEFAULT_ENVIRONMENT self.transaction.environment = None self.transaction.save() self.assertEqual(self.transaction.environment, 'test') self.assertTrue(self.transaction.date) def test_save_notokens(self): """ Check that an error is thrown if neither card nor customer token are provided to the transaction """ self.transaction.card_token = None self.transaction.customer_token = None self.assertRaises(PinError, self.transaction.save) def test_valid_environment(self): """ Check that errors are thrown when a fake environment is requested """ self.transaction.environment = 'this should not exist' self.assertRaises(PinError, self.transaction.save) class ProcessTransactionsTests(TestCase): """ Transaction processing related tests """ def setUp(self): """ Common setup for methods """ super(ProcessTransactionsTests, self).setUp() self.transaction = PinTransaction() self.transaction.card_token = '12345' self.transaction.ip_address = '127.0.0.1' self.transaction.amount = 500 self.transaction.currency = 'AUD' self.transaction.email_address = 'test@example.com' self.transaction.environment = 'test' self.transaction.save() self.response_data = json.dumps({ 'response': { 'token': '12345', 'success': True, 'amount': 500, 'total_fees': 500, 'currency': 'AUD', 'description': 'test charge', 'email': 'test@example.com', 'ip_address': '127.0.0.1', 'created_at': '2012-06-20T03:10:49Z', 'status_message': 'Success!', 'error_message': None, 'card': { 'token': 'card_nytGw7koRg23EEp9NTmz9w', 'display_number': 'XXXX-XXXX-XXXX-0000', 'scheme': 'master', 'expiry_month': 6, 'expiry_year': 2017, 'name': 'Roland Robot', 'address_line1': '42 Sevenoaks St', 'address_line2': None, 'address_city': 'Lathlain', 'address_postcode': '6454', 'address_state': 'WA', 'address_country': 'Australia', 'primary': None, }, 'transfer': None } }) self.response_error = json.dumps({ 'error': 'invalid_resource', 'error_description': 'One or more parameters were missing or invalid.', # Should there really be a charge token? 'charge_token': '1234', 'messages': [{ 'code': 'description_invalid', 'message': 'Description can\'t be blank', 'param': 'description' }] }) self.response_error_no_messages = json.dumps({ 'error': 'invalid_resource', 'error_description': 'One or more parameters were missing or invalid.', # Should there really be a charge token? 'charge_token': '1234' }) @patch('requests.post') def test_only_process_once(self, mock_request): """ Check that transactions are processed exactly once """ mock_request.return_value = FakeResponse(200, self.response_data) # Shouldn't be marked as processed before process_transaction is called # for the first time. self.assertFalse(self.transaction.processed) # Should be marked after the first call. result = self.transaction.process_transaction() self.assertTrue(self.transaction.processed) # Shouldn't process anything the second time result = self.transaction.process_transaction() self.assertIsNone(result) @override_settings(PIN_ENVIRONMENTS={}) @patch('requests.post') def test_valid_environment(self, mock_request): """ Check that an error is thrown with no environment """ mock_request.return_value = FakeResponse(200, self.response_data) self.assertRaises(PinError, self.transaction.process_transaction) @override_settings(PIN_ENVIRONMENTS=ENV_MISSING_SECRET) @patch('requests.post') def test_secret_set(self, mock_request): """ Check that an error is thrown with no secret """ mock_request.return_value = FakeResponse(200, self.response_data) self.assertRaises(ConfigError, self.transaction.process_transaction) @override_settings(PIN_ENVIRONMENTS=ENV_MISSING_HOST) @patch('requests.post') def test_host_set(self, mock_request): """ Check that an error is thrown with no host """ mock_request.return_value = FakeResponse(200, self.response_data) self.assertRaises(ConfigError, self.transaction.process_transaction) @patch('requests.post') def test_response_not_json(self, mock_request): """ Check that failure is returned for non-JSON responses """ mock_request.return_value = FakeResponse(200, '') response = self.transaction.process_transaction() self.assertEqual(response, 'Failure.') @patch('requests.post') def test_response_badparam(self, mock_request): """ Check that a specific error is thrown for invalid parameters """ mock_request.return_value = FakeResponse(200, self.response_error) response = self.transaction.process_transaction() self.assertEqual(response, 'Failure: Description can\'t be blank') @patch('requests.post') def test_response_noparam(self, mock_request): """ Check that a specific error is thrown for missing parameters """ mock_request.return_value = FakeResponse( 200, self.response_error_no_messages ) response = self.transaction.process_transaction() self.assertEqual( response, 'Failure: One or more parameters were missing or invalid.' ) @patch('requests.post') def test_response_success(self, mock_request): """ Check that the success response is correctly processed """ mock_request.return_value = FakeResponse(200, self.response_data) response = self.transaction.process_transaction() self.assertEqual(response, 'Success!') self.assertTrue(self.transaction.succeeded) self.assertEqual(self.transaction.transaction_token, '12345') self.assertEqual(self.transaction.fees, 5.0) self.assertEqual(self.transaction.pin_response, 'Success!') self.assertEqual(self.transaction.card_address1, '42 Sevenoaks St') self.assertIsNone(self.transaction.card_address2) self.assertEqual(self.transaction.card_city, 'Lathlain') self.assertEqual(self.transaction.card_state, 'WA') self.assertEqual(self.transaction.card_postcode, '6454') self.assertEqual(self.transaction.card_country, 'Australia') self.assertEqual(self.transaction.card_number, 'XXXX-XXXX-XXXX-0000') self.assertEqual(self.transaction.card_type, 'master')
39.608069
79
0.621799
import json from django.conf import settings from django.contrib.auth.models import User from django.test import TestCase from django.test.utils import override_settings from mock import patch from pinpayments.models import ( ConfigError, CustomerToken, PinError, PinTransaction ) from requests import Response ENV_MISSING_SECRET = { 'test': { 'key': 'key1', 'host': 'test-api.pin.net.au', }, } ENV_MISSING_HOST = { 'test': { 'key': 'key1', 'secret': 'secret1', }, } class FakeResponse(Response): def __init__(self, status_code, content): super(FakeResponse, self).__init__() self.status_code = status_code self._content = content class CustomerTokenTests(TestCase): @override_settings(PIN_DEFAULT_ENVIRONMENT=None) def test_default_environment(self): del settings.PIN_DEFAULT_ENVIRONMENT token = CustomerToken() token.user = User.objects.create() token.environment = None token.save() self.assertEqual(token.environment, 'test') class CreateFromCardTokenTests(TestCase): def setUp(self): super(CreateFromCardTokenTests, self).setUp() self.user = User.objects.create() self.response_data = json.dumps({ 'response': { 'token': '1234', 'email': 'test@example.com', 'created_at': '2012-06-22T06:27:33Z', 'card': { 'token': '54321', 'display_number': 'XXXX-XXXX-XXXX-0000', 'scheme': 'master', 'expiry_month': 6, 'expiry_year': 2017, 'name': 'Roland Robot', 'address_line1': '42 Sevenoaks St', 'address_line2': None, 'address_city': 'Lathlain', 'address_postcode': '6454', 'address_state': 'WA', 'address_country': 'Australia', 'primary': None, } } }) self.response_error = json.dumps({ 'error': 'invalid_resource', 'error_description': 'One or more parameters were missing or invalid.' }) @patch('requests.post') def test_default_environment(self, mock_request): mock_request.return_value = FakeResponse(200, self.response_data) token = CustomerToken.create_from_card_token('1234', self.user) self.assertEqual(token.environment, 'test') @override_settings(PIN_ENVIRONMENTS={}) @patch('requests.post') def test_valid_environment(self, mock_request): mock_request.return_value = FakeResponse(200, self.response_data) with self.assertRaises(ConfigError): CustomerToken.create_from_card_token( '1234', self.user, environment='test' ) @override_settings(PIN_ENVIRONMENTS=ENV_MISSING_SECRET) @patch('requests.post') def test_secret_set(self, mock_request): mock_request.return_value = FakeResponse(200, self.response_data) with self.assertRaises(ConfigError): CustomerToken.create_from_card_token( '1234', self.user, environment='test' ) @override_settings(PIN_ENVIRONMENTS=ENV_MISSING_HOST) @patch('requests.post') def test_host_set(self, mock_request): mock_request.return_value = FakeResponse(200, self.response_data) with self.assertRaises(ConfigError): CustomerToken.create_from_card_token( '1234', self.user, environment='test' ) @patch('requests.post') def test_response_not_json(self, mock_request): mock_request.return_value = FakeResponse(200, '') with self.assertRaises(PinError): CustomerToken.create_from_card_token( '1234', self.user, environment='test' ) @patch('requests.post') def test_response_error(self, mock_request): mock_request.return_value = FakeResponse(200, self.response_error) with self.assertRaises(PinError): CustomerToken.create_from_card_token( '1234', self.user, environment='test' ) @patch('requests.post') def test_response_success(self, mock_request): mock_request.return_value = FakeResponse(200, self.response_data) customer = CustomerToken.create_from_card_token( '1234', self.user, environment='test' ) self.assertIsInstance(customer, CustomerToken) self.assertEqual(customer.user, self.user) self.assertEqual(customer.token, '1234') self.assertEqual(customer.environment, 'test') self.assertEqual(customer.card_number, 'XXXX-XXXX-XXXX-0000') self.assertEqual(customer.card_type, 'master') class PinTransactionTests(TestCase): def setUp(self): super(PinTransactionTests, self).setUp() self.transaction = PinTransaction() self.transaction.card_token = '12345' self.transaction.ip_address = '127.0.0.1' self.transaction.amount = 500 self.transaction.currency = 'AUD' self.transaction.email_address = 'test@example.com' self.transaction.environment = 'test' @override_settings(PIN_DEFAULT_ENVIRONMENT=None) def test_save_defaults(self): del settings.PIN_DEFAULT_ENVIRONMENT self.transaction.environment = None self.transaction.save() self.assertEqual(self.transaction.environment, 'test') self.assertTrue(self.transaction.date) def test_save_notokens(self): self.transaction.card_token = None self.transaction.customer_token = None self.assertRaises(PinError, self.transaction.save) def test_valid_environment(self): self.transaction.environment = 'this should not exist' self.assertRaises(PinError, self.transaction.save) class ProcessTransactionsTests(TestCase): def setUp(self): super(ProcessTransactionsTests, self).setUp() self.transaction = PinTransaction() self.transaction.card_token = '12345' self.transaction.ip_address = '127.0.0.1' self.transaction.amount = 500 self.transaction.currency = 'AUD' self.transaction.email_address = 'test@example.com' self.transaction.environment = 'test' self.transaction.save() self.response_data = json.dumps({ 'response': { 'token': '12345', 'success': True, 'amount': 500, 'total_fees': 500, 'currency': 'AUD', 'description': 'test charge', 'email': 'test@example.com', 'ip_address': '127.0.0.1', 'created_at': '2012-06-20T03:10:49Z', 'status_message': 'Success!', 'error_message': None, 'card': { 'token': 'card_nytGw7koRg23EEp9NTmz9w', 'display_number': 'XXXX-XXXX-XXXX-0000', 'scheme': 'master', 'expiry_month': 6, 'expiry_year': 2017, 'name': 'Roland Robot', 'address_line1': '42 Sevenoaks St', 'address_line2': None, 'address_city': 'Lathlain', 'address_postcode': '6454', 'address_state': 'WA', 'address_country': 'Australia', 'primary': None, }, 'transfer': None } }) self.response_error = json.dumps({ 'error': 'invalid_resource', 'error_description': 'One or more parameters were missing or invalid.', 'charge_token': '1234', 'messages': [{ 'code': 'description_invalid', 'message': 'Description can\'t be blank', 'param': 'description' }] }) self.response_error_no_messages = json.dumps({ 'error': 'invalid_resource', 'error_description': 'One or more parameters were missing or invalid.', # Should there really be a charge token? 'charge_token': '1234' }) @patch('requests.post') def test_only_process_once(self, mock_request): mock_request.return_value = FakeResponse(200, self.response_data) # Shouldn't be marked as processed before process_transaction is called self.assertFalse(self.transaction.processed) result = self.transaction.process_transaction() self.assertTrue(self.transaction.processed) result = self.transaction.process_transaction() self.assertIsNone(result) @override_settings(PIN_ENVIRONMENTS={}) @patch('requests.post') def test_valid_environment(self, mock_request): mock_request.return_value = FakeResponse(200, self.response_data) self.assertRaises(PinError, self.transaction.process_transaction) @override_settings(PIN_ENVIRONMENTS=ENV_MISSING_SECRET) @patch('requests.post') def test_secret_set(self, mock_request): mock_request.return_value = FakeResponse(200, self.response_data) self.assertRaises(ConfigError, self.transaction.process_transaction) @override_settings(PIN_ENVIRONMENTS=ENV_MISSING_HOST) @patch('requests.post') def test_host_set(self, mock_request): mock_request.return_value = FakeResponse(200, self.response_data) self.assertRaises(ConfigError, self.transaction.process_transaction) @patch('requests.post') def test_response_not_json(self, mock_request): mock_request.return_value = FakeResponse(200, '') response = self.transaction.process_transaction() self.assertEqual(response, 'Failure.') @patch('requests.post') def test_response_badparam(self, mock_request): mock_request.return_value = FakeResponse(200, self.response_error) response = self.transaction.process_transaction() self.assertEqual(response, 'Failure: Description can\'t be blank') @patch('requests.post') def test_response_noparam(self, mock_request): mock_request.return_value = FakeResponse( 200, self.response_error_no_messages ) response = self.transaction.process_transaction() self.assertEqual( response, 'Failure: One or more parameters were missing or invalid.' ) @patch('requests.post') def test_response_success(self, mock_request): mock_request.return_value = FakeResponse(200, self.response_data) response = self.transaction.process_transaction() self.assertEqual(response, 'Success!') self.assertTrue(self.transaction.succeeded) self.assertEqual(self.transaction.transaction_token, '12345') self.assertEqual(self.transaction.fees, 5.0) self.assertEqual(self.transaction.pin_response, 'Success!') self.assertEqual(self.transaction.card_address1, '42 Sevenoaks St') self.assertIsNone(self.transaction.card_address2) self.assertEqual(self.transaction.card_city, 'Lathlain') self.assertEqual(self.transaction.card_state, 'WA') self.assertEqual(self.transaction.card_postcode, '6454') self.assertEqual(self.transaction.card_country, 'Australia') self.assertEqual(self.transaction.card_number, 'XXXX-XXXX-XXXX-0000') self.assertEqual(self.transaction.card_type, 'master')
true
true
f72576c2d1acd4d4c339871d110e259e22d8e73b
13,114
py
Python
sdk/python/pulumi_azure_native/network/v20200501/express_route_circuit_authorization.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure_native/network/v20200501/express_route_circuit_authorization.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure_native/network/v20200501/express_route_circuit_authorization.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from ._enums import * __all__ = ['ExpressRouteCircuitAuthorization'] class ExpressRouteCircuitAuthorization(pulumi.CustomResource): def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, authorization_key: Optional[pulumi.Input[str]] = None, authorization_name: Optional[pulumi.Input[str]] = None, authorization_use_status: Optional[pulumi.Input[Union[str, 'AuthorizationUseStatus']]] = None, circuit_name: Optional[pulumi.Input[str]] = None, id: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, __props__=None, __name__=None, __opts__=None): """ Authorization in an ExpressRouteCircuit resource. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] authorization_key: The authorization key. :param pulumi.Input[str] authorization_name: The name of the authorization. :param pulumi.Input[Union[str, 'AuthorizationUseStatus']] authorization_use_status: The authorization use status. :param pulumi.Input[str] circuit_name: The name of the express route circuit. :param pulumi.Input[str] id: Resource ID. :param pulumi.Input[str] name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :param pulumi.Input[str] resource_group_name: The name of the resource group. """ if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['authorization_key'] = authorization_key __props__['authorization_name'] = authorization_name __props__['authorization_use_status'] = authorization_use_status if circuit_name is None and not opts.urn: raise TypeError("Missing required property 'circuit_name'") __props__['circuit_name'] = circuit_name __props__['id'] = id __props__['name'] = name if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__['resource_group_name'] = resource_group_name __props__['etag'] = None __props__['provisioning_state'] = None __props__['type'] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:network/v20200501:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/latest:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/latest:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20150501preview:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20150501preview:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20150615:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20150615:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20160330:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20160330:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20160601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20160601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20160901:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20160901:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20161201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20161201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20170301:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20170301:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20170601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20170601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20170801:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20170801:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20170901:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20170901:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20171001:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20171001:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20171101:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20171101:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20180101:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20180101:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20180201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20180201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20180401:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20180401:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20180601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20180601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20180701:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20180701:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20180801:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20180801:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20181001:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20181001:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20181101:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20181101:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20181201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20181201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20190201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20190201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20190401:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20190401:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20190601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20190601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20190701:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20190701:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20190801:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20190801:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20190901:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20190901:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20191101:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20191101:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20191201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20191201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20200301:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20200301:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20200401:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20200401:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20200601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20200601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20200701:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20200701:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20200801:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20200801:ExpressRouteCircuitAuthorization")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(ExpressRouteCircuitAuthorization, __self__).__init__( 'azure-native:network/v20200501:ExpressRouteCircuitAuthorization', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'ExpressRouteCircuitAuthorization': """ Get an existing ExpressRouteCircuitAuthorization resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() __props__["authorization_key"] = None __props__["authorization_use_status"] = None __props__["etag"] = None __props__["name"] = None __props__["provisioning_state"] = None __props__["type"] = None return ExpressRouteCircuitAuthorization(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="authorizationKey") def authorization_key(self) -> pulumi.Output[Optional[str]]: """ The authorization key. """ return pulumi.get(self, "authorization_key") @property @pulumi.getter(name="authorizationUseStatus") def authorization_use_status(self) -> pulumi.Output[Optional[str]]: """ The authorization use status. """ return pulumi.get(self, "authorization_use_status") @property @pulumi.getter def etag(self) -> pulumi.Output[str]: """ A unique read-only string that changes whenever the resource is updated. """ return pulumi.get(self, "etag") @property @pulumi.getter def name(self) -> pulumi.Output[Optional[str]]: """ The name of the resource that is unique within a resource group. This name can be used to access the resource. """ return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> pulumi.Output[str]: """ The provisioning state of the authorization resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ Type of the resource. """ return pulumi.get(self, "type") def translate_output_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop def translate_input_property(self, prop): return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
82.477987
6,429
0.753317
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from ._enums import * __all__ = ['ExpressRouteCircuitAuthorization'] class ExpressRouteCircuitAuthorization(pulumi.CustomResource): def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, authorization_key: Optional[pulumi.Input[str]] = None, authorization_name: Optional[pulumi.Input[str]] = None, authorization_use_status: Optional[pulumi.Input[Union[str, 'AuthorizationUseStatus']]] = None, circuit_name: Optional[pulumi.Input[str]] = None, id: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, __props__=None, __name__=None, __opts__=None): if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['authorization_key'] = authorization_key __props__['authorization_name'] = authorization_name __props__['authorization_use_status'] = authorization_use_status if circuit_name is None and not opts.urn: raise TypeError("Missing required property 'circuit_name'") __props__['circuit_name'] = circuit_name __props__['id'] = id __props__['name'] = name if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__['resource_group_name'] = resource_group_name __props__['etag'] = None __props__['provisioning_state'] = None __props__['type'] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:network/v20200501:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/latest:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/latest:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20150501preview:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20150501preview:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20150615:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20150615:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20160330:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20160330:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20160601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20160601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20160901:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20160901:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20161201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20161201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20170301:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20170301:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20170601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20170601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20170801:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20170801:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20170901:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20170901:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20171001:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20171001:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20171101:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20171101:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20180101:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20180101:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20180201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20180201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20180401:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20180401:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20180601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20180601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20180701:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20180701:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20180801:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20180801:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20181001:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20181001:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20181101:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20181101:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20181201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20181201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20190201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20190201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20190401:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20190401:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20190601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20190601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20190701:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20190701:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20190801:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20190801:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20190901:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20190901:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20191101:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20191101:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20191201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20191201:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20200301:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20200301:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20200401:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20200401:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20200601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20200601:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20200701:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20200701:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-native:network/v20200801:ExpressRouteCircuitAuthorization"), pulumi.Alias(type_="azure-nextgen:network/v20200801:ExpressRouteCircuitAuthorization")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(ExpressRouteCircuitAuthorization, __self__).__init__( 'azure-native:network/v20200501:ExpressRouteCircuitAuthorization', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'ExpressRouteCircuitAuthorization': opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() __props__["authorization_key"] = None __props__["authorization_use_status"] = None __props__["etag"] = None __props__["name"] = None __props__["provisioning_state"] = None __props__["type"] = None return ExpressRouteCircuitAuthorization(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="authorizationKey") def authorization_key(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "authorization_key") @property @pulumi.getter(name="authorizationUseStatus") def authorization_use_status(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "authorization_use_status") @property @pulumi.getter def etag(self) -> pulumi.Output[str]: return pulumi.get(self, "etag") @property @pulumi.getter def name(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "name") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> pulumi.Output[str]: return pulumi.get(self, "provisioning_state") @property @pulumi.getter def type(self) -> pulumi.Output[str]: return pulumi.get(self, "type") def translate_output_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop def translate_input_property(self, prop): return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
true
true
f725772c43f53c9873559775e2e56aabd5ec8fda
13,185
py
Python
aps/loader/simu.py
LvHang/aps
3e9c8b247e0526481970c28e8af1a6a93cc7f2cc
[ "Apache-2.0" ]
5
2021-07-05T12:21:44.000Z
2021-11-23T08:09:45.000Z
aps/loader/simu.py
LvHang/aps
3e9c8b247e0526481970c28e8af1a6a93cc7f2cc
[ "Apache-2.0" ]
null
null
null
aps/loader/simu.py
LvHang/aps
3e9c8b247e0526481970c28e8af1a6a93cc7f2cc
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # Copyright 2020 Jian Wu # License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """ Adopt from my another project: https://github.com/funcwj/setk See https://github.com/funcwj/setk/tree/master/doc/data_simu for command line usage """ import argparse import numpy as np from aps.loader.audio import read_audio, add_room_response from aps.opts import StrToBoolAction from aps.const import EPSILON def coeff_snr(sig_pow, ref_pow, snr): """ For mix = Sa + alpha*Sb Given SNR = 10*log10[Pa/(Pb * alpha^2)] we got alpha = Pa/[Pb*10^(SNR/10)]^0.5 """ return (ref_pow / (sig_pow * 10**(snr / 10) + EPSILON))**0.5 def add_speaker(mix_nsamps, src_spk, src_begin, sdr, src_rir=None, channel=-1, sr=16000): """ Mix source speakers """ spk_image, spk_power = [], [] for i, spk in enumerate(src_spk): if src_rir is None: src = spk[None, ...] if spk.ndim == 1 else spk spk_image.append(src) spk_power.append(np.mean(src[0]**2)) else: rir = src_rir[i] if rir.ndim == 1: rir = rir[None, ...] if channel >= 0: if rir.ndim == 2: rir = rir[channel:channel + 1] revb, p = add_room_response(spk, rir, sr=sr) spk_image.append(revb) spk_power.append(p) # make mix N, _ = spk_image[0].shape mix = [np.zeros([N, mix_nsamps], dtype=np.float32) for _ in src_spk] # start mixing ref_power = spk_power[0] for i, image in enumerate(spk_image): dur = image.shape[-1] beg = src_begin[i] coeff = 1 if i == 0 else coeff_snr(spk_power[i], ref_power, sdr[i]) mix[i][..., beg:beg + dur] += coeff * image return mix def add_point_noise(mix_nsamps, ref_power, noise, noise_begin, snr, noise_rir=None, channel=-1, repeat=False, sr=16000): """ Add pointsource noises """ image = [] image_power = [] for i, noise in enumerate(noise): beg = noise_begin[i] if not repeat: dur = min(noise.shape[-1], mix_nsamps - beg) else: dur = mix_nsamps - beg # if short, then padding if noise.shape[-1] < dur: noise = np.pad(noise, (0, dur - noise.shape[-1]), mode="wrap") if noise_rir is None: src = noise[None, ...] if noise.ndim == 1 else noise image.append(src) image_power.append(np.mean(src[0, :dur]**2) if dur > 0 else 0) else: rir = noise_rir[i] if rir.ndim == 1: rir = rir[None, ...] if channel >= 0: if rir.ndim == 2: rir = rir[channel:channel + 1] revb, revb_power = add_room_response(noise[:dur], rir, sr=sr) image.append(revb) image_power.append(revb_power) # make noise mix N, _ = image[0].shape mix = np.zeros([N, mix_nsamps], dtype=np.float32) # start mixing for i, img in enumerate(image): beg = noise_begin[i] coeff = coeff_snr(image_power[i], ref_power, snr[i]) mix[..., beg:beg + dur] += coeff * img[..., :dur] return mix def load_audio(src_args, beg=None, end=None, sr=16000): """ Load audio from args.xxx """ if src_args: src_path = src_args.split(",") beg_int = [None for _ in src_path] end_int = [None for _ in src_path] if beg: beg_int = [int(v) for v in beg.split(",")] if end: end_int = [int(v) for v in end.split(",")] return [ read_audio(s, sr=sr, beg=b, end=e) for s, b, e in zip(src_path, beg_int, end_int) ] else: return None def run_simu(args): def arg_float(src_args): return [float(s) for s in src_args.split(",")] if src_args else None src_spk = load_audio(args.src_spk, sr=args.sr) src_rir = load_audio(args.src_rir, sr=args.sr) if src_rir: if len(src_rir) != len(src_spk): raise RuntimeError( f"Number of --src-rir={args.src_rir} do not match with " + f"--src-spk={args.src_spk} option") sdr = arg_float(args.src_sdr) if len(src_spk) > 1 and not sdr: raise RuntimeError("--src-sdr need to be assigned for " + f"--src-spk={args.src_spk}") if sdr: if len(src_spk) - 1 != len(sdr): raise RuntimeError("Number of --src-snr - 1 do not match with " + "--src-snr option") sdr = [0] + sdr src_begin = arg_float(args.src_begin) if src_begin: src_begin = [int(v) for v in src_begin] else: src_begin = [0 for _ in src_spk] # number samples of the mixture mix_nsamps = max([b + s.size for b, s in zip(src_begin, src_spk)]) point_noise_rir = load_audio(args.point_noise_rir, sr=args.sr) point_noise_end = [ str(int(v) + mix_nsamps) for v in args.point_noise_offset.split() ] point_noise = load_audio(args.point_noise, beg=args.point_noise_offset, end=",".join(point_noise_end), sr=args.sr) if args.point_noise: if point_noise_rir: if len(point_noise) != len(point_noise_rir): raise RuntimeError( f"Number of --point-noise-rir={args.point_noise_rir} do not match with " + f"--point-noise={args.point_noise} option") point_snr = arg_float(args.point_noise_snr) if not point_snr: raise RuntimeError("--point-noise-snr need to be assigned for " + f"--point-noise={args.point_noise}") if len(point_noise) != len(point_snr): raise RuntimeError( f"Number of --point-noise-snr={args.point_noise_snr} do not match with " + f"--point-noise={args.point_noise} option") point_begin = arg_float(args.point_noise_begin) if point_begin: point_begin = [int(v) for v in point_begin] else: point_begin = [0 for _ in point_noise] isotropic_noise = load_audio(args.isotropic_noise, beg=str(args.isotropic_noise_offset), end=str(args.isotropic_noise_offset + mix_nsamps), sr=args.sr) if isotropic_noise: isotropic_noise = isotropic_noise[0] isotropic_snr = arg_float(args.isotropic_noise_snr) if not isotropic_snr: raise RuntimeError( "--isotropic-snr need to be assigned for " + f"--isotropic-noise={args.isotropic_noise} option") isotropic_snr = isotropic_snr[0] else: isotropic_snr = None # add speakers spk = add_speaker(mix_nsamps, src_spk, src_begin, sdr, src_rir=src_rir, channel=args.dump_channel, sr=args.sr) spk_utt = sum(spk) mix = spk_utt.copy() spk_power = np.mean(spk_utt[0]**2) if point_noise: noise = add_point_noise(mix_nsamps, spk_power, point_noise, point_begin, point_snr, noise_rir=point_noise_rir, channel=args.dump_channel, repeat=args.point_noise_repeat, sr=args.sr) num_channels = spk_utt.shape[0] if num_channels != noise.shape[0]: if num_channels == 1: noise = noise[0:1] else: raise RuntimeError("Channel mismatch between source speaker " + "configuration and pointsource noise's, " + f"{num_channels} vs {noise.shape[0]}") mix = spk_utt + noise else: noise = None ch = args.dump_channel if isotropic_noise is not None: N, _ = spk_utt.shape if N == 1: if isotropic_noise.ndim == 1: isotropic_noise = isotropic_noise[None, ...] else: if ch >= 0: isotropic_noise = isotropic_noise[ch:ch + 1] else: raise RuntimeError( "Single channel mixture vs multi-channel " "isotropic noise") else: if isotropic_noise.shape[0] != N: raise RuntimeError( "Channel number mismatch between mixture and isotropic noise, " + f"{N} vs {isotropic_noise.shape[0]}") dur = min(mix_nsamps, isotropic_noise.shape[-1]) isotropic_chunk = isotropic_noise[0, :dur] power = np.mean(isotropic_chunk**2) coeff = coeff_snr(power, spk_power, isotropic_snr) mix[..., :dur] += coeff * isotropic_chunk if noise is None: noise = coeff * isotropic_chunk else: noise[..., :dur] += coeff * isotropic_chunk factor = args.norm_factor / (np.max(np.abs(mix)) + EPSILON) mix = mix.squeeze() * factor spk = [s[0] * factor for s in spk] if noise is None: return mix, spk, None else: return mix, spk, noise[0] * factor def make_argparse(): parser = argparse.ArgumentParser( description="Command to do audio data simulation", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--src-spk", type=str, required=True, help="Source speakers, e.g., spk1.wav,spk2.wav") parser.add_argument("--src-rir", type=str, default="", help="RIRs for each source speakers") parser.add_argument("--src-sdr", type=str, default="", help="SDR for each speakers (if needed)") parser.add_argument("--src-begin", type=str, default="", help="Begining samples on the mixture utterances") parser.add_argument("--point-noise", type=str, default="", help="Add pointsource noises") parser.add_argument("--point-noise-rir", type=str, default="", help="RIRs of the pointsource noises (if needed)") parser.add_argument("--point-noise-snr", type=str, default="", help="SNR of the pointsource noises") parser.add_argument("--point-noise-begin", type=str, default="", help="Begining samples of the " "pointsource noises on the mixture " "utterances (if needed)") parser.add_argument("--point-noise-offset", type=str, default="", help="Add from the offset position " "of the pointsource noise") parser.add_argument("--point-noise-repeat", action=StrToBoolAction, default=False, help="Repeat the pointsource noise or not") parser.add_argument("--isotropic-noise", type=str, default="", help="Add isotropic noises") parser.add_argument("--isotropic-noise-snr", type=str, default="", help="SNR of the isotropic noises") parser.add_argument("--isotropic-noise-offset", type=int, default=0, help="Add noise from the offset position " "of the isotropic noise") parser.add_argument("--dump-channel", type=int, default=-1, help="Index of the channel to dump out (-1 means all)") parser.add_argument('--norm-factor', type=float, default=0.9, help="Normalization factor of the final output") parser.add_argument("--sr", type=int, default=16000, help="Value of the sample rate") return parser
36.222527
92
0.498597
import argparse import numpy as np from aps.loader.audio import read_audio, add_room_response from aps.opts import StrToBoolAction from aps.const import EPSILON def coeff_snr(sig_pow, ref_pow, snr): return (ref_pow / (sig_pow * 10**(snr / 10) + EPSILON))**0.5 def add_speaker(mix_nsamps, src_spk, src_begin, sdr, src_rir=None, channel=-1, sr=16000): spk_image, spk_power = [], [] for i, spk in enumerate(src_spk): if src_rir is None: src = spk[None, ...] if spk.ndim == 1 else spk spk_image.append(src) spk_power.append(np.mean(src[0]**2)) else: rir = src_rir[i] if rir.ndim == 1: rir = rir[None, ...] if channel >= 0: if rir.ndim == 2: rir = rir[channel:channel + 1] revb, p = add_room_response(spk, rir, sr=sr) spk_image.append(revb) spk_power.append(p) N, _ = spk_image[0].shape mix = [np.zeros([N, mix_nsamps], dtype=np.float32) for _ in src_spk] ref_power = spk_power[0] for i, image in enumerate(spk_image): dur = image.shape[-1] beg = src_begin[i] coeff = 1 if i == 0 else coeff_snr(spk_power[i], ref_power, sdr[i]) mix[i][..., beg:beg + dur] += coeff * image return mix def add_point_noise(mix_nsamps, ref_power, noise, noise_begin, snr, noise_rir=None, channel=-1, repeat=False, sr=16000): image = [] image_power = [] for i, noise in enumerate(noise): beg = noise_begin[i] if not repeat: dur = min(noise.shape[-1], mix_nsamps - beg) else: dur = mix_nsamps - beg if noise.shape[-1] < dur: noise = np.pad(noise, (0, dur - noise.shape[-1]), mode="wrap") if noise_rir is None: src = noise[None, ...] if noise.ndim == 1 else noise image.append(src) image_power.append(np.mean(src[0, :dur]**2) if dur > 0 else 0) else: rir = noise_rir[i] if rir.ndim == 1: rir = rir[None, ...] if channel >= 0: if rir.ndim == 2: rir = rir[channel:channel + 1] revb, revb_power = add_room_response(noise[:dur], rir, sr=sr) image.append(revb) image_power.append(revb_power) N, _ = image[0].shape mix = np.zeros([N, mix_nsamps], dtype=np.float32) for i, img in enumerate(image): beg = noise_begin[i] coeff = coeff_snr(image_power[i], ref_power, snr[i]) mix[..., beg:beg + dur] += coeff * img[..., :dur] return mix def load_audio(src_args, beg=None, end=None, sr=16000): if src_args: src_path = src_args.split(",") beg_int = [None for _ in src_path] end_int = [None for _ in src_path] if beg: beg_int = [int(v) for v in beg.split(",")] if end: end_int = [int(v) for v in end.split(",")] return [ read_audio(s, sr=sr, beg=b, end=e) for s, b, e in zip(src_path, beg_int, end_int) ] else: return None def run_simu(args): def arg_float(src_args): return [float(s) for s in src_args.split(",")] if src_args else None src_spk = load_audio(args.src_spk, sr=args.sr) src_rir = load_audio(args.src_rir, sr=args.sr) if src_rir: if len(src_rir) != len(src_spk): raise RuntimeError( f"Number of --src-rir={args.src_rir} do not match with " + f"--src-spk={args.src_spk} option") sdr = arg_float(args.src_sdr) if len(src_spk) > 1 and not sdr: raise RuntimeError("--src-sdr need to be assigned for " + f"--src-spk={args.src_spk}") if sdr: if len(src_spk) - 1 != len(sdr): raise RuntimeError("Number of --src-snr - 1 do not match with " + "--src-snr option") sdr = [0] + sdr src_begin = arg_float(args.src_begin) if src_begin: src_begin = [int(v) for v in src_begin] else: src_begin = [0 for _ in src_spk] mix_nsamps = max([b + s.size for b, s in zip(src_begin, src_spk)]) point_noise_rir = load_audio(args.point_noise_rir, sr=args.sr) point_noise_end = [ str(int(v) + mix_nsamps) for v in args.point_noise_offset.split() ] point_noise = load_audio(args.point_noise, beg=args.point_noise_offset, end=",".join(point_noise_end), sr=args.sr) if args.point_noise: if point_noise_rir: if len(point_noise) != len(point_noise_rir): raise RuntimeError( f"Number of --point-noise-rir={args.point_noise_rir} do not match with " + f"--point-noise={args.point_noise} option") point_snr = arg_float(args.point_noise_snr) if not point_snr: raise RuntimeError("--point-noise-snr need to be assigned for " + f"--point-noise={args.point_noise}") if len(point_noise) != len(point_snr): raise RuntimeError( f"Number of --point-noise-snr={args.point_noise_snr} do not match with " + f"--point-noise={args.point_noise} option") point_begin = arg_float(args.point_noise_begin) if point_begin: point_begin = [int(v) for v in point_begin] else: point_begin = [0 for _ in point_noise] isotropic_noise = load_audio(args.isotropic_noise, beg=str(args.isotropic_noise_offset), end=str(args.isotropic_noise_offset + mix_nsamps), sr=args.sr) if isotropic_noise: isotropic_noise = isotropic_noise[0] isotropic_snr = arg_float(args.isotropic_noise_snr) if not isotropic_snr: raise RuntimeError( "--isotropic-snr need to be assigned for " + f"--isotropic-noise={args.isotropic_noise} option") isotropic_snr = isotropic_snr[0] else: isotropic_snr = None spk = add_speaker(mix_nsamps, src_spk, src_begin, sdr, src_rir=src_rir, channel=args.dump_channel, sr=args.sr) spk_utt = sum(spk) mix = spk_utt.copy() spk_power = np.mean(spk_utt[0]**2) if point_noise: noise = add_point_noise(mix_nsamps, spk_power, point_noise, point_begin, point_snr, noise_rir=point_noise_rir, channel=args.dump_channel, repeat=args.point_noise_repeat, sr=args.sr) num_channels = spk_utt.shape[0] if num_channels != noise.shape[0]: if num_channels == 1: noise = noise[0:1] else: raise RuntimeError("Channel mismatch between source speaker " + "configuration and pointsource noise's, " + f"{num_channels} vs {noise.shape[0]}") mix = spk_utt + noise else: noise = None ch = args.dump_channel if isotropic_noise is not None: N, _ = spk_utt.shape if N == 1: if isotropic_noise.ndim == 1: isotropic_noise = isotropic_noise[None, ...] else: if ch >= 0: isotropic_noise = isotropic_noise[ch:ch + 1] else: raise RuntimeError( "Single channel mixture vs multi-channel " "isotropic noise") else: if isotropic_noise.shape[0] != N: raise RuntimeError( "Channel number mismatch between mixture and isotropic noise, " + f"{N} vs {isotropic_noise.shape[0]}") dur = min(mix_nsamps, isotropic_noise.shape[-1]) isotropic_chunk = isotropic_noise[0, :dur] power = np.mean(isotropic_chunk**2) coeff = coeff_snr(power, spk_power, isotropic_snr) mix[..., :dur] += coeff * isotropic_chunk if noise is None: noise = coeff * isotropic_chunk else: noise[..., :dur] += coeff * isotropic_chunk factor = args.norm_factor / (np.max(np.abs(mix)) + EPSILON) mix = mix.squeeze() * factor spk = [s[0] * factor for s in spk] if noise is None: return mix, spk, None else: return mix, spk, noise[0] * factor def make_argparse(): parser = argparse.ArgumentParser( description="Command to do audio data simulation", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--src-spk", type=str, required=True, help="Source speakers, e.g., spk1.wav,spk2.wav") parser.add_argument("--src-rir", type=str, default="", help="RIRs for each source speakers") parser.add_argument("--src-sdr", type=str, default="", help="SDR for each speakers (if needed)") parser.add_argument("--src-begin", type=str, default="", help="Begining samples on the mixture utterances") parser.add_argument("--point-noise", type=str, default="", help="Add pointsource noises") parser.add_argument("--point-noise-rir", type=str, default="", help="RIRs of the pointsource noises (if needed)") parser.add_argument("--point-noise-snr", type=str, default="", help="SNR of the pointsource noises") parser.add_argument("--point-noise-begin", type=str, default="", help="Begining samples of the " "pointsource noises on the mixture " "utterances (if needed)") parser.add_argument("--point-noise-offset", type=str, default="", help="Add from the offset position " "of the pointsource noise") parser.add_argument("--point-noise-repeat", action=StrToBoolAction, default=False, help="Repeat the pointsource noise or not") parser.add_argument("--isotropic-noise", type=str, default="", help="Add isotropic noises") parser.add_argument("--isotropic-noise-snr", type=str, default="", help="SNR of the isotropic noises") parser.add_argument("--isotropic-noise-offset", type=int, default=0, help="Add noise from the offset position " "of the isotropic noise") parser.add_argument("--dump-channel", type=int, default=-1, help="Index of the channel to dump out (-1 means all)") parser.add_argument('--norm-factor', type=float, default=0.9, help="Normalization factor of the final output") parser.add_argument("--sr", type=int, default=16000, help="Value of the sample rate") return parser
true
true
f7257753ce0834da08cef9848377fb031be44fc6
2,553
py
Python
tests/test_parametric_printer_coverage.py
ka3bhy/wexpect
14a4279579a740ce15743db44228f3b0cf4ee8f4
[ "MIT" ]
52
2019-04-24T14:38:43.000Z
2022-03-08T22:03:11.000Z
tests/test_parametric_printer_coverage.py
ka3bhy/wexpect
14a4279579a740ce15743db44228f3b0cf4ee8f4
[ "MIT" ]
51
2019-05-13T12:15:09.000Z
2021-12-15T14:00:15.000Z
tests/test_parametric_printer_coverage.py
ka3bhy/wexpect
14a4279579a740ce15743db44228f3b0cf4ee8f4
[ "MIT" ]
20
2019-07-15T15:48:31.000Z
2022-03-27T08:55:17.000Z
import wexpect import unittest import sys import os import time from tests import PexpectTestCase @unittest.skipIf(wexpect.spawn_class_name == 'legacy_wexpect', "legacy unsupported") class TestCaseParametricPrinter(PexpectTestCase.PexpectTestCase): def test_all_line_length (self): here = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, here) # With quotes (C:\Program Files\Python37\python.exe needs quotes) python_executable = '"' + sys.executable + '" ' child_script = here + '\\parametric_printer.py' self.prompt = '> ' # Start the child process self.p = wexpect.spawn(python_executable + ' ' + child_script, coverage_console_reader=True) # Wait for prompt self.p.expect(self.prompt) self._test(['a'], range(1,200), [1], [0]) self.p.terminate() def test_long_console(self): here = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, here) # With quotes (C:\Program Files\Python37\python.exe needs quotes) python_executable = '"' + sys.executable + '" ' child_script = here + '\\parametric_printer.py' self.prompt = '> ' # Start the child process self.p = wexpect.spawn(python_executable + ' ' + child_script, coverage_console_reader=True) # Wait for prompt self.p.expect(self.prompt) self._test(['a', 'b', 'c', 'd', 'e', 'f'], [8, 16, 32, 64], [64, 128, 256], [-1, 0]) self.p.terminate() def _test(self, character_list, character_count_list, line_count_list, speed_ms_list): # print(f'character_list: {character_list} character_count_list: {character_count_list} line_count_list: {line_count_list} speed_ms_list: {speed_ms_list}') for character in character_list: for character_count in character_count_list: for line_count in line_count_list: for speed_ms in speed_ms_list: command = f'{character},{character_count},{line_count},{speed_ms}' self.p.sendline(command) self.p.expect(self.prompt) expected = [character*character_count] * line_count try: self.assertEqual(self.p.before.splitlines()[1:-1], expected) except: raise if __name__ == '__main__': unittest.main() suite = unittest.makeSuite(TestCaseParametricPrinter,'test')
36.471429
166
0.613396
import wexpect import unittest import sys import os import time from tests import PexpectTestCase @unittest.skipIf(wexpect.spawn_class_name == 'legacy_wexpect', "legacy unsupported") class TestCaseParametricPrinter(PexpectTestCase.PexpectTestCase): def test_all_line_length (self): here = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, here) python_executable = '"' + sys.executable + '" ' child_script = here + '\\parametric_printer.py' self.prompt = '> ' self.p = wexpect.spawn(python_executable + ' ' + child_script, coverage_console_reader=True) self.p.expect(self.prompt) self._test(['a'], range(1,200), [1], [0]) self.p.terminate() def test_long_console(self): here = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, here) python_executable = '"' + sys.executable + '" ' child_script = here + '\\parametric_printer.py' self.prompt = '> ' self.p = wexpect.spawn(python_executable + ' ' + child_script, coverage_console_reader=True) self.p.expect(self.prompt) self._test(['a', 'b', 'c', 'd', 'e', 'f'], [8, 16, 32, 64], [64, 128, 256], [-1, 0]) self.p.terminate() def _test(self, character_list, character_count_list, line_count_list, speed_ms_list): for character in character_list: for character_count in character_count_list: for line_count in line_count_list: for speed_ms in speed_ms_list: command = f'{character},{character_count},{line_count},{speed_ms}' self.p.sendline(command) self.p.expect(self.prompt) expected = [character*character_count] * line_count try: self.assertEqual(self.p.before.splitlines()[1:-1], expected) except: raise if __name__ == '__main__': unittest.main() suite = unittest.makeSuite(TestCaseParametricPrinter,'test')
true
true
f725787c40eac809defe6a07fbbbbed9170067b9
3,731
py
Python
contrib/macdeploy/custom_dsstore.py
BufferUnderwhelm/asspennies
919be76d6d4be42fea02af1194df2875b91c85dc
[ "MIT" ]
null
null
null
contrib/macdeploy/custom_dsstore.py
BufferUnderwhelm/asspennies
919be76d6d4be42fea02af1194df2875b91c85dc
[ "MIT" ]
null
null
null
contrib/macdeploy/custom_dsstore.py
BufferUnderwhelm/asspennies
919be76d6d4be42fea02af1194df2875b91c85dc
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) 2013-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import biplist from ds_store import DSStore from mac_alias import Alias import sys output_file = sys.argv[1] package_name_ns = sys.argv[2] ds = DSStore.open(output_file, 'w+') ds['.']['bwsp'] = { 'ShowStatusBar': False, 'WindowBounds': '{{300, 280}, {500, 343}}', 'ContainerShowSidebar': False, 'SidebarWidth': 0, 'ShowTabView': False, 'PreviewPaneVisibility': False, 'ShowToolbar': False, 'ShowSidebar': False, 'ShowPathbar': True } icvp = { 'gridOffsetX': 0.0, 'textSize': 12.0, 'viewOptionsVersion': 1, 'backgroundImageAlias': b'\x00\x00\x00\x00\x02\x1e\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd1\x94\\\xb0H+\x00\x05\x00\x00\x00\x98\x0fbackground.tiff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x99\xd19\xb0\xf8\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\x00\x00\r\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b.background\x00\x00\x10\x00\x08\x00\x00\xd1\x94\\\xb0\x00\x00\x00\x11\x00\x08\x00\x00\xd19\xb0\xf8\x00\x00\x00\x01\x00\x04\x00\x00\x00\x98\x00\x0e\x00 \x00\x0f\x00b\x00a\x00c\x00k\x00g\x00r\x00o\x00u\x00n\x00d\x00.\x00t\x00i\x00f\x00f\x00\x0f\x00\x02\x00\x00\x00\x12\x00\x1c/.background/background.tiff\x00\x14\x01\x06\x00\x00\x00\x00\x01\x06\x00\x02\x00\x00\x0cMacintosh HD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xce\x97\xab\xc3H+\x00\x00\x01\x88[\x88\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02u\xab\x8d\xd1\x94\\\xb0devrddsk\xff\xff\xff\xff\x00\x00\t \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07bitcoin\x00\x00\x10\x00\x08\x00\x00\xce\x97\xab\xc3\x00\x00\x00\x11\x00\x08\x00\x00\xd1\x94\\\xb0\x00\x00\x00\x01\x00\x14\x01\x88[\x88\x00\x16\xa9\t\x00\x08\xfaR\x00\x08\xfaQ\x00\x02d\x8e\x00\x0e\x00\x02\x00\x00\x00\x0f\x00\x1a\x00\x0c\x00M\x00a\x00c\x00i\x00n\x00t\x00o\x00s\x00h\x00 \x00H\x00D\x00\x13\x00\x01/\x00\x00\x15\x00\x02\x00\x14\xff\xff\x00\x00\xff\xff\x00\x00', 'backgroundColorBlue': 1.0, 'iconSize': 96.0, 'backgroundColorGreen': 1.0, 'arrangeBy': 'none', 'showIconPreview': True, 'gridSpacing': 100.0, 'gridOffsetY': 0.0, 'showItemInfo': False, 'labelOnBottom': True, 'backgroundType': 2, 'backgroundColorRed': 1.0 } alias = Alias.from_bytes(icvp['backgroundImageAlias']) alias.volume.name = package_name_ns alias.volume.posix_path = '/Volumes/' + package_name_ns alias.volume.disk_image_alias.target.filename = package_name_ns + '.temp.dmg' alias.volume.disk_image_alias.target.carbon_path = 'Macintosh HD:Users:\x00asspenniesuser:\x00Documents:\x00asspennies:\x00asspennies:\x00' + package_name_ns + '.temp.dmg' alias.volume.disk_image_alias.target.posix_path = 'Users/asspenniesuser/Documents/asspennies/asspennies/' + package_name_ns + '.temp.dmg' alias.target.carbon_path = package_name_ns + ':.background:\x00background.tiff' icvp['backgroundImageAlias'] = biplist.Data(alias.to_bytes()) ds['.']['icvp'] = icvp ds['.']['vSrn'] = ('long', 1) ds['Applications']['Iloc'] = (370, 156) ds['AssPennies-Qt.app']['Iloc'] = (128, 156) ds.flush() ds.close()
62.183333
1,817
0.725811
import biplist from ds_store import DSStore from mac_alias import Alias import sys output_file = sys.argv[1] package_name_ns = sys.argv[2] ds = DSStore.open(output_file, 'w+') ds['.']['bwsp'] = { 'ShowStatusBar': False, 'WindowBounds': '{{300, 280}, {500, 343}}', 'ContainerShowSidebar': False, 'SidebarWidth': 0, 'ShowTabView': False, 'PreviewPaneVisibility': False, 'ShowToolbar': False, 'ShowSidebar': False, 'ShowPathbar': True } icvp = { 'gridOffsetX': 0.0, 'textSize': 12.0, 'viewOptionsVersion': 1, 'backgroundImageAlias': b'\x00\x00\x00\x00\x02\x1e\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd1\x94\\\xb0H+\x00\x05\x00\x00\x00\x98\x0fbackground.tiff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x99\xd19\xb0\xf8\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\x00\x00\r\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b.background\x00\x00\x10\x00\x08\x00\x00\xd1\x94\\\xb0\x00\x00\x00\x11\x00\x08\x00\x00\xd19\xb0\xf8\x00\x00\x00\x01\x00\x04\x00\x00\x00\x98\x00\x0e\x00 \x00\x0f\x00b\x00a\x00c\x00k\x00g\x00r\x00o\x00u\x00n\x00d\x00.\x00t\x00i\x00f\x00f\x00\x0f\x00\x02\x00\x00\x00\x12\x00\x1c/.background/background.tiff\x00\x14\x01\x06\x00\x00\x00\x00\x01\x06\x00\x02\x00\x00\x0cMacintosh HD\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xce\x97\xab\xc3H+\x00\x00\x01\x88[\x88\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02u\xab\x8d\xd1\x94\\\xb0devrddsk\xff\xff\xff\xff\x00\x00\t \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x07bitcoin\x00\x00\x10\x00\x08\x00\x00\xce\x97\xab\xc3\x00\x00\x00\x11\x00\x08\x00\x00\xd1\x94\\\xb0\x00\x00\x00\x01\x00\x14\x01\x88[\x88\x00\x16\xa9\t\x00\x08\xfaR\x00\x08\xfaQ\x00\x02d\x8e\x00\x0e\x00\x02\x00\x00\x00\x0f\x00\x1a\x00\x0c\x00M\x00a\x00c\x00i\x00n\x00t\x00o\x00s\x00h\x00 \x00H\x00D\x00\x13\x00\x01/\x00\x00\x15\x00\x02\x00\x14\xff\xff\x00\x00\xff\xff\x00\x00', 'backgroundColorBlue': 1.0, 'iconSize': 96.0, 'backgroundColorGreen': 1.0, 'arrangeBy': 'none', 'showIconPreview': True, 'gridSpacing': 100.0, 'gridOffsetY': 0.0, 'showItemInfo': False, 'labelOnBottom': True, 'backgroundType': 2, 'backgroundColorRed': 1.0 } alias = Alias.from_bytes(icvp['backgroundImageAlias']) alias.volume.name = package_name_ns alias.volume.posix_path = '/Volumes/' + package_name_ns alias.volume.disk_image_alias.target.filename = package_name_ns + '.temp.dmg' alias.volume.disk_image_alias.target.carbon_path = 'Macintosh HD:Users:\x00asspenniesuser:\x00Documents:\x00asspennies:\x00asspennies:\x00' + package_name_ns + '.temp.dmg' alias.volume.disk_image_alias.target.posix_path = 'Users/asspenniesuser/Documents/asspennies/asspennies/' + package_name_ns + '.temp.dmg' alias.target.carbon_path = package_name_ns + ':.background:\x00background.tiff' icvp['backgroundImageAlias'] = biplist.Data(alias.to_bytes()) ds['.']['icvp'] = icvp ds['.']['vSrn'] = ('long', 1) ds['Applications']['Iloc'] = (370, 156) ds['AssPennies-Qt.app']['Iloc'] = (128, 156) ds.flush() ds.close()
true
true
f72579efb9020b0aeda91f6744f1f71d26ad9971
380
py
Python
yandex_checkout/domain/models/payment_data/payment_data_factory.py
pavel52rus/yandex-checkout-sdk-python
10c8b0ce12712bca675254f2a230f9fc0e1cb9b4
[ "MIT" ]
null
null
null
yandex_checkout/domain/models/payment_data/payment_data_factory.py
pavel52rus/yandex-checkout-sdk-python
10c8b0ce12712bca675254f2a230f9fc0e1cb9b4
[ "MIT" ]
null
null
null
yandex_checkout/domain/models/payment_data/payment_data_factory.py
pavel52rus/yandex-checkout-sdk-python
10c8b0ce12712bca675254f2a230f9fc0e1cb9b4
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from yandex_checkout.domain.common.type_factory import TypeFactory from yandex_checkout.domain.models.payment_data.payment_data_class_map import PaymentDataClassMap class PaymentDataFactory(TypeFactory): """ Factory for payment data objects """ def __init__(self): super(PaymentDataFactory, self).__init__(PaymentDataClassMap())
29.230769
97
0.765789
from yandex_checkout.domain.common.type_factory import TypeFactory from yandex_checkout.domain.models.payment_data.payment_data_class_map import PaymentDataClassMap class PaymentDataFactory(TypeFactory): def __init__(self): super(PaymentDataFactory, self).__init__(PaymentDataClassMap())
true
true
f7257ab79e200ce2c0c75e0ae6d7b38cf586e521
4,649
py
Python
ee/clickhouse/queries/paths/path_event_query.py
thinhnguyenuit/posthog
4758e66790485587d29a617174158d07341342f8
[ "MIT" ]
null
null
null
ee/clickhouse/queries/paths/path_event_query.py
thinhnguyenuit/posthog
4758e66790485587d29a617174158d07341342f8
[ "MIT" ]
null
null
null
ee/clickhouse/queries/paths/path_event_query.py
thinhnguyenuit/posthog
4758e66790485587d29a617174158d07341342f8
[ "MIT" ]
null
null
null
from typing import Any, Dict, Tuple from ee.clickhouse.models.property import get_property_string_expr from ee.clickhouse.queries.event_query import ClickhouseEventQuery from posthog.constants import AUTOCAPTURE_EVENT, PAGEVIEW_EVENT, SCREEN_EVENT from posthog.models.filters.path_filter import PathFilter class PathEventQuery(ClickhouseEventQuery): FUNNEL_PERSONS_ALIAS = "funnel_persons" _filter: PathFilter def __init__( self, filter: PathFilter, team_id: int, round_interval=False, should_join_distinct_ids=False, should_join_persons=False, **kwargs, ) -> None: super().__init__(filter, team_id, round_interval, should_join_distinct_ids, should_join_persons, **kwargs) def get_query(self) -> Tuple[str, Dict[str, Any]]: # TODO: ColumnOptimizer with options like self._filter.include_pageviews, self._filter.include_screenviews, funnel_paths_timestamp = "" funnel_paths_join = "" funnel_paths_filter = "" if self._filter.funnel_paths: funnel_paths_timestamp = f"{self.FUNNEL_PERSONS_ALIAS}.timestamp as min_timestamp" funnel_paths_join = f"JOIN {self.FUNNEL_PERSONS_ALIAS} ON {self.FUNNEL_PERSONS_ALIAS}.person_id = {self.DISTINCT_ID_TABLE_ALIAS}.person_id" funnel_paths_filter = f"AND {self.EVENT_TABLE_ALIAS}.timestamp >= min_timestamp" _fields = [ f"{self.EVENT_TABLE_ALIAS}.timestamp AS timestamp", ( f"if(event = '{SCREEN_EVENT}', {self._get_screen_name_parsing()}, " f"if({self.EVENT_TABLE_ALIAS}.event = '{PAGEVIEW_EVENT}', {self._get_current_url_parsing()}, " f"if({self.EVENT_TABLE_ALIAS}.event = '{AUTOCAPTURE_EVENT}', concat('autocapture:', {self.EVENT_TABLE_ALIAS}.elements_chain), " f"{self.EVENT_TABLE_ALIAS}.event))) AS path_item" ), f"{self.DISTINCT_ID_TABLE_ALIAS}.person_id as person_id" if self._should_join_distinct_ids else "", funnel_paths_timestamp, ] _fields = list(filter(None, _fields)) date_query, date_params = self._get_date_filter() self.params.update(date_params) prop_filters = self._filter.properties prop_query, prop_params = self._get_props(prop_filters) self.params.update(prop_params) event_query, event_params = self._get_event_query() self.params.update(event_params) query = f""" SELECT {','.join(_fields)} FROM events {self.EVENT_TABLE_ALIAS} {self._get_disintct_id_query()} {self._get_person_query()} {funnel_paths_join} WHERE team_id = %(team_id)s {event_query} {date_query} {prop_query} {funnel_paths_filter} ORDER BY {self.DISTINCT_ID_TABLE_ALIAS}.person_id, {self.EVENT_TABLE_ALIAS}.timestamp """ return query, self.params def _determine_should_join_distinct_ids(self) -> None: self._should_join_distinct_ids = True def _get_current_url_parsing(self): path_type, _ = get_property_string_expr("events", "$current_url", "'$current_url'", "properties") return f"if(length({path_type}) > 1, trim( TRAILING '/' FROM {path_type}), {path_type})" def _get_screen_name_parsing(self): path_type, _ = get_property_string_expr("events", "$screen_name", "'$screen_name'", "properties") return path_type def _get_event_query(self) -> Tuple[str, Dict[str, Any]]: params: Dict[str, Any] = {} conditions = [] or_conditions = [] if self._filter.include_pageviews: or_conditions.append(f"event = '{PAGEVIEW_EVENT}'") if self._filter.include_screenviews: or_conditions.append(f"event = '{SCREEN_EVENT}'") if self._filter.include_autocaptures: or_conditions.append(f"event = '{AUTOCAPTURE_EVENT}'") if self._filter.include_all_custom_events: or_conditions.append(f"NOT event LIKE '$%%'") if self._filter.custom_events: or_conditions.append(f"event IN %(custom_events)s") params["custom_events"] = self._filter.custom_events if or_conditions: conditions.append(f"({' OR '.join(or_conditions)})") if self._filter.exclude_events: conditions.append(f"NOT event IN %(exclude_events)s") params["exclude_events"] = self._filter.exclude_events if conditions: return f" AND {' AND '.join(conditions)}", params return "", {}
39.735043
151
0.655195
from typing import Any, Dict, Tuple from ee.clickhouse.models.property import get_property_string_expr from ee.clickhouse.queries.event_query import ClickhouseEventQuery from posthog.constants import AUTOCAPTURE_EVENT, PAGEVIEW_EVENT, SCREEN_EVENT from posthog.models.filters.path_filter import PathFilter class PathEventQuery(ClickhouseEventQuery): FUNNEL_PERSONS_ALIAS = "funnel_persons" _filter: PathFilter def __init__( self, filter: PathFilter, team_id: int, round_interval=False, should_join_distinct_ids=False, should_join_persons=False, **kwargs, ) -> None: super().__init__(filter, team_id, round_interval, should_join_distinct_ids, should_join_persons, **kwargs) def get_query(self) -> Tuple[str, Dict[str, Any]]: funnel_paths_timestamp = "" funnel_paths_join = "" funnel_paths_filter = "" if self._filter.funnel_paths: funnel_paths_timestamp = f"{self.FUNNEL_PERSONS_ALIAS}.timestamp as min_timestamp" funnel_paths_join = f"JOIN {self.FUNNEL_PERSONS_ALIAS} ON {self.FUNNEL_PERSONS_ALIAS}.person_id = {self.DISTINCT_ID_TABLE_ALIAS}.person_id" funnel_paths_filter = f"AND {self.EVENT_TABLE_ALIAS}.timestamp >= min_timestamp" _fields = [ f"{self.EVENT_TABLE_ALIAS}.timestamp AS timestamp", ( f"if(event = '{SCREEN_EVENT}', {self._get_screen_name_parsing()}, " f"if({self.EVENT_TABLE_ALIAS}.event = '{PAGEVIEW_EVENT}', {self._get_current_url_parsing()}, " f"if({self.EVENT_TABLE_ALIAS}.event = '{AUTOCAPTURE_EVENT}', concat('autocapture:', {self.EVENT_TABLE_ALIAS}.elements_chain), " f"{self.EVENT_TABLE_ALIAS}.event))) AS path_item" ), f"{self.DISTINCT_ID_TABLE_ALIAS}.person_id as person_id" if self._should_join_distinct_ids else "", funnel_paths_timestamp, ] _fields = list(filter(None, _fields)) date_query, date_params = self._get_date_filter() self.params.update(date_params) prop_filters = self._filter.properties prop_query, prop_params = self._get_props(prop_filters) self.params.update(prop_params) event_query, event_params = self._get_event_query() self.params.update(event_params) query = f""" SELECT {','.join(_fields)} FROM events {self.EVENT_TABLE_ALIAS} {self._get_disintct_id_query()} {self._get_person_query()} {funnel_paths_join} WHERE team_id = %(team_id)s {event_query} {date_query} {prop_query} {funnel_paths_filter} ORDER BY {self.DISTINCT_ID_TABLE_ALIAS}.person_id, {self.EVENT_TABLE_ALIAS}.timestamp """ return query, self.params def _determine_should_join_distinct_ids(self) -> None: self._should_join_distinct_ids = True def _get_current_url_parsing(self): path_type, _ = get_property_string_expr("events", "$current_url", "'$current_url'", "properties") return f"if(length({path_type}) > 1, trim( TRAILING '/' FROM {path_type}), {path_type})" def _get_screen_name_parsing(self): path_type, _ = get_property_string_expr("events", "$screen_name", "'$screen_name'", "properties") return path_type def _get_event_query(self) -> Tuple[str, Dict[str, Any]]: params: Dict[str, Any] = {} conditions = [] or_conditions = [] if self._filter.include_pageviews: or_conditions.append(f"event = '{PAGEVIEW_EVENT}'") if self._filter.include_screenviews: or_conditions.append(f"event = '{SCREEN_EVENT}'") if self._filter.include_autocaptures: or_conditions.append(f"event = '{AUTOCAPTURE_EVENT}'") if self._filter.include_all_custom_events: or_conditions.append(f"NOT event LIKE '$%%'") if self._filter.custom_events: or_conditions.append(f"event IN %(custom_events)s") params["custom_events"] = self._filter.custom_events if or_conditions: conditions.append(f"({' OR '.join(or_conditions)})") if self._filter.exclude_events: conditions.append(f"NOT event IN %(exclude_events)s") params["exclude_events"] = self._filter.exclude_events if conditions: return f" AND {' AND '.join(conditions)}", params return "", {}
true
true
f7257ab8f76526d2fc5780943a2451a7b5e04d54
4,946
py
Python
example_scenes/basic.py
Pow3r5/manim
2972a64342aa5ae72977b444f653b05250ab1f8f
[ "MIT" ]
2
2022-03-31T08:31:00.000Z
2022-03-31T08:31:43.000Z
example_scenes/basic.py
Pow3r5/manim
2972a64342aa5ae72977b444f653b05250ab1f8f
[ "MIT" ]
null
null
null
example_scenes/basic.py
Pow3r5/manim
2972a64342aa5ae72977b444f653b05250ab1f8f
[ "MIT" ]
null
null
null
#!/usr/bin/env python from manim import * # To watch one of these scenes, run the following: # python --quality m manim -p example_scenes.py SquareToCircle # # Use the flag --quality l for a faster rendering at a lower quality. # Use -s to skip to the end and just save the final frame # Use the -p to have preview of the animation (or image, if -s was # used) pop up once done. # Use -n <number> to skip ahead to the nth animation of a scene. # Use -r <number> to specify a resolution (for example, -r 1920,1080 # for a 1920x1080 video) class OpeningManim(Scene): def construct(self): title = Tex(r"This is some \LaTeX") basel = MathTex(r"\sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}") VGroup(title, basel).arrange(DOWN) self.play( Write(title), FadeIn(basel, shift=DOWN), ) self.wait() transform_title = Tex("That was a transform") transform_title.to_corner(UP + LEFT) self.play( Transform(title, transform_title), LaggedStart(*(FadeOut(obj, shift=DOWN) for obj in basel)), ) self.wait() grid = NumberPlane() grid_title = Tex("This is a grid", font_size=72) grid_title.move_to(transform_title) self.add(grid, grid_title) # Make sure title is on top of grid self.play( FadeOut(title), FadeIn(grid_title, shift=UP), Create(grid, run_time=3, lag_ratio=0.1), ) self.wait() grid_transform_title = Tex( r"That was a non-linear function \\ applied to the grid", ) grid_transform_title.move_to(grid_title, UL) grid.prepare_for_nonlinear_transform() self.play( grid.animate.apply_function( lambda p: p + np.array( [ np.sin(p[1]), np.sin(p[0]), 0, ], ), ), run_time=3, ) self.wait() self.play(Transform(grid_title, grid_transform_title)) self.wait() class SquareToCircle(Scene): def construct(self): circle = Circle() square = Square() square.flip(RIGHT) square.rotate(-3 * TAU / 8) circle.set_fill(PINK, opacity=0.5) self.play(Create(square)) self.play(Transform(square, circle)) self.play(FadeOut(square)) class WarpSquare(Scene): def construct(self): square = Square() self.play( ApplyPointwiseFunction( lambda point: complex_to_R3(np.exp(R3_to_complex(point))), square, ), ) self.wait() class WriteStuff(Scene): def construct(self): example_text = Tex("This is a some text", tex_to_color_map={"text": YELLOW}) example_tex = MathTex( "\\sum_{k=1}^\\infty {1 \\over k^2} = {\\pi^2 \\over 6}", ) group = VGroup(example_text, example_tex) group.arrange(DOWN) group.width = config["frame_width"] - 2 * LARGE_BUFF self.play(Write(example_text)) self.play(Write(example_tex)) self.wait() class UpdatersExample(Scene): def construct(self): decimal = DecimalNumber( 0, show_ellipsis=True, num_decimal_places=3, include_sign=True, ) square = Square().to_edge(UP) decimal.add_updater(lambda d: d.next_to(square, RIGHT)) decimal.add_updater(lambda d: d.set_value(square.get_center()[1])) self.add(square, decimal) self.play( square.animate.to_edge(DOWN), rate_func=there_and_back, run_time=5, ) self.wait() class SpiralInExample(Scene): def construct(self): logo_green = "#81b29a" logo_blue = "#454866" logo_red = "#e07a5f" font_color = "#ece6e2" pi = MathTex(r"\pi").scale(7).set_color(font_color) pi.shift(2.25 * LEFT + 1.5 * UP) circle = Circle(color=logo_green, fill_opacity=0.7, stroke_width=0).shift(LEFT) square = Square(color=logo_blue, fill_opacity=0.8, stroke_width=0).shift(UP) triangle = Triangle(color=logo_red, fill_opacity=0.9, stroke_width=0).shift( RIGHT ) pentagon = Polygon( *[ [np.cos(2 * np.pi / 5 * i), np.sin(2 * np.pi / 5 * i), 0] for i in range(5) ], color=PURPLE_B, fill_opacity=1, stroke_width=0 ).shift(UP + 2 * RIGHT) shapes = VGroup(triangle, square, circle, pentagon, pi) self.play(SpiralIn(shapes, fade_in_fraction=0.9)) self.wait() self.play(FadeOut(shapes)) # See many more examples at https://docs.manim.community/en/stable/examples.html
29.975758
87
0.558229
from manim import * class OpeningManim(Scene): def construct(self): title = Tex(r"This is some \LaTeX") basel = MathTex(r"\sum_{n=1}^\infty \frac{1}{n^2} = \frac{\pi^2}{6}") VGroup(title, basel).arrange(DOWN) self.play( Write(title), FadeIn(basel, shift=DOWN), ) self.wait() transform_title = Tex("That was a transform") transform_title.to_corner(UP + LEFT) self.play( Transform(title, transform_title), LaggedStart(*(FadeOut(obj, shift=DOWN) for obj in basel)), ) self.wait() grid = NumberPlane() grid_title = Tex("This is a grid", font_size=72) grid_title.move_to(transform_title) self.add(grid, grid_title) self.play( FadeOut(title), FadeIn(grid_title, shift=UP), Create(grid, run_time=3, lag_ratio=0.1), ) self.wait() grid_transform_title = Tex( r"That was a non-linear function \\ applied to the grid", ) grid_transform_title.move_to(grid_title, UL) grid.prepare_for_nonlinear_transform() self.play( grid.animate.apply_function( lambda p: p + np.array( [ np.sin(p[1]), np.sin(p[0]), 0, ], ), ), run_time=3, ) self.wait() self.play(Transform(grid_title, grid_transform_title)) self.wait() class SquareToCircle(Scene): def construct(self): circle = Circle() square = Square() square.flip(RIGHT) square.rotate(-3 * TAU / 8) circle.set_fill(PINK, opacity=0.5) self.play(Create(square)) self.play(Transform(square, circle)) self.play(FadeOut(square)) class WarpSquare(Scene): def construct(self): square = Square() self.play( ApplyPointwiseFunction( lambda point: complex_to_R3(np.exp(R3_to_complex(point))), square, ), ) self.wait() class WriteStuff(Scene): def construct(self): example_text = Tex("This is a some text", tex_to_color_map={"text": YELLOW}) example_tex = MathTex( "\\sum_{k=1}^\\infty {1 \\over k^2} = {\\pi^2 \\over 6}", ) group = VGroup(example_text, example_tex) group.arrange(DOWN) group.width = config["frame_width"] - 2 * LARGE_BUFF self.play(Write(example_text)) self.play(Write(example_tex)) self.wait() class UpdatersExample(Scene): def construct(self): decimal = DecimalNumber( 0, show_ellipsis=True, num_decimal_places=3, include_sign=True, ) square = Square().to_edge(UP) decimal.add_updater(lambda d: d.next_to(square, RIGHT)) decimal.add_updater(lambda d: d.set_value(square.get_center()[1])) self.add(square, decimal) self.play( square.animate.to_edge(DOWN), rate_func=there_and_back, run_time=5, ) self.wait() class SpiralInExample(Scene): def construct(self): logo_green = "#81b29a" logo_blue = "#454866" logo_red = "#e07a5f" font_color = "#ece6e2" pi = MathTex(r"\pi").scale(7).set_color(font_color) pi.shift(2.25 * LEFT + 1.5 * UP) circle = Circle(color=logo_green, fill_opacity=0.7, stroke_width=0).shift(LEFT) square = Square(color=logo_blue, fill_opacity=0.8, stroke_width=0).shift(UP) triangle = Triangle(color=logo_red, fill_opacity=0.9, stroke_width=0).shift( RIGHT ) pentagon = Polygon( *[ [np.cos(2 * np.pi / 5 * i), np.sin(2 * np.pi / 5 * i), 0] for i in range(5) ], color=PURPLE_B, fill_opacity=1, stroke_width=0 ).shift(UP + 2 * RIGHT) shapes = VGroup(triangle, square, circle, pentagon, pi) self.play(SpiralIn(shapes, fade_in_fraction=0.9)) self.wait() self.play(FadeOut(shapes))
true
true
f7257af7f5369ac97b09687baeec3f79676d59fb
17,484
py
Python
SE4TeC_demo/GUI_function.py
JingweiZuo/SE2TeC
f2aab845aa648e366d0f6917a5d8abfd4d556d13
[ "Apache-2.0" ]
1
2020-05-10T11:23:11.000Z
2020-05-10T11:23:11.000Z
SE4TeC_demo/GUI_function.py
JingweiZuo/SE4TeC
f2aab845aa648e366d0f6917a5d8abfd4d556d13
[ "Apache-2.0" ]
null
null
null
SE4TeC_demo/GUI_function.py
JingweiZuo/SE4TeC
f2aab845aa648e366d0f6917a5d8abfd4d556d13
[ "Apache-2.0" ]
null
null
null
import time import tkinter as tk from tkinter import * import tkinter.filedialog as filedialog from tkinter.filedialog import askopenfilename import utils.utils as util import utils.similarity_measures as sm import SMAP.MatrixProfile as mp import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk from matplotlib.figure import Figure from matplotlib import pyplot as plt import pandas as pd import numpy as np LARGE_FONT= ("Verdana", 12) class gui_function: def __init__(self, master): self.filename = 'file name' self.training_filename = 'choose training set' self.testing_filename = 'choose testing set' #transfer the main test part to the class self.master = master self.dataset = util.Dataset() self.testdataset = util.Dataset() self.dataset_name = None self.shapeletList1 = [] self.shapeletList2 = [] def add_dataset(self): self.dataset_name = askopenfilename(parent=self.master, title="Choose a file") array_tsdict = util.load_dataset(self.dataset_name) dir = self.dataset_name.split("/") datasetname = dir[-1] self.dataset.update(array_tsdict, datasetname) self.master.v_dsname.set(self.dataset.name) self.master.v_tslength.set(self.dataset.tslength) self.master.v_tsnbr.set(self.dataset.size) self.master.v_classnbr.set(len(self.dataset.ClassList)) self.master.show_frame(self.master.frame2, "SMAPPage") def add_testing_file(self): self.testfile_name = askopenfilename(parent=self.master, title="Choose a file") array_tsdict = util.load_dataset(self.testfile_name) dir = self.testfile_name.split("/") datasetname = dir[-1] self.testdataset.update(array_tsdict, datasetname) self.master.v_testdsname.set(self.testdataset.name) self.master.v_testtslength.set(self.testdataset.tslength) self.master.v_testtsnbr.set(self.testdataset.size) self.master.v_testclassnbr.set(len(self.testdataset.ClassList)) self.master.testdataset= self.testdataset def ShowAlgoFrame(self, algorithm): self.master.frame2_1[algorithm].tkraise() self.master.frame2_1[algorithm].grid(row=0, column=0, sticky=W) def extractDP(self, master): self.nbr_source = master.v_source.get() self.nbr_target = master.v_target.get() dataset = master.dataset hash_source = dataset.tsNameDir[self.nbr_source] hash_target = dataset.tsNameDir[self.nbr_target] self.source = dataset.tsObjectDir[hash_source] self.target = dataset.tsObjectDir[hash_target] self.m = master.v_queryL.get() index_start = master.v_queryI.get() data = self.target.timeseries index_end = index_start + self.m query = self.source.timeseries[index_start:index_end] #DP = sm.mass_v2(data, query) #DP = sm.mass_v1(query, data) DP = sm.euclidean_distance_unequal_lengths(data, query) # display the figures on the CANVAS of the GUI # CANVAS # remove the axis_x of "self.axe2" plt.setp(self.master.ax2.get_xaxis(), visible=False) self.master.ax2.spines['bottom'].set_visible(False) self.master.ax3.clear() # clear the previous plot at the same position x = range(len(DP)) self.master.ax3.spines['top'].set_visible(False) self.master.ax3.spines['right'].set_visible(False) self.master.ax3.set_ylabel("Distance Profile") self.master.ax3.plot(x, DP, linewidth=0.5, label="D. P. of Query in " +self.nbr_target) self.master.ax3.legend() self.master.canvas.draw() # show the Nearest Neighbor in target TS DP_list = DP.tolist() index_inValue = DP_list.index(min(DP_list)) index_end = index_inValue + master.m NearestN = self.target.timeseries[index_inValue:index_end] x_target = range(len(self.target.timeseries)) x_NearestN = range(index_inValue, index_end) self.ax2 = self.master.ax2 self.ax2.clear() self.ax2.plot(x_target, self.target.timeseries, linewidth=0.5, label=self.nbr_target) self.ax2.plot(x_NearestN, NearestN, linewidth=2, label="Nearest Neighbor of Query") self.ax2.spines['top'].set_visible(False) self.ax2.spines['right'].set_visible(False) self.ax2.set_ylabel("Target TS") self.ax2.legend(loc="upper right") self.master.canvas.draw() def extractMP(self, master): self.nbr_source = master.v_source.get() self.nbr_target = master.v_target.get() dataset = master.dataset hash_source = dataset.tsNameDir[self.nbr_source] hash_target = dataset.tsNameDir[self.nbr_target] self.source = dataset.tsObjectDir[hash_source] self.target = dataset.tsObjectDir[hash_target] self.m = master.v_queryL.get() dp_all, MP= mp.computeMP(self.source, self.target, self.m, "mass_v2") # CANVAS # remove the axis_x of "self.axe2" plt.setp(self.master.ax2.get_xaxis(), visible=False) self.master.ax2.spines['bottom'].set_visible(False) self.master.ax3.clear() # clear the previous plot at the same position x = range(len(MP)) self.master.ax3.spines['top'].set_visible(False) self.master.ax3.spines['right'].set_visible(False) self.master.ax3.set_ylabel("Matrix Profile") self.master.ax3.plot(x, MP, linewidth=0.5, label="M. P. of "+self.nbr_source+" towards " +self.nbr_target) self.master.ax3.legend() self.master.canvas.draw() # show the matching pair in Source and Target TS index_source = MP.index(min(MP)) index_source_end = index_source + self.m x_pair_source = range(index_source, index_source_end) pair_source = self.source.timeseries[index_source:index_source_end] DP = sm.euclidean_distance_unequal_lengths(self.target.timeseries, pair_source) index_target = DP.tolist().index(min(DP.tolist())) index_target_end = index_target + self.m x_pair_target = range(index_target, index_target_end) pair_target = self.target.timeseries[index_target:index_target_end] # remove the Query in Source TS self.master.ax1.clear() x = range(len(self.source.timeseries)) self.master.ax1.spines['top'].set_visible(False) self.master.ax1.spines['right'].set_visible(False) self.master.ax1.set_ylabel("Source TS") self.master.ax1.plot(x_pair_source, pair_source, linewidth=2, color="red", label="Nearest Pair in source") self.master.ax1.plot(x, self.source.timeseries, linewidth=0.5, label=self.nbr_source) self.master.ax1.legend() self.master.canvas.draw() # remove the Nearest Neighbor in Target TS self.master.ax2.clear() x = range(len(self.target.timeseries)) self.master.ax2.spines['top'].set_visible(False) self.master.ax2.spines['right'].set_visible(False) self.master.ax2.set_ylabel("Target TS") self.master.ax2.plot(x_pair_target, pair_target, linewidth=2, color="red", label="Nearest Pair in target") self.master.ax2.plot(x, self.target.timeseries, linewidth=0.5, label=self.nbr_target) self.master.ax2.legend() self.master.canvas.draw() def extractLB(self): return 0 def extractRP(self, master): source = master.source input_class = str(master.v_class.get()) start = time.clock() DP_all, mp_all, self.dist_differ, dist_threshold, self.dist_side_C, self.dist_side_nonC = mp.computeDistDiffer(source, master.dataset.tsObjectDir, self.m) end = time.clock() self.SMAP_time = round(end - start, 2) if str(source.class_timeseries) == input_class: RP = self.dist_side_C else: RP = self.dist_side_nonC # CANVAS # Configire the axis looking (start) self.master.ax3.clear() if (self.master.ax2.get_ylabel()!="Rep. Profile"): self.master.ax2.clear() plt.setp(self.master.ax2.get_xaxis(), visible=True) self.master.ax2.spines['bottom'].set_visible(True) self.master.ax3.axis("off") # Configire the axis looking (end) x = range(len(RP)) self.master.ax2.set_ylabel("Rep. Profile") label = "Rep. P. of " + self.nbr_source + " in class " + input_class self.master.ax2.plot(x, RP, linewidth=0.5, label=label) self.master.ax2.legend() self.master.canvas.draw() # remove the Query in Source TS self.master.ax1.clear() x = range(len(self.source.timeseries)) self.master.ax1.spines['top'].set_visible(False) self.master.ax1.spines['right'].set_visible(False) self.master.ax1.set_ylabel("Source TS") self.master.ax1.plot(x, self.source.timeseries, linewidth=0.5, label=self.nbr_source) self.master.ax1.legend() self.master.canvas.draw() def extractDiscP(self, master): '''source = master.source dp_all, mp_all, dist_differ, dist_threshold, dist_side_C, dist_side_nonC = mp.computeDistDiffer(source, master.dataset.tsObjectDir, self.m)''' DiscP = self.dist_differ # CANVAS # Configire the axis looking (start) plt.setp(self.master.ax2.get_xaxis(), visible=False) self.master.ax2.spines['bottom'].set_visible(False) self.master.ax3.axis("on") # Configire the axis looking (end) x = range(len(DiscP)) self.master.ax3.set_ylabel("Discm. Profile") label = "Discm. P. of " + self.nbr_source self.master.ax3.plot(x, DiscP, linewidth=0.5, label=label) self.master.ax3.legend() self.master.canvas.draw() # show the pattern found in source TS discP_list = DiscP.tolist() index_maxValue = discP_list.index(max(discP_list)) index_end = index_maxValue + master.m source = master.source.timeseries pattern = source[index_maxValue:index_end] x_source = range(len(source)) x_pattern = range(index_maxValue, index_end) # CANVAS self.ax1 = self.master.ax1 self.ax1.clear() self.ax1.plot(x_source, source, linewidth=0.5, label="Source TS") self.ax1.plot(x_pattern, pattern, linewidth=2, color="red", label="Candidate Shaplet in "+ master.v_source.get()) self.ax1.spines['top'].set_visible(False) self.ax1.spines['right'].set_visible(False) self.ax1.set_ylabel("Source TS") self.ax1.legend(loc="upper right") self.master.canvas.draw() self.master.v_timeSMAP.set(self.SMAP_time) def extractDiscP_LB(self, master): self.master.v_timeSMAPLB.set(0) def drawShapelet(self, path, filename): testFile = pd.read_csv(path + filename, header=None) Class = testFile[0][0] shapData = testFile[1][0] shapData = shapData.strip('()').replace('[', '').replace(']', '') shapeletList = [] # shapObjectList: DD, Thresh shapObjectList = shapData.split("),(") for shapObject in shapObjectList: shap = Shapelet() shapObject = shapObject.split(',') shap.DD = float(shapObject[0]) shap.thresh = float(shapObject[1]) shap.Class = Class shap.subseq = [float(s) for s in shapObject[2:]] shapeletList.append(shap) return shapeletList def drawTS(self, path, filename): tsObjectList1 = [] tsObjectList2 = [] testFile = pd.read_csv(path + filename, header=None) tsClass1 = testFile[testFile[1] == 1] tsClass2 = testFile[testFile[1] == -1] for i in tsClass1.index: ts = timeseries() row = tsClass1.loc[i] ts.id = row[0] ts.Class = row[1] ts.seq = row[2].split(',') ts.seq = [float(val) for val in ts.seq] tsObjectList1.append(ts) for i in tsClass2.index: ts = timeseries() row = tsClass2.loc[i] ts.id = row[0] ts.Class = row[1] ts.seq = row[2].split(',') ts.seq = [float(val) for val in ts.seq] tsObjectList2.append(ts) return tsObjectList1, tsObjectList2 def showTSset(self): path_ECG = "/Users/Jingwei/Desktop/PhD_study/Done/EDBTdemo2018/SMAP_results/ECG200/TS_raw/" file_ECG = "TS.csv" path = path_ECG filename = file_ECG tsObjectC1, tsObjectC2 = self.drawTS(path, filename) self.fig = self.master.figure if self.master.v_class.get()=="1.0": self.fig.clf() self.ax1 = self.fig.add_subplot(211) self.ax2 = self.fig.add_subplot(212) input_class = self.master.v_class.get() if input_class == "1.0": self.ax1.clear() for ts in tsObjectC1[11:21]: seq = ts.seq self.ax1.set_ylabel("TS data class 1") X = range(0, len(seq)) self.ax1.plot(X, seq, color='green', linewidth=0.5) elif input_class == "-1.0": self.ax2.clear() for ts in tsObjectC2[0:10]: seq = ts.seq self.ax2.set_xlabel("index/offset") self.ax2.set_ylabel("TS data class -1.0") X = range(0, len(seq)) self.ax2.plot(X, seq, color='green', linewidth=0.5) self.master.canvas.draw() def extractShapeletCandidate(self): path_ECG = "/Users/Jingwei/Desktop/PhD_study/Done/EDBTdemo2018/SMAP_results/ECG200/Shapelets/" f1_ECG = "part-00043-956f02be-ab81-45db-9679-0bfd9150f5e8.csv" # 1 f2_ECG = "part-00013-956f02be-ab81-45db-9679-0bfd9150f5e8.csv" # -1 path = path_ECG filename1 = f1_ECG filename2 = f2_ECG self.shapeletList1 = self.drawShapelet(path, filename1) self.shapeletList2 = self.drawShapelet(path, filename2) input_k = self.master.v_k.get() input_c = self.master.v_class.get() self.fig = self.master.figure if input_c == "1.0": i = 0 for shap in self.shapeletList1[:input_k]: self.subaxe = self.fig.add_subplot(211) shapdata = shap.subseq # add a shift of 10 for shapelets X = range(10, len(shapdata)+10) self.subaxe.plot(X, shapdata, color='red', linewidth=2) i = i + 0.1 elif input_c == "-1.0": i = 0 for shap in self.shapeletList2[:input_k]: self.subaxe = self.fig.add_subplot(212) shapdata = shap.subseq X = range(0, len(shapdata)) self.subaxe.plot(X, shapdata, color='blue', linewidth=2) self.master.canvas.draw() # canvas._tkcanvas.pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=True) def extractED(self): return 0 def extractEDMatrix(self, master): self.master.v_timeUSE.set(0) def predict(self, master): #list of Shapelet from different class testdataset = master.guiFunc.testdataset nbr_testTS = master.v_testInstance.get() print("---callback predict---") print(nbr_testTS) if nbr_testTS!="select": hash_testTS = testdataset.tsNameDir[nbr_testTS] self.testTS = testdataset.tsObjectDir[hash_testTS] testTS = self.testTS.timeseries min_dist = float('inf') index_target = None predict_class = '0' match_shapelet = None print("length os shapeletList1 is " + str(len(self.shapeletList1))) for shap in self.shapeletList1 + self.shapeletList2: DP = sm.euclidean_distance_unequal_lengths(testTS, shap.subseq) DP = DP.tolist() DP_min = min(DP) if min_dist > DP_min: min_dist = DP_min index_target = DP.index(DP_min) match_shapelet = shap self.testTS = testdataset.tsObjectDir[hash_testTS] # CANVAS x = range(len(testTS)) shap_data = match_shapelet.subseq x_shap = range(index_target, index_target + len(shap_data)) self.master.figure.clf() self.ax = self.master.figure.add_subplot(111) self.ax.spines['top'].set_visible(False) self.ax.spines['right'].set_visible(False) self.ax.plot(x, testTS, linewidth=0.5, label="testing TS: " + nbr_testTS) self.ax.plot(x_shap, shap_data, linewidth=2, label="Matching Shapelet") self.ax.set_ylabel("Testing TS") self.ax.set_title("Real class: " + str(self.testTS.class_timeseries) + "; Prediction: " + str(match_shapelet.Class)) self.ax.legend(loc="upper right") self.master.canvas.draw() class Shapelet(object): def __init__(self): self.id = 0.0 self.Class = '' self.subseq = None self.DD = 0.0 self.thresh = 0.0 class timeseries(object): def __init__(self): self.id = None self.Class = '' self.seq = None
42.643902
162
0.623256
import time import tkinter as tk from tkinter import * import tkinter.filedialog as filedialog from tkinter.filedialog import askopenfilename import utils.utils as util import utils.similarity_measures as sm import SMAP.MatrixProfile as mp import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk from matplotlib.figure import Figure from matplotlib import pyplot as plt import pandas as pd import numpy as np LARGE_FONT= ("Verdana", 12) class gui_function: def __init__(self, master): self.filename = 'file name' self.training_filename = 'choose training set' self.testing_filename = 'choose testing set' self.master = master self.dataset = util.Dataset() self.testdataset = util.Dataset() self.dataset_name = None self.shapeletList1 = [] self.shapeletList2 = [] def add_dataset(self): self.dataset_name = askopenfilename(parent=self.master, title="Choose a file") array_tsdict = util.load_dataset(self.dataset_name) dir = self.dataset_name.split("/") datasetname = dir[-1] self.dataset.update(array_tsdict, datasetname) self.master.v_dsname.set(self.dataset.name) self.master.v_tslength.set(self.dataset.tslength) self.master.v_tsnbr.set(self.dataset.size) self.master.v_classnbr.set(len(self.dataset.ClassList)) self.master.show_frame(self.master.frame2, "SMAPPage") def add_testing_file(self): self.testfile_name = askopenfilename(parent=self.master, title="Choose a file") array_tsdict = util.load_dataset(self.testfile_name) dir = self.testfile_name.split("/") datasetname = dir[-1] self.testdataset.update(array_tsdict, datasetname) self.master.v_testdsname.set(self.testdataset.name) self.master.v_testtslength.set(self.testdataset.tslength) self.master.v_testtsnbr.set(self.testdataset.size) self.master.v_testclassnbr.set(len(self.testdataset.ClassList)) self.master.testdataset= self.testdataset def ShowAlgoFrame(self, algorithm): self.master.frame2_1[algorithm].tkraise() self.master.frame2_1[algorithm].grid(row=0, column=0, sticky=W) def extractDP(self, master): self.nbr_source = master.v_source.get() self.nbr_target = master.v_target.get() dataset = master.dataset hash_source = dataset.tsNameDir[self.nbr_source] hash_target = dataset.tsNameDir[self.nbr_target] self.source = dataset.tsObjectDir[hash_source] self.target = dataset.tsObjectDir[hash_target] self.m = master.v_queryL.get() index_start = master.v_queryI.get() data = self.target.timeseries index_end = index_start + self.m query = self.source.timeseries[index_start:index_end] DP = sm.euclidean_distance_unequal_lengths(data, query) plt.setp(self.master.ax2.get_xaxis(), visible=False) self.master.ax2.spines['bottom'].set_visible(False) self.master.ax3.clear() x = range(len(DP)) self.master.ax3.spines['top'].set_visible(False) self.master.ax3.spines['right'].set_visible(False) self.master.ax3.set_ylabel("Distance Profile") self.master.ax3.plot(x, DP, linewidth=0.5, label="D. P. of Query in " +self.nbr_target) self.master.ax3.legend() self.master.canvas.draw() DP_list = DP.tolist() index_inValue = DP_list.index(min(DP_list)) index_end = index_inValue + master.m NearestN = self.target.timeseries[index_inValue:index_end] x_target = range(len(self.target.timeseries)) x_NearestN = range(index_inValue, index_end) self.ax2 = self.master.ax2 self.ax2.clear() self.ax2.plot(x_target, self.target.timeseries, linewidth=0.5, label=self.nbr_target) self.ax2.plot(x_NearestN, NearestN, linewidth=2, label="Nearest Neighbor of Query") self.ax2.spines['top'].set_visible(False) self.ax2.spines['right'].set_visible(False) self.ax2.set_ylabel("Target TS") self.ax2.legend(loc="upper right") self.master.canvas.draw() def extractMP(self, master): self.nbr_source = master.v_source.get() self.nbr_target = master.v_target.get() dataset = master.dataset hash_source = dataset.tsNameDir[self.nbr_source] hash_target = dataset.tsNameDir[self.nbr_target] self.source = dataset.tsObjectDir[hash_source] self.target = dataset.tsObjectDir[hash_target] self.m = master.v_queryL.get() dp_all, MP= mp.computeMP(self.source, self.target, self.m, "mass_v2") plt.setp(self.master.ax2.get_xaxis(), visible=False) self.master.ax2.spines['bottom'].set_visible(False) self.master.ax3.clear() x = range(len(MP)) self.master.ax3.spines['top'].set_visible(False) self.master.ax3.spines['right'].set_visible(False) self.master.ax3.set_ylabel("Matrix Profile") self.master.ax3.plot(x, MP, linewidth=0.5, label="M. P. of "+self.nbr_source+" towards " +self.nbr_target) self.master.ax3.legend() self.master.canvas.draw() index_source = MP.index(min(MP)) index_source_end = index_source + self.m x_pair_source = range(index_source, index_source_end) pair_source = self.source.timeseries[index_source:index_source_end] DP = sm.euclidean_distance_unequal_lengths(self.target.timeseries, pair_source) index_target = DP.tolist().index(min(DP.tolist())) index_target_end = index_target + self.m x_pair_target = range(index_target, index_target_end) pair_target = self.target.timeseries[index_target:index_target_end] self.master.ax1.clear() x = range(len(self.source.timeseries)) self.master.ax1.spines['top'].set_visible(False) self.master.ax1.spines['right'].set_visible(False) self.master.ax1.set_ylabel("Source TS") self.master.ax1.plot(x_pair_source, pair_source, linewidth=2, color="red", label="Nearest Pair in source") self.master.ax1.plot(x, self.source.timeseries, linewidth=0.5, label=self.nbr_source) self.master.ax1.legend() self.master.canvas.draw() self.master.ax2.clear() x = range(len(self.target.timeseries)) self.master.ax2.spines['top'].set_visible(False) self.master.ax2.spines['right'].set_visible(False) self.master.ax2.set_ylabel("Target TS") self.master.ax2.plot(x_pair_target, pair_target, linewidth=2, color="red", label="Nearest Pair in target") self.master.ax2.plot(x, self.target.timeseries, linewidth=0.5, label=self.nbr_target) self.master.ax2.legend() self.master.canvas.draw() def extractLB(self): return 0 def extractRP(self, master): source = master.source input_class = str(master.v_class.get()) start = time.clock() DP_all, mp_all, self.dist_differ, dist_threshold, self.dist_side_C, self.dist_side_nonC = mp.computeDistDiffer(source, master.dataset.tsObjectDir, self.m) end = time.clock() self.SMAP_time = round(end - start, 2) if str(source.class_timeseries) == input_class: RP = self.dist_side_C else: RP = self.dist_side_nonC self.master.ax3.clear() if (self.master.ax2.get_ylabel()!="Rep. Profile"): self.master.ax2.clear() plt.setp(self.master.ax2.get_xaxis(), visible=True) self.master.ax2.spines['bottom'].set_visible(True) self.master.ax3.axis("off") x = range(len(RP)) self.master.ax2.set_ylabel("Rep. Profile") label = "Rep. P. of " + self.nbr_source + " in class " + input_class self.master.ax2.plot(x, RP, linewidth=0.5, label=label) self.master.ax2.legend() self.master.canvas.draw() self.master.ax1.clear() x = range(len(self.source.timeseries)) self.master.ax1.spines['top'].set_visible(False) self.master.ax1.spines['right'].set_visible(False) self.master.ax1.set_ylabel("Source TS") self.master.ax1.plot(x, self.source.timeseries, linewidth=0.5, label=self.nbr_source) self.master.ax1.legend() self.master.canvas.draw() def extractDiscP(self, master): DiscP = self.dist_differ plt.setp(self.master.ax2.get_xaxis(), visible=False) self.master.ax2.spines['bottom'].set_visible(False) self.master.ax3.axis("on") x = range(len(DiscP)) self.master.ax3.set_ylabel("Discm. Profile") label = "Discm. P. of " + self.nbr_source self.master.ax3.plot(x, DiscP, linewidth=0.5, label=label) self.master.ax3.legend() self.master.canvas.draw() discP_list = DiscP.tolist() index_maxValue = discP_list.index(max(discP_list)) index_end = index_maxValue + master.m source = master.source.timeseries pattern = source[index_maxValue:index_end] x_source = range(len(source)) x_pattern = range(index_maxValue, index_end) self.ax1 = self.master.ax1 self.ax1.clear() self.ax1.plot(x_source, source, linewidth=0.5, label="Source TS") self.ax1.plot(x_pattern, pattern, linewidth=2, color="red", label="Candidate Shaplet in "+ master.v_source.get()) self.ax1.spines['top'].set_visible(False) self.ax1.spines['right'].set_visible(False) self.ax1.set_ylabel("Source TS") self.ax1.legend(loc="upper right") self.master.canvas.draw() self.master.v_timeSMAP.set(self.SMAP_time) def extractDiscP_LB(self, master): self.master.v_timeSMAPLB.set(0) def drawShapelet(self, path, filename): testFile = pd.read_csv(path + filename, header=None) Class = testFile[0][0] shapData = testFile[1][0] shapData = shapData.strip('()').replace('[', '').replace(']', '') shapeletList = [] shapObjectList = shapData.split("),(") for shapObject in shapObjectList: shap = Shapelet() shapObject = shapObject.split(',') shap.DD = float(shapObject[0]) shap.thresh = float(shapObject[1]) shap.Class = Class shap.subseq = [float(s) for s in shapObject[2:]] shapeletList.append(shap) return shapeletList def drawTS(self, path, filename): tsObjectList1 = [] tsObjectList2 = [] testFile = pd.read_csv(path + filename, header=None) tsClass1 = testFile[testFile[1] == 1] tsClass2 = testFile[testFile[1] == -1] for i in tsClass1.index: ts = timeseries() row = tsClass1.loc[i] ts.id = row[0] ts.Class = row[1] ts.seq = row[2].split(',') ts.seq = [float(val) for val in ts.seq] tsObjectList1.append(ts) for i in tsClass2.index: ts = timeseries() row = tsClass2.loc[i] ts.id = row[0] ts.Class = row[1] ts.seq = row[2].split(',') ts.seq = [float(val) for val in ts.seq] tsObjectList2.append(ts) return tsObjectList1, tsObjectList2 def showTSset(self): path_ECG = "/Users/Jingwei/Desktop/PhD_study/Done/EDBTdemo2018/SMAP_results/ECG200/TS_raw/" file_ECG = "TS.csv" path = path_ECG filename = file_ECG tsObjectC1, tsObjectC2 = self.drawTS(path, filename) self.fig = self.master.figure if self.master.v_class.get()=="1.0": self.fig.clf() self.ax1 = self.fig.add_subplot(211) self.ax2 = self.fig.add_subplot(212) input_class = self.master.v_class.get() if input_class == "1.0": self.ax1.clear() for ts in tsObjectC1[11:21]: seq = ts.seq self.ax1.set_ylabel("TS data class 1") X = range(0, len(seq)) self.ax1.plot(X, seq, color='green', linewidth=0.5) elif input_class == "-1.0": self.ax2.clear() for ts in tsObjectC2[0:10]: seq = ts.seq self.ax2.set_xlabel("index/offset") self.ax2.set_ylabel("TS data class -1.0") X = range(0, len(seq)) self.ax2.plot(X, seq, color='green', linewidth=0.5) self.master.canvas.draw() def extractShapeletCandidate(self): path_ECG = "/Users/Jingwei/Desktop/PhD_study/Done/EDBTdemo2018/SMAP_results/ECG200/Shapelets/" f1_ECG = "part-00043-956f02be-ab81-45db-9679-0bfd9150f5e8.csv" f2_ECG = "part-00013-956f02be-ab81-45db-9679-0bfd9150f5e8.csv" path = path_ECG filename1 = f1_ECG filename2 = f2_ECG self.shapeletList1 = self.drawShapelet(path, filename1) self.shapeletList2 = self.drawShapelet(path, filename2) input_k = self.master.v_k.get() input_c = self.master.v_class.get() self.fig = self.master.figure if input_c == "1.0": i = 0 for shap in self.shapeletList1[:input_k]: self.subaxe = self.fig.add_subplot(211) shapdata = shap.subseq X = range(10, len(shapdata)+10) self.subaxe.plot(X, shapdata, color='red', linewidth=2) i = i + 0.1 elif input_c == "-1.0": i = 0 for shap in self.shapeletList2[:input_k]: self.subaxe = self.fig.add_subplot(212) shapdata = shap.subseq X = range(0, len(shapdata)) self.subaxe.plot(X, shapdata, color='blue', linewidth=2) self.master.canvas.draw() def extractED(self): return 0 def extractEDMatrix(self, master): self.master.v_timeUSE.set(0) def predict(self, master): testdataset = master.guiFunc.testdataset nbr_testTS = master.v_testInstance.get() print("---callback predict---") print(nbr_testTS) if nbr_testTS!="select": hash_testTS = testdataset.tsNameDir[nbr_testTS] self.testTS = testdataset.tsObjectDir[hash_testTS] testTS = self.testTS.timeseries min_dist = float('inf') index_target = None predict_class = '0' match_shapelet = None print("length os shapeletList1 is " + str(len(self.shapeletList1))) for shap in self.shapeletList1 + self.shapeletList2: DP = sm.euclidean_distance_unequal_lengths(testTS, shap.subseq) DP = DP.tolist() DP_min = min(DP) if min_dist > DP_min: min_dist = DP_min index_target = DP.index(DP_min) match_shapelet = shap self.testTS = testdataset.tsObjectDir[hash_testTS] x = range(len(testTS)) shap_data = match_shapelet.subseq x_shap = range(index_target, index_target + len(shap_data)) self.master.figure.clf() self.ax = self.master.figure.add_subplot(111) self.ax.spines['top'].set_visible(False) self.ax.spines['right'].set_visible(False) self.ax.plot(x, testTS, linewidth=0.5, label="testing TS: " + nbr_testTS) self.ax.plot(x_shap, shap_data, linewidth=2, label="Matching Shapelet") self.ax.set_ylabel("Testing TS") self.ax.set_title("Real class: " + str(self.testTS.class_timeseries) + "; Prediction: " + str(match_shapelet.Class)) self.ax.legend(loc="upper right") self.master.canvas.draw() class Shapelet(object): def __init__(self): self.id = 0.0 self.Class = '' self.subseq = None self.DD = 0.0 self.thresh = 0.0 class timeseries(object): def __init__(self): self.id = None self.Class = '' self.seq = None
true
true
f7257b07ee9ab3353bab98ac28e4ae6d47c6bf1c
2,171
py
Python
cifar10/models/repnet.py
NNHieu/loss-landscape
dfe517f23993ffbafea99272026d09e074e50b4f
[ "MIT" ]
null
null
null
cifar10/models/repnet.py
NNHieu/loss-landscape
dfe517f23993ffbafea99272026d09e074e50b4f
[ "MIT" ]
null
null
null
cifar10/models/repnet.py
NNHieu/loss-landscape
dfe517f23993ffbafea99272026d09e074e50b4f
[ "MIT" ]
null
null
null
import torch import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt import torch.autograd as autograd from torchvision import datasets, transforms from torch.utils.data import DataLoader import torch.optim as optim import os import argparse class ResNetLayer(nn.Module): def __init__(self, n_channels, n_inner_channels, kernel_size=3, num_groups=8): super().__init__() self.conv1 = nn.Conv2d(n_channels, n_inner_channels, kernel_size, padding=kernel_size//2, bias=False) self.conv2 = nn.Conv2d(n_inner_channels, n_channels, kernel_size, padding=kernel_size//2, bias=False) self.norm1 = nn.GroupNorm(num_groups, n_inner_channels) self.norm2 = nn.GroupNorm(num_groups, n_channels) self.norm3 = nn.GroupNorm(num_groups, n_channels) self.conv1.weight.data.normal_(0, 0.01) self.conv2.weight.data.normal_(0, 0.01) def forward(self, z, x): if z is None: y = self.norm1(F.relu(self.conv1(x))) return self.norm3(F.relu(x + self.norm2(self.conv2(y)))) else: y = self.norm1(F.relu(self.conv1(z))) return self.norm3(F.relu(z + self.norm2(x + self.conv2(y)))) class RepeatConvLayer(nn.Module): def __init__(self, f, num_repeat): super().__init__() self.f = f self.num_repeat = num_repeat def forward(self, x): z = self.f(None, x) for i in range(self.num_repeat): z = self.f(z, x) return z def repeatNet(num_repeat): chan = 48 f = ResNetLayer(chan, 64, kernel_size=3) model = nn.Sequential(nn.Conv2d(3,chan, kernel_size=3, bias=True, padding=1), nn.BatchNorm2d(chan), RepeatConvLayer(f, num_repeat), nn.BatchNorm2d(chan), nn.AvgPool2d(8,8), nn.Flatten(), nn.Linear(chan*4*4,10)) return model def repeatNet5(): return repeatNet(5) def repeatNet10(): return repeatNet(10) def repeatNet17(): return repeatNet(17)
30.577465
109
0.607094
import torch import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt import torch.autograd as autograd from torchvision import datasets, transforms from torch.utils.data import DataLoader import torch.optim as optim import os import argparse class ResNetLayer(nn.Module): def __init__(self, n_channels, n_inner_channels, kernel_size=3, num_groups=8): super().__init__() self.conv1 = nn.Conv2d(n_channels, n_inner_channels, kernel_size, padding=kernel_size//2, bias=False) self.conv2 = nn.Conv2d(n_inner_channels, n_channels, kernel_size, padding=kernel_size//2, bias=False) self.norm1 = nn.GroupNorm(num_groups, n_inner_channels) self.norm2 = nn.GroupNorm(num_groups, n_channels) self.norm3 = nn.GroupNorm(num_groups, n_channels) self.conv1.weight.data.normal_(0, 0.01) self.conv2.weight.data.normal_(0, 0.01) def forward(self, z, x): if z is None: y = self.norm1(F.relu(self.conv1(x))) return self.norm3(F.relu(x + self.norm2(self.conv2(y)))) else: y = self.norm1(F.relu(self.conv1(z))) return self.norm3(F.relu(z + self.norm2(x + self.conv2(y)))) class RepeatConvLayer(nn.Module): def __init__(self, f, num_repeat): super().__init__() self.f = f self.num_repeat = num_repeat def forward(self, x): z = self.f(None, x) for i in range(self.num_repeat): z = self.f(z, x) return z def repeatNet(num_repeat): chan = 48 f = ResNetLayer(chan, 64, kernel_size=3) model = nn.Sequential(nn.Conv2d(3,chan, kernel_size=3, bias=True, padding=1), nn.BatchNorm2d(chan), RepeatConvLayer(f, num_repeat), nn.BatchNorm2d(chan), nn.AvgPool2d(8,8), nn.Flatten(), nn.Linear(chan*4*4,10)) return model def repeatNet5(): return repeatNet(5) def repeatNet10(): return repeatNet(10) def repeatNet17(): return repeatNet(17)
true
true
f7257b2056fac589a4b126844ed598c5e63b20c6
635
py
Python
manage.py
nrsharip/iss-web
e8ca66ade3933dfac4795ba7c44e067c26a079e2
[ "MIT" ]
1
2020-09-08T21:47:50.000Z
2020-09-08T21:47:50.000Z
manage.py
nrsharip/iss-web
e8ca66ade3933dfac4795ba7c44e067c26a079e2
[ "MIT" ]
null
null
null
manage.py
nrsharip/iss-web
e8ca66ade3933dfac4795ba7c44e067c26a079e2
[ "MIT" ]
null
null
null
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'web_server_moex.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
28.863636
79
0.686614
import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'web_server_moex.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
true
true
f7257b772a4fb5328778dcbc7b3b0d836de83e58
20,431
py
Python
beta/spreadtrading/stEngine.py
black0144/vnpy
0d0ea30dad14a0150f7500ff9a62528030321426
[ "MIT" ]
18
2019-02-21T05:42:41.000Z
2022-03-31T10:17:51.000Z
beta/spreadtrading/stEngine.py
black0144/vnpy
0d0ea30dad14a0150f7500ff9a62528030321426
[ "MIT" ]
1
2018-06-12T10:08:24.000Z
2018-06-12T10:08:24.000Z
beta/spreadtrading/stEngine.py
black0144/vnpy
0d0ea30dad14a0150f7500ff9a62528030321426
[ "MIT" ]
5
2017-12-20T09:57:17.000Z
2021-08-01T19:47:14.000Z
# encoding: UTF-8 import json import traceback import shelve import parser import re from vnpy.event import Event from vnpy.trader.vtFunction import getJsonPath, getTempPath from vnpy.trader.vtEvent import (EVENT_TICK, EVENT_TRADE, EVENT_POSITION, EVENT_TIMER, EVENT_ORDER) from vnpy.trader.vtObject import (VtSubscribeReq, VtOrderReq, VtCancelOrderReq, VtLogData) from vnpy.trader.vtConstant import (DIRECTION_LONG, DIRECTION_SHORT, OFFSET_OPEN, OFFSET_CLOSE, PRICETYPE_LIMITPRICE) from .stBase import (StLeg, StSpread, EVENT_SPREADTRADING_TICK, EVENT_SPREADTRADING_POS, EVENT_SPREADTRADING_LOG, EVENT_SPREADTRADING_ALGO, EVENT_SPREADTRADING_ALGOLOG) from .stAlgo import SniperAlgo ######################################################################## class StDataEngine(object): """价差数据计算引擎""" settingFileName = 'ST_setting.json' settingFilePath = getJsonPath(settingFileName, __file__) #---------------------------------------------------------------------- def __init__(self, mainEngine, eventEngine): """Constructor""" self.mainEngine = mainEngine self.eventEngine = eventEngine # 腿、价差相关字典 self.legDict = {} # vtSymbol:StLeg self.spreadDict = {} # name:StSpread self.vtSymbolSpreadDict = {} # vtSymbol:StSpread self.registerEvent() #---------------------------------------------------------------------- def loadSetting(self): """加载配置""" try: with open(self.settingFilePath) as f: l = json.load(f) for setting in l: result, msg = self.createSpread(setting) self.writeLog(msg) self.writeLog(u'价差配置加载完成') except: content = u'价差配置加载出错,原因:' + traceback.format_exc() self.writeLog(content) #---------------------------------------------------------------------- def saveSetting(self): """保存配置""" with open(self.settingFilePath) as f: pass #---------------------------------------------------------------------- def createSpread(self, setting): """创建价差""" result = False msg = '' # 检查价差重名 if setting['name'] in self.spreadDict: msg = u'%s价差存在重名' %setting['name'] return result, msg # 检查腿是否已使用 l = [] l.append(setting['activeLeg']['vtSymbol']) for d in setting['passiveLegs']: l.append(d['vtSymbol']) for vtSymbol in l: if vtSymbol in self.vtSymbolSpreadDict: existingSpread = self.vtSymbolSpreadDict[vtSymbol] msg = u'%s合约已经存在于%s价差中' %(vtSymbol, existingSpread.name) return result, msg # 创建价差 spread = StSpread() spread.name = setting['name'] spread.formula = setting['formula'] formula = spread.formula if not re.match("[0-9A-Z\/\+\-\*\(\) ].*", formula) : msg = u'%s价差存在公式问题请重新编写 %s' % (setting['name'] , spread.formula) return result, msg try : spread.code = parser.expr(formula).compile() except : msg = u'%s价差存在公式问题请重新编写 %s' % (setting['name'] , spread.formula) return result, msg self.spreadDict[spread.name] = spread # 创建主动腿 activeSetting = setting['activeLeg'] activeLeg = StLeg() activeLeg.vtSymbol = str(activeSetting['vtSymbol']) activeLeg.ratio = float(activeSetting['ratio']) activeLeg.payup = int(activeSetting['payup']) activeLeg.legname = str(activeSetting['legname']) spread.addActiveLeg(activeLeg) self.legDict[activeLeg.vtSymbol] = activeLeg self.vtSymbolSpreadDict[activeLeg.vtSymbol] = spread self.subscribeMarketData(activeLeg.vtSymbol) # 创建被动腿 passiveSettingList = setting['passiveLegs'] passiveLegList = [] for d in passiveSettingList: passiveLeg = StLeg() passiveLeg.vtSymbol = str(d['vtSymbol']) passiveLeg.ratio = float(d['ratio']) passiveLeg.payup = int(d['payup']) passiveLeg.legname = str(d['legname']) spread.addPassiveLeg(passiveLeg) self.legDict[passiveLeg.vtSymbol] = passiveLeg self.vtSymbolSpreadDict[passiveLeg.vtSymbol] = spread self.subscribeMarketData(passiveLeg.vtSymbol) # 初始化价差 spread.initSpread() self.putSpreadTickEvent(spread) self.putSpreadPosEvent(spread) # 返回结果 result = True msg = u'%s价差创建成功' %spread.name return result, msg #---------------------------------------------------------------------- def processTickEvent(self, event): """处理行情推送""" # 检查行情是否需要处理 tick = event.dict_['data'] if tick.vtSymbol not in self.legDict: return # 更新腿价格 leg = self.legDict[tick.vtSymbol] leg.bidPrice = tick.bidPrice1 leg.askPrice = tick.askPrice1 leg.bidVolume = tick.bidVolume1 leg.askVolume = tick.askVolume1 # 更新价差价格 spread = self.vtSymbolSpreadDict[tick.vtSymbol] spread.calculatePrice() # 发出事件 self.putSpreadTickEvent(spread) #---------------------------------------------------------------------- def putSpreadTickEvent(self, spread): """发出价差行情更新事件""" event1 = Event(EVENT_SPREADTRADING_TICK+spread.name) event1.dict_['data'] = spread self.eventEngine.put(event1) event2 = Event(EVENT_SPREADTRADING_TICK) event2.dict_['data'] = spread self.eventEngine.put(event2) #---------------------------------------------------------------------- def processTradeEvent(self, event): """处理成交推送""" # 检查成交是否需要处理 trade = event.dict_['data'] if trade.vtSymbol not in self.legDict: return # 更新腿持仓 leg = self.legDict[trade.vtSymbol] direction = trade.direction offset = trade.offset if direction == DIRECTION_LONG: if offset == OFFSET_OPEN: leg.longPos += trade.volume else: leg.shortPos -= trade.volume else: if offset == OFFSET_OPEN: leg.shortPos += trade.volume else: leg.longPos -= trade.volume leg.netPos = leg.longPos - leg.shortPos # 更新价差持仓 spread = self.vtSymbolSpreadDict[trade.vtSymbol] spread.calculatePos() # 推送价差持仓更新 event1 = Event(EVENT_SPREADTRADING_POS+spread.name) event1.dict_['data'] = spread self.eventEngine.put(event1) event2 = Event(EVENT_SPREADTRADING_POS) event2.dict_['data'] = spread self.eventEngine.put(event2) #---------------------------------------------------------------------- def processPosEvent(self, event): """处理持仓推送""" # 检查持仓是否需要处理 pos = event.dict_['data'] if pos.vtSymbol not in self.legDict: return # 更新腿持仓 leg = self.legDict[pos.vtSymbol] direction = pos.direction if direction == DIRECTION_LONG: leg.longPos = pos.position else: leg.shortPos = pos.position leg.netPos = leg.longPos - leg.shortPos # 更新价差持仓 spread = self.vtSymbolSpreadDict[pos.vtSymbol] spread.calculatePos() # 推送价差持仓更新 self.putSpreadPosEvent(spread) #---------------------------------------------------------------------- def putSpreadPosEvent(self, spread): """发出价差持仓事件""" event1 = Event(EVENT_SPREADTRADING_POS+spread.name) event1.dict_['data'] = spread self.eventEngine.put(event1) event2 = Event(EVENT_SPREADTRADING_POS) event2.dict_['data'] = spread self.eventEngine.put(event2) #---------------------------------------------------------------------- def registerEvent(self): """""" self.eventEngine.register(EVENT_TICK, self.processTickEvent) self.eventEngine.register(EVENT_TRADE, self.processTradeEvent) self.eventEngine.register(EVENT_POSITION, self.processPosEvent) #---------------------------------------------------------------------- def subscribeMarketData(self, vtSymbol): """订阅行情""" contract = self.mainEngine.getContract(vtSymbol) if not contract: self.writeLog(u'订阅行情失败,找不到该合约%s' %vtSymbol) return req = VtSubscribeReq() req.symbol = contract.symbol req.exchange = contract.exchange self.mainEngine.subscribe(req, contract.gatewayName) #---------------------------------------------------------------------- def writeLog(self, content): """发出日志""" log = VtLogData() log.logContent = content event = Event(EVENT_SPREADTRADING_LOG) event.dict_['data'] = log self.eventEngine.put(event) #---------------------------------------------------------------------- def getAllSpreads(self): """获取所有的价差""" return self.spreadDict.values() ######################################################################## class StAlgoEngine(object): """价差算法交易引擎""" algoFileName = 'SpreadTradingAlgo.vt' algoFilePath = getTempPath(algoFileName) #---------------------------------------------------------------------- def __init__(self, dataEngine, mainEngine, eventEngine): """Constructor""" self.dataEngine = dataEngine self.mainEngine = mainEngine self.eventEngine = eventEngine self.algoDict = {} # spreadName:algo self.vtSymbolAlgoDict = {} # vtSymbol:algo self.registerEvent() #---------------------------------------------------------------------- def registerEvent(self): """注册事件监听""" self.eventEngine.register(EVENT_SPREADTRADING_TICK, self.processSpreadTickEvent) self.eventEngine.register(EVENT_SPREADTRADING_POS, self.processSpreadPosEvent) self.eventEngine.register(EVENT_TRADE, self.processTradeEvent) self.eventEngine.register(EVENT_ORDER, self.processOrderEvent) self.eventEngine.register(EVENT_TIMER, self.processTimerEvent) #---------------------------------------------------------------------- def processSpreadTickEvent(self, event): """处理价差行情事件""" spread = event.dict_['data'] algo = self.algoDict.get(spread.name, None) if algo: algo.updateSpreadTick(spread) #---------------------------------------------------------------------- def processSpreadPosEvent(self, event): """处理价差持仓事件""" spread = event.dict_['data'] algo = self.algoDict.get(spread.name, None) if algo: algo.updateSpreadPos(spread) #---------------------------------------------------------------------- def processTradeEvent(self, event): """处理成交事件""" trade = event.dict_['data'] algo = self.vtSymbolAlgoDict.get(trade.vtSymbol, None) if algo: algo.updateTrade(trade) #---------------------------------------------------------------------- def processOrderEvent(self, event): """处理委托事件""" order = event.dict_['data'] algo = self.vtSymbolAlgoDict.get(order.vtSymbol, None) if algo: algo.updateOrder(order) #---------------------------------------------------------------------- def processTimerEvent(self, event): """""" for algo in self.algoDict.values(): algo.updateTimer() #---------------------------------------------------------------------- def sendOrder(self, vtSymbol, direction, offset, price, volume, payup=0): """发单""" contract = self.mainEngine.getContract(vtSymbol) if not contract: return '' req = VtOrderReq() req.symbol = contract.symbol req.exchange = contract.exchange req.vtSymbol = contract.vtSymbol req.direction = direction req.offset = offset req.volume = int(volume) req.priceType = PRICETYPE_LIMITPRICE if direction == DIRECTION_LONG: req.price = price + payup * contract.priceTick else: req.price = price - payup * contract.priceTick # 委托转换 reqList = self.mainEngine.convertOrderReq(req) vtOrderIDList = [] for req in reqList: vtOrderID = self.mainEngine.sendOrder(req, contract.gatewayName) vtOrderIDList.append(vtOrderID) return vtOrderIDList #---------------------------------------------------------------------- def cancelOrder(self, vtOrderID): """撤单""" order = self.mainEngine.getOrder(vtOrderID) if not order: return req = VtCancelOrderReq() req.symbol = order.symbol req.exchange = order.exchange req.frontID = order.frontID req.sessionID = order.sessionID req.orderID = order.orderID self.mainEngine.cancelOrder(req, order.gatewayName) #---------------------------------------------------------------------- def buy(self, vtSymbol, price, volume, payup=0): """买入""" l = self.sendOrder(vtSymbol, DIRECTION_LONG, OFFSET_OPEN, price, volume, payup) return l #---------------------------------------------------------------------- def sell(self, vtSymbol, price, volume, payup=0): """卖出""" l = self.sendOrder(vtSymbol, DIRECTION_SHORT, OFFSET_CLOSE, price, volume, payup) return l #---------------------------------------------------------------------- def short(self, vtSymbol, price, volume, payup=0): """卖空""" l = self.sendOrder(vtSymbol, DIRECTION_SHORT, OFFSET_OPEN, price, volume, payup) return l #---------------------------------------------------------------------- def cover(self, vtSymbol, price, volume, payup=0): """平空""" l = self.sendOrder(vtSymbol, DIRECTION_LONG, OFFSET_CLOSE, price, volume, payup) return l #---------------------------------------------------------------------- def putAlgoEvent(self, algo): """发出算法状态更新事件""" event = Event(EVENT_SPREADTRADING_ALGO+algo.name) self.eventEngine.put(event) #---------------------------------------------------------------------- def writeLog(self, content): """输出日志""" log = VtLogData() log.logContent = content event = Event(EVENT_SPREADTRADING_ALGOLOG) event.dict_['data'] = log self.eventEngine.put(event) #---------------------------------------------------------------------- def saveSetting(self): """保存算法配置""" setting = {} for algo in self.algoDict.values(): setting[algo.spreadName] = algo.getAlgoParams() f = shelve.open(self.algoFilePath) f['setting'] = setting f.close() #---------------------------------------------------------------------- def loadSetting(self): """加载算法配置""" # 创建算法对象 l = self.dataEngine.getAllSpreads() for spread in l: algo = SniperAlgo(self, spread) self.algoDict[spread.name] = algo # 保存腿代码和算法对象的映射 for leg in spread.allLegs: self.vtSymbolAlgoDict[leg.vtSymbol] = algo # 加载配置 f = shelve.open(self.algoFilePath) setting = f.get('setting', None) f.close() if not setting: return for algo in self.algoDict.values(): if algo.spreadName in setting: d = setting[algo.spreadName] algo.setAlgoParams(d) #---------------------------------------------------------------------- def stopAll(self): """停止全部算法""" for algo in self.algoDict.values(): algo.stop() #---------------------------------------------------------------------- def startAlgo(self, spreadName): """启动算法""" algo = self.algoDict[spreadName] algoActive = algo.start() return algoActive #---------------------------------------------------------------------- def stopAlgo(self, spreadName): """停止算法""" algo = self.algoDict[spreadName] algoActive = algo.stop() return algoActive #---------------------------------------------------------------------- def getAllAlgoParams(self): """获取所有算法的参数""" return [algo.getAlgoParams() for algo in self.algoDict.values()] #---------------------------------------------------------------------- def setAlgoBuyPrice(self, spreadName, buyPrice): """设置算法买开价格""" algo = self.algoDict[spreadName] algo.setBuyPrice(buyPrice) #---------------------------------------------------------------------- def setAlgoSellPrice(self, spreadName, sellPrice): """设置算法卖平价格""" algo = self.algoDict[spreadName] algo.setSellPrice(sellPrice) #---------------------------------------------------------------------- def setAlgoShortPrice(self, spreadName, shortPrice): """设置算法卖开价格""" algo = self.algoDict[spreadName] algo.setShortPrice(shortPrice) #---------------------------------------------------------------------- def setAlgoCoverPrice(self, spreadName, coverPrice): """设置算法买平价格""" algo = self.algoDict[spreadName] algo.setCoverPrice(coverPrice) #---------------------------------------------------------------------- def setAlgoMode(self, spreadName, mode): """设置算法工作模式""" algo = self.algoDict[spreadName] algo.setMode(mode) #---------------------------------------------------------------------- def setAlgoMaxOrderSize(self, spreadName, maxOrderSize): """设置算法单笔委托限制""" algo = self.algoDict[spreadName] algo.setMaxOrderSize(maxOrderSize) #---------------------------------------------------------------------- def setAlgoMaxPosSize(self, spreadName, maxPosSize): """设置算法持仓限制""" algo = self.algoDict[spreadName] algo.setMaxPosSize(maxPosSize) ######################################################################## class StEngine(object): """价差引擎""" #---------------------------------------------------------------------- def __init__(self, mainEngine, eventEngine): """Constructor""" self.mainEngine = mainEngine self.eventEngine = eventEngine self.dataEngine = StDataEngine(mainEngine, eventEngine) self.algoEngine = StAlgoEngine(self.dataEngine, mainEngine, eventEngine) #---------------------------------------------------------------------- def init(self): """初始化""" self.dataEngine.loadSetting() self.algoEngine.loadSetting() #---------------------------------------------------------------------- def stop(self): """停止""" self.dataEngine.saveSetting() self.algoEngine.stopAll() self.algoEngine.saveSetting()
34.805792
89
0.467623
import json import traceback import shelve import parser import re from vnpy.event import Event from vnpy.trader.vtFunction import getJsonPath, getTempPath from vnpy.trader.vtEvent import (EVENT_TICK, EVENT_TRADE, EVENT_POSITION, EVENT_TIMER, EVENT_ORDER) from vnpy.trader.vtObject import (VtSubscribeReq, VtOrderReq, VtCancelOrderReq, VtLogData) from vnpy.trader.vtConstant import (DIRECTION_LONG, DIRECTION_SHORT, OFFSET_OPEN, OFFSET_CLOSE, PRICETYPE_LIMITPRICE) from .stBase import (StLeg, StSpread, EVENT_SPREADTRADING_TICK, EVENT_SPREADTRADING_POS, EVENT_SPREADTRADING_LOG, EVENT_SPREADTRADING_ALGO, EVENT_SPREADTRADING_ALGOLOG) from .stAlgo import SniperAlgo ctiveLeg.legname = str(activeSetting['legname']) spread.addActiveLeg(activeLeg) self.legDict[activeLeg.vtSymbol] = activeLeg self.vtSymbolSpreadDict[activeLeg.vtSymbol] = spread self.subscribeMarketData(activeLeg.vtSymbol) passiveSettingList = setting['passiveLegs'] passiveLegList = [] for d in passiveSettingList: passiveLeg = StLeg() passiveLeg.vtSymbol = str(d['vtSymbol']) passiveLeg.ratio = float(d['ratio']) passiveLeg.payup = int(d['payup']) passiveLeg.legname = str(d['legname']) spread.addPassiveLeg(passiveLeg) self.legDict[passiveLeg.vtSymbol] = passiveLeg self.vtSymbolSpreadDict[passiveLeg.vtSymbol] = spread self.subscribeMarketData(passiveLeg.vtSymbol) spread.initSpread() self.putSpreadTickEvent(spread) self.putSpreadPosEvent(spread) result = True msg = u'%s价差创建成功' %spread.name return result, msg def processTickEvent(self, event): tick = event.dict_['data'] if tick.vtSymbol not in self.legDict: return leg = self.legDict[tick.vtSymbol] leg.bidPrice = tick.bidPrice1 leg.askPrice = tick.askPrice1 leg.bidVolume = tick.bidVolume1 leg.askVolume = tick.askVolume1 spread = self.vtSymbolSpreadDict[tick.vtSymbol] spread.calculatePrice() self.putSpreadTickEvent(spread) def putSpreadTickEvent(self, spread): event1 = Event(EVENT_SPREADTRADING_TICK+spread.name) event1.dict_['data'] = spread self.eventEngine.put(event1) event2 = Event(EVENT_SPREADTRADING_TICK) event2.dict_['data'] = spread self.eventEngine.put(event2) def processTradeEvent(self, event): trade = event.dict_['data'] if trade.vtSymbol not in self.legDict: return leg = self.legDict[trade.vtSymbol] direction = trade.direction offset = trade.offset if direction == DIRECTION_LONG: if offset == OFFSET_OPEN: leg.longPos += trade.volume else: leg.shortPos -= trade.volume else: if offset == OFFSET_OPEN: leg.shortPos += trade.volume else: leg.longPos -= trade.volume leg.netPos = leg.longPos - leg.shortPos spread = self.vtSymbolSpreadDict[trade.vtSymbol] spread.calculatePos() event1 = Event(EVENT_SPREADTRADING_POS+spread.name) event1.dict_['data'] = spread self.eventEngine.put(event1) event2 = Event(EVENT_SPREADTRADING_POS) event2.dict_['data'] = spread self.eventEngine.put(event2) def processPosEvent(self, event): pos = event.dict_['data'] if pos.vtSymbol not in self.legDict: return leg = self.legDict[pos.vtSymbol] direction = pos.direction if direction == DIRECTION_LONG: leg.longPos = pos.position else: leg.shortPos = pos.position leg.netPos = leg.longPos - leg.shortPos spread = self.vtSymbolSpreadDict[pos.vtSymbol] spread.calculatePos() self.putSpreadPosEvent(spread) def putSpreadPosEvent(self, spread): event1 = Event(EVENT_SPREADTRADING_POS+spread.name) event1.dict_['data'] = spread self.eventEngine.put(event1) event2 = Event(EVENT_SPREADTRADING_POS) event2.dict_['data'] = spread self.eventEngine.put(event2) def registerEvent(self): self.eventEngine.register(EVENT_TICK, self.processTickEvent) self.eventEngine.register(EVENT_TRADE, self.processTradeEvent) self.eventEngine.register(EVENT_POSITION, self.processPosEvent) def subscribeMarketData(self, vtSymbol): contract = self.mainEngine.getContract(vtSymbol) if not contract: self.writeLog(u'订阅行情失败,找不到该合约%s' %vtSymbol) return req = VtSubscribeReq() req.symbol = contract.symbol req.exchange = contract.exchange self.mainEngine.subscribe(req, contract.gatewayName) def writeLog(self, content): log = VtLogData() log.logContent = content event = Event(EVENT_SPREADTRADING_LOG) event.dict_['data'] = log self.eventEngine.put(event) def getAllSpreads(self): return self.spreadDict.values() q) vtOrderIDList = [] for req in reqList: vtOrderID = self.mainEngine.sendOrder(req, contract.gatewayName) vtOrderIDList.append(vtOrderID) return vtOrderIDList def cancelOrder(self, vtOrderID): order = self.mainEngine.getOrder(vtOrderID) if not order: return req = VtCancelOrderReq() req.symbol = order.symbol req.exchange = order.exchange req.frontID = order.frontID req.sessionID = order.sessionID req.orderID = order.orderID self.mainEngine.cancelOrder(req, order.gatewayName) def buy(self, vtSymbol, price, volume, payup=0): l = self.sendOrder(vtSymbol, DIRECTION_LONG, OFFSET_OPEN, price, volume, payup) return l def sell(self, vtSymbol, price, volume, payup=0): l = self.sendOrder(vtSymbol, DIRECTION_SHORT, OFFSET_CLOSE, price, volume, payup) return l def short(self, vtSymbol, price, volume, payup=0): l = self.sendOrder(vtSymbol, DIRECTION_SHORT, OFFSET_OPEN, price, volume, payup) return l def cover(self, vtSymbol, price, volume, payup=0): l = self.sendOrder(vtSymbol, DIRECTION_LONG, OFFSET_CLOSE, price, volume, payup) return l def putAlgoEvent(self, algo): event = Event(EVENT_SPREADTRADING_ALGO+algo.name) self.eventEngine.put(event) def writeLog(self, content): log = VtLogData() log.logContent = content event = Event(EVENT_SPREADTRADING_ALGOLOG) event.dict_['data'] = log self.eventEngine.put(event) def saveSetting(self): setting = {} for algo in self.algoDict.values(): setting[algo.spreadName] = algo.getAlgoParams() f = shelve.open(self.algoFilePath) f['setting'] = setting f.close() def loadSetting(self): l = self.dataEngine.getAllSpreads() for spread in l: algo = SniperAlgo(self, spread) self.algoDict[spread.name] = algo for leg in spread.allLegs: self.vtSymbolAlgoDict[leg.vtSymbol] = algo f = shelve.open(self.algoFilePath) setting = f.get('setting', None) f.close() if not setting: return for algo in self.algoDict.values(): if algo.spreadName in setting: d = setting[algo.spreadName] algo.setAlgoParams(d) def stopAll(self): for algo in self.algoDict.values(): algo.stop() def startAlgo(self, spreadName): algo = self.algoDict[spreadName] algoActive = algo.start() return algoActive def stopAlgo(self, spreadName): algo = self.algoDict[spreadName] algoActive = algo.stop() return algoActive def getAllAlgoParams(self): return [algo.getAlgoParams() for algo in self.algoDict.values()] def setAlgoBuyPrice(self, spreadName, buyPrice): algo = self.algoDict[spreadName] algo.setBuyPrice(buyPrice) def setAlgoSellPrice(self, spreadName, sellPrice): algo = self.algoDict[spreadName] algo.setSellPrice(sellPrice) def setAlgoShortPrice(self, spreadName, shortPrice): algo = self.algoDict[spreadName] algo.setShortPrice(shortPrice) def setAlgoCoverPrice(self, spreadName, coverPrice): algo = self.algoDict[spreadName] algo.setCoverPrice(coverPrice) def setAlgoMode(self, spreadName, mode): algo = self.algoDict[spreadName] algo.setMode(mode) def setAlgoMaxOrderSize(self, spreadName, maxOrderSize): algo = self.algoDict[spreadName] algo.setMaxOrderSize(maxOrderSize) def setAlgoMaxPosSize(self, spreadName, maxPosSize): algo = self.algoDict[spreadName] algo.setMaxPosSize(maxPosSize)
true
true
f7257c269b0dd8b39aab1647dd5c4b9c17e4563f
13,360
py
Python
server/models/postgis/user.py
rustyb/osm-ireland-tasking-manager
958c232ba50ca02e5adbc7541a4b9efa7186bfdc
[ "BSD-2-Clause" ]
null
null
null
server/models/postgis/user.py
rustyb/osm-ireland-tasking-manager
958c232ba50ca02e5adbc7541a4b9efa7186bfdc
[ "BSD-2-Clause" ]
4
2020-03-24T17:47:26.000Z
2021-06-02T00:32:15.000Z
server/models/postgis/user.py
rustyb/osm-ireland-tasking-manager
958c232ba50ca02e5adbc7541a4b9efa7186bfdc
[ "BSD-2-Clause" ]
1
2021-01-30T20:12:18.000Z
2021-01-30T20:12:18.000Z
import geojson import datetime import dateutil.parser from server import db from sqlalchemy import desc, text from server.models.dtos.user_dto import UserDTO, UserMappedProjectsDTO, MappedProject, UserFilterDTO, Pagination, \ UserSearchQuery, UserSearchDTO, ProjectParticipantUser, ListedUser from server.models.postgis.licenses import License, users_licenses_table from server.models.postgis.project_info import ProjectInfo from server.models.postgis.statuses import MappingLevel, ProjectStatus, UserRole from server.models.postgis.utils import NotFound, timestamp class User(db.Model): """ Describes the history associated with a task """ __tablename__ = "users" id = db.Column(db.BigInteger, primary_key=True, index=True) validation_message = db.Column(db.Boolean, default=True, nullable=False) username = db.Column(db.String, unique=True) role = db.Column(db.Integer, default=0, nullable=False) mapping_level = db.Column(db.Integer, default=1, nullable=False) projects_mapped = db.Column(db.Integer, default=1, nullable=False) tasks_mapped = db.Column(db.Integer, default=0, nullable=False) tasks_validated = db.Column(db.Integer, default=0, nullable=False) tasks_invalidated = db.Column(db.Integer, default=0, nullable=False) projects_mapped = db.Column(db.ARRAY(db.Integer)) email_address = db.Column(db.String) is_email_verified = db.Column(db.Boolean, default=False) is_expert = db.Column(db.Boolean, default=False) twitter_id = db.Column(db.String) facebook_id = db.Column(db.String) linkedin_id = db.Column(db.String) date_registered = db.Column(db.DateTime, default=timestamp) # Represents the date the user last had one of their tasks validated last_validation_date = db.Column(db.DateTime, default=timestamp) # Relationships accepted_licenses = db.relationship("License", secondary=users_licenses_table) def create(self): """ Creates and saves the current model to the DB """ db.session.add(self) db.session.commit() def save(self): db.session.commit() def get_by_id(self, user_id: int): """ Return the user for the specified id, or None if not found """ return User.query.get(user_id) def get_by_username(self, username: str): """ Return the user for the specified username, or None if not found """ return User.query.filter_by(username=username).one_or_none() def update_username(self, username: str): """ Update the username """ self.username = username db.session.commit() def update(self, user_dto: UserDTO): """ Update the user details """ self.email_address = user_dto.email_address.lower() if user_dto.email_address else None self.twitter_id = user_dto.twitter_id.lower() if user_dto.twitter_id else None self.facebook_id = user_dto.facebook_id.lower() if user_dto.facebook_id else None self.linkedin_id = user_dto.linkedin_id.lower() if user_dto.linkedin_id else None self.validation_message = user_dto.validation_message db.session.commit() def set_email_verified_status(self, is_verified: bool): """ Updates email verfied flag on successfully verified emails""" self.is_email_verified = is_verified db.session.commit() def set_is_expert(self, is_expert: bool): """ Enables or disables expert mode on the user""" self.is_expert = is_expert db.session.commit() @staticmethod def get_all_users(query: UserSearchQuery) -> UserSearchDTO: """ Search and filter all users """ # Base query that applies to all searches base = db.session.query(User.id, User.username, User.mapping_level, User.role) # Add filter to query as required if query.mapping_level: base = base.filter(User.mapping_level == MappingLevel[query.mapping_level.upper()].value) if query.username: base = base.filter(User.username.ilike(query.username.lower() + '%')) if query.role: base = base.filter(User.role == UserRole[query.role.upper()].value) results = base.order_by(User.username).paginate(query.page, 20, True) dto = UserSearchDTO() for result in results.items: listed_user = ListedUser() listed_user.id = result.id listed_user.mapping_level = MappingLevel(result.mapping_level).name listed_user.username = result.username listed_user.role = UserRole(result.role).name dto.users.append(listed_user) dto.pagination = Pagination(results) return dto @staticmethod def get_all_users_not_pagainated(): """ Get all users in DB""" return db.session.query(User.id).all() @staticmethod def filter_users(user_filter: str, project_id: int, page: int, is_project_manager:bool=False) -> UserFilterDTO: """ Finds users that matches first characters, for auto-complete. Users who have participated (mapped or validated) in the project, if given, will be returned ahead of those who have not. """ # Note that the projects_mapped column includes both mapped and validated projects. query = db.session.query(User.username, User.projects_mapped.any(project_id).label("participant")) \ .filter(User.username.ilike(user_filter.lower() + '%')) \ .order_by(desc("participant").nullslast(), User.username) if is_project_manager: query = query.filter(User.role.in_([UserRole.ADMIN.value, UserRole.PROJECT_MANAGER.value])) results = query.paginate(page, 20, True) if results.total == 0: raise NotFound() dto = UserFilterDTO() for result in results.items: dto.usernames.append(result.username) if project_id is not None: participant = ProjectParticipantUser() participant.username = result.username participant.project_id = project_id participant.is_participant = bool(result.participant) dto.users.append(participant) dto.pagination = Pagination(results) return dto @staticmethod def upsert_mapped_projects(user_id: int, project_id: int): """ Adds projects to mapped_projects if it doesn't exist """ sql = "select * from users where id = :user_id and projects_mapped @> '{{:project_id}}'" result = db.engine.execute(text(sql), user_id=user_id, project_id=project_id) if result.rowcount > 0: return # User has previously mapped this project so return sql = '''update users set projects_mapped = array_append(projects_mapped, :project_id) where id = :user_id''' db.engine.execute(text(sql), project_id=project_id, user_id=user_id) @staticmethod def get_mapped_projects(user_id: int, preferred_locale: str) -> UserMappedProjectsDTO: """ Get all projects a user has mapped on """ # This query looks scary, but we're really just creating an outer join between the query that gets the # counts of all mapped tasks and the query that gets counts of all validated tasks. This is necessary to # handle cases where users have only validated tasks on a project, or only mapped on a project. sql = '''SELECT p.id, p.status, p.default_locale, c.mapped, c.validated, st_asgeojson(p.centroid) FROM projects p, (SELECT coalesce(v.project_id, m.project_id) project_id, coalesce(v.validated, 0) validated, coalesce(m.mapped, 0) mapped FROM (SELECT t.project_id, count (t.validated_by) validated FROM tasks t WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = :user_id) AND t.validated_by = :user_id GROUP BY t.project_id, t.validated_by) v FULL OUTER JOIN (SELECT t.project_id, count(t.mapped_by) mapped FROM tasks t WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = :user_id) AND t.mapped_by = :user_id GROUP BY t.project_id, t.mapped_by) m ON v.project_id = m.project_id) c WHERE p.id = c.project_id ORDER BY p.id DESC''' results = db.engine.execute(text(sql), user_id=user_id) if results.rowcount == 0: raise NotFound() mapped_projects_dto = UserMappedProjectsDTO() for row in results: mapped_project = MappedProject() mapped_project.project_id = row[0] mapped_project.status = ProjectStatus(row[1]).name mapped_project.tasks_mapped = row[3] mapped_project.tasks_validated = row[4] mapped_project.centroid = geojson.loads(row[5]) project_info = ProjectInfo.get_dto_for_locale(row[0], preferred_locale, row[2]) mapped_project.name = project_info.name mapped_projects_dto.mapped_projects.append(mapped_project) return mapped_projects_dto def set_user_role(self, role: UserRole): """ Sets the supplied role on the user """ self.role = role.value db.session.commit() def set_mapping_level(self, level: MappingLevel): """ Sets the supplied level on the user """ self.mapping_level = level.value db.session.commit() def accept_license_terms(self, license_id: int): """ Associate the user in scope with the supplied license """ image_license = License.get_by_id(license_id) self.accepted_licenses.append(image_license) db.session.commit() def has_user_accepted_licence(self, license_id: int): """ Test to see if the user has accepted the terms of the specified license""" image_license = License.get_by_id(license_id) if image_license in self.accepted_licenses: return True return False def delete(self): """ Delete the user in scope from DB """ db.session.delete(self) db.session.commit() def as_dto(self, logged_in_username: str) -> UserDTO: """ Create DTO object from user in scope """ user_dto = UserDTO() user_dto.id = self.id user_dto.username = self.username user_dto.role = UserRole(self.role).name user_dto.mapping_level = MappingLevel(self.mapping_level).name user_dto.is_expert = self.is_expert or False user_dto.date_registered = str(self.date_registered) try: user_dto.projects_mapped = len(self.projects_mapped) # Handle users that haven't touched a project yet. except: user_dto.projects_mapped = 0 user_dto.tasks_mapped = self.tasks_mapped user_dto.tasks_validated = self.tasks_validated user_dto.tasks_invalidated = self.tasks_invalidated user_dto.twitter_id = self.twitter_id user_dto.linkedin_id = self.linkedin_id user_dto.facebook_id = self.facebook_id user_dto.validation_message = self.validation_message user_dto.total_time_spent = 0 user_dto.time_spent_mapping = 0 user_dto.time_spent_validating = 0 sql = """SELECT SUM(TO_TIMESTAMP(action_text, 'HH24:MI:SS')::TIME) FROM task_history WHERE action='LOCKED_FOR_VALIDATION' and user_id = :user_id;""" total_validation_time = db.engine.execute(text(sql), user_id=self.id) for row in total_validation_time: total_validation_time = row[0] if total_validation_time: total_validation_seconds = total_validation_time.total_seconds() user_dto.time_spent_validating = total_validation_seconds user_dto.total_time_spent += user_dto.time_spent_validating sql = """SELECT SUM(TO_TIMESTAMP(action_text, 'HH24:MI:SS')::TIME) FROM task_history WHERE action='LOCKED_FOR_MAPPING' and user_id = :user_id;""" total_mapping_time = db.engine.execute(text(sql), user_id=self.id) for row in total_mapping_time: total_mapping_time = row[0] if total_mapping_time: total_mapping_seconds = total_mapping_time.total_seconds() user_dto.time_spent_mapping = total_mapping_seconds user_dto.total_time_spent += user_dto.time_spent_mapping if self.username == logged_in_username: # Only return email address when logged in user is looking at their own profile user_dto.email_address = self.email_address user_dto.is_email_verified = self.is_email_verified return user_dto
44.385382
118
0.643114
import geojson import datetime import dateutil.parser from server import db from sqlalchemy import desc, text from server.models.dtos.user_dto import UserDTO, UserMappedProjectsDTO, MappedProject, UserFilterDTO, Pagination, \ UserSearchQuery, UserSearchDTO, ProjectParticipantUser, ListedUser from server.models.postgis.licenses import License, users_licenses_table from server.models.postgis.project_info import ProjectInfo from server.models.postgis.statuses import MappingLevel, ProjectStatus, UserRole from server.models.postgis.utils import NotFound, timestamp class User(db.Model): __tablename__ = "users" id = db.Column(db.BigInteger, primary_key=True, index=True) validation_message = db.Column(db.Boolean, default=True, nullable=False) username = db.Column(db.String, unique=True) role = db.Column(db.Integer, default=0, nullable=False) mapping_level = db.Column(db.Integer, default=1, nullable=False) projects_mapped = db.Column(db.Integer, default=1, nullable=False) tasks_mapped = db.Column(db.Integer, default=0, nullable=False) tasks_validated = db.Column(db.Integer, default=0, nullable=False) tasks_invalidated = db.Column(db.Integer, default=0, nullable=False) projects_mapped = db.Column(db.ARRAY(db.Integer)) email_address = db.Column(db.String) is_email_verified = db.Column(db.Boolean, default=False) is_expert = db.Column(db.Boolean, default=False) twitter_id = db.Column(db.String) facebook_id = db.Column(db.String) linkedin_id = db.Column(db.String) date_registered = db.Column(db.DateTime, default=timestamp) last_validation_date = db.Column(db.DateTime, default=timestamp) accepted_licenses = db.relationship("License", secondary=users_licenses_table) def create(self): db.session.add(self) db.session.commit() def save(self): db.session.commit() def get_by_id(self, user_id: int): return User.query.get(user_id) def get_by_username(self, username: str): return User.query.filter_by(username=username).one_or_none() def update_username(self, username: str): self.username = username db.session.commit() def update(self, user_dto: UserDTO): self.email_address = user_dto.email_address.lower() if user_dto.email_address else None self.twitter_id = user_dto.twitter_id.lower() if user_dto.twitter_id else None self.facebook_id = user_dto.facebook_id.lower() if user_dto.facebook_id else None self.linkedin_id = user_dto.linkedin_id.lower() if user_dto.linkedin_id else None self.validation_message = user_dto.validation_message db.session.commit() def set_email_verified_status(self, is_verified: bool): self.is_email_verified = is_verified db.session.commit() def set_is_expert(self, is_expert: bool): self.is_expert = is_expert db.session.commit() @staticmethod def get_all_users(query: UserSearchQuery) -> UserSearchDTO: base = db.session.query(User.id, User.username, User.mapping_level, User.role) if query.mapping_level: base = base.filter(User.mapping_level == MappingLevel[query.mapping_level.upper()].value) if query.username: base = base.filter(User.username.ilike(query.username.lower() + '%')) if query.role: base = base.filter(User.role == UserRole[query.role.upper()].value) results = base.order_by(User.username).paginate(query.page, 20, True) dto = UserSearchDTO() for result in results.items: listed_user = ListedUser() listed_user.id = result.id listed_user.mapping_level = MappingLevel(result.mapping_level).name listed_user.username = result.username listed_user.role = UserRole(result.role).name dto.users.append(listed_user) dto.pagination = Pagination(results) return dto @staticmethod def get_all_users_not_pagainated(): return db.session.query(User.id).all() @staticmethod def filter_users(user_filter: str, project_id: int, page: int, is_project_manager:bool=False) -> UserFilterDTO: query = db.session.query(User.username, User.projects_mapped.any(project_id).label("participant")) \ .filter(User.username.ilike(user_filter.lower() + '%')) \ .order_by(desc("participant").nullslast(), User.username) if is_project_manager: query = query.filter(User.role.in_([UserRole.ADMIN.value, UserRole.PROJECT_MANAGER.value])) results = query.paginate(page, 20, True) if results.total == 0: raise NotFound() dto = UserFilterDTO() for result in results.items: dto.usernames.append(result.username) if project_id is not None: participant = ProjectParticipantUser() participant.username = result.username participant.project_id = project_id participant.is_participant = bool(result.participant) dto.users.append(participant) dto.pagination = Pagination(results) return dto @staticmethod def upsert_mapped_projects(user_id: int, project_id: int): sql = "select * from users where id = :user_id and projects_mapped @> '{{:project_id}}'" result = db.engine.execute(text(sql), user_id=user_id, project_id=project_id) if result.rowcount > 0: return sql = '''update users set projects_mapped = array_append(projects_mapped, :project_id) where id = :user_id''' db.engine.execute(text(sql), project_id=project_id, user_id=user_id) @staticmethod def get_mapped_projects(user_id: int, preferred_locale: str) -> UserMappedProjectsDTO: # counts of all mapped tasks and the query that gets counts of all validated tasks. This is necessary to # handle cases where users have only validated tasks on a project, or only mapped on a project. sql = '''SELECT p.id, p.status, p.default_locale, c.mapped, c.validated, st_asgeojson(p.centroid) FROM projects p, (SELECT coalesce(v.project_id, m.project_id) project_id, coalesce(v.validated, 0) validated, coalesce(m.mapped, 0) mapped FROM (SELECT t.project_id, count (t.validated_by) validated FROM tasks t WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = :user_id) AND t.validated_by = :user_id GROUP BY t.project_id, t.validated_by) v FULL OUTER JOIN (SELECT t.project_id, count(t.mapped_by) mapped FROM tasks t WHERE t.project_id IN (SELECT unnest(projects_mapped) FROM users WHERE id = :user_id) AND t.mapped_by = :user_id GROUP BY t.project_id, t.mapped_by) m ON v.project_id = m.project_id) c WHERE p.id = c.project_id ORDER BY p.id DESC''' results = db.engine.execute(text(sql), user_id=user_id) if results.rowcount == 0: raise NotFound() mapped_projects_dto = UserMappedProjectsDTO() for row in results: mapped_project = MappedProject() mapped_project.project_id = row[0] mapped_project.status = ProjectStatus(row[1]).name mapped_project.tasks_mapped = row[3] mapped_project.tasks_validated = row[4] mapped_project.centroid = geojson.loads(row[5]) project_info = ProjectInfo.get_dto_for_locale(row[0], preferred_locale, row[2]) mapped_project.name = project_info.name mapped_projects_dto.mapped_projects.append(mapped_project) return mapped_projects_dto def set_user_role(self, role: UserRole): self.role = role.value db.session.commit() def set_mapping_level(self, level: MappingLevel): self.mapping_level = level.value db.session.commit() def accept_license_terms(self, license_id: int): image_license = License.get_by_id(license_id) self.accepted_licenses.append(image_license) db.session.commit() def has_user_accepted_licence(self, license_id: int): image_license = License.get_by_id(license_id) if image_license in self.accepted_licenses: return True return False def delete(self): db.session.delete(self) db.session.commit() def as_dto(self, logged_in_username: str) -> UserDTO: user_dto = UserDTO() user_dto.id = self.id user_dto.username = self.username user_dto.role = UserRole(self.role).name user_dto.mapping_level = MappingLevel(self.mapping_level).name user_dto.is_expert = self.is_expert or False user_dto.date_registered = str(self.date_registered) try: user_dto.projects_mapped = len(self.projects_mapped) # Handle users that haven't touched a project yet. except: user_dto.projects_mapped = 0 user_dto.tasks_mapped = self.tasks_mapped user_dto.tasks_validated = self.tasks_validated user_dto.tasks_invalidated = self.tasks_invalidated user_dto.twitter_id = self.twitter_id user_dto.linkedin_id = self.linkedin_id user_dto.facebook_id = self.facebook_id user_dto.validation_message = self.validation_message user_dto.total_time_spent = 0 user_dto.time_spent_mapping = 0 user_dto.time_spent_validating = 0 sql = """SELECT SUM(TO_TIMESTAMP(action_text, 'HH24:MI:SS')::TIME) FROM task_history WHERE action='LOCKED_FOR_VALIDATION' and user_id = :user_id;""" total_validation_time = db.engine.execute(text(sql), user_id=self.id) for row in total_validation_time: total_validation_time = row[0] if total_validation_time: total_validation_seconds = total_validation_time.total_seconds() user_dto.time_spent_validating = total_validation_seconds user_dto.total_time_spent += user_dto.time_spent_validating sql = """SELECT SUM(TO_TIMESTAMP(action_text, 'HH24:MI:SS')::TIME) FROM task_history WHERE action='LOCKED_FOR_MAPPING' and user_id = :user_id;""" total_mapping_time = db.engine.execute(text(sql), user_id=self.id) for row in total_mapping_time: total_mapping_time = row[0] if total_mapping_time: total_mapping_seconds = total_mapping_time.total_seconds() user_dto.time_spent_mapping = total_mapping_seconds user_dto.total_time_spent += user_dto.time_spent_mapping if self.username == logged_in_username: user_dto.email_address = self.email_address user_dto.is_email_verified = self.is_email_verified return user_dto
true
true
f7257d2547d1644fe9f677f8883223e1b992288c
7,585
py
Python
mmdet/models/detectors/maskformer.py
ayulockin/mmdetection
6b87ac22b8d9dea8cc28b9ce84909e6c311e6268
[ "Apache-2.0" ]
2
2021-11-27T03:30:42.000Z
2022-01-01T05:14:18.000Z
mmdet/models/detectors/maskformer.py
Bella-ing/mmdetection
70f6d9cfade4a2f0b198e4f64776521d181b28be
[ "Apache-2.0" ]
1
2020-05-20T08:13:44.000Z
2020-05-20T08:13:44.000Z
mmdet/models/detectors/maskformer.py
Bella-ing/mmdetection
70f6d9cfade4a2f0b198e4f64776521d181b28be
[ "Apache-2.0" ]
null
null
null
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import numpy as np from mmdet.core import INSTANCE_OFFSET from mmdet.core.visualization import imshow_det_bboxes from ..builder import DETECTORS, build_backbone, build_head, build_neck from .single_stage import SingleStageDetector @DETECTORS.register_module() class MaskFormer(SingleStageDetector): r"""Implementation of `Per-Pixel Classification is NOT All You Need for Semantic Segmentation <https://arxiv.org/pdf/2107.06278>`_.""" def __init__(self, backbone, neck=None, panoptic_head=None, train_cfg=None, test_cfg=None, init_cfg=None): super(SingleStageDetector, self).__init__(init_cfg=init_cfg) self.backbone = build_backbone(backbone) if neck is not None: self.neck = build_neck(neck) panoptic_head.update(train_cfg=train_cfg) panoptic_head.update(test_cfg=test_cfg) self.panoptic_head = build_head(panoptic_head) self.num_things_classes = self.panoptic_head.num_things_classes self.num_stuff_classes = self.panoptic_head.num_stuff_classes self.num_classes = self.panoptic_head.num_classes self.train_cfg = train_cfg self.test_cfg = test_cfg def forward_dummy(self, img, img_metas): """Used for computing network flops. See `mmdetection/tools/analysis_tools/get_flops.py` Args: img (Tensor): of shape (N, C, H, W) encoding input images. Typically these should be mean centered and std scaled. img_metas (list[Dict]): list of image info dict where each dict has: 'img_shape', 'scale_factor', 'flip', and may also contain 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'. For details on the values of these keys see `mmdet/datasets/pipelines/formatting.py:Collect`. """ super(SingleStageDetector, self).forward_train(img, img_metas) x = self.extract_feat(img) outs = self.panoptic_head(x, img_metas) return outs def forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_masks, gt_semantic_seg, gt_bboxes_ignore=None, **kargs): """ Args: img (Tensor): of shape (N, C, H, W) encoding input images. Typically these should be mean centered and std scaled. img_metas (list[Dict]): list of image info dict where each dict has: 'img_shape', 'scale_factor', 'flip', and may also contain 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'. For details on the values of these keys see `mmdet/datasets/pipelines/formatting.py:Collect`. gt_bboxes (list[Tensor]): Ground truth bboxes for each image with shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format. gt_labels (list[Tensor]): class indices corresponding to each box. gt_masks (list[BitmapMasks]): true segmentation masks for each box used if the architecture supports a segmentation task. gt_semantic_seg (list[tensor]): semantic segmentation mask for images. gt_bboxes_ignore (list[Tensor]): specify which bounding boxes can be ignored when computing the loss. Defaults to None. Returns: dict[str, Tensor]: a dictionary of loss components """ # add batch_input_shape in img_metas super(SingleStageDetector, self).forward_train(img, img_metas) x = self.extract_feat(img) losses = self.panoptic_head.forward_train(x, img_metas, gt_bboxes, gt_labels, gt_masks, gt_semantic_seg, gt_bboxes_ignore) return losses def simple_test(self, img, img_metas, **kwargs): """Test without augmentation.""" feat = self.extract_feat(img) mask_results = self.panoptic_head.simple_test(feat, img_metas, **kwargs) results = [] for mask in mask_results: result = {'pan_results': mask.detach().cpu().numpy()} results.append(result) return results def aug_test(self, imgs, img_metas, **kwargs): raise NotImplementedError def onnx_export(self, img, img_metas): raise NotImplementedError def show_result(self, img, result, score_thr=0.3, bbox_color=(72, 101, 241), text_color=(72, 101, 241), mask_color=None, thickness=2, font_size=13, win_name='', show=False, wait_time=0, out_file=None): """Draw `result` over `img`. Args: img (str or Tensor): The image to be displayed. result (dict): The results. score_thr (float, optional): Minimum score of bboxes to be shown. Default: 0.3. bbox_color (str or tuple(int) or :obj:`Color`):Color of bbox lines. The tuple of color should be in BGR order. Default: 'green'. text_color (str or tuple(int) or :obj:`Color`):Color of texts. The tuple of color should be in BGR order. Default: 'green'. mask_color (None or str or tuple(int) or :obj:`Color`): Color of masks. The tuple of color should be in BGR order. Default: None. thickness (int): Thickness of lines. Default: 2. font_size (int): Font size of texts. Default: 13. win_name (str): The window name. Default: ''. wait_time (float): Value of waitKey param. Default: 0. show (bool): Whether to show the image. Default: False. out_file (str or None): The filename to write the image. Default: None. Returns: img (Tensor): Only if not `show` or `out_file`. """ img = mmcv.imread(img) img = img.copy() pan_results = result['pan_results'] # keep objects ahead ids = np.unique(pan_results)[::-1] legal_indices = ids != self.num_classes # for VOID label ids = ids[legal_indices] labels = np.array([id % INSTANCE_OFFSET for id in ids], dtype=np.int64) segms = (pan_results[None] == ids[:, None, None]) # if out_file specified, do not show image in window if out_file is not None: show = False # draw bounding boxes img = imshow_det_bboxes( img, segms=segms, labels=labels, class_names=self.CLASSES, bbox_color=bbox_color, text_color=text_color, mask_color=mask_color, thickness=thickness, font_size=font_size, win_name=win_name, show=show, wait_time=wait_time, out_file=out_file) if not (show or out_file): return img
39.921053
79
0.562162
import mmcv import numpy as np from mmdet.core import INSTANCE_OFFSET from mmdet.core.visualization import imshow_det_bboxes from ..builder import DETECTORS, build_backbone, build_head, build_neck from .single_stage import SingleStageDetector @DETECTORS.register_module() class MaskFormer(SingleStageDetector): def __init__(self, backbone, neck=None, panoptic_head=None, train_cfg=None, test_cfg=None, init_cfg=None): super(SingleStageDetector, self).__init__(init_cfg=init_cfg) self.backbone = build_backbone(backbone) if neck is not None: self.neck = build_neck(neck) panoptic_head.update(train_cfg=train_cfg) panoptic_head.update(test_cfg=test_cfg) self.panoptic_head = build_head(panoptic_head) self.num_things_classes = self.panoptic_head.num_things_classes self.num_stuff_classes = self.panoptic_head.num_stuff_classes self.num_classes = self.panoptic_head.num_classes self.train_cfg = train_cfg self.test_cfg = test_cfg def forward_dummy(self, img, img_metas): super(SingleStageDetector, self).forward_train(img, img_metas) x = self.extract_feat(img) outs = self.panoptic_head(x, img_metas) return outs def forward_train(self, img, img_metas, gt_bboxes, gt_labels, gt_masks, gt_semantic_seg, gt_bboxes_ignore=None, **kargs): super(SingleStageDetector, self).forward_train(img, img_metas) x = self.extract_feat(img) losses = self.panoptic_head.forward_train(x, img_metas, gt_bboxes, gt_labels, gt_masks, gt_semantic_seg, gt_bboxes_ignore) return losses def simple_test(self, img, img_metas, **kwargs): feat = self.extract_feat(img) mask_results = self.panoptic_head.simple_test(feat, img_metas, **kwargs) results = [] for mask in mask_results: result = {'pan_results': mask.detach().cpu().numpy()} results.append(result) return results def aug_test(self, imgs, img_metas, **kwargs): raise NotImplementedError def onnx_export(self, img, img_metas): raise NotImplementedError def show_result(self, img, result, score_thr=0.3, bbox_color=(72, 101, 241), text_color=(72, 101, 241), mask_color=None, thickness=2, font_size=13, win_name='', show=False, wait_time=0, out_file=None): img = mmcv.imread(img) img = img.copy() pan_results = result['pan_results'] ids = np.unique(pan_results)[::-1] legal_indices = ids != self.num_classes ids = ids[legal_indices] labels = np.array([id % INSTANCE_OFFSET for id in ids], dtype=np.int64) segms = (pan_results[None] == ids[:, None, None]) if out_file is not None: show = False img = imshow_det_bboxes( img, segms=segms, labels=labels, class_names=self.CLASSES, bbox_color=bbox_color, text_color=text_color, mask_color=mask_color, thickness=thickness, font_size=font_size, win_name=win_name, show=show, wait_time=wait_time, out_file=out_file) if not (show or out_file): return img
true
true
f7257da3da9f350d02208ba89525fe652376caa1
19,232
py
Python
yaldevtools/source_code.py
libyal/libyal
407e4710c9c11000dc45427d72bbdbdc2861c51a
[ "Apache-2.0" ]
176
2015-01-11T01:57:37.000Z
2022-03-30T05:31:33.000Z
yaldevtools/source_code.py
libyal/libyal
407e4710c9c11000dc45427d72bbdbdc2861c51a
[ "Apache-2.0" ]
79
2015-01-07T19:05:32.000Z
2022-01-25T15:19:29.000Z
yaldevtools/source_code.py
libyal/libyal
407e4710c9c11000dc45427d72bbdbdc2861c51a
[ "Apache-2.0" ]
25
2015-07-16T13:29:00.000Z
2022-02-12T08:15:19.000Z
# -*- coding: utf-8 -*- """The source code classes.""" import collections from yaldevtools import definitions class EnumDeclaration(object): """Enumeration type declaration. Attributes: name (str): name. constants (dict[str, str]): constant values per name. """ def __init__(self, name): """Initializes an enumeration type declaration. Args: name (str): name. """ super(EnumDeclaration, self).__init__() self.constants = collections.OrderedDict() self.name = name class FunctionArgument(object): """Function argument.""" def __init__(self, argument_string): """Initializes a function argument. Args: argument_string (str): function argument. """ super(FunctionArgument, self).__init__() self._strings = [argument_string] def AddArgumentString(self, argument_string): """Adds an argument string to the function argument. Args: argument_string (str): function argument. """ self._strings.append(argument_string) def CopyToString(self): """Copies the function argument to a string. Returns: str: function argument. """ number_of_strings = len(self._strings) argument_string = '' if number_of_strings == 1: argument_string = self._strings[0] elif number_of_strings > 1: argument_string = '{0:s}{1:s}'.format( self._strings[0], ', '.join(self._strings[1:])) return argument_string class FunctionPrototype(object): """Function prototype. Attributes: arguments (list[FunctionArgument]): function arguments. have_bfio (bool): True if the function prototype is defined if BFIO is defined. have_debug_output (bool): True if the function prototype is defined if debug output is defined. have_extern (bool): True if the function prototype is defined as externally available (API). have_wide_character_type (bool): True if the function prototype is defined if the wide character type is defined. name (str): name. return_type (str): return type. return_values (set[str]): return values or None if the function does not return values. value_description (str): description of the value. """ def __init__(self, name, return_type): """Initializes a function prototype. Args: name (str): name. return_type (str): return type. """ super(FunctionPrototype, self).__init__() self._parsed_value = False self._value_name = None self._value_type = None self.arguments = [] self.have_bfio = False self.have_debug_output = False self.have_extern = False self.have_wide_character_type = False self.name = name self.return_type = return_type self.return_values = None self.value_description = None def AddArgument(self, argument): """Adds an argument to the function prototype. Args: argument (FunctionArgument): function argument. """ self.arguments.append(argument) def AddArgumentString(self, argument_string): """Adds an argument string to the function prototype. Args: argument_string (str): function argument. """ function_argument = FunctionArgument(argument_string) self.arguments.append(function_argument) def CopyToManpageString(self): """Copies the function prototype to a string to be used in manpage. Returns: str: function prototype to be used in manpage. """ argument_strings = [] for function_argument in self.arguments: argument_string = function_argument.CopyToString() argument_string = '"{0:s}"'.format(argument_string) argument_strings.append(argument_string) return ' '.join(argument_strings) def CopyToString(self): """Copies the function prototype to a string. Returns: str: function prototype. """ argument_strings = [] for function_argument in self.arguments: argument_string = function_argument.CopyToString() argument_strings.append(argument_string) return ', '.join(argument_strings) def _ParseValue(self): """Parses the value name and type.""" # Strip the library name. _, _, function_name = self.name.partition('_') # Strip the library type. _, _, function_name = function_name.partition('_') value_name = None value_type = None number_of_arguments = len(self.arguments) if function_name.startswith('get_utf'): if number_of_arguments in (3, 4): _, _, value_name = function_name.partition('_') _, _, value_name = value_name.partition('_') elif function_name.startswith('get_'): # TODO: handle by_index, by_path getters if number_of_arguments == 3: _, _, value_name = function_name.partition('_') self._parsed_value = True self._value_name = value_name self._value_type = value_type def GetValueName(self): """Determines the value name of a getter or setter function. Returns: str: value name or None if not available. """ if not self._parsed_value: self._ParseValue() return self._value_name def GetValueType(self): """Determines the value type of a getter or setter function. Returns: str: value type or None if not available. """ if not self._parsed_value: self._ParseValue() return self._value_type class PythonTypeObjectFunctionPrototype(object): """Python type object function prototype. Attributes: arguments (list[str]): arguments. data_type (str): data type. function_type (str): function type. object_type (str): object type. return_values (set[str]): return values or None if the function does not return values. value_description (str): description of the value. value_type (str): value type. """ def __init__(self, python_module_name, type_name, type_function): """Initializes a Python type object function prototype. Args: python_module_name (str): python module name. type_name (str): type name. type_function (str): type function. """ super(PythonTypeObjectFunctionPrototype, self).__init__() self._name = None self._python_module_name = python_module_name self._type_function = type_function self._type_name = type_name self._value_name = None self.arguments = [] self.data_type = definitions.DATA_TYPE_NONE self.function_type = None self.object_type = None self.return_values = None self.value_description = None self.value_type = None @property def name(self): """str: name.""" if self._name is None: self._name = '{0:s}_{1:s}_{2:s}'.format( self._python_module_name, self._type_name, self.type_function) return self._name @property def type_function(self): """str: type function.""" # TODO: make overrides more generic. if self._type_function == 'set_parent_file': return 'set_parent' if (self._type_function.startswith('copy_') and not self._type_function.startswith('copy_from_')): return 'get_{0:s}'.format(self._type_function[5:]) if (self._type_function.startswith('get_utf8_') or self._type_function.startswith('set_utf8_')): return ''.join([self._type_function[:4], self._type_function[9:]]) if self._type_function.startswith('get_data_as_'): _, _, type_function_suffix = self._type_function.partition('_data_as_') if type_function_suffix in ( '16bit_integer', '32bit_integer', '64bit_integer'): return 'get_data_as_integer' if type_function_suffix in ('filetime', 'floatingtime'): return 'get_data_as_datetime' if type_function_suffix == 'utf8_string': return 'get_data_as_string' return self._type_function if self._type_function.startswith('get_'): type_function_prefix, _, type_function_suffix = ( self._type_function.partition('_by_')) if type_function_suffix in ('entry', 'index'): return type_function_prefix if type_function_suffix in ('utf8_name', 'utf8_path'): return ''.join([self._type_function[:-10], self._type_function[-5:]]) if self._type_function.endswith('_utf8_string'): return ''.join([self._type_function[:-12], self._type_function[-7:]]) if self._type_function.endswith('_utf8_string_size'): return ''.join([self._type_function[:-17], self._type_function[-12:]]) return self._type_function @property def value_name(self): """str: value name.""" if self._value_name is None: # TODO: make overrides more generic. if self.function_type == definitions.FUNCTION_TYPE_COPY: if self._type_function.startswith('copy_'): self._value_name = self._type_function[5:] elif self.function_type == definitions.FUNCTION_TYPE_COPY_FROM: if self._type_function.startswith('copy_from_'): self._value_name = self._type_function[10:] elif self.function_type == definitions.FUNCTION_TYPE_COPY_TO: if self._type_function.startswith('get_'): self._value_name = self._type_function[4:] elif self.function_type in ( definitions.FUNCTION_TYPE_GET, definitions.FUNCTION_TYPE_GET_BY_IDENTIFIER, definitions.FUNCTION_TYPE_GET_BY_INDEX, definitions.FUNCTION_TYPE_GET_BY_NAME, definitions.FUNCTION_TYPE_GET_BY_PATH): type_function_prefix, _, _ = self._type_function.partition('_by_') if type_function_prefix.startswith('get_'): type_function_prefix = type_function_prefix[4:] if type_function_prefix.startswith('utf8_'): type_function_prefix = type_function_prefix[5:] self._value_name = type_function_prefix elif self.function_type == definitions.FUNCTION_TYPE_IS: if self._type_function.startswith('is_'): self._value_name = self._type_function[3:] elif self.function_type == definitions.FUNCTION_TYPE_SET: if self._type_function.startswith('set_utf8_'): self._value_name = self._type_function[9:] elif self._type_function.startswith('set_'): self._value_name = self._type_function[4:] return self._value_name def DataTypeIsDatetime(self): """Determines if the data type is a datetime type. Returns: bool: True if the data type is a datetime type. """ return self.data_type in ( definitions.DATA_TYPE_FAT_DATE_TIME, definitions.DATA_TYPE_FILETIME, definitions.DATA_TYPE_FLOATINGTIME, definitions.DATA_TYPE_POSIX_TIME) def DataTypeIsFloat(self): """Determines if the data type is a floating-point type. Returns: bool: True if the data type is a floating-point type. """ return self.data_type in ( definitions.DATA_TYPE_FLOAT, definitions.DATA_TYPE_DOUBLE) def DataTypeIsInteger(self): """Determines if the data type is an integer type. Returns: bool: True if the data type is an integer type. """ return self.data_type in ( definitions.DATA_TYPE_INT, definitions.DATA_TYPE_INT32, definitions.DATA_TYPE_OFF64, definitions.DATA_TYPE_SIZE32, definitions.DATA_TYPE_SIZE64, definitions.DATA_TYPE_UINT8, definitions.DATA_TYPE_UINT16, definitions.DATA_TYPE_UINT32, definitions.DATA_TYPE_UINT64) def GetAttributeDescription(self): """Retrieves the fuction as attribute description. Returns: str: function as attribute description. """ description = '' type_function = self.type_function value_name = self.value_name if value_name: value_name = value_name.replace('_', ' ') if type_function == 'get_ascii_codepage': description = ( 'The codepage used for ASCII strings in the {0:s}.').format( self._type_name) elif type_function == 'get_data_as_boolean': description = 'The data as a boolean.' elif type_function == 'get_data_as_datetime': description = 'The data as a datetime object.' elif type_function == 'get_data_as_integer': description = 'The data as an integer.' elif type_function == 'get_data_as_floating_point': description = 'The data as a floating point.' elif type_function == 'get_data_as_string': description = 'The data as a string.' elif self.function_type == definitions.FUNCTION_TYPE_IS: type_name = self._type_name if type_name: type_name = type_name.replace('_', ' ') description = 'Indicates the {0:s} is {1:s}.'.format( type_name, value_name) elif self.value_description: description = 'The {0:s}.'.format(self.value_description) elif value_name: description = 'The {0:s}.'.format(value_name) return description def GetDataTypeDescription(self): """Retrieves the data type description. Returns: str: data type description. """ if self.data_type == definitions.DATA_TYPE_BINARY_DATA: data_type_description = 'Binary string' elif self.data_type == definitions.DATA_TYPE_BOOLEAN: data_type_description = 'Boolean' elif self.DataTypeIsDatetime(): data_type_description = 'Datetime' elif self.data_type == definitions.DATA_TYPE_OBJECT: data_type_description = 'Object' elif self.DataTypeIsFloat(): data_type_description = 'Float' elif self.DataTypeIsInteger(): data_type_description = 'Integer' elif self.data_type in ( definitions.DATA_TYPE_GUID, definitions.DATA_TYPE_STRING, definitions.DATA_TYPE_UUID): data_type_description = 'Unicode string' elif self.data_type == definitions.DATA_TYPE_NARROW_STRING: data_type_description = 'String' elif self.data_type == definitions.DATA_TYPE_NONE: data_type_description = 'None' else: data_type_description = self.data_type if (data_type_description != 'None' and self.return_values and 'None' in self.return_values): data_type_description = '{0:s} or None'.format(data_type_description) return data_type_description def GetDescription(self): """Retrieves the description. Returns: list[str]: lines of the description. """ description = [''] type_function = self.type_function type_name = self._type_name if type_name: type_name = type_name.replace('_', ' ') value_name = self.value_name if value_name: value_name = value_name.replace('_', ' ') if type_function == 'close': description = ['Closes a {0:s}.'.format(type_name)] elif type_function == 'get_ascii_codepage': description = [( 'Retrieves the codepage for ASCII strings used in ' 'the {0:s}.').format(type_name)] elif type_function == 'get_data_as_boolean': description = ['Retrieves the data as a boolean.'] elif type_function == 'get_data_as_datetime': description = ['Retrieves the data as a datetime object.'] elif type_function == 'get_data_as_integer': description = ['Retrieves the data as an integer.'] elif type_function == 'get_data_as_floating_point': description = ['Retrieves the data as a floating point.'] elif type_function == 'get_data_as_string': description = ['Retrieves the data as a string.'] elif type_function == 'get_string': description = ['Retrieves the {0:s} formatted as a string.'.format( type_name)] elif type_function == 'open': description = ['Opens a {0:s}.'.format(type_name)] elif type_function == 'open_file_object': description = [( 'Opens a {0:s} using a file-like object.').format(type_name)] elif type_function == 'read_buffer': if self.value_description: description = ['Reads a buffer of {0:s}.'.format( self.value_description)] else: description = ['Reads a buffer of data.'] elif type_function == 'read_buffer_at_offset': if self.value_description: description = ['Reads a buffer of {0:s} at a specific offset.'.format( self.value_description)] else: description = ['Reads a buffer of data at a specific offset.'] elif type_function == 'seek_offset': if self.value_description: description = ['Seeks an offset within the {0:s}.'.format( self.value_description)] else: description = ['Seeks an offset within the data.'] elif type_function == 'set_ascii_codepage': description = [ ('Sets the codepage for ASCII strings used in the ' '{0:s}.').format(type_name), ('Expects the codepage to be a string containing a Python ' 'codec definition.')] elif type_function == 'set_parent': description = ['Sets the parent file.'] elif type_function == 'signal_abort': description = ['Signals the {0:s} to abort the current activity.'.format( type_name)] elif self.function_type == definitions.FUNCTION_TYPE_GET_BY_INDEX: _, _, argument_suffix = self.arguments[0].rpartition('_') if self.value_description: description = ['Retrieves the {0:s} specified by the {1:s}.'.format( self.value_description, argument_suffix)] else: description = ['Retrieves the {0:s} specified by the {1:s}.'.format( value_name, argument_suffix)] elif self.function_type in ( definitions.FUNCTION_TYPE_GET_BY_IDENTIFIER, definitions.FUNCTION_TYPE_GET_BY_NAME, definitions.FUNCTION_TYPE_GET_BY_PATH): _, _, type_function_suffix = type_function.partition('_by_') if self.value_description: description = ['Retrieves the {0:s} specified by the {1:s}.'.format( self.value_description, type_function_suffix)] else: description = ['Retrieves the {0:s} specified by the {1:s}.'.format( value_name, type_function_suffix)] elif self.function_type == definitions.FUNCTION_TYPE_COPY_FROM: # TODO: fix value name. description = ['Copies the {0:s} from the {1:s}.'.format( type_name, value_name)] elif self.function_type in ( definitions.FUNCTION_TYPE_COPY, definitions.FUNCTION_TYPE_GET): if self.value_description: description = ['Retrieves the {0:s}.'.format(self.value_description)] else: description = ['Retrieves the {0:s}.'.format(value_name)] elif self.function_type == definitions.FUNCTION_TYPE_IS: description = ['Determines if the {0:s} is {1:s}.'.format( type_name, value_name)] elif self.function_type == definitions.FUNCTION_TYPE_SET: description = ['Sets the {0:s}.'.format(value_name)] return description def GetValueNameAndPrefix(self): """Determines the value name and its prefix. Returns: tuple[str, str]: value name and prefix. """ if self.value_name: value_name_prefix, _, value_name = self.value_name.partition('_') if value_name_prefix in ('root', 'sub'): return value_name, value_name_prefix return self.value_name, None
31.271545
79
0.674085
import collections from yaldevtools import definitions class EnumDeclaration(object): def __init__(self, name): super(EnumDeclaration, self).__init__() self.constants = collections.OrderedDict() self.name = name class FunctionArgument(object): def __init__(self, argument_string): super(FunctionArgument, self).__init__() self._strings = [argument_string] def AddArgumentString(self, argument_string): self._strings.append(argument_string) def CopyToString(self): number_of_strings = len(self._strings) argument_string = '' if number_of_strings == 1: argument_string = self._strings[0] elif number_of_strings > 1: argument_string = '{0:s}{1:s}'.format( self._strings[0], ', '.join(self._strings[1:])) return argument_string class FunctionPrototype(object): def __init__(self, name, return_type): super(FunctionPrototype, self).__init__() self._parsed_value = False self._value_name = None self._value_type = None self.arguments = [] self.have_bfio = False self.have_debug_output = False self.have_extern = False self.have_wide_character_type = False self.name = name self.return_type = return_type self.return_values = None self.value_description = None def AddArgument(self, argument): self.arguments.append(argument) def AddArgumentString(self, argument_string): function_argument = FunctionArgument(argument_string) self.arguments.append(function_argument) def CopyToManpageString(self): argument_strings = [] for function_argument in self.arguments: argument_string = function_argument.CopyToString() argument_string = '"{0:s}"'.format(argument_string) argument_strings.append(argument_string) return ' '.join(argument_strings) def CopyToString(self): argument_strings = [] for function_argument in self.arguments: argument_string = function_argument.CopyToString() argument_strings.append(argument_string) return ', '.join(argument_strings) def _ParseValue(self): _, _, function_name = self.name.partition('_') _, _, function_name = function_name.partition('_') value_name = None value_type = None number_of_arguments = len(self.arguments) if function_name.startswith('get_utf'): if number_of_arguments in (3, 4): _, _, value_name = function_name.partition('_') _, _, value_name = value_name.partition('_') elif function_name.startswith('get_'): if number_of_arguments == 3: _, _, value_name = function_name.partition('_') self._parsed_value = True self._value_name = value_name self._value_type = value_type def GetValueName(self): if not self._parsed_value: self._ParseValue() return self._value_name def GetValueType(self): if not self._parsed_value: self._ParseValue() return self._value_type class PythonTypeObjectFunctionPrototype(object): def __init__(self, python_module_name, type_name, type_function): super(PythonTypeObjectFunctionPrototype, self).__init__() self._name = None self._python_module_name = python_module_name self._type_function = type_function self._type_name = type_name self._value_name = None self.arguments = [] self.data_type = definitions.DATA_TYPE_NONE self.function_type = None self.object_type = None self.return_values = None self.value_description = None self.value_type = None @property def name(self): if self._name is None: self._name = '{0:s}_{1:s}_{2:s}'.format( self._python_module_name, self._type_name, self.type_function) return self._name @property def type_function(self): if self._type_function == 'set_parent_file': return 'set_parent' if (self._type_function.startswith('copy_') and not self._type_function.startswith('copy_from_')): return 'get_{0:s}'.format(self._type_function[5:]) if (self._type_function.startswith('get_utf8_') or self._type_function.startswith('set_utf8_')): return ''.join([self._type_function[:4], self._type_function[9:]]) if self._type_function.startswith('get_data_as_'): _, _, type_function_suffix = self._type_function.partition('_data_as_') if type_function_suffix in ( '16bit_integer', '32bit_integer', '64bit_integer'): return 'get_data_as_integer' if type_function_suffix in ('filetime', 'floatingtime'): return 'get_data_as_datetime' if type_function_suffix == 'utf8_string': return 'get_data_as_string' return self._type_function if self._type_function.startswith('get_'): type_function_prefix, _, type_function_suffix = ( self._type_function.partition('_by_')) if type_function_suffix in ('entry', 'index'): return type_function_prefix if type_function_suffix in ('utf8_name', 'utf8_path'): return ''.join([self._type_function[:-10], self._type_function[-5:]]) if self._type_function.endswith('_utf8_string'): return ''.join([self._type_function[:-12], self._type_function[-7:]]) if self._type_function.endswith('_utf8_string_size'): return ''.join([self._type_function[:-17], self._type_function[-12:]]) return self._type_function @property def value_name(self): if self._value_name is None: if self.function_type == definitions.FUNCTION_TYPE_COPY: if self._type_function.startswith('copy_'): self._value_name = self._type_function[5:] elif self.function_type == definitions.FUNCTION_TYPE_COPY_FROM: if self._type_function.startswith('copy_from_'): self._value_name = self._type_function[10:] elif self.function_type == definitions.FUNCTION_TYPE_COPY_TO: if self._type_function.startswith('get_'): self._value_name = self._type_function[4:] elif self.function_type in ( definitions.FUNCTION_TYPE_GET, definitions.FUNCTION_TYPE_GET_BY_IDENTIFIER, definitions.FUNCTION_TYPE_GET_BY_INDEX, definitions.FUNCTION_TYPE_GET_BY_NAME, definitions.FUNCTION_TYPE_GET_BY_PATH): type_function_prefix, _, _ = self._type_function.partition('_by_') if type_function_prefix.startswith('get_'): type_function_prefix = type_function_prefix[4:] if type_function_prefix.startswith('utf8_'): type_function_prefix = type_function_prefix[5:] self._value_name = type_function_prefix elif self.function_type == definitions.FUNCTION_TYPE_IS: if self._type_function.startswith('is_'): self._value_name = self._type_function[3:] elif self.function_type == definitions.FUNCTION_TYPE_SET: if self._type_function.startswith('set_utf8_'): self._value_name = self._type_function[9:] elif self._type_function.startswith('set_'): self._value_name = self._type_function[4:] return self._value_name def DataTypeIsDatetime(self): return self.data_type in ( definitions.DATA_TYPE_FAT_DATE_TIME, definitions.DATA_TYPE_FILETIME, definitions.DATA_TYPE_FLOATINGTIME, definitions.DATA_TYPE_POSIX_TIME) def DataTypeIsFloat(self): return self.data_type in ( definitions.DATA_TYPE_FLOAT, definitions.DATA_TYPE_DOUBLE) def DataTypeIsInteger(self): return self.data_type in ( definitions.DATA_TYPE_INT, definitions.DATA_TYPE_INT32, definitions.DATA_TYPE_OFF64, definitions.DATA_TYPE_SIZE32, definitions.DATA_TYPE_SIZE64, definitions.DATA_TYPE_UINT8, definitions.DATA_TYPE_UINT16, definitions.DATA_TYPE_UINT32, definitions.DATA_TYPE_UINT64) def GetAttributeDescription(self): description = '' type_function = self.type_function value_name = self.value_name if value_name: value_name = value_name.replace('_', ' ') if type_function == 'get_ascii_codepage': description = ( 'The codepage used for ASCII strings in the {0:s}.').format( self._type_name) elif type_function == 'get_data_as_boolean': description = 'The data as a boolean.' elif type_function == 'get_data_as_datetime': description = 'The data as a datetime object.' elif type_function == 'get_data_as_integer': description = 'The data as an integer.' elif type_function == 'get_data_as_floating_point': description = 'The data as a floating point.' elif type_function == 'get_data_as_string': description = 'The data as a string.' elif self.function_type == definitions.FUNCTION_TYPE_IS: type_name = self._type_name if type_name: type_name = type_name.replace('_', ' ') description = 'Indicates the {0:s} is {1:s}.'.format( type_name, value_name) elif self.value_description: description = 'The {0:s}.'.format(self.value_description) elif value_name: description = 'The {0:s}.'.format(value_name) return description def GetDataTypeDescription(self): if self.data_type == definitions.DATA_TYPE_BINARY_DATA: data_type_description = 'Binary string' elif self.data_type == definitions.DATA_TYPE_BOOLEAN: data_type_description = 'Boolean' elif self.DataTypeIsDatetime(): data_type_description = 'Datetime' elif self.data_type == definitions.DATA_TYPE_OBJECT: data_type_description = 'Object' elif self.DataTypeIsFloat(): data_type_description = 'Float' elif self.DataTypeIsInteger(): data_type_description = 'Integer' elif self.data_type in ( definitions.DATA_TYPE_GUID, definitions.DATA_TYPE_STRING, definitions.DATA_TYPE_UUID): data_type_description = 'Unicode string' elif self.data_type == definitions.DATA_TYPE_NARROW_STRING: data_type_description = 'String' elif self.data_type == definitions.DATA_TYPE_NONE: data_type_description = 'None' else: data_type_description = self.data_type if (data_type_description != 'None' and self.return_values and 'None' in self.return_values): data_type_description = '{0:s} or None'.format(data_type_description) return data_type_description def GetDescription(self): description = [''] type_function = self.type_function type_name = self._type_name if type_name: type_name = type_name.replace('_', ' ') value_name = self.value_name if value_name: value_name = value_name.replace('_', ' ') if type_function == 'close': description = ['Closes a {0:s}.'.format(type_name)] elif type_function == 'get_ascii_codepage': description = [( 'Retrieves the codepage for ASCII strings used in ' 'the {0:s}.').format(type_name)] elif type_function == 'get_data_as_boolean': description = ['Retrieves the data as a boolean.'] elif type_function == 'get_data_as_datetime': description = ['Retrieves the data as a datetime object.'] elif type_function == 'get_data_as_integer': description = ['Retrieves the data as an integer.'] elif type_function == 'get_data_as_floating_point': description = ['Retrieves the data as a floating point.'] elif type_function == 'get_data_as_string': description = ['Retrieves the data as a string.'] elif type_function == 'get_string': description = ['Retrieves the {0:s} formatted as a string.'.format( type_name)] elif type_function == 'open': description = ['Opens a {0:s}.'.format(type_name)] elif type_function == 'open_file_object': description = [( 'Opens a {0:s} using a file-like object.').format(type_name)] elif type_function == 'read_buffer': if self.value_description: description = ['Reads a buffer of {0:s}.'.format( self.value_description)] else: description = ['Reads a buffer of data.'] elif type_function == 'read_buffer_at_offset': if self.value_description: description = ['Reads a buffer of {0:s} at a specific offset.'.format( self.value_description)] else: description = ['Reads a buffer of data at a specific offset.'] elif type_function == 'seek_offset': if self.value_description: description = ['Seeks an offset within the {0:s}.'.format( self.value_description)] else: description = ['Seeks an offset within the data.'] elif type_function == 'set_ascii_codepage': description = [ ('Sets the codepage for ASCII strings used in the ' '{0:s}.').format(type_name), ('Expects the codepage to be a string containing a Python ' 'codec definition.')] elif type_function == 'set_parent': description = ['Sets the parent file.'] elif type_function == 'signal_abort': description = ['Signals the {0:s} to abort the current activity.'.format( type_name)] elif self.function_type == definitions.FUNCTION_TYPE_GET_BY_INDEX: _, _, argument_suffix = self.arguments[0].rpartition('_') if self.value_description: description = ['Retrieves the {0:s} specified by the {1:s}.'.format( self.value_description, argument_suffix)] else: description = ['Retrieves the {0:s} specified by the {1:s}.'.format( value_name, argument_suffix)] elif self.function_type in ( definitions.FUNCTION_TYPE_GET_BY_IDENTIFIER, definitions.FUNCTION_TYPE_GET_BY_NAME, definitions.FUNCTION_TYPE_GET_BY_PATH): _, _, type_function_suffix = type_function.partition('_by_') if self.value_description: description = ['Retrieves the {0:s} specified by the {1:s}.'.format( self.value_description, type_function_suffix)] else: description = ['Retrieves the {0:s} specified by the {1:s}.'.format( value_name, type_function_suffix)] elif self.function_type == definitions.FUNCTION_TYPE_COPY_FROM: description = ['Copies the {0:s} from the {1:s}.'.format( type_name, value_name)] elif self.function_type in ( definitions.FUNCTION_TYPE_COPY, definitions.FUNCTION_TYPE_GET): if self.value_description: description = ['Retrieves the {0:s}.'.format(self.value_description)] else: description = ['Retrieves the {0:s}.'.format(value_name)] elif self.function_type == definitions.FUNCTION_TYPE_IS: description = ['Determines if the {0:s} is {1:s}.'.format( type_name, value_name)] elif self.function_type == definitions.FUNCTION_TYPE_SET: description = ['Sets the {0:s}.'.format(value_name)] return description def GetValueNameAndPrefix(self): if self.value_name: value_name_prefix, _, value_name = self.value_name.partition('_') if value_name_prefix in ('root', 'sub'): return value_name, value_name_prefix return self.value_name, None
true
true
f7257dbe457fadac40393d1ec3dd31766bbf6237
540
py
Python
sample_app/admin.py
imimran/inline-in-fieldset
c20568904011889001d92024c8881782a84aa00c
[ "MIT" ]
null
null
null
sample_app/admin.py
imimran/inline-in-fieldset
c20568904011889001d92024c8881782a84aa00c
[ "MIT" ]
null
null
null
sample_app/admin.py
imimran/inline-in-fieldset
c20568904011889001d92024c8881782a84aa00c
[ "MIT" ]
null
null
null
from django.contrib import admin from .models import Student, Subject class SubjectInline(admin.TabularInline): model = Subject insert_after = 'name' class StudentAdmin(admin.ModelAdmin): fields = ( 'name', 'department', 'gender', ) inlines = [ SubjectInline, ] change_form_template = 'admin/custom/change_form.html' class Media: css = { 'all': ( 'css/admin.css', ) } admin.site.register(Student, StudentAdmin)
16.875
58
0.572222
from django.contrib import admin from .models import Student, Subject class SubjectInline(admin.TabularInline): model = Subject insert_after = 'name' class StudentAdmin(admin.ModelAdmin): fields = ( 'name', 'department', 'gender', ) inlines = [ SubjectInline, ] change_form_template = 'admin/custom/change_form.html' class Media: css = { 'all': ( 'css/admin.css', ) } admin.site.register(Student, StudentAdmin)
true
true
f7257df7d21d92286f4cc0d13478da8406845b2f
26,886
py
Python
zipline/data/resample.py
Code37/zipline
de038dbf584980af4f30822f8e5d306bac2a44cb
[ "Apache-2.0" ]
412
2017-04-30T14:35:47.000Z
2022-03-29T02:58:33.000Z
zipline/data/resample.py
waijay1992/zipline
8beba055aa4211dc2debc5c3083077cbd19d0bbc
[ "Apache-2.0" ]
116
2017-05-15T04:45:45.000Z
2020-05-30T19:09:00.000Z
zipline/data/resample.py
waijay1992/zipline
8beba055aa4211dc2debc5c3083077cbd19d0bbc
[ "Apache-2.0" ]
80
2017-05-03T13:17:33.000Z
2021-02-08T15:42:09.000Z
# Copyright 2016 Quantopian, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from collections import OrderedDict from abc import ABCMeta, abstractmethod import numpy as np import pandas as pd from six import with_metaclass from zipline.data._resample import ( _minute_to_session_open, _minute_to_session_high, _minute_to_session_low, _minute_to_session_close, _minute_to_session_volume, ) from zipline.data.bar_reader import NoDataOnDate from zipline.data.minute_bars import MinuteBarReader from zipline.data.session_bars import SessionBarReader from zipline.utils.memoize import lazyval _MINUTE_TO_SESSION_OHCLV_HOW = OrderedDict(( ('open', 'first'), ('high', 'max'), ('low', 'min'), ('close', 'last'), ('volume', 'sum'), )) def minute_frame_to_session_frame(minute_frame, calendar): """ Resample a DataFrame with minute data into the frame expected by a BcolzDailyBarWriter. Parameters ---------- minute_frame : pd.DataFrame A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`, and `dt` (minute dts) calendar : zipline.utils.calendars.trading_calendar.TradingCalendar A TradingCalendar on which session labels to resample from minute to session. Return ------ session_frame : pd.DataFrame A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`, and `day` (datetime-like). """ how = OrderedDict((c, _MINUTE_TO_SESSION_OHCLV_HOW[c]) for c in minute_frame.columns) return minute_frame.groupby(calendar.minute_to_session_label).agg(how) def minute_to_session(column, close_locs, data, out): """ Resample an array with minute data into an array with session data. This function assumes that the minute data is the exact length of all minutes in the sessions in the output. Parameters ---------- column : str The `open`, `high`, `low`, `close`, or `volume` column. close_locs : array[intp] The locations in `data` which are the market close minutes. data : array[float64|uint32] The minute data to be sampled into session data. The first value should align with the market open of the first session, containing values for all minutes for all sessions. With the last value being the market close of the last session. out : array[float64|uint32] The output array into which to write the sampled sessions. """ if column == 'open': _minute_to_session_open(close_locs, data, out) elif column == 'high': _minute_to_session_high(close_locs, data, out) elif column == 'low': _minute_to_session_low(close_locs, data, out) elif column == 'close': _minute_to_session_close(close_locs, data, out) elif column == 'volume': _minute_to_session_volume(close_locs, data, out) return out class DailyHistoryAggregator(object): """ Converts minute pricing data into a daily summary, to be used for the last slot in a call to history with a frequency of `1d`. This summary is the same as a daily bar rollup of minute data, with the distinction that the summary is truncated to the `dt` requested. i.e. the aggregation slides forward during a the course of simulation day. Provides aggregation for `open`, `high`, `low`, `close`, and `volume`. The aggregation rules for each price type is documented in their respective """ def __init__(self, market_opens, minute_reader, trading_calendar): self._market_opens = market_opens self._minute_reader = minute_reader self._trading_calendar = trading_calendar # The caches are structured as (date, market_open, entries), where # entries is a dict of asset -> (last_visited_dt, value) # # Whenever an aggregation method determines the current value, # the entry for the respective asset should be overwritten with a new # entry for the current dt.value (int) and aggregation value. # # When the requested dt's date is different from date the cache is # flushed, so that the cache entries do not grow unbounded. # # Example cache: # cache = (date(2016, 3, 17), # pd.Timestamp('2016-03-17 13:31', tz='UTC'), # { # 1: (1458221460000000000, np.nan), # 2: (1458221460000000000, 42.0), # }) self._caches = { 'open': None, 'high': None, 'low': None, 'close': None, 'volume': None } # The int value is used for deltas to avoid extra computation from # creating new Timestamps. self._one_min = pd.Timedelta('1 min').value def _prelude(self, dt, field): session = self._trading_calendar.minute_to_session_label(dt) dt_value = dt.value cache = self._caches[field] if cache is None or cache[0] != session: market_open = self._market_opens.loc[session] cache = self._caches[field] = (session, market_open, {}) _, market_open, entries = cache market_open = market_open.tz_localize('UTC') if dt != market_open: prev_dt = dt_value - self._one_min else: prev_dt = None return market_open, prev_dt, dt_value, entries def opens(self, assets, dt): """ The open field's aggregation returns the first value that occurs for the day, if there has been no data on or before the `dt` the open is `nan`. Once the first non-nan open is seen, that value remains constant per asset for the remainder of the day. Returns ------- np.array with dtype=float64, in order of assets parameter. """ market_open, prev_dt, dt_value, entries = self._prelude(dt, 'open') opens = [] session_label = self._trading_calendar.minute_to_session_label(dt) for asset in assets: if not asset.is_alive_for_session(session_label): opens.append(np.NaN) continue if prev_dt is None: val = self._minute_reader.get_value(asset, dt, 'open') entries[asset] = (dt_value, val) opens.append(val) continue else: try: last_visited_dt, first_open = entries[asset] if last_visited_dt == dt_value: opens.append(first_open) continue elif not pd.isnull(first_open): opens.append(first_open) entries[asset] = (dt_value, first_open) continue else: after_last = pd.Timestamp( last_visited_dt + self._one_min, tz='UTC') window = self._minute_reader.load_raw_arrays( ['open'], after_last, dt, [asset], )[0] nonnan = window[~pd.isnull(window)] if len(nonnan): val = nonnan[0] else: val = np.nan entries[asset] = (dt_value, val) opens.append(val) continue except KeyError: window = self._minute_reader.load_raw_arrays( ['open'], market_open, dt, [asset], )[0] nonnan = window[~pd.isnull(window)] if len(nonnan): val = nonnan[0] else: val = np.nan entries[asset] = (dt_value, val) opens.append(val) continue return np.array(opens) def highs(self, assets, dt): """ The high field's aggregation returns the largest high seen between the market open and the current dt. If there has been no data on or before the `dt` the high is `nan`. Returns ------- np.array with dtype=float64, in order of assets parameter. """ market_open, prev_dt, dt_value, entries = self._prelude(dt, 'high') highs = [] session_label = self._trading_calendar.minute_to_session_label(dt) for asset in assets: if not asset.is_alive_for_session(session_label): highs.append(np.NaN) continue if prev_dt is None: val = self._minute_reader.get_value(asset, dt, 'high') entries[asset] = (dt_value, val) highs.append(val) continue else: try: last_visited_dt, last_max = entries[asset] if last_visited_dt == dt_value: highs.append(last_max) continue elif last_visited_dt == prev_dt: curr_val = self._minute_reader.get_value( asset, dt, 'high') if pd.isnull(curr_val): val = last_max elif pd.isnull(last_max): val = curr_val else: val = max(last_max, curr_val) entries[asset] = (dt_value, val) highs.append(val) continue else: after_last = pd.Timestamp( last_visited_dt + self._one_min, tz='UTC') window = self._minute_reader.load_raw_arrays( ['high'], after_last, dt, [asset], )[0].T val = np.nanmax(np.append(window, last_max)) entries[asset] = (dt_value, val) highs.append(val) continue except KeyError: window = self._minute_reader.load_raw_arrays( ['high'], market_open, dt, [asset], )[0].T val = np.nanmax(window) entries[asset] = (dt_value, val) highs.append(val) continue return np.array(highs) def lows(self, assets, dt): """ The low field's aggregation returns the smallest low seen between the market open and the current dt. If there has been no data on or before the `dt` the low is `nan`. Returns ------- np.array with dtype=float64, in order of assets parameter. """ market_open, prev_dt, dt_value, entries = self._prelude(dt, 'low') lows = [] session_label = self._trading_calendar.minute_to_session_label(dt) for asset in assets: if not asset.is_alive_for_session(session_label): lows.append(np.NaN) continue if prev_dt is None: val = self._minute_reader.get_value(asset, dt, 'low') entries[asset] = (dt_value, val) lows.append(val) continue else: try: last_visited_dt, last_min = entries[asset] if last_visited_dt == dt_value: lows.append(last_min) continue elif last_visited_dt == prev_dt: curr_val = self._minute_reader.get_value( asset, dt, 'low') val = np.nanmin([last_min, curr_val]) entries[asset] = (dt_value, val) lows.append(val) continue else: after_last = pd.Timestamp( last_visited_dt + self._one_min, tz='UTC') window = self._minute_reader.load_raw_arrays( ['low'], after_last, dt, [asset], )[0].T val = np.nanmin(np.append(window, last_min)) entries[asset] = (dt_value, val) lows.append(val) continue except KeyError: window = self._minute_reader.load_raw_arrays( ['low'], market_open, dt, [asset], )[0].T val = np.nanmin(window) entries[asset] = (dt_value, val) lows.append(val) continue return np.array(lows) def closes(self, assets, dt): """ The close field's aggregation returns the latest close at the given dt. If the close for the given dt is `nan`, the most recent non-nan `close` is used. If there has been no data on or before the `dt` the close is `nan`. Returns ------- np.array with dtype=float64, in order of assets parameter. """ market_open, prev_dt, dt_value, entries = self._prelude(dt, 'close') closes = [] session_label = self._trading_calendar.minute_to_session_label(dt) def _get_filled_close(asset): """ Returns the most recent non-nan close for the asset in this session. If there has been no data in this session on or before the `dt`, returns `nan` """ window = self._minute_reader.load_raw_arrays( ['close'], market_open, dt, [asset], )[0] try: return window[~np.isnan(window)][-1] except IndexError: return np.NaN for asset in assets: if not asset.is_alive_for_session(session_label): closes.append(np.NaN) continue if prev_dt is None: val = self._minute_reader.get_value(asset, dt, 'close') entries[asset] = (dt_value, val) closes.append(val) continue else: try: last_visited_dt, last_close = entries[asset] if last_visited_dt == dt_value: closes.append(last_close) continue elif last_visited_dt == prev_dt: val = self._minute_reader.get_value( asset, dt, 'close') if pd.isnull(val): val = last_close entries[asset] = (dt_value, val) closes.append(val) continue else: val = self._minute_reader.get_value( asset, dt, 'close') if pd.isnull(val): val = _get_filled_close(asset) entries[asset] = (dt_value, val) closes.append(val) continue except KeyError: val = self._minute_reader.get_value( asset, dt, 'close') if pd.isnull(val): val = _get_filled_close(asset) entries[asset] = (dt_value, val) closes.append(val) continue return np.array(closes) def volumes(self, assets, dt): """ The volume field's aggregation returns the sum of all volumes between the market open and the `dt` If there has been no data on or before the `dt` the volume is 0. Returns ------- np.array with dtype=int64, in order of assets parameter. """ market_open, prev_dt, dt_value, entries = self._prelude(dt, 'volume') volumes = [] session_label = self._trading_calendar.minute_to_session_label(dt) for asset in assets: if not asset.is_alive_for_session(session_label): volumes.append(0) continue if prev_dt is None: val = self._minute_reader.get_value(asset, dt, 'volume') entries[asset] = (dt_value, val) volumes.append(val) continue else: try: last_visited_dt, last_total = entries[asset] if last_visited_dt == dt_value: volumes.append(last_total) continue elif last_visited_dt == prev_dt: val = self._minute_reader.get_value( asset, dt, 'volume') val += last_total entries[asset] = (dt_value, val) volumes.append(val) continue else: after_last = pd.Timestamp( last_visited_dt + self._one_min, tz='UTC') window = self._minute_reader.load_raw_arrays( ['volume'], after_last, dt, [asset], )[0] val = np.nansum(window) + last_total entries[asset] = (dt_value, val) volumes.append(val) continue except KeyError: window = self._minute_reader.load_raw_arrays( ['volume'], market_open, dt, [asset], )[0] val = np.nansum(window) entries[asset] = (dt_value, val) volumes.append(val) continue return np.array(volumes) class MinuteResampleSessionBarReader(SessionBarReader): def __init__(self, calendar, minute_bar_reader): self._calendar = calendar self._minute_bar_reader = minute_bar_reader def _get_resampled(self, columns, start_session, end_session, assets): range_open = self._calendar.session_open(start_session) range_close = self._calendar.session_close(end_session) minute_data = self._minute_bar_reader.load_raw_arrays( columns, range_open, range_close, assets, ) # Get the index of the close minute for each session in the range. # If the range contains only one session, the only close in the range # is the last minute in the data. Otherwise, we need to get all the # session closes and find their indices in the range of minutes. if start_session == end_session: close_ilocs = np.array([len(minute_data[0]) - 1], dtype=np.int64) else: minutes = self._calendar.minutes_in_range( range_open, range_close, ) session_closes = self._calendar.session_closes_in_range( start_session, end_session, ) close_ilocs = minutes.searchsorted(session_closes.values) results = [] shape = (len(close_ilocs), len(assets)) for col in columns: if col != 'volume': out = np.full(shape, np.nan) else: out = np.zeros(shape, dtype=np.uint32) results.append(out) for i in range(len(assets)): for j, column in enumerate(columns): data = minute_data[j][:, i] minute_to_session(column, close_ilocs, data, results[j][:, i]) return results @property def trading_calendar(self): return self._calendar def load_raw_arrays(self, columns, start_dt, end_dt, sids): return self._get_resampled(columns, start_dt, end_dt, sids) def get_value(self, sid, session, colname): # WARNING: This will need caching or other optimization if used in a # tight loop. # This was developed to complete interface, but has not been tuned # for real world use. return self._get_resampled([colname], session, session, [sid])[0][0][0] @lazyval def sessions(self): cal = self._calendar first = self._minute_bar_reader.first_trading_day last = cal.minute_to_session_label( self._minute_bar_reader.last_available_dt) return cal.sessions_in_range(first, last) @lazyval def last_available_dt(self): return self.trading_calendar.minute_to_session_label( self._minute_bar_reader.last_available_dt ) @property def first_trading_day(self): return self._minute_bar_reader.first_trading_day def get_last_traded_dt(self, asset, dt): return self.trading_calendar.minute_to_session_label( self._minute_bar_reader.get_last_traded_dt(asset, dt)) class ReindexBarReader(with_metaclass(ABCMeta)): """ A base class for readers which reindexes results, filling in the additional indices with empty data. Used to align the reading assets which trade on different calendars. Currently only supports a ``trading_calendar`` which is a superset of the ``reader``'s calendar. Parameters ---------- - trading_calendar : zipline.utils.trading_calendar.TradingCalendar The calendar to use when indexing results from the reader. - reader : MinuteBarReader|SessionBarReader The reader which has a calendar that is a subset of the desired ``trading_calendar``. - first_trading_session : pd.Timestamp The first trading session the reader should provide. Must be specified, since the ``reader``'s first session may not exactly align with the desired calendar. Specifically, in the case where the first session on the target calendar is a holiday on the ``reader``'s calendar. - last_trading_session : pd.Timestamp The last trading session the reader should provide. Must be specified, since the ``reader``'s last session may not exactly align with the desired calendar. Specifically, in the case where the last session on the target calendar is a holiday on the ``reader``'s calendar. """ def __init__(self, trading_calendar, reader, first_trading_session, last_trading_session): self._trading_calendar = trading_calendar self._reader = reader self._first_trading_session = first_trading_session self._last_trading_session = last_trading_session @property def last_available_dt(self): return self._reader.last_available_dt def get_last_traded_dt(self, sid, dt): return self._reader.get_last_traded_dt(sid, dt) @property def first_trading_day(self): return self._reader.first_trading_day def get_value(self, sid, dt, field): # Give an empty result if no data is present. try: return self._reader.get_value(sid, dt, field) except NoDataOnDate: if field == 'volume': return 0 else: return np.nan @abstractmethod def _outer_dts(self, start_dt, end_dt): raise NotImplementedError @abstractmethod def _inner_dts(self, start_dt, end_dt): raise NotImplementedError @property def trading_calendar(self): return self._trading_calendar @lazyval def sessions(self): return self.trading_calendar.sessions_in_range( self._first_trading_session, self._last_trading_session ) def load_raw_arrays(self, fields, start_dt, end_dt, sids): outer_dts = self._outer_dts(start_dt, end_dt) inner_dts = self._inner_dts(start_dt, end_dt) indices = outer_dts.searchsorted(inner_dts) shape = len(outer_dts), len(sids) outer_results = [] if len(inner_dts) > 0: inner_results = self._reader.load_raw_arrays( fields, inner_dts[0], inner_dts[-1], sids) else: inner_results = None for i, field in enumerate(fields): if field != 'volume': out = np.full(shape, np.nan) else: out = np.zeros(shape, dtype=np.uint32) if inner_results is not None: out[indices] = inner_results[i] outer_results.append(out) return outer_results class ReindexMinuteBarReader(ReindexBarReader, MinuteBarReader): """ See: ``ReindexBarReader`` """ def _outer_dts(self, start_dt, end_dt): return self._trading_calendar.minutes_in_range(start_dt, end_dt) def _inner_dts(self, start_dt, end_dt): return self._reader.calendar.minutes_in_range(start_dt, end_dt) class ReindexSessionBarReader(ReindexBarReader, SessionBarReader): """ See: ``ReindexBarReader`` """ def _outer_dts(self, start_dt, end_dt): return self.trading_calendar.sessions_in_range(start_dt, end_dt) def _inner_dts(self, start_dt, end_dt): return self._reader.trading_calendar.sessions_in_range( start_dt, end_dt)
36.6794
79
0.542699
from collections import OrderedDict from abc import ABCMeta, abstractmethod import numpy as np import pandas as pd from six import with_metaclass from zipline.data._resample import ( _minute_to_session_open, _minute_to_session_high, _minute_to_session_low, _minute_to_session_close, _minute_to_session_volume, ) from zipline.data.bar_reader import NoDataOnDate from zipline.data.minute_bars import MinuteBarReader from zipline.data.session_bars import SessionBarReader from zipline.utils.memoize import lazyval _MINUTE_TO_SESSION_OHCLV_HOW = OrderedDict(( ('open', 'first'), ('high', 'max'), ('low', 'min'), ('close', 'last'), ('volume', 'sum'), )) def minute_frame_to_session_frame(minute_frame, calendar): how = OrderedDict((c, _MINUTE_TO_SESSION_OHCLV_HOW[c]) for c in minute_frame.columns) return minute_frame.groupby(calendar.minute_to_session_label).agg(how) def minute_to_session(column, close_locs, data, out): if column == 'open': _minute_to_session_open(close_locs, data, out) elif column == 'high': _minute_to_session_high(close_locs, data, out) elif column == 'low': _minute_to_session_low(close_locs, data, out) elif column == 'close': _minute_to_session_close(close_locs, data, out) elif column == 'volume': _minute_to_session_volume(close_locs, data, out) return out class DailyHistoryAggregator(object): def __init__(self, market_opens, minute_reader, trading_calendar): self._market_opens = market_opens self._minute_reader = minute_reader self._trading_calendar = trading_calendar # flushed, so that the cache entries do not grow unbounded. # # Example cache: # cache = (date(2016, 3, 17), # pd.Timestamp('2016-03-17 13:31', tz='UTC'), # { # 1: (1458221460000000000, np.nan), # 2: (1458221460000000000, 42.0), # }) self._caches = { 'open': None, 'high': None, 'low': None, 'close': None, 'volume': None } # The int value is used for deltas to avoid extra computation from # creating new Timestamps. self._one_min = pd.Timedelta('1 min').value def _prelude(self, dt, field): session = self._trading_calendar.minute_to_session_label(dt) dt_value = dt.value cache = self._caches[field] if cache is None or cache[0] != session: market_open = self._market_opens.loc[session] cache = self._caches[field] = (session, market_open, {}) _, market_open, entries = cache market_open = market_open.tz_localize('UTC') if dt != market_open: prev_dt = dt_value - self._one_min else: prev_dt = None return market_open, prev_dt, dt_value, entries def opens(self, assets, dt): market_open, prev_dt, dt_value, entries = self._prelude(dt, 'open') opens = [] session_label = self._trading_calendar.minute_to_session_label(dt) for asset in assets: if not asset.is_alive_for_session(session_label): opens.append(np.NaN) continue if prev_dt is None: val = self._minute_reader.get_value(asset, dt, 'open') entries[asset] = (dt_value, val) opens.append(val) continue else: try: last_visited_dt, first_open = entries[asset] if last_visited_dt == dt_value: opens.append(first_open) continue elif not pd.isnull(first_open): opens.append(first_open) entries[asset] = (dt_value, first_open) continue else: after_last = pd.Timestamp( last_visited_dt + self._one_min, tz='UTC') window = self._minute_reader.load_raw_arrays( ['open'], after_last, dt, [asset], )[0] nonnan = window[~pd.isnull(window)] if len(nonnan): val = nonnan[0] else: val = np.nan entries[asset] = (dt_value, val) opens.append(val) continue except KeyError: window = self._minute_reader.load_raw_arrays( ['open'], market_open, dt, [asset], )[0] nonnan = window[~pd.isnull(window)] if len(nonnan): val = nonnan[0] else: val = np.nan entries[asset] = (dt_value, val) opens.append(val) continue return np.array(opens) def highs(self, assets, dt): market_open, prev_dt, dt_value, entries = self._prelude(dt, 'high') highs = [] session_label = self._trading_calendar.minute_to_session_label(dt) for asset in assets: if not asset.is_alive_for_session(session_label): highs.append(np.NaN) continue if prev_dt is None: val = self._minute_reader.get_value(asset, dt, 'high') entries[asset] = (dt_value, val) highs.append(val) continue else: try: last_visited_dt, last_max = entries[asset] if last_visited_dt == dt_value: highs.append(last_max) continue elif last_visited_dt == prev_dt: curr_val = self._minute_reader.get_value( asset, dt, 'high') if pd.isnull(curr_val): val = last_max elif pd.isnull(last_max): val = curr_val else: val = max(last_max, curr_val) entries[asset] = (dt_value, val) highs.append(val) continue else: after_last = pd.Timestamp( last_visited_dt + self._one_min, tz='UTC') window = self._minute_reader.load_raw_arrays( ['high'], after_last, dt, [asset], )[0].T val = np.nanmax(np.append(window, last_max)) entries[asset] = (dt_value, val) highs.append(val) continue except KeyError: window = self._minute_reader.load_raw_arrays( ['high'], market_open, dt, [asset], )[0].T val = np.nanmax(window) entries[asset] = (dt_value, val) highs.append(val) continue return np.array(highs) def lows(self, assets, dt): market_open, prev_dt, dt_value, entries = self._prelude(dt, 'low') lows = [] session_label = self._trading_calendar.minute_to_session_label(dt) for asset in assets: if not asset.is_alive_for_session(session_label): lows.append(np.NaN) continue if prev_dt is None: val = self._minute_reader.get_value(asset, dt, 'low') entries[asset] = (dt_value, val) lows.append(val) continue else: try: last_visited_dt, last_min = entries[asset] if last_visited_dt == dt_value: lows.append(last_min) continue elif last_visited_dt == prev_dt: curr_val = self._minute_reader.get_value( asset, dt, 'low') val = np.nanmin([last_min, curr_val]) entries[asset] = (dt_value, val) lows.append(val) continue else: after_last = pd.Timestamp( last_visited_dt + self._one_min, tz='UTC') window = self._minute_reader.load_raw_arrays( ['low'], after_last, dt, [asset], )[0].T val = np.nanmin(np.append(window, last_min)) entries[asset] = (dt_value, val) lows.append(val) continue except KeyError: window = self._minute_reader.load_raw_arrays( ['low'], market_open, dt, [asset], )[0].T val = np.nanmin(window) entries[asset] = (dt_value, val) lows.append(val) continue return np.array(lows) def closes(self, assets, dt): market_open, prev_dt, dt_value, entries = self._prelude(dt, 'close') closes = [] session_label = self._trading_calendar.minute_to_session_label(dt) def _get_filled_close(asset): window = self._minute_reader.load_raw_arrays( ['close'], market_open, dt, [asset], )[0] try: return window[~np.isnan(window)][-1] except IndexError: return np.NaN for asset in assets: if not asset.is_alive_for_session(session_label): closes.append(np.NaN) continue if prev_dt is None: val = self._minute_reader.get_value(asset, dt, 'close') entries[asset] = (dt_value, val) closes.append(val) continue else: try: last_visited_dt, last_close = entries[asset] if last_visited_dt == dt_value: closes.append(last_close) continue elif last_visited_dt == prev_dt: val = self._minute_reader.get_value( asset, dt, 'close') if pd.isnull(val): val = last_close entries[asset] = (dt_value, val) closes.append(val) continue else: val = self._minute_reader.get_value( asset, dt, 'close') if pd.isnull(val): val = _get_filled_close(asset) entries[asset] = (dt_value, val) closes.append(val) continue except KeyError: val = self._minute_reader.get_value( asset, dt, 'close') if pd.isnull(val): val = _get_filled_close(asset) entries[asset] = (dt_value, val) closes.append(val) continue return np.array(closes) def volumes(self, assets, dt): market_open, prev_dt, dt_value, entries = self._prelude(dt, 'volume') volumes = [] session_label = self._trading_calendar.minute_to_session_label(dt) for asset in assets: if not asset.is_alive_for_session(session_label): volumes.append(0) continue if prev_dt is None: val = self._minute_reader.get_value(asset, dt, 'volume') entries[asset] = (dt_value, val) volumes.append(val) continue else: try: last_visited_dt, last_total = entries[asset] if last_visited_dt == dt_value: volumes.append(last_total) continue elif last_visited_dt == prev_dt: val = self._minute_reader.get_value( asset, dt, 'volume') val += last_total entries[asset] = (dt_value, val) volumes.append(val) continue else: after_last = pd.Timestamp( last_visited_dt + self._one_min, tz='UTC') window = self._minute_reader.load_raw_arrays( ['volume'], after_last, dt, [asset], )[0] val = np.nansum(window) + last_total entries[asset] = (dt_value, val) volumes.append(val) continue except KeyError: window = self._minute_reader.load_raw_arrays( ['volume'], market_open, dt, [asset], )[0] val = np.nansum(window) entries[asset] = (dt_value, val) volumes.append(val) continue return np.array(volumes) class MinuteResampleSessionBarReader(SessionBarReader): def __init__(self, calendar, minute_bar_reader): self._calendar = calendar self._minute_bar_reader = minute_bar_reader def _get_resampled(self, columns, start_session, end_session, assets): range_open = self._calendar.session_open(start_session) range_close = self._calendar.session_close(end_session) minute_data = self._minute_bar_reader.load_raw_arrays( columns, range_open, range_close, assets, ) # Get the index of the close minute for each session in the range. # If the range contains only one session, the only close in the range # is the last minute in the data. Otherwise, we need to get all the # session closes and find their indices in the range of minutes. if start_session == end_session: close_ilocs = np.array([len(minute_data[0]) - 1], dtype=np.int64) else: minutes = self._calendar.minutes_in_range( range_open, range_close, ) session_closes = self._calendar.session_closes_in_range( start_session, end_session, ) close_ilocs = minutes.searchsorted(session_closes.values) results = [] shape = (len(close_ilocs), len(assets)) for col in columns: if col != 'volume': out = np.full(shape, np.nan) else: out = np.zeros(shape, dtype=np.uint32) results.append(out) for i in range(len(assets)): for j, column in enumerate(columns): data = minute_data[j][:, i] minute_to_session(column, close_ilocs, data, results[j][:, i]) return results @property def trading_calendar(self): return self._calendar def load_raw_arrays(self, columns, start_dt, end_dt, sids): return self._get_resampled(columns, start_dt, end_dt, sids) def get_value(self, sid, session, colname): # WARNING: This will need caching or other optimization if used in a # tight loop. # This was developed to complete interface, but has not been tuned # for real world use. return self._get_resampled([colname], session, session, [sid])[0][0][0] @lazyval def sessions(self): cal = self._calendar first = self._minute_bar_reader.first_trading_day last = cal.minute_to_session_label( self._minute_bar_reader.last_available_dt) return cal.sessions_in_range(first, last) @lazyval def last_available_dt(self): return self.trading_calendar.minute_to_session_label( self._minute_bar_reader.last_available_dt ) @property def first_trading_day(self): return self._minute_bar_reader.first_trading_day def get_last_traded_dt(self, asset, dt): return self.trading_calendar.minute_to_session_label( self._minute_bar_reader.get_last_traded_dt(asset, dt)) class ReindexBarReader(with_metaclass(ABCMeta)): def __init__(self, trading_calendar, reader, first_trading_session, last_trading_session): self._trading_calendar = trading_calendar self._reader = reader self._first_trading_session = first_trading_session self._last_trading_session = last_trading_session @property def last_available_dt(self): return self._reader.last_available_dt def get_last_traded_dt(self, sid, dt): return self._reader.get_last_traded_dt(sid, dt) @property def first_trading_day(self): return self._reader.first_trading_day def get_value(self, sid, dt, field): # Give an empty result if no data is present. try: return self._reader.get_value(sid, dt, field) except NoDataOnDate: if field == 'volume': return 0 else: return np.nan @abstractmethod def _outer_dts(self, start_dt, end_dt): raise NotImplementedError @abstractmethod def _inner_dts(self, start_dt, end_dt): raise NotImplementedError @property def trading_calendar(self): return self._trading_calendar @lazyval def sessions(self): return self.trading_calendar.sessions_in_range( self._first_trading_session, self._last_trading_session ) def load_raw_arrays(self, fields, start_dt, end_dt, sids): outer_dts = self._outer_dts(start_dt, end_dt) inner_dts = self._inner_dts(start_dt, end_dt) indices = outer_dts.searchsorted(inner_dts) shape = len(outer_dts), len(sids) outer_results = [] if len(inner_dts) > 0: inner_results = self._reader.load_raw_arrays( fields, inner_dts[0], inner_dts[-1], sids) else: inner_results = None for i, field in enumerate(fields): if field != 'volume': out = np.full(shape, np.nan) else: out = np.zeros(shape, dtype=np.uint32) if inner_results is not None: out[indices] = inner_results[i] outer_results.append(out) return outer_results class ReindexMinuteBarReader(ReindexBarReader, MinuteBarReader): def _outer_dts(self, start_dt, end_dt): return self._trading_calendar.minutes_in_range(start_dt, end_dt) def _inner_dts(self, start_dt, end_dt): return self._reader.calendar.minutes_in_range(start_dt, end_dt) class ReindexSessionBarReader(ReindexBarReader, SessionBarReader): def _outer_dts(self, start_dt, end_dt): return self.trading_calendar.sessions_in_range(start_dt, end_dt) def _inner_dts(self, start_dt, end_dt): return self._reader.trading_calendar.sessions_in_range( start_dt, end_dt)
true
true
f725827d5a741e222353b63795ed67c9692af41b
1,201
py
Python
load_testing/ial2_sign_up.locustfile.py
isabella232/identity-loadtest
d915fe5920978672246a1de46b0d9530f7d38fcc
[ "CC0-1.0" ]
null
null
null
load_testing/ial2_sign_up.locustfile.py
isabella232/identity-loadtest
d915fe5920978672246a1de46b0d9530f7d38fcc
[ "CC0-1.0" ]
1
2021-02-24T02:55:22.000Z
2021-02-24T02:55:22.000Z
load_testing/ial2_sign_up.locustfile.py
isabella232/identity-loadtest
d915fe5920978672246a1de46b0d9530f7d38fcc
[ "CC0-1.0" ]
null
null
null
from locust import HttpUser, TaskSet, task, between from common_flows import flow_ial2_proofing, flow_sign_up, flow_helper class IAL2SignUpLoad(TaskSet): # Preload drivers license data license_front = flow_helper.load_fixture("mont-front.jpeg") license_back = flow_helper.load_fixture("mont-back.jpeg") def on_start(self): print("*** Starting Sign-Up and IAL2 proof load tests ***") def on_stop(self): print("*** Ending IAL2 Sign-Up load tests ***") """ @task(<weight>) : value=3 executes 3x as often as value=1 """ """ Things inside task are synchronous. Tasks are async """ @task(1) def sign_up_and_proof_load_test(self): # Sign up flow flow_sign_up.do_sign_up(self) # Get /account page flow_helper.do_request(self, "get", "/account", "/account") # IAL2 Proofing flow flow_ial2_proofing.do_ial2_proofing(self) # Get the /account page now flow_helper.do_request(self, "get", "/account", "/account") # Now log out flow_helper.do_request(self, "get", "/logout", "/") class WebsiteUser(HttpUser): tasks = [IAL2SignUpLoad] wait_time = between(5, 9)
29.292683
70
0.654455
from locust import HttpUser, TaskSet, task, between from common_flows import flow_ial2_proofing, flow_sign_up, flow_helper class IAL2SignUpLoad(TaskSet): license_front = flow_helper.load_fixture("mont-front.jpeg") license_back = flow_helper.load_fixture("mont-back.jpeg") def on_start(self): print("*** Starting Sign-Up and IAL2 proof load tests ***") def on_stop(self): print("*** Ending IAL2 Sign-Up load tests ***") @task(1) def sign_up_and_proof_load_test(self): flow_sign_up.do_sign_up(self) flow_helper.do_request(self, "get", "/account", "/account") flow_ial2_proofing.do_ial2_proofing(self) flow_helper.do_request(self, "get", "/account", "/account") flow_helper.do_request(self, "get", "/logout", "/") class WebsiteUser(HttpUser): tasks = [IAL2SignUpLoad] wait_time = between(5, 9)
true
true
f725827e2a3d139f12b578cfd7d4e3af8491e768
927
py
Python
bin/pdbqt2pdb_ref.py
gicsaw/pdbtools
10a9441f0345d34e90ca1c454a6aa460b7da926d
[ "MIT" ]
null
null
null
bin/pdbqt2pdb_ref.py
gicsaw/pdbtools
10a9441f0345d34e90ca1c454a6aa460b7da926d
[ "MIT" ]
null
null
null
bin/pdbqt2pdb_ref.py
gicsaw/pdbtools
10a9441f0345d34e90ca1c454a6aa460b7da926d
[ "MIT" ]
null
null
null
#!/usr/bin/env python import pdbtools.ligand_tools as ligand_tools def main(): import argparse title_line = 'convert pdbqt to pdb using reference pdb file' parser = argparse.ArgumentParser(description=title_line) parser.add_argument('-i', '--input_file', required=True, help='input ligand pdbqt file') parser.add_argument('-o', '--output_file', required=True, help='output ligand pdb file') parser.add_argument('-r', '--ref_file', required=True, help='reference ligand pdb file') args = parser.parse_args() ligand_input_file = args.input_file ligand_output_file = args.output_file ref_file = args.ref_file e = ligand_tools.pdbqt_to_pdb_ref(ligand_input_file, ligand_output_file, ref_file) if e is not None: print(e) if __name__ == "__main__": main()
30.9
76
0.629989
import pdbtools.ligand_tools as ligand_tools def main(): import argparse title_line = 'convert pdbqt to pdb using reference pdb file' parser = argparse.ArgumentParser(description=title_line) parser.add_argument('-i', '--input_file', required=True, help='input ligand pdbqt file') parser.add_argument('-o', '--output_file', required=True, help='output ligand pdb file') parser.add_argument('-r', '--ref_file', required=True, help='reference ligand pdb file') args = parser.parse_args() ligand_input_file = args.input_file ligand_output_file = args.output_file ref_file = args.ref_file e = ligand_tools.pdbqt_to_pdb_ref(ligand_input_file, ligand_output_file, ref_file) if e is not None: print(e) if __name__ == "__main__": main()
true
true
f72583f1e1e8e5ca6b7b3190c8fd9abe0893dc59
9,848
py
Python
pysnmp-with-texts/CISCO-HARDWARE-IP-VERIFY-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
8
2019-05-09T17:04:00.000Z
2021-06-09T06:50:51.000Z
pysnmp-with-texts/CISCO-HARDWARE-IP-VERIFY-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
4
2019-05-31T16:42:59.000Z
2020-01-31T21:57:17.000Z
pysnmp-with-texts/CISCO-HARDWARE-IP-VERIFY-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
10
2019-04-30T05:51:36.000Z
2022-02-16T03:33:41.000Z
# # PySNMP MIB module CISCO-HARDWARE-IP-VERIFY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-HARDWARE-IP-VERIFY-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:59:41 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance") Gauge32, Integer32, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, NotificationType, iso, Unsigned32, Counter32, Bits, MibIdentifier, TimeTicks, ObjectIdentity, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Integer32", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "NotificationType", "iso", "Unsigned32", "Counter32", "Bits", "MibIdentifier", "TimeTicks", "ObjectIdentity", "IpAddress") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") ciscoHardwareIpVerifyMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 804)) ciscoHardwareIpVerifyMIB.setRevisions(('2012-09-04 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: ciscoHardwareIpVerifyMIB.setRevisionsDescriptions(('Initial version of this MIB module.',)) if mibBuilder.loadTexts: ciscoHardwareIpVerifyMIB.setLastUpdated('201209040000Z') if mibBuilder.loadTexts: ciscoHardwareIpVerifyMIB.setOrganization('Cisco Systems, Inc.') if mibBuilder.loadTexts: ciscoHardwareIpVerifyMIB.setContactInfo('Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: cs-lan-switch-snmp@cisco.com') if mibBuilder.loadTexts: ciscoHardwareIpVerifyMIB.setDescription("This MIB module defines management objects for configuration and monitoring of the Intrusion Detection System (IDS) that checks for IP packet verification. The following terms are used throughout the MIB: IDS: Intrusion Detection System CRC: Cyclic Redundancy Check DF: Don't Fragment ") ciscoHardwareIpVerifyMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 804, 0)) ciscoHardwareIpVerifyMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 804, 1)) ciscoHardwareIpVerifyMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 804, 2)) chivIpVerifyTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 804, 1, 1), ) if mibBuilder.loadTexts: chivIpVerifyTable.setStatus('current') if mibBuilder.loadTexts: chivIpVerifyTable.setDescription('A list of IDS check configuration and statistical information for each IP type and each IDS check type on the management device.') chivIpVerifyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 804, 1, 1, 1), ).setIndexNames((0, "CISCO-HARDWARE-IP-VERIFY-MIB", "chivIpVerifyCheckIpType"), (0, "CISCO-HARDWARE-IP-VERIFY-MIB", "chivIpVerifyCheckTypeName")) if mibBuilder.loadTexts: chivIpVerifyEntry.setStatus('current') if mibBuilder.loadTexts: chivIpVerifyEntry.setDescription('An entry contains the IDS packet check configuration information and the associated counters.') chivIpVerifyCheckIpType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 804, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ipv4", 1), ("ipv6", 2)))) if mibBuilder.loadTexts: chivIpVerifyCheckIpType.setStatus('current') if mibBuilder.loadTexts: chivIpVerifyCheckIpType.setDescription('This object indicates the IP address type for IDS packet check.') chivIpVerifyCheckTypeName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 804, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17))).clone(namedValues=NamedValues(("addressSrcBroadcast", 1), ("addressSrcMulticast", 2), ("addressDestZero", 3), ("addressIdentical", 4), ("addressSrcReserved", 5), ("addressClassE", 6), ("checksum", 7), ("protocol", 8), ("fragment", 9), ("lengthMinimum", 10), ("lengthConsistent", 11), ("lengthMaximumFragment", 12), ("lengthMaximumUdp", 13), ("lengthMaximumTcp", 14), ("tcpFlags", 15), ("tcpTinyFlags", 16), ("version", 17)))) if mibBuilder.loadTexts: chivIpVerifyCheckTypeName.setStatus('current') if mibBuilder.loadTexts: chivIpVerifyCheckTypeName.setDescription('This object indicates the IDS packet check type which can be configured on the device. Each check type is a specific criteria. Those IP packets that matches the certain criteria are dropped. addressSrcBroadcast(1) Drop the IPv4 packet if the source address is a broadcast IPv4 address. addressSrcMulticast(2) Drop the IPv4 packet if the source address is a multicast IPv4 address. addressDestZero(3) Drop the IPv4 packet if the destination address is 0.0.0.0. addressIdentical(4) Drop the IPv4 packet if the source IPv4 address is identical to destination IPv4 address. addressSrcReserved(5) Drop the IPv4 packet if the source address is a reserved IPv4 address. addressClassE(6) Drop the IPv4 packet if either the source address or destination address is a class E IPv4 address. checksum(7) Drops the IPv4 packet if its checksum is invalid. protocol(8) Drop the IPv4 packet if the packet fragment has an invalid IP protocol number fragment(9) Drop the IPv4 packet if the packet fragment has a nonzero offset and the DF bit is active. lengthMinimum(10) Drop the IPv4 packet if the Ethernet frame length is less than the IP packet length plus four octets (the CRC length). lengthConsistent(11) Drop the IPv4 or IPv6 packet where the Ethernet frame size is greater than or equal to the IP packet length plus the Ethernet header. lengthMaximumFragment(12) Drop the IPv4 or IPv6 packet if the maximum fragment offset is greater than 65536. lengthMaximumUdp(13) Drop the IPv4 or IPv6 packet if the IP payload length is less than the UDP packet length. lengthMaximumTcp(14) Drop the IPv4 or IPv6 packet if the TCP length is greater than the IP payload length. tcpFlags(15) Drop the IPv4 packet if verification of TCP packet header fails. tcpTinyFlags(16) Drop the IPv4 or IPv6 packet if the IP fragment offset is 1, or if the IP fragment offset is 0 and the IP payload length is less than 16. version(17) Drop the IPv4 packet if the Ethertype is not set to 4 (IPv4); and drops the IPv6 packet if the Ethertype is not set to 6 (IPv6).') chivIpVerifyCheckStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 804, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: chivIpVerifyCheckStatus.setStatus('current') if mibBuilder.loadTexts: chivIpVerifyCheckStatus.setDescription('This object specifies the IDS packet check configuration status.') chivIpVerifyPacketsDropped = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 804, 1, 1, 1, 4), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: chivIpVerifyPacketsDropped.setStatus('current') if mibBuilder.loadTexts: chivIpVerifyPacketsDropped.setDescription('This object indicates the number of packets which has been dropped.') ciscoHardwareIpVerifyMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 804, 2, 1)) ciscoHardwareIpVerifyMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 804, 2, 2)) ciscoHardwareIpVerifyMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 804, 2, 1, 1)).setObjects(("CISCO-HARDWARE-IP-VERIFY-MIB", "ciscoHardwareIpVerifyMIBStatisticGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoHardwareIpVerifyMIBCompliance = ciscoHardwareIpVerifyMIBCompliance.setStatus('current') if mibBuilder.loadTexts: ciscoHardwareIpVerifyMIBCompliance.setDescription('The compliance statement for the CISCO-HARDWARE-IP-VERIFY-MIB.') ciscoHardwareIpVerifyMIBStatisticGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 804, 2, 2, 1)).setObjects(("CISCO-HARDWARE-IP-VERIFY-MIB", "chivIpVerifyCheckStatus"), ("CISCO-HARDWARE-IP-VERIFY-MIB", "chivIpVerifyPacketsDropped")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoHardwareIpVerifyMIBStatisticGroup = ciscoHardwareIpVerifyMIBStatisticGroup.setStatus('current') if mibBuilder.loadTexts: ciscoHardwareIpVerifyMIBStatisticGroup.setDescription('A collection of objects that provides configuration and statistical information for IDS packet check.') mibBuilder.exportSymbols("CISCO-HARDWARE-IP-VERIFY-MIB", ciscoHardwareIpVerifyMIBConform=ciscoHardwareIpVerifyMIBConform, chivIpVerifyCheckIpType=chivIpVerifyCheckIpType, ciscoHardwareIpVerifyMIBStatisticGroup=ciscoHardwareIpVerifyMIBStatisticGroup, ciscoHardwareIpVerifyMIBGroups=ciscoHardwareIpVerifyMIBGroups, ciscoHardwareIpVerifyMIBCompliances=ciscoHardwareIpVerifyMIBCompliances, chivIpVerifyTable=chivIpVerifyTable, chivIpVerifyCheckStatus=chivIpVerifyCheckStatus, ciscoHardwareIpVerifyMIBObjects=ciscoHardwareIpVerifyMIBObjects, PYSNMP_MODULE_ID=ciscoHardwareIpVerifyMIB, ciscoHardwareIpVerifyMIBNotifs=ciscoHardwareIpVerifyMIBNotifs, chivIpVerifyEntry=chivIpVerifyEntry, ciscoHardwareIpVerifyMIBCompliance=ciscoHardwareIpVerifyMIBCompliance, chivIpVerifyCheckTypeName=chivIpVerifyCheckTypeName, chivIpVerifyPacketsDropped=chivIpVerifyPacketsDropped, ciscoHardwareIpVerifyMIB=ciscoHardwareIpVerifyMIB)
172.77193
2,096
0.792141
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance") Gauge32, Integer32, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, NotificationType, iso, Unsigned32, Counter32, Bits, MibIdentifier, TimeTicks, ObjectIdentity, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Integer32", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "NotificationType", "iso", "Unsigned32", "Counter32", "Bits", "MibIdentifier", "TimeTicks", "ObjectIdentity", "IpAddress") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") ciscoHardwareIpVerifyMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 804)) ciscoHardwareIpVerifyMIB.setRevisions(('2012-09-04 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: ciscoHardwareIpVerifyMIB.setRevisionsDescriptions(('Initial version of this MIB module.',)) if mibBuilder.loadTexts: ciscoHardwareIpVerifyMIB.setLastUpdated('201209040000Z') if mibBuilder.loadTexts: ciscoHardwareIpVerifyMIB.setOrganization('Cisco Systems, Inc.') if mibBuilder.loadTexts: ciscoHardwareIpVerifyMIB.setContactInfo('Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: cs-lan-switch-snmp@cisco.com') if mibBuilder.loadTexts: ciscoHardwareIpVerifyMIB.setDescription("This MIB module defines management objects for configuration and monitoring of the Intrusion Detection System (IDS) that checks for IP packet verification. The following terms are used throughout the MIB: IDS: Intrusion Detection System CRC: Cyclic Redundancy Check DF: Don't Fragment ") ciscoHardwareIpVerifyMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 804, 0)) ciscoHardwareIpVerifyMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 804, 1)) ciscoHardwareIpVerifyMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 804, 2)) chivIpVerifyTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 804, 1, 1), ) if mibBuilder.loadTexts: chivIpVerifyTable.setStatus('current') if mibBuilder.loadTexts: chivIpVerifyTable.setDescription('A list of IDS check configuration and statistical information for each IP type and each IDS check type on the management device.') chivIpVerifyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 804, 1, 1, 1), ).setIndexNames((0, "CISCO-HARDWARE-IP-VERIFY-MIB", "chivIpVerifyCheckIpType"), (0, "CISCO-HARDWARE-IP-VERIFY-MIB", "chivIpVerifyCheckTypeName")) if mibBuilder.loadTexts: chivIpVerifyEntry.setStatus('current') if mibBuilder.loadTexts: chivIpVerifyEntry.setDescription('An entry contains the IDS packet check configuration information and the associated counters.') chivIpVerifyCheckIpType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 804, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ipv4", 1), ("ipv6", 2)))) if mibBuilder.loadTexts: chivIpVerifyCheckIpType.setStatus('current') if mibBuilder.loadTexts: chivIpVerifyCheckIpType.setDescription('This object indicates the IP address type for IDS packet check.') chivIpVerifyCheckTypeName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 804, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17))).clone(namedValues=NamedValues(("addressSrcBroadcast", 1), ("addressSrcMulticast", 2), ("addressDestZero", 3), ("addressIdentical", 4), ("addressSrcReserved", 5), ("addressClassE", 6), ("checksum", 7), ("protocol", 8), ("fragment", 9), ("lengthMinimum", 10), ("lengthConsistent", 11), ("lengthMaximumFragment", 12), ("lengthMaximumUdp", 13), ("lengthMaximumTcp", 14), ("tcpFlags", 15), ("tcpTinyFlags", 16), ("version", 17)))) if mibBuilder.loadTexts: chivIpVerifyCheckTypeName.setStatus('current') if mibBuilder.loadTexts: chivIpVerifyCheckTypeName.setDescription('This object indicates the IDS packet check type which can be configured on the device. Each check type is a specific criteria. Those IP packets that matches the certain criteria are dropped. addressSrcBroadcast(1) Drop the IPv4 packet if the source address is a broadcast IPv4 address. addressSrcMulticast(2) Drop the IPv4 packet if the source address is a multicast IPv4 address. addressDestZero(3) Drop the IPv4 packet if the destination address is 0.0.0.0. addressIdentical(4) Drop the IPv4 packet if the source IPv4 address is identical to destination IPv4 address. addressSrcReserved(5) Drop the IPv4 packet if the source address is a reserved IPv4 address. addressClassE(6) Drop the IPv4 packet if either the source address or destination address is a class E IPv4 address. checksum(7) Drops the IPv4 packet if its checksum is invalid. protocol(8) Drop the IPv4 packet if the packet fragment has an invalid IP protocol number fragment(9) Drop the IPv4 packet if the packet fragment has a nonzero offset and the DF bit is active. lengthMinimum(10) Drop the IPv4 packet if the Ethernet frame length is less than the IP packet length plus four octets (the CRC length). lengthConsistent(11) Drop the IPv4 or IPv6 packet where the Ethernet frame size is greater than or equal to the IP packet length plus the Ethernet header. lengthMaximumFragment(12) Drop the IPv4 or IPv6 packet if the maximum fragment offset is greater than 65536. lengthMaximumUdp(13) Drop the IPv4 or IPv6 packet if the IP payload length is less than the UDP packet length. lengthMaximumTcp(14) Drop the IPv4 or IPv6 packet if the TCP length is greater than the IP payload length. tcpFlags(15) Drop the IPv4 packet if verification of TCP packet header fails. tcpTinyFlags(16) Drop the IPv4 or IPv6 packet if the IP fragment offset is 1, or if the IP fragment offset is 0 and the IP payload length is less than 16. version(17) Drop the IPv4 packet if the Ethertype is not set to 4 (IPv4); and drops the IPv6 packet if the Ethertype is not set to 6 (IPv6).') chivIpVerifyCheckStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 804, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: chivIpVerifyCheckStatus.setStatus('current') if mibBuilder.loadTexts: chivIpVerifyCheckStatus.setDescription('This object specifies the IDS packet check configuration status.') chivIpVerifyPacketsDropped = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 804, 1, 1, 1, 4), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: chivIpVerifyPacketsDropped.setStatus('current') if mibBuilder.loadTexts: chivIpVerifyPacketsDropped.setDescription('This object indicates the number of packets which has been dropped.') ciscoHardwareIpVerifyMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 804, 2, 1)) ciscoHardwareIpVerifyMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 804, 2, 2)) ciscoHardwareIpVerifyMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 804, 2, 1, 1)).setObjects(("CISCO-HARDWARE-IP-VERIFY-MIB", "ciscoHardwareIpVerifyMIBStatisticGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoHardwareIpVerifyMIBCompliance = ciscoHardwareIpVerifyMIBCompliance.setStatus('current') if mibBuilder.loadTexts: ciscoHardwareIpVerifyMIBCompliance.setDescription('The compliance statement for the CISCO-HARDWARE-IP-VERIFY-MIB.') ciscoHardwareIpVerifyMIBStatisticGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 804, 2, 2, 1)).setObjects(("CISCO-HARDWARE-IP-VERIFY-MIB", "chivIpVerifyCheckStatus"), ("CISCO-HARDWARE-IP-VERIFY-MIB", "chivIpVerifyPacketsDropped")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoHardwareIpVerifyMIBStatisticGroup = ciscoHardwareIpVerifyMIBStatisticGroup.setStatus('current') if mibBuilder.loadTexts: ciscoHardwareIpVerifyMIBStatisticGroup.setDescription('A collection of objects that provides configuration and statistical information for IDS packet check.') mibBuilder.exportSymbols("CISCO-HARDWARE-IP-VERIFY-MIB", ciscoHardwareIpVerifyMIBConform=ciscoHardwareIpVerifyMIBConform, chivIpVerifyCheckIpType=chivIpVerifyCheckIpType, ciscoHardwareIpVerifyMIBStatisticGroup=ciscoHardwareIpVerifyMIBStatisticGroup, ciscoHardwareIpVerifyMIBGroups=ciscoHardwareIpVerifyMIBGroups, ciscoHardwareIpVerifyMIBCompliances=ciscoHardwareIpVerifyMIBCompliances, chivIpVerifyTable=chivIpVerifyTable, chivIpVerifyCheckStatus=chivIpVerifyCheckStatus, ciscoHardwareIpVerifyMIBObjects=ciscoHardwareIpVerifyMIBObjects, PYSNMP_MODULE_ID=ciscoHardwareIpVerifyMIB, ciscoHardwareIpVerifyMIBNotifs=ciscoHardwareIpVerifyMIBNotifs, chivIpVerifyEntry=chivIpVerifyEntry, ciscoHardwareIpVerifyMIBCompliance=ciscoHardwareIpVerifyMIBCompliance, chivIpVerifyCheckTypeName=chivIpVerifyCheckTypeName, chivIpVerifyPacketsDropped=chivIpVerifyPacketsDropped, ciscoHardwareIpVerifyMIB=ciscoHardwareIpVerifyMIB)
true
true
f72583f3abd30086f322b31d478f793386b37978
1,402
py
Python
plugins/infocenteruri.py
LandGrey/taoman
3ad45823e7af0a8a9ee6e1296446c3a6aab43fe4
[ "MIT" ]
207
2017-05-03T10:31:45.000Z
2022-03-26T09:49:03.000Z
plugins/infocenteruri.py
the8robot/taoman
3ad45823e7af0a8a9ee6e1296446c3a6aab43fe4
[ "MIT" ]
1
2020-03-29T03:28:29.000Z
2020-03-29T04:41:03.000Z
plugins/infocenteruri.py
the8robot/taoman
3ad45823e7af0a8a9ee6e1296446c3a6aab43fe4
[ "MIT" ]
59
2017-05-06T02:43:36.000Z
2022-01-22T12:39:07.000Z
#!/usr/bin/env python # coding:utf-8 # """ Copyright (c) 2017 LandGrey (https://github.com/LandGrey/taoman) License: MIT """ import urllib import requests from lib.fun import crawl_link_handle from lib.config import baidu_base_url, get_head, timeout, baidu_first_pattern, self_pattern, intranet_ip_pattern, \ ip_simple_pattern def crawlinfocenter(domain): domains = [] data = {'wd': 'site:{0} 信息化|网络中心'.format(domain)} requests.packages.urllib3.disable_warnings() req = requests.get(baidu_base_url + urllib.urlencode(data), headers=get_head(), timeout=timeout, verify=False) content = req.text match = baidu_first_pattern.findall(content) if match: info_center_url = crawl_link_handle(match[0][0]) reqs = requests.get('http://' + info_center_url, headers=get_head(), timeout=timeout, verify=False) matchs = self_pattern.findall(reqs.text) for m in matchs: domains.append(crawl_link_handle(m) if domain in m else (crawl_link_handle(m) if ip_simple_pattern.findall(crawl_link_handle(m) if not intranet_ip_pattern.findall(crawl_link_handle(m)) else '') else '')) return domains
38.944444
118
0.599857
import urllib import requests from lib.fun import crawl_link_handle from lib.config import baidu_base_url, get_head, timeout, baidu_first_pattern, self_pattern, intranet_ip_pattern, \ ip_simple_pattern def crawlinfocenter(domain): domains = [] data = {'wd': 'site:{0} 信息化|网络中心'.format(domain)} requests.packages.urllib3.disable_warnings() req = requests.get(baidu_base_url + urllib.urlencode(data), headers=get_head(), timeout=timeout, verify=False) content = req.text match = baidu_first_pattern.findall(content) if match: info_center_url = crawl_link_handle(match[0][0]) reqs = requests.get('http://' + info_center_url, headers=get_head(), timeout=timeout, verify=False) matchs = self_pattern.findall(reqs.text) for m in matchs: domains.append(crawl_link_handle(m) if domain in m else (crawl_link_handle(m) if ip_simple_pattern.findall(crawl_link_handle(m) if not intranet_ip_pattern.findall(crawl_link_handle(m)) else '') else '')) return domains
true
true
f725848078385894b2570cd95107b891abee18ba
7,574
py
Python
file_hash.py
XVicarious/file_hash
ebab0151dbbd2d162742008d9088ad03a38f495e
[ "MIT" ]
null
null
null
file_hash.py
XVicarious/file_hash
ebab0151dbbd2d162742008d9088ad03a38f495e
[ "MIT" ]
1
2018-10-27T09:02:13.000Z
2018-10-27T09:02:13.000Z
file_hash.py
XVicarious/file_hash
ebab0151dbbd2d162742008d9088ad03a38f495e
[ "MIT" ]
null
null
null
"""Hash your files for easy identification.""" import hashlib import logging import os from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from typing import Dict from flexget import plugin from flexget.event import event from flexget.logger import FlexGetLogger from .cunit import IECUnit PLUGIN_ID = 'file_hash' log: FlexGetLogger = logging.getLogger(PLUGIN_ID) class FileHashPlugin(object): """ Task class that does the hashing. By default file_hash will: - Use blake2b if it is available, otherwise it will use MD5 - Start at 50MiB into the file - If the file is less than 50MiB, it starts at the beginning - Hashes 25MiB of the file after the starting point - If the file does not have 25MiB after the starting point, it will hash from the starting point to the end - Choose MAX two 'size', 'start', 'stop' Examples: # Use file_hash with the default settings. file_hash: yes # Use sha1 with the rest of the default settings file_hash: sha1 # Hash 1MiB, 25MiB into the file with algorithm SHA256 file_hash: algorithm: sha256 size: 1 start: 25 # Hash from 25MiB in to 35MiB in file_hash: start: 25 stop: 35 """ @staticmethod def __default_algo(): return 'blake2b' if 'blake2b' in hashlib.algorithms_available else 'md5' hash_size_default = 25 hash_start_default = 50 schema = { 'oneOf': [ {'type': 'boolean'}, {'type': 'string', 'enum': list(hashlib.algorithms_available)}, {'type': 'object', 'properties': { 'algorithm': { 'type': 'string', 'enum': list(hashlib.algorithms_available)}, 'size': {'type': 'integer', 'default': hash_size_default}, 'start': {'type': 'integer', 'default': hash_start_default}, 'stop': {'type': 'integer'}, 'time': {'type': 'boolean', 'default': 'boolean'}}}, ], } plugin_fields = {'file_hash_type', 'file_hash_hash', 'file_hash_modified', 'file_hash_bytes'} @staticmethod def __strict_boolean(check): if isinstance(check, bool) and check: return True return False def __get_algo(self, config): return self.__default_algo() def compare_entry(self, entry, config): if 'file_hash' in entry: file_hash = entry['file_hash'] match_algo = file_hash.algorithm == self.__get_algo(config) match_file_size = file_hash.file_size == os.path.getsize(entry['location']) match_modified = file_hash.modified == os.path.getmtime(entry['location']) match_start = file_hash.start == config.get('start') match_stop = file_hash.stop == config.get('stop') match_chunk_size = file_hash.chunk_size == config.get('size') match_strict = match_file_size and match_start and match_stop and match_chunk_size if match_algo and match_strict: return True return False def on_task_metainfo(self, task, config): """Call the plugin.""" log.info('Starting file_hash') # todo: add conditions to adapt to users' configuration if self.__strict_boolean(config): config = {True} hash_portion = { 'algorithm': self.__get_algo(config), 'size': IECUnit.MiB * (config['size'] if 'size' in config else self.hash_size_default), 'start': IECUnit.MiB * (config['start'] if 'start' in config else self.hash_start_default), 'stop': IECUnit.MiB * (config['stop'] if 'stop' in config else -1), } hasher = hashlib.new(hash_portion['algorithm']) log.verbose('Hasing with algorithm: %s', hash_portion['algorithm']) log.debug('Hashing %s MiB of each file.', hash_portion['size']) log.debug('Hashing starting %s MiB into file.', hash_portion['start']) log.debug('Hashing ending at %s MiB.', hash_portion['stop']) len_entries = len(task.entries) idx = 0 for entry in task.entries: idx += 1 file_size = os.path.getsize(entry['location']) if self.compare_entry(entry, config): log.verbose('This file seems to be unmodified, skipping') continue log.verbose('%s/%s: Hasing %s', idx, len_entries, entry['location']) current_hasher = hasher.copy() tmp_hash_portion_start = -1 if file_size < hash_portion['start']: log.debug('The file is only %s MiB, adjusting start location.', float(file_size / IECUnit.MiB)) if file_size < hash_portion['size']: log.debug('The file is less than the set size to to hash, setting start position to 0') tmp_hash_portion_start = 0 else: tmp_hash_portion_start = file_size - hash_portion['size'] log.debug('The size of the file is greater than the set size to hash, \ setting start position to %s MiB', tmp_hash_portion_start) with open(entry['location'], 'rb') as to_hash: to_hash.seek(tmp_hash_portion_start if tmp_hash_portion_start > -1 else hash_portion['start']) piece = to_hash.read(hash_portion['size']) current_hasher.update(piece) file_digest = current_hasher.hexdigest() file_modified = os.path.getmtime(entry['location']) filehash = FileHash(hash_portion, file_digest, file_modified, file_size) entry['file_hash'] = filehash log.debug(filehash) to_hash.close() class FileHash(object): """Store the information from the hashing.""" algorithm = None file_hash = None modified = None start = None stop = None chunk_size = None size = None def __init__(self, config_settings: Dict, file_hash, modified, size): """ Initialize a FileHash object. config_settings -- ends up being the config for the plugin file_hash -- the hash of the file modified -- last time the file was modified size -- size of the file in bytes """ self.algorithm = config_settings['algorithm'] self.start = config_settings['start'] self.stop = config_settings['stop'] self.chunk_size = config_settings['size'] self.file_hash = file_hash self.modified = modified self.size = size def __eq__(self, other): return isinstance(other, FileHash) and\ self.algorithm == other.algorithm and\ self.file_hash == other.file_hash def __repr__(self): """Represent a FileHash.""" return """<FileHash: \ algorithm={0}, \ start={1}, stop={2}, \ chunk_size={3}, \ file_hash={4}, \ modified={5}, \ size={6}""".format( self.algorithm, self.start, self.stop, self.chunk_size, self.file_hash, self.modified, self.size) @event('plugin.register') def register_plugin(): plugin.register(FileHashPlugin, PLUGIN_ID, api_ver=2, interfaces=['task', 'series_metainfo', 'movie_metainfo'])
37.127451
115
0.591761
import hashlib import logging import os from builtins import * from typing import Dict from flexget import plugin from flexget.event import event from flexget.logger import FlexGetLogger from .cunit import IECUnit PLUGIN_ID = 'file_hash' log: FlexGetLogger = logging.getLogger(PLUGIN_ID) class FileHashPlugin(object): @staticmethod def __default_algo(): return 'blake2b' if 'blake2b' in hashlib.algorithms_available else 'md5' hash_size_default = 25 hash_start_default = 50 schema = { 'oneOf': [ {'type': 'boolean'}, {'type': 'string', 'enum': list(hashlib.algorithms_available)}, {'type': 'object', 'properties': { 'algorithm': { 'type': 'string', 'enum': list(hashlib.algorithms_available)}, 'size': {'type': 'integer', 'default': hash_size_default}, 'start': {'type': 'integer', 'default': hash_start_default}, 'stop': {'type': 'integer'}, 'time': {'type': 'boolean', 'default': 'boolean'}}}, ], } plugin_fields = {'file_hash_type', 'file_hash_hash', 'file_hash_modified', 'file_hash_bytes'} @staticmethod def __strict_boolean(check): if isinstance(check, bool) and check: return True return False def __get_algo(self, config): return self.__default_algo() def compare_entry(self, entry, config): if 'file_hash' in entry: file_hash = entry['file_hash'] match_algo = file_hash.algorithm == self.__get_algo(config) match_file_size = file_hash.file_size == os.path.getsize(entry['location']) match_modified = file_hash.modified == os.path.getmtime(entry['location']) match_start = file_hash.start == config.get('start') match_stop = file_hash.stop == config.get('stop') match_chunk_size = file_hash.chunk_size == config.get('size') match_strict = match_file_size and match_start and match_stop and match_chunk_size if match_algo and match_strict: return True return False def on_task_metainfo(self, task, config): log.info('Starting file_hash') if self.__strict_boolean(config): config = {True} hash_portion = { 'algorithm': self.__get_algo(config), 'size': IECUnit.MiB * (config['size'] if 'size' in config else self.hash_size_default), 'start': IECUnit.MiB * (config['start'] if 'start' in config else self.hash_start_default), 'stop': IECUnit.MiB * (config['stop'] if 'stop' in config else -1), } hasher = hashlib.new(hash_portion['algorithm']) log.verbose('Hasing with algorithm: %s', hash_portion['algorithm']) log.debug('Hashing %s MiB of each file.', hash_portion['size']) log.debug('Hashing starting %s MiB into file.', hash_portion['start']) log.debug('Hashing ending at %s MiB.', hash_portion['stop']) len_entries = len(task.entries) idx = 0 for entry in task.entries: idx += 1 file_size = os.path.getsize(entry['location']) if self.compare_entry(entry, config): log.verbose('This file seems to be unmodified, skipping') continue log.verbose('%s/%s: Hasing %s', idx, len_entries, entry['location']) current_hasher = hasher.copy() tmp_hash_portion_start = -1 if file_size < hash_portion['start']: log.debug('The file is only %s MiB, adjusting start location.', float(file_size / IECUnit.MiB)) if file_size < hash_portion['size']: log.debug('The file is less than the set size to to hash, setting start position to 0') tmp_hash_portion_start = 0 else: tmp_hash_portion_start = file_size - hash_portion['size'] log.debug('The size of the file is greater than the set size to hash, \ setting start position to %s MiB', tmp_hash_portion_start) with open(entry['location'], 'rb') as to_hash: to_hash.seek(tmp_hash_portion_start if tmp_hash_portion_start > -1 else hash_portion['start']) piece = to_hash.read(hash_portion['size']) current_hasher.update(piece) file_digest = current_hasher.hexdigest() file_modified = os.path.getmtime(entry['location']) filehash = FileHash(hash_portion, file_digest, file_modified, file_size) entry['file_hash'] = filehash log.debug(filehash) to_hash.close() class FileHash(object): algorithm = None file_hash = None modified = None start = None stop = None chunk_size = None size = None def __init__(self, config_settings: Dict, file_hash, modified, size): self.algorithm = config_settings['algorithm'] self.start = config_settings['start'] self.stop = config_settings['stop'] self.chunk_size = config_settings['size'] self.file_hash = file_hash self.modified = modified self.size = size def __eq__(self, other): return isinstance(other, FileHash) and\ self.algorithm == other.algorithm and\ self.file_hash == other.file_hash def __repr__(self): return """<FileHash: \ algorithm={0}, \ start={1}, stop={2}, \ chunk_size={3}, \ file_hash={4}, \ modified={5}, \ size={6}""".format( self.algorithm, self.start, self.stop, self.chunk_size, self.file_hash, self.modified, self.size) @event('plugin.register') def register_plugin(): plugin.register(FileHashPlugin, PLUGIN_ID, api_ver=2, interfaces=['task', 'series_metainfo', 'movie_metainfo'])
true
true
f72585050c810ea13194c609b96660990583ebbd
2,046
py
Python
Day-04/part2.py
archanpatkar/advent2021
8e0780cd28b5825af092e4ba8e3d9cd1059bce92
[ "MIT" ]
null
null
null
Day-04/part2.py
archanpatkar/advent2021
8e0780cd28b5825af092e4ba8e3d9cd1059bce92
[ "MIT" ]
null
null
null
Day-04/part2.py
archanpatkar/advent2021
8e0780cd28b5825af092e4ba8e3d9cd1059bce92
[ "MIT" ]
null
null
null
import sys sys.path.append("..") from common import * def parse(d): temp = d.strip().split("\n") first = tuple([int(n) for n in temp[0].strip().split(",")]) second = [] temp2 = [] print(temp) for r in temp[1:]: # print(r) if(len(r) == 0): second.append(tuple(temp2)) temp2 = [] else: temp2.append(tuple([int(n) for n in r.split(" ") if(len(n) > 0)])) second.append(tuple(temp2)) print(first) print(second) return (first,second) data = aoci(parse) boards = [b for b in data[1] if len(b) > 0] print("boards") print(boards) print("-----------------------------") pos = {b:{} for b in boards} winners = [] winners2 = [] winner = None i = 0 draw = None found = None for draw in data[0]: print("Draw:",draw) for board in boards: for l in range(len(board)): if draw in board[l]: if not pos[board].get((l,board[l].index(draw))): pos[board][(l,board[l].index(draw))] = [] pos[board][(l,board[l].index(draw))] = draw nd = {b:{} for b in pos} for b in boards: if(not(b in winners2)): for i in range(5): nd[b][(i,0)] = 0 nd[b][(0,i)] = 0 nd[b][(0,0,"C")] = 0 for k in pos[b]: nd[b][(k[0],0)] += 1 if(k[1] == 0): nd[b][(0,0,"C")] += 1 else: nd[b][(0,k[1])] += 1 for s in nd[b]: if(nd[b][s] >= 5): found = (b,nd[b],pos[b],draw) winners.append(found) winners2.append(b) break if len(winners) == len(boards): break if(winner == None): winner = winners[-1] pprint(winner,indent=4) sum = 0 for i in range(5): for j in range(5): if not((i,j) in winner[2]): print(winner[0][i][j]) sum += winner[0][i][j] print("output") print(sum) print(draw) print(sum * winner[-1])
25.575
78
0.451124
import sys sys.path.append("..") from common import * def parse(d): temp = d.strip().split("\n") first = tuple([int(n) for n in temp[0].strip().split(",")]) second = [] temp2 = [] print(temp) for r in temp[1:]: if(len(r) == 0): second.append(tuple(temp2)) temp2 = [] else: temp2.append(tuple([int(n) for n in r.split(" ") if(len(n) > 0)])) second.append(tuple(temp2)) print(first) print(second) return (first,second) data = aoci(parse) boards = [b for b in data[1] if len(b) > 0] print("boards") print(boards) print("-----------------------------") pos = {b:{} for b in boards} winners = [] winners2 = [] winner = None i = 0 draw = None found = None for draw in data[0]: print("Draw:",draw) for board in boards: for l in range(len(board)): if draw in board[l]: if not pos[board].get((l,board[l].index(draw))): pos[board][(l,board[l].index(draw))] = [] pos[board][(l,board[l].index(draw))] = draw nd = {b:{} for b in pos} for b in boards: if(not(b in winners2)): for i in range(5): nd[b][(i,0)] = 0 nd[b][(0,i)] = 0 nd[b][(0,0,"C")] = 0 for k in pos[b]: nd[b][(k[0],0)] += 1 if(k[1] == 0): nd[b][(0,0,"C")] += 1 else: nd[b][(0,k[1])] += 1 for s in nd[b]: if(nd[b][s] >= 5): found = (b,nd[b],pos[b],draw) winners.append(found) winners2.append(b) break if len(winners) == len(boards): break if(winner == None): winner = winners[-1] pprint(winner,indent=4) sum = 0 for i in range(5): for j in range(5): if not((i,j) in winner[2]): print(winner[0][i][j]) sum += winner[0][i][j] print("output") print(sum) print(draw) print(sum * winner[-1])
true
true
f7258523558bf650489ce11f89d5a70fe2400656
1,042
py
Python
dts_test_project/dts_test_app/migrations/0001_initial.py
pvandegeer/django-tenant-schemas
20c72782cee51a33fd5c56a0af7b2c653c1b6770
[ "MIT" ]
2
2018-08-14T07:37:06.000Z
2018-09-27T11:20:54.000Z
dts_test_project/dts_test_app/migrations/0001_initial.py
pvandegeer/django-tenant-schemas
20c72782cee51a33fd5c56a0af7b2c653c1b6770
[ "MIT" ]
1
2021-01-25T09:48:27.000Z
2021-01-25T09:48:27.000Z
dts_test_project/dts_test_app/migrations/0001_initial.py
pvandegeer/django-tenant-schemas
20c72782cee51a33fd5c56a0af7b2c653c1b6770
[ "MIT" ]
3
2018-08-14T07:37:08.000Z
2021-04-24T07:52:00.000Z
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='DummyModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=100)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='ModelWithFkToPublicUser', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), ]
28.944444
114
0.56238
from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='DummyModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=100)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='ModelWithFkToPublicUser', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), ]
true
true
f7258581d63de21fec44899869d8d610223ca22b
2,803
py
Python
src/redgrease/cluster.py
jsam/redgrease
245755b34bce287c63abb6624478cdf8189816b6
[ "MIT" ]
null
null
null
src/redgrease/cluster.py
jsam/redgrease
245755b34bce287c63abb6624478cdf8189816b6
[ "MIT" ]
null
null
null
src/redgrease/cluster.py
jsam/redgrease
245755b34bce287c63abb6624478cdf8189816b6
[ "MIT" ]
null
null
null
from typing import Callable, Dict import rediscluster import rediscluster.exceptions import redgrease.client import redgrease.data import redgrease.utils class RedisCluster(rediscluster.RedisCluster): """RedisCluster client class, with support for gears features Behaves exactly like the rediscluster.RedisCluster client, but is extended with a 'gears' property fo executiong Gears commands. Attributes: gears (redgrease.client.Gears): Gears command client. """ # States how target node is selected for cluster commands: # - blocked : command is not allowed - Raises a RedisClusterException # - random : excuted on one randomly selected node # - all-masters : executed on all master node # - all-nodes : executed on all nodes # - slot-id : executed on the node defined by the second argument NODES_FLAGS = { **rediscluster.RedisCluster.NODES_FLAGS, **{ "RG.INFOCLUSTER": "random", "RG.PYSTATS": "all-nodes", "RG.PYDUMPREQS": "random", "RG.REFRESHCLUSTER": "all-nodes", "RG.DUMPEXECUTIONS": "random", "RG.DUMPREGISTRATIONS": "random", }, } # Not to be confused with redis.Redis.RESPONSE_CALLBACKS # RESULT_CALLBACKS is special to rediscluster.RedisCluster. # It decides how results of commands defined in `NODES_FLAGS` are aggregated into # a final response, **after** redis.Redis.RESPONSE_CALLBACKS as been applied to # each response individually. RESULT_CALLBACKS = { **rediscluster.RedisCluster.RESULT_CALLBACKS, **{ "RG.INFOCLUSTER": lambda _, res: next(iter(res.values())), "RG.PYSTATS": lambda _, res: res, "RG.PYDUMPREQS": lambda _, res: next(iter(res.values())), "RG.REFRESHCLUSTER": lambda _, res: all(res.values()), }, } RESPONSE_CALLBACKS: Dict[str, Callable] = { **rediscluster.RedisCluster.RESPONSE_CALLBACKS, **redgrease.client.Gears.RESPONSE_CALLBACKS, } def __init__(self, *args, **kwargs): """Instantiate a redis cluster client, with gears features""" self._gears = None self.connection = None super().__init__(*args, **kwargs) @property def gears(self) -> redgrease.client.Gears: """Gears client, exposing gears commands Returns: Gears: Gears client """ if not self._gears: self._gears = redgrease.client.Gears(self) return self._gears def RedisGears(*args, **kwargs): try: return RedisCluster(*args, **kwargs) except (AttributeError, rediscluster.exceptions.RedisClusterException): return redgrease.client.Redis(*args, **kwargs)
32.593023
85
0.642526
from typing import Callable, Dict import rediscluster import rediscluster.exceptions import redgrease.client import redgrease.data import redgrease.utils class RedisCluster(rediscluster.RedisCluster): NODES_FLAGS = { **rediscluster.RedisCluster.NODES_FLAGS, **{ "RG.INFOCLUSTER": "random", "RG.PYSTATS": "all-nodes", "RG.PYDUMPREQS": "random", "RG.REFRESHCLUSTER": "all-nodes", "RG.DUMPEXECUTIONS": "random", "RG.DUMPREGISTRATIONS": "random", }, } RESULT_CALLBACKS = { **rediscluster.RedisCluster.RESULT_CALLBACKS, **{ "RG.INFOCLUSTER": lambda _, res: next(iter(res.values())), "RG.PYSTATS": lambda _, res: res, "RG.PYDUMPREQS": lambda _, res: next(iter(res.values())), "RG.REFRESHCLUSTER": lambda _, res: all(res.values()), }, } RESPONSE_CALLBACKS: Dict[str, Callable] = { **rediscluster.RedisCluster.RESPONSE_CALLBACKS, **redgrease.client.Gears.RESPONSE_CALLBACKS, } def __init__(self, *args, **kwargs): self._gears = None self.connection = None super().__init__(*args, **kwargs) @property def gears(self) -> redgrease.client.Gears: if not self._gears: self._gears = redgrease.client.Gears(self) return self._gears def RedisGears(*args, **kwargs): try: return RedisCluster(*args, **kwargs) except (AttributeError, rediscluster.exceptions.RedisClusterException): return redgrease.client.Redis(*args, **kwargs)
true
true
f72587485c282a74d27d67de475830aad98af691
1,316
py
Python
elpips/util.py
niopeng/elpips
385012a2ee614c75a1631546c391039af85744f4
[ "BSD-2-Clause" ]
88
2019-06-13T10:42:26.000Z
2022-03-30T07:36:20.000Z
elpips/util.py
niopeng/elpips
385012a2ee614c75a1631546c391039af85744f4
[ "BSD-2-Clause" ]
4
2019-11-13T23:11:33.000Z
2021-07-21T11:04:08.000Z
elpips/util.py
niopeng/elpips
385012a2ee614c75a1631546c391039af85744f4
[ "BSD-2-Clause" ]
18
2019-06-10T16:31:10.000Z
2022-01-04T03:48:57.000Z
import tensorflow as tf import numpy as np def switch_case_cond(cases, default_case): if cases: condition, effect = cases[0] return tf.cond(condition, effect, lambda: switch_case_cond(cases[1:], default_case)) return default_case() def switch_case_where(cases, default_case): if cases: condition, effect = cases[0] return tf.where(condition, effect, switch_case_where(cases[1:], default_case)) return default_case def np_dtype(tf_dtype): if tf_dtype == tf.float32: return np.float32 if tf_dtype == tf.float64: return np.float64 raise Exception('Unsupported dtype') def f32_to_dtype(x, dtype): if dtype == tf.float32: return x return tf.cast(x, dtype) def as_tuple(x): '''Formats x as a tuple. If x is already a tuple returns it as is, otherwise returns a 1-tuple containing x.''' if isinstance(x, tuple): return x else: return (x,) def for_each(x, func): '''Runs 'func' for x, or each item of x if x is a tuple. Returns the results in the same format.''' if isinstance(x, tuple): return tuple((func(s) for s in x)) else: return func(x) def for_tuple(x, func): '''Runs 'func' for as_tuple(x). Returns the results in the original format. Assumes 'func' returns tuple when given tuple.''' if isinstance(x, tuple): return func(x) else: return func(as_tuple(x))[0]
25.803922
126
0.715046
import tensorflow as tf import numpy as np def switch_case_cond(cases, default_case): if cases: condition, effect = cases[0] return tf.cond(condition, effect, lambda: switch_case_cond(cases[1:], default_case)) return default_case() def switch_case_where(cases, default_case): if cases: condition, effect = cases[0] return tf.where(condition, effect, switch_case_where(cases[1:], default_case)) return default_case def np_dtype(tf_dtype): if tf_dtype == tf.float32: return np.float32 if tf_dtype == tf.float64: return np.float64 raise Exception('Unsupported dtype') def f32_to_dtype(x, dtype): if dtype == tf.float32: return x return tf.cast(x, dtype) def as_tuple(x): if isinstance(x, tuple): return x else: return (x,) def for_each(x, func): if isinstance(x, tuple): return tuple((func(s) for s in x)) else: return func(x) def for_tuple(x, func): if isinstance(x, tuple): return func(x) else: return func(as_tuple(x))[0]
true
true
f72587bcc4673fe9fd1a8a3ffec34ab4d833f88b
5,113
py
Python
src/estimagic/benchmarking/run_benchmark.py
PaulBehler/estimagic
c14f743986262d508e55738c90737cb504fe987b
[ "MIT" ]
7
2019-05-11T07:19:46.000Z
2019-05-31T07:03:13.000Z
src/estimagic/benchmarking/run_benchmark.py
PaulBehler/estimagic
c14f743986262d508e55738c90737cb504fe987b
[ "MIT" ]
14
2019-05-04T14:15:52.000Z
2019-06-10T11:45:27.000Z
src/estimagic/benchmarking/run_benchmark.py
PaulBehler/estimagic
c14f743986262d508e55738c90737cb504fe987b
[ "MIT" ]
1
2019-05-21T08:44:37.000Z
2019-05-21T08:44:37.000Z
"""Functions to create, run and visualize optimization benchmarks. TO-DO: - Add other benchmark sets: - finish medium scale problems from https://arxiv.org/pdf/1710.11005.pdf, Page 34. - add scalar problems from https://github.com/AxelThevenot - Add option for deterministic noise or wiggle. """ from pathlib import Path import numpy as np from estimagic import batch_evaluators from estimagic.logging.read_log import read_optimization_histories from estimagic.optimization.optimize import minimize def run_benchmark( problems, optimize_options, logging_directory, *, batch_evaluator="joblib", n_cores=1, error_handling="continue", fast_logging=True, seed=None, ): """Run problems with different optimize options. Args: problems (dict): Nested dictionary with benchmark problems of the structure: {"name": {"inputs": {...}, "solution": {...}, "info": {...}}} where "inputs" are keyword arguments for ``minimize`` such as the criterion function and start parameters. "solution" contains the entries "params" and "value" and "info" might contain information about the test problem. optimize_options (list or dict): Either a list of algorithms or a Nested dictionary that maps a name for optimizer settings (e.g. ``"lbfgsb_strict_criterion"``) to a dictionary of keyword arguments for arguments for ``minimize`` (e.g. ``{"algorithm": "scipy_lbfgsb", "algo_options": {"convergence.relative_criterion_tolerance": 1e-12}}``). Alternatively, the values can just be an algorithm which is then benchmarked at default settings. batch_evaluator (str or callable): See :ref:`batch_evaluators`. logging_directory (pathlib.Path): Directory in which the log databases are saved. n_cores (int): Number of optimizations that is run in parallel. Note that in addition to that an optimizer might parallelize. error_handling (str): One of "raise", "continue". fast_logging (bool): Whether the slightly unsafe but much faster database configuration is chosen. Returns: dict: Nested Dictionary with information on the benchmark run. The outer keys are tuples where the first entry is the name of the problem and the second the name of the optimize options. The values are dicts with the entries: "runtime", "params_history", "criterion_history", "solution" """ np.random.seed(seed) logging_directory = Path(logging_directory) logging_directory.mkdir(parents=True, exist_ok=True) if isinstance(batch_evaluator, str): batch_evaluator = getattr( batch_evaluators, f"{batch_evaluator}_batch_evaluator" ) opt_options = _process_optimize_options(optimize_options) log_options = {"fast_logging": fast_logging, "if_table_exists": "replace"} kwargs_list = [] names = [] for prob_name, problem in problems.items(): for option_name, options in opt_options.items(): kwargs = { **options, **problem["inputs"], "logging": logging_directory / f"{prob_name}_{option_name}.db", "log_options": log_options, } kwargs_list.append(kwargs) names.append((prob_name, option_name)) log_paths = [kwargs["logging"] for kwargs in kwargs_list] raw_results = batch_evaluator( func=minimize, arguments=kwargs_list, n_cores=n_cores, error_handling=error_handling, unpack_symbol="**", ) results = {} for name, result, log_path in zip(names, raw_results, log_paths): histories = read_optimization_histories(log_path) stop = histories["metadata"]["timestamps"].max() start = histories["metadata"]["timestamps"].min() runtime = (stop - start).total_seconds() results[name] = { "params_history": histories["params"], "criterion_history": histories["values"], "time_history": histories["metadata"]["timestamps"] - start, "solution": result, "runtime": runtime, } return results def _process_optimize_options(raw_options): if not isinstance(raw_options, dict): dict_options = {} for option in raw_options: if isinstance(option, str): dict_options[option] = option else: dict_options[option.__name__] = option else: dict_options = raw_options out_options = {} for name, option in dict_options.items(): if not isinstance(option, dict): option = {"algorithm": option} if "log_options" in option: raise ValueError( "Log options cannot be specified as part of optimize_options. Logging " "behavior is configured by the run_benchmark function." ) out_options[name] = option return out_options
37.050725
88
0.643067
from pathlib import Path import numpy as np from estimagic import batch_evaluators from estimagic.logging.read_log import read_optimization_histories from estimagic.optimization.optimize import minimize def run_benchmark( problems, optimize_options, logging_directory, *, batch_evaluator="joblib", n_cores=1, error_handling="continue", fast_logging=True, seed=None, ): np.random.seed(seed) logging_directory = Path(logging_directory) logging_directory.mkdir(parents=True, exist_ok=True) if isinstance(batch_evaluator, str): batch_evaluator = getattr( batch_evaluators, f"{batch_evaluator}_batch_evaluator" ) opt_options = _process_optimize_options(optimize_options) log_options = {"fast_logging": fast_logging, "if_table_exists": "replace"} kwargs_list = [] names = [] for prob_name, problem in problems.items(): for option_name, options in opt_options.items(): kwargs = { **options, **problem["inputs"], "logging": logging_directory / f"{prob_name}_{option_name}.db", "log_options": log_options, } kwargs_list.append(kwargs) names.append((prob_name, option_name)) log_paths = [kwargs["logging"] for kwargs in kwargs_list] raw_results = batch_evaluator( func=minimize, arguments=kwargs_list, n_cores=n_cores, error_handling=error_handling, unpack_symbol="**", ) results = {} for name, result, log_path in zip(names, raw_results, log_paths): histories = read_optimization_histories(log_path) stop = histories["metadata"]["timestamps"].max() start = histories["metadata"]["timestamps"].min() runtime = (stop - start).total_seconds() results[name] = { "params_history": histories["params"], "criterion_history": histories["values"], "time_history": histories["metadata"]["timestamps"] - start, "solution": result, "runtime": runtime, } return results def _process_optimize_options(raw_options): if not isinstance(raw_options, dict): dict_options = {} for option in raw_options: if isinstance(option, str): dict_options[option] = option else: dict_options[option.__name__] = option else: dict_options = raw_options out_options = {} for name, option in dict_options.items(): if not isinstance(option, dict): option = {"algorithm": option} if "log_options" in option: raise ValueError( "Log options cannot be specified as part of optimize_options. Logging " "behavior is configured by the run_benchmark function." ) out_options[name] = option return out_options
true
true
f725895b361675e864ed1a5ce6a8bc79a831c085
6,172
py
Python
Data_Handling/Data_analyze.py
KristofferLM96/TsetlinMachine-GO
926091fc70042abe5a67230932398bdab2c46328
[ "MIT" ]
2
2020-02-27T16:22:08.000Z
2020-03-22T11:04:35.000Z
Data_Handling/Data_analyze.py
KristofferLM96/TsetlinMachine-GO
926091fc70042abe5a67230932398bdab2c46328
[ "MIT" ]
null
null
null
Data_Handling/Data_analyze.py
KristofferLM96/TsetlinMachine-GO
926091fc70042abe5a67230932398bdab2c46328
[ "MIT" ]
null
null
null
# ----------------------------------------------- # ................. LIBRARIES ................... # ----------------------------------------------- import glob import os import time import numpy as np # ----------------------------------------------- # ............. GLOBAL VARIABLES ................ # ----------------------------------------------- name = "100_9x9Aya" # 9x9Natsukaze || 9x9Aya || x_9x9Aya .. x = amount moves file_name = name + "_binary.txt" binary_path = "Data/Binary/" + file_name original_path = "/home/kristoffer/Documents/Data/Original/9x9_10k_r104_144x20k/*" encoding = "UTF-8" # ISO-8859-1 / UTF-8 multiple_files = True unique_list = [] original_list = [] # [check_handicap(), check_duplication(), get_result_ratio(), check_moves(), remove_empty_lines()] run_programs = [0, 0, 1, 0, 0] # ----------------------------------------------- # ................. FUNCTIONS ................... # ----------------------------------------------- def remove_empty_lines(): output_file = open("Data/Binary/" + name + "_binary_1.txt", "w+") with open(binary_path, "r") as file: for line in file: if not line.isspace(): output_file.write(line) def check_handicap(): file = open(original_path, 'r', encoding=encoding) file_lines = file.readlines() _handicap = file_lines[0].split("HA[") print(_handicap) handicap = _handicap[1][0] print(handicap) file.close() def check_duplication(): file = open(binary_path, 'r', encoding=encoding) global original_list global unique_list original_list = [line.strip() for line in file] print("Original List Length:", len(original_list)) original_length = len(original_list) unique_list = np.unique(original_list) unique_length = len(unique_list) print("Unique List Length:", unique_length) print("Original - Unique:", original_length - unique_length, "\n") file.close() def get_result_ratio(): win = open("Data/Results-Split/" + name + "_win.txt", 'r') loss = open("Data/Results-Split/" + name + "_loss.txt", 'r') draw = open("Data/Results-Split/" + name + "_draw.txt", 'r') win_amount = len(win.readlines()) loss_amount = len(loss.readlines()) draw_amount = len(draw.readlines()) total_amount = win_amount + loss_amount + draw_amount print("Total Amount:", total_amount) print("Amount of wins:", win_amount, ",", round(((win_amount * 100) / total_amount), 2), "%") print("Amount of loss:", loss_amount, ",", round(((loss_amount * 100) / total_amount), 2), "%") print("Amount of draw:", draw_amount, ",", round(((draw_amount * 100) / total_amount), 2), "%") win.close() loss.close() draw.close() def check_moves(): total_pos = 19 moves_list = [] def get_moves(_game_lines): if "HA[" in _game_lines[0]: handicap = int(_game_lines[0].split("HA[")[1][0]) else: handicap = 0 _move_list = [] const = 4 for row in _game_lines[1:-1]: x = translate(row[3]) y = translate(row[4]) if row[1] + row[2] == "AB": for i in range(handicap): x = translate(row[4 + (i * const)]) y = translate(row[5 + (i * const)]) _move = ["b", x, y] if x != total_pos and y != total_pos: _move_list.append(_move) else: if row[1] == "B": _move = ["b", x, y] if row[1] == "W": _move = ["w", x, y] if x != total_pos and y != total_pos: _move_list.append(_move) return _move_list def translate(i): if i == "a": return 0 if i == "b": return 1 if i == "c": return 2 if i == "d": return 3 if i == "e": return 4 if i == "f": return 5 if i == "g": return 6 if i == "h": return 7 if i == "i": return 8 if i == "j": return 9 if i == "k": return 10 if i == "l": return 11 if i == "m": return 12 if i == "n": return 13 if i == "o": return 14 if i == "p": return 15 if i == "q": return 16 if i == "r": return 17 if i == "s": return 18 if i == "t": return 19 counter = 1 total_files = len(glob.glob(os.path.join(original_path, '*.sgf'))) for infile in glob.glob(os.path.join(original_path, '*.sgf')): start_time = time.time() file = open(infile, 'r', encoding="ISO-8859-1") file_lines = file.readlines() moves_list.append(len(get_moves(file_lines))) print(infile) print("Getting moves from file ", counter, "out of", total_files, "files. ............................................... ", round((counter / total_files * 100), 2), "% ............................................... ", round((time.time() - start_time) * 1000, 2), "ms", "\n") counter = counter + 1 file.close() unique_moves_list, unique_moves_list_count = np.unique(moves_list, return_counts=True) print(unique_moves_list, "\n") print(unique_moves_list_count, "\n") total_data = sum(unique_moves_list_count) for x, y in np.nditer([unique_moves_list, unique_moves_list_count]): print("Moves: %d : Amount: %d, %d %%" % (int(x), int(y), ((int(y)*100)/total_data))) print("\n") print("Unique Move lengths:", len(unique_moves_list)) # ----------------------------------------------- # .................. MAIN ....................... # ----------------------------------------------- if run_programs[0]: check_handicap() if run_programs[1]: check_duplication() if run_programs[2]: get_result_ratio() if run_programs[3]: check_moves() if run_programs[4]: remove_empty_lines()
31.814433
108
0.487362
import glob import os import time import numpy as np name = "100_9x9Aya" file_name = name + "_binary.txt" binary_path = "Data/Binary/" + file_name original_path = "/home/kristoffer/Documents/Data/Original/9x9_10k_r104_144x20k/*" encoding = "UTF-8" multiple_files = True unique_list = [] original_list = [] run_programs = [0, 0, 1, 0, 0] def remove_empty_lines(): output_file = open("Data/Binary/" + name + "_binary_1.txt", "w+") with open(binary_path, "r") as file: for line in file: if not line.isspace(): output_file.write(line) def check_handicap(): file = open(original_path, 'r', encoding=encoding) file_lines = file.readlines() _handicap = file_lines[0].split("HA[") print(_handicap) handicap = _handicap[1][0] print(handicap) file.close() def check_duplication(): file = open(binary_path, 'r', encoding=encoding) global original_list global unique_list original_list = [line.strip() for line in file] print("Original List Length:", len(original_list)) original_length = len(original_list) unique_list = np.unique(original_list) unique_length = len(unique_list) print("Unique List Length:", unique_length) print("Original - Unique:", original_length - unique_length, "\n") file.close() def get_result_ratio(): win = open("Data/Results-Split/" + name + "_win.txt", 'r') loss = open("Data/Results-Split/" + name + "_loss.txt", 'r') draw = open("Data/Results-Split/" + name + "_draw.txt", 'r') win_amount = len(win.readlines()) loss_amount = len(loss.readlines()) draw_amount = len(draw.readlines()) total_amount = win_amount + loss_amount + draw_amount print("Total Amount:", total_amount) print("Amount of wins:", win_amount, ",", round(((win_amount * 100) / total_amount), 2), "%") print("Amount of loss:", loss_amount, ",", round(((loss_amount * 100) / total_amount), 2), "%") print("Amount of draw:", draw_amount, ",", round(((draw_amount * 100) / total_amount), 2), "%") win.close() loss.close() draw.close() def check_moves(): total_pos = 19 moves_list = [] def get_moves(_game_lines): if "HA[" in _game_lines[0]: handicap = int(_game_lines[0].split("HA[")[1][0]) else: handicap = 0 _move_list = [] const = 4 for row in _game_lines[1:-1]: x = translate(row[3]) y = translate(row[4]) if row[1] + row[2] == "AB": for i in range(handicap): x = translate(row[4 + (i * const)]) y = translate(row[5 + (i * const)]) _move = ["b", x, y] if x != total_pos and y != total_pos: _move_list.append(_move) else: if row[1] == "B": _move = ["b", x, y] if row[1] == "W": _move = ["w", x, y] if x != total_pos and y != total_pos: _move_list.append(_move) return _move_list def translate(i): if i == "a": return 0 if i == "b": return 1 if i == "c": return 2 if i == "d": return 3 if i == "e": return 4 if i == "f": return 5 if i == "g": return 6 if i == "h": return 7 if i == "i": return 8 if i == "j": return 9 if i == "k": return 10 if i == "l": return 11 if i == "m": return 12 if i == "n": return 13 if i == "o": return 14 if i == "p": return 15 if i == "q": return 16 if i == "r": return 17 if i == "s": return 18 if i == "t": return 19 counter = 1 total_files = len(glob.glob(os.path.join(original_path, '*.sgf'))) for infile in glob.glob(os.path.join(original_path, '*.sgf')): start_time = time.time() file = open(infile, 'r', encoding="ISO-8859-1") file_lines = file.readlines() moves_list.append(len(get_moves(file_lines))) print(infile) print("Getting moves from file ", counter, "out of", total_files, "files. ............................................... ", round((counter / total_files * 100), 2), "% ............................................... ", round((time.time() - start_time) * 1000, 2), "ms", "\n") counter = counter + 1 file.close() unique_moves_list, unique_moves_list_count = np.unique(moves_list, return_counts=True) print(unique_moves_list, "\n") print(unique_moves_list_count, "\n") total_data = sum(unique_moves_list_count) for x, y in np.nditer([unique_moves_list, unique_moves_list_count]): print("Moves: %d : Amount: %d, %d %%" % (int(x), int(y), ((int(y)*100)/total_data))) print("\n") print("Unique Move lengths:", len(unique_moves_list)) if run_programs[0]: check_handicap() if run_programs[1]: check_duplication() if run_programs[2]: get_result_ratio() if run_programs[3]: check_moves() if run_programs[4]: remove_empty_lines()
true
true
f725898cfbcf257a6620878c85d91d75a4f7b6bd
11,001
py
Python
SBaaS_rnasequencing/stage01_rnasequencing_genesCountTable_io.py
dmccloskey/SBaaS_rnasequencing
521ad0b671b0bca02e9cebfc1b372f2265955418
[ "MIT" ]
null
null
null
SBaaS_rnasequencing/stage01_rnasequencing_genesCountTable_io.py
dmccloskey/SBaaS_rnasequencing
521ad0b671b0bca02e9cebfc1b372f2265955418
[ "MIT" ]
null
null
null
SBaaS_rnasequencing/stage01_rnasequencing_genesCountTable_io.py
dmccloskey/SBaaS_rnasequencing
521ad0b671b0bca02e9cebfc1b372f2265955418
[ "MIT" ]
null
null
null
#system import json #sbaas from .stage01_rnasequencing_genesCountTable_query import stage01_rnasequencing_genesCountTable_query from .stage01_rnasequencing_analysis_query import stage01_rnasequencing_analysis_query from SBaaS_base.sbaas_template_io import sbaas_template_io # Resources from io_utilities.base_importData import base_importData from io_utilities.base_exportData import base_exportData from sequencing_analysis.genes_countFPKMattr_table import genes_countFPKMattr_table from ddt_python.ddt_container_filterMenuAndChart2dAndTable import ddt_container_filterMenuAndChart2dAndTable from ddt_python.ddt_container import ddt_container from listDict.listDict import listDict from math import log2 class stage01_rnasequencing_genesCountTable_io( stage01_rnasequencing_genesCountTable_query, stage01_rnasequencing_analysis_query, sbaas_template_io): def import_dataStage01RNASequencingGenesCountTable_add( self,genes_count_table_dir,genes_fpkm_table_dir, genes_attr_table_dir, analysis_id_I,experiment_ids_I,samples_host_dirs_I,sample_names_I): '''table adds''' countFPKMattr = genes_countFPKMattr_table(); countFPKMattr.import_countTable( filename_I=genes_count_table_dir,); countFPKMattr.import_fpkmTable( filename_I=genes_fpkm_table_dir,); countFPKMattr.import_attrTable( filename_I=genes_attr_table_dir,); #parse the filenames and samplenames sna2sns_I={}; sna2experimentID_I={}; sample_names_lst = sample_names_I.split(','); experiment_ids_lst = experiment_ids_I.split(','); for cnt,sample_replicates in enumerate(samples_host_dirs_I.split('|')): sna2sns_I[sample_names_lst[cnt]] = []; sna2experimentID_I[sample_names_lst[cnt]] = experiment_ids_lst[cnt]; for sample in sample_replicates.split(','): filename = sample.split('/')[-1].replace('.bam','').replace('.fastq',''); sna2sns_I[sample_names_lst[cnt]].append(filename); genesCountTable = countFPKMattr.alignAndReformat_countFPKMattrTables( analysis_id_I = analysis_id_I, sna2experimentID_I = sna2experimentID_I, sna2sns_I = sna2sns_I) self.add_dataStage01RNASequencingGenesCountTable(genesCountTable); def import_dataStage01RNASequencingGenesCountTable_update(self, filename): '''table adds''' data = base_importData(); data.read_csv(filename); data.format_data(); self.update_dataStage01RNASequencingGenesCountTable(data.data); data.clear_data(); def export_dataStage01RNASequencingGenesCountTable_js(self,analysis_id_I,data_dir_I='tmp'): '''Export data for a box and whiskers plot''' # get the analysis information experiment_ids,sample_names = [],[]; experiment_ids,sample_names = self.get_experimentIDAndSampleName_analysisID_dataStage01RNASequencingAnalysis(analysis_id_I); data_O = []; for sample_name_cnt,sample_name in enumerate(sample_names): # query fpkm data: fpkms = []; fpkms = self.get_rows_experimentIDAndSampleName_dataStage01RNASequencingGenesCountTable(experiment_ids[sample_name_cnt],sample_name); data_O.extend(fpkms); # dump chart parameters to a js files data1_keys = ['experiment_id','sample_name','gene_short_name' ]; data1_nestkeys = ['gene_short_name']; data1_keymap = {'xdata':'gene_short_name', 'ydatamean':'FPKM', 'ydatalb':'FPKM_conf_lo', 'ydataub':'FPKM_conf_hi', 'serieslabel':'sample_name', 'featureslabel':'gene_short_name'}; # make the data object dataobject_O = [{"data":data_O,"datakeys":data1_keys,"datanestkeys":data1_nestkeys}]; # make the tile parameter objects formtileparameters_O = {'tileheader':'Filter menu','tiletype':'html','tileid':"filtermenu1",'rowid':"row1",'colid':"col1", 'tileclass':"panel panel-default",'rowclass':"row",'colclass':"col-sm-4"}; formparameters_O = {'htmlid':'filtermenuform1',"htmltype":'form_01',"formsubmitbuttonidtext":{'id':'submit1','text':'submit'},"formresetbuttonidtext":{'id':'reset1','text':'reset'},"formupdatebuttonidtext":{'id':'update1','text':'update'}}; formtileparameters_O.update(formparameters_O); svgparameters_O = {"svgtype":'boxandwhiskersplot2d_02',"svgkeymap":[data1_keymap], 'svgid':'svg1', "svgmargin":{ 'top': 50, 'right': 150, 'bottom': 50, 'left': 50 }, "svgwidth":500,"svgheight":350, "svgx1axislabel":"gene","svgy1axislabel":"FPKM", 'svgformtileid':'filtermenu1','svgresetbuttonid':'reset1','svgsubmitbuttonid':'submit1'}; svgtileparameters_O = {'tileheader':'Custom box and whiskers plot','tiletype':'svg','tileid':"tile2",'rowid':"row1",'colid':"col2", 'tileclass':"panel panel-default",'rowclass':"row",'colclass':"col-sm-8"}; svgtileparameters_O.update(svgparameters_O); tableparameters_O = {"tabletype":'responsivetable_01', 'tableid':'table1', "tablefilters":None, "tableclass":"table table-condensed table-hover", 'tableformtileid':'filtermenu1','tableresetbuttonid':'reset1','tablesubmitbuttonid':'submit1'}; tabletileparameters_O = {'tileheader':'FPKM','tiletype':'table','tileid':"tile3",'rowid':"row2",'colid':"col1", 'tileclass':"panel panel-default",'rowclass':"row",'colclass':"col-sm-12"}; tabletileparameters_O.update(tableparameters_O); parametersobject_O = [formtileparameters_O,svgtileparameters_O,tabletileparameters_O]; tile2datamap_O = {"filtermenu1":[0],"tile2":[0],"tile3":[0]}; # dump the data to a json file ddtutilities = ddt_container(parameters_I = parametersobject_O,data_I = dataobject_O,tile2datamap_I = tile2datamap_O,filtermenu_I = None); if data_dir_I=='tmp': filename_str = self.settings['visualization_data'] + '/tmp/ddt_data.js' elif data_dir_I=='data_json': data_json_O = ddtutilities.get_allObjects_js(); return data_json_O; with open(filename_str,'w') as file: file.write(ddtutilities.get_allObjects()); def export_dataStage01RNASequencingGenesCountTable_pairWisePlot_js(self,analysis_id_I,log2normalization_I=True,data_dir_I='tmp'): '''Export data for a pairwise scatter plot INPUT: analysis_id = String, analysis_id log2normalization_I = Boolean, apply a log2 normalization the FPKM values (default: True) data_dir_I = string, data directory OUTPUT: ''' # get the analysis information experiment_ids,sample_names = [],[]; experiment_ids,sample_names = self.get_experimentIDAndSampleName_analysisID_dataStage01RNASequencingAnalysis(analysis_id_I); data_O = []; for sample_name_cnt,sample_name in enumerate(sample_names): # query fpkm data: fpkms = []; fpkms = self.get_rows_experimentIDAndSampleName_dataStage01RNASequencingGenesCountTable(experiment_ids[sample_name_cnt],sample_name); if log2normalization_I: for f in fpkms: if f['FPKM'] == 0.0: f['FPKM'] = 0.0; else: f['FPKM'] = log2(f['FPKM']); data_O.extend(fpkms); # reorganize the data listdict = listDict(data_O); data_O,columnValueHeader_O = listdict.convert_listDict2ColumnGroupListDict( #value_labels_I = ['FPKM','FPKM_conf_lo','FPKM_conf_hi'], value_labels_I = ['FPKM',], column_labels_I = ['experiment_id','sample_name'], feature_labels_I = ['gene_id','gene_short_name'], na_str_I=0.0, columnValueConnector_str_I='_', ); # make the tile object #data1 = filtermenu/table data1_keymap_table = { 'xdata':'svd_method', 'ydata':'singular_value_index', 'zdata':'d_vector', 'rowslabel':'svd_method', 'columnslabel':'singular_value_index', }; #data2 = svg #if single plot, data2 = filter menu, data2, and table data1_keys = ['gene_id','gene_short_name' ]; data1_nestkeys = ['gene_short_name']; data1_keymap_svg = []; svgtype = []; svgtile2datamap = []; data_svg_keymap = []; for cnt1,column1 in enumerate(columnValueHeader_O): for cnt2,column2 in enumerate(columnValueHeader_O[cnt1+1:]): keymap = { 'xdata':column1, 'ydata':column2, 'serieslabel':'', 'featureslabel':'gene_short_name', 'tooltipdata':'gene_short_name', }; data1_keymap_svg.append([keymap]); data_svg_keymap.append(keymap); svgtype.append('pcaplot2d_scores_01'); svgtile2datamap.append([0]); nsvgtable = ddt_container_filterMenuAndChart2dAndTable(); nsvgtable.make_filterMenuAndChart2dAndTable( data_filtermenu=data_O, data_filtermenu_keys=data1_keys, data_filtermenu_nestkeys=data1_nestkeys, data_filtermenu_keymap=data1_keymap_table, data_svg_keys=data1_keys, data_svg_nestkeys=data1_nestkeys, data_svg_keymap=data_svg_keymap, data_table_keys=data1_keys, data_table_nestkeys=data1_nestkeys, data_table_keymap=data1_keymap_table, data_svg=None, data_table=None, svgtype=svgtype, tabletype='responsivetable_01', svgx1axislabel='', svgy1axislabel='', tablekeymap = [data1_keymap_table], svgkeymap = data1_keymap_svg, formtile2datamap=[0], tabletile2datamap=[0], svgtile2datamap=svgtile2datamap, svgfilters=None, svgtileheader='Pair-wise scatter plot', tablefilters=None, tableheaders=None ); if data_dir_I=='tmp': filename_str = self.settings['visualization_data'] + '/tmp/ddt_data.js' elif data_dir_I=='data_json': data_json_O = nsvgtable.get_allObjects_js(); return data_json_O; with open(filename_str,'w') as file: file.write(nsvgtable.get_allObjects());
50.463303
248
0.634942
import json from .stage01_rnasequencing_genesCountTable_query import stage01_rnasequencing_genesCountTable_query from .stage01_rnasequencing_analysis_query import stage01_rnasequencing_analysis_query from SBaaS_base.sbaas_template_io import sbaas_template_io from io_utilities.base_importData import base_importData from io_utilities.base_exportData import base_exportData from sequencing_analysis.genes_countFPKMattr_table import genes_countFPKMattr_table from ddt_python.ddt_container_filterMenuAndChart2dAndTable import ddt_container_filterMenuAndChart2dAndTable from ddt_python.ddt_container import ddt_container from listDict.listDict import listDict from math import log2 class stage01_rnasequencing_genesCountTable_io( stage01_rnasequencing_genesCountTable_query, stage01_rnasequencing_analysis_query, sbaas_template_io): def import_dataStage01RNASequencingGenesCountTable_add( self,genes_count_table_dir,genes_fpkm_table_dir, genes_attr_table_dir, analysis_id_I,experiment_ids_I,samples_host_dirs_I,sample_names_I): countFPKMattr = genes_countFPKMattr_table(); countFPKMattr.import_countTable( filename_I=genes_count_table_dir,); countFPKMattr.import_fpkmTable( filename_I=genes_fpkm_table_dir,); countFPKMattr.import_attrTable( filename_I=genes_attr_table_dir,); sna2sns_I={}; sna2experimentID_I={}; sample_names_lst = sample_names_I.split(','); experiment_ids_lst = experiment_ids_I.split(','); for cnt,sample_replicates in enumerate(samples_host_dirs_I.split('|')): sna2sns_I[sample_names_lst[cnt]] = []; sna2experimentID_I[sample_names_lst[cnt]] = experiment_ids_lst[cnt]; for sample in sample_replicates.split(','): filename = sample.split('/')[-1].replace('.bam','').replace('.fastq',''); sna2sns_I[sample_names_lst[cnt]].append(filename); genesCountTable = countFPKMattr.alignAndReformat_countFPKMattrTables( analysis_id_I = analysis_id_I, sna2experimentID_I = sna2experimentID_I, sna2sns_I = sna2sns_I) self.add_dataStage01RNASequencingGenesCountTable(genesCountTable); def import_dataStage01RNASequencingGenesCountTable_update(self, filename): data = base_importData(); data.read_csv(filename); data.format_data(); self.update_dataStage01RNASequencingGenesCountTable(data.data); data.clear_data(); def export_dataStage01RNASequencingGenesCountTable_js(self,analysis_id_I,data_dir_I='tmp'): experiment_ids,sample_names = [],[]; experiment_ids,sample_names = self.get_experimentIDAndSampleName_analysisID_dataStage01RNASequencingAnalysis(analysis_id_I); data_O = []; for sample_name_cnt,sample_name in enumerate(sample_names): fpkms = []; fpkms = self.get_rows_experimentIDAndSampleName_dataStage01RNASequencingGenesCountTable(experiment_ids[sample_name_cnt],sample_name); data_O.extend(fpkms); data1_keys = ['experiment_id','sample_name','gene_short_name' ]; data1_nestkeys = ['gene_short_name']; data1_keymap = {'xdata':'gene_short_name', 'ydatamean':'FPKM', 'ydatalb':'FPKM_conf_lo', 'ydataub':'FPKM_conf_hi', 'serieslabel':'sample_name', 'featureslabel':'gene_short_name'}; dataobject_O = [{"data":data_O,"datakeys":data1_keys,"datanestkeys":data1_nestkeys}]; formtileparameters_O = {'tileheader':'Filter menu','tiletype':'html','tileid':"filtermenu1",'rowid':"row1",'colid':"col1", 'tileclass':"panel panel-default",'rowclass':"row",'colclass':"col-sm-4"}; formparameters_O = {'htmlid':'filtermenuform1',"htmltype":'form_01',"formsubmitbuttonidtext":{'id':'submit1','text':'submit'},"formresetbuttonidtext":{'id':'reset1','text':'reset'},"formupdatebuttonidtext":{'id':'update1','text':'update'}}; formtileparameters_O.update(formparameters_O); svgparameters_O = {"svgtype":'boxandwhiskersplot2d_02',"svgkeymap":[data1_keymap], 'svgid':'svg1', "svgmargin":{ 'top': 50, 'right': 150, 'bottom': 50, 'left': 50 }, "svgwidth":500,"svgheight":350, "svgx1axislabel":"gene","svgy1axislabel":"FPKM", 'svgformtileid':'filtermenu1','svgresetbuttonid':'reset1','svgsubmitbuttonid':'submit1'}; svgtileparameters_O = {'tileheader':'Custom box and whiskers plot','tiletype':'svg','tileid':"tile2",'rowid':"row1",'colid':"col2", 'tileclass':"panel panel-default",'rowclass':"row",'colclass':"col-sm-8"}; svgtileparameters_O.update(svgparameters_O); tableparameters_O = {"tabletype":'responsivetable_01', 'tableid':'table1', "tablefilters":None, "tableclass":"table table-condensed table-hover", 'tableformtileid':'filtermenu1','tableresetbuttonid':'reset1','tablesubmitbuttonid':'submit1'}; tabletileparameters_O = {'tileheader':'FPKM','tiletype':'table','tileid':"tile3",'rowid':"row2",'colid':"col1", 'tileclass':"panel panel-default",'rowclass':"row",'colclass':"col-sm-12"}; tabletileparameters_O.update(tableparameters_O); parametersobject_O = [formtileparameters_O,svgtileparameters_O,tabletileparameters_O]; tile2datamap_O = {"filtermenu1":[0],"tile2":[0],"tile3":[0]}; ddtutilities = ddt_container(parameters_I = parametersobject_O,data_I = dataobject_O,tile2datamap_I = tile2datamap_O,filtermenu_I = None); if data_dir_I=='tmp': filename_str = self.settings['visualization_data'] + '/tmp/ddt_data.js' elif data_dir_I=='data_json': data_json_O = ddtutilities.get_allObjects_js(); return data_json_O; with open(filename_str,'w') as file: file.write(ddtutilities.get_allObjects()); def export_dataStage01RNASequencingGenesCountTable_pairWisePlot_js(self,analysis_id_I,log2normalization_I=True,data_dir_I='tmp'): experiment_ids,sample_names = [],[]; experiment_ids,sample_names = self.get_experimentIDAndSampleName_analysisID_dataStage01RNASequencingAnalysis(analysis_id_I); data_O = []; for sample_name_cnt,sample_name in enumerate(sample_names): fpkms = []; fpkms = self.get_rows_experimentIDAndSampleName_dataStage01RNASequencingGenesCountTable(experiment_ids[sample_name_cnt],sample_name); if log2normalization_I: for f in fpkms: if f['FPKM'] == 0.0: f['FPKM'] = 0.0; else: f['FPKM'] = log2(f['FPKM']); data_O.extend(fpkms); listdict = listDict(data_O); data_O,columnValueHeader_O = listdict.convert_listDict2ColumnGroupListDict( value_labels_I = ['FPKM',], column_labels_I = ['experiment_id','sample_name'], feature_labels_I = ['gene_id','gene_short_name'], na_str_I=0.0, columnValueConnector_str_I='_', ); data1_keymap_table = { 'xdata':'svd_method', 'ydata':'singular_value_index', 'zdata':'d_vector', 'rowslabel':'svd_method', 'columnslabel':'singular_value_index', }; data1_keys = ['gene_id','gene_short_name' ]; data1_nestkeys = ['gene_short_name']; data1_keymap_svg = []; svgtype = []; svgtile2datamap = []; data_svg_keymap = []; for cnt1,column1 in enumerate(columnValueHeader_O): for cnt2,column2 in enumerate(columnValueHeader_O[cnt1+1:]): keymap = { 'xdata':column1, 'ydata':column2, 'serieslabel':'', 'featureslabel':'gene_short_name', 'tooltipdata':'gene_short_name', }; data1_keymap_svg.append([keymap]); data_svg_keymap.append(keymap); svgtype.append('pcaplot2d_scores_01'); svgtile2datamap.append([0]); nsvgtable = ddt_container_filterMenuAndChart2dAndTable(); nsvgtable.make_filterMenuAndChart2dAndTable( data_filtermenu=data_O, data_filtermenu_keys=data1_keys, data_filtermenu_nestkeys=data1_nestkeys, data_filtermenu_keymap=data1_keymap_table, data_svg_keys=data1_keys, data_svg_nestkeys=data1_nestkeys, data_svg_keymap=data_svg_keymap, data_table_keys=data1_keys, data_table_nestkeys=data1_nestkeys, data_table_keymap=data1_keymap_table, data_svg=None, data_table=None, svgtype=svgtype, tabletype='responsivetable_01', svgx1axislabel='', svgy1axislabel='', tablekeymap = [data1_keymap_table], svgkeymap = data1_keymap_svg, formtile2datamap=[0], tabletile2datamap=[0], svgtile2datamap=svgtile2datamap, svgfilters=None, svgtileheader='Pair-wise scatter plot', tablefilters=None, tableheaders=None ); if data_dir_I=='tmp': filename_str = self.settings['visualization_data'] + '/tmp/ddt_data.js' elif data_dir_I=='data_json': data_json_O = nsvgtable.get_allObjects_js(); return data_json_O; with open(filename_str,'w') as file: file.write(nsvgtable.get_allObjects());
true
true
f7258a45bcc7583012e19070d9419ded10110a6e
2,480
py
Python
redunlive/utils.py
nmaekawa/redunlive
3f1830d605c46a300d028a32b564d803964f2384
[ "Apache-2.0" ]
null
null
null
redunlive/utils.py
nmaekawa/redunlive
3f1830d605c46a300d028a32b564d803964f2384
[ "Apache-2.0" ]
null
null
null
redunlive/utils.py
nmaekawa/redunlive
3f1830d605c46a300d028a32b564d803964f2384
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- import re import sys import platform import requests from requests.auth import HTTPBasicAuth from . import __version__ from . import log def clean_name( name ): """ replaces non-alpha with underscores '_' and set the string to lower case """ return re.sub( '[^0-9a-zA-Z]+', '_', name ).lower() def pull_data( url, creds=None): """ reads a text file from given url if basic auth needed, pass args creds['user'] and creds['pwd'] """ headers = { 'User-Agent': default_useragent(), 'Accept-Encoding': 'gzip, deflate', 'Accept': 'text/html, text/*' } au = None if not creds is None: if 'user' in creds.keys() and 'pwd' in creds.keys(): au = HTTPBasicAuth( creds['user'], creds['pwd'] ) headers.update( {'X-REQUESTED-AUTH': 'Basic'} ) try: response = requests.get( url, headers=headers, auth=au ) except requests.HTTPError as e: log.warning("data from url(%s) is unavailable. Error: %s" % ( url, e ) ) return None else: return response.text def default_useragent(): """Return a string representing the default user agent.""" _implementation = platform.python_implementation() if _implementation == 'CPython': _implementation_version = platform.python_version() elif _implementation == 'PyPy': _implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro) if sys.pypy_version_info.releaselevel != 'final': _implementation_version = ''.join([_implementation_version, \ sys.pypy_version_info.releaselevel]) elif _implementation == 'Jython': _implementation_version = platform.python_version() # Complete Guess elif _implementation == 'IronPython': _implementation_version = platform.python_version() # Complete Guess else: _implementation_version = 'Unknown' try: p_system = platform.system() p_release = platform.release() except IOError: p_system = 'Unknown' p_release = 'Unknown' return " ".join(['%s/%s' % (__name__, __version__), '%s/%s' % (_implementation, _implementation_version), '%s/%s' % (p_system, p_release)])
32.207792
80
0.594355
import re import sys import platform import requests from requests.auth import HTTPBasicAuth from . import __version__ from . import log def clean_name( name ): return re.sub( '[^0-9a-zA-Z]+', '_', name ).lower() def pull_data( url, creds=None): headers = { 'User-Agent': default_useragent(), 'Accept-Encoding': 'gzip, deflate', 'Accept': 'text/html, text/*' } au = None if not creds is None: if 'user' in creds.keys() and 'pwd' in creds.keys(): au = HTTPBasicAuth( creds['user'], creds['pwd'] ) headers.update( {'X-REQUESTED-AUTH': 'Basic'} ) try: response = requests.get( url, headers=headers, auth=au ) except requests.HTTPError as e: log.warning("data from url(%s) is unavailable. Error: %s" % ( url, e ) ) return None else: return response.text def default_useragent(): _implementation = platform.python_implementation() if _implementation == 'CPython': _implementation_version = platform.python_version() elif _implementation == 'PyPy': _implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro) if sys.pypy_version_info.releaselevel != 'final': _implementation_version = ''.join([_implementation_version, \ sys.pypy_version_info.releaselevel]) elif _implementation == 'Jython': _implementation_version = platform.python_version() elif _implementation == 'IronPython': _implementation_version = platform.python_version() else: _implementation_version = 'Unknown' try: p_system = platform.system() p_release = platform.release() except IOError: p_system = 'Unknown' p_release = 'Unknown' return " ".join(['%s/%s' % (__name__, __version__), '%s/%s' % (_implementation, _implementation_version), '%s/%s' % (p_system, p_release)])
true
true
f7258af14dcf0fa82efc690560fcea365ab3ef09
4,999
py
Python
cameras_to_albums.py
brandoconnor/flickr-album-per-camera
358c90cded12c6c9ecb9f8ae289e005f172d30e2
[ "Apache-2.0" ]
null
null
null
cameras_to_albums.py
brandoconnor/flickr-album-per-camera
358c90cded12c6c9ecb9f8ae289e005f172d30e2
[ "Apache-2.0" ]
1
2016-02-12T02:25:19.000Z
2016-02-13T00:07:46.000Z
cameras_to_albums.py
brandoconnor/flickr-album-per-camera
358c90cded12c6c9ecb9f8ae289e005f172d30e2
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python """ A simple script to organize photos into albums named by their camera source. For me, this is useful for cycling through only high quality photos on my TV hooked up to a chromecast. """ import argparse import flickrapi def auth_flickr(api_key, api_secret): """Authenticate user to flickr API.""" flickr = flickrapi.FlickrAPI(api_key, api_secret, format='parsed-json') flickr.authenticate_via_browser(perms='write') return flickr def get_user_id(flickr, user): """Get the user_id from the username.""" user_data = flickr.people.findByUsername(username=user) return user_data['user']['id'] def get_photoset_dict(flickr, user_id): """construct a photoset dict of album name to album/set id.""" print('Gathering dictionary of all photos in all photosets...') init_photoset = flickr.photosets.getList(user_id=user_id) photoset_dict = dict() set_num = 1 for set_page in range(1, init_photoset['photosets']['pages'] + 1): photoset = flickr.photosets.getList(user_id=user_id, page=set_page) for pset in photoset['photosets']['photoset']: print('processing photoset %s of %s' % (set_num, init_photoset['photosets']['total'])) set_num += 1 # a_dict = {'thing': {'this': ['list, 'values']} } photoset_dict[pset['title']['_content']] = {pset['id']: []} init_photoset_object = flickr.photosets.getPhotos( photoset_id=pset['id']) for photoset_page in range(1, init_photoset_object['photoset']['pages'] + 1): photoset_object = flickr.photosets.getPhotos( user_id=user_id, photoset_id=pset['id'], page=photoset_page) photoset_dict[pset['title']['_content']][ pset['id']] += [p['id'] for p in photoset_object['photoset']['photo']] return photoset_dict def main(args): """Main code block. Do all the things.""" flickr = auth_flickr(args.api_key, args.api_secret) user_id = get_user_id(flickr, user=args.username) album_dict = get_photoset_dict(flickr, user_id) init_photos = flickr.people.getPhotos(user_id=user_id) total = init_photos['photos']['total'] photo_num = args.initial_photo / 100 * 100 # TODO ensure less than total photos if photo_num > total: raise('Trying to start at photo %s but only %s total. Exiting.' % (args.initial_photo, total)) init_page = args.initial_photo / 100 + 1 # 100 photos per page for page_num in range(init_page, init_photos['photos']['pages'] + 1): photo_batch = flickr.people.getPhotos(user_id=user_id, page=page_num) for photo in photo_batch['photos']['photo']: photo_num += 1 photo_id = photo['id'] print('processing photo %s of %s: %s' % (photo_num, total, photo_id)) photo_data = flickr.photos.getExif(photo_id=photo_id) camera_name = photo_data['photo']['camera'] if len(camera_name) > 0: if camera_name not in album_dict.keys(): print('adding camera album "%s"' % camera_name) new_set = flickr.photosets.create(title=camera_name, primary_photo_id=photo_id, description='All photos taken behind a %s' % camera_name) album_dict[camera_name] = { new_set['photoset']['id']: [photo_id]} continue elif photo_id not in [p for p in album_dict[camera_name].values()[0]]: # if this photo is not in the appropriate album, add it print('Adding photo to camera album.') flickr.photosets.addPhoto(photoset_id=album_dict[ camera_name].keys()[0], photo_id=photo_id) album_dict[camera_name].values()[0].append(photo_id) else: print('Photo is already in the appropriate set') continue else: print('Skipping photo with insufficient metadata.') if __name__ in '__main__': parser = argparse.ArgumentParser() parser.add_argument('-d', '--dry_run', action='store_true', default=False, help="Verbose minus action. Default=False") parser.add_argument('-i', '--initial_photo', help='approximate initial photo. Rounds down to nearest hundred', type=int, default=0) parser.add_argument('-k', '--api_key', help='flickr API key', required=True) parser.add_argument('-s', '--api_secret', help='flickr API secret', required=True) parser.add_argument('-u', '--username', help='your flickr username', required=True) exit(main(parser.parse_args()))
46.719626
114
0.595319
import argparse import flickrapi def auth_flickr(api_key, api_secret): flickr = flickrapi.FlickrAPI(api_key, api_secret, format='parsed-json') flickr.authenticate_via_browser(perms='write') return flickr def get_user_id(flickr, user): user_data = flickr.people.findByUsername(username=user) return user_data['user']['id'] def get_photoset_dict(flickr, user_id): print('Gathering dictionary of all photos in all photosets...') init_photoset = flickr.photosets.getList(user_id=user_id) photoset_dict = dict() set_num = 1 for set_page in range(1, init_photoset['photosets']['pages'] + 1): photoset = flickr.photosets.getList(user_id=user_id, page=set_page) for pset in photoset['photosets']['photoset']: print('processing photoset %s of %s' % (set_num, init_photoset['photosets']['total'])) set_num += 1 photoset_dict[pset['title']['_content']] = {pset['id']: []} init_photoset_object = flickr.photosets.getPhotos( photoset_id=pset['id']) for photoset_page in range(1, init_photoset_object['photoset']['pages'] + 1): photoset_object = flickr.photosets.getPhotos( user_id=user_id, photoset_id=pset['id'], page=photoset_page) photoset_dict[pset['title']['_content']][ pset['id']] += [p['id'] for p in photoset_object['photoset']['photo']] return photoset_dict def main(args): flickr = auth_flickr(args.api_key, args.api_secret) user_id = get_user_id(flickr, user=args.username) album_dict = get_photoset_dict(flickr, user_id) init_photos = flickr.people.getPhotos(user_id=user_id) total = init_photos['photos']['total'] photo_num = args.initial_photo / 100 * 100 # TODO ensure less than total photos if photo_num > total: raise('Trying to start at photo %s but only %s total. Exiting.' % (args.initial_photo, total)) init_page = args.initial_photo / 100 + 1 # 100 photos per page for page_num in range(init_page, init_photos['photos']['pages'] + 1): photo_batch = flickr.people.getPhotos(user_id=user_id, page=page_num) for photo in photo_batch['photos']['photo']: photo_num += 1 photo_id = photo['id'] print('processing photo %s of %s: %s' % (photo_num, total, photo_id)) photo_data = flickr.photos.getExif(photo_id=photo_id) camera_name = photo_data['photo']['camera'] if len(camera_name) > 0: if camera_name not in album_dict.keys(): print('adding camera album "%s"' % camera_name) new_set = flickr.photosets.create(title=camera_name, primary_photo_id=photo_id, description='All photos taken behind a %s' % camera_name) album_dict[camera_name] = { new_set['photoset']['id']: [photo_id]} continue elif photo_id not in [p for p in album_dict[camera_name].values()[0]]: # if this photo is not in the appropriate album, add it print('Adding photo to camera album.') flickr.photosets.addPhoto(photoset_id=album_dict[ camera_name].keys()[0], photo_id=photo_id) album_dict[camera_name].values()[0].append(photo_id) else: print('Photo is already in the appropriate set') continue else: print('Skipping photo with insufficient metadata.') if __name__ in '__main__': parser = argparse.ArgumentParser() parser.add_argument('-d', '--dry_run', action='store_true', default=False, help="Verbose minus action. Default=False") parser.add_argument('-i', '--initial_photo', help='approximate initial photo. Rounds down to nearest hundred', type=int, default=0) parser.add_argument('-k', '--api_key', help='flickr API key', required=True) parser.add_argument('-s', '--api_secret', help='flickr API secret', required=True) parser.add_argument('-u', '--username', help='your flickr username', required=True) exit(main(parser.parse_args()))
true
true
f7258c968558839fb8aa4aaba0600d037324ede1
2,204
py
Python
cheritest/trunk/tests/alu/test_msub_ex.py
tupipa/beri
cef1b41d52592cfa7454ddf59f9f2994e447cd66
[ "Apache-2.0" ]
36
2015-05-29T16:47:19.000Z
2022-02-08T21:16:26.000Z
cheritest/trunk/tests/alu/test_msub_ex.py
tupipa/beri
cef1b41d52592cfa7454ddf59f9f2994e447cd66
[ "Apache-2.0" ]
1
2015-10-14T13:05:21.000Z
2015-10-19T20:34:03.000Z
cheritest/trunk/tests/alu/test_msub_ex.py
tupipa/beri
cef1b41d52592cfa7454ddf59f9f2994e447cd66
[ "Apache-2.0" ]
15
2015-06-11T07:10:58.000Z
2021-06-18T05:14:54.000Z
#- # Copyright (c) 2015 Michael Roe # All rights reserved. # # This software was developed by the University of Cambridge Computer # Laboratory as part of the Rigorous Engineering of Mainstream Systems (REMS) # project, funded by EPSRC grant EP/K008528/1. # # @BERI_LICENSE_HEADER_START@ # # Licensed to BERI Open Systems C.I.C. (BERI) under one or more contributor # license agreements. See the NOTICE file distributed with this work for # additional information regarding copyright ownership. BERI licenses this # file to you under the BERI Hardware-Software License, Version 1.0 (the # "License"); you may not use this file except in compliance with the # License. You may obtain a copy of the License at: # # http://www.beri-open-systems.org/legal/license-1-0.txt # # Unless required by applicable law or agreed to in writing, Work distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. # # @BERI_LICENSE_HEADER_END@ # from beritest_tools import BaseBERITestCase from nose.plugins.attrib import attr class test_msub_ex(BaseBERITestCase): @attr('ignorebadex') @attr('madd') def test_msub_ex_1(self): self.assertRegisterEqual(self.MIPS.a0, 0xfffffffffffffffa, "MSUB of a value that was not a valid sign extention of a 32-bit value gave an unexpected result.") @attr('ignorebadex') @attr('madd') def test_msub_ex_2(self): self.assertRegisterEqual(self.MIPS.a1, 0xffffffffffffffff, "MSUB of a value that was not a valid sign extention of a 32-bit value gave an unexpected result.") @attr('ignorebadex') @attr('madd') def test_msub_ex_3(self): self.assertRegisterEqual(self.MIPS.a2, 0xfffffffffffffffa, "MSUB of a value that was not a valid sign extention of a 32-bit value gave an unexpected result.") @attr('ignorebadex') @attr('madd') def test_msub_ex_4(self): self.assertRegisterEqual(self.MIPS.a3, 0xffffffffffffffff, "MSUB of a value that was not a valid sign extention of a 32-bit value gave an unexpected result.")
41.584906
166
0.748185
from beritest_tools import BaseBERITestCase from nose.plugins.attrib import attr class test_msub_ex(BaseBERITestCase): @attr('ignorebadex') @attr('madd') def test_msub_ex_1(self): self.assertRegisterEqual(self.MIPS.a0, 0xfffffffffffffffa, "MSUB of a value that was not a valid sign extention of a 32-bit value gave an unexpected result.") @attr('ignorebadex') @attr('madd') def test_msub_ex_2(self): self.assertRegisterEqual(self.MIPS.a1, 0xffffffffffffffff, "MSUB of a value that was not a valid sign extention of a 32-bit value gave an unexpected result.") @attr('ignorebadex') @attr('madd') def test_msub_ex_3(self): self.assertRegisterEqual(self.MIPS.a2, 0xfffffffffffffffa, "MSUB of a value that was not a valid sign extention of a 32-bit value gave an unexpected result.") @attr('ignorebadex') @attr('madd') def test_msub_ex_4(self): self.assertRegisterEqual(self.MIPS.a3, 0xffffffffffffffff, "MSUB of a value that was not a valid sign extention of a 32-bit value gave an unexpected result.")
true
true
f7258cce35cf6a9ce718c2c71ffc2151fcba6ee2
498
py
Python
contentsummary/urls.py
Bobstin/itcsummary
259d8f64e415a1c7cbc926752c717e307c09953f
[ "MIT" ]
null
null
null
contentsummary/urls.py
Bobstin/itcsummary
259d8f64e415a1c7cbc926752c717e307c09953f
[ "MIT" ]
5
2021-02-27T13:23:58.000Z
2021-09-22T17:39:19.000Z
contentsummary/urls.py
Bobstin/itcsummary
259d8f64e415a1c7cbc926752c717e307c09953f
[ "MIT" ]
null
null
null
from django.conf.urls import url from . import views urlpatterns = [ url(r'^next/(?P<priornumber>[0-9]+)/$', views.nextSession, name='nextSession'), url(r'^all/$', views.allSessions, name='allSessions'), url(r'^allpt1/$', views.allSessionspt1, name='allSessionspt1'), url(r'^allpt2/$', views.allSessionspt2, name='allSessionspt2'), url(r'^singleSession/(?P<session_number>[0-9]+)/$', views.singleSession, name='singleSession'), url(r'^$', views.example, name='example'), ]
41.5
99
0.670683
from django.conf.urls import url from . import views urlpatterns = [ url(r'^next/(?P<priornumber>[0-9]+)/$', views.nextSession, name='nextSession'), url(r'^all/$', views.allSessions, name='allSessions'), url(r'^allpt1/$', views.allSessionspt1, name='allSessionspt1'), url(r'^allpt2/$', views.allSessionspt2, name='allSessionspt2'), url(r'^singleSession/(?P<session_number>[0-9]+)/$', views.singleSession, name='singleSession'), url(r'^$', views.example, name='example'), ]
true
true
f7258cd44fa3033315e86b9b007b80c34183601d
71,980
py
Python
nova/compute/resource_tracker.py
aspiers/nova
e8b6b0bc78ec229803d1d27f8a4706e2c425bd77
[ "Apache-2.0" ]
1
2021-12-27T00:47:30.000Z
2021-12-27T00:47:30.000Z
nova/compute/resource_tracker.py
aspiers/nova
e8b6b0bc78ec229803d1d27f8a4706e2c425bd77
[ "Apache-2.0" ]
null
null
null
nova/compute/resource_tracker.py
aspiers/nova
e8b6b0bc78ec229803d1d27f8a4706e2c425bd77
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Track resources like memory and disk for a compute host. Provides the scheduler with useful information about availability through the ComputeNode model. """ import collections import copy from keystoneauth1 import exceptions as ks_exc import os_resource_classes as orc from oslo_log import log as logging from oslo_serialization import jsonutils import retrying from nova.compute import claims from nova.compute import monitors from nova.compute import stats as compute_stats from nova.compute import task_states from nova.compute import utils as compute_utils from nova.compute import vm_states import nova.conf from nova import exception from nova.i18n import _ from nova import objects from nova.objects import base as obj_base from nova.objects import migration as migration_obj from nova.pci import manager as pci_manager from nova.pci import request as pci_request from nova import rpc from nova.scheduler.client import report from nova import utils from nova.virt import hardware CONF = nova.conf.CONF LOG = logging.getLogger(__name__) COMPUTE_RESOURCE_SEMAPHORE = "compute_resources" def _instance_in_resize_state(instance): """Returns True if the instance is in one of the resizing states. :param instance: `nova.objects.Instance` object """ vm = instance.vm_state task = instance.task_state if vm == vm_states.RESIZED: return True if (vm in [vm_states.ACTIVE, vm_states.STOPPED] and task in ( task_states.resizing_states + task_states.rebuild_states)): return True return False def _is_trackable_migration(migration): # Only look at resize/migrate migration and evacuation records # NOTE(danms): RT should probably examine live migration # records as well and do something smart. However, ignore # those for now to avoid them being included in below calculations. return migration.migration_type in ('resize', 'migration', 'evacuation') def _normalize_inventory_from_cn_obj(inv_data, cn): """Helper function that injects various information from a compute node object into the inventory dict returned from the virt driver's get_inventory() method. This function allows us to marry information like *_allocation_ratio and reserved memory amounts that are in the compute_nodes DB table and that the virt driver doesn't know about with the information the virt driver *does* know about. Note that if the supplied inv_data contains allocation_ratio, reserved or other fields, we DO NOT override the value with that of the compute node. This is to ensure that the virt driver is the single source of truth regarding inventory information. For instance, the Ironic virt driver will always return a very specific inventory with allocation_ratios pinned to 1.0. :param inv_data: Dict, keyed by resource class, of inventory information returned from virt driver's get_inventory() method :param compute_node: `objects.ComputeNode` describing the compute node """ if orc.VCPU in inv_data: cpu_inv = inv_data[orc.VCPU] if 'allocation_ratio' not in cpu_inv: cpu_inv['allocation_ratio'] = cn.cpu_allocation_ratio if 'reserved' not in cpu_inv: cpu_inv['reserved'] = CONF.reserved_host_cpus if orc.MEMORY_MB in inv_data: mem_inv = inv_data[orc.MEMORY_MB] if 'allocation_ratio' not in mem_inv: mem_inv['allocation_ratio'] = cn.ram_allocation_ratio if 'reserved' not in mem_inv: mem_inv['reserved'] = CONF.reserved_host_memory_mb if orc.DISK_GB in inv_data: disk_inv = inv_data[orc.DISK_GB] if 'allocation_ratio' not in disk_inv: disk_inv['allocation_ratio'] = cn.disk_allocation_ratio if 'reserved' not in disk_inv: # TODO(johngarbutt) We should either move to reserved_host_disk_gb # or start tracking DISK_MB. reserved_mb = CONF.reserved_host_disk_mb reserved_gb = compute_utils.convert_mb_to_ceil_gb(reserved_mb) disk_inv['reserved'] = reserved_gb class ResourceTracker(object): """Compute helper class for keeping track of resource usage as instances are built and destroyed. """ def __init__(self, host, driver): self.host = host self.driver = driver self.pci_tracker = None # Dict of objects.ComputeNode objects, keyed by nodename self.compute_nodes = {} # Dict of Stats objects, keyed by nodename self.stats = collections.defaultdict(compute_stats.Stats) # Set of UUIDs of instances tracked on this host. self.tracked_instances = set() self.tracked_migrations = {} self.is_bfv = {} # dict, keyed by instance uuid, to is_bfv boolean monitor_handler = monitors.MonitorHandler(self) self.monitors = monitor_handler.monitors self.old_resources = collections.defaultdict(objects.ComputeNode) self.reportclient = report.SchedulerReportClient() self.ram_allocation_ratio = CONF.ram_allocation_ratio self.cpu_allocation_ratio = CONF.cpu_allocation_ratio self.disk_allocation_ratio = CONF.disk_allocation_ratio @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def instance_claim(self, context, instance, nodename, limits=None): """Indicate that some resources are needed for an upcoming compute instance build operation. This should be called before the compute node is about to perform an instance build operation that will consume additional resources. :param context: security context :param instance: instance to reserve resources for. :type instance: nova.objects.instance.Instance object :param nodename: The Ironic nodename selected by the scheduler :param limits: Dict of oversubscription limits for memory, disk, and CPUs. :returns: A Claim ticket representing the reserved resources. It can be used to revert the resource usage if an error occurs during the instance build. """ if self.disabled(nodename): # instance_claim() was called before update_available_resource() # (which ensures that a compute node exists for nodename). We # shouldn't get here but in case we do, just set the instance's # host and nodename attribute (probably incorrect) and return a # NoopClaim. # TODO(jaypipes): Remove all the disabled junk from the resource # tracker. Servicegroup API-level active-checking belongs in the # nova-compute manager. self._set_instance_host_and_node(instance, nodename) return claims.NopClaim() # sanity checks: if instance.host: LOG.warning("Host field should not be set on the instance " "until resources have been claimed.", instance=instance) if instance.node: LOG.warning("Node field should not be set on the instance " "until resources have been claimed.", instance=instance) # get the overhead required to build this instance: overhead = self.driver.estimate_instance_overhead(instance) LOG.debug("Memory overhead for %(flavor)d MB instance; %(overhead)d " "MB", {'flavor': instance.flavor.memory_mb, 'overhead': overhead['memory_mb']}) LOG.debug("Disk overhead for %(flavor)d GB instance; %(overhead)d " "GB", {'flavor': instance.flavor.root_gb, 'overhead': overhead.get('disk_gb', 0)}) LOG.debug("CPU overhead for %(flavor)d vCPUs instance; %(overhead)d " "vCPU(s)", {'flavor': instance.flavor.vcpus, 'overhead': overhead.get('vcpus', 0)}) cn = self.compute_nodes[nodename] pci_requests = objects.InstancePCIRequests.get_by_instance_uuid( context, instance.uuid) claim = claims.Claim(context, instance, nodename, self, cn, pci_requests, overhead=overhead, limits=limits) # self._set_instance_host_and_node() will save instance to the DB # so set instance.numa_topology first. We need to make sure # that numa_topology is saved while under COMPUTE_RESOURCE_SEMAPHORE # so that the resource audit knows about any cpus we've pinned. instance_numa_topology = claim.claimed_numa_topology instance.numa_topology = instance_numa_topology self._set_instance_host_and_node(instance, nodename) if self.pci_tracker: # NOTE(jaypipes): ComputeNode.pci_device_pools is set below # in _update_usage_from_instance(). self.pci_tracker.claim_instance(context, pci_requests, instance_numa_topology) # Mark resources in-use and update stats self._update_usage_from_instance(context, instance, nodename) elevated = context.elevated() # persist changes to the compute node: self._update(elevated, cn) return claim @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def rebuild_claim(self, context, instance, nodename, limits=None, image_meta=None, migration=None): """Create a claim for a rebuild operation.""" instance_type = instance.flavor return self._move_claim(context, instance, instance_type, nodename, migration, move_type='evacuation', limits=limits, image_meta=image_meta) @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def resize_claim(self, context, instance, instance_type, nodename, migration, image_meta=None, limits=None): """Create a claim for a resize or cold-migration move. Note that this code assumes ``instance.new_flavor`` is set when resizing with a new flavor. """ return self._move_claim(context, instance, instance_type, nodename, migration, image_meta=image_meta, limits=limits) def _move_claim(self, context, instance, new_instance_type, nodename, migration, move_type=None, image_meta=None, limits=None): """Indicate that resources are needed for a move to this host. Move can be either a migrate/resize, live-migrate or an evacuate/rebuild operation. :param context: security context :param instance: instance object to reserve resources for :param new_instance_type: new instance_type being resized to :param nodename: The Ironic nodename selected by the scheduler :param image_meta: instance image metadata :param move_type: move type - can be one of 'migration', 'resize', 'live-migration', 'evacuate' :param limits: Dict of oversubscription limits for memory, disk, and CPUs :param migration: A migration object if one was already created elsewhere for this operation (otherwise None) :returns: A Claim ticket representing the reserved resources. This should be turned into finalize a resource claim or free resources after the compute operation is finished. """ image_meta = image_meta or {} if migration: self._claim_existing_migration(migration, nodename) else: migration = self._create_migration(context, instance, new_instance_type, nodename, move_type) if self.disabled(nodename): # compute_driver doesn't support resource tracking, just # generate the migration record and continue the resize: return claims.NopClaim(migration=migration) # get memory overhead required to build this instance: overhead = self.driver.estimate_instance_overhead(new_instance_type) LOG.debug("Memory overhead for %(flavor)d MB instance; %(overhead)d " "MB", {'flavor': new_instance_type.memory_mb, 'overhead': overhead['memory_mb']}) LOG.debug("Disk overhead for %(flavor)d GB instance; %(overhead)d " "GB", {'flavor': instance.flavor.root_gb, 'overhead': overhead.get('disk_gb', 0)}) LOG.debug("CPU overhead for %(flavor)d vCPUs instance; %(overhead)d " "vCPU(s)", {'flavor': instance.flavor.vcpus, 'overhead': overhead.get('vcpus', 0)}) cn = self.compute_nodes[nodename] # TODO(moshele): we are recreating the pci requests even if # there was no change on resize. This will cause allocating # the old/new pci device in the resize phase. In the future # we would like to optimise this. new_pci_requests = pci_request.get_pci_requests_from_flavor( new_instance_type) new_pci_requests.instance_uuid = instance.uuid # PCI requests come from two sources: instance flavor and # SR-IOV ports. SR-IOV ports pci_request don't have an alias_name. # On resize merge the SR-IOV ports pci_requests with the new # instance flavor pci_requests. if instance.pci_requests: for request in instance.pci_requests.requests: if request.alias_name is None: new_pci_requests.requests.append(request) claim = claims.MoveClaim(context, instance, nodename, new_instance_type, image_meta, self, cn, new_pci_requests, overhead=overhead, limits=limits) claim.migration = migration claimed_pci_devices_objs = [] if self.pci_tracker: # NOTE(jaypipes): ComputeNode.pci_device_pools is set below # in _update_usage_from_instance(). claimed_pci_devices_objs = self.pci_tracker.claim_instance( context, new_pci_requests, claim.claimed_numa_topology) claimed_pci_devices = objects.PciDeviceList( objects=claimed_pci_devices_objs) # TODO(jaypipes): Move claimed_numa_topology out of the Claim's # constructor flow so the Claim constructor only tests whether # resources can be claimed, not consume the resources directly. mig_context = objects.MigrationContext( context=context, instance_uuid=instance.uuid, migration_id=migration.id, old_numa_topology=instance.numa_topology, new_numa_topology=claim.claimed_numa_topology, old_pci_devices=instance.pci_devices, new_pci_devices=claimed_pci_devices, old_pci_requests=instance.pci_requests, new_pci_requests=new_pci_requests) instance.migration_context = mig_context instance.save() # Mark the resources in-use for the resize landing on this # compute host: self._update_usage_from_migration(context, instance, migration, nodename) elevated = context.elevated() self._update(elevated, cn) return claim def _create_migration(self, context, instance, new_instance_type, nodename, move_type=None): """Create a migration record for the upcoming resize. This should be done while the COMPUTE_RESOURCES_SEMAPHORE is held so the resource claim will not be lost if the audit process starts. """ migration = objects.Migration(context=context.elevated()) migration.dest_compute = self.host migration.dest_node = nodename migration.dest_host = self.driver.get_host_ip_addr() migration.old_instance_type_id = instance.flavor.id migration.new_instance_type_id = new_instance_type.id migration.status = 'pre-migrating' migration.instance_uuid = instance.uuid migration.source_compute = instance.host migration.source_node = instance.node if move_type: migration.migration_type = move_type else: migration.migration_type = migration_obj.determine_migration_type( migration) migration.create() return migration def _claim_existing_migration(self, migration, nodename): """Make an existing migration record count for resource tracking. If a migration record was created already before the request made it to this compute host, only set up the migration so it's included in resource tracking. This should be done while the COMPUTE_RESOURCES_SEMAPHORE is held. """ migration.dest_compute = self.host migration.dest_node = nodename migration.dest_host = self.driver.get_host_ip_addr() migration.status = 'pre-migrating' migration.save() def _set_instance_host_and_node(self, instance, nodename): """Tag the instance as belonging to this host. This should be done while the COMPUTE_RESOURCES_SEMAPHORE is held so the resource claim will not be lost if the audit process starts. """ instance.host = self.host instance.launched_on = self.host instance.node = nodename instance.save() def _unset_instance_host_and_node(self, instance): """Untag the instance so it no longer belongs to the host. This should be done while the COMPUTE_RESOURCES_SEMAPHORE is held so the resource claim will not be lost if the audit process starts. """ instance.host = None instance.node = None instance.save() @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def abort_instance_claim(self, context, instance, nodename): """Remove usage from the given instance.""" self._update_usage_from_instance(context, instance, nodename, is_removed=True) instance.clear_numa_topology() self._unset_instance_host_and_node(instance) self._update(context.elevated(), self.compute_nodes[nodename]) def _drop_pci_devices(self, instance, nodename, prefix): if self.pci_tracker: # free old/new allocated pci devices pci_devices = self._get_migration_context_resource( 'pci_devices', instance, prefix=prefix) if pci_devices: for pci_device in pci_devices: self.pci_tracker.free_device(pci_device, instance) dev_pools_obj = self.pci_tracker.stats.to_device_pools_obj() self.compute_nodes[nodename].pci_device_pools = dev_pools_obj @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def drop_move_claim(self, context, instance, nodename, instance_type=None, prefix='new_'): """Remove usage for an incoming/outgoing migration. :param context: Security context. :param instance: The instance whose usage is to be removed. :param nodename: Host on which to remove usage. If the migration completed successfully, this is normally the source. If it did not complete successfully (failed or reverted), this is normally the destination. :param instance_type: The flavor that determines the usage to remove. If the migration completed successfully, this is the old flavor to be removed from the source. If the migration did not complete successfully, this is the new flavor to be removed from the destination. :param prefix: Prefix to use when accessing migration context attributes. 'old_' or 'new_', with 'new_' being the default. """ # Remove usage for an instance that is tracked in migrations, such as # on the dest node during revert resize. if instance['uuid'] in self.tracked_migrations: migration = self.tracked_migrations.pop(instance['uuid']) if not instance_type: instance_type = self._get_instance_type(instance, prefix, migration) # Remove usage for an instance that is not tracked in migrations (such # as on the source node after a migration). # NOTE(lbeliveau): On resize on the same node, the instance is # included in both tracked_migrations and tracked_instances. elif instance['uuid'] in self.tracked_instances: self.tracked_instances.remove(instance['uuid']) if instance_type is not None: numa_topology = self._get_migration_context_resource( 'numa_topology', instance, prefix=prefix) usage = self._get_usage_dict( instance_type, instance, numa_topology=numa_topology) self._drop_pci_devices(instance, nodename, prefix) self._update_usage(usage, nodename, sign=-1) ctxt = context.elevated() self._update(ctxt, self.compute_nodes[nodename]) @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def update_usage(self, context, instance, nodename): """Update the resource usage and stats after a change in an instance """ if self.disabled(nodename): return uuid = instance['uuid'] # don't update usage for this instance unless it submitted a resource # claim first: if uuid in self.tracked_instances: self._update_usage_from_instance(context, instance, nodename) self._update(context.elevated(), self.compute_nodes[nodename]) def disabled(self, nodename): return (nodename not in self.compute_nodes or not self.driver.node_is_available(nodename)) def _check_for_nodes_rebalance(self, context, resources, nodename): """Check if nodes rebalance has happened. The ironic driver maintains a hash ring mapping bare metal nodes to compute nodes. If a compute dies, the hash ring is rebuilt, and some of its bare metal nodes (more precisely, those not in ACTIVE state) are assigned to other computes. This method checks for this condition and adjusts the database accordingly. :param context: security context :param resources: initial values :param nodename: node name :returns: True if a suitable compute node record was found, else False """ if not self.driver.rebalances_nodes: return False # Its possible ironic just did a node re-balance, so let's # check if there is a compute node that already has the correct # hypervisor_hostname. We can re-use that rather than create a # new one and have to move existing placement allocations cn_candidates = objects.ComputeNodeList.get_by_hypervisor( context, nodename) if len(cn_candidates) == 1: cn = cn_candidates[0] LOG.info("ComputeNode %(name)s moving from %(old)s to %(new)s", {"name": nodename, "old": cn.host, "new": self.host}) cn.host = self.host self.compute_nodes[nodename] = cn self._copy_resources(cn, resources) self._setup_pci_tracker(context, cn, resources) self._update(context, cn) return True elif len(cn_candidates) > 1: LOG.error( "Found more than one ComputeNode for nodename %s. " "Please clean up the orphaned ComputeNode records in your DB.", nodename) return False def _init_compute_node(self, context, resources): """Initialize the compute node if it does not already exist. The resource tracker will be inoperable if compute_node is not defined. The compute_node will remain undefined if we fail to create it or if there is no associated service registered. If this method has to create a compute node it needs initial values - these come from resources. :param context: security context :param resources: initial values :returns: True if a new compute_nodes table record was created, False otherwise """ nodename = resources['hypervisor_hostname'] # if there is already a compute node just use resources # to initialize if nodename in self.compute_nodes: cn = self.compute_nodes[nodename] self._copy_resources(cn, resources) self._setup_pci_tracker(context, cn, resources) return False # now try to get the compute node record from the # database. If we get one we use resources to initialize cn = self._get_compute_node(context, nodename) if cn: self.compute_nodes[nodename] = cn self._copy_resources(cn, resources) self._setup_pci_tracker(context, cn, resources) return False if self._check_for_nodes_rebalance(context, resources, nodename): return False # there was no local copy and none in the database # so we need to create a new compute node. This needs # to be initialized with resource values. cn = objects.ComputeNode(context) cn.host = self.host self._copy_resources(cn, resources, initial=True) self.compute_nodes[nodename] = cn cn.create() LOG.info('Compute node record created for ' '%(host)s:%(node)s with uuid: %(uuid)s', {'host': self.host, 'node': nodename, 'uuid': cn.uuid}) self._setup_pci_tracker(context, cn, resources) return True def _setup_pci_tracker(self, context, compute_node, resources): if not self.pci_tracker: n_id = compute_node.id self.pci_tracker = pci_manager.PciDevTracker(context, node_id=n_id) if 'pci_passthrough_devices' in resources: dev_json = resources.pop('pci_passthrough_devices') self.pci_tracker.update_devices_from_hypervisor_resources( dev_json) dev_pools_obj = self.pci_tracker.stats.to_device_pools_obj() compute_node.pci_device_pools = dev_pools_obj def _copy_resources(self, compute_node, resources, initial=False): """Copy resource values to supplied compute_node.""" nodename = resources['hypervisor_hostname'] stats = self.stats[nodename] # purge old stats and init with anything passed in by the driver # NOTE(danms): Preserve 'failed_builds' across the stats clearing, # as that is not part of resources # TODO(danms): Stop doing this when we get a column to store this # directly prev_failed_builds = stats.get('failed_builds', 0) stats.clear() stats['failed_builds'] = prev_failed_builds stats.digest_stats(resources.get('stats')) compute_node.stats = stats # Update the allocation ratios for the related ComputeNode object # but only if the configured values are not the default; the # ComputeNode._from_db_object method takes care of providing default # allocation ratios when the config is left at the default, so # we'll really end up with something like a # ComputeNode.cpu_allocation_ratio of 16.0. We want to avoid # resetting the ComputeNode fields to None because that will make # the _resource_change method think something changed when really it # didn't. # NOTE(yikun): The CONF.initial_(cpu|ram|disk)_allocation_ratio would # be used when we initialize the compute node object, that means the # ComputeNode.(cpu|ram|disk)_allocation_ratio will be set to # CONF.initial_(cpu|ram|disk)_allocation_ratio when initial flag is # True. for res in ('cpu', 'disk', 'ram'): attr = '%s_allocation_ratio' % res if initial: conf_alloc_ratio = getattr(CONF, 'initial_%s' % attr) else: conf_alloc_ratio = getattr(self, attr) # NOTE(yikun): In Stein version, we change the default value of # (cpu|ram|disk)_allocation_ratio from 0.0 to None, but we still # should allow 0.0 to keep compatibility, and this 0.0 condition # will be removed in the next version (T version). if conf_alloc_ratio not in (0.0, None): setattr(compute_node, attr, conf_alloc_ratio) # now copy rest to compute_node compute_node.update_from_virt_driver(resources) def remove_node(self, nodename): """Handle node removal/rebalance. Clean up any stored data about a compute node no longer managed by this host. """ self.stats.pop(nodename, None) self.compute_nodes.pop(nodename, None) self.old_resources.pop(nodename, None) def _get_host_metrics(self, context, nodename): """Get the metrics from monitors and notify information to message bus. """ metrics = objects.MonitorMetricList() metrics_info = {} for monitor in self.monitors: try: monitor.populate_metrics(metrics) except NotImplementedError: LOG.debug("The compute driver doesn't support host " "metrics for %(mon)s", {'mon': monitor}) except Exception as exc: LOG.warning("Cannot get the metrics from %(mon)s; " "error: %(exc)s", {'mon': monitor, 'exc': exc}) # TODO(jaypipes): Remove this when compute_node.metrics doesn't need # to be populated as a JSONified string. metric_list = metrics.to_list() if len(metric_list): metrics_info['nodename'] = nodename metrics_info['metrics'] = metric_list metrics_info['host'] = self.host metrics_info['host_ip'] = CONF.my_ip notifier = rpc.get_notifier(service='compute', host=nodename) notifier.info(context, 'compute.metrics.update', metrics_info) compute_utils.notify_about_metrics_update( context, self.host, CONF.my_ip, nodename, metrics) return metric_list def update_available_resource(self, context, nodename, startup=False): """Override in-memory calculations of compute node resource usage based on data audited from the hypervisor layer. Add in resource claims in progress to account for operations that have declared a need for resources, but not necessarily retrieved them from the hypervisor layer yet. :param nodename: Temporary parameter representing the Ironic resource node. This parameter will be removed once Ironic baremetal resource nodes are handled like any other resource in the system. :param startup: Boolean indicating whether we're running this on on startup (True) or periodic (False). """ LOG.debug("Auditing locally available compute resources for " "%(host)s (node: %(node)s)", {'node': nodename, 'host': self.host}) resources = self.driver.get_available_resource(nodename) # NOTE(jaypipes): The resources['hypervisor_hostname'] field now # contains a non-None value, even for non-Ironic nova-compute hosts. It # is this value that will be populated in the compute_nodes table. resources['host_ip'] = CONF.my_ip # We want the 'cpu_info' to be None from the POV of the # virt driver, but the DB requires it to be non-null so # just force it to empty string if "cpu_info" not in resources or resources["cpu_info"] is None: resources["cpu_info"] = '' self._verify_resources(resources) self._report_hypervisor_resource_view(resources) self._update_available_resource(context, resources, startup=startup) def _pair_instances_to_migrations(self, migrations, instance_by_uuid): for migration in migrations: try: migration.instance = instance_by_uuid[migration.instance_uuid] except KeyError: # NOTE(danms): If this happens, we don't set it here, and # let the code either fail or lazy-load the instance later # which is what happened before we added this optimization. # NOTE(tdurakov) this situation is possible for resize/cold # migration when migration is finished but haven't yet # confirmed/reverted in that case instance already changed host # to destination and no matching happens LOG.debug('Migration for instance %(uuid)s refers to ' 'another host\'s instance!', {'uuid': migration.instance_uuid}) @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def _update_available_resource(self, context, resources, startup=False): # initialize the compute node object, creating it # if it does not already exist. is_new_compute_node = self._init_compute_node(context, resources) nodename = resources['hypervisor_hostname'] # if we could not init the compute node the tracker will be # disabled and we should quit now if self.disabled(nodename): return # Grab all instances assigned to this node: instances = objects.InstanceList.get_by_host_and_node( context, self.host, nodename, expected_attrs=['system_metadata', 'numa_topology', 'flavor', 'migration_context']) # Now calculate usage based on instance utilization: instance_by_uuid = self._update_usage_from_instances( context, instances, nodename) # Grab all in-progress migrations: migrations = objects.MigrationList.get_in_progress_by_host_and_node( context, self.host, nodename) self._pair_instances_to_migrations(migrations, instance_by_uuid) self._update_usage_from_migrations(context, migrations, nodename) # A new compute node means there won't be a resource provider yet since # that would be created via the _update() call below, and if there is # no resource provider then there are no allocations against it. if not is_new_compute_node: self._remove_deleted_instances_allocations( context, self.compute_nodes[nodename], migrations, instance_by_uuid) # Detect and account for orphaned instances that may exist on the # hypervisor, but are not in the DB: orphans = self._find_orphaned_instances() self._update_usage_from_orphans(orphans, nodename) cn = self.compute_nodes[nodename] # NOTE(yjiang5): Because pci device tracker status is not cleared in # this periodic task, and also because the resource tracker is not # notified when instances are deleted, we need remove all usages # from deleted instances. self.pci_tracker.clean_usage(instances, migrations, orphans) dev_pools_obj = self.pci_tracker.stats.to_device_pools_obj() cn.pci_device_pools = dev_pools_obj self._report_final_resource_view(nodename) metrics = self._get_host_metrics(context, nodename) # TODO(pmurray): metrics should not be a json string in ComputeNode, # but it is. This should be changed in ComputeNode cn.metrics = jsonutils.dumps(metrics) # update the compute_node self._update(context, cn, startup=startup) LOG.debug('Compute_service record updated for %(host)s:%(node)s', {'host': self.host, 'node': nodename}) def _get_compute_node(self, context, nodename): """Returns compute node for the host and nodename.""" try: return objects.ComputeNode.get_by_host_and_nodename( context, self.host, nodename) except exception.NotFound: LOG.warning("No compute node record for %(host)s:%(node)s", {'host': self.host, 'node': nodename}) def _report_hypervisor_resource_view(self, resources): """Log the hypervisor's view of free resources. This is just a snapshot of resource usage recorded by the virt driver. The following resources are logged: - free memory - free disk - free CPUs - assignable PCI devices """ nodename = resources['hypervisor_hostname'] free_ram_mb = resources['memory_mb'] - resources['memory_mb_used'] free_disk_gb = resources['local_gb'] - resources['local_gb_used'] vcpus = resources['vcpus'] if vcpus: free_vcpus = vcpus - resources['vcpus_used'] else: free_vcpus = 'unknown' pci_devices = resources.get('pci_passthrough_devices') LOG.debug("Hypervisor/Node resource view: " "name=%(node)s " "free_ram=%(free_ram)sMB " "free_disk=%(free_disk)sGB " "free_vcpus=%(free_vcpus)s " "pci_devices=%(pci_devices)s", {'node': nodename, 'free_ram': free_ram_mb, 'free_disk': free_disk_gb, 'free_vcpus': free_vcpus, 'pci_devices': pci_devices}) def _report_final_resource_view(self, nodename): """Report final calculate of physical memory, used virtual memory, disk, usable vCPUs, used virtual CPUs and PCI devices, including instance calculations and in-progress resource claims. These values will be exposed via the compute node table to the scheduler. """ cn = self.compute_nodes[nodename] vcpus = cn.vcpus if vcpus: tcpu = vcpus ucpu = cn.vcpus_used LOG.debug("Total usable vcpus: %(tcpu)s, " "total allocated vcpus: %(ucpu)s", {'tcpu': vcpus, 'ucpu': ucpu}) else: tcpu = 0 ucpu = 0 pci_stats = (list(cn.pci_device_pools) if cn.pci_device_pools else []) LOG.debug("Final resource view: " "name=%(node)s " "phys_ram=%(phys_ram)sMB " "used_ram=%(used_ram)sMB " "phys_disk=%(phys_disk)sGB " "used_disk=%(used_disk)sGB " "total_vcpus=%(total_vcpus)s " "used_vcpus=%(used_vcpus)s " "pci_stats=%(pci_stats)s", {'node': nodename, 'phys_ram': cn.memory_mb, 'used_ram': cn.memory_mb_used, 'phys_disk': cn.local_gb, 'used_disk': cn.local_gb_used, 'total_vcpus': tcpu, 'used_vcpus': ucpu, 'pci_stats': pci_stats}) def _resource_change(self, compute_node): """Check to see if any resources have changed.""" nodename = compute_node.hypervisor_hostname old_compute = self.old_resources[nodename] if not obj_base.obj_equal_prims( compute_node, old_compute, ['updated_at']): self.old_resources[nodename] = copy.deepcopy(compute_node) return True return False def _get_traits(self, nodename, provider_tree): # Get the traits from the ProviderTree which will be the set # of virt-owned traits plus any externally defined traits set # on the provider that aren't owned by the virt driver. traits = provider_tree.data(nodename).traits # Now get the driver's capabilities and add any supported # traits that are missing, and remove any existing set traits # that are not currently supported. for trait, supported in self.driver.capabilities_as_traits().items(): if supported: traits.add(trait) elif trait in traits: traits.remove(trait) return list(traits) @retrying.retry(stop_max_attempt_number=4, retry_on_exception=lambda e: isinstance( e, exception.ResourceProviderUpdateConflict)) def _update_to_placement(self, context, compute_node, startup): """Send resource and inventory changes to placement.""" # NOTE(jianghuaw): Some resources(e.g. VGPU) are not saved in the # object of compute_node; instead the inventory data for these # resource is reported by driver's get_inventory(). So even there # is no resource change for compute_node as above, we need proceed # to get inventory and use report client interfaces to update # inventory to placement. It's report client's responsibility to # ensure the update request to placement only happens when inventory # is changed. nodename = compute_node.hypervisor_hostname # Persist the stats to the Scheduler # First try update_provider_tree # Retrieve the provider tree associated with this compute node. If # it doesn't exist yet, this will create it with a (single, root) # provider corresponding to the compute node. prov_tree = self.reportclient.get_provider_tree_and_ensure_root( context, compute_node.uuid, name=compute_node.hypervisor_hostname) # Let the virt driver rearrange the provider tree and set/update # the inventory, traits, and aggregates throughout. allocs = None try: try: self.driver.update_provider_tree(prov_tree, nodename) except exception.ReshapeNeeded: if not startup: # This isn't supposed to happen during periodic, so raise # it up; the compute manager will treat it specially. raise LOG.info("Performing resource provider inventory and " "allocation data migration during compute service " "startup or fast-forward upgrade.") allocs = self.reportclient.get_allocations_for_provider_tree( context, nodename) self.driver.update_provider_tree(prov_tree, nodename, allocations=allocs) # Inject driver capabilities traits into the provider # tree. We need to determine the traits that the virt # driver owns - so those that come from the tree itself # (via the virt driver) plus the compute capabilities # traits, and then merge those with the traits set # externally that the driver does not own - and remove any # set on the provider externally that the virt owns but # aren't in the current list of supported traits. For # example, let's say we reported multiattach support as a # trait at t1 and then at t2 it's not, so we need to # remove it. But at both t1 and t2 there is a # CUSTOM_VENDOR_TRAIT_X which we can't touch because it # was set externally on the provider. traits = self._get_traits(nodename, provider_tree=prov_tree) prov_tree.update_traits(nodename, traits) except NotImplementedError: # update_provider_tree isn't implemented yet - try get_inventory try: inv_data = self.driver.get_inventory(nodename) _normalize_inventory_from_cn_obj(inv_data, compute_node) except NotImplementedError: # Eventually all virt drivers will return an inventory dict in # the format that the placement API expects and we'll be able # to remove this code branch inv_data = compute_utils.compute_node_to_inventory_dict( compute_node) prov_tree.update_inventory(nodename, inv_data) # Flush any changes. If we processed ReshapeNeeded above, allocs is not # None, and this will hit placement's POST /reshaper route. self.reportclient.update_from_provider_tree(context, prov_tree, allocations=allocs) def _update(self, context, compute_node, startup=False): """Update partial stats locally and populate them to Scheduler.""" if self._resource_change(compute_node): # If the compute_node's resource changed, update to DB. # NOTE(jianghuaw): Once we completely move to use get_inventory() # for all resource provider's inv data. We can remove this check. # At the moment we still need this check and save compute_node. compute_node.save() self._update_to_placement(context, compute_node, startup) if self.pci_tracker: self.pci_tracker.save(context) def _update_usage(self, usage, nodename, sign=1): mem_usage = usage['memory_mb'] disk_usage = usage.get('root_gb', 0) vcpus_usage = usage.get('vcpus', 0) overhead = self.driver.estimate_instance_overhead(usage) mem_usage += overhead['memory_mb'] disk_usage += overhead.get('disk_gb', 0) vcpus_usage += overhead.get('vcpus', 0) cn = self.compute_nodes[nodename] cn.memory_mb_used += sign * mem_usage cn.local_gb_used += sign * disk_usage cn.local_gb_used += sign * usage.get('ephemeral_gb', 0) cn.local_gb_used += sign * usage.get('swap', 0) / 1024 cn.vcpus_used += sign * vcpus_usage # free ram and disk may be negative, depending on policy: cn.free_ram_mb = cn.memory_mb - cn.memory_mb_used cn.free_disk_gb = cn.local_gb - cn.local_gb_used stats = self.stats[nodename] cn.running_vms = stats.num_instances # Calculate the numa usage free = sign == -1 updated_numa_topology = hardware.get_host_numa_usage_from_instance( cn, usage, free) cn.numa_topology = updated_numa_topology def _get_migration_context_resource(self, resource, instance, prefix='new_'): migration_context = instance.migration_context resource = prefix + resource if migration_context and resource in migration_context: return getattr(migration_context, resource) return None def _update_usage_from_migration(self, context, instance, migration, nodename): """Update usage for a single migration. The record may represent an incoming or outbound migration. """ if not _is_trackable_migration(migration): return uuid = migration.instance_uuid LOG.info("Updating resource usage from migration %s", migration.uuid, instance_uuid=uuid) incoming = (migration.dest_compute == self.host and migration.dest_node == nodename) outbound = (migration.source_compute == self.host and migration.source_node == nodename) same_node = (incoming and outbound) tracked = uuid in self.tracked_instances itype = None numa_topology = None sign = 0 if same_node: # Same node resize. Record usage for the 'new_' resources. This # is executed on resize_claim(). if (instance['instance_type_id'] == migration.old_instance_type_id): itype = self._get_instance_type(instance, 'new_', migration) numa_topology = self._get_migration_context_resource( 'numa_topology', instance) # Allocate pci device(s) for the instance. sign = 1 else: # The instance is already set to the new flavor (this is done # by the compute manager on finish_resize()), hold space for a # possible revert to the 'old_' resources. # NOTE(lbeliveau): When the periodic audit timer gets # triggered, the compute usage gets reset. The usage for an # instance that is migrated to the new flavor but not yet # confirmed/reverted will first get accounted for by # _update_usage_from_instances(). This method will then be # called, and we need to account for the '_old' resources # (just in case). itype = self._get_instance_type(instance, 'old_', migration) numa_topology = self._get_migration_context_resource( 'numa_topology', instance, prefix='old_') elif incoming and not tracked: # instance has not yet migrated here: itype = self._get_instance_type(instance, 'new_', migration) numa_topology = self._get_migration_context_resource( 'numa_topology', instance) # Allocate pci device(s) for the instance. sign = 1 LOG.debug('Starting to track incoming migration %s with flavor %s', migration.uuid, itype.flavorid, instance=instance) elif outbound and not tracked: # instance migrated, but record usage for a possible revert: itype = self._get_instance_type(instance, 'old_', migration) numa_topology = self._get_migration_context_resource( 'numa_topology', instance, prefix='old_') LOG.debug('Starting to track outgoing migration %s with flavor %s', migration.uuid, itype.flavorid, instance=instance) if itype: cn = self.compute_nodes[nodename] usage = self._get_usage_dict( itype, instance, numa_topology=numa_topology) if self.pci_tracker and sign: self.pci_tracker.update_pci_for_instance( context, instance, sign=sign) self._update_usage(usage, nodename) if self.pci_tracker: obj = self.pci_tracker.stats.to_device_pools_obj() cn.pci_device_pools = obj else: obj = objects.PciDevicePoolList() cn.pci_device_pools = obj self.tracked_migrations[uuid] = migration def _update_usage_from_migrations(self, context, migrations, nodename): filtered = {} instances = {} self.tracked_migrations.clear() # do some defensive filtering against bad migrations records in the # database: for migration in migrations: uuid = migration.instance_uuid try: if uuid not in instances: instances[uuid] = migration.instance except exception.InstanceNotFound as e: # migration referencing deleted instance LOG.debug('Migration instance not found: %s', e) continue # skip migration if instance isn't in a resize state: if not _instance_in_resize_state(instances[uuid]): LOG.warning("Instance not resizing, skipping migration.", instance_uuid=uuid) continue # filter to most recently updated migration for each instance: other_migration = filtered.get(uuid, None) # NOTE(claudiub): In Python 3, you cannot compare NoneTypes. if other_migration: om = other_migration other_time = om.updated_at or om.created_at migration_time = migration.updated_at or migration.created_at if migration_time > other_time: filtered[uuid] = migration else: filtered[uuid] = migration for migration in filtered.values(): instance = instances[migration.instance_uuid] # Skip migration (and mark it as error) if it doesn't match the # instance migration id. # This can happen if we have a stale migration record. # We want to proceed if instance.migration_context is None if (instance.migration_context is not None and instance.migration_context.migration_id != migration.id): LOG.info("Current instance migration %(im)s doesn't match " "migration %(m)s, marking migration as error. " "This can occur if a previous migration for this " "instance did not complete.", {'im': instance.migration_context.migration_id, 'm': migration.id}) migration.status = "error" migration.save() continue try: self._update_usage_from_migration(context, instance, migration, nodename) except exception.FlavorNotFound: LOG.warning("Flavor could not be found, skipping migration.", instance_uuid=instance.uuid) continue def _update_usage_from_instance(self, context, instance, nodename, is_removed=False): """Update usage for a single instance.""" uuid = instance['uuid'] is_new_instance = uuid not in self.tracked_instances # NOTE(sfinucan): Both brand new instances as well as instances that # are being unshelved will have is_new_instance == True is_removed_instance = not is_new_instance and (is_removed or instance['vm_state'] in vm_states.ALLOW_RESOURCE_REMOVAL) if is_new_instance: self.tracked_instances.add(uuid) sign = 1 if is_removed_instance: self.tracked_instances.remove(uuid) sign = -1 cn = self.compute_nodes[nodename] stats = self.stats[nodename] stats.update_stats_for_instance(instance, is_removed_instance) cn.stats = stats # if it's a new or deleted instance: if is_new_instance or is_removed_instance: if self.pci_tracker: self.pci_tracker.update_pci_for_instance(context, instance, sign=sign) # new instance, update compute node resource usage: self._update_usage(self._get_usage_dict(instance, instance), nodename, sign=sign) # Stop tracking removed instances in the is_bfv cache. This needs to # happen *after* calling _get_usage_dict() since that relies on the # is_bfv cache. if is_removed_instance and uuid in self.is_bfv: del self.is_bfv[uuid] cn.current_workload = stats.calculate_workload() if self.pci_tracker: obj = self.pci_tracker.stats.to_device_pools_obj() cn.pci_device_pools = obj else: cn.pci_device_pools = objects.PciDevicePoolList() def _update_usage_from_instances(self, context, instances, nodename): """Calculate resource usage based on instance utilization. This is different than the hypervisor's view as it will account for all instances assigned to the local compute host, even if they are not currently powered on. """ self.tracked_instances.clear() cn = self.compute_nodes[nodename] # set some initial values, reserve room for host/hypervisor: cn.local_gb_used = CONF.reserved_host_disk_mb / 1024 cn.memory_mb_used = CONF.reserved_host_memory_mb cn.vcpus_used = CONF.reserved_host_cpus cn.free_ram_mb = (cn.memory_mb - cn.memory_mb_used) cn.free_disk_gb = (cn.local_gb - cn.local_gb_used) cn.current_workload = 0 cn.running_vms = 0 instance_by_uuid = {} for instance in instances: if instance.vm_state not in vm_states.ALLOW_RESOURCE_REMOVAL: self._update_usage_from_instance(context, instance, nodename) instance_by_uuid[instance.uuid] = instance return instance_by_uuid def _remove_deleted_instances_allocations(self, context, cn, migrations, instance_by_uuid): migration_uuids = [migration.uuid for migration in migrations if 'uuid' in migration] # NOTE(jaypipes): All of this code sucks. It's basically dealing with # all the corner cases in move, local delete, unshelve and rebuild # operations for when allocations should be deleted when things didn't # happen according to the normal flow of events where the scheduler # always creates allocations for an instance try: # pai: report.ProviderAllocInfo namedtuple pai = self.reportclient.get_allocations_for_resource_provider( context, cn.uuid) except (exception.ResourceProviderAllocationRetrievalFailed, ks_exc.ClientException) as e: LOG.error("Skipping removal of allocations for deleted instances: " "%s", e) return allocations = pai.allocations if not allocations: # The main loop below would short-circuit anyway, but this saves us # the (potentially expensive) context.elevated construction below. return read_deleted_context = context.elevated(read_deleted='yes') for consumer_uuid, alloc in allocations.items(): if consumer_uuid in self.tracked_instances: LOG.debug("Instance %s actively managed on this compute host " "and has allocations in placement: %s.", consumer_uuid, alloc) continue if consumer_uuid in migration_uuids: LOG.debug("Migration %s is active on this compute host " "and has allocations in placement: %s.", consumer_uuid, alloc) continue # We know these are instances now, so proceed instance_uuid = consumer_uuid instance = instance_by_uuid.get(instance_uuid) if not instance: try: instance = objects.Instance.get_by_uuid( read_deleted_context, consumer_uuid, expected_attrs=[]) except exception.InstanceNotFound: # The instance isn't even in the database. Either the # scheduler _just_ created an allocation for it and we're # racing with the creation in the cell database, or the # instance was deleted and fully archived before we got a # chance to run this. The former is far more likely than # the latter. Avoid deleting allocations for a building # instance here. LOG.info("Instance %(uuid)s has allocations against this " "compute host but is not found in the database.", {'uuid': instance_uuid}, exc_info=False) continue if instance.deleted: # The instance is gone, so we definitely want to remove # allocations associated with it. # NOTE(jaypipes): This will not be true if/when we support # cross-cell migrations... LOG.debug("Instance %s has been deleted (perhaps locally). " "Deleting allocations that remained for this " "instance against this compute host: %s.", instance_uuid, alloc) self.reportclient.delete_allocation_for_instance(context, instance_uuid) continue if not instance.host: # Allocations related to instances being scheduled should not # be deleted if we already wrote the allocation previously. LOG.debug("Instance %s has been scheduled to this compute " "host, the scheduler has made an allocation " "against this compute node but the instance has " "yet to start. Skipping heal of allocation: %s.", instance_uuid, alloc) continue if (instance.host == cn.host and instance.node == cn.hypervisor_hostname): # The instance is supposed to be on this compute host but is # not in the list of actively managed instances. LOG.warning("Instance %s is not being actively managed by " "this compute host but has allocations " "referencing this compute host: %s. Skipping " "heal of allocation because we do not know " "what to do.", instance_uuid, alloc) continue if instance.host != cn.host: # The instance has been moved to another host either via a # migration, evacuation or unshelve in between the time when we # ran InstanceList.get_by_host_and_node(), added those # instances to RT.tracked_instances and the above # Instance.get_by_uuid() call. We SHOULD attempt to remove any # allocations that reference this compute host if the VM is in # a stable terminal state (i.e. it isn't in a state of waiting # for resize to confirm/revert), however if the destination # host is an Ocata compute host, it will delete the allocation # that contains this source compute host information anyway and # recreate an allocation that only refers to itself. So we # don't need to do anything in that case. Just log the # situation here for information but don't attempt to delete or # change the allocation. LOG.warning("Instance %s has been moved to another host " "%s(%s). There are allocations remaining against " "the source host that might need to be removed: " "%s.", instance_uuid, instance.host, instance.node, alloc) def delete_allocation_for_evacuated_instance(self, context, instance, node, node_type='source'): # Clean up the instance allocation from this node in placement cn_uuid = self.compute_nodes[node].uuid if not self.reportclient.remove_provider_tree_from_instance_allocation( context, instance.uuid, cn_uuid): LOG.error("Failed to clean allocation of evacuated " "instance on the %s node %s", node_type, cn_uuid, instance=instance) def _find_orphaned_instances(self): """Given the set of instances and migrations already account for by resource tracker, sanity check the hypervisor to determine if there are any "orphaned" instances left hanging around. Orphans could be consuming memory and should be accounted for in usage calculations to guard against potential out of memory errors. """ uuids1 = frozenset(self.tracked_instances) uuids2 = frozenset(self.tracked_migrations.keys()) uuids = uuids1 | uuids2 usage = self.driver.get_per_instance_usage() vuuids = frozenset(usage.keys()) orphan_uuids = vuuids - uuids orphans = [usage[uuid] for uuid in orphan_uuids] return orphans def _update_usage_from_orphans(self, orphans, nodename): """Include orphaned instances in usage.""" for orphan in orphans: memory_mb = orphan['memory_mb'] LOG.warning("Detected running orphan instance: %(uuid)s " "(consuming %(memory_mb)s MB memory)", {'uuid': orphan['uuid'], 'memory_mb': memory_mb}) # just record memory usage for the orphan usage = {'memory_mb': memory_mb} self._update_usage(usage, nodename) def delete_allocation_for_shelve_offloaded_instance(self, context, instance): self.reportclient.delete_allocation_for_instance(context, instance.uuid) def _verify_resources(self, resources): resource_keys = ["vcpus", "memory_mb", "local_gb", "cpu_info", "vcpus_used", "memory_mb_used", "local_gb_used", "numa_topology"] missing_keys = [k for k in resource_keys if k not in resources] if missing_keys: reason = _("Missing keys: %s") % missing_keys raise exception.InvalidInput(reason=reason) def _get_instance_type(self, instance, prefix, migration): """Get the instance type from instance.""" stashed_flavors = migration.migration_type in ('resize',) if stashed_flavors: return getattr(instance, '%sflavor' % prefix) else: # NOTE(ndipanov): Certain migration types (all but resize) # do not change flavors so there is no need to stash # them. In that case - just get the instance flavor. return instance.flavor def _get_usage_dict(self, object_or_dict, instance, **updates): """Make a usage dict _update methods expect. Accepts a dict or an Instance or Flavor object, and a set of updates. Converts the object to a dict and applies the updates. :param object_or_dict: instance or flavor as an object or just a dict :param instance: nova.objects.Instance for the related operation; this is needed to determine if the instance is volume-backed :param updates: key-value pairs to update the passed object. Currently only considers 'numa_topology', all other keys are ignored. :returns: a dict with all the information from object_or_dict updated with updates """ def _is_bfv(): # Check to see if we have the is_bfv value cached. if instance.uuid in self.is_bfv: is_bfv = self.is_bfv[instance.uuid] else: is_bfv = compute_utils.is_volume_backed_instance( instance._context, instance) self.is_bfv[instance.uuid] = is_bfv return is_bfv usage = {} if isinstance(object_or_dict, objects.Instance): is_bfv = _is_bfv() usage = {'memory_mb': object_or_dict.flavor.memory_mb, 'swap': object_or_dict.flavor.swap, 'vcpus': object_or_dict.flavor.vcpus, 'root_gb': (0 if is_bfv else object_or_dict.flavor.root_gb), 'ephemeral_gb': object_or_dict.flavor.ephemeral_gb, 'numa_topology': object_or_dict.numa_topology} elif isinstance(object_or_dict, objects.Flavor): usage = obj_base.obj_to_primitive(object_or_dict) if _is_bfv(): usage['root_gb'] = 0 else: usage.update(object_or_dict) for key in ('numa_topology',): if key in updates: usage[key] = updates[key] return usage def build_failed(self, nodename): """Increments the failed_builds stats for the given node.""" self.stats[nodename].build_failed() def build_succeeded(self, nodename): """Resets the failed_builds stats for the given node.""" self.stats[nodename].build_succeeded() @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def claim_pci_devices(self, context, pci_requests): """Claim instance PCI resources :param context: security context :param pci_requests: a list of nova.objects.InstancePCIRequests :returns: a list of nova.objects.PciDevice objects """ result = self.pci_tracker.claim_instance( context, pci_requests, None) self.pci_tracker.save(context) return result @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def allocate_pci_devices_for_instance(self, context, instance): """Allocate instance claimed PCI resources :param context: security context :param instance: instance object """ self.pci_tracker.allocate_instance(instance) self.pci_tracker.save(context) @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def free_pci_device_allocations_for_instance(self, context, instance): """Free instance allocated PCI resources :param context: security context :param instance: instance object """ self.pci_tracker.free_instance_allocations(context, instance) self.pci_tracker.save(context) @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def free_pci_device_claims_for_instance(self, context, instance): """Free instance claimed PCI resources :param context: security context :param instance: instance object """ self.pci_tracker.free_instance_claims(context, instance) self.pci_tracker.save(context)
46.408769
79
0.621367
import collections import copy from keystoneauth1 import exceptions as ks_exc import os_resource_classes as orc from oslo_log import log as logging from oslo_serialization import jsonutils import retrying from nova.compute import claims from nova.compute import monitors from nova.compute import stats as compute_stats from nova.compute import task_states from nova.compute import utils as compute_utils from nova.compute import vm_states import nova.conf from nova import exception from nova.i18n import _ from nova import objects from nova.objects import base as obj_base from nova.objects import migration as migration_obj from nova.pci import manager as pci_manager from nova.pci import request as pci_request from nova import rpc from nova.scheduler.client import report from nova import utils from nova.virt import hardware CONF = nova.conf.CONF LOG = logging.getLogger(__name__) COMPUTE_RESOURCE_SEMAPHORE = "compute_resources" def _instance_in_resize_state(instance): vm = instance.vm_state task = instance.task_state if vm == vm_states.RESIZED: return True if (vm in [vm_states.ACTIVE, vm_states.STOPPED] and task in ( task_states.resizing_states + task_states.rebuild_states)): return True return False def _is_trackable_migration(migration): return migration.migration_type in ('resize', 'migration', 'evacuation') def _normalize_inventory_from_cn_obj(inv_data, cn): if orc.VCPU in inv_data: cpu_inv = inv_data[orc.VCPU] if 'allocation_ratio' not in cpu_inv: cpu_inv['allocation_ratio'] = cn.cpu_allocation_ratio if 'reserved' not in cpu_inv: cpu_inv['reserved'] = CONF.reserved_host_cpus if orc.MEMORY_MB in inv_data: mem_inv = inv_data[orc.MEMORY_MB] if 'allocation_ratio' not in mem_inv: mem_inv['allocation_ratio'] = cn.ram_allocation_ratio if 'reserved' not in mem_inv: mem_inv['reserved'] = CONF.reserved_host_memory_mb if orc.DISK_GB in inv_data: disk_inv = inv_data[orc.DISK_GB] if 'allocation_ratio' not in disk_inv: disk_inv['allocation_ratio'] = cn.disk_allocation_ratio if 'reserved' not in disk_inv: reserved_mb = CONF.reserved_host_disk_mb reserved_gb = compute_utils.convert_mb_to_ceil_gb(reserved_mb) disk_inv['reserved'] = reserved_gb class ResourceTracker(object): def __init__(self, host, driver): self.host = host self.driver = driver self.pci_tracker = None self.compute_nodes = {} self.stats = collections.defaultdict(compute_stats.Stats) self.tracked_instances = set() self.tracked_migrations = {} self.is_bfv = {} monitor_handler = monitors.MonitorHandler(self) self.monitors = monitor_handler.monitors self.old_resources = collections.defaultdict(objects.ComputeNode) self.reportclient = report.SchedulerReportClient() self.ram_allocation_ratio = CONF.ram_allocation_ratio self.cpu_allocation_ratio = CONF.cpu_allocation_ratio self.disk_allocation_ratio = CONF.disk_allocation_ratio @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def instance_claim(self, context, instance, nodename, limits=None): if self.disabled(nodename): self._set_instance_host_and_node(instance, nodename) return claims.NopClaim() if instance.host: LOG.warning("Host field should not be set on the instance " "until resources have been claimed.", instance=instance) if instance.node: LOG.warning("Node field should not be set on the instance " "until resources have been claimed.", instance=instance) overhead = self.driver.estimate_instance_overhead(instance) LOG.debug("Memory overhead for %(flavor)d MB instance; %(overhead)d " "MB", {'flavor': instance.flavor.memory_mb, 'overhead': overhead['memory_mb']}) LOG.debug("Disk overhead for %(flavor)d GB instance; %(overhead)d " "GB", {'flavor': instance.flavor.root_gb, 'overhead': overhead.get('disk_gb', 0)}) LOG.debug("CPU overhead for %(flavor)d vCPUs instance; %(overhead)d " "vCPU(s)", {'flavor': instance.flavor.vcpus, 'overhead': overhead.get('vcpus', 0)}) cn = self.compute_nodes[nodename] pci_requests = objects.InstancePCIRequests.get_by_instance_uuid( context, instance.uuid) claim = claims.Claim(context, instance, nodename, self, cn, pci_requests, overhead=overhead, limits=limits) instance_numa_topology = claim.claimed_numa_topology instance.numa_topology = instance_numa_topology self._set_instance_host_and_node(instance, nodename) if self.pci_tracker: # NOTE(jaypipes): ComputeNode.pci_device_pools is set below # in _update_usage_from_instance(). self.pci_tracker.claim_instance(context, pci_requests, instance_numa_topology) # Mark resources in-use and update stats self._update_usage_from_instance(context, instance, nodename) elevated = context.elevated() # persist changes to the compute node: self._update(elevated, cn) return claim @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def rebuild_claim(self, context, instance, nodename, limits=None, image_meta=None, migration=None): instance_type = instance.flavor return self._move_claim(context, instance, instance_type, nodename, migration, move_type='evacuation', limits=limits, image_meta=image_meta) @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def resize_claim(self, context, instance, instance_type, nodename, migration, image_meta=None, limits=None): return self._move_claim(context, instance, instance_type, nodename, migration, image_meta=image_meta, limits=limits) def _move_claim(self, context, instance, new_instance_type, nodename, migration, move_type=None, image_meta=None, limits=None): image_meta = image_meta or {} if migration: self._claim_existing_migration(migration, nodename) else: migration = self._create_migration(context, instance, new_instance_type, nodename, move_type) if self.disabled(nodename): # compute_driver doesn't support resource tracking, just return claims.NopClaim(migration=migration) overhead = self.driver.estimate_instance_overhead(new_instance_type) LOG.debug("Memory overhead for %(flavor)d MB instance; %(overhead)d " "MB", {'flavor': new_instance_type.memory_mb, 'overhead': overhead['memory_mb']}) LOG.debug("Disk overhead for %(flavor)d GB instance; %(overhead)d " "GB", {'flavor': instance.flavor.root_gb, 'overhead': overhead.get('disk_gb', 0)}) LOG.debug("CPU overhead for %(flavor)d vCPUs instance; %(overhead)d " "vCPU(s)", {'flavor': instance.flavor.vcpus, 'overhead': overhead.get('vcpus', 0)}) cn = self.compute_nodes[nodename] new_pci_requests = pci_request.get_pci_requests_from_flavor( new_instance_type) new_pci_requests.instance_uuid = instance.uuid # On resize merge the SR-IOV ports pci_requests with the new # instance flavor pci_requests. if instance.pci_requests: for request in instance.pci_requests.requests: if request.alias_name is None: new_pci_requests.requests.append(request) claim = claims.MoveClaim(context, instance, nodename, new_instance_type, image_meta, self, cn, new_pci_requests, overhead=overhead, limits=limits) claim.migration = migration claimed_pci_devices_objs = [] if self.pci_tracker: # NOTE(jaypipes): ComputeNode.pci_device_pools is set below # in _update_usage_from_instance(). claimed_pci_devices_objs = self.pci_tracker.claim_instance( context, new_pci_requests, claim.claimed_numa_topology) claimed_pci_devices = objects.PciDeviceList( objects=claimed_pci_devices_objs) # TODO(jaypipes): Move claimed_numa_topology out of the Claim's mig_context = objects.MigrationContext( context=context, instance_uuid=instance.uuid, migration_id=migration.id, old_numa_topology=instance.numa_topology, new_numa_topology=claim.claimed_numa_topology, old_pci_devices=instance.pci_devices, new_pci_devices=claimed_pci_devices, old_pci_requests=instance.pci_requests, new_pci_requests=new_pci_requests) instance.migration_context = mig_context instance.save() self._update_usage_from_migration(context, instance, migration, nodename) elevated = context.elevated() self._update(elevated, cn) return claim def _create_migration(self, context, instance, new_instance_type, nodename, move_type=None): migration = objects.Migration(context=context.elevated()) migration.dest_compute = self.host migration.dest_node = nodename migration.dest_host = self.driver.get_host_ip_addr() migration.old_instance_type_id = instance.flavor.id migration.new_instance_type_id = new_instance_type.id migration.status = 'pre-migrating' migration.instance_uuid = instance.uuid migration.source_compute = instance.host migration.source_node = instance.node if move_type: migration.migration_type = move_type else: migration.migration_type = migration_obj.determine_migration_type( migration) migration.create() return migration def _claim_existing_migration(self, migration, nodename): migration.dest_compute = self.host migration.dest_node = nodename migration.dest_host = self.driver.get_host_ip_addr() migration.status = 'pre-migrating' migration.save() def _set_instance_host_and_node(self, instance, nodename): instance.host = self.host instance.launched_on = self.host instance.node = nodename instance.save() def _unset_instance_host_and_node(self, instance): instance.host = None instance.node = None instance.save() @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def abort_instance_claim(self, context, instance, nodename): self._update_usage_from_instance(context, instance, nodename, is_removed=True) instance.clear_numa_topology() self._unset_instance_host_and_node(instance) self._update(context.elevated(), self.compute_nodes[nodename]) def _drop_pci_devices(self, instance, nodename, prefix): if self.pci_tracker: pci_devices = self._get_migration_context_resource( 'pci_devices', instance, prefix=prefix) if pci_devices: for pci_device in pci_devices: self.pci_tracker.free_device(pci_device, instance) dev_pools_obj = self.pci_tracker.stats.to_device_pools_obj() self.compute_nodes[nodename].pci_device_pools = dev_pools_obj @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def drop_move_claim(self, context, instance, nodename, instance_type=None, prefix='new_'): if instance['uuid'] in self.tracked_migrations: migration = self.tracked_migrations.pop(instance['uuid']) if not instance_type: instance_type = self._get_instance_type(instance, prefix, migration) elif instance['uuid'] in self.tracked_instances: self.tracked_instances.remove(instance['uuid']) if instance_type is not None: numa_topology = self._get_migration_context_resource( 'numa_topology', instance, prefix=prefix) usage = self._get_usage_dict( instance_type, instance, numa_topology=numa_topology) self._drop_pci_devices(instance, nodename, prefix) self._update_usage(usage, nodename, sign=-1) ctxt = context.elevated() self._update(ctxt, self.compute_nodes[nodename]) @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def update_usage(self, context, instance, nodename): if self.disabled(nodename): return uuid = instance['uuid'] # claim first: if uuid in self.tracked_instances: self._update_usage_from_instance(context, instance, nodename) self._update(context.elevated(), self.compute_nodes[nodename]) def disabled(self, nodename): return (nodename not in self.compute_nodes or not self.driver.node_is_available(nodename)) def _check_for_nodes_rebalance(self, context, resources, nodename): if not self.driver.rebalances_nodes: return False # Its possible ironic just did a node re-balance, so let's cn_candidates = objects.ComputeNodeList.get_by_hypervisor( context, nodename) if len(cn_candidates) == 1: cn = cn_candidates[0] LOG.info("ComputeNode %(name)s moving from %(old)s to %(new)s", {"name": nodename, "old": cn.host, "new": self.host}) cn.host = self.host self.compute_nodes[nodename] = cn self._copy_resources(cn, resources) self._setup_pci_tracker(context, cn, resources) self._update(context, cn) return True elif len(cn_candidates) > 1: LOG.error( "Found more than one ComputeNode for nodename %s. " "Please clean up the orphaned ComputeNode records in your DB.", nodename) return False def _init_compute_node(self, context, resources): nodename = resources['hypervisor_hostname'] if nodename in self.compute_nodes: cn = self.compute_nodes[nodename] self._copy_resources(cn, resources) self._setup_pci_tracker(context, cn, resources) return False cn = self._get_compute_node(context, nodename) if cn: self.compute_nodes[nodename] = cn self._copy_resources(cn, resources) self._setup_pci_tracker(context, cn, resources) return False if self._check_for_nodes_rebalance(context, resources, nodename): return False cn = objects.ComputeNode(context) cn.host = self.host self._copy_resources(cn, resources, initial=True) self.compute_nodes[nodename] = cn cn.create() LOG.info('Compute node record created for ' '%(host)s:%(node)s with uuid: %(uuid)s', {'host': self.host, 'node': nodename, 'uuid': cn.uuid}) self._setup_pci_tracker(context, cn, resources) return True def _setup_pci_tracker(self, context, compute_node, resources): if not self.pci_tracker: n_id = compute_node.id self.pci_tracker = pci_manager.PciDevTracker(context, node_id=n_id) if 'pci_passthrough_devices' in resources: dev_json = resources.pop('pci_passthrough_devices') self.pci_tracker.update_devices_from_hypervisor_resources( dev_json) dev_pools_obj = self.pci_tracker.stats.to_device_pools_obj() compute_node.pci_device_pools = dev_pools_obj def _copy_resources(self, compute_node, resources, initial=False): nodename = resources['hypervisor_hostname'] stats = self.stats[nodename] prev_failed_builds = stats.get('failed_builds', 0) stats.clear() stats['failed_builds'] = prev_failed_builds stats.digest_stats(resources.get('stats')) compute_node.stats = stats # ComputeNode.cpu_allocation_ratio of 16.0. We want to avoid # resetting the ComputeNode fields to None because that will make # the _resource_change method think something changed when really it # didn't. for res in ('cpu', 'disk', 'ram'): attr = '%s_allocation_ratio' % res if initial: conf_alloc_ratio = getattr(CONF, 'initial_%s' % attr) else: conf_alloc_ratio = getattr(self, attr) if conf_alloc_ratio not in (0.0, None): setattr(compute_node, attr, conf_alloc_ratio) compute_node.update_from_virt_driver(resources) def remove_node(self, nodename): self.stats.pop(nodename, None) self.compute_nodes.pop(nodename, None) self.old_resources.pop(nodename, None) def _get_host_metrics(self, context, nodename): metrics = objects.MonitorMetricList() metrics_info = {} for monitor in self.monitors: try: monitor.populate_metrics(metrics) except NotImplementedError: LOG.debug("The compute driver doesn't support host " "metrics for %(mon)s", {'mon': monitor}) except Exception as exc: LOG.warning("Cannot get the metrics from %(mon)s; " "error: %(exc)s", {'mon': monitor, 'exc': exc}) # TODO(jaypipes): Remove this when compute_node.metrics doesn't need metric_list = metrics.to_list() if len(metric_list): metrics_info['nodename'] = nodename metrics_info['metrics'] = metric_list metrics_info['host'] = self.host metrics_info['host_ip'] = CONF.my_ip notifier = rpc.get_notifier(service='compute', host=nodename) notifier.info(context, 'compute.metrics.update', metrics_info) compute_utils.notify_about_metrics_update( context, self.host, CONF.my_ip, nodename, metrics) return metric_list def update_available_resource(self, context, nodename, startup=False): LOG.debug("Auditing locally available compute resources for " "%(host)s (node: %(node)s)", {'node': nodename, 'host': self.host}) resources = self.driver.get_available_resource(nodename) resources['host_ip'] = CONF.my_ip if "cpu_info" not in resources or resources["cpu_info"] is None: resources["cpu_info"] = '' self._verify_resources(resources) self._report_hypervisor_resource_view(resources) self._update_available_resource(context, resources, startup=startup) def _pair_instances_to_migrations(self, migrations, instance_by_uuid): for migration in migrations: try: migration.instance = instance_by_uuid[migration.instance_uuid] except KeyError: # let the code either fail or lazy-load the instance later # which is what happened before we added this optimization. # NOTE(tdurakov) this situation is possible for resize/cold # migration when migration is finished but haven't yet LOG.debug('Migration for instance %(uuid)s refers to ' 'another host\'s instance!', {'uuid': migration.instance_uuid}) @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def _update_available_resource(self, context, resources, startup=False): # initialize the compute node object, creating it # if it does not already exist. is_new_compute_node = self._init_compute_node(context, resources) nodename = resources['hypervisor_hostname'] # if we could not init the compute node the tracker will be # disabled and we should quit now if self.disabled(nodename): return # Grab all instances assigned to this node: instances = objects.InstanceList.get_by_host_and_node( context, self.host, nodename, expected_attrs=['system_metadata', 'numa_topology', 'flavor', 'migration_context']) # Now calculate usage based on instance utilization: instance_by_uuid = self._update_usage_from_instances( context, instances, nodename) # Grab all in-progress migrations: migrations = objects.MigrationList.get_in_progress_by_host_and_node( context, self.host, nodename) self._pair_instances_to_migrations(migrations, instance_by_uuid) self._update_usage_from_migrations(context, migrations, nodename) # A new compute node means there won't be a resource provider yet since if not is_new_compute_node: self._remove_deleted_instances_allocations( context, self.compute_nodes[nodename], migrations, instance_by_uuid) orphans = self._find_orphaned_instances() self._update_usage_from_orphans(orphans, nodename) cn = self.compute_nodes[nodename] self.pci_tracker.clean_usage(instances, migrations, orphans) dev_pools_obj = self.pci_tracker.stats.to_device_pools_obj() cn.pci_device_pools = dev_pools_obj self._report_final_resource_view(nodename) metrics = self._get_host_metrics(context, nodename) cn.metrics = jsonutils.dumps(metrics) self._update(context, cn, startup=startup) LOG.debug('Compute_service record updated for %(host)s:%(node)s', {'host': self.host, 'node': nodename}) def _get_compute_node(self, context, nodename): try: return objects.ComputeNode.get_by_host_and_nodename( context, self.host, nodename) except exception.NotFound: LOG.warning("No compute node record for %(host)s:%(node)s", {'host': self.host, 'node': nodename}) def _report_hypervisor_resource_view(self, resources): nodename = resources['hypervisor_hostname'] free_ram_mb = resources['memory_mb'] - resources['memory_mb_used'] free_disk_gb = resources['local_gb'] - resources['local_gb_used'] vcpus = resources['vcpus'] if vcpus: free_vcpus = vcpus - resources['vcpus_used'] else: free_vcpus = 'unknown' pci_devices = resources.get('pci_passthrough_devices') LOG.debug("Hypervisor/Node resource view: " "name=%(node)s " "free_ram=%(free_ram)sMB " "free_disk=%(free_disk)sGB " "free_vcpus=%(free_vcpus)s " "pci_devices=%(pci_devices)s", {'node': nodename, 'free_ram': free_ram_mb, 'free_disk': free_disk_gb, 'free_vcpus': free_vcpus, 'pci_devices': pci_devices}) def _report_final_resource_view(self, nodename): cn = self.compute_nodes[nodename] vcpus = cn.vcpus if vcpus: tcpu = vcpus ucpu = cn.vcpus_used LOG.debug("Total usable vcpus: %(tcpu)s, " "total allocated vcpus: %(ucpu)s", {'tcpu': vcpus, 'ucpu': ucpu}) else: tcpu = 0 ucpu = 0 pci_stats = (list(cn.pci_device_pools) if cn.pci_device_pools else []) LOG.debug("Final resource view: " "name=%(node)s " "phys_ram=%(phys_ram)sMB " "used_ram=%(used_ram)sMB " "phys_disk=%(phys_disk)sGB " "used_disk=%(used_disk)sGB " "total_vcpus=%(total_vcpus)s " "used_vcpus=%(used_vcpus)s " "pci_stats=%(pci_stats)s", {'node': nodename, 'phys_ram': cn.memory_mb, 'used_ram': cn.memory_mb_used, 'phys_disk': cn.local_gb, 'used_disk': cn.local_gb_used, 'total_vcpus': tcpu, 'used_vcpus': ucpu, 'pci_stats': pci_stats}) def _resource_change(self, compute_node): nodename = compute_node.hypervisor_hostname old_compute = self.old_resources[nodename] if not obj_base.obj_equal_prims( compute_node, old_compute, ['updated_at']): self.old_resources[nodename] = copy.deepcopy(compute_node) return True return False def _get_traits(self, nodename, provider_tree): traits = provider_tree.data(nodename).traits # Now get the driver's capabilities and add any supported for trait, supported in self.driver.capabilities_as_traits().items(): if supported: traits.add(trait) elif trait in traits: traits.remove(trait) return list(traits) @retrying.retry(stop_max_attempt_number=4, retry_on_exception=lambda e: isinstance( e, exception.ResourceProviderUpdateConflict)) def _update_to_placement(self, context, compute_node, startup): # is no resource change for compute_node as above, we need proceed # to get inventory and use report client interfaces to update # inventory to placement. It's report client's responsibility to # ensure the update request to placement only happens when inventory # is changed. nodename = compute_node.hypervisor_hostname # Persist the stats to the Scheduler # First try update_provider_tree # Retrieve the provider tree associated with this compute node. If # it doesn't exist yet, this will create it with a (single, root) prov_tree = self.reportclient.get_provider_tree_and_ensure_root( context, compute_node.uuid, name=compute_node.hypervisor_hostname) allocs = None try: try: self.driver.update_provider_tree(prov_tree, nodename) except exception.ReshapeNeeded: if not startup: # it up; the compute manager will treat it specially. raise LOG.info("Performing resource provider inventory and " "allocation data migration during compute service " "startup or fast-forward upgrade.") allocs = self.reportclient.get_allocations_for_provider_tree( context, nodename) self.driver.update_provider_tree(prov_tree, nodename, allocations=allocs) # Inject driver capabilities traits into the provider # tree. We need to determine the traits that the virt # driver owns - so those that come from the tree itself # (via the virt driver) plus the compute capabilities # traits, and then merge those with the traits set # externally that the driver does not own - and remove any # set on the provider externally that the virt owns but # aren't in the current list of supported traits. For # trait at t1 and then at t2 it's not, so we need to # was set externally on the provider. traits = self._get_traits(nodename, provider_tree=prov_tree) prov_tree.update_traits(nodename, traits) except NotImplementedError: # update_provider_tree isn't implemented yet - try get_inventory try: inv_data = self.driver.get_inventory(nodename) _normalize_inventory_from_cn_obj(inv_data, compute_node) except NotImplementedError: # to remove this code branch inv_data = compute_utils.compute_node_to_inventory_dict( compute_node) prov_tree.update_inventory(nodename, inv_data) # Flush any changes. If we processed ReshapeNeeded above, allocs is not # None, and this will hit placement's POST /reshaper route. self.reportclient.update_from_provider_tree(context, prov_tree, allocations=allocs) def _update(self, context, compute_node, startup=False): if self._resource_change(compute_node): # NOTE(jianghuaw): Once we completely move to use get_inventory() # for all resource provider's inv data. We can remove this check. compute_node.save() self._update_to_placement(context, compute_node, startup) if self.pci_tracker: self.pci_tracker.save(context) def _update_usage(self, usage, nodename, sign=1): mem_usage = usage['memory_mb'] disk_usage = usage.get('root_gb', 0) vcpus_usage = usage.get('vcpus', 0) overhead = self.driver.estimate_instance_overhead(usage) mem_usage += overhead['memory_mb'] disk_usage += overhead.get('disk_gb', 0) vcpus_usage += overhead.get('vcpus', 0) cn = self.compute_nodes[nodename] cn.memory_mb_used += sign * mem_usage cn.local_gb_used += sign * disk_usage cn.local_gb_used += sign * usage.get('ephemeral_gb', 0) cn.local_gb_used += sign * usage.get('swap', 0) / 1024 cn.vcpus_used += sign * vcpus_usage cn.free_ram_mb = cn.memory_mb - cn.memory_mb_used cn.free_disk_gb = cn.local_gb - cn.local_gb_used stats = self.stats[nodename] cn.running_vms = stats.num_instances free = sign == -1 updated_numa_topology = hardware.get_host_numa_usage_from_instance( cn, usage, free) cn.numa_topology = updated_numa_topology def _get_migration_context_resource(self, resource, instance, prefix='new_'): migration_context = instance.migration_context resource = prefix + resource if migration_context and resource in migration_context: return getattr(migration_context, resource) return None def _update_usage_from_migration(self, context, instance, migration, nodename): if not _is_trackable_migration(migration): return uuid = migration.instance_uuid LOG.info("Updating resource usage from migration %s", migration.uuid, instance_uuid=uuid) incoming = (migration.dest_compute == self.host and migration.dest_node == nodename) outbound = (migration.source_compute == self.host and migration.source_node == nodename) same_node = (incoming and outbound) tracked = uuid in self.tracked_instances itype = None numa_topology = None sign = 0 if same_node: if (instance['instance_type_id'] == migration.old_instance_type_id): itype = self._get_instance_type(instance, 'new_', migration) numa_topology = self._get_migration_context_resource( 'numa_topology', instance) sign = 1 else: itype = self._get_instance_type(instance, 'old_', migration) numa_topology = self._get_migration_context_resource( 'numa_topology', instance, prefix='old_') elif incoming and not tracked: itype = self._get_instance_type(instance, 'new_', migration) numa_topology = self._get_migration_context_resource( 'numa_topology', instance) sign = 1 LOG.debug('Starting to track incoming migration %s with flavor %s', migration.uuid, itype.flavorid, instance=instance) elif outbound and not tracked: itype = self._get_instance_type(instance, 'old_', migration) numa_topology = self._get_migration_context_resource( 'numa_topology', instance, prefix='old_') LOG.debug('Starting to track outgoing migration %s with flavor %s', migration.uuid, itype.flavorid, instance=instance) if itype: cn = self.compute_nodes[nodename] usage = self._get_usage_dict( itype, instance, numa_topology=numa_topology) if self.pci_tracker and sign: self.pci_tracker.update_pci_for_instance( context, instance, sign=sign) self._update_usage(usage, nodename) if self.pci_tracker: obj = self.pci_tracker.stats.to_device_pools_obj() cn.pci_device_pools = obj else: obj = objects.PciDevicePoolList() cn.pci_device_pools = obj self.tracked_migrations[uuid] = migration def _update_usage_from_migrations(self, context, migrations, nodename): filtered = {} instances = {} self.tracked_migrations.clear() for migration in migrations: uuid = migration.instance_uuid try: if uuid not in instances: instances[uuid] = migration.instance except exception.InstanceNotFound as e: LOG.debug('Migration instance not found: %s', e) continue if not _instance_in_resize_state(instances[uuid]): LOG.warning("Instance not resizing, skipping migration.", instance_uuid=uuid) continue # filter to most recently updated migration for each instance: other_migration = filtered.get(uuid, None) # NOTE(claudiub): In Python 3, you cannot compare NoneTypes. if other_migration: om = other_migration other_time = om.updated_at or om.created_at migration_time = migration.updated_at or migration.created_at if migration_time > other_time: filtered[uuid] = migration else: filtered[uuid] = migration for migration in filtered.values(): instance = instances[migration.instance_uuid] # Skip migration (and mark it as error) if it doesn't match the if (instance.migration_context is not None and instance.migration_context.migration_id != migration.id): LOG.info("Current instance migration %(im)s doesn't match " "migration %(m)s, marking migration as error. " "This can occur if a previous migration for this " "instance did not complete.", {'im': instance.migration_context.migration_id, 'm': migration.id}) migration.status = "error" migration.save() continue try: self._update_usage_from_migration(context, instance, migration, nodename) except exception.FlavorNotFound: LOG.warning("Flavor could not be found, skipping migration.", instance_uuid=instance.uuid) continue def _update_usage_from_instance(self, context, instance, nodename, is_removed=False): uuid = instance['uuid'] is_new_instance = uuid not in self.tracked_instances # NOTE(sfinucan): Both brand new instances as well as instances that # are being unshelved will have is_new_instance == True is_removed_instance = not is_new_instance and (is_removed or instance['vm_state'] in vm_states.ALLOW_RESOURCE_REMOVAL) if is_new_instance: self.tracked_instances.add(uuid) sign = 1 if is_removed_instance: self.tracked_instances.remove(uuid) sign = -1 cn = self.compute_nodes[nodename] stats = self.stats[nodename] stats.update_stats_for_instance(instance, is_removed_instance) cn.stats = stats # if it's a new or deleted instance: if is_new_instance or is_removed_instance: if self.pci_tracker: self.pci_tracker.update_pci_for_instance(context, instance, sign=sign) self._update_usage(self._get_usage_dict(instance, instance), nodename, sign=sign) if is_removed_instance and uuid in self.is_bfv: del self.is_bfv[uuid] cn.current_workload = stats.calculate_workload() if self.pci_tracker: obj = self.pci_tracker.stats.to_device_pools_obj() cn.pci_device_pools = obj else: cn.pci_device_pools = objects.PciDevicePoolList() def _update_usage_from_instances(self, context, instances, nodename): self.tracked_instances.clear() cn = self.compute_nodes[nodename] cn.local_gb_used = CONF.reserved_host_disk_mb / 1024 cn.memory_mb_used = CONF.reserved_host_memory_mb cn.vcpus_used = CONF.reserved_host_cpus cn.free_ram_mb = (cn.memory_mb - cn.memory_mb_used) cn.free_disk_gb = (cn.local_gb - cn.local_gb_used) cn.current_workload = 0 cn.running_vms = 0 instance_by_uuid = {} for instance in instances: if instance.vm_state not in vm_states.ALLOW_RESOURCE_REMOVAL: self._update_usage_from_instance(context, instance, nodename) instance_by_uuid[instance.uuid] = instance return instance_by_uuid def _remove_deleted_instances_allocations(self, context, cn, migrations, instance_by_uuid): migration_uuids = [migration.uuid for migration in migrations if 'uuid' in migration] # all the corner cases in move, local delete, unshelve and rebuild # operations for when allocations should be deleted when things didn't try: pai = self.reportclient.get_allocations_for_resource_provider( context, cn.uuid) except (exception.ResourceProviderAllocationRetrievalFailed, ks_exc.ClientException) as e: LOG.error("Skipping removal of allocations for deleted instances: " "%s", e) return allocations = pai.allocations if not allocations: return read_deleted_context = context.elevated(read_deleted='yes') for consumer_uuid, alloc in allocations.items(): if consumer_uuid in self.tracked_instances: LOG.debug("Instance %s actively managed on this compute host " "and has allocations in placement: %s.", consumer_uuid, alloc) continue if consumer_uuid in migration_uuids: LOG.debug("Migration %s is active on this compute host " "and has allocations in placement: %s.", consumer_uuid, alloc) continue instance_uuid = consumer_uuid instance = instance_by_uuid.get(instance_uuid) if not instance: try: instance = objects.Instance.get_by_uuid( read_deleted_context, consumer_uuid, expected_attrs=[]) except exception.InstanceNotFound: # scheduler _just_ created an allocation for it and we're LOG.info("Instance %(uuid)s has allocations against this " "compute host but is not found in the database.", {'uuid': instance_uuid}, exc_info=False) continue if instance.deleted: LOG.debug("Instance %s has been deleted (perhaps locally). " "Deleting allocations that remained for this " "instance against this compute host: %s.", instance_uuid, alloc) self.reportclient.delete_allocation_for_instance(context, instance_uuid) continue if not instance.host: LOG.debug("Instance %s has been scheduled to this compute " "host, the scheduler has made an allocation " "against this compute node but the instance has " "yet to start. Skipping heal of allocation: %s.", instance_uuid, alloc) continue if (instance.host == cn.host and instance.node == cn.hypervisor_hostname): LOG.warning("Instance %s is not being actively managed by " "this compute host but has allocations " "referencing this compute host: %s. Skipping " "heal of allocation because we do not know " "what to do.", instance_uuid, alloc) continue if instance.host != cn.host: # for resize to confirm/revert), however if the destination # host is an Ocata compute host, it will delete the allocation # that contains this source compute host information anyway and # recreate an allocation that only refers to itself. So we # don't need to do anything in that case. Just log the # change the allocation. LOG.warning("Instance %s has been moved to another host " "%s(%s). There are allocations remaining against " "the source host that might need to be removed: " "%s.", instance_uuid, instance.host, instance.node, alloc) def delete_allocation_for_evacuated_instance(self, context, instance, node, node_type='source'): # Clean up the instance allocation from this node in placement cn_uuid = self.compute_nodes[node].uuid if not self.reportclient.remove_provider_tree_from_instance_allocation( context, instance.uuid, cn_uuid): LOG.error("Failed to clean allocation of evacuated " "instance on the %s node %s", node_type, cn_uuid, instance=instance) def _find_orphaned_instances(self): uuids1 = frozenset(self.tracked_instances) uuids2 = frozenset(self.tracked_migrations.keys()) uuids = uuids1 | uuids2 usage = self.driver.get_per_instance_usage() vuuids = frozenset(usage.keys()) orphan_uuids = vuuids - uuids orphans = [usage[uuid] for uuid in orphan_uuids] return orphans def _update_usage_from_orphans(self, orphans, nodename): for orphan in orphans: memory_mb = orphan['memory_mb'] LOG.warning("Detected running orphan instance: %(uuid)s " "(consuming %(memory_mb)s MB memory)", {'uuid': orphan['uuid'], 'memory_mb': memory_mb}) # just record memory usage for the orphan usage = {'memory_mb': memory_mb} self._update_usage(usage, nodename) def delete_allocation_for_shelve_offloaded_instance(self, context, instance): self.reportclient.delete_allocation_for_instance(context, instance.uuid) def _verify_resources(self, resources): resource_keys = ["vcpus", "memory_mb", "local_gb", "cpu_info", "vcpus_used", "memory_mb_used", "local_gb_used", "numa_topology"] missing_keys = [k for k in resource_keys if k not in resources] if missing_keys: reason = _("Missing keys: %s") % missing_keys raise exception.InvalidInput(reason=reason) def _get_instance_type(self, instance, prefix, migration): stashed_flavors = migration.migration_type in ('resize',) if stashed_flavors: return getattr(instance, '%sflavor' % prefix) else: # NOTE(ndipanov): Certain migration types (all but resize) # do not change flavors so there is no need to stash # them. In that case - just get the instance flavor. return instance.flavor def _get_usage_dict(self, object_or_dict, instance, **updates): def _is_bfv(): # Check to see if we have the is_bfv value cached. if instance.uuid in self.is_bfv: is_bfv = self.is_bfv[instance.uuid] else: is_bfv = compute_utils.is_volume_backed_instance( instance._context, instance) self.is_bfv[instance.uuid] = is_bfv return is_bfv usage = {} if isinstance(object_or_dict, objects.Instance): is_bfv = _is_bfv() usage = {'memory_mb': object_or_dict.flavor.memory_mb, 'swap': object_or_dict.flavor.swap, 'vcpus': object_or_dict.flavor.vcpus, 'root_gb': (0 if is_bfv else object_or_dict.flavor.root_gb), 'ephemeral_gb': object_or_dict.flavor.ephemeral_gb, 'numa_topology': object_or_dict.numa_topology} elif isinstance(object_or_dict, objects.Flavor): usage = obj_base.obj_to_primitive(object_or_dict) if _is_bfv(): usage['root_gb'] = 0 else: usage.update(object_or_dict) for key in ('numa_topology',): if key in updates: usage[key] = updates[key] return usage def build_failed(self, nodename): self.stats[nodename].build_failed() def build_succeeded(self, nodename): self.stats[nodename].build_succeeded() @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def claim_pci_devices(self, context, pci_requests): result = self.pci_tracker.claim_instance( context, pci_requests, None) self.pci_tracker.save(context) return result @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def allocate_pci_devices_for_instance(self, context, instance): self.pci_tracker.allocate_instance(instance) self.pci_tracker.save(context) @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def free_pci_device_allocations_for_instance(self, context, instance): self.pci_tracker.free_instance_allocations(context, instance) self.pci_tracker.save(context) @utils.synchronized(COMPUTE_RESOURCE_SEMAPHORE) def free_pci_device_claims_for_instance(self, context, instance): self.pci_tracker.free_instance_claims(context, instance) self.pci_tracker.save(context)
true
true
f7258d9ad8ec1ffdd9a1d4a476dabdc315bbf560
5,448
py
Python
synthesizer/models/custom_decoder.py
Khizar-Ali/Lip2Wav
07f056b3468ca660823830680bf25bdd42034f9e
[ "MIT" ]
541
2020-05-14T05:56:31.000Z
2022-03-30T03:34:55.000Z
synthesizer/models/custom_decoder.py
Khizar-Ali/Lip2Wav
07f056b3468ca660823830680bf25bdd42034f9e
[ "MIT" ]
36
2020-05-14T06:00:31.000Z
2022-03-10T06:13:44.000Z
synthesizer/models/custom_decoder.py
Khizar-Ali/Lip2Wav
07f056b3468ca660823830680bf25bdd42034f9e
[ "MIT" ]
123
2020-05-19T02:43:47.000Z
2022-03-26T11:28:13.000Z
from __future__ import absolute_import, division, print_function import collections import tensorflow as tf from synthesizer.models.helpers import TacoTestHelper, TacoTrainingHelper from tensorflow.contrib.seq2seq.python.ops import decoder from tensorflow.contrib.seq2seq.python.ops import helper as helper_py from tensorflow.python.framework import ops, tensor_shape from tensorflow.python.layers import base as layers_base from tensorflow.python.ops import rnn_cell_impl from tensorflow.python.util import nest class CustomDecoderOutput( #collections.namedtuple("CustomDecoderOutput", ("rnn_output", "token_output", "sample_id"))): collections.namedtuple("CustomDecoderOutput", ("rnn_output", "sample_id"))): pass class CustomDecoder(decoder.Decoder): """Custom sampling decoder. Allows for stop token prediction at inference time and returns equivalent loss in training time. Note: Only use this decoder with Tacotron 2 as it only accepts tacotron custom helpers """ def __init__(self, cell, helper, initial_state, output_layer=None): """Initialize CustomDecoder. Args: cell: An `RNNCell` instance. helper: A `Helper` instance. initial_state: A (possibly nested tuple of...) tensors and TensorArrays. The initial state of the RNNCell. output_layer: (Optional) An instance of `tf.layers.Layer`, i.e., `tf.layers.Dense`. Optional layer to apply to the RNN output prior to storing the result or sampling. Raises: TypeError: if `cell`, `helper` or `output_layer` have an incorrect type. """ rnn_cell_impl.assert_like_rnncell(type(cell), cell) if not isinstance(helper, helper_py.Helper): raise TypeError("helper must be a Helper, received: %s" % type(helper)) if (output_layer is not None and not isinstance(output_layer, layers_base.Layer)): raise TypeError( "output_layer must be a Layer, received: %s" % type(output_layer)) self._cell = cell self._helper = helper self._initial_state = initial_state self._output_layer = output_layer @property def batch_size(self): return self._helper.batch_size def _rnn_output_size(self): size = self._cell.output_size if self._output_layer is None: return size else: # To use layer"s compute_output_shape, we need to convert the # RNNCell"s output_size entries into shapes with an unknown # batch size. We then pass this through the layer"s # compute_output_shape and read off all but the first (batch) # dimensions to get the output size of the rnn with the layer # applied to the top. output_shape_with_unknown_batch = nest.map_structure( lambda s: tensor_shape.TensorShape([None]).concatenate(s), size) layer_output_shape = self._output_layer._compute_output_shape( # pylint: disable=protected-access output_shape_with_unknown_batch) return nest.map_structure(lambda s: s[1:], layer_output_shape) @property def output_size(self): # Return the cell output and the id #return CustomDecoderOutput( # rnn_output=self._rnn_output_size(), # token_output=self._helper.token_output_size, # sample_id=self._helper.sample_ids_shape) return CustomDecoderOutput( rnn_output=self._rnn_output_size(), sample_id=self._helper.sample_ids_shape) @property def output_dtype(self): # Assume the dtype of the cell is the output_size structure # containing the input_state"s first component's dtype. # Return that structure and the sample_ids_dtype from the helper. dtype = nest.flatten(self._initial_state)[0].dtype #return CustomDecoderOutput( # nest.map_structure(lambda _: dtype, self._rnn_output_size()), # tf.float32, # self._helper.sample_ids_dtype) return CustomDecoderOutput( nest.map_structure(lambda _: dtype, self._rnn_output_size()), self._helper.sample_ids_dtype) def initialize(self, name=None): """Initialize the decoder. Args: name: Name scope for any created operations. Returns: `(finished, first_inputs, initial_state)`. """ return self._helper.initialize() + (self._initial_state,) def step(self, time, inputs, state, name=None): """Perform a custom decoding step. Enables for dyanmic <stop_token> prediction Args: time: scalar `int32` tensor. inputs: A (structure of) input tensors. state: A (structure of) state tensors and TensorArrays. name: Name scope for any created operations. Returns: `(outputs, next_state, next_inputs, finished)`. """ with ops.name_scope(name, "CustomDecoderStep", (time, inputs, state)): #Call outputprojection wrapper cell #(cell_outputs, stop_token), cell_state = self._cell(inputs, state) (cell_outputs), cell_state = self._cell(inputs, state) #apply output_layer (if existant) if self._output_layer is not None: cell_outputs = self._output_layer(cell_outputs) sample_ids = self._helper.sample( time=time, outputs=cell_outputs, state=cell_state) #(finished, next_inputs, next_state) = self._helper.next_inputs( # time=time, # outputs=cell_outputs, # state=cell_state, # sample_ids=sample_ids, # stop_token_prediction=stop_token) (finished, next_inputs, next_state) = self._helper.next_inputs( time=time, outputs=cell_outputs, state=cell_state, sample_ids=sample_ids) #outputs = CustomDecoderOutput(cell_outputs, stop_token, sample_ids) outputs = CustomDecoderOutput(cell_outputs, sample_ids) return (outputs, next_state, next_inputs, finished)
36.810811
101
0.752019
from __future__ import absolute_import, division, print_function import collections import tensorflow as tf from synthesizer.models.helpers import TacoTestHelper, TacoTrainingHelper from tensorflow.contrib.seq2seq.python.ops import decoder from tensorflow.contrib.seq2seq.python.ops import helper as helper_py from tensorflow.python.framework import ops, tensor_shape from tensorflow.python.layers import base as layers_base from tensorflow.python.ops import rnn_cell_impl from tensorflow.python.util import nest class CustomDecoderOutput( collections.namedtuple("CustomDecoderOutput", ("rnn_output", "sample_id"))): pass class CustomDecoder(decoder.Decoder): def __init__(self, cell, helper, initial_state, output_layer=None): rnn_cell_impl.assert_like_rnncell(type(cell), cell) if not isinstance(helper, helper_py.Helper): raise TypeError("helper must be a Helper, received: %s" % type(helper)) if (output_layer is not None and not isinstance(output_layer, layers_base.Layer)): raise TypeError( "output_layer must be a Layer, received: %s" % type(output_layer)) self._cell = cell self._helper = helper self._initial_state = initial_state self._output_layer = output_layer @property def batch_size(self): return self._helper.batch_size def _rnn_output_size(self): size = self._cell.output_size if self._output_layer is None: return size else: # RNNCell"s output_size entries into shapes with an unknown # compute_output_shape and read off all but the first (batch) # dimensions to get the output size of the rnn with the layer # applied to the top. output_shape_with_unknown_batch = nest.map_structure( lambda s: tensor_shape.TensorShape([None]).concatenate(s), size) layer_output_shape = self._output_layer._compute_output_shape( # pylint: disable=protected-access output_shape_with_unknown_batch) return nest.map_structure(lambda s: s[1:], layer_output_shape) @property def output_size(self): # Return the cell output and the id #return CustomDecoderOutput( # rnn_output=self._rnn_output_size(), # token_output=self._helper.token_output_size, # sample_id=self._helper.sample_ids_shape) return CustomDecoderOutput( rnn_output=self._rnn_output_size(), sample_id=self._helper.sample_ids_shape) @property def output_dtype(self): # Assume the dtype of the cell is the output_size structure # containing the input_state"s first component's dtype. # Return that structure and the sample_ids_dtype from the helper. dtype = nest.flatten(self._initial_state)[0].dtype #return CustomDecoderOutput( # nest.map_structure(lambda _: dtype, self._rnn_output_size()), # tf.float32, # self._helper.sample_ids_dtype) return CustomDecoderOutput( nest.map_structure(lambda _: dtype, self._rnn_output_size()), self._helper.sample_ids_dtype) def initialize(self, name=None): return self._helper.initialize() + (self._initial_state,) def step(self, time, inputs, state, name=None): with ops.name_scope(name, "CustomDecoderStep", (time, inputs, state)): #Call outputprojection wrapper cell #(cell_outputs, stop_token), cell_state = self._cell(inputs, state) (cell_outputs), cell_state = self._cell(inputs, state) #apply output_layer (if existant) if self._output_layer is not None: cell_outputs = self._output_layer(cell_outputs) sample_ids = self._helper.sample( time=time, outputs=cell_outputs, state=cell_state) #(finished, next_inputs, next_state) = self._helper.next_inputs( # time=time, # outputs=cell_outputs, # state=cell_state, # sample_ids=sample_ids, # stop_token_prediction=stop_token) (finished, next_inputs, next_state) = self._helper.next_inputs( time=time, outputs=cell_outputs, state=cell_state, sample_ids=sample_ids) #outputs = CustomDecoderOutput(cell_outputs, stop_token, sample_ids) outputs = CustomDecoderOutput(cell_outputs, sample_ids) return (outputs, next_state, next_inputs, finished)
true
true
f7258fa1fd9ffacbfd6a1a0cc0f2cd988adbdb32
3,381
py
Python
Server_Code/database.py
PUT-PTM/2019_SmartAttendance
cab58f3f355c07d3dfd4c73c8adb4c7bbf6d676c
[ "MIT" ]
1
2019-03-13T16:00:32.000Z
2019-03-13T16:00:32.000Z
Server_Code/database.py
PUT-PTM/2019_SmartAttendance
cab58f3f355c07d3dfd4c73c8adb4c7bbf6d676c
[ "MIT" ]
null
null
null
Server_Code/database.py
PUT-PTM/2019_SmartAttendance
cab58f3f355c07d3dfd4c73c8adb4c7bbf6d676c
[ "MIT" ]
1
2021-07-10T08:27:21.000Z
2021-07-10T08:27:21.000Z
from datetime import datetime import json from pathlib import Path import pymssql config_json: dict = json.loads(Path('config.json').read_text()) # Connecting to database def connect(): global config_json # Connect to Microsoft SQL server conn = pymssql.connect( server=config_json['server'], user=config_json['user'], password=config_json['password'], database=config_json['database'] ) return conn def student_exists(sid: int) -> bool: conn = connect() cursor = conn.cursor() # Correct request cursor.execute('select COUNT(1) from StudentInfo where SID=' + str(sid) + ';') result = cursor.fetchone() conn.close() return str(result[0]) == '1' def student_info_get() -> dict: conn = connect() cursor = conn.cursor() # Get all students from database cursor.execute('select * from StudentInfo order by SID;') # Convert table into json data: dict = json.loads('{"elements":[]}') row = cursor.fetchone() while row: # Creating json table with data data['elements'].append( # Creating json table with data json.loads( '{"SID":' + str(row[0]) + ',' + '"fName": "' + row[1] + '",' + '"lName": "' + row[2] + '"}' ) ) row = cursor.fetchone() # While end conn.close() return data def student_info_insert(info: dict) -> None: # Get values from JSON sid = str(info['SID']) f_name = '\'' + info['fName'] + '\'' l_name = '\'' + info['lName'] + '\'' # Add entry to database sql_req = 'insert into StudentInfo values (' + sid + ',' + f_name + ',' + l_name + ');' conn = connect() cursor = conn.cursor() cursor.execute(sql_req) conn.commit() conn.close() print('Finished sql req!') def student_info_delete(sid: int) -> None: conn = connect() cursor = conn.cursor() cursor.execute('delete from StudentInfo where SID=' + str(sid) + ';') conn.commit() conn.close() def presence_get() -> dict: conn = connect() cursor = conn.cursor() cursor.execute('select * from Presence order by Date;') # Convert table into json data = json.loads('{"elements":[]}') row = cursor.fetchone() while row: # Creating json table with data data['elements'].append( # Creating json table with data json.loads( '{"SID":' + str(row[0]) + ',' + '"Date": "' + row[1].strftime('%Y-%m-%d %H:%M:%S') + '",' + '"CID": "' + str(row[2]) + '",' + '"Room": "' + row[3] + '"}' ) ) row = cursor.fetchone() # While end conn.close() return data def presence_insert(info: dict): # Get values from JSONs sid = str(info.get('SID')) date = '\'' + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + '\'' cid = info.get('CID') room = '\'' + info.get('Room') + '\'' # Request building sql_req = 'insert into Presence values (' + sid + ',' + date if cid is not None: sql_req += ',' + str(cid) if len(room) > 2: sql_req += ',' + room sql_req += ');' conn = connect() cursor = conn.cursor() cursor.execute(sql_req) conn.commit() conn.close() print('Finished sql req!')
25.613636
91
0.540964
from datetime import datetime import json from pathlib import Path import pymssql config_json: dict = json.loads(Path('config.json').read_text()) def connect(): global config_json conn = pymssql.connect( server=config_json['server'], user=config_json['user'], password=config_json['password'], database=config_json['database'] ) return conn def student_exists(sid: int) -> bool: conn = connect() cursor = conn.cursor() cursor.execute('select COUNT(1) from StudentInfo where SID=' + str(sid) + ';') result = cursor.fetchone() conn.close() return str(result[0]) == '1' def student_info_get() -> dict: conn = connect() cursor = conn.cursor() cursor.execute('select * from StudentInfo order by SID;') data: dict = json.loads('{"elements":[]}') row = cursor.fetchone() while row: data['elements'].append( json.loads( '{"SID":' + str(row[0]) + ',' + '"fName": "' + row[1] + '",' + '"lName": "' + row[2] + '"}' ) ) row = cursor.fetchone() conn.close() return data def student_info_insert(info: dict) -> None: sid = str(info['SID']) f_name = '\'' + info['fName'] + '\'' l_name = '\'' + info['lName'] + '\'' sql_req = 'insert into StudentInfo values (' + sid + ',' + f_name + ',' + l_name + ');' conn = connect() cursor = conn.cursor() cursor.execute(sql_req) conn.commit() conn.close() print('Finished sql req!') def student_info_delete(sid: int) -> None: conn = connect() cursor = conn.cursor() cursor.execute('delete from StudentInfo where SID=' + str(sid) + ';') conn.commit() conn.close() def presence_get() -> dict: conn = connect() cursor = conn.cursor() cursor.execute('select * from Presence order by Date;') data = json.loads('{"elements":[]}') row = cursor.fetchone() while row: data['elements'].append( json.loads( '{"SID":' + str(row[0]) + ',' + '"Date": "' + row[1].strftime('%Y-%m-%d %H:%M:%S') + '",' + '"CID": "' + str(row[2]) + '",' + '"Room": "' + row[3] + '"}' ) ) row = cursor.fetchone() conn.close() return data def presence_insert(info: dict): sid = str(info.get('SID')) date = '\'' + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + '\'' cid = info.get('CID') room = '\'' + info.get('Room') + '\'' sql_req = 'insert into Presence values (' + sid + ',' + date if cid is not None: sql_req += ',' + str(cid) if len(room) > 2: sql_req += ',' + room sql_req += ');' conn = connect() cursor = conn.cursor() cursor.execute(sql_req) conn.commit() conn.close() print('Finished sql req!')
true
true
f725901ae4990c796dfc0c6fd9dcacb4bed91c78
3,385
py
Python
examples/basic_operations/update_ad_group.py
JakobSteixner/google-ads-python
df2b802cc7e78295a4ece21cc7ef3787cd35dab0
[ "Apache-2.0" ]
null
null
null
examples/basic_operations/update_ad_group.py
JakobSteixner/google-ads-python
df2b802cc7e78295a4ece21cc7ef3787cd35dab0
[ "Apache-2.0" ]
null
null
null
examples/basic_operations/update_ad_group.py
JakobSteixner/google-ads-python
df2b802cc7e78295a4ece21cc7ef3787cd35dab0
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example updates an ad group. To get ad groups, run get_ad_groups.py. """ import argparse import sys from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException from google.api_core import protobuf_helpers # [START update_ad_group] def main(client, customer_id, ad_group_id, cpc_bid_micro_amount): ad_group_service = client.get_service("AdGroupService") # Create ad group operation. ad_group_operation = client.get_type("AdGroupOperation") ad_group = ad_group_operation.update ad_group.resource_name = ad_group_service.ad_group_path( customer_id, ad_group_id ) ad_group.status = client.enums.AdGroupStatusEnum.PAUSED ad_group.cpc_bid_micros = cpc_bid_micro_amount client.copy_from( ad_group_operation.update_mask, protobuf_helpers.field_mask(None, ad_group._pb), ) # Update the ad group. ad_group_response = ad_group_service.mutate_ad_groups( customer_id=customer_id, operations=[ad_group_operation] ) print(f"Updated ad group {ad_group_response.results[0].resource_name}.") # [END update_ad_group] if __name__ == "__main__": # GoogleAdsClient will read the google-ads.yaml configuration file in the # home directory if none is specified. googleads_client = GoogleAdsClient.load_from_storage(version="v10") parser = argparse.ArgumentParser( description=( "Updates an ad group for specified customer and campaign " "id with the given bid micro amount." ) ) # The following argument(s) should be provided to run the example. parser.add_argument( "-c", "--customer_id", type=str, required=True, help="The Google Ads customer ID.", ) parser.add_argument( "-a", "--ad_group_id", type=str, required=True, help="The ad group ID." ) parser.add_argument( "-b", "--cpc_bid_micro_amount", type=int, required=True, help="The cpc bid micro amount.", ) args = parser.parse_args() try: main( googleads_client, args.customer_id, args.ad_group_id, args.cpc_bid_micro_amount, ) except GoogleAdsException as ex: print( f'Request with ID "{ex.request_id}" failed with status ' f'"{ex.error.code().name}" and includes the following errors:' ) for error in ex.failure.errors: print(f'\tError with message "{error.message}".') if error.location: for field_path_element in error.location.field_path_elements: print(f"\t\tOn field: {field_path_element.field_name}") sys.exit(1)
32.548077
79
0.676809
import argparse import sys from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException from google.api_core import protobuf_helpers def main(client, customer_id, ad_group_id, cpc_bid_micro_amount): ad_group_service = client.get_service("AdGroupService") ad_group_operation = client.get_type("AdGroupOperation") ad_group = ad_group_operation.update ad_group.resource_name = ad_group_service.ad_group_path( customer_id, ad_group_id ) ad_group.status = client.enums.AdGroupStatusEnum.PAUSED ad_group.cpc_bid_micros = cpc_bid_micro_amount client.copy_from( ad_group_operation.update_mask, protobuf_helpers.field_mask(None, ad_group._pb), ) ad_group_response = ad_group_service.mutate_ad_groups( customer_id=customer_id, operations=[ad_group_operation] ) print(f"Updated ad group {ad_group_response.results[0].resource_name}.") if __name__ == "__main__": googleads_client = GoogleAdsClient.load_from_storage(version="v10") parser = argparse.ArgumentParser( description=( "Updates an ad group for specified customer and campaign " "id with the given bid micro amount." ) ) parser.add_argument( "-c", "--customer_id", type=str, required=True, help="The Google Ads customer ID.", ) parser.add_argument( "-a", "--ad_group_id", type=str, required=True, help="The ad group ID." ) parser.add_argument( "-b", "--cpc_bid_micro_amount", type=int, required=True, help="The cpc bid micro amount.", ) args = parser.parse_args() try: main( googleads_client, args.customer_id, args.ad_group_id, args.cpc_bid_micro_amount, ) except GoogleAdsException as ex: print( f'Request with ID "{ex.request_id}" failed with status ' f'"{ex.error.code().name}" and includes the following errors:' ) for error in ex.failure.errors: print(f'\tError with message "{error.message}".') if error.location: for field_path_element in error.location.field_path_elements: print(f"\t\tOn field: {field_path_element.field_name}") sys.exit(1)
true
true
f72590d6e6483328b9562e5788fc07feb3ad4594
11,628
py
Python
tests/suite.py
dannielarriola/uai-coursebuilder
fbd440a8bfe1a928ac52985aea2949d5e91ad203
[ "Apache-2.0" ]
null
null
null
tests/suite.py
dannielarriola/uai-coursebuilder
fbd440a8bfe1a928ac52985aea2949d5e91ad203
[ "Apache-2.0" ]
27
2016-08-31T19:04:46.000Z
2016-09-29T00:22:32.000Z
tests/suite.py
dannielarriola/uai-coursebuilder
fbd440a8bfe1a928ac52985aea2949d5e91ad203
[ "Apache-2.0" ]
null
null
null
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Course Builder test suite. This script runs all functional and units test in the Course Builder project. Here is how to use the script: - if you don't have pip, install it using 'sudo apt-get install python-pip' - install WebTest using: 'sudo pip install WebTest' - make sure your PYTHONPATH contains: google_appengine, google_appengine/lib/jinja2-2.6, google_appengine/lib/webapp2-2.5.1 and the 'coursebuilder' directory itself - invoke this test suite from the command line: # Run test method baz in unittest.TestCase Bar found in tests/foo.py. python tests/suite.py --test_class_name tests.foo.Bar.baz - review the output to make sure there are no errors or warnings Good luck! """ __author__ = 'Sean Lip' import argparse import cStringIO import logging import os import shutil import sys import unittest import task_queue import webtest import appengine_config from tools.etl import etl from google.appengine.api.search import simple_search_stub from google.appengine.datastore import datastore_stub_util from google.appengine.ext import testbed _PARSER = argparse.ArgumentParser() _PARSER.add_argument( '--test_class_name', help='optional dotted module name of the test(s) to run', type=str) # Direct key access so we'll throw if os.environ is misconfigured. TEST_DATA_BASE = os.path.join( os.environ['COURSEBUILDER_RESOURCES'], 'test-data') def empty_environ(): os.environ['AUTH_DOMAIN'] = 'example.com' os.environ['SERVER_NAME'] = 'localhost' os.environ['HTTP_HOST'] = 'localhost' os.environ['SERVER_PORT'] = '8080' os.environ['USER_EMAIL'] = '' os.environ['USER_ID'] = '' os.environ['DEFAULT_VERSION_HOSTNAME'] = ( os.environ['HTTP_HOST'] + ':' + os.environ['SERVER_PORT']) def iterate_tests(test_suite_or_case): """Iterate through all of the test cases in 'test_suite_or_case'.""" try: suite = iter(test_suite_or_case) except TypeError: yield test_suite_or_case else: for test in suite: for subtest in iterate_tests(test): yield subtest class TestBase(unittest.TestCase): """Base class for all Course Builder tests.""" INTEGRATION_SERVER_BASE_URL = 'http://localhost:8081' ADMIN_SERVER_BASE_URL = 'http://localhost:8000' STOP_AFTER_FIRST_FAILURE = False HAS_PENDING_FAILURE = False # Log level for all tests in this test case. Override if you need to test # against different logging levels. Be very careful when setting this to # logging.DEBUG: downstream code is sometimes very chatty at logging.DEBUG, # and can generate enough logging data that tests run out of memory. LOG_LEVEL = logging.ERROR def setUp(self): if TestBase.STOP_AFTER_FIRST_FAILURE: assert not TestBase.HAS_PENDING_FAILURE super(TestBase, self).setUp() self._set_up_logging() # e.g. TEST_DATA_BASE/tests/functional/tests/MyTestCase. self.test_tempdir = os.path.join( TEST_DATA_BASE, self.__class__.__module__.replace('.', os.sep), self.__class__.__name__) self.reset_filesystem() self._originals = {} # Map of object -> {symbol_string: original_value} def _set_up_logging(self): self._log = cStringIO.StringIO() self._stream_handler = logging.StreamHandler(self._log) self._stream_handler.setFormatter( logging.Formatter(fmt='%(levelname)s: %(message)s')) self._logger = logging.getLogger() self._logger.addHandler(self._stream_handler) self._logger.setLevel(self.LOG_LEVEL) def tearDown(self): self._unswap_all() self.reset_filesystem(remove_only=True) self._tear_down_logging() super(TestBase, self).tearDown() def _tear_down_logging(self): self._logger.removeHandler(self._stream_handler) self._log.close() def get_log(self): self._log.flush() return self._log.getvalue() def assertLogContains(self, message): self.assertIn(message, self.get_log()) def reset_filesystem(self, remove_only=False): if os.path.exists(self.test_tempdir): shutil.rmtree(self.test_tempdir) if not remove_only: os.makedirs(self.test_tempdir) def run(self, result=None): if not result: result = self.defaultTestResult() super(TestBase, self).run(result) if not result.wasSuccessful(): TestBase.HAS_PENDING_FAILURE = True def shortDescription(self): """Additional information logged during unittest invocation.""" # Suppress default logging of docstrings. Instead log name/status only. return None def swap(self, source, symbol, new): # pylint: disable=invalid-name """Swaps out source.symbol for a new value. Allows swapping of members and methods: myobject.foo = 'original_foo' self.swap(myobject, 'foo', 'bar') self.assertEqual('bar', myobject.foo) myobject.baz() # -> 'original_baz' self.swap(myobject, 'baz', lambda: 'quux') self.assertEqual('quux', myobject.bar()) Swaps are automatically undone in tearDown(). Args: source: object. The source object to swap from. symbol: string. The name of the symbol to swap. new: object. The new value to swap in. """ if source not in self._originals: self._originals[source] = {} if not self._originals[source].get(symbol, None): self._originals[source][symbol] = getattr(source, symbol) setattr(source, symbol, new) def _unswap_all(self): for source, symbol_to_value in self._originals.iteritems(): for symbol, value in symbol_to_value.iteritems(): setattr(source, symbol, value) class FunctionalTestBase(TestBase): """Base class for functional tests.""" class AppEngineTestBase(FunctionalTestBase): """Base class for tests that require App Engine services.""" def getApp(self): """Returns the main application to be tested.""" raise Exception('Not implemented.') def setUp(self): super(AppEngineTestBase, self).setUp() empty_environ() # setup an app to be tested self.testapp = webtest.TestApp(self.getApp()) self.testbed = testbed.Testbed() self.testbed.activate() # configure datastore policy to emulate instantaneously and globally # consistent HRD; we also patch dev_appserver in main.py to run under # the same policy policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy( probability=1) # declare any relevant App Engine service stubs here self.testbed.init_user_stub() self.testbed.init_memcache_stub() self.testbed.init_datastore_v3_stub(consistency_policy=policy) self.testbed.init_taskqueue_stub(root_path=os.environ['SOURCE_DIR']) self.taskq = self.testbed.get_stub(testbed.TASKQUEUE_SERVICE_NAME) self.testbed.init_urlfetch_stub() self.testbed.init_files_stub() self.testbed.init_blobstore_stub() self.testbed.init_mail_stub() self.testbed.init_app_identity_stub() # TODO(emichael): Fix this when an official stub is created self.testbed._register_stub( 'search', simple_search_stub.SearchServiceStub()) self.task_dispatcher = task_queue.TaskQueueHandlerDispatcher( self.testapp, self.taskq) # Handle for testing sent mail. self.mail_stub = self.testbed.get_stub(testbed.MAIL_SERVICE_NAME) def tearDown(self): self.testbed.deactivate() super(AppEngineTestBase, self).tearDown() def get_mail_stub(self): return self.testbed.get_stub(testbed.MAIL_SERVICE_NAME) def create_test_suite(parsed_args): """Loads all requested test suites. By default, loads all unittest.TestCases found under the project root's tests/ directory. Args: parsed_args: argparse.Namespace. Processed command-line arguments. Returns: unittest.TestSuite. The test suite populated with all tests to run. """ loader = unittest.TestLoader() if not parsed_args.test_class_name: raise Exception('Expected --test_class_name to be specified.') return loader.loadTestsFromName(parsed_args.test_class_name) def fix_sys_path(): """Fix the sys.path to include GAE extra paths.""" import dev_appserver # pylint: disable=C6204 # dev_appserver.fix_sys_path() prepends GAE paths to sys.path and hides # our classes like 'tests' behind other modules that have 'tests'. # Here, unlike dev_appserver, we append the path instead of prepending it, # so that our classes come first. sys.path += dev_appserver.EXTRA_PATHS[:] # This is to work around an issue with the __import__ builtin. The # problem seems to be that if the sys.path list contains an item that # partially matches a package name to import, __import__ will get # confused, and report an error message (which removes the first path # element from the module it's complaining about, which does not help # efforts to diagnose the problem at all). # # The specific case where this causes an issue is between # $COURSEBUILDER_HOME/tests/internal and $COURSEBUILDER_HOME/internal # Since the former exists, __import__ will ignore the second, and so # things like .../internal/experimental/autoregister/autoregister # cannot be loaded. # # To address this issue, we ensure that COURSEBUILDER_HOME is on sys.path # before anything else, and do it before appengine_config's module # importation starts running. (And we have to do it here, because if we # try to do this within appengine_config, AppEngine will throw an error) if appengine_config.BUNDLE_ROOT in sys.path: sys.path.remove(appengine_config.BUNDLE_ROOT) sys.path.insert(0, appengine_config.BUNDLE_ROOT) def main(): """Starts in-process server and runs all test cases in this module.""" fix_sys_path() etl._set_env_vars_from_app_yaml() parsed_args = _PARSER.parse_args() test_suite = create_test_suite(parsed_args) result = unittest.TextTestRunner(verbosity=2).run(test_suite) if result.errors or result.failures: raise Exception( 'Test suite failed: %s errors, %s failures of ' ' %s tests run.' % ( len(result.errors), len(result.failures), result.testsRun)) import tests.functional.actions as actions count = len(actions.UNIQUE_URLS_FOUND.keys()) result.stream.writeln('INFO: Unique URLs found: %s' % count) result.stream.writeln('INFO: All %s tests PASSED!' % result.testsRun) if __name__ == '__main__': appengine_config.gcb_force_default_encoding('ascii') main()
36.566038
80
0.689456
__author__ = 'Sean Lip' import argparse import cStringIO import logging import os import shutil import sys import unittest import task_queue import webtest import appengine_config from tools.etl import etl from google.appengine.api.search import simple_search_stub from google.appengine.datastore import datastore_stub_util from google.appengine.ext import testbed _PARSER = argparse.ArgumentParser() _PARSER.add_argument( '--test_class_name', help='optional dotted module name of the test(s) to run', type=str) TEST_DATA_BASE = os.path.join( os.environ['COURSEBUILDER_RESOURCES'], 'test-data') def empty_environ(): os.environ['AUTH_DOMAIN'] = 'example.com' os.environ['SERVER_NAME'] = 'localhost' os.environ['HTTP_HOST'] = 'localhost' os.environ['SERVER_PORT'] = '8080' os.environ['USER_EMAIL'] = '' os.environ['USER_ID'] = '' os.environ['DEFAULT_VERSION_HOSTNAME'] = ( os.environ['HTTP_HOST'] + ':' + os.environ['SERVER_PORT']) def iterate_tests(test_suite_or_case): try: suite = iter(test_suite_or_case) except TypeError: yield test_suite_or_case else: for test in suite: for subtest in iterate_tests(test): yield subtest class TestBase(unittest.TestCase): INTEGRATION_SERVER_BASE_URL = 'http://localhost:8081' ADMIN_SERVER_BASE_URL = 'http://localhost:8000' STOP_AFTER_FIRST_FAILURE = False HAS_PENDING_FAILURE = False # Log level for all tests in this test case. Override if you need to test # against different logging levels. Be very careful when setting this to # logging.DEBUG: downstream code is sometimes very chatty at logging.DEBUG, # and can generate enough logging data that tests run out of memory. LOG_LEVEL = logging.ERROR def setUp(self): if TestBase.STOP_AFTER_FIRST_FAILURE: assert not TestBase.HAS_PENDING_FAILURE super(TestBase, self).setUp() self._set_up_logging() # e.g. TEST_DATA_BASE/tests/functional/tests/MyTestCase. self.test_tempdir = os.path.join( TEST_DATA_BASE, self.__class__.__module__.replace('.', os.sep), self.__class__.__name__) self.reset_filesystem() self._originals = {} # Map of object -> {symbol_string: original_value} def _set_up_logging(self): self._log = cStringIO.StringIO() self._stream_handler = logging.StreamHandler(self._log) self._stream_handler.setFormatter( logging.Formatter(fmt='%(levelname)s: %(message)s')) self._logger = logging.getLogger() self._logger.addHandler(self._stream_handler) self._logger.setLevel(self.LOG_LEVEL) def tearDown(self): self._unswap_all() self.reset_filesystem(remove_only=True) self._tear_down_logging() super(TestBase, self).tearDown() def _tear_down_logging(self): self._logger.removeHandler(self._stream_handler) self._log.close() def get_log(self): self._log.flush() return self._log.getvalue() def assertLogContains(self, message): self.assertIn(message, self.get_log()) def reset_filesystem(self, remove_only=False): if os.path.exists(self.test_tempdir): shutil.rmtree(self.test_tempdir) if not remove_only: os.makedirs(self.test_tempdir) def run(self, result=None): if not result: result = self.defaultTestResult() super(TestBase, self).run(result) if not result.wasSuccessful(): TestBase.HAS_PENDING_FAILURE = True def shortDescription(self): # Suppress default logging of docstrings. Instead log name/status only. return None def swap(self, source, symbol, new): # pylint: disable=invalid-name if source not in self._originals: self._originals[source] = {} if not self._originals[source].get(symbol, None): self._originals[source][symbol] = getattr(source, symbol) setattr(source, symbol, new) def _unswap_all(self): for source, symbol_to_value in self._originals.iteritems(): for symbol, value in symbol_to_value.iteritems(): setattr(source, symbol, value) class FunctionalTestBase(TestBase): class AppEngineTestBase(FunctionalTestBase): def getApp(self): raise Exception('Not implemented.') def setUp(self): super(AppEngineTestBase, self).setUp() empty_environ() # setup an app to be tested self.testapp = webtest.TestApp(self.getApp()) self.testbed = testbed.Testbed() self.testbed.activate() # configure datastore policy to emulate instantaneously and globally # consistent HRD; we also patch dev_appserver in main.py to run under # the same policy policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy( probability=1) # declare any relevant App Engine service stubs here self.testbed.init_user_stub() self.testbed.init_memcache_stub() self.testbed.init_datastore_v3_stub(consistency_policy=policy) self.testbed.init_taskqueue_stub(root_path=os.environ['SOURCE_DIR']) self.taskq = self.testbed.get_stub(testbed.TASKQUEUE_SERVICE_NAME) self.testbed.init_urlfetch_stub() self.testbed.init_files_stub() self.testbed.init_blobstore_stub() self.testbed.init_mail_stub() self.testbed.init_app_identity_stub() # TODO(emichael): Fix this when an official stub is created self.testbed._register_stub( 'search', simple_search_stub.SearchServiceStub()) self.task_dispatcher = task_queue.TaskQueueHandlerDispatcher( self.testapp, self.taskq) # Handle for testing sent mail. self.mail_stub = self.testbed.get_stub(testbed.MAIL_SERVICE_NAME) def tearDown(self): self.testbed.deactivate() super(AppEngineTestBase, self).tearDown() def get_mail_stub(self): return self.testbed.get_stub(testbed.MAIL_SERVICE_NAME) def create_test_suite(parsed_args): loader = unittest.TestLoader() if not parsed_args.test_class_name: raise Exception('Expected --test_class_name to be specified.') return loader.loadTestsFromName(parsed_args.test_class_name) def fix_sys_path(): import dev_appserver # pylint: disable=C6204 # dev_appserver.fix_sys_path() prepends GAE paths to sys.path and hides # our classes like 'tests' behind other modules that have 'tests'. # Here, unlike dev_appserver, we append the path instead of prepending it, # so that our classes come first. sys.path += dev_appserver.EXTRA_PATHS[:] # This is to work around an issue with the __import__ builtin. The # problem seems to be that if the sys.path list contains an item that # partially matches a package name to import, __import__ will get # confused, and report an error message (which removes the first path # element from the module it's complaining about, which does not help # importation starts running. (And we have to do it here, because if we # try to do this within appengine_config, AppEngine will throw an error) if appengine_config.BUNDLE_ROOT in sys.path: sys.path.remove(appengine_config.BUNDLE_ROOT) sys.path.insert(0, appengine_config.BUNDLE_ROOT) def main(): fix_sys_path() etl._set_env_vars_from_app_yaml() parsed_args = _PARSER.parse_args() test_suite = create_test_suite(parsed_args) result = unittest.TextTestRunner(verbosity=2).run(test_suite) if result.errors or result.failures: raise Exception( 'Test suite failed: %s errors, %s failures of ' ' %s tests run.' % ( len(result.errors), len(result.failures), result.testsRun)) import tests.functional.actions as actions count = len(actions.UNIQUE_URLS_FOUND.keys()) result.stream.writeln('INFO: Unique URLs found: %s' % count) result.stream.writeln('INFO: All %s tests PASSED!' % result.testsRun) if __name__ == '__main__': appengine_config.gcb_force_default_encoding('ascii') main()
true
true
f7259138e078865f2f6c44a93538b382ee2f400a
786
py
Python
pyleecan/Methods/Output/OutElec/get_Nr.py
tobsen2code/pyleecan
5b1ded9e389e0c79ed7b7c878b6e939f2d9962e9
[ "Apache-2.0" ]
5
2020-03-05T15:22:39.000Z
2022-03-02T15:26:08.000Z
pyleecan/Methods/Output/OutElec/get_Nr.py
Eomys/Pyleecan
4d7f0cbabf0311006963e7a2f435db2ecd901118
[ "Apache-2.0" ]
8
2020-07-09T07:43:01.000Z
2022-03-08T12:52:06.000Z
pyleecan/Methods/Output/OutElec/get_Nr.py
Eomys/Pyleecan
4d7f0cbabf0311006963e7a2f435db2ecd901118
[ "Apache-2.0" ]
4
2019-12-23T12:38:01.000Z
2022-01-07T10:47:48.000Z
from numpy import ones def get_Nr(self, Time=None): """Create speed in function of time vector Nr Parameters ---------- self : OutElec An OutElec object Time : Data a time axis (SciDataTool Data object) Returns ------- Nr: ndarray speed in function of time """ if Time is None: if self.axes_dict is not None and "time" in self.axes_dict: Time = self.axes_dict["time"] else: raise Exception('You must define "time" property before calling get_Nr') if self.OP.get_N0() is None: raise Exception('You must define "N0" before calling get_Nr') # Same speed for every timestep Nr = self.OP.get_N0() * ones(Time.get_length(is_smallestperiod=True)) return Nr
23.818182
84
0.611959
from numpy import ones def get_Nr(self, Time=None): if Time is None: if self.axes_dict is not None and "time" in self.axes_dict: Time = self.axes_dict["time"] else: raise Exception('You must define "time" property before calling get_Nr') if self.OP.get_N0() is None: raise Exception('You must define "N0" before calling get_Nr') Nr = self.OP.get_N0() * ones(Time.get_length(is_smallestperiod=True)) return Nr
true
true
f72595be695d8aadf33d417466be973d11af82cd
21,863
py
Python
qkeras/qoctave.py
thaarres/qkeras
a04bfe65a144ef6dd0ca0880866ef6109c3638fc
[ "Apache-2.0" ]
1
2019-12-08T16:22:21.000Z
2019-12-08T16:22:21.000Z
qkeras/qoctave.py
Athena-INT/qkeras
4cd7bb948bca11507d124cdddc3afda4956a72db
[ "Apache-2.0" ]
null
null
null
qkeras/qoctave.py
Athena-INT/qkeras
4cd7bb948bca11507d124cdddc3afda4956a72db
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Octave Convolution.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import re from keras.layers import Activation from keras.layers import Add from keras.layers import AveragePooling2D from keras.layers import Conv2D from keras.layers import SeparableConv2D from keras.layers import UpSampling2D from .qlayers import QActivation from .qlayers import QAveragePooling2D from .qlayers import QConv2D from .qlayers import QSeparableConv2D def GetActivationSuffix(activation): """Returns suffix for layer name to facilitate debugging.""" if not activation: return "linear" if "po2" in activation: return "q2" elif "quantized_relu" in activation: suffix = "qr" elif "quantized_tanh" in activation: suffix = "qt" else: suffix = "qb" numbers = re.findall(r"[0-9]+", activation) numbers = [n + "_" if len(n) > 1 else n for n in numbers] return suffix + "".join(numbers) def QOctaveConv2D( filters, kernel_size, alpha, strides=(1, 1), padding="valid", kernel_initializer="he_normal", bias_initializer="zeros", # NOTE: kernel_regularizer not used with separable convolution kernel_regularizer=None, bias_regularizer=None, kernel_constraint=None, bias_constraint=None, use_separable=True, name="", **kwargs): """Implements quantized QOctaveConv2D.""" def _QOctaveConv2DInternal(x): """Computes QOctaveConv2D on a tensor.""" x_h, x_l = x bias_quantizer = kwargs.get("bias_quantizer", None) kernel_quantizer = kwargs.get("kernel_quantizer", None) depthwise_quantizer = kwargs.get("depthwise_quantizer", None) pointwise_quantizer = kwargs.get("pointwise_quantizer", None) acc_quantizer = kwargs.get("acc_quantizer", None) pooling_quantizer = kwargs.get("pooling_quantizer", None) depthwise_activation = kwargs.get("depthwise_activation", None) activation = kwargs.get("activation", None) bias_range = kwargs.get("bias_range", 1.0) kernel_range = kwargs.get("kernel_range", 1.0) depthwise_range = kwargs.get("depthwise_range", 1.0) pointwise_range = kwargs.get("pointwise_range", 1.0) if activation: act_suffix = "_" + GetActivationSuffix(activation) acc_suffix = "_" + GetActivationSuffix(acc_quantizer) if alpha == -1.0: if use_separable: x_h = QSeparableConv2D( filters, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=pointwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_h_to_h")(x_h) else: x_h = QConv2D( filters, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_h_to_h")(x_h) if activation: x_h = QActivation( activation, name=name + "_c_h_to_h_act" + act_suffix)( x_h) return [x_h, None] co_h = int(filters * (1 - alpha)) co_l = filters - co_h x_h_to_h = None x_h_to_l = None x_l_to_l = None x_l_to_h = None if co_h > 0: if x_h is not None: if use_separable: x_h_to_h = QSeparableConv2D( co_h, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=pointwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_h_to_h")(x_h) else: x_h_to_h = QConv2D( co_h, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_h_to_h")(x_h) if acc_quantizer: x_h_to_h = QActivation( acc_quantizer, name=name + "_c_h_to_h_act" + acc_suffix)(x_h_to_h) if co_l > 0: if x_h is not None: x_h_to_l = QAveragePooling2D( pool_size=2, strides=2, quantizer=pooling_quantizer, name=name + "_avg_h_to_l")(x_h) if use_separable: x_h_to_l = QSeparableConv2D( co_l, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=pointwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_h_to_l")(x_h_to_l) else: x_h_to_l = QConv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_h_to_l")(x_h_to_l) if acc_quantizer: x_h_to_l = QActivation( acc_quantizer, name=name + "_c_h_to_l_act" + acc_suffix)(x_h_to_l) if co_h > 0: if x_l is not None: _, height, width, _ = x_l.shape.as_list() if height == 1 and width == 1: local_kernel = 1 local_strides = 1 local_padding = "same" upsampling = False else: local_kernel = kernel_size local_strides = strides local_padding = padding upsampling = True if use_separable and upsampling: x_l_to_h = QSeparableConv2D( co_h, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=pointwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_l_to_h")(x_l) else: x_l_to_h = QConv2D( co_h, local_kernel, strides=local_strides, padding=local_padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_l_to_h")(x_l) if acc_quantizer: x_l_to_h = QActivation( acc_quantizer, name=name + "_c_l_to_h_act" + acc_suffix)(x_l_to_h) if upsampling: x_l_to_h = UpSampling2D( size=(2, 2), name=name + "_u_l_to_h")(x_l_to_h) if co_l > 0: if x_l is not None: if use_separable: x_l_to_l = QSeparableConv2D( co_l, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=depthwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_l_to_l")(x_l) else: x_l_to_l = QConv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_l_to_l")(x_l) if acc_quantizer: x_l_to_l = QActivation( acc_quantizer, name=name + "_c_l_to_l_act" + acc_suffix)( x_l_to_l) if x_h_to_h is not None and x_l_to_h is not None: x_h = Add(name=name + "_a_h")([x_h_to_h, x_l_to_h]) elif x_h_to_h is not None: x_h = x_h_to_h elif x_l_to_h is not None: x_h = x_l_to_h else: x_h = None if x_l_to_l is not None and x_h_to_l is not None: x_l = Add(name=name + "_a_l")([x_l_to_l, x_h_to_l]) elif x_l_to_l is not None: x_l = x_l_to_l elif x_h_to_l is not None: x_l = x_h_to_l else: x_l = None if x_h is not None and activation is not None: x_h = QActivation(activation, name=name + "_h_act" + act_suffix)(x_h) if x_l is not None and activation is not None: x_l = QActivation(activation, name=name + "_l_act" + act_suffix)(x_l) return [x_h, x_l] return _QOctaveConv2DInternal def OctaveConv2D( filters, kernel_size, alpha, strides=(1, 1), padding="valid", kernel_initializer="he_normal", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, kernel_constraint=None, bias_constraint=None, activation=None, use_separable=True, name="", **kwargs): """Implements OctaveConv2D.""" def _OctaveConv2DInternal(x): """Computes octave on tensor.""" acc_quantizer = kwargs.get("acc_quantizer", None) x_h, x_l = x if alpha == -1.0: if use_separable: x_h = SeparableConv2D( filters, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_h")(x_h) else: x_h = Conv2D( filters, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name+"_c_h_to_h")(x_h) if activation: x_h = Activation(activation, name=name + "_c_h_to_h_act")(x_h) return [x_h, None] co_h = int(filters * (1 - alpha)) co_l = filters - co_h x_h_to_h = None x_h_to_l = None x_l_to_l = None x_l_to_h = None if co_h > 0: if x_h is not None: if use_separable: x_h_to_h = SeparableConv2D( co_h, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_h")(x_h) else: x_h_to_h = Conv2D( co_h, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_h")(x_h) if activation: x_h_to_h = Activation( acc_quantizer, name=name + "_c_h_to_h_act")(x_h_to_h) if co_l > 0: if x_h is not None: x_h_to_l = AveragePooling2D(pool_size=2, strides=2, name=name + "_p_h_to_l")(x_h) if use_separable: x_h_to_l = SeparableConv2D( co_l, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_l")(x_h_to_l) else: x_h_to_l = Conv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_l")(x_h_to_l) if activation: x_h_to_l = Activation( acc_quantizer, name=name + "_c_h_to_l_act")(x_h_to_l) if co_h > 0: if x_l is not None: _, height, width, _ = x_l.shape.as_list() if height == 1 and width == 1: local_kernel = 1 local_strides = 1 local_padding = "same" upsampling = False else: local_kernel = kernel_size local_strides = strides local_padding = padding upsampling = True if use_separable and upsampling: x_l_to_h = SeparableConv2D( co_h, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_l_to_h")(x_l) else: x_l_to_h = Conv2D( co_h, local_kernel, strides=local_strides, padding=local_padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_l_to_h")(x_l) if activation: x_l_to_h = Activation( acc_quantizer, name=name + "_c_l_to_h_act")(x_l_to_h) if upsampling: x_l_to_h = UpSampling2D( size=(2, 2), name=name + "_u_l_to_h")(x_l_to_h) if co_l > 0: if x_l is not None: if use_separable: x_l_to_l = SeparableConv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_l_to_l")(x_l) else: x_l_to_l = Conv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_l_to_l")(x_l) if activation: x_l_to_l = Activation( acc_quantizer, name=name + "_c_l_to_l_act")(x_l_to_l) if x_h_to_h is not None and x_l_to_h is not None: x_h = Add(name=name + "_a_h")([x_h_to_h, x_l_to_h]) elif x_h_to_h is not None: x_h = x_h_to_h elif x_l_to_h is not None: x_h = x_l_to_h else: x_h = None if x_l_to_l is not None and x_h_to_l is not None: x_l = Add(name=name + "_a_l")([x_l_to_l, x_h_to_l]) elif x_l_to_l is not None: x_l = x_l_to_l elif x_h_to_l is not None: x_l = x_h_to_l else: x_l = None if x_h is not None: x_h = Activation(activation, name=name + "_h_act")(x_h) if x_l is not None: x_l = Activation(activation, name=name + "_l_act")(x_l) return (x_h, x_l) return _OctaveConv2DInternal
36.806397
80
0.634725
from __future__ import absolute_import from __future__ import division from __future__ import print_function import re from keras.layers import Activation from keras.layers import Add from keras.layers import AveragePooling2D from keras.layers import Conv2D from keras.layers import SeparableConv2D from keras.layers import UpSampling2D from .qlayers import QActivation from .qlayers import QAveragePooling2D from .qlayers import QConv2D from .qlayers import QSeparableConv2D def GetActivationSuffix(activation): if not activation: return "linear" if "po2" in activation: return "q2" elif "quantized_relu" in activation: suffix = "qr" elif "quantized_tanh" in activation: suffix = "qt" else: suffix = "qb" numbers = re.findall(r"[0-9]+", activation) numbers = [n + "_" if len(n) > 1 else n for n in numbers] return suffix + "".join(numbers) def QOctaveConv2D( filters, kernel_size, alpha, strides=(1, 1), padding="valid", kernel_initializer="he_normal", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, kernel_constraint=None, bias_constraint=None, use_separable=True, name="", **kwargs): def _QOctaveConv2DInternal(x): x_h, x_l = x bias_quantizer = kwargs.get("bias_quantizer", None) kernel_quantizer = kwargs.get("kernel_quantizer", None) depthwise_quantizer = kwargs.get("depthwise_quantizer", None) pointwise_quantizer = kwargs.get("pointwise_quantizer", None) acc_quantizer = kwargs.get("acc_quantizer", None) pooling_quantizer = kwargs.get("pooling_quantizer", None) depthwise_activation = kwargs.get("depthwise_activation", None) activation = kwargs.get("activation", None) bias_range = kwargs.get("bias_range", 1.0) kernel_range = kwargs.get("kernel_range", 1.0) depthwise_range = kwargs.get("depthwise_range", 1.0) pointwise_range = kwargs.get("pointwise_range", 1.0) if activation: act_suffix = "_" + GetActivationSuffix(activation) acc_suffix = "_" + GetActivationSuffix(acc_quantizer) if alpha == -1.0: if use_separable: x_h = QSeparableConv2D( filters, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=pointwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_h_to_h")(x_h) else: x_h = QConv2D( filters, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_h_to_h")(x_h) if activation: x_h = QActivation( activation, name=name + "_c_h_to_h_act" + act_suffix)( x_h) return [x_h, None] co_h = int(filters * (1 - alpha)) co_l = filters - co_h x_h_to_h = None x_h_to_l = None x_l_to_l = None x_l_to_h = None if co_h > 0: if x_h is not None: if use_separable: x_h_to_h = QSeparableConv2D( co_h, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=pointwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_h_to_h")(x_h) else: x_h_to_h = QConv2D( co_h, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_h_to_h")(x_h) if acc_quantizer: x_h_to_h = QActivation( acc_quantizer, name=name + "_c_h_to_h_act" + acc_suffix)(x_h_to_h) if co_l > 0: if x_h is not None: x_h_to_l = QAveragePooling2D( pool_size=2, strides=2, quantizer=pooling_quantizer, name=name + "_avg_h_to_l")(x_h) if use_separable: x_h_to_l = QSeparableConv2D( co_l, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=pointwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_h_to_l")(x_h_to_l) else: x_h_to_l = QConv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_h_to_l")(x_h_to_l) if acc_quantizer: x_h_to_l = QActivation( acc_quantizer, name=name + "_c_h_to_l_act" + acc_suffix)(x_h_to_l) if co_h > 0: if x_l is not None: _, height, width, _ = x_l.shape.as_list() if height == 1 and width == 1: local_kernel = 1 local_strides = 1 local_padding = "same" upsampling = False else: local_kernel = kernel_size local_strides = strides local_padding = padding upsampling = True if use_separable and upsampling: x_l_to_h = QSeparableConv2D( co_h, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=pointwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_l_to_h")(x_l) else: x_l_to_h = QConv2D( co_h, local_kernel, strides=local_strides, padding=local_padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_l_to_h")(x_l) if acc_quantizer: x_l_to_h = QActivation( acc_quantizer, name=name + "_c_l_to_h_act" + acc_suffix)(x_l_to_h) if upsampling: x_l_to_h = UpSampling2D( size=(2, 2), name=name + "_u_l_to_h")(x_l_to_h) if co_l > 0: if x_l is not None: if use_separable: x_l_to_l = QSeparableConv2D( co_l, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, depthwise_quantizer=depthwise_quantizer, pointwise_quantizer=depthwise_quantizer, bias_quantizer=bias_quantizer, depthwise_activation=depthwise_activation, pointwise_range=pointwise_range, depthwise_range=depthwise_range, bias_range=bias_range, name=name + "_c_l_to_l")(x_l) else: x_l_to_l = QConv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, kernel_quantizer=kernel_quantizer, bias_quantizer=bias_quantizer, kernel_range=kernel_range, bias_range=bias_range, name=name + "_c_l_to_l")(x_l) if acc_quantizer: x_l_to_l = QActivation( acc_quantizer, name=name + "_c_l_to_l_act" + acc_suffix)( x_l_to_l) if x_h_to_h is not None and x_l_to_h is not None: x_h = Add(name=name + "_a_h")([x_h_to_h, x_l_to_h]) elif x_h_to_h is not None: x_h = x_h_to_h elif x_l_to_h is not None: x_h = x_l_to_h else: x_h = None if x_l_to_l is not None and x_h_to_l is not None: x_l = Add(name=name + "_a_l")([x_l_to_l, x_h_to_l]) elif x_l_to_l is not None: x_l = x_l_to_l elif x_h_to_l is not None: x_l = x_h_to_l else: x_l = None if x_h is not None and activation is not None: x_h = QActivation(activation, name=name + "_h_act" + act_suffix)(x_h) if x_l is not None and activation is not None: x_l = QActivation(activation, name=name + "_l_act" + act_suffix)(x_l) return [x_h, x_l] return _QOctaveConv2DInternal def OctaveConv2D( filters, kernel_size, alpha, strides=(1, 1), padding="valid", kernel_initializer="he_normal", bias_initializer="zeros", kernel_regularizer=None, bias_regularizer=None, kernel_constraint=None, bias_constraint=None, activation=None, use_separable=True, name="", **kwargs): def _OctaveConv2DInternal(x): acc_quantizer = kwargs.get("acc_quantizer", None) x_h, x_l = x if alpha == -1.0: if use_separable: x_h = SeparableConv2D( filters, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_h")(x_h) else: x_h = Conv2D( filters, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name+"_c_h_to_h")(x_h) if activation: x_h = Activation(activation, name=name + "_c_h_to_h_act")(x_h) return [x_h, None] co_h = int(filters * (1 - alpha)) co_l = filters - co_h x_h_to_h = None x_h_to_l = None x_l_to_l = None x_l_to_h = None if co_h > 0: if x_h is not None: if use_separable: x_h_to_h = SeparableConv2D( co_h, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_h")(x_h) else: x_h_to_h = Conv2D( co_h, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_h")(x_h) if activation: x_h_to_h = Activation( acc_quantizer, name=name + "_c_h_to_h_act")(x_h_to_h) if co_l > 0: if x_h is not None: x_h_to_l = AveragePooling2D(pool_size=2, strides=2, name=name + "_p_h_to_l")(x_h) if use_separable: x_h_to_l = SeparableConv2D( co_l, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_l")(x_h_to_l) else: x_h_to_l = Conv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_h_to_l")(x_h_to_l) if activation: x_h_to_l = Activation( acc_quantizer, name=name + "_c_h_to_l_act")(x_h_to_l) if co_h > 0: if x_l is not None: _, height, width, _ = x_l.shape.as_list() if height == 1 and width == 1: local_kernel = 1 local_strides = 1 local_padding = "same" upsampling = False else: local_kernel = kernel_size local_strides = strides local_padding = padding upsampling = True if use_separable and upsampling: x_l_to_h = SeparableConv2D( co_h, kernel_size, strides=strides, padding=padding, depthwise_regularizer=kernel_regularizer, depthwise_constraint=kernel_constraint, depthwise_initializer=kernel_initializer, pointwise_regularizer=kernel_regularizer, pointwise_constraint=kernel_constraint, pointwise_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_l_to_h")(x_l) else: x_l_to_h = Conv2D( co_h, local_kernel, strides=local_strides, padding=local_padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_l_to_h")(x_l) if activation: x_l_to_h = Activation( acc_quantizer, name=name + "_c_l_to_h_act")(x_l_to_h) if upsampling: x_l_to_h = UpSampling2D( size=(2, 2), name=name + "_u_l_to_h")(x_l_to_h) if co_l > 0: if x_l is not None: if use_separable: x_l_to_l = SeparableConv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_l_to_l")(x_l) else: x_l_to_l = Conv2D( co_l, kernel_size, strides=strides, padding=padding, kernel_regularizer=kernel_regularizer, kernel_constraint=kernel_constraint, kernel_initializer=kernel_initializer, bias_regularizer=bias_regularizer, bias_constraint=bias_constraint, bias_initializer=bias_initializer, name=name + "_c_l_to_l")(x_l) if activation: x_l_to_l = Activation( acc_quantizer, name=name + "_c_l_to_l_act")(x_l_to_l) if x_h_to_h is not None and x_l_to_h is not None: x_h = Add(name=name + "_a_h")([x_h_to_h, x_l_to_h]) elif x_h_to_h is not None: x_h = x_h_to_h elif x_l_to_h is not None: x_h = x_l_to_h else: x_h = None if x_l_to_l is not None and x_h_to_l is not None: x_l = Add(name=name + "_a_l")([x_l_to_l, x_h_to_l]) elif x_l_to_l is not None: x_l = x_l_to_l elif x_h_to_l is not None: x_l = x_h_to_l else: x_l = None if x_h is not None: x_h = Activation(activation, name=name + "_h_act")(x_h) if x_l is not None: x_l = Activation(activation, name=name + "_l_act")(x_l) return (x_h, x_l) return _OctaveConv2DInternal
true
true
f7259600ce77f1327a75cfc7ad33fc54ddf8e263
261
py
Python
daily_work/daily_work/doctype/daily_default_setting/daily_default_setting.py
muirawachanga/mwai
1a95cba5bc6368361fc48984ba05307ae4093ead
[ "MIT" ]
null
null
null
daily_work/daily_work/doctype/daily_default_setting/daily_default_setting.py
muirawachanga/mwai
1a95cba5bc6368361fc48984ba05307ae4093ead
[ "MIT" ]
null
null
null
daily_work/daily_work/doctype/daily_default_setting/daily_default_setting.py
muirawachanga/mwai
1a95cba5bc6368361fc48984ba05307ae4093ead
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright (c) 2019, steve and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class DailyDefaultSetting(Document): pass
23.727273
49
0.785441
from __future__ import unicode_literals import frappe from frappe.model.document import Document class DailyDefaultSetting(Document): pass
true
true
f7259615a162f1f9b8997248b81998d51618e2f1
1,384
py
Python
cli.py
stesla/arxtools
7f1a3b973e3d78faed4085d547b7d27ebcd9838d
[ "MIT" ]
null
null
null
cli.py
stesla/arxtools
7f1a3b973e3d78faed4085d547b7d27ebcd9838d
[ "MIT" ]
null
null
null
cli.py
stesla/arxtools
7f1a3b973e3d78faed4085d547b7d27ebcd9838d
[ "MIT" ]
null
null
null
import click import configparser import json import sys from arxtools import export_clues, fetch_clues from arxtools.clue import Clue @click.group() def cli(): pass def get_character_info(name): config = configparser.ConfigParser() config.read('arxtools.ini') try: return config[name.lower()] except KeyError: click.echo(f'No character named "{name}" found.', err=True) sys.exit(1) @cli.command("import") @click.argument('name') def _import(name): info = get_character_info(name) username = info['username'] password = info['password'] clues = fetch_clues(username, password) click.echo(json.dumps([c.to_dict() for c in clues])) @cli.command("export") @click.argument('name') def _export(name): info = get_character_info(name) directory = info['directory'] clues = [Clue.from_dict(c) for c in json.load(sys.stdin)] export_clues(clues, directory) @cli.command('update') @click.argument('name') def _update(name): info = get_character_info(name) username = info['username'] password = info['password'] directory = info['directory'] click.echo(f'Fetching clues for {username}...', err=True) clues = fetch_clues(username, password) click.echo(f'Exporting to markdown in {directory}...', err=True) export_clues(clues, directory) if __name__ == '__main__': cli()
24.714286
68
0.682803
import click import configparser import json import sys from arxtools import export_clues, fetch_clues from arxtools.clue import Clue @click.group() def cli(): pass def get_character_info(name): config = configparser.ConfigParser() config.read('arxtools.ini') try: return config[name.lower()] except KeyError: click.echo(f'No character named "{name}" found.', err=True) sys.exit(1) @cli.command("import") @click.argument('name') def _import(name): info = get_character_info(name) username = info['username'] password = info['password'] clues = fetch_clues(username, password) click.echo(json.dumps([c.to_dict() for c in clues])) @cli.command("export") @click.argument('name') def _export(name): info = get_character_info(name) directory = info['directory'] clues = [Clue.from_dict(c) for c in json.load(sys.stdin)] export_clues(clues, directory) @cli.command('update') @click.argument('name') def _update(name): info = get_character_info(name) username = info['username'] password = info['password'] directory = info['directory'] click.echo(f'Fetching clues for {username}...', err=True) clues = fetch_clues(username, password) click.echo(f'Exporting to markdown in {directory}...', err=True) export_clues(clues, directory) if __name__ == '__main__': cli()
true
true
f7259776fb98e992d885bf99cf4adf99f37e8745
8,549
py
Python
gui/qt/utxo_list.py
ComputerCraftr/openswap
7de04aa80dab79bebe4b64483011dad70a48694c
[ "MIT" ]
16
2018-11-05T13:19:02.000Z
2021-04-06T12:11:49.000Z
gui/qt/utxo_list.py
ComputerCraftr/openswap
7de04aa80dab79bebe4b64483011dad70a48694c
[ "MIT" ]
11
2018-11-11T08:56:03.000Z
2018-12-08T02:31:57.000Z
gui/qt/utxo_list.py
ComputerCraftr/openswap
7de04aa80dab79bebe4b64483011dad70a48694c
[ "MIT" ]
5
2019-01-07T13:45:05.000Z
2020-06-12T14:13:21.000Z
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2015 Thomas Voegtlin # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from .util import * from electroncash.i18n import _ class UTXOList(MyTreeWidget): filter_columns = [0, 2] # Address, Label def __init__(self, parent=None): MyTreeWidget.__init__(self, parent, self.create_menu, [ _('Address'), _('Label'), _('Amount'), _('Height'), _('Output point')], 1) self.setSelectionMode(QAbstractItemView.ExtendedSelection) self.setSortingEnabled(True) # force attributes to always be defined, even if None, at construction. self.wallet = self.parent.wallet if hasattr(self.parent, 'wallet') else None self.utxos = list() def get_name(self, x): return x.get('prevout_hash') + ":%d"%x.get('prevout_n') @rate_limited(1.0) # performance tweak -- limit updates to no more than oncer per second def update(self): if self.wallet and self.wallet.thread and not self.wallet.thread.isRunning(): # short-cut return if window was closed and wallet is stopped return super().update() def on_update(self): prev_selection = self.get_selected() # cache previous selection, if any self.clear() self.wallet = self.parent.wallet if not self.wallet: return self.utxos = self.wallet.get_utxos() for x in self.utxos: address = x['address'] address_text = address.to_ui_string() height = x['height'] name = self.get_name(x) label = self.wallet.get_label(x['prevout_hash']) amount = self.parent.format_amount(x['value']) utxo_item = SortableTreeWidgetItem([address_text, label, amount, str(height), name[0:10] + '...' + name[-2:]]) utxo_item.DataRole = Qt.UserRole+100 # set this here to avoid sorting based on Qt.UserRole+1 utxo_item.setFont(0, QFont(MONOSPACE_FONT)) utxo_item.setFont(4, QFont(MONOSPACE_FONT)) utxo_item.setData(0, Qt.UserRole, name) a_frozen = self.wallet.is_frozen(address) c_frozen = x['is_frozen_coin'] if a_frozen and not c_frozen: # address is frozen, coin is not frozen # emulate the "Look" off the address_list .py's frozen entry utxo_item.setBackground(0, QColor('lightblue')) elif c_frozen and not a_frozen: # coin is frozen, address is not frozen utxo_item.setBackground(0, ColorScheme.BLUE.as_color(True)) elif c_frozen and a_frozen: # both coin and address are frozen so color-code it to indicate that. utxo_item.setBackground(0, QColor('lightblue')) utxo_item.setForeground(0, QColor('#3399ff')) # save the address-level-frozen and coin-level-frozen flags to the data item for retrieval later in create_menu() below. utxo_item.setData(0, Qt.UserRole+1, "{}{}".format(("a" if a_frozen else ""), ("c" if c_frozen else ""))) self.addChild(utxo_item) if name in prev_selection: # NB: This needs to be here after the item is added to the widget. See #979. utxo_item.setSelected(True) # restore previous selection def get_selected(self): return { x.data(0, Qt.UserRole) : x.data(0, Qt.UserRole+1) # dict of "name" -> frozen flags string (eg: "ac") for x in self.selectedItems() } def create_menu(self, position): selected = self.get_selected() if not selected: return menu = QMenu() coins = filter(lambda x: self.get_name(x) in selected, self.utxos) spendable_coins = list(filter(lambda x: not selected.get(self.get_name(x), ''), coins)) # Unconditionally add the "Spend" option but leave it disabled if there are no spendable_coins menu.addAction(_("Spend"), lambda: self.parent.spend_coins(spendable_coins)).setEnabled(bool(spendable_coins)) if len(selected) == 1: # single selection, offer them the "Details" option and also coin/address "freeze" status, if any txid = list(selected.keys())[0].split(':')[0] frozen_flags = list(selected.values())[0] tx = self.wallet.transactions.get(txid) if tx: label = self.wallet.get_label(txid) or None menu.addAction(_("Details"), lambda: self.parent.show_transaction(tx, label)) act = None needsep = True if 'c' in frozen_flags: menu.addSeparator() menu.addAction(_("Coin is frozen"), lambda: None).setEnabled(False) menu.addAction(_("Unfreeze Coin"), lambda: self.set_frozen_coins(list(selected.keys()), False)) menu.addSeparator() needsep = False else: menu.addAction(_("Freeze Coin"), lambda: self.set_frozen_coins(list(selected.keys()), True)) if 'a' in frozen_flags: if needsep: menu.addSeparator() menu.addAction(_("Address is frozen"), lambda: None).setEnabled(False) menu.addAction(_("Unfreeze Address"), lambda: self.set_frozen_addresses_for_coins(list(selected.keys()), False)) else: menu.addAction(_("Freeze Address"), lambda: self.set_frozen_addresses_for_coins(list(selected.keys()), True)) else: # multi-selection menu.addSeparator() if any(['c' not in flags for flags in selected.values()]): # they have some coin-level non-frozen in the selection, so add the menu action "Freeze coins" menu.addAction(_("Freeze Coins"), lambda: self.set_frozen_coins(list(selected.keys()), True)) if any(['c' in flags for flags in selected.values()]): # they have some coin-level frozen in the selection, so add the menu action "Unfreeze coins" menu.addAction(_("Unfreeze Coins"), lambda: self.set_frozen_coins(list(selected.keys()), False)) if any(['a' not in flags for flags in selected.values()]): # they have some address-level non-frozen in the selection, so add the menu action "Freeze addresses" menu.addAction(_("Freeze Addresses"), lambda: self.set_frozen_addresses_for_coins(list(selected.keys()), True)) if any(['a' in flags for flags in selected.values()]): # they have some address-level frozen in the selection, so add the menu action "Unfreeze addresses" menu.addAction(_("Unfreeze Addresses"), lambda: self.set_frozen_addresses_for_coins(list(selected.keys()), False)) menu.exec_(self.viewport().mapToGlobal(position)) def on_permit_edit(self, item, column): # disable editing fields in this tab (labels) return False def set_frozen_coins(self, coins, b): if self.parent: self.parent.set_frozen_coin_state(coins, b) def set_frozen_addresses_for_coins(self, coins, b): if not self.parent: return addrs = set() for utxo in self.utxos: name = self.get_name(utxo) if name in coins: addrs.add(utxo['address']) if addrs: self.parent.set_frozen_state(list(addrs), b)
52.771605
138
0.63177
from .util import * from electroncash.i18n import _ class UTXOList(MyTreeWidget): filter_columns = [0, 2] def __init__(self, parent=None): MyTreeWidget.__init__(self, parent, self.create_menu, [ _('Address'), _('Label'), _('Amount'), _('Height'), _('Output point')], 1) self.setSelectionMode(QAbstractItemView.ExtendedSelection) self.setSortingEnabled(True) self.wallet = self.parent.wallet if hasattr(self.parent, 'wallet') else None self.utxos = list() def get_name(self, x): return x.get('prevout_hash') + ":%d"%x.get('prevout_n') @rate_limited(1.0) def update(self): if self.wallet and self.wallet.thread and not self.wallet.thread.isRunning(): return super().update() def on_update(self): prev_selection = self.get_selected() self.clear() self.wallet = self.parent.wallet if not self.wallet: return self.utxos = self.wallet.get_utxos() for x in self.utxos: address = x['address'] address_text = address.to_ui_string() height = x['height'] name = self.get_name(x) label = self.wallet.get_label(x['prevout_hash']) amount = self.parent.format_amount(x['value']) utxo_item = SortableTreeWidgetItem([address_text, label, amount, str(height), name[0:10] + '...' + name[-2:]]) utxo_item.DataRole = Qt.UserRole+100 utxo_item.setFont(0, QFont(MONOSPACE_FONT)) utxo_item.setFont(4, QFont(MONOSPACE_FONT)) utxo_item.setData(0, Qt.UserRole, name) a_frozen = self.wallet.is_frozen(address) c_frozen = x['is_frozen_coin'] if a_frozen and not c_frozen: utxo_item.setBackground(0, QColor('lightblue')) elif c_frozen and not a_frozen: # coin is frozen, address is not frozen utxo_item.setBackground(0, ColorScheme.BLUE.as_color(True)) elif c_frozen and a_frozen: # both coin and address are frozen so color-code it to indicate that. utxo_item.setBackground(0, QColor('lightblue')) utxo_item.setForeground(0, QColor(' # save the address-level-frozen and coin-level-frozen flags to the data item for retrieval later in create_menu() below. utxo_item.setData(0, Qt.UserRole+1, "{}{}".format(("a" if a_frozen else ""), ("c" if c_frozen else ""))) self.addChild(utxo_item) if name in prev_selection: # NB: This needs to be here after the item is added to the widget. See #979. utxo_item.setSelected(True) # restore previous selection def get_selected(self): return { x.data(0, Qt.UserRole) : x.data(0, Qt.UserRole+1) # dict of "name" -> frozen flags string (eg: "ac") for x in self.selectedItems() } def create_menu(self, position): selected = self.get_selected() if not selected: return menu = QMenu() coins = filter(lambda x: self.get_name(x) in selected, self.utxos) spendable_coins = list(filter(lambda x: not selected.get(self.get_name(x), ''), coins)) # Unconditionally add the "Spend" option but leave it disabled if there are no spendable_coins menu.addAction(_("Spend"), lambda: self.parent.spend_coins(spendable_coins)).setEnabled(bool(spendable_coins)) if len(selected) == 1: # single selection, offer them the "Details" option and also coin/address "freeze" status, if any txid = list(selected.keys())[0].split(':')[0] frozen_flags = list(selected.values())[0] tx = self.wallet.transactions.get(txid) if tx: label = self.wallet.get_label(txid) or None menu.addAction(_("Details"), lambda: self.parent.show_transaction(tx, label)) act = None needsep = True if 'c' in frozen_flags: menu.addSeparator() menu.addAction(_("Coin is frozen"), lambda: None).setEnabled(False) menu.addAction(_("Unfreeze Coin"), lambda: self.set_frozen_coins(list(selected.keys()), False)) menu.addSeparator() needsep = False else: menu.addAction(_("Freeze Coin"), lambda: self.set_frozen_coins(list(selected.keys()), True)) if 'a' in frozen_flags: if needsep: menu.addSeparator() menu.addAction(_("Address is frozen"), lambda: None).setEnabled(False) menu.addAction(_("Unfreeze Address"), lambda: self.set_frozen_addresses_for_coins(list(selected.keys()), False)) else: menu.addAction(_("Freeze Address"), lambda: self.set_frozen_addresses_for_coins(list(selected.keys()), True)) else: # multi-selection menu.addSeparator() if any(['c' not in flags for flags in selected.values()]): # they have some coin-level non-frozen in the selection, so add the menu action "Freeze coins" menu.addAction(_("Freeze Coins"), lambda: self.set_frozen_coins(list(selected.keys()), True)) if any(['c' in flags for flags in selected.values()]): # they have some coin-level frozen in the selection, so add the menu action "Unfreeze coins" menu.addAction(_("Unfreeze Coins"), lambda: self.set_frozen_coins(list(selected.keys()), False)) if any(['a' not in flags for flags in selected.values()]): # they have some address-level non-frozen in the selection, so add the menu action "Freeze addresses" menu.addAction(_("Freeze Addresses"), lambda: self.set_frozen_addresses_for_coins(list(selected.keys()), True)) if any(['a' in flags for flags in selected.values()]): # they have some address-level frozen in the selection, so add the menu action "Unfreeze addresses" menu.addAction(_("Unfreeze Addresses"), lambda: self.set_frozen_addresses_for_coins(list(selected.keys()), False)) menu.exec_(self.viewport().mapToGlobal(position)) def on_permit_edit(self, item, column): # disable editing fields in this tab (labels) return False def set_frozen_coins(self, coins, b): if self.parent: self.parent.set_frozen_coin_state(coins, b) def set_frozen_addresses_for_coins(self, coins, b): if not self.parent: return addrs = set() for utxo in self.utxos: name = self.get_name(utxo) if name in coins: addrs.add(utxo['address']) if addrs: self.parent.set_frozen_state(list(addrs), b)
true
true
f72597acf84a319c1cde2a9c2a80f3c7b7cfc2a4
984
py
Python
src/platform/avr/pmfeatures.py
ArtemovSA/PyMite
a22fbae773b285ccf4993905a46dd396cb762f69
[ "OLDAP-2.6", "Python-2.0" ]
51
2015-03-24T07:53:03.000Z
2021-08-06T12:55:53.000Z
src/platform/avr/pmfeatures.py
ArtemovSA/PyMite
a22fbae773b285ccf4993905a46dd396cb762f69
[ "OLDAP-2.6", "Python-2.0" ]
null
null
null
src/platform/avr/pmfeatures.py
ArtemovSA/PyMite
a22fbae773b285ccf4993905a46dd396cb762f69
[ "OLDAP-2.6", "Python-2.0" ]
15
2015-04-09T14:17:27.000Z
2022-01-26T02:42:47.000Z
# This file is Copyright 2010 Dean Hall. # # This file is part of the Python-on-a-Chip program. # Python-on-a-Chip is free software: you can redistribute it and/or modify # it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1. # # Python-on-a-Chip is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # A copy of the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1 # is seen in the file COPYING up one directory from this. PM_FEATURES = { "HAVE_PRINT": True, "HAVE_GC": True, "HAVE_FLOAT": False, "HAVE_DEL": True, "HAVE_IMPORTS": True, "HAVE_DEFAULTARGS": True, "HAVE_REPLICATION": True, "HAVE_CLASSES": False, "HAVE_ASSERT": False, "HAVE_GENERATORS": False, "HAVE_BACKTICK": True, "HAVE_STRING_FORMAT": True, "HAVE_CLOSURES": False, "HAVE_BYTEARRAY": False, "HAVE_DEBUG_INFO": False, }
32.8
74
0.707317
PM_FEATURES = { "HAVE_PRINT": True, "HAVE_GC": True, "HAVE_FLOAT": False, "HAVE_DEL": True, "HAVE_IMPORTS": True, "HAVE_DEFAULTARGS": True, "HAVE_REPLICATION": True, "HAVE_CLASSES": False, "HAVE_ASSERT": False, "HAVE_GENERATORS": False, "HAVE_BACKTICK": True, "HAVE_STRING_FORMAT": True, "HAVE_CLOSURES": False, "HAVE_BYTEARRAY": False, "HAVE_DEBUG_INFO": False, }
true
true
f7259813b4e802d256d946467bf98359af8d5554
2,970
py
Python
ally/Order/tests/PricingConstruction.py
jpwatt/PyAlly
463ac0ad22df7dd79456c58ab8da4d378427983c
[ "MIT" ]
2
2021-02-28T22:02:38.000Z
2021-12-20T19:00:25.000Z
ally/Order/tests/PricingConstruction.py
jpwatt/PyAlly
463ac0ad22df7dd79456c58ab8da4d378427983c
[ "MIT" ]
null
null
null
ally/Order/tests/PricingConstruction.py
jpwatt/PyAlly
463ac0ad22df7dd79456c58ab8da4d378427983c
[ "MIT" ]
null
null
null
# MIT License # # Copyright (c) 2020 Brett Graves # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import xml.etree.ElementTree as ET import unittest from ..classes import * from .classes import * from ..order import Order class TestPricingConstruction(unittest.TestCase): def test_market_construction(self): p = Market() self.assertEqual( p.attributes, {'Typ':'1'}, "Should have type 1" ) def test_limit_construction(self): p = Limit(limpx=10.51) self.assertEqual( p.attributes, {'Typ':'2', 'Px':'10.51'}, "Should have type 2, with Px included" ) p = Limit(limpx=10.51141) self.assertEqual( p.attributes, {'Typ':'2', 'Px':'10.51'}, "Should have type 2, with Px included" ) def test_stop_construction(self): p = Stop(stoppx=10.51) self.assertEqual( p.attributes, { 'Typ':"3", 'StopPx':"10.51"}, "Should have typ 3, with StopPx included" ) p = Stop(stoppx=10.5112312) self.assertEqual( p.attributes, { 'Typ':"3", 'StopPx':"10.51"}, "Should have typ 3, with StopPx included" ) def test_stoplimit_construction(self): p = StopLimit(limpx = 10.1, stoppx = 10.51) self.assertEqual( p.attributes, { 'Typ':"4", 'Px': '10.1', 'StopPx':"10.51" }, "Should have typ 3, with StopPx included" ) def test_trailingstop_construction(self): p = TrailingStop( use_pct = True, offset = 1.12 ) self.assertEqual( p.attributes, { 'Typ':"P"}, "Should have typ P" ) self.assertEqual( p.fixml, { 'PegInstr': { 'OfstTyp': 1, 'PegPxTyp': 1, 'OfstVal': 1.12 } }, "Should include tag with peginstr" ) p = TrailingStop( use_pct = False, offset = 5.69 ) self.assertEqual( p.attributes, { 'Typ':"P"}, "Should have typ P" ) self.assertEqual( p.fixml, { 'PegInstr': { 'OfstTyp': 0, 'PegPxTyp': 1, 'OfstVal': 5.69 } }, "Should include tag with peginstr" )
23.385827
80
0.66835
import xml.etree.ElementTree as ET import unittest from ..classes import * from .classes import * from ..order import Order class TestPricingConstruction(unittest.TestCase): def test_market_construction(self): p = Market() self.assertEqual( p.attributes, {'Typ':'1'}, "Should have type 1" ) def test_limit_construction(self): p = Limit(limpx=10.51) self.assertEqual( p.attributes, {'Typ':'2', 'Px':'10.51'}, "Should have type 2, with Px included" ) p = Limit(limpx=10.51141) self.assertEqual( p.attributes, {'Typ':'2', 'Px':'10.51'}, "Should have type 2, with Px included" ) def test_stop_construction(self): p = Stop(stoppx=10.51) self.assertEqual( p.attributes, { 'Typ':"3", 'StopPx':"10.51"}, "Should have typ 3, with StopPx included" ) p = Stop(stoppx=10.5112312) self.assertEqual( p.attributes, { 'Typ':"3", 'StopPx':"10.51"}, "Should have typ 3, with StopPx included" ) def test_stoplimit_construction(self): p = StopLimit(limpx = 10.1, stoppx = 10.51) self.assertEqual( p.attributes, { 'Typ':"4", 'Px': '10.1', 'StopPx':"10.51" }, "Should have typ 3, with StopPx included" ) def test_trailingstop_construction(self): p = TrailingStop( use_pct = True, offset = 1.12 ) self.assertEqual( p.attributes, { 'Typ':"P"}, "Should have typ P" ) self.assertEqual( p.fixml, { 'PegInstr': { 'OfstTyp': 1, 'PegPxTyp': 1, 'OfstVal': 1.12 } }, "Should include tag with peginstr" ) p = TrailingStop( use_pct = False, offset = 5.69 ) self.assertEqual( p.attributes, { 'Typ':"P"}, "Should have typ P" ) self.assertEqual( p.fixml, { 'PegInstr': { 'OfstTyp': 0, 'PegPxTyp': 1, 'OfstVal': 5.69 } }, "Should include tag with peginstr" )
true
true
f72598b7fb1cec8183f6a3b3b326c48b968194b9
2,843
py
Python
starvine/bvcopula/tests/test_freeze_params.py
wgurecky/StarVine
b952a88eeaff476484ba6a26420cfe4ef575d162
[ "BSD-3-Clause" ]
12
2018-10-04T06:15:13.000Z
2020-01-08T03:32:30.000Z
starvine/bvcopula/tests/test_freeze_params.py
wgurecky/StarVine
b952a88eeaff476484ba6a26420cfe4ef575d162
[ "BSD-3-Clause" ]
25
2017-08-29T06:28:37.000Z
2020-10-16T23:56:57.000Z
starvine/bvcopula/tests/test_freeze_params.py
wgurecky/StarVine
b952a88eeaff476484ba6a26420cfe4ef575d162
[ "BSD-3-Clause" ]
3
2017-04-08T20:19:09.000Z
2020-01-09T20:01:02.000Z
## # \brief Test ability to determine best fit copula via AIC from __future__ import print_function, division from starvine.bvcopula.pc_base import PairCopula import unittest import numpy as np import os pwd_ = os.getcwd() dataDir = pwd_ + "/tests/data/" np.random.seed(123) class TestGaussFrozen(unittest.TestCase): @classmethod def setUpClass(self): np.random.seed(123) def testGaussFrozen(self): # Load matlab data set stocks = np.loadtxt(dataDir + 'stocks.csv', delimiter=',') x = stocks[:, 0] y = stocks[:, 1] stockModel = PairCopula(x, y) # Try to fit all copula stockModel.copulaTournament(verbosity=0) # Ensure that the gaussian copula was chosen as the best fit self.assertTrue(stockModel.copulaModel.name == "gauss") self.assertTrue(stockModel.copulaParams[0] == "gauss") # Check gaussian copula parameters for correctness self.assertAlmostEqual(stockModel.copulaParams[1][0], 0.73874003, 4) # Eval the frozen model frzU, frzV = stockModel.copulaModel.sample(40000) # Eval a model with specified params setU, setV = stockModel.copulaModel.sample(40000, (0.73874003,)) # Ensure both frozen model and specified param model produce same result frzModel = PairCopula(frzU, frzV) setModel = PairCopula(setU, setV) frzKtau, fp = frzModel.empKTau() setKtau, sp = setModel.empKTau() self.assertAlmostEqual(frzKtau, setKtau, delta=0.02) self.assertAlmostEqual(fp, sp, delta=0.02) # Eval a model with different specified params setU2, setV2 = stockModel.copulaModel.sample(20000, (0.3,)) setModel2 = PairCopula(setU2, setV2) setKtau2, sp2 = setModel2.empKTau() self.assertTrue(setKtau2 != setKtau) self.assertTrue(abs(setKtau2 - setKtau) > 0.2) def testFrankFrozen(self): np.random.seed(123) # Load matlab data set stocks = np.loadtxt(dataDir + 'stocks.csv', delimiter=',') x = stocks[:, 0] y = stocks[:, 1] stockModel = PairCopula(x, y, family={'frank': 0, }) # Try to fit all copula stockModel.copulaTournament(verbosity=0) # Eval the frozen model frzU, frzV = stockModel.copulaModel.sample(40000) # Eval a model with specified params setU, setV = stockModel.copulaModel.sample(40000, *stockModel.copulaParams[1]) # Ensure both frozen model and specified param model produce same result frzModel = PairCopula(frzU, frzV) setModel = PairCopula(setU, setV) frzKtau, fp = frzModel.empKTau() setKtau, sp = setModel.empKTau() self.assertAlmostEqual(frzKtau, setKtau, delta=0.02) self.assertAlmostEqual(fp, sp, delta=0.02)
35.098765
86
0.651425
from __future__ import print_function, division from starvine.bvcopula.pc_base import PairCopula import unittest import numpy as np import os pwd_ = os.getcwd() dataDir = pwd_ + "/tests/data/" np.random.seed(123) class TestGaussFrozen(unittest.TestCase): @classmethod def setUpClass(self): np.random.seed(123) def testGaussFrozen(self): stocks = np.loadtxt(dataDir + 'stocks.csv', delimiter=',') x = stocks[:, 0] y = stocks[:, 1] stockModel = PairCopula(x, y) stockModel.copulaTournament(verbosity=0) self.assertTrue(stockModel.copulaModel.name == "gauss") self.assertTrue(stockModel.copulaParams[0] == "gauss") self.assertAlmostEqual(stockModel.copulaParams[1][0], 0.73874003, 4) frzU, frzV = stockModel.copulaModel.sample(40000) setU, setV = stockModel.copulaModel.sample(40000, (0.73874003,)) frzModel = PairCopula(frzU, frzV) setModel = PairCopula(setU, setV) frzKtau, fp = frzModel.empKTau() setKtau, sp = setModel.empKTau() self.assertAlmostEqual(frzKtau, setKtau, delta=0.02) self.assertAlmostEqual(fp, sp, delta=0.02) setU2, setV2 = stockModel.copulaModel.sample(20000, (0.3,)) setModel2 = PairCopula(setU2, setV2) setKtau2, sp2 = setModel2.empKTau() self.assertTrue(setKtau2 != setKtau) self.assertTrue(abs(setKtau2 - setKtau) > 0.2) def testFrankFrozen(self): np.random.seed(123) stocks = np.loadtxt(dataDir + 'stocks.csv', delimiter=',') x = stocks[:, 0] y = stocks[:, 1] stockModel = PairCopula(x, y, family={'frank': 0, }) stockModel.copulaTournament(verbosity=0) frzU, frzV = stockModel.copulaModel.sample(40000) setU, setV = stockModel.copulaModel.sample(40000, *stockModel.copulaParams[1]) frzModel = PairCopula(frzU, frzV) setModel = PairCopula(setU, setV) frzKtau, fp = frzModel.empKTau() setKtau, sp = setModel.empKTau() self.assertAlmostEqual(frzKtau, setKtau, delta=0.02) self.assertAlmostEqual(fp, sp, delta=0.02)
true
true
f7259984a8976fd2deb189a6e90d3aaeabfca3d9
1,402
py
Python
source/appModules/totalcmd.py
oleguldberg/nvda
05f55ff146ef8ba481a2de4f1bcf187200474cea
[ "bzip2-1.0.6" ]
1,592
2015-11-10T12:05:44.000Z
2022-03-31T11:50:40.000Z
source/appModules/totalcmd.py
oleguldberg/nvda
05f55ff146ef8ba481a2de4f1bcf187200474cea
[ "bzip2-1.0.6" ]
9,479
2015-11-10T20:56:48.000Z
2022-03-31T23:51:30.000Z
source/appModules/totalcmd.py
oleguldberg/nvda
05f55ff146ef8ba481a2de4f1bcf187200474cea
[ "bzip2-1.0.6" ]
682
2015-11-10T11:19:23.000Z
2022-03-31T07:51:29.000Z
#appModules/totalcmd.py #A part of NonVisual Desktop Access (NVDA) #Copyright (C) 2006-2012 NVDA Contributors #This file is covered by the GNU General Public License. #See the file COPYING for more details. import appModuleHandler from NVDAObjects.IAccessible import IAccessible import speech import controlTypes import ui oldActivePannel=0 class AppModule(appModuleHandler.AppModule): def chooseNVDAObjectOverlayClasses(self, obj, clsList): if obj.windowClassName in ("TMyListBox", "TMyListBox.UnicodeClass"): clsList.insert(0, TCList) class TCList(IAccessible): def event_gainFocus(self): global oldActivePannel if oldActivePannel !=self.windowControlID: oldActivePannel=self.windowControlID obj=self while obj and obj.parent and obj.parent.windowClassName!="TTOTAL_CMD": obj=obj.parent counter=0 while obj and obj.previous and obj.windowClassName!="TPanel": obj=obj.previous if obj.windowClassName!="TDrivePanel": counter+=1 if counter==2: ui.message(_("left")) else: ui.message(_("right")) super(TCList,self).event_gainFocus() def reportFocus(self): if self.name: speakList=[] if controlTypes.State.SELECTED in self.states: speakList.append(controlTypes.State.SELECTED.displayString) speakList.append(self.name.split("\\")[-1]) speech.speakMessage(" ".join(speakList)) else: super(TCList,self).reportFocus()
28.04
73
0.752496
import appModuleHandler from NVDAObjects.IAccessible import IAccessible import speech import controlTypes import ui oldActivePannel=0 class AppModule(appModuleHandler.AppModule): def chooseNVDAObjectOverlayClasses(self, obj, clsList): if obj.windowClassName in ("TMyListBox", "TMyListBox.UnicodeClass"): clsList.insert(0, TCList) class TCList(IAccessible): def event_gainFocus(self): global oldActivePannel if oldActivePannel !=self.windowControlID: oldActivePannel=self.windowControlID obj=self while obj and obj.parent and obj.parent.windowClassName!="TTOTAL_CMD": obj=obj.parent counter=0 while obj and obj.previous and obj.windowClassName!="TPanel": obj=obj.previous if obj.windowClassName!="TDrivePanel": counter+=1 if counter==2: ui.message(_("left")) else: ui.message(_("right")) super(TCList,self).event_gainFocus() def reportFocus(self): if self.name: speakList=[] if controlTypes.State.SELECTED in self.states: speakList.append(controlTypes.State.SELECTED.displayString) speakList.append(self.name.split("\\")[-1]) speech.speakMessage(" ".join(speakList)) else: super(TCList,self).reportFocus()
true
true
f7259a6ab0d551d886b30961db6d5aff508bdecb
772
py
Python
scripts/plotting/reprocessed_kccg_samples_pca/main.py
populationgenomics/ancestry
faf6fd4bc3a1f8b2a2adb7e59cf584d4bfdf79e6
[ "MIT" ]
null
null
null
scripts/plotting/reprocessed_kccg_samples_pca/main.py
populationgenomics/ancestry
faf6fd4bc3a1f8b2a2adb7e59cf584d4bfdf79e6
[ "MIT" ]
21
2021-03-09T06:35:59.000Z
2022-02-21T22:56:15.000Z
scripts/plotting/reprocessed_kccg_samples_pca/main.py
populationgenomics/ancestry
faf6fd4bc3a1f8b2a2adb7e59cf584d4bfdf79e6
[ "MIT" ]
null
null
null
"""Entry point for the analysis runner.""" import os import sys import hail as hl import hailtop.batch as hb from analysis_runner import dataproc OUTPUT = os.getenv('OUTPUT') assert OUTPUT hl.init(default_reference='GRCh38') POP = sys.argv[1] if len(sys.argv) > 1 else 'nfe' service_backend = hb.ServiceBackend( billing_project=os.getenv('HAIL_BILLING_PROJECT'), bucket=os.getenv('HAIL_BUCKET') ) batch = hb.Batch(name=f'{POP} kccg-reprocessed', backend=service_backend) dataproc.hail_dataproc_job( batch, f'project_reprocessed_kccg_samples.py --output={OUTPUT} --pop {POP}', max_age='5h', packages=['click', 'selenium'], init=['gs://cpg-reference/hail_dataproc/install_phantomjs.sh'], job_name=f'{POP}-kccg-reprocessed', ) batch.run()
24.125
86
0.727979
import os import sys import hail as hl import hailtop.batch as hb from analysis_runner import dataproc OUTPUT = os.getenv('OUTPUT') assert OUTPUT hl.init(default_reference='GRCh38') POP = sys.argv[1] if len(sys.argv) > 1 else 'nfe' service_backend = hb.ServiceBackend( billing_project=os.getenv('HAIL_BILLING_PROJECT'), bucket=os.getenv('HAIL_BUCKET') ) batch = hb.Batch(name=f'{POP} kccg-reprocessed', backend=service_backend) dataproc.hail_dataproc_job( batch, f'project_reprocessed_kccg_samples.py --output={OUTPUT} --pop {POP}', max_age='5h', packages=['click', 'selenium'], init=['gs://cpg-reference/hail_dataproc/install_phantomjs.sh'], job_name=f'{POP}-kccg-reprocessed', ) batch.run()
true
true
f7259b305c1ad5cae4a9beae16737854d8e966c3
7,804
py
Python
botstory/ast/story_context/__init__.py
botstory/bot-story
9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3
[ "MIT" ]
5
2017-01-14T13:42:13.000Z
2021-07-27T21:52:04.000Z
botstory/ast/story_context/__init__.py
botstory/bot-story
9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3
[ "MIT" ]
235
2016-11-07T23:33:28.000Z
2018-03-13T11:27:33.000Z
botstory/ast/story_context/__init__.py
hyzhak/bot-story
9c5b2fc7f7a14dbd467d70f60d5ba855ef89dac3
[ "MIT" ]
5
2017-01-14T13:42:14.000Z
2020-11-06T08:33:20.000Z
from botstory import matchers, utils from botstory.ast import callable, forking, loop from botstory.ast.story_context import reducers from botstory.utils import advanced_json_encoder import numbers import logging import uuid logger = logging.getLogger(__name__) class MissedStoryPart(Exception): pass class StoryContext: def __init__(self, message, library, matched=False, waiting_for=None, parent_uid=None): self.uid = str(uuid.uuid4()) self.parent_uid = parent_uid self.library = library # whether message was passed validation and was matched one story self.matched = matched self.message = message self.waiting_for = waiting_for def clone(self): return StoryContext(library=self.library, matched=self.matched, message=self.message, parent_uid=self.uid, waiting_for=self.waiting_for, ) def compiled_story(self): if self.is_empty_stack(): return self.library.get_global_story(self.message) else: return self.library.get_story_by_topic(self.stack_tail()['topic'], stack=self.stack()[:-1]) def could_scope_out(self): """ could bubble up from current scope :return: """ return not self.waiting_for or \ isinstance(self.waiting_for, callable.EndOfStory) or \ self.is_breaking_a_loop() def current_step(self): return self.stack_tail()['step'] def does_it_match_any_story(self): return self.compiled_story() is not None and not self.matched def get_child_story(self): logger.debug('# get_child_story') """ try child story that match message and get scope of it :return: """ story_loop = self.compiled_story() if hasattr(story_loop, 'children_matcher') and not self.matched: return self.get_story_scope_child(story_loop) story_part = self.get_current_story_part() if not hasattr(story_part, 'get_child_by_validation_result'): logger.debug('# does not have get_child_by_validation_result') return None if isinstance(self.waiting_for, forking.SwitchOnValue): logger.debug('# switch on value') return story_part.get_child_by_validation_result(self.waiting_for.value) # for some base classes we could try validate result direct child_story = story_part.get_child_by_validation_result(self.waiting_for) if child_story: logger.debug('# child_story') logger.debug(child_story) return child_story stack_tail = self.stack_tail() if stack_tail['data'] is not None and not self.matched: validator = matchers.deserialize(stack_tail['data']) logger.debug('# validator') logger.debug(validator) logger.debug('# self.message') logger.debug(self.message) validation_result = validator.validate(self.message) logger.debug('# validation_result') logger.debug(validation_result) res = story_part.get_child_by_validation_result(validation_result) logger.debug('# res') logger.debug(res) # or we validate message # but can't find right child story # maybe we should use independent validators for each story here if res is None: return self.get_story_scope_child(story_part) else: return res return None def get_story_scope_child(self, story_part): logger.debug('# get_story_scope_child') validator = story_part.children_matcher() logger.debug('# validator') logger.debug(validator) logger.debug('# self.message') logger.debug(self.message) topic = validator.validate(self.message) # if topic == None: # we inside story loop scope # but got message that doesn't match # any local stories logger.debug('# topic {}'.format(topic)) return story_part.by_topic(topic) def get_current_story_part(self): compiled_story = self.compiled_story() if not compiled_story: return None try: return compiled_story.story_line[self.current_step()] except IndexError: return None def get_user_data(self): return get_user_data(self.message) def has_child_story(self): return self.get_child_story() is not None def is_breaking_a_loop(self): return isinstance(self.waiting_for, loop.BreakLoop) def is_empty_stack(self): return len(self.stack()) == 0 def is_end_of_story(self): compiled_story = self.compiled_story() if not compiled_story: return True return self.current_step() >= len(compiled_story.story_line) def is_scope_level(self): return isinstance(self.compiled_story(), loop.StoriesLoopNode) def is_scope_level_part(self): return isinstance(self.get_current_story_part(), loop.StoriesLoopNode) def is_tail_of_story(self): compiled_story = self.compiled_story() if not compiled_story: return True return self.current_step() >= len(compiled_story.story_line) - 1 def is_waiting_for_input(self): """ could make one step further :return: """ return self.waiting_for and \ not isinstance(self.waiting_for, forking.SwitchOnValue) and \ not is_base_type(self.waiting_for) def stack(self): return self.message['session']['stack'] def stack_tail(self): stack = self.stack() if len(stack) == 0: raise MissedStoryPart() return stack[-1] def to_json(self): return { 'uid': self.uid, 'parent_uid': self.parent_uid, 'matched': self.matched, 'message': self.message, 'waiting_for': str(self.waiting_for), } def user(self): return self.message['user'] def __repr__(self): try: return advanced_json_encoder.AdvancedJSONEncoder().encode(self.to_json()) except Exception as err: logger.warn(err) logger.warn('fail to dump json of message {} ' 'waiting for {}'.format(str(self.message), str(self.waiting_for))) def is_base_type(value): return isinstance(value, str) or isinstance(value, numbers.Number) def clean_message_data(ctx): return utils.safe_set(ctx, 'session', 'data', 'message', {}) def get_user_data(ctx): return ctx['session']['data'] def get_message_data(ctx, *args, **kwargs): return utils.safe_get(get_user_data(ctx)['message'], *args, **kwargs) def get_message_attachment(ctx, attachment_type): logger.debug('# get_message_data(ctx)') logger.debug(get_message_data(ctx)) attachment_list = get_message_data(ctx, 'attachments') if attachment_list is None or len(attachment_list) == 0: return None attachment_list_of_type = [a for a in attachment_list if a['type'] == attachment_type] if attachment_list_of_type is None or len(attachment_list_of_type) == 0: return None return attachment_list_of_type[0] def set_user_data(ctx, data): ctx['session']['data'] = { **get_user_data(ctx), **data, } return ctx def set_message_data(ctx, *args): return utils.safe_set(ctx, 'session', 'data', 'message', *args) __all__ = [get_user_data, reducers, set_user_data, StoryContext]
32.381743
103
0.631471
from botstory import matchers, utils from botstory.ast import callable, forking, loop from botstory.ast.story_context import reducers from botstory.utils import advanced_json_encoder import numbers import logging import uuid logger = logging.getLogger(__name__) class MissedStoryPart(Exception): pass class StoryContext: def __init__(self, message, library, matched=False, waiting_for=None, parent_uid=None): self.uid = str(uuid.uuid4()) self.parent_uid = parent_uid self.library = library self.matched = matched self.message = message self.waiting_for = waiting_for def clone(self): return StoryContext(library=self.library, matched=self.matched, message=self.message, parent_uid=self.uid, waiting_for=self.waiting_for, ) def compiled_story(self): if self.is_empty_stack(): return self.library.get_global_story(self.message) else: return self.library.get_story_by_topic(self.stack_tail()['topic'], stack=self.stack()[:-1]) def could_scope_out(self): return not self.waiting_for or \ isinstance(self.waiting_for, callable.EndOfStory) or \ self.is_breaking_a_loop() def current_step(self): return self.stack_tail()['step'] def does_it_match_any_story(self): return self.compiled_story() is not None and not self.matched def get_child_story(self): logger.debug('# get_child_story') story_loop = self.compiled_story() if hasattr(story_loop, 'children_matcher') and not self.matched: return self.get_story_scope_child(story_loop) story_part = self.get_current_story_part() if not hasattr(story_part, 'get_child_by_validation_result'): logger.debug('# does not have get_child_by_validation_result') return None if isinstance(self.waiting_for, forking.SwitchOnValue): logger.debug('# switch on value') return story_part.get_child_by_validation_result(self.waiting_for.value) child_story = story_part.get_child_by_validation_result(self.waiting_for) if child_story: logger.debug('# child_story') logger.debug(child_story) return child_story stack_tail = self.stack_tail() if stack_tail['data'] is not None and not self.matched: validator = matchers.deserialize(stack_tail['data']) logger.debug('# validator') logger.debug(validator) logger.debug('# self.message') logger.debug(self.message) validation_result = validator.validate(self.message) logger.debug('# validation_result') logger.debug(validation_result) res = story_part.get_child_by_validation_result(validation_result) logger.debug('# res') logger.debug(res) # maybe we should use independent validators for each story here if res is None: return self.get_story_scope_child(story_part) else: return res return None def get_story_scope_child(self, story_part): logger.debug(' validator = story_part.children_matcher() logger.debug(' logger.debug(validator) logger.debug(' logger.debug(self.message) topic = validator.validate(self.message) # if topic == None: # we inside story loop scope # but got message that doesn't match logger.debug('# topic {}'.format(topic)) return story_part.by_topic(topic) def get_current_story_part(self): compiled_story = self.compiled_story() if not compiled_story: return None try: return compiled_story.story_line[self.current_step()] except IndexError: return None def get_user_data(self): return get_user_data(self.message) def has_child_story(self): return self.get_child_story() is not None def is_breaking_a_loop(self): return isinstance(self.waiting_for, loop.BreakLoop) def is_empty_stack(self): return len(self.stack()) == 0 def is_end_of_story(self): compiled_story = self.compiled_story() if not compiled_story: return True return self.current_step() >= len(compiled_story.story_line) def is_scope_level(self): return isinstance(self.compiled_story(), loop.StoriesLoopNode) def is_scope_level_part(self): return isinstance(self.get_current_story_part(), loop.StoriesLoopNode) def is_tail_of_story(self): compiled_story = self.compiled_story() if not compiled_story: return True return self.current_step() >= len(compiled_story.story_line) - 1 def is_waiting_for_input(self): return self.waiting_for and \ not isinstance(self.waiting_for, forking.SwitchOnValue) and \ not is_base_type(self.waiting_for) def stack(self): return self.message['session']['stack'] def stack_tail(self): stack = self.stack() if len(stack) == 0: raise MissedStoryPart() return stack[-1] def to_json(self): return { 'uid': self.uid, 'parent_uid': self.parent_uid, 'matched': self.matched, 'message': self.message, 'waiting_for': str(self.waiting_for), } def user(self): return self.message['user'] def __repr__(self): try: return advanced_json_encoder.AdvancedJSONEncoder().encode(self.to_json()) except Exception as err: logger.warn(err) logger.warn('fail to dump json of message {} ' 'waiting for {}'.format(str(self.message), str(self.waiting_for))) def is_base_type(value): return isinstance(value, str) or isinstance(value, numbers.Number) def clean_message_data(ctx): return utils.safe_set(ctx, 'session', 'data', 'message', {}) def get_user_data(ctx): return ctx['session']['data'] def get_message_data(ctx, *args, **kwargs): return utils.safe_get(get_user_data(ctx)['message'], *args, **kwargs) def get_message_attachment(ctx, attachment_type): logger.debug('# get_message_data(ctx)') logger.debug(get_message_data(ctx)) attachment_list = get_message_data(ctx, 'attachments') if attachment_list is None or len(attachment_list) == 0: return None attachment_list_of_type = [a for a in attachment_list if a['type'] == attachment_type] if attachment_list_of_type is None or len(attachment_list_of_type) == 0: return None return attachment_list_of_type[0] def set_user_data(ctx, data): ctx['session']['data'] = { **get_user_data(ctx), **data, } return ctx def set_message_data(ctx, *args): return utils.safe_set(ctx, 'session', 'data', 'message', *args) __all__ = [get_user_data, reducers, set_user_data, StoryContext]
true
true
f7259b4e1f74cc2b78fa2fe6a806234b94c86cc1
6,467
py
Python
scd_manager.py
gavinlive/scd-data-manager
570b67bacb4bf17f0b49c5875933f233ddd76e6c
[ "MIT" ]
null
null
null
scd_manager.py
gavinlive/scd-data-manager
570b67bacb4bf17f0b49c5875933f233ddd76e6c
[ "MIT" ]
1
2020-06-09T08:48:01.000Z
2020-06-09T09:23:07.000Z
scd_manager.py
gavinlive/scd-data-manager
570b67bacb4bf17f0b49c5875933f233ddd76e6c
[ "MIT" ]
null
null
null
import os, sys import pydicom as pyd import matplotlib.pyplot as plt import collections import pandas as pd PatientRecord = collections.namedtuple('PatientRecord', ['patient_id', 'image_folder', 'original_id', 'gender', 'age', 'pathology', 'all_scans', 'scans', 'scans_list', 'scans_total']) PatientScans = collections.namedtuple('PatientScans', ['files', 'prefixes', 'suffixes', 'total_number']) DataRecord = collections.namedtuple('DataRecord', ['dicom_path', 'contour_path']) class DataManager(object): def __config__(self): self.path = '.' self.patient_info_path = self.path + '/scd_patientdata.csv' self.meta_data_path = self.path + '/scd_patientdata.csv' self.images_path = self.path + '/SCD_DeidentifiedImages/' self.segmentations_path = self.path + '/SCD_ManualContours/' def __init__(self): self.__config__() self.__load_patient_info() self._patients = next(os.walk(self.images_path))[1] print(self._patients) self.__get_patient_images() if(self.__verify_scan_sets()==True): print("verified all scan sets") if(self.__verify_scan_numbers()==True): print("verified all scan numbers") def __import_contours(self, patient, suffixes, files): path = self.segmentations_path + patient + '/contours-manual/IRCCI-expert/' records_list=[] numbers_list = [] for file in os.listdir(path): if file.endswith(".txt"): f=file.split("-") scan_number = int(f[2]) f=f[3] if((f=="icontour") and (scan_number in suffixes)): contour_filepath = path +'/' + file indx = suffixes.index(scan_number) dicom_filepath = files[indx] records_list.append(DataRecord(dicom_filepath, contour_filepath)) numbers_list.append(scan_number) return records_list,numbers_list,len(records_list) def __load_patient_info(self): self.patient_info = pd.read_csv(self.patient_info_path) def __get_patient_info(self, patient): this = self.patient_info[self.patient_info['OriginalID']==patient].values.tolist()[0] print(this) cols = self.patient_info.columns.values.tolist() toget = ['Gender', 'Age', 'PathologyID', 'Pathology'] toreturn=[] for t in toget: indx = cols.index(t) toreturn.append(this[indx]) return toreturn def depre__import_contours(self): for patient in self._patients: path = self.segmentations_path + patient + '/contours-manual/IRCCI-expert/' records_list=[] numbers_list = [] for file in os.listdir(path): if file.endswith(".txt"): f=file.split("-") scan_number = f[2] f=f[3] if((f=="icontour") and (scan_number in self.patient[patient].all_scans.suffixes)): contour_filepath = path +'/' + file indx = self.patient[patient].all_scans.suffixes.indx(scan_number) dicom_filepath = self.patient[patient].all_scans.files[indx] records_list.append(DataRecord(dicom_filepath, contour_filepath)) numbers_list.append(scan_number) self.patient[patient].scans=records_list self.patient[patient].scans_list=numbers_list self.patient[patient].scans_total = len(records_list) def __verify_scan_sets(self): for patient in self._patients: prefix_list = self.patient[patient].all_scans.prefixes b = [(x==1) for x in prefix_list] if False in b: print('Fault for patient: %s' % patient) return False return True def __verify_scan_numbers(self): for patient in self._patients: prefix_list = self.patient[patient].all_scans.suffixes b = [(prefix_list.count(x)==1) for x in prefix_list] if False in b: print('Fault for patient: %s' % patient) return False return True def __get_patient_images(self): self.patient = {} for patient in self._patients: #list_of_image_folders_for_patient = next(os.walk(self.images_path + patient))[1] #list_of_image_folders_for_patient_full_path = [self.images_path + patient + '/' + x for x in list_of_image_folders_for_patient] #self.patient[patient] = {"patient_id": patient, "images": list_of_image_folders_for_patient, "original_id": "", #"gender": "", "age": 0, "pathology": "" } def get_files(list_of_folders): file_list = [] for folder in list_of_folders: for file in os.listdir(folder): if file.endswith(".dcm"): file_list.append(folder +'/' + file) return file_list def get_prefix_suffix(files): prefixes = [] suffixes = [] for file in files: f=file.split("-") f=f[-2::] f[1] = f[1].split(".")[0] prefixes.append(int(f[0])) suffixes.append(int(f[1])) return prefixes, suffixes files = get_files([self.images_path+patient+'/DICOM']) prefixes, suffixes = get_prefix_suffix(files) this_patient_scan_set = PatientScans(files, prefixes, suffixes, len(files)) scans, scans_list, scans_total = self.__import_contours(patient, suffixes, files) gender, age, pathologyID, _ = self.__get_patient_info(patient) this_patient_record = PatientRecord(patient_id=patient, image_folder=self.images_path + patient, original_id="", gender=gender, age=age, pathology=pathologyID, all_scans=this_patient_scan_set, scans=scans, scans_list=scans_list, scans_total=scans_total) self.patient[patient] = this_patient_record def total_examples(self): count=0 for patient in self._patients: count += self.patient[patient].scans_total return count def __call__(self, patient,scan_number): return self.patient[patient].all_scans.files[scan_number]
44.6
183
0.598113
import os, sys import pydicom as pyd import matplotlib.pyplot as plt import collections import pandas as pd PatientRecord = collections.namedtuple('PatientRecord', ['patient_id', 'image_folder', 'original_id', 'gender', 'age', 'pathology', 'all_scans', 'scans', 'scans_list', 'scans_total']) PatientScans = collections.namedtuple('PatientScans', ['files', 'prefixes', 'suffixes', 'total_number']) DataRecord = collections.namedtuple('DataRecord', ['dicom_path', 'contour_path']) class DataManager(object): def __config__(self): self.path = '.' self.patient_info_path = self.path + '/scd_patientdata.csv' self.meta_data_path = self.path + '/scd_patientdata.csv' self.images_path = self.path + '/SCD_DeidentifiedImages/' self.segmentations_path = self.path + '/SCD_ManualContours/' def __init__(self): self.__config__() self.__load_patient_info() self._patients = next(os.walk(self.images_path))[1] print(self._patients) self.__get_patient_images() if(self.__verify_scan_sets()==True): print("verified all scan sets") if(self.__verify_scan_numbers()==True): print("verified all scan numbers") def __import_contours(self, patient, suffixes, files): path = self.segmentations_path + patient + '/contours-manual/IRCCI-expert/' records_list=[] numbers_list = [] for file in os.listdir(path): if file.endswith(".txt"): f=file.split("-") scan_number = int(f[2]) f=f[3] if((f=="icontour") and (scan_number in suffixes)): contour_filepath = path +'/' + file indx = suffixes.index(scan_number) dicom_filepath = files[indx] records_list.append(DataRecord(dicom_filepath, contour_filepath)) numbers_list.append(scan_number) return records_list,numbers_list,len(records_list) def __load_patient_info(self): self.patient_info = pd.read_csv(self.patient_info_path) def __get_patient_info(self, patient): this = self.patient_info[self.patient_info['OriginalID']==patient].values.tolist()[0] print(this) cols = self.patient_info.columns.values.tolist() toget = ['Gender', 'Age', 'PathologyID', 'Pathology'] toreturn=[] for t in toget: indx = cols.index(t) toreturn.append(this[indx]) return toreturn def depre__import_contours(self): for patient in self._patients: path = self.segmentations_path + patient + '/contours-manual/IRCCI-expert/' records_list=[] numbers_list = [] for file in os.listdir(path): if file.endswith(".txt"): f=file.split("-") scan_number = f[2] f=f[3] if((f=="icontour") and (scan_number in self.patient[patient].all_scans.suffixes)): contour_filepath = path +'/' + file indx = self.patient[patient].all_scans.suffixes.indx(scan_number) dicom_filepath = self.patient[patient].all_scans.files[indx] records_list.append(DataRecord(dicom_filepath, contour_filepath)) numbers_list.append(scan_number) self.patient[patient].scans=records_list self.patient[patient].scans_list=numbers_list self.patient[patient].scans_total = len(records_list) def __verify_scan_sets(self): for patient in self._patients: prefix_list = self.patient[patient].all_scans.prefixes b = [(x==1) for x in prefix_list] if False in b: print('Fault for patient: %s' % patient) return False return True def __verify_scan_numbers(self): for patient in self._patients: prefix_list = self.patient[patient].all_scans.suffixes b = [(prefix_list.count(x)==1) for x in prefix_list] if False in b: print('Fault for patient: %s' % patient) return False return True def __get_patient_images(self): self.patient = {} for patient in self._patients: def get_files(list_of_folders): file_list = [] for folder in list_of_folders: for file in os.listdir(folder): if file.endswith(".dcm"): file_list.append(folder +'/' + file) return file_list def get_prefix_suffix(files): prefixes = [] suffixes = [] for file in files: f=file.split("-") f=f[-2::] f[1] = f[1].split(".")[0] prefixes.append(int(f[0])) suffixes.append(int(f[1])) return prefixes, suffixes files = get_files([self.images_path+patient+'/DICOM']) prefixes, suffixes = get_prefix_suffix(files) this_patient_scan_set = PatientScans(files, prefixes, suffixes, len(files)) scans, scans_list, scans_total = self.__import_contours(patient, suffixes, files) gender, age, pathologyID, _ = self.__get_patient_info(patient) this_patient_record = PatientRecord(patient_id=patient, image_folder=self.images_path + patient, original_id="", gender=gender, age=age, pathology=pathologyID, all_scans=this_patient_scan_set, scans=scans, scans_list=scans_list, scans_total=scans_total) self.patient[patient] = this_patient_record def total_examples(self): count=0 for patient in self._patients: count += self.patient[patient].scans_total return count def __call__(self, patient,scan_number): return self.patient[patient].all_scans.files[scan_number]
true
true
f7259c70b3269cebc23b86955129c52126b5c426
587
py
Python
Python1/python1Homework/input_counter1.py
ceeblet/OST_PythonCertificationTrack
042e0ce964bc88b3f4132dcbd7e06c5f504eae34
[ "MIT" ]
null
null
null
Python1/python1Homework/input_counter1.py
ceeblet/OST_PythonCertificationTrack
042e0ce964bc88b3f4132dcbd7e06c5f504eae34
[ "MIT" ]
null
null
null
Python1/python1Homework/input_counter1.py
ceeblet/OST_PythonCertificationTrack
042e0ce964bc88b3f4132dcbd7e06c5f504eae34
[ "MIT" ]
null
null
null
#!/usr/local/bin/python3 """input_counter.py""" myset = set() mydict = {} mysetlength = len(myset) while True: text = input("Enter a line (or Enter to quit): ") if not text: break for punc in ",?;.": text = text.replace(punc, "") textwords = (text.lower().split()) for word in textwords: myset.add(word) newsetlength = len(myset) if newsetlength > mysetlength: mydict[word] = newsetlength mysetlength = newsetlength for word in (mydict.keys()): print(word, mydict[word]) print("Finished")
26.681818
53
0.584327
myset = set() mydict = {} mysetlength = len(myset) while True: text = input("Enter a line (or Enter to quit): ") if not text: break for punc in ",?;.": text = text.replace(punc, "") textwords = (text.lower().split()) for word in textwords: myset.add(word) newsetlength = len(myset) if newsetlength > mysetlength: mydict[word] = newsetlength mysetlength = newsetlength for word in (mydict.keys()): print(word, mydict[word]) print("Finished")
true
true
f7259ef31d09ee215158684c34454fabb4e5926d
614
py
Python
aws-auth0-auth/helloWorld.py
skarlekar/ms-auth-tutorials
0de172817e54533be93700de19028cfa8757861f
[ "MIT" ]
null
null
null
aws-auth0-auth/helloWorld.py
skarlekar/ms-auth-tutorials
0de172817e54533be93700de19028cfa8757861f
[ "MIT" ]
1
2021-06-01T21:41:36.000Z
2021-06-01T21:41:36.000Z
aws-auth0-auth/helloWorld.py
skarlekar/ms-auth-tutorials
0de172817e54533be93700de19028cfa8757861f
[ "MIT" ]
1
2017-10-26T15:08:40.000Z
2017-10-26T15:08:40.000Z
"""Simple helloWorld service.""" import json def sayHello(event, context): """Return a message in the response body.""" print('Event is: {}'.format(json.dumps(event))) body = { "message": "Hello! Your Auth0 authorized function executed successfully!" } response = { "statusCode": 200, "body": json.dumps(body) } return response # Use this code if you don't use the http event with the LAMBDA-PROXY # integration """ return { "message": "Go Serverless v1.0! Your function executed successfully!", "event": event } """
22.740741
81
0.599349
import json def sayHello(event, context): print('Event is: {}'.format(json.dumps(event))) body = { "message": "Hello! Your Auth0 authorized function executed successfully!" } response = { "statusCode": 200, "body": json.dumps(body) } return response # integration
true
true
f7259f1cbf5a3448b4489597dc832795cc8d1b52
9,120
py
Python
fuji_server/models/data_provenance.py
vemonet/fuji
92aabcb58d76a58981c677bcf0da8e57309c6096
[ "MIT" ]
null
null
null
fuji_server/models/data_provenance.py
vemonet/fuji
92aabcb58d76a58981c677bcf0da8e57309c6096
[ "MIT" ]
null
null
null
fuji_server/models/data_provenance.py
vemonet/fuji
92aabcb58d76a58981c677bcf0da8e57309c6096
[ "MIT" ]
null
null
null
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from fuji_server.models.base_model_ import Model from fuji_server.models.data_provenance_output import DataProvenanceOutput # noqa: F401,E501 from fuji_server.models.debug import Debug # noqa: F401,E501 from fuji_server.models.fair_result_common import FAIRResultCommon # noqa: F401,E501 from fuji_server.models.fair_result_common_score import FAIRResultCommonScore # noqa: F401,E501 from fuji_server.models.fair_result_evaluation_criterium import FAIRResultEvaluationCriterium # noqa: F401,E501 from fuji_server import util class DataProvenance(Model): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, id: int=None, metric_identifier: str=None, metric_name: str=None, metric_tests: Dict[str, FAIRResultEvaluationCriterium]=None, test_status: str='fail', score: FAIRResultCommonScore=None, maturity: str='incomplete', output: DataProvenanceOutput=None, test_debug: Debug=None): # noqa: E501 """DataProvenance - a model defined in Swagger :param id: The id of this DataProvenance. # noqa: E501 :type id: int :param metric_identifier: The metric_identifier of this DataProvenance. # noqa: E501 :type metric_identifier: str :param metric_name: The metric_name of this DataProvenance. # noqa: E501 :type metric_name: str :param metric_tests: The metric_tests of this DataProvenance. # noqa: E501 :type metric_tests: Dict[str, FAIRResultEvaluationCriterium] :param test_status: The test_status of this DataProvenance. # noqa: E501 :type test_status: str :param score: The score of this DataProvenance. # noqa: E501 :type score: FAIRResultCommonScore :param maturity: The maturity of this DataProvenance. # noqa: E501 :type maturity: str :param output: The output of this DataProvenance. # noqa: E501 :type output: DataProvenanceOutput :param test_debug: The test_debug of this DataProvenance. # noqa: E501 :type test_debug: Debug """ self.swagger_types = { 'id': int, 'metric_identifier': str, 'metric_name': str, 'metric_tests': Dict[str, FAIRResultEvaluationCriterium], 'test_status': str, 'score': FAIRResultCommonScore, 'maturity': str, 'output': DataProvenanceOutput, 'test_debug': Debug } self.attribute_map = { 'id': 'id', 'metric_identifier': 'metric_identifier', 'metric_name': 'metric_name', 'metric_tests': 'metric_tests', 'test_status': 'test_status', 'score': 'score', 'maturity': 'maturity', 'output': 'output', 'test_debug': 'test_debug' } self._id = id self._metric_identifier = metric_identifier self._metric_name = metric_name self._metric_tests = metric_tests self._test_status = test_status self._score = score self._maturity = maturity self._output = output self._test_debug = test_debug @classmethod def from_dict(cls, dikt) -> 'DataProvenance': """Returns the dict as a model :param dikt: A dict. :type: dict :return: The DataProvenance of this DataProvenance. # noqa: E501 :rtype: DataProvenance """ return util.deserialize_model(dikt, cls) @property def id(self) -> int: """Gets the id of this DataProvenance. :return: The id of this DataProvenance. :rtype: int """ return self._id @id.setter def id(self, id: int): """Sets the id of this DataProvenance. :param id: The id of this DataProvenance. :type id: int """ if id is None: raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501 self._id = id @property def metric_identifier(self) -> str: """Gets the metric_identifier of this DataProvenance. :return: The metric_identifier of this DataProvenance. :rtype: str """ return self._metric_identifier @metric_identifier.setter def metric_identifier(self, metric_identifier: str): """Sets the metric_identifier of this DataProvenance. :param metric_identifier: The metric_identifier of this DataProvenance. :type metric_identifier: str """ if metric_identifier is None: raise ValueError("Invalid value for `metric_identifier`, must not be `None`") # noqa: E501 self._metric_identifier = metric_identifier @property def metric_name(self) -> str: """Gets the metric_name of this DataProvenance. :return: The metric_name of this DataProvenance. :rtype: str """ return self._metric_name @metric_name.setter def metric_name(self, metric_name: str): """Sets the metric_name of this DataProvenance. :param metric_name: The metric_name of this DataProvenance. :type metric_name: str """ if metric_name is None: raise ValueError("Invalid value for `metric_name`, must not be `None`") # noqa: E501 self._metric_name = metric_name @property def metric_tests(self) -> Dict[str, FAIRResultEvaluationCriterium]: """Gets the metric_tests of this DataProvenance. :return: The metric_tests of this DataProvenance. :rtype: Dict[str, FAIRResultEvaluationCriterium] """ return self._metric_tests @metric_tests.setter def metric_tests(self, metric_tests: Dict[str, FAIRResultEvaluationCriterium]): """Sets the metric_tests of this DataProvenance. :param metric_tests: The metric_tests of this DataProvenance. :type metric_tests: Dict[str, FAIRResultEvaluationCriterium] """ self._metric_tests = metric_tests @property def test_status(self) -> str: """Gets the test_status of this DataProvenance. :return: The test_status of this DataProvenance. :rtype: str """ return self._test_status @test_status.setter def test_status(self, test_status: str): """Sets the test_status of this DataProvenance. :param test_status: The test_status of this DataProvenance. :type test_status: str """ allowed_values = ["pass", "fail", "indeterminate"] # noqa: E501 if test_status not in allowed_values: raise ValueError( "Invalid value for `test_status` ({0}), must be one of {1}" .format(test_status, allowed_values) ) self._test_status = test_status @property def score(self) -> FAIRResultCommonScore: """Gets the score of this DataProvenance. :return: The score of this DataProvenance. :rtype: FAIRResultCommonScore """ return self._score @score.setter def score(self, score: FAIRResultCommonScore): """Sets the score of this DataProvenance. :param score: The score of this DataProvenance. :type score: FAIRResultCommonScore """ if score is None: raise ValueError("Invalid value for `score`, must not be `None`") # noqa: E501 self._score = score @property def maturity(self) -> str: """Gets the maturity of this DataProvenance. :return: The maturity of this DataProvenance. :rtype: str """ return self._maturity @maturity.setter def maturity(self, maturity: int): """Sets the maturity of this Uniqueness. :param maturity: The maturity of this Uniqueness. :type maturity: int """ self._maturity = maturity @property def output(self) -> DataProvenanceOutput: """Gets the output of this DataProvenance. :return: The output of this DataProvenance. :rtype: DataProvenanceOutput """ return self._output @output.setter def output(self, output: DataProvenanceOutput): """Sets the output of this DataProvenance. :param output: The output of this DataProvenance. :type output: DataProvenanceOutput """ self._output = output @property def test_debug(self) -> Debug: """Gets the test_debug of this DataProvenance. :return: The test_debug of this DataProvenance. :rtype: Debug """ return self._test_debug @test_debug.setter def test_debug(self, test_debug: Debug): """Sets the test_debug of this DataProvenance. :param test_debug: The test_debug of this DataProvenance. :type test_debug: Debug """ self._test_debug = test_debug
31.448276
311
0.639035
from __future__ import absolute_import from datetime import date, datetime from typing import List, Dict from fuji_server.models.base_model_ import Model from fuji_server.models.data_provenance_output import DataProvenanceOutput from fuji_server.models.debug import Debug from fuji_server.models.fair_result_common import FAIRResultCommon from fuji_server.models.fair_result_common_score import FAIRResultCommonScore from fuji_server.models.fair_result_evaluation_criterium import FAIRResultEvaluationCriterium from fuji_server import util class DataProvenance(Model): def __init__(self, id: int=None, metric_identifier: str=None, metric_name: str=None, metric_tests: Dict[str, FAIRResultEvaluationCriterium]=None, test_status: str='fail', score: FAIRResultCommonScore=None, maturity: str='incomplete', output: DataProvenanceOutput=None, test_debug: Debug=None): self.swagger_types = { 'id': int, 'metric_identifier': str, 'metric_name': str, 'metric_tests': Dict[str, FAIRResultEvaluationCriterium], 'test_status': str, 'score': FAIRResultCommonScore, 'maturity': str, 'output': DataProvenanceOutput, 'test_debug': Debug } self.attribute_map = { 'id': 'id', 'metric_identifier': 'metric_identifier', 'metric_name': 'metric_name', 'metric_tests': 'metric_tests', 'test_status': 'test_status', 'score': 'score', 'maturity': 'maturity', 'output': 'output', 'test_debug': 'test_debug' } self._id = id self._metric_identifier = metric_identifier self._metric_name = metric_name self._metric_tests = metric_tests self._test_status = test_status self._score = score self._maturity = maturity self._output = output self._test_debug = test_debug @classmethod def from_dict(cls, dikt) -> 'DataProvenance': return util.deserialize_model(dikt, cls) @property def id(self) -> int: return self._id @id.setter def id(self, id: int): if id is None: raise ValueError("Invalid value for `id`, must not be `None`") self._id = id @property def metric_identifier(self) -> str: return self._metric_identifier @metric_identifier.setter def metric_identifier(self, metric_identifier: str): if metric_identifier is None: raise ValueError("Invalid value for `metric_identifier`, must not be `None`") self._metric_identifier = metric_identifier @property def metric_name(self) -> str: return self._metric_name @metric_name.setter def metric_name(self, metric_name: str): if metric_name is None: raise ValueError("Invalid value for `metric_name`, must not be `None`") self._metric_name = metric_name @property def metric_tests(self) -> Dict[str, FAIRResultEvaluationCriterium]: return self._metric_tests @metric_tests.setter def metric_tests(self, metric_tests: Dict[str, FAIRResultEvaluationCriterium]): self._metric_tests = metric_tests @property def test_status(self) -> str: return self._test_status @test_status.setter def test_status(self, test_status: str): allowed_values = ["pass", "fail", "indeterminate"] if test_status not in allowed_values: raise ValueError( "Invalid value for `test_status` ({0}), must be one of {1}" .format(test_status, allowed_values) ) self._test_status = test_status @property def score(self) -> FAIRResultCommonScore: return self._score @score.setter def score(self, score: FAIRResultCommonScore): if score is None: raise ValueError("Invalid value for `score`, must not be `None`") self._score = score @property def maturity(self) -> str: return self._maturity @maturity.setter def maturity(self, maturity: int): self._maturity = maturity @property def output(self) -> DataProvenanceOutput: return self._output @output.setter def output(self, output: DataProvenanceOutput): self._output = output @property def test_debug(self) -> Debug: return self._test_debug @test_debug.setter def test_debug(self, test_debug: Debug): self._test_debug = test_debug
true
true
f725a0d77d7b829ac919d0eaca76f246b6e73be7
43,643
py
Python
dbaas/maintenance/migrations/0030_auto__add_field_maintenance_disable_alarms.py
didindinn/database-as-a-service
747de31ff8546f7874ddd654af860e130afd17a0
[ "BSD-3-Clause" ]
303
2015-01-08T10:35:54.000Z
2022-02-28T08:54:06.000Z
dbaas/maintenance/migrations/0030_auto__add_field_maintenance_disable_alarms.py
nouraellm/database-as-a-service
5e655c9347bea991b7218a01549f5e44f161d7be
[ "BSD-3-Clause" ]
124
2015-01-14T12:56:15.000Z
2022-03-22T20:45:11.000Z
dbaas/maintenance/migrations/0030_auto__add_field_maintenance_disable_alarms.py
nouraellm/database-as-a-service
5e655c9347bea991b7218a01549f5e44f161d7be
[ "BSD-3-Clause" ]
110
2015-01-02T11:59:48.000Z
2022-02-28T08:54:06.000Z
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Maintenance.disable_alarms' db.add_column(u'maintenance_maintenance', 'disable_alarms', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) def backwards(self, orm): # Deleting field 'Maintenance.disable_alarms' db.delete_column(u'maintenance_maintenance', 'disable_alarms') models = { u'account.team': { 'Meta': {'ordering': "[u'name']", 'object_name': 'Team'}, 'contacts': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'database_alocation_limit': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '2'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'role': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.Group']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.User']", 'symmetrical': 'False'}) }, u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'backup.backupgroup': { 'Meta': {'object_name': 'BackupGroup'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'logical.database': { 'Meta': {'ordering': "(u'name',)", 'unique_together': "((u'name', u'environment'),)", 'object_name': 'Database'}, 'backup_path': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'databaseinfra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DatabaseInfra']"}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'disk_auto_resize': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_in_quarantine': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_protected': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'db_index': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['logical.Project']"}), 'quarantine_dt': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'quarantine_user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases_quarantine'", 'null': 'True', 'to': u"orm['auth.User']"}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'subscribe_to_email_events': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'team': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases'", 'null': 'True', 'to': u"orm['account.Team']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'used_size_in_bytes': ('django.db.models.fields.FloatField', [], {'default': '0.0'}) }, u'logical.project': { 'Meta': {'ordering': "[u'name']", 'object_name': 'Project'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databasechangeparameter': { 'Meta': {'object_name': 'DatabaseChangeParameter'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'change_parameters'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_change_parameters'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databasecreate': { 'Meta': {'object_name': 'DatabaseCreate'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases_create'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['logical.Database']"}), 'description': ('django.db.models.fields.TextField', [], {}), 'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases_create'", 'to': u"orm['physical.Environment']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'infra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases_create'", 'to': u"orm['physical.DatabaseInfra']"}), 'is_protected': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases_create'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'plan_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases_create'", 'null': 'True', 'to': u"orm['logical.Project']"}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'subscribe_to_email_events': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'create_database'", 'to': u"orm['notification.TaskHistory']"}), 'team': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases_create'", 'to': u"orm['account.Team']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, u'maintenance.databasereinstallvm': { 'Meta': {'object_name': 'DatabaseReinstallVM'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'reinstall_vm'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_reinstall_vm'", 'to': u"orm['physical.Instance']"}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_reinsgtall_vm'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databaseresize': { 'Meta': {'object_name': 'DatabaseResize'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'resizes'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'source_offer': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_resizes_source'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Offering']"}), 'source_offer_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'target_offer': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_resizes_target'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Offering']"}), 'target_offer_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_resizes'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databaserestore': { 'Meta': {'object_name': 'DatabaseRestore'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_restore'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_restore'", 'to': u"orm['backup.BackupGroup']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'new_group': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_restore_new'", 'null': 'True', 'to': u"orm['backup.BackupGroup']"}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_restore'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databaserestoreinstancepair': { 'Meta': {'unique_together': "((u'master', u'slave', u'restore'),)", 'object_name': 'DatabaseRestoreInstancePair'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'master': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'restore_master'", 'to': u"orm['physical.Instance']"}), 'restore': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'restore_instances'", 'to': u"orm['maintenance.DatabaseRestore']"}), 'slave': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'restore_slave'", 'to': u"orm['physical.Instance']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databaseupgrade': { 'Meta': {'object_name': 'DatabaseUpgrade'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'upgrades'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'source_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_upgrades_source'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'source_plan_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'target_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_upgrades_target'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'target_plan_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_upgrades'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.hostmaintenance': { 'Meta': {'unique_together': "((u'host', u'maintenance'),)", 'object_name': 'HostMaintenance', 'index_together': "[[u'host', u'maintenance']]"}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'host': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'host_maintenance'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Host']"}), 'hostname': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'main_log': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'maintenance': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'maintenance'", 'to': u"orm['maintenance.Maintenance']"}), 'rollback_log': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '4'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.maintenance': { 'Meta': {'object_name': 'Maintenance'}, 'affected_hosts': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'celery_task_id': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '500'}), 'disable_alarms': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'hostsid': ('django.db.models.fields.CommaSeparatedIntegerField', [], {'max_length': '10000'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'main_script': ('django.db.models.fields.TextField', [], {}), 'maximum_workers': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '1'}), 'revoked_by': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'rollback_script': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'scheduled_for': ('django.db.models.fields.DateTimeField', [], {'unique': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.maintenanceparameters': { 'Meta': {'object_name': 'MaintenanceParameters'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'function_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'maintenance': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'maintenance_params'", 'to': u"orm['maintenance.Maintenance']"}), 'parameter_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'notification.taskhistory': { 'Meta': {'object_name': 'TaskHistory'}, 'arguments': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'context': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'database_name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'details': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'ended_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_class': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'object_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'task_id': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'task_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'task_status': ('django.db.models.fields.CharField', [], {'default': "u'WAITING'", 'max_length': '100', 'db_index': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'null': 'True', 'blank': 'True'}) }, u'physical.databaseinfra': { 'Meta': {'object_name': 'DatabaseInfra'}, 'capacity': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'database_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'disk_offering': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DiskOffering']"}), 'endpoint': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'endpoint_dns': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'engine': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Engine']"}), 'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_vm_created': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'name_prefix': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'name_stamp': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '406', 'blank': 'True'}), 'per_database_size_mbytes': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'plan': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Plan']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}) }, u'physical.diskoffering': { 'Meta': {'object_name': 'DiskOffering'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'size_kb': ('django.db.models.fields.PositiveIntegerField', [], {}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.engine': { 'Meta': {'ordering': "(u'engine_type__name', u'version')", 'unique_together': "((u'version', u'engine_type'),)", 'object_name': 'Engine'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'engine_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'engines'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.EngineType']"}), 'engine_upgrade_option': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_engine'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Engine']"}), 'has_users': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'read_node_description': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'null': 'True', 'blank': 'True'}), 'template_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user_data_script': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'version': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'write_node_description': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'null': 'True', 'blank': 'True'}) }, u'physical.enginetype': { 'Meta': {'ordering': "(u'name',)", 'object_name': 'EngineType'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_in_memory': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.environment': { 'Meta': {'object_name': 'Environment'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'migrate_environment': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'migrate_to'", 'null': 'True', 'to': u"orm['physical.Environment']"}), 'min_of_zones': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.host': { 'Meta': {'object_name': 'Host'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'future_host': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Host']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'hostname': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'identifier': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255'}), 'monitor_url': ('django.db.models.fields.URLField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}), 'offering': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Offering']", 'null': 'True'}), 'os_description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '406', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}) }, u'physical.instance': { 'Meta': {'unique_together': "((u'address', u'port'),)", 'object_name': 'Instance'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'databaseinfra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'instances'", 'to': u"orm['physical.DatabaseInfra']"}), 'dns': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'future_instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Instance']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'hostname': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'instances'", 'to': u"orm['physical.Host']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance_type': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'port': ('django.db.models.fields.IntegerField', [], {}), 'read_only': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'shard': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'total_size_in_bytes': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'used_size_in_bytes': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, u'physical.offering': { 'Meta': {'object_name': 'Offering'}, 'cpus': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'environments': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'offerings'", 'symmetrical': 'False', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'memory_size_mb': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.parameter': { 'Meta': {'ordering': "(u'engine_type__name', u'name')", 'unique_together': "((u'name', u'engine_type'),)", 'object_name': 'Parameter'}, 'allowed_values': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '200', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'custom_method': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'dynamic': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'engine_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'enginetype'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.EngineType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'parameter_type': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.plan': { 'Meta': {'object_name': 'Plan'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'disk_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'plans'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DiskOffering']"}), 'engine': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'plans'", 'to': u"orm['physical.Engine']"}), 'engine_equivalent_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_plan'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'environments': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'plans'", 'symmetrical': 'False', 'to': u"orm['physical.Environment']"}), 'has_persistence': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_ha': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'max_db_size': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'migrate_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'migrate_to'", 'null': 'True', 'to': u"orm['physical.Plan']"}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'provider': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'replication_topology': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'replication_topology'", 'null': 'True', 'to': u"orm['physical.ReplicationTopology']"}), 'stronger_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'main_offerings'", 'null': 'True', 'to': u"orm['physical.Offering']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'weaker_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'weaker_offerings'", 'null': 'True', 'to': u"orm['physical.Offering']"}) }, u'physical.replicationtopology': { 'Meta': {'object_name': 'ReplicationTopology'}, 'can_change_parameters': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_clone_db': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_reinstall_vm': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_resize_vm': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_switch_master': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_upgrade_db': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'class_path': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'details': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'engine': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'replication_topologies'", 'symmetrical': 'False', 'to': u"orm['physical.Engine']"}), 'has_horizontal_scalability': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'parameter': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'replication_topologies'", 'blank': 'True', 'to': u"orm['physical.Parameter']"}), 'script': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'replication_topologies'", 'null': 'True', 'to': u"orm['physical.Script']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.script': { 'Meta': {'object_name': 'Script'}, 'configuration': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'initialization': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'start_database': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'start_replication': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) } } complete_apps = ['maintenance']
97.200445
227
0.578512
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): db.add_column(u'maintenance_maintenance', 'disable_alarms', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) def backwards(self, orm): db.delete_column(u'maintenance_maintenance', 'disable_alarms') models = { u'account.team': { 'Meta': {'ordering': "[u'name']", 'object_name': 'Team'}, 'contacts': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'database_alocation_limit': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '2'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'role': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.Group']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.User']", 'symmetrical': 'False'}) }, u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'backup.backupgroup': { 'Meta': {'object_name': 'BackupGroup'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'logical.database': { 'Meta': {'ordering': "(u'name',)", 'unique_together': "((u'name', u'environment'),)", 'object_name': 'Database'}, 'backup_path': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'databaseinfra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DatabaseInfra']"}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'disk_auto_resize': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_in_quarantine': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_protected': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'db_index': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['logical.Project']"}), 'quarantine_dt': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'quarantine_user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases_quarantine'", 'null': 'True', 'to': u"orm['auth.User']"}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'subscribe_to_email_events': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'team': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases'", 'null': 'True', 'to': u"orm['account.Team']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'used_size_in_bytes': ('django.db.models.fields.FloatField', [], {'default': '0.0'}) }, u'logical.project': { 'Meta': {'ordering': "[u'name']", 'object_name': 'Project'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databasechangeparameter': { 'Meta': {'object_name': 'DatabaseChangeParameter'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'change_parameters'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_change_parameters'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databasecreate': { 'Meta': {'object_name': 'DatabaseCreate'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases_create'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['logical.Database']"}), 'description': ('django.db.models.fields.TextField', [], {}), 'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases_create'", 'to': u"orm['physical.Environment']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'infra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases_create'", 'to': u"orm['physical.DatabaseInfra']"}), 'is_protected': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases_create'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'plan_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'databases_create'", 'null': 'True', 'to': u"orm['logical.Project']"}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'subscribe_to_email_events': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'create_database'", 'to': u"orm['notification.TaskHistory']"}), 'team': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databases_create'", 'to': u"orm['account.Team']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, u'maintenance.databasereinstallvm': { 'Meta': {'object_name': 'DatabaseReinstallVM'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'reinstall_vm'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_reinstall_vm'", 'to': u"orm['physical.Instance']"}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_reinsgtall_vm'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databaseresize': { 'Meta': {'object_name': 'DatabaseResize'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'resizes'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'source_offer': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_resizes_source'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Offering']"}), 'source_offer_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'target_offer': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_resizes_target'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Offering']"}), 'target_offer_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_resizes'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databaserestore': { 'Meta': {'object_name': 'DatabaseRestore'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_restore'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_restore'", 'to': u"orm['backup.BackupGroup']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'new_group': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_restore_new'", 'null': 'True', 'to': u"orm['backup.BackupGroup']"}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_restore'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databaserestoreinstancepair': { 'Meta': {'unique_together': "((u'master', u'slave', u'restore'),)", 'object_name': 'DatabaseRestoreInstancePair'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'master': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'restore_master'", 'to': u"orm['physical.Instance']"}), 'restore': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'restore_instances'", 'to': u"orm['maintenance.DatabaseRestore']"}), 'slave': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'restore_slave'", 'to': u"orm['physical.Instance']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.databaseupgrade': { 'Meta': {'object_name': 'DatabaseUpgrade'}, 'can_do_retry': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'current_step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'database': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'upgrades'", 'to': u"orm['logical.Database']"}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'source_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_upgrades_source'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'source_plan_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'target_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'database_upgrades_target'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'target_plan_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'task': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'database_upgrades'", 'to': u"orm['notification.TaskHistory']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.hostmaintenance': { 'Meta': {'unique_together': "((u'host', u'maintenance'),)", 'object_name': 'HostMaintenance', 'index_together': "[[u'host', u'maintenance']]"}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'host': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'host_maintenance'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Host']"}), 'hostname': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'main_log': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'maintenance': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'maintenance'", 'to': u"orm['maintenance.Maintenance']"}), 'rollback_log': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '4'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.maintenance': { 'Meta': {'object_name': 'Maintenance'}, 'affected_hosts': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'celery_task_id': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'created_by': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '500'}), 'disable_alarms': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'finished_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'hostsid': ('django.db.models.fields.CommaSeparatedIntegerField', [], {'max_length': '10000'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'main_script': ('django.db.models.fields.TextField', [], {}), 'maximum_workers': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '1'}), 'revoked_by': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'rollback_script': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'scheduled_for': ('django.db.models.fields.DateTimeField', [], {'unique': 'True'}), 'started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'maintenance.maintenanceparameters': { 'Meta': {'object_name': 'MaintenanceParameters'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'function_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'maintenance': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'maintenance_params'", 'to': u"orm['maintenance.Maintenance']"}), 'parameter_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'notification.taskhistory': { 'Meta': {'object_name': 'TaskHistory'}, 'arguments': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'context': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'database_name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'null': 'True', 'blank': 'True'}), 'db_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'details': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'ended_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_class': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'object_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'task_id': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'task_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'task_status': ('django.db.models.fields.CharField', [], {'default': "u'WAITING'", 'max_length': '100', 'db_index': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'null': 'True', 'blank': 'True'}) }, u'physical.databaseinfra': { 'Meta': {'object_name': 'DatabaseInfra'}, 'capacity': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'database_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'disk_offering': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DiskOffering']"}), 'endpoint': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'endpoint_dns': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'engine': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Engine']"}), 'environment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_vm_created': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'name_prefix': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'name_stamp': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '406', 'blank': 'True'}), 'per_database_size_mbytes': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'plan': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'databaseinfras'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.Plan']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}) }, u'physical.diskoffering': { 'Meta': {'object_name': 'DiskOffering'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'size_kb': ('django.db.models.fields.PositiveIntegerField', [], {}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.engine': { 'Meta': {'ordering': "(u'engine_type__name', u'version')", 'unique_together': "((u'version', u'engine_type'),)", 'object_name': 'Engine'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'engine_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'engines'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.EngineType']"}), 'engine_upgrade_option': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_engine'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Engine']"}), 'has_users': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'read_node_description': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'null': 'True', 'blank': 'True'}), 'template_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user_data_script': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'version': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'write_node_description': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100', 'null': 'True', 'blank': 'True'}) }, u'physical.enginetype': { 'Meta': {'ordering': "(u'name',)", 'object_name': 'EngineType'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_in_memory': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.environment': { 'Meta': {'object_name': 'Environment'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'migrate_environment': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'migrate_to'", 'null': 'True', 'to': u"orm['physical.Environment']"}), 'min_of_zones': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.host': { 'Meta': {'object_name': 'Host'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'future_host': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Host']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'hostname': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'identifier': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '255'}), 'monitor_url': ('django.db.models.fields.URLField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}), 'offering': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Offering']", 'null': 'True'}), 'os_description': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '406', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}) }, u'physical.instance': { 'Meta': {'unique_together': "((u'address', u'port'),)", 'object_name': 'Instance'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'databaseinfra': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'instances'", 'to': u"orm['physical.DatabaseInfra']"}), 'dns': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'future_instance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['physical.Instance']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'hostname': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'instances'", 'to': u"orm['physical.Host']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'instance_type': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'port': ('django.db.models.fields.IntegerField', [], {}), 'read_only': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'shard': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'total_size_in_bytes': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'used_size_in_bytes': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}) }, u'physical.offering': { 'Meta': {'object_name': 'Offering'}, 'cpus': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'environments': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'offerings'", 'symmetrical': 'False', 'to': u"orm['physical.Environment']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'memory_size_mb': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.parameter': { 'Meta': {'ordering': "(u'engine_type__name', u'name')", 'unique_together': "((u'name', u'engine_type'),)", 'object_name': 'Parameter'}, 'allowed_values': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '200', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'custom_method': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'dynamic': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'engine_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'enginetype'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.EngineType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'parameter_type': ('django.db.models.fields.CharField', [], {'default': "u''", 'max_length': '100'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.plan': { 'Meta': {'object_name': 'Plan'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'disk_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'plans'", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u"orm['physical.DiskOffering']"}), 'engine': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'plans'", 'to': u"orm['physical.Engine']"}), 'engine_equivalent_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_plan'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Plan']"}), 'environments': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'plans'", 'symmetrical': 'False', 'to': u"orm['physical.Environment']"}), 'has_persistence': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_ha': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'max_db_size': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'migrate_plan': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'migrate_to'", 'null': 'True', 'to': u"orm['physical.Plan']"}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'provider': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'replication_topology': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'replication_topology'", 'null': 'True', 'to': u"orm['physical.ReplicationTopology']"}), 'stronger_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'main_offerings'", 'null': 'True', 'to': u"orm['physical.Offering']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'weaker_offering': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'weaker_offerings'", 'null': 'True', 'to': u"orm['physical.Offering']"}) }, u'physical.replicationtopology': { 'Meta': {'object_name': 'ReplicationTopology'}, 'can_change_parameters': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_clone_db': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_reinstall_vm': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_resize_vm': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_switch_master': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'can_upgrade_db': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'class_path': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'details': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'engine': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'replication_topologies'", 'symmetrical': 'False', 'to': u"orm['physical.Engine']"}), 'has_horizontal_scalability': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'parameter': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'replication_topologies'", 'blank': 'True', 'to': u"orm['physical.Parameter']"}), 'script': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'replication_topologies'", 'null': 'True', 'to': u"orm['physical.Script']"}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, u'physical.script': { 'Meta': {'object_name': 'Script'}, 'configuration': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'initialization': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'start_database': ('django.db.models.fields.CharField', [], {'max_length': '300'}), 'start_replication': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) } } complete_apps = ['maintenance']
true
true
f725a15222a68089d26599b0bfbcfc3a016ae93b
1,466
py
Python
_action_files/nb2post.py
inc0/fastpages
28603b7c6f38f83eea715ab12d71895078dbff9a
[ "Apache-2.0" ]
null
null
null
_action_files/nb2post.py
inc0/fastpages
28603b7c6f38f83eea715ab12d71895078dbff9a
[ "Apache-2.0" ]
null
null
null
_action_files/nb2post.py
inc0/fastpages
28603b7c6f38f83eea715ab12d71895078dbff9a
[ "Apache-2.0" ]
null
null
null
"""Converts Jupyter Notebooks to Jekyll compliant blog posts""" from datetime import datetime import re, os, logging from nbdev import export2html from nbdev.export2html import Config, Path, _re_digits, _to_html, _re_block_notes from fast_template import rename_for_jekyll warnings = set() # Modify the naming process such that destination files get named properly for Jekyll _posts def _nb2htmlfname(nb_path, dest=None): fname = rename_for_jekyll(nb_path, warnings=warnings) if dest is None: dest = Config().doc_path return Path(dest)/fname # Add embedded links for youtube and twitter def add_embedded_links(cell): "Convert block quotes to embedded links in `cell`" _styles = ['youtube', 'twitter'] def _inner(m): title,text = m.groups() if title.lower() not in _styles: return f"> {m.groups()[0]}: {m.groups()[1]}" return '{% include '+title.lower()+".html content=\'`"+_to_html(text)+"`\' %}" if cell['cell_type'] == 'markdown': cell['source'] = _re_block_notes.sub(_inner, cell['source']) return cell # TODO: Open a GitHub Issue in addition to printing warnings for original, new in warnings: print(f'{original} has been renamed to {new} to be complaint with Jekyll naming conventions.\n') ## apply monkey patches export2html._nb2htmlfname = _nb2htmlfname export2html.process_cell.append(add_embedded_links) export2html.notebook2html(fname='_notebooks/*.ipynb', dest='_posts/')
39.621622
100
0.723056
from datetime import datetime import re, os, logging from nbdev import export2html from nbdev.export2html import Config, Path, _re_digits, _to_html, _re_block_notes from fast_template import rename_for_jekyll warnings = set() def _nb2htmlfname(nb_path, dest=None): fname = rename_for_jekyll(nb_path, warnings=warnings) if dest is None: dest = Config().doc_path return Path(dest)/fname def add_embedded_links(cell): _styles = ['youtube', 'twitter'] def _inner(m): title,text = m.groups() if title.lower() not in _styles: return f"> {m.groups()[0]}: {m.groups()[1]}" return '{% include '+title.lower()+".html content=\'`"+_to_html(text)+"`\' %}" if cell['cell_type'] == 'markdown': cell['source'] = _re_block_notes.sub(_inner, cell['source']) return cell for original, new in warnings: print(f'{original} has been renamed to {new} to be complaint with Jekyll naming conventions.\n') name = _nb2htmlfname export2html.process_cell.append(add_embedded_links) export2html.notebook2html(fname='_notebooks/*.ipynb', dest='_posts/')
true
true
f725a1d093a3821295e1aa148bb4213f8b3be699
7,204
py
Python
Chapter05/stock_trading_visual_continuous_env.py
harinipsamy/Tensorflow-2-Reinforcement-Learning-Cookbook
b8858554e4c819c96de10c100f8213ab41561c69
[ "MIT" ]
null
null
null
Chapter05/stock_trading_visual_continuous_env.py
harinipsamy/Tensorflow-2-Reinforcement-Learning-Cookbook
b8858554e4c819c96de10c100f8213ab41561c69
[ "MIT" ]
null
null
null
Chapter05/stock_trading_visual_continuous_env.py
harinipsamy/Tensorflow-2-Reinforcement-Learning-Cookbook
b8858554e4c819c96de10c100f8213ab41561c69
[ "MIT" ]
1
2021-03-27T18:35:14.000Z
2021-03-27T18:35:14.000Z
#!/usr/bin/env python # Visual stock/share trading RL environment with continuous trade actions # Chapter 5, TensorFlow 2 Reinforcement Learning Cookbook | Praveen Palanisamy import os import random from typing import Dict import cv2 import gym import numpy as np import pandas as pd from gym import spaces from trading_utils import TradeVisualizer env_config = { "ticker": "MSFT", "opening_account_balance": 1000, # Number of steps (days) of data provided to the agent in one observation "observation_horizon_sequence_length": 30, } class StockTradingVisualContinuousEnv(gym.Env): def __init__(self, env_config: Dict = env_config): """Stock trading environment for RL agents with continuous action space Args: ticker (str, optional): Ticker symbol for the stock. Defaults to "MSFT". env_config (Dict): Env configuration values """ super(StockTradingVisualContinuousEnv, self).__init__() self.ticker = env_config.get("ticker", "MSFT") data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "data") self.ticker_file_stream = os.path.join(f"{data_dir}", f"{self.ticker}.csv") assert os.path.isfile( self.ticker_file_stream ), f"Historical stock data file stream not found at: data/{self.ticker}.csv" # Stock market data stream. An offline file stream is used. Alternatively, a web # API can be used to pull live data. # Data-Frame: Date Open High Low Close Adj-Close Volume self.ohlcv_df = pd.read_csv(self.ticker_file_stream) self.opening_account_balance = env_config["opening_account_balance"] # Action: 1-dim value indicating a fraction amount of shares to Buy (0 to 1) or # sell (-1 to 0). The fraction is taken on the allowable number of # shares that can be bought or sold based on the account balance (no margin). self.action_space = spaces.Box( low=np.array([-1]), high=np.array([1]), dtype=np.float ) self.observation_features = [ "Open", "High", "Low", "Close", "Adj Close", "Volume", ] self.obs_width, self.obs_height = 128, 128 self.horizon = env_config.get("observation_horizon_sequence_length") self.observation_space = spaces.Box( low=0, high=255, shape=(128, 128, 3), dtype=np.uint8, ) self.viz = None # Visualizer def step(self, action): # Execute one step within the environment self.execute_trade_action(action) self.current_step += 1 reward = self.account_value - self.opening_account_balance # Profit (loss) done = self.account_value <= 0 or self.current_step >= len( self.ohlcv_df.loc[:, "Open"].values ) obs = self.get_observation() return obs, reward, done, {} def reset(self): # Reset the state of the environment to an initial state self.cash_balance = self.opening_account_balance self.account_value = self.opening_account_balance self.num_shares_held = 0 self.cost_basis = 0 self.current_step = 0 self.trades = [] if self.viz is None: self.viz = TradeVisualizer( self.ticker, self.ticker_file_stream, "TFRL-Cookbook Ch4-StockTradingVisualContinuousEnv", ) return self.get_observation() def render(self, **kwargs): # Render the environment to the screen if self.current_step > self.horizon: self.viz.render( self.current_step, self.account_value, self.trades, window_size=self.horizon, ) def close(self): if self.viz is not None: self.viz.close() self.viz = None def get_observation(self): """Return a view of the Ticker price chart as image observation Returns: img_observation (np.ndarray): Image of ticker candle stick plot with volume bars as observation """ img_observation = self.viz.render_image_observation( self.current_step, self.horizon ) img_observation = cv2.resize( img_observation, dsize=(128, 128), interpolation=cv2.INTER_CUBIC ) return img_observation def execute_trade_action(self, action): if action == 0: # Indicates "Hold" action # Hold position; No trade to be executed return order_type = "buy" if action > 0 else "sell" order_fraction_of_allowable_shares = abs(action) # Stochastically determine the current stock price based on Market Open & Close current_price = random.uniform( self.ohlcv_df.loc[self.current_step, "Open"], self.ohlcv_df.loc[self.current_step, "Close"], ) if order_type == "buy": allowable_shares = int(self.cash_balance / current_price) # Simulate a BUY order and execute it at current_price num_shares_bought = int( allowable_shares * order_fraction_of_allowable_shares ) current_cost = self.cost_basis * self.num_shares_held additional_cost = num_shares_bought * current_price self.cash_balance -= additional_cost self.cost_basis = (current_cost + additional_cost) / ( self.num_shares_held + num_shares_bought ) self.num_shares_held += num_shares_bought if num_shares_bought > 0: self.trades.append( { "type": "buy", "step": self.current_step, "shares": num_shares_bought, "proceeds": additional_cost, } ) elif order_type == "sell": # Simulate a SELL order and execute it at current_price num_shares_sold = int( self.num_shares_held * order_fraction_of_allowable_shares ) self.cash_balance += num_shares_sold * current_price self.num_shares_held -= num_shares_sold sale_proceeds = num_shares_sold * current_price if num_shares_sold > 0: self.trades.append( { "type": "sell", "step": self.current_step, "shares": num_shares_sold, "proceeds": sale_proceeds, } ) if self.num_shares_held == 0: self.cost_basis = 0 # Update account value self.account_value = self.cash_balance + self.num_shares_held * current_price if __name__ == "__main__": env = StockTradingVisualContinuousEnv() obs = env.reset() for _ in range(600): action = env.action_space.sample() next_obs, reward, done, _ = env.step(action) env.render()
35.141463
88
0.593282
import os import random from typing import Dict import cv2 import gym import numpy as np import pandas as pd from gym import spaces from trading_utils import TradeVisualizer env_config = { "ticker": "MSFT", "opening_account_balance": 1000, "observation_horizon_sequence_length": 30, } class StockTradingVisualContinuousEnv(gym.Env): def __init__(self, env_config: Dict = env_config): super(StockTradingVisualContinuousEnv, self).__init__() self.ticker = env_config.get("ticker", "MSFT") data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "data") self.ticker_file_stream = os.path.join(f"{data_dir}", f"{self.ticker}.csv") assert os.path.isfile( self.ticker_file_stream ), f"Historical stock data file stream not found at: data/{self.ticker}.csv" self.ohlcv_df = pd.read_csv(self.ticker_file_stream) self.opening_account_balance = env_config["opening_account_balance"] self.action_space = spaces.Box( low=np.array([-1]), high=np.array([1]), dtype=np.float ) self.observation_features = [ "Open", "High", "Low", "Close", "Adj Close", "Volume", ] self.obs_width, self.obs_height = 128, 128 self.horizon = env_config.get("observation_horizon_sequence_length") self.observation_space = spaces.Box( low=0, high=255, shape=(128, 128, 3), dtype=np.uint8, ) self.viz = None def step(self, action): self.execute_trade_action(action) self.current_step += 1 reward = self.account_value - self.opening_account_balance done = self.account_value <= 0 or self.current_step >= len( self.ohlcv_df.loc[:, "Open"].values ) obs = self.get_observation() return obs, reward, done, {} def reset(self): self.cash_balance = self.opening_account_balance self.account_value = self.opening_account_balance self.num_shares_held = 0 self.cost_basis = 0 self.current_step = 0 self.trades = [] if self.viz is None: self.viz = TradeVisualizer( self.ticker, self.ticker_file_stream, "TFRL-Cookbook Ch4-StockTradingVisualContinuousEnv", ) return self.get_observation() def render(self, **kwargs): if self.current_step > self.horizon: self.viz.render( self.current_step, self.account_value, self.trades, window_size=self.horizon, ) def close(self): if self.viz is not None: self.viz.close() self.viz = None def get_observation(self): img_observation = self.viz.render_image_observation( self.current_step, self.horizon ) img_observation = cv2.resize( img_observation, dsize=(128, 128), interpolation=cv2.INTER_CUBIC ) return img_observation def execute_trade_action(self, action): if action == 0: return order_type = "buy" if action > 0 else "sell" order_fraction_of_allowable_shares = abs(action) current_price = random.uniform( self.ohlcv_df.loc[self.current_step, "Open"], self.ohlcv_df.loc[self.current_step, "Close"], ) if order_type == "buy": allowable_shares = int(self.cash_balance / current_price) num_shares_bought = int( allowable_shares * order_fraction_of_allowable_shares ) current_cost = self.cost_basis * self.num_shares_held additional_cost = num_shares_bought * current_price self.cash_balance -= additional_cost self.cost_basis = (current_cost + additional_cost) / ( self.num_shares_held + num_shares_bought ) self.num_shares_held += num_shares_bought if num_shares_bought > 0: self.trades.append( { "type": "buy", "step": self.current_step, "shares": num_shares_bought, "proceeds": additional_cost, } ) elif order_type == "sell": num_shares_sold = int( self.num_shares_held * order_fraction_of_allowable_shares ) self.cash_balance += num_shares_sold * current_price self.num_shares_held -= num_shares_sold sale_proceeds = num_shares_sold * current_price if num_shares_sold > 0: self.trades.append( { "type": "sell", "step": self.current_step, "shares": num_shares_sold, "proceeds": sale_proceeds, } ) if self.num_shares_held == 0: self.cost_basis = 0 self.account_value = self.cash_balance + self.num_shares_held * current_price if __name__ == "__main__": env = StockTradingVisualContinuousEnv() obs = env.reset() for _ in range(600): action = env.action_space.sample() next_obs, reward, done, _ = env.step(action) env.render()
true
true
f725a200284daaaded9eadc2048d2708f4206809
109,449
py
Python
olfactorybulb/slices/CoronalSlice/TC4_0.py
fameshpatel/olfactorybulb
8d7a644b4560309ef177c0590ff73ed4c2432604
[ "MIT" ]
null
null
null
olfactorybulb/slices/CoronalSlice/TC4_0.py
fameshpatel/olfactorybulb
8d7a644b4560309ef177c0590ff73ed4c2432604
[ "MIT" ]
null
null
null
olfactorybulb/slices/CoronalSlice/TC4_0.py
fameshpatel/olfactorybulb
8d7a644b4560309ef177c0590ff73ed4c2432604
[ "MIT" ]
null
null
null
from neuron import h class TransformTC4: def __init__(self): # Create a section lookup by section name # Note: this assumes each section has a unique name self.name2section = { sec.name(): sec for sec in h.allsec() } # This will store the new section coordinates self.section_coords = { } def set_coords(self, sec_name): # Lookup the section nrn_section = self.name2section[sec_name] # Lookup its new coords new_coords = self.section_coords[sec_name] # Use 3D points as section L and diam sources h.pt3dconst(1, sec=nrn_section) # Clear the existing points - and allocate room for the incoming points h.pt3dclear(len(new_coords["diam"]), sec=nrn_section) # Use vectorization to add the points to section xvec = h.Vector(new_coords["x"]) yvec = h.Vector(new_coords["y"]) zvec = h.Vector(new_coords["z"]) dvec = h.Vector(new_coords["diam"]) h.pt3dadd(xvec, yvec, zvec, dvec, sec=nrn_section) def set_all(self): for sec_name in self.section_coords.keys(): self.set_coords(sec_name) @staticmethod def apply_on(prefix): t = TransformTC4() t.define_coords(prefix) t.set_all() @staticmethod def apply(): t = TransformTC4() t.define_coords() t.set_all() def define_coords(self, prefix = 'TC4[0]'): if prefix != '': prefix += '.' self.section_coords = { prefix + 'apic[68]': { 'x':[-401.322,-402.235,-402.958,-401.756], 'y':[743.117,744.267,743.755,747.357], 'z':[-23.836,-21.982,-21.153,-19.972], 'diam':[0.264,0.264,0.264,0.264] }, prefix + 'apic[100]': { 'x':[-368.650,-369.977,-371.475,-372.161,-372.512,-373.361,-373.937,-374.711,-375.289,-375.521,-375.522,-376.265,-375.041,-375.495,-375.517,-374.957,-374.165,-373.673,-372.672,-371.700], 'y':[721.906,722.984,723.293,723.815,724.044,724.948,725.556,726.107,726.840,727.356,728.641,728.811,731.930,731.927,732.329,732.519,732.126,732.122,732.931,732.884], 'z':[-26.366,-25.829,-24.064,-23.086,-21.692,-20.685,-20.100,-19.668,-18.622,-17.585,-16.403,-13.942,-13.605,-11.861,-10.119,-8.762,-7.375,-6.275,-5.944,-4.515], 'diam':[0.613,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[113]': { 'x':[-383.489,-383.890,-383.410,-381.081,-380.535], 'y':[724.129,724.331,723.344,724.340,723.080], 'z':[-44.607,-43.031,-41.923,-41.646,-40.779], 'diam':[0.613,0.264,0.264,0.264,0.264] }, prefix + 'apic[37]': { 'x':[-375.585,-375.040,-374.570,-372.798,-371.266], 'y':[726.541,727.069,727.549,727.462,727.211], 'z':[-37.841,-35.655,-33.710,-32.052,-30.669], 'diam':[0.613,0.706,0.706,0.792,0.792] }, prefix + 'dend[2]': { 'x':[-305.424,-306.149,-306.972,-307.633,-307.203,-306.701,-307.338,-308.001,-307.992,-308.743,-309.466,-310.076,-309.901,-309.758,-310.736,-310.876,-311.714,-311.679,-312.585,-313.265,-314.333,-315.285,-316.729,-317.738,-318.707,-319.653,-320.304,-321.717,-323.098,-323.748,-323.829,-324.387,-325.403,-325.801,-326.171,-327.007,-326.773,-326.650,-327.482,-327.738,-328.016,-328.723,-328.947,-329.713,-330.844,-331.091,-331.111,-332.015,-332.114,-332.743,-333.113,-334.087,-334.663,-335.558,-336.136,-336.693,-337.237,-337.555,-337.335,-337.787,-338.119,-339.486,-340.852,-341.635,-342.410,-343.707,-345.556,-346.546,-347.430,-347.788,-348.533,-350.674,-351.546,-352.687,-353.566,-355.548,-356.503,-358.427,-359.864,-360.664,-361.856,-363.812,-364.870,-365.902,-367.369,-368.292,-368.764,-369.440,-370.536,-369.616,-370.027,-370.562,-369.958,-371.540,-372.116,-372.849,-373.095,-373.288,-373.202,-373.851,-374.295,-374.686,-374.293,-374.813,-375.303,-375.578,-376.148,-376.218,-377.242,-377.452,-377.267,-377.331,-377.443,-377.591,-377.441,-377.731,-378.310,-378.240,-378.158,-379.308,-379.335,-379.848,-380.406,-380.797,-380.513,-380.372,-380.032,-379.849,-379.917,-379.376,-378.853,-379.067,-378.944,-379.432,-379.750,-381.569,-381.330,-381.775,-382.134,-382.884,-383.706,-384.466,-384.231,-383.911,-385.008,-385.241,-385.364,-385.829,-386.448,-386.579,-386.330,-384.136,-387.079,-387.052,-386.854,-387.056,-387.134,-386.899,-387.208,-387.344,-387.404,-388.023,-387.858,-388.750,-389.583,-389.749,-390.293,-390.904,-391.807,-392.082,-393.498,-394.299,-395.083,-396.237,-397.409,-398.536,-398.992,-399.711,-400.673,-401.799,-401.981,-402.645,-402.713,-403.474,-404.364,-404.557,-405.328,-406.310,-406.915,-406.661,-407.622,-408.540,-408.281,-408.601,-409.468,-410.498,-411.801,-412.336,-413.417,-414.658,-415.811,-417.025,-417.416,-418.083,-418.578,-418.893,-419.861,-419.442,-420.697,-420.904,-421.188,-421.585,-422.166,-421.938,-421.805,-421.925,-422.798,-423.851,-424.795], 'y':[657.846,655.817,654.383,653.371,652.356,651.413,650.015,649.378,647.780,646.618,645.949,644.136,642.224,640.841,639.570,637.857,636.189,635.102,634.031,633.678,632.205,631.336,631.200,630.695,628.655,627.457,626.996,626.050,625.432,624.547,623.001,621.427,620.541,619.190,617.529,616.051,614.099,613.047,612.730,611.830,610.882,610.074,608.913,607.579,606.409,605.188,603.234,602.723,601.681,600.729,599.748,598.653,597.857,597.572,596.367,594.512,593.448,591.688,590.399,589.428,587.989,587.069,585.854,585.221,584.161,583.198,580.883,581.289,582.894,584.788,583.671,583.680,584.025,584.415,583.736,583.322,583.894,582.830,582.608,583.592,582.619,582.818,582.532,583.399,583.482,583.227,581.977,580.616,579.303,578.936,577.589,576.747,575.455,573.755,572.849,571.127,569.857,568.450,567.149,565.861,564.832,563.384,562.328,559.544,558.447,557.437,556.355,554.987,553.428,552.117,550.812,549.716,546.844,545.215,542.425,541.523,539.703,538.178,536.442,534.657,532.485,531.476,530.006,528.892,526.795,525.742,524.451,521.642,519.838,518.634,516.972,514.884,513.827,511.941,511.025,508.376,506.818,505.672,504.514,503.805,502.764,502.042,500.095,498.508,497.199,495.989,494.709,493.780,492.397,490.989,490.029,489.595,487.717,485.106,484.052,482.960,481.577,479.617,478.870,477.803,476.740,474.906,473.845,473.536,473.042,471.747,470.879,470.946,470.850,469.999,468.585,467.704,467.859,467.609,467.765,466.920,465.363,464.453,464.173,463.719,462.390,461.857,461.112,459.863,459.303,458.068,457.058,455.924,454.394,453.021,452.240,452.244,451.172,450.056,449.408,449.081,449.179,448.412,446.642,445.859,444.628,444.020,442.960,442.026,441.460,440.411,439.813,438.771,437.936,436.800,435.005,434.026,432.869,431.080,429.895,428.409,426.955,426.013,425.250], 'z':[-86.353,-87.989,-88.761,-88.939,-88.680,-88.000,-88.761,-89.898,-89.692,-89.536,-90.332,-90.940,-91.312,-91.513,-92.119,-92.179,-92.385,-92.720,-93.485,-94.379,-96.344,-98.222,-99.345,-100.621,-101.779,-102.844,-103.498,-105.342,-106.480,-106.656,-107.169,-107.746,-108.364,-109.480,-109.473,-110.100,-110.682,-111.082,-112.447,-113.092,-113.890,-115.204,-115.781,-117.054,-117.343,-117.169,-117.852,-119.066,-119.581,-119.313,-119.441,-119.837,-120.587,-121.746,-122.672,-123.778,-124.385,-125.363,-124.846,-125.350,-126.532,-127.184,-127.755,-128.331,-129.353,-130.216,-130.395,-130.526,-130.866,-130.201,-130.487,-130.377,-130.020,-130.195,-130.095,-129.484,-129.739,-130.273,-129.503,-128.554,-128.446,-128.139,-128.708,-129.447,-129.267,-129.626,-128.220,-129.090,-128.702,-127.449,-127.936,-128.480,-128.426,-128.490,-128.582,-129.206,-128.592,-127.909,-128.036,-127.543,-128.534,-129.986,-129.992,-130.331,-130.234,-130.883,-131.173,-131.188,-131.680,-131.871,-132.231,-132.626,-133.187,-134.125,-134.815,-135.144,-136.072,-136.551,-136.788,-137.401,-138.135,-138.287,-139.150,-139.579,-140.098,-140.192,-140.236,-141.162,-141.916,-142.092,-142.369,-142.775,-143.167,-144.192,-145.113,-145.094,-145.724,-146.425,-146.455,-146.475,-147.001,-147.326,-147.918,-148.456,-148.977,-149.126,-149.373,-149.399,-149.570,-150.616,-150.866,-152.262,-150.603,-151.171,-151.544,-151.308,-152.278,-153.162,-153.967,-154.817,-155.295,-155.630,-155.975,-156.965,-156.694,-157.271,-158.206,-159.039,-160.278,-161.103,-161.318,-162.349,-163.169,-162.746,-163.119,-164.759,-164.727,-165.663,-166.734,-167.411,-167.563,-168.462,-169.395,-169.037,-169.627,-170.025,-170.360,-171.438,-171.585,-172.070,-173.092,-174.290,-174.577,-175.730,-176.070,-176.351,-177.666,-178.886,-180.318,-180.816,-182.097,-182.728,-183.377,-184.530,-185.581,-186.584,-186.938,-186.899,-187.257,-187.614,-188.210,-188.098,-187.870,-188.570,-188.928,-189.297,-189.777,-189.732,-189.137], 'diam':[0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[123]': { 'x':[-388.217,-387.909,-388.043,-388.419,-388.477,-388.170,-388.968,-389.566,-390.968,-391.192,-392.156,-392.402,-392.782,-393.483,-393.249,-393.743], 'y':[750.404,751.127,751.354,751.752,752.328,752.722,753.615,754.306,754.648,754.734,755.681,757.866,758.125,758.138,761.297,762.410], 'z':[-11.011,-8.893,-6.999,-6.000,-4.675,-3.202,-0.731,0.335,2.959,4.058,5.472,7.517,8.479,9.546,10.264,10.996], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[137]': { 'x':[-406.717,-408.041,-408.660], 'y':[739.828,738.773,737.771], 'z':[-42.726,-43.717,-44.083], 'diam':[0.264,0.264,0.264] }, prefix + 'apic[87]': { 'x':[-383.728,-383.712,-383.710,-384.757,-384.819,-384.736,-384.132,-383.222,-383.501,-383.637,-383.721], 'y':[729.654,730.154,730.665,731.362,732.288,733.530,733.810,734.566,736.049,736.656,737.408], 'z':[-36.522,-35.245,-33.983,-32.367,-30.814,-29.637,-28.144,-26.853,-24.876,-24.069,-23.133], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[107]': { 'x':[-402.452,-402.181,-402.512,-403.510,-404.990,-407.221,-407.770,-408.463,-409.672,-410.454,-411.101,-411.695,-411.789], 'y':[733.848,735.891,736.974,738.379,738.467,740.361,741.079,741.936,743.547,744.308,744.920,746.146,747.115], 'z':[-36.376,-35.862,-35.126,-34.206,-33.382,-31.205,-30.321,-29.313,-27.433,-26.810,-26.317,-25.184,-24.501], 'diam':[0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[45]': { 'x':[-366.165,-366.313,-366.835], 'y':[732.626,733.106,733.993], 'z':[-4.049,-3.108,-1.770], 'diam':[0.349,0.349,0.349] }, prefix + 'apic[35]': { 'x':[-375.082,-376.135,-376.999,-377.821], 'y':[723.155,724.325,724.617,725.564], 'z':[-47.527,-44.332,-42.503,-41.334], 'diam':[1.234,0.792,0.792,0.792] }, prefix + 'apic[38]': { 'x':[-371.266,-371.908], 'y':[727.211,728.584], 'z':[-30.669,-28.319], 'diam':[0.792,0.528] }, prefix + 'apic[33]': { 'x':[-374.024,-375.311,-377.581,-378.871,-380.203,-381.533,-382.323,-383.122,-384.607,-385.543,-385.955,-385.374,-384.843,-384.505,-384.329,-384.884,-385.583,-386.239,-387.042], 'y':[715.198,716.497,717.045,717.621,716.615,718.152,718.867,719.520,720.476,721.465,723.395,724.035,724.041,723.880,724.005,724.978,725.181,725.388,726.011], 'z':[-38.925,-37.785,-37.421,-37.312,-36.767,-35.118,-34.480,-34.154,-33.048,-31.047,-27.090,-24.605,-23.094,-21.588,-20.360,-18.534,-17.451,-14.734,-12.598], 'diam':[0.877,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[4]': { 'x':[-372.673,-370.268,-368.721,-367.836,-366.480,-365.724,-364.489,-364.000,-364.098], 'y':[717.133,716.035,716.542,716.517,716.592,716.446,716.739,717.539,717.234], 'z':[-46.593,-45.274,-45.463,-44.560,-43.284,-42.583,-42.087,-41.024,-39.614], 'diam':[1.320,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706] }, prefix + 'apic[73]': { 'x':[-382.134,-384.144,-385.221,-385.503,-386.609,-388.356,-389.217,-389.277], 'y':[726.717,727.360,728.561,729.123,729.959,730.043,731.161,731.679], 'z':[-40.431,-37.713,-36.462,-35.538,-34.327,-31.762,-30.401,-29.218], 'diam':[0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706] }, prefix + 'apic[27]': { 'x':[-356.857,-356.708,-357.203,-357.340], 'y':[702.880,703.299,703.826,703.884], 'z':[-29.899,-28.605,-27.042,-25.850], 'diam':[0.442,0.442,0.442,0.442] }, prefix + 'apic[23]': { 'x':[-362.344,-361.072,-360.172,-360.559,-359.839], 'y':[708.536,708.312,707.816,707.671,708.648], 'z':[-29.530,-28.825,-28.610,-27.247,-26.957], 'diam':[0.528,0.264,0.264,0.264,0.264] }, prefix + 'apic[120]': { 'x':[-394.546,-395.049,-395.217,-395.218], 'y':[737.443,738.429,739.655,740.049], 'z':[-41.888,-40.244,-37.510,-36.531], 'diam':[0.528,0.528,0.613,0.613] }, prefix + 'apic[80]': { 'x':[-396.249,-396.770,-398.279,-400.340,-401.841,-402.934,-404.005,-403.900,-405.902], 'y':[731.890,731.769,733.115,732.914,733.113,733.800,733.330,734.782,732.221], 'z':[-29.596,-30.740,-31.656,-31.900,-31.798,-31.216,-30.988,-32.214,-32.098], 'diam':[0.442,0.528,0.528,0.349,0.349,0.349,0.349,0.349,0.264] }, prefix + 'apic[125]': { 'x':[-396.161,-396.692,-397.460,-397.899,-398.619], 'y':[740.635,741.256,742.070,742.393,742.819], 'z':[-35.501,-33.897,-33.109,-32.098,-31.263], 'diam':[0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[140]': { 'x':[-392.313,-393.520,-394.433,-396.215,-397.872,-398.268,-400.003,-400.972,-401.942,-403.022,-403.964,-405.032,-405.625,-405.135,-405.528], 'y':[732.909,733.465,733.906,733.127,733.614,735.331,735.090,735.531,736.857,737.613,738.345,738.197,737.888,740.515,741.655], 'z':[-53.049,-53.616,-53.980,-53.947,-53.513,-53.518,-53.593,-54.213,-53.589,-53.466,-53.172,-52.276,-51.350,-51.238,-49.825], 'diam':[0.442,0.349,0.349,0.349,0.349,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[28]': { 'x':[-356.857,-356.919,-356.761], 'y':[702.880,701.549,701.058], 'z':[-29.899,-30.956,-32.674], 'diam':[0.442,0.442,0.442] }, prefix + 'apic[79]': { 'x':[-389.277,-392.355,-393.562,-395.216,-396.249], 'y':[731.679,731.891,732.249,732.656,731.890], 'z':[-29.218,-29.900,-30.475,-29.766,-29.596], 'diam':[0.706,0.442,0.442,0.442,0.442] }, prefix + 'apic[6]': { 'x':[-362.553,-361.157], 'y':[717.930,717.776], 'z':[-39.618,-40.571], 'diam':[0.442,0.264] }, prefix + 'apic[58]': { 'x':[-368.533,-367.127,-367.500,-367.990,-366.772,-364.813,-363.144,-361.999,-360.753,-360.087,-359.239,-358.460,-356.936,-355.972], 'y':[725.556,724.702,725.159,725.813,725.501,724.931,724.064,723.631,723.152,723.091,721.588,721.156,720.129,718.758], 'z':[-29.616,-28.522,-27.381,-26.560,-25.220,-23.497,-21.118,-19.723,-18.596,-17.662,-17.243,-16.599,-16.381,-16.184], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[116]': { 'x':[-407.931,-408.947,-409.732,-410.750,-412.326,-413.177], 'y':[734.348,735.025,735.733,735.467,735.552,735.258], 'z':[-37.540,-37.480,-37.005,-36.943,-36.793,-37.324], 'diam':[0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[40]': { 'x':[-372.570,-372.849,-373.328], 'y':[730.628,731.242,731.957], 'z':[-21.545,-20.472,-19.495], 'diam':[0.528,0.349,0.349] }, prefix + 'apic[74]': { 'x':[-389.277,-389.302,-389.392,-389.856,-389.686,-389.242], 'y':[731.679,732.541,733.801,735.468,736.410,737.183], 'z':[-29.218,-27.141,-24.164,-20.790,-18.228,-16.218], 'diam':[0.706,0.528,0.613,0.613,0.613,0.613] }, prefix + 'apic[112]': { 'x':[-393.081,-394.111,-395.147], 'y':[723.019,724.029,723.597], 'z':[-41.593,-40.711,-39.279], 'diam':[0.349,0.349,0.349] }, prefix + 'dend[6]': { 'x':[-316.649,-316.983,-317.001,-316.991,-318.052,-319.144,-320.229,-320.690,-320.721,-320.971,-321.537,-323.054,-323.926,-325.276,-327.635,-326.904,-327.275,-328.221,-328.880,-329.401,-329.713,-330.354,-331.563,-332.397,-332.869,-333.901,-334.766,-336.052,-337.195,-338.096,-338.652,-339.383,-339.641,-339.814,-339.943,-339.773,-340.698,-341.420,-342.074,-343.010,-343.509,-344.218,-345.016,-345.544,-345.947,-346.366,-346.623,-346.994,-348.169,-349.116,-350.655,-351.823,-352.929,-354.289,-355.540,-356.724,-358.809,-360.180,-361.545,-363.034,-364.550,-366.090,-368.226,-370.293,-371.230,-372.645,-373.711,-374.577,-376.534,-377.696,-378.902,-379.974,-380.897,-382.571,-384.229,-386.551,-386.744,-387.056,-388.525,-388.441,-388.860,-390.513,-391.655,-392.346,-393.119,-394.626,-396.507,-397.421,-398.495,-399.628,-400.393,-401.059,-400.775,-400.778,-402.156,-402.780,-403.163,-403.496,-403.410,-403.824,-403.804,-404.479,-405.193,-406.114,-405.251,-405.872,-407.220,-407.017,-407.361,-408.038,-408.831,-409.900,-409.459,-410.673,-411.358,-411.926,-412.272,-412.908,-413.529,-414.666,-415.458,-416.558,-417.888,-419.097,-419.184,-420.554,-421.509,-422.694,-423.226,-423.698,-424.487,-425.051,-426.607,-427.473,-428.605,-429.542,-431.626,-433.594,-434.985,-435.229,-435.324,-435.402,-435.347,-434.879,-434.224,-434.166,-434.772,-435.318,-435.951,-436.312,-436.963,-437.227,-437.313,-437.152,-437.569,-438.780,-440.223,-441.081,-441.657,-442.116,-443.317,-444.559,-446.245,-447.687], 'y':[714.484,714.221,715.057,716.820,716.696,716.724,716.798,717.294,717.360,717.687,718.119,718.775,718.794,718.806,719.070,719.804,719.978,720.201,720.189,720.071,720.724,721.468,721.636,721.968,722.043,722.759,722.716,723.242,723.542,723.505,723.461,724.344,724.482,724.358,724.307,724.258,724.339,724.578,724.602,724.640,725.008,725.341,725.094,724.889,724.749,725.711,726.235,727.135,727.474,727.264,728.507,729.042,729.031,728.949,728.793,728.703,728.929,728.849,728.824,729.236,729.066,728.853,730.052,729.783,729.616,729.516,729.532,729.442,729.475,729.328,729.244,729.123,728.956,728.750,728.624,730.111,729.933,731.110,731.107,731.188,731.421,731.550,731.448,731.394,731.317,731.061,730.824,731.181,731.345,731.293,731.604,731.442,731.303,731.175,733.338,733.942,734.276,734.242,734.418,734.992,735.434,735.902,736.442,736.800,736.761,737.061,737.474,737.508,738.166,739.026,739.582,739.321,739.225,739.208,739.967,739.972,740.377,740.793,740.775,740.865,741.357,741.737,741.558,741.439,741.470,742.032,742.406,742.088,738.975,738.371,738.149,737.385,737.046,736.909,736.754,736.588,735.994,735.937,735.640,735.058,734.900,735.510,736.036,735.937,735.919,735.807,735.770,735.918,736.277,736.113,735.849,735.755,735.553,735.454,735.173,734.910,734.628,734.484,734.347,734.210,733.492,733.964,734.527,734.769], 'z':[-111.225,-114.063,-116.672,-117.876,-118.327,-118.778,-119.829,-120.661,-121.710,-122.946,-123.788,-125.324,-126.776,-127.648,-128.862,-130.491,-131.624,-132.882,-134.193,-135.688,-136.718,-137.379,-139.032,-140.858,-142.578,-143.834,-144.717,-146.181,-148.760,-150.107,-151.384,-152.760,-153.873,-155.288,-156.354,-158.299,-160.121,-161.333,-162.173,-164.462,-165.634,-166.386,-169.205,-171.164,-172.511,-173.835,-175.081,-176.608,-178.738,-180.321,-181.422,-182.288,-182.632,-183.390,-184.101,-183.996,-185.383,-186.128,-186.892,-187.802,-188.348,-189.358,-189.816,-190.464,-191.580,-191.995,-192.570,-193.437,-194.785,-195.363,-195.728,-196.188,-197.307,-198.222,-198.673,-199.755,-201.642,-202.367,-202.093,-203.128,-204.036,-205.216,-205.904,-207.091,-207.836,-209.536,-210.497,-211.413,-211.993,-213.273,-214.849,-216.140,-217.461,-219.082,-220.175,-221.973,-223.114,-224.928,-225.964,-227.718,-229.134,-230.704,-232.044,-232.848,-233.580,-234.790,-236.957,-237.958,-238.881,-240.012,-241.024,-243.092,-244.631,-246.152,-246.583,-247.862,-249.239,-251.487,-253.017,-254.423,-257.443,-259.092,-260.520,-262.041,-263.933,-264.954,-266.800,-267.720,-268.800,-269.669,-270.867,-272.910,-274.841,-275.713,-276.408,-277.523,-280.140,-281.939,-284.192,-286.187,-287.933,-289.034,-290.688,-292.907,-293.812,-295.181,-296.226,-297.638,-298.721,-299.720,-301.587,-302.552,-304.882,-306.234,-309.215,-311.194,-312.640,-313.513,-314.663,-315.795,-317.907,-319.477,-320.685,-321.816], 'diam':[1.056,0.877,0.877,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.613,0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264] }, prefix + 'apic[48]': { 'x':[-369.377,-368.868,-369.001], 'y':[728.596,728.853,729.446], 'z':[-20.031,-18.610,-17.351], 'diam':[0.349,0.264,0.264] }, prefix + 'apic[90]': { 'x':[-380.344,-377.873,-376.028,-375.083,-374.022,-371.998,-371.004,-369.502,-367.979,-368.221,-367.901,-368.675,-367.791,-368.599,-368.650], 'y':[724.015,722.870,724.168,722.390,722.279,721.505,720.499,721.433,721.332,722.116,722.974,721.697,722.709,721.204,721.906], 'z':[-44.355,-43.085,-41.437,-39.030,-38.067,-36.429,-34.992,-34.486,-33.082,-31.540,-30.933,-29.551,-29.546,-28.180,-26.366], 'diam':[0.613,0.613,0.613,0.613,0.528,0.528,0.528,0.528,0.613,0.613,0.613,0.613,0.613,0.613,0.613] }, prefix + 'apic[34]': { 'x':[-371.406,-373.446,-374.045,-375.082], 'y':[719.126,720.902,722.725,723.155], 'z':[-51.397,-50.313,-48.625,-47.527], 'diam':[1.933,1.234,1.234,1.234] }, prefix + 'soma': { 'x':[-297.841,-296.129,-294.417], 'y':[712.070,707.901,703.732], 'z':[-90.454,-89.770,-89.086], 'diam':[9.117,9.117,9.117] }, prefix + 'apic[44]': { 'x':[-365.089,-365.966,-366.538,-366.585,-366.373,-365.923], 'y':[732.271,732.384,732.702,732.198,732.093,731.595], 'z':[-3.214,-0.623,1.276,2.750,4.070,5.421], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'dend[7]': { 'x':[-300.796,-300.629,-299.381,-298.107,-296.935,-295.815,-297.338,-296.883,-295.403,-294.246,-293.197,-294.411,-295.384], 'y':[716.093,716.461,718.499,719.941,720.652,722.212,722.700,723.818,725.076,725.606,726.013,727.292,727.861], 'z':[-93.880,-97.054,-98.171,-97.995,-97.600,-97.415,-98.277,-100.250,-100.297,-100.731,-101.787,-103.411,-103.483], 'diam':[2.639,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847] }, prefix + 'apic[51]': { 'x':[-371.266,-370.307,-369.473], 'y':[727.211,726.650,726.158], 'z':[-30.669,-30.517,-29.787], 'diam':[0.792,0.442,0.442] }, prefix + 'dend[1]': { 'x':[-305.424,-304.042,-302.853,-301.401,-301.475,-300.185,-299.370,-298.648,-297.367,-296.733,-296.589,-296.564,-295.410,-294.247,-293.738,-293.850,-292.744,-292.152,-291.235,-291.015,-290.358,-290.719,-290.732,-289.687,-289.078,-288.530,-288.398,-288.768,-289.694,-291.113,-291.647,-290.869,-289.664,-289.045,-289.208,-289.575,-288.697,-287.855,-287.774,-287.870,-288.258,-287.918,-288.898,-289.985,-291.039,-290.634,-289.983,-289.708,-289.081,-288.893,-288.390,-288.861,-288.311,-289.781,-289.462,-289.582,-288.727,-287.871,-286.490,-286.391,-286.640,-286.069,-285.657,-286.066,-285.516,-284.870,-284.029,-283.113,-282.856,-282.601,-283.255,-282.010,-281.988,-281.796,-281.050,-281.154,-280.658,-279.152,-276.654,-275.812,-275.296,-275.576,-275.747,-274.804,-274.308,-273.451,-273.500,-274.257,-274.079,-273.230,-271.422,-270.993,-271.541,-271.849,-271.412,-271.399,-272.308,-272.909,-272.324,-271.094,-270.359,-270.459,-270.600,-269.870,-268.826,-267.621,-266.871,-265.858,-264.683,-264.741,-264.610,-263.893,-262.818,-262.468,-262.149,-261.449,-260.954,-260.040,-259.115,-257.052,-257.087,-256.522,-256.485,-256.763,-257.396,-257.902,-257.965,-257.688,-257.164], 'y':[657.846,657.791,657.893,657.814,657.019,656.482,656.563,655.737,654.890,654.083,653.043,651.499,651.047,650.917,649.724,648.757,647.762,646.524,645.859,645.206,644.845,645.449,645.536,645.856,645.241,645.518,645.860,646.617,645.696,645.313,644.061,643.927,643.242,642.669,641.119,639.853,638.957,638.146,636.354,635.362,635.940,635.534,634.786,633.929,632.889,632.434,632.389,631.401,630.361,628.448,627.315,625.868,625.358,623.596,622.671,622.106,620.987,619.894,618.554,617.114,615.494,614.186,612.488,611.281,610.310,609.927,610.067,608.745,607.589,606.562,604.617,604.482,603.054,602.084,602.371,600.515,599.739,600.062,600.860,600.380,599.933,598.475,597.205,596.701,595.451,594.543,593.467,591.978,592.247,590.802,590.391,589.646,588.469,588.695,587.992,587.962,587.366,585.678,584.292,583.218,582.187,581.145,579.203,578.520,578.122,577.192,576.552,576.048,576.075,575.140,574.006,573.708,574.957,575.148,575.296,575.967,576.599,576.663,576.532,576.820,576.110,576.379,576.314,575.493,574.309,573.159,572.010,571.139,568.656], 'z':[-86.353,-85.529,-85.081,-85.081,-84.108,-83.038,-82.162,-82.382,-82.418,-82.809,-82.436,-82.485,-82.104,-81.102,-80.896,-81.498,-81.182,-80.628,-80.760,-78.686,-77.214,-76.173,-74.987,-73.858,-72.479,-71.627,-70.503,-69.472,-69.583,-68.837,-67.928,-67.179,-66.627,-65.977,-66.335,-66.195,-65.980,-65.711,-65.095,-64.514,-63.447,-62.578,-61.868,-62.631,-62.426,-61.430,-60.244,-59.620,-58.465,-58.266,-56.615,-56.255,-55.507,-54.016,-53.469,-52.455,-51.468,-51.645,-50.379,-50.081,-47.948,-46.420,-45.712,-45.465,-44.915,-44.095,-43.288,-43.068,-43.100,-42.232,-41.208,-40.582,-39.689,-39.174,-38.423,-36.285,-35.165,-34.167,-33.331,-32.431,-31.376,-30.655,-30.141,-29.144,-28.431,-28.655,-28.135,-27.252,-25.953,-25.375,-25.486,-24.248,-22.363,-21.133,-20.396,-19.227,-18.697,-18.745,-18.398,-18.727,-19.260,-19.073,-18.625,-18.097,-17.512,-16.403,-16.166,-15.700,-14.756,-13.758,-14.177,-12.613,-9.986,-8.810,-7.134,-6.015,-4.744,-3.132,-2.168,-1.488,-0.362,0.628,1.713,3.046,2.575,1.905,1.594,1.117,0.154], 'diam':[0.706,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[89]': { 'x':[-379.163,-380.344], 'y':[723.461,724.015], 'z':[-44.007,-44.355], 'diam':[0.877,0.613] }, prefix + 'apic[47]': { 'x':[-372.570,-371.402,-370.112,-369.377], 'y':[730.628,729.969,729.136,728.596], 'z':[-21.545,-21.283,-21.133,-20.031], 'diam':[0.528,0.349,0.349,0.349] }, prefix + 'apic[135]': { 'x':[-403.344,-404.833,-405.705,-406.717], 'y':[738.048,739.098,739.762,739.828], 'z':[-43.286,-43.078,-42.839,-42.726], 'diam':[0.442,0.264,0.264,0.264] }, prefix + 'apic[91]': { 'x':[-368.650,-367.768,-366.866,-366.207,-366.046], 'y':[721.906,721.405,720.902,720.854,719.602], 'z':[-26.366,-26.208,-25.987,-24.898,-24.003], 'diam':[0.613,0.613,0.613,0.613,0.613] }, prefix + 'apic[5]': { 'x':[-364.098,-362.553], 'y':[717.234,717.930], 'z':[-39.614,-39.618], 'diam':[0.706,0.442] }, prefix + 'apic[75]': { 'x':[-389.242,-388.895,-388.210,-388.241,-388.144,-387.602,-387.273,-387.188,-386.756,-386.127,-385.543,-385.309,-385.814], 'y':[737.183,738.243,739.209,739.894,741.103,741.980,742.475,743.913,744.573,745.087,745.377,745.847,746.839], 'z':[-16.218,-12.900,-9.258,-7.620,-5.404,-3.018,-1.408,0.555,2.090,4.370,6.626,8.162,9.799], 'diam':[0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[134]': { 'x':[-403.344,-402.905,-403.123,-403.736,-403.761,-404.028,-404.588,-405.416,-406.891,-407.591,-408.446,-409.223,-410.226,-411.601,-412.837], 'y':[738.048,738.367,738.915,738.747,739.105,739.715,740.437,741.376,741.669,742.078,741.766,742.791,742.719,742.498,741.671], 'z':[-43.286,-41.803,-40.778,-39.230,-38.238,-37.158,-36.282,-35.290,-34.281,-33.621,-32.949,-31.983,-31.129,-30.446,-29.820], 'diam':[0.442,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[59]': { 'x':[-369.473,-370.332,-370.901,-371.241,-371.721,-372.168,-372.791,-373.585,-375.066,-375.746,-377.356,-378.685,-380.662,-381.393,-382.332], 'y':[726.158,726.320,727.055,727.076,727.030,727.498,728.226,728.932,730.561,730.807,731.445,731.398,732.496,733.263,734.055], 'z':[-29.787,-28.427,-27.366,-26.320,-25.163,-24.110,-23.312,-22.837,-21.048,-19.973,-19.261,-19.341,-18.252,-17.209,-15.994], 'diam':[0.442,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[129]': { 'x':[-398.619,-398.144,-396.833,-395.620,-394.129,-393.195,-391.656], 'y':[742.819,744.039,744.242,744.354,744.977,745.242,745.878], 'z':[-31.263,-30.283,-29.397,-29.496,-29.474,-29.020,-28.572], 'diam':[0.528,0.442,0.442,0.349,0.349,0.349,0.349] }, prefix + 'apic[121]': { 'x':[-395.218,-394.442,-392.681,-392.662,-392.284,-391.833,-391.694,-391.831,-391.358,-390.996,-390.826,-390.616,-390.174,-389.856,-389.471,-389.975,-389.094,-388.217], 'y':[740.049,740.470,742.068,742.957,743.347,744.253,744.763,745.305,746.466,746.931,747.742,748.447,749.095,749.411,749.985,751.045,751.172,750.404], 'z':[-36.531,-34.248,-32.785,-30.706,-29.154,-28.049,-26.876,-25.779,-24.940,-23.069,-22.177,-20.901,-18.759,-17.774,-16.807,-15.021,-13.488,-11.011], 'diam':[0.613,0.528,0.528,0.528,0.528,0.528,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[110]': { 'x':[-385.468,-387.572,-389.788,-391.006,-392.106,-393.081], 'y':[724.833,724.673,724.627,724.242,723.925,723.019], 'z':[-44.329,-45.429,-45.203,-43.626,-42.591,-41.593], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[106]': { 'x':[-402.452,-403.941,-404.936,-406.279,-407.311,-408.710,-410.147,-411.321,-412.445,-414.348,-415.722,-416.569,-417.334,-418.375], 'y':[733.848,734.898,734.288,735.318,736.342,736.824,737.289,737.867,738.070,738.011,738.010,738.637,738.109,737.668], 'z':[-36.376,-36.168,-36.322,-35.927,-35.044,-34.549,-34.458,-34.444,-34.199,-34.411,-33.981,-33.486,-32.905,-32.090], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[84]': { 'x':[-399.225,-400.103,-401.110,-401.373,-401.164,-401.370,-402.264,-403.218,-403.813,-404.231,-404.721,-405.639,-406.121,-406.493], 'y':[733.084,733.197,733.796,734.209,734.694,735.575,736.320,736.465,737.091,736.996,737.832,737.431,737.661,737.447], 'z':[-25.820,-24.007,-23.049,-22.161,-21.072,-19.401,-18.681,-17.993,-17.246,-15.982,-14.545,-12.813,-11.146,-10.109], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[138]': { 'x':[-395.800,-395.965,-396.134,-396.609,-397.328,-398.070,-399.140], 'y':[733.524,732.992,732.306,731.152,730.447,729.318,729.053], 'z':[-49.182,-50.780,-51.807,-53.077,-54.235,-54.980,-55.770], 'diam':[0.528,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[71]': { 'x':[-376.862,-378.454,-379.163], 'y':[723.172,723.508,723.461], 'z':[-46.307,-44.748,-44.007], 'diam':[0.706,0.877,0.877] }, prefix + 'apic[46]': { 'x':[-373.328,-374.274,-375.465], 'y':[731.957,734.034,733.094], 'z':[-19.495,-19.446,-19.025], 'diam':[0.349,0.349,0.349] }, prefix + 'apic[67]': { 'x':[-401.322,-403.370,-405.274,-406.226,-407.264,-408.568,-409.344,-409.866], 'y':[743.117,744.299,744.453,744.789,745.350,745.594,745.888,746.372], 'z':[-23.836,-23.740,-23.604,-22.887,-21.930,-21.080,-20.374,-19.399], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[119]': { 'x':[-390.228,-390.976,-392.517,-393.740,-394.546], 'y':[733.473,734.446,735.745,736.353,737.443], 'z':[-48.183,-46.963,-44.675,-42.952,-41.888], 'diam':[0.792,0.613,0.613,0.613,0.528] }, prefix + 'apic[72]': { 'x':[-379.163,-380.181,-381.890,-382.134], 'y':[723.461,724.379,725.773,726.717], 'z':[-44.007,-42.596,-40.784,-40.431], 'diam':[0.877,0.613,0.706,0.706] }, prefix + 'dend[11]': { 'x':[-294.791,-293.140,-292.783,-290.713,-290.655,-290.188,-288.506,-287.280,-286.090,-284.912,-285.133,-283.721,-282.796,-282.623,-282.502], 'y':[710.004,713.461,715.652,716.458,716.473,716.604,717.441,717.570,718.762,718.895,719.742,719.885,720.735,721.054,721.731], 'z':[-86.422,-85.845,-85.220,-83.665,-82.255,-81.122,-81.177,-80.922,-80.404,-79.352,-78.063,-77.651,-76.237,-74.944,-73.572], 'diam':[1.056,0.970,0.792,0.792,0.792,0.706,0.706,0.706,0.613,0.613,0.613,0.613,0.613,0.613,0.613] }, prefix + 'apic[122]': { 'x':[-388.217,-386.515,-385.184,-383.909,-382.779], 'y':[750.404,748.284,748.026,747.797,747.609], 'z':[-11.011,-11.024,-12.036,-12.709,-13.393], 'diam':[0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[49]': { 'x':[-369.377,-368.228,-367.476,-366.543], 'y':[728.596,727.114,725.964,725.221], 'z':[-20.031,-20.326,-19.765,-18.258], 'diam':[0.349,0.264,0.264,0.264] }, prefix + 'dend[5]': { 'x':[-316.649,-318.958,-318.981,-319.333,-320.244,-321.413,-322.842,-324.481,-325.669,-326.839,-328.090,-329.139,-330.198,-331.295,-333.278,-332.747,-331.998,-332.347,-332.276,-332.415,-332.778,-333.568,-333.965,-333.579,-332.436,-332.341,-332.329,-333.431,-333.684,-334.871,-335.965,-336.832,-337.691,-337.277,-336.875,-336.846,-337.515,-337.397,-338.426,-339.039,-339.107,-339.004,-339.427,-340.204,-340.455,-341.852,-342.206,-342.441,-343.182,-344.209,-343.085,-342.254,-344.055,-344.947,-344.602,-343.618,-343.279,-342.908,-343.759,-345.362,-346.787,-347.350,-346.364,-347.149,-347.365,-347.640,-348.724,-349.710,-351.060,-350.389,-350.014,-351.023,-352.021,-351.911,-353.296,-354.248,-354.893,-356.258,-357.746,-358.774,-359.466,-359.599,-361.041,-362.928,-364.470,-365.607,-366.839,-367.907,-369.602,-371.029,-372.248,-372.467,-372.430,-374.338,-375.407,-376.527,-377.433,-378.730,-379.878,-380.990,-381.925,-383.621,-384.549,-386.062,-386.751,-387.244,-388.160,-389.073,-390.029,-390.853,-391.545,-392.577,-393.437,-393.721,-395.070,-396.529,-397.119,-397.932,-398.996,-399.741,-401.409,-402.944,-404.120,-404.359,-405.317,-406.802,-407.860,-409.152,-410.414,-411.510,-412.517,-413.068,-413.433,-413.952,-414.417,-414.571,-414.548,-414.383], 'y':[714.484,716.593,718.184,716.186,717.644,718.233,719.091,719.448,719.313,719.418,720.599,721.048,721.170,721.395,721.354,722.579,723.203,723.854,724.553,724.896,725.306,725.287,725.570,725.498,726.193,727.513,728.054,728.854,729.625,729.489,731.018,731.739,732.271,732.529,734.471,736.637,737.154,738.074,738.658,739.201,739.808,742.433,743.500,743.371,744.331,744.318,744.245,745.964,746.608,747.151,747.645,748.057,749.000,750.458,751.448,752.148,753.193,754.235,755.250,755.168,754.970,756.855,757.453,757.620,757.751,758.042,758.596,758.589,759.962,760.707,761.837,762.908,763.340,763.650,764.305,765.202,766.530,768.380,769.992,770.601,771.804,772.282,772.908,773.040,773.002,772.898,772.962,772.991,773.544,773.667,773.671,774.578,775.392,775.525,775.479,776.353,776.592,776.886,776.758,776.634,777.459,778.340,778.455,779.689,780.327,780.651,780.483,780.313,781.298,781.902,783.166,783.597,784.795,784.952,784.832,784.678,784.742,785.722,786.506,786.587,787.436,788.051,788.074,787.471,788.881,789.500,789.952,790.847,791.594,791.883,791.638,791.490,792.315,793.171,793.332,794.332,794.514,795.050], 'z':[-111.225,-112.096,-112.778,-112.952,-112.086,-112.363,-112.727,-112.864,-113.338,-113.360,-113.583,-113.837,-114.419,-114.901,-115.908,-116.220,-117.276,-118.195,-118.920,-120.715,-121.987,-122.726,-123.758,-125.640,-127.540,-128.067,-129.492,-130.248,-131.623,-132.098,-132.665,-133.357,-134.616,-135.596,-135.639,-135.664,-136.645,-135.985,-135.773,-136.517,-137.608,-138.234,-138.390,-139.128,-140.062,-140.115,-141.237,-142.085,-143.330,-144.870,-145.470,-146.247,-147.042,-148.025,-148.484,-149.022,-150.634,-151.207,-153.307,-153.989,-154.985,-155.852,-156.962,-157.833,-159.045,-160.161,-160.904,-161.222,-162.184,-162.331,-163.013,-163.759,-164.807,-166.084,-167.110,-166.909,-166.093,-166.035,-165.757,-165.335,-165.266,-164.286,-164.368,-164.008,-164.724,-164.839,-165.324,-165.097,-165.881,-166.721,-167.310,-168.314,-169.388,-170.169,-170.854,-172.060,-172.520,-173.703,-174.731,-175.178,-175.785,-176.946,-178.194,-179.466,-180.153,-181.245,-182.477,-183.588,-185.357,-185.715,-186.803,-187.278,-189.062,-191.056,-193.691,-194.063,-195.156,-197.145,-197.544,-199.456,-200.944,-202.405,-203.334,-204.265,-205.276,-206.048,-206.190,-206.854,-207.607,-208.433,-209.774,-211.073,-212.885,-214.262,-216.731,-219.673,-221.165,-222.107], 'diam':[1.056,0.792,0.792,0.792,0.792,0.792,0.792,0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[97]': { 'x':[-362.285,-362.051,-362.069,-362.465,-362.054], 'y':[721.533,722.002,722.743,722.616,725.244], 'z':[-9.374,-7.838,-6.037,-4.512,-3.277], 'diam':[0.442,0.349,0.349,0.349,0.349] }, prefix + 'dend[9]': { 'x':[-294.830,-295.019,-296.705,-298.463,-299.485,-300.396,-300.541,-300.711,-300.967,-301.287,-302.167,-303.836,-304.771,-305.265,-305.334,-304.783,-304.938,-306.477,-306.579,-306.605,-306.689,-307.224,-308.364,-309.162,-309.453,-309.910,-311.716,-313.958,-314.448,-313.862,-313.425,-314.097,-315.684,-317.108,-317.128,-317.402,-317.895,-319.382,-320.558,-320.194,-321.449,-322.181,-323.190,-323.992,-325.336,-326.664,-328.158,-329.705,-330.207,-330.231,-329.519,-328.997,-329.664,-330.116,-329.647,-328.969,-328.500,-330.009,-330.995,-331.880,-332.206,-330.894,-330.321,-330.754,-331.398,-330.727,-330.165,-329.455,-329.211,-329.932,-330.788,-331.039,-330.200,-329.123,-330.442,-331.822,-332.370,-332.965,-333.966,-335.342,-336.305,-337.337,-338.062,-337.802,-336.979,-337.241,-337.839,-337.862,-337.650,-339.262,-340.757,-340.760,-339.830,-340.562,-341.519,-342.628,-343.668,-343.146,-343.413,-345.207,-345.814,-346.727,-348.098,-349.362,-350.359,-350.885,-350.409,-350.328,-350.100,-350.166,-351.863,-352.672,-352.830,-351.990,-351.964,-352.901,-353.631,-354.191,-353.962,-353.052,-352.448,-352.575,-352.585,-352.488,-352.743,-353.489,-352.411,-351.461,-351.838,-353.632,-354.914,-356.387,-357.193,-358.372,-359.149,-360.096,-360.043,-359.621,-359.522,-359.528,-359.507,-359.366,-358.791,-357.691,-358.258,-359.288,-360.272,-362.296,-361.057,-361.591,-360.769,-359.677,-359.492,-360.772,-362.029,-363.020,-362.052,-362.053,-362.828,-364.067,-365.062,-366.401,-368.134,-369.346,-370.330,-370.535,-371.044,-371.190,-371.517,-373.030,-374.155,-376.178,-377.205,-379.135,-379.908,-379.591,-381.050,-382.671,-384.904,-385.771,-386.850,-387.624,-389.130,-390.054,-390.873,-389.911,-390.880,-392.670,-393.909,-395.051,-394.087,-393.367,-394.004,-394.952,-395.290,-394.891,-394.160,-393.017,-391.815,-391.271,-392.436,-393.456,-393.611,-392.471,-392.044,-392.390,-392.691,-393.166,-395.432,-394.087,-392.539,-391.980,-391.454,-391.349,-393.052,-394.609,-394.727,-394.135,-392.862,-391.741,-391.197,-392.902,-394.211,-394.537,-395.048,-393.304,-393.007,-393.454,-394.327,-395.345,-395.379,-394.668,-393.616,-392.766,-391.684,-391.898,-393.057,-393.293,-392.370,-393.288,-395.177,-395.728,-394.366,-394.033,-395.375,-396.420,-397.630,-399.400,-400.338,-401.494,-402.032,-402.541,-402.933,-404.294,-405.208,-406.295,-407.326,-408.671,-409.401,-411.009,-410.883,-411.841,-414.295,-415.304,-416.806,-417.313,-417.892,-419.029,-420.457,-420.779,-420.403,-421.253,-422.369,-421.540,-421.434,-421.200,-420.936,-421.233,-422.947,-424.726,-425.650,-426.884,-426.475,-426.529,-427.484,-428.742,-429.364,-429.870,-430.119,-428.618,-430.383,-431.852,-432.922,-433.970,-433.098,-432.312,-431.996,-431.601,-432.153,-431.739,-433.528,-432.767,-431.738,-432.515,-432.570,-433.421,-433.545,-432.803,-432.798,-433.210,-433.374,-432.580,-433.241,-433.819,-434.415,-434.811,-434.381,-434.951,-437.417,-438.549,-439.545,-440.883,-441.895,-443.236,-443.498,-444.618,-445.658,-447.702,-448.539,-449.584,-451.291,-452.933,-454.340,-456.504,-459.001,-460.314,-461.831,-463.193,-465.030,-466.279,-468.057,-469.173,-470.487,-471.485,-472.819,-473.561,-474.700,-475.830,-475.782,-476.661,-477.651,-478.943,-479.486,-480.410,-479.879,-480.702,-481.437,-480.497,-480.641,-480.652,-482.521,-483.324,-484.395,-485.971,-486.452], 'y':[745.482,744.352,743.219,743.800,744.449,746.007,746.859,747.858,749.656,750.480,751.048,753.750,754.930,756.068,756.744,758.140,759.155,760.524,761.354,762.503,763.005,763.440,763.998,764.570,764.898,764.869,764.346,764.319,765.107,766.001,767.422,769.417,769.880,770.429,771.439,772.813,775.088,776.363,777.119,779.079,779.481,780.412,780.724,781.609,781.305,779.904,782.475,783.082,783.100,784.517,785.215,786.928,787.447,787.683,788.110,788.990,789.803,789.930,790.079,790.062,790.946,791.931,793.595,793.963,794.357,795.361,796.090,796.402,796.803,797.787,798.493,799.800,800.938,801.769,802.525,802.648,802.886,802.852,803.499,804.297,804.842,805.280,806.123,807.350,807.879,808.693,809.383,810.764,811.272,811.338,811.427,811.822,812.431,813.547,814.073,814.577,815.709,816.688,817.727,819.067,819.690,819.794,817.293,818.399,818.671,820.298,822.874,823.842,824.717,825.499,825.296,825.238,826.200,826.766,827.593,827.854,828.093,828.450,829.209,830.051,830.441,831.215,831.978,832.821,833.120,834.227,835.383,836.194,836.766,837.168,836.616,837.484,838.267,838.488,838.633,839.115,840.373,841.928,843.574,844.835,846.355,847.361,848.759,850.050,850.851,852.153,852.547,853.898,855.096,855.972,856.997,857.214,857.943,857.957,858.348,858.326,860.524,861.790,862.292,862.392,862.175,862.586,862.080,861.735,861.481,862.462,864.487,865.461,866.392,867.722,868.078,868.574,868.716,868.865,869.618,869.901,870.340,870.872,870.916,872.019,872.045,873.016,873.280,873.350,873.508,874.412,875.846,876.039,876.271,877.669,878.962,879.867,880.266,880.881,881.525,883.278,884.233,884.794,885.859,887.392,887.771,888.566,889.325,890.103,890.860,891.566,892.443,892.672,893.165,894.595,895.287,896.465,896.900,898.008,899.305,900.586,900.818,901.506,902.470,902.988,904.741,905.246,906.312,908.023,908.740,910.493,911.581,912.613,912.874,913.624,915.199,916.316,916.536,916.706,917.052,918.717,919.789,920.528,921.368,921.923,922.993,923.102,923.804,924.601,924.933,924.925,925.005,925.497,925.938,926.734,927.705,928.522,928.871,929.140,929.739,929.885,929.840,929.580,930.295,930.619,930.764,931.272,931.176,931.755,931.502,932.505,933.405,933.900,934.629,935.894,937.165,937.775,939.299,940.168,941.640,943.283,944.239,946.413,946.528,946.015,945.659,947.900,948.609,949.588,949.989,949.789,949.972,950.591,950.699,952.564,952.515,953.117,953.166,953.969,955.103,956.117,957.570,959.134,960.239,961.239,961.663,962.324,963.749,963.905,961.947,962.811,964.146,965.825,966.270,966.956,967.559,968.192,968.472,968.900,970.231,970.887,971.103,971.058,971.829,972.074,971.811,972.336,973.337,975.128,976.087,976.664,976.993,976.606,976.604,977.364,977.966,979.931,980.712,980.760,981.149,982.842,983.566,984.157,984.343,984.565,984.960,984.705,984.286,984.373,984.471,984.652,984.938,984.708,985.375,985.914,985.511,986.685,988.974,992.202,993.280,994.033,995.336,997.476,998.370,999.680,1001.725,1002.479,1002.545,1004.289,1006.041], 'z':[-106.725,-109.001,-108.739,-108.583,-108.530,-109.027,-110.074,-110.539,-111.014,-111.748,-111.112,-109.931,-109.796,-110.057,-111.248,-111.649,-112.218,-110.520,-109.243,-108.272,-107.280,-106.377,-106.834,-105.948,-104.900,-103.802,-103.701,-104.527,-104.958,-105.431,-105.847,-105.773,-104.451,-104.119,-105.376,-105.796,-106.933,-107.209,-107.178,-107.401,-107.662,-107.640,-107.868,-107.973,-108.780,-111.078,-111.654,-112.237,-113.297,-113.470,-114.266,-114.728,-115.497,-116.532,-117.827,-118.942,-119.958,-120.840,-120.978,-121.715,-122.088,-122.474,-123.397,-125.086,-127.132,-128.463,-128.913,-129.988,-131.190,-131.565,-132.212,-133.454,-133.032,-133.007,-133.891,-134.875,-136.128,-137.427,-138.890,-139.330,-139.656,-140.119,-141.324,-141.272,-140.139,-141.090,-141.841,-143.167,-144.467,-143.976,-143.472,-144.685,-145.027,-145.724,-145.835,-145.715,-146.900,-147.905,-148.020,-146.709,-145.856,-145.334,-146.157,-146.100,-146.461,-146.981,-148.361,-149.509,-150.767,-148.395,-147.469,-146.155,-144.677,-143.876,-142.637,-142.195,-141.415,-140.370,-138.440,-136.463,-135.128,-133.322,-131.525,-129.821,-127.852,-126.957,-126.535,-126.276,-125.204,-124.914,-122.076,-120.340,-119.029,-119.870,-120.930,-122.629,-123.057,-123.305,-122.765,-121.249,-120.840,-121.504,-122.923,-123.271,-121.958,-121.172,-120.607,-119.529,-119.662,-119.014,-118.052,-117.621,-116.620,-115.651,-114.760,-114.241,-113.129,-111.731,-111.145,-110.962,-111.166,-110.723,-110.574,-110.537,-110.832,-111.761,-112.573,-114.296,-115.125,-114.001,-112.972,-113.209,-114.375,-114.555,-113.352,-112.165,-111.832,-112.856,-113.402,-112.279,-110.489,-111.888,-113.526,-114.229,-115.044,-117.066,-117.402,-118.132,-118.265,-117.808,-117.967,-118.300,-119.307,-121.780,-122.981,-123.681,-124.349,-124.124,-123.505,-123.657,-123.993,-124.409,-125.114,-125.915,-126.492,-127.790,-128.509,-129.527,-129.894,-130.940,-131.949,-132.699,-133.438,-134.220,-133.799,-135.302,-136.435,-137.355,-137.192,-136.527,-135.854,-135.750,-136.588,-136.873,-137.603,-137.112,-137.211,-138.369,-138.829,-139.236,-139.855,-139.136,-137.927,-137.191,-136.999,-137.042,-138.456,-139.750,-139.278,-138.564,-137.944,-138.976,-139.081,-140.226,-141.159,-141.426,-141.461,-141.932,-142.262,-142.554,-143.842,-146.616,-147.514,-147.864,-149.089,-149.461,-149.851,-150.039,-150.895,-151.377,-150.339,-148.826,-149.043,-148.904,-148.525,-146.954,-145.606,-144.923,-144.310,-144.874,-144.941,-145.590,-145.796,-145.791,-144.587,-144.171,-145.085,-144.277,-143.979,-143.878,-143.040,-142.802,-143.534,-142.986,-141.908,-141.910,-143.482,-144.777,-146.473,-146.765,-147.099,-147.926,-148.816,-149.406,-149.876,-150.466,-151.011,-151.435,-150.980,-149.861,-149.800,-150.081,-149.384,-148.444,-147.844,-146.951,-148.078,-149.628,-150.950,-151.670,-152.860,-153.838,-154.822,-156.033,-157.488,-159.356,-160.253,-161.386,-162.532,-162.487,-162.628,-162.317,-161.640,-161.902,-162.831,-162.415,-161.915,-161.242,-160.431,-161.141,-161.516,-160.725,-161.089,-160.943,-161.476,-160.734,-160.286,-160.674,-159.941,-160.474,-160.646,-160.657,-160.211,-159.288,-159.365,-160.144,-161.011,-161.364,-160.617,-159.636,-159.971,-159.261,-158.119,-157.558,-157.351,-156.804,-156.222,-155.675,-155.124,-155.682,-157.387,-157.305,-157.856,-157.899,-158.404], 'diam':[1.584,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.141,1.141,1.141,1.056,1.056,1.056,1.056,1.056,1.056,1.056,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,1.141,1.141,1.141,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.706,0.706,0.706,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.528,0.528,0.528,0.528] }, prefix + 'apic[133]': { 'x':[-395.800,-396.659,-398.062,-399.762,-401.076,-401.844,-402.367,-402.802,-403.344], 'y':[733.524,734.243,734.271,734.799,735.448,736.263,736.813,737.474,738.048], 'z':[-49.182,-48.793,-48.810,-47.874,-46.669,-45.895,-45.210,-44.141,-43.286], 'diam':[0.528,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442] }, prefix + 'apic[52]': { 'x':[-369.473,-368.533], 'y':[726.158,725.556], 'z':[-29.787,-29.616], 'diam':[0.442,0.349] }, prefix + 'apic[60]': { 'x':[-375.585,-374.330,-373.399], 'y':[726.541,725.473,724.744], 'z':[-37.841,-38.464,-38.753], 'diam':[0.613,0.349,0.349] }, prefix + 'apic[29]': { 'x':[-363.474,-361.593,-360.236,-356.998,-355.747,-354.171], 'y':[708.950,709.223,709.329,710.767,711.430,711.753], 'z':[-30.479,-31.285,-31.665,-31.946,-31.404,-31.184], 'diam':[0.442,0.442,0.442,0.442,0.442,0.442] }, prefix + 'apic[83]': { 'x':[-396.249,-397.668,-398.580,-399.275,-398.445,-399.225], 'y':[731.890,732.937,732.567,731.888,733.471,733.084], 'z':[-29.596,-29.295,-29.020,-28.390,-27.647,-25.820], 'diam':[0.442,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[141]': { 'x':[-405.528,-407.064,-407.997,-409.379,-410.668,-413.057,-414.735,-415.819], 'y':[741.655,740.806,741.126,741.189,741.166,742.567,742.282,742.290], 'z':[-49.825,-48.485,-47.945,-47.974,-48.236,-47.509,-46.876,-46.560], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[32]': { 'x':[-374.047,-375.377,-376.578,-376.863,-376.698,-376.712,-375.809,-375.324,-373.768,-373.132,-372.237,-370.628,-368.896,-365.873], 'y':[713.597,714.397,714.061,713.488,713.107,711.757,711.765,711.906,711.252,711.417,711.263,710.982,709.197,709.878], 'z':[-36.870,-36.237,-35.099,-34.175,-33.014,-30.618,-29.134,-28.005,-27.161,-25.704,-24.674,-24.485,-24.259,-25.370], 'diam':[1.056,0.613,0.613,0.613,0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.264,0.264,0.264] }, prefix + 'apic[10]': { 'x':[-361.157,-360.269,-359.369,-358.779,-357.548,-356.271], 'y':[717.776,716.766,715.817,715.534,714.767,714.283], 'z':[-40.571,-41.634,-42.525,-43.829,-45.002,-46.011], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'dend[3]': { 'x':[-298.473,-300.796], 'y':[711.113,716.093], 'z':[-91.333,-93.880], 'diam':[2.111,2.639] }, prefix + 'apic[96]': { 'x':[-356.531,-355.340,-355.120,-355.284,-355.345,-355.552,-355.564,-355.514,-356.372,-356.873,-357.634,-358.764,-359.947,-359.490], 'y':[719.306,718.169,718.525,719.169,719.818,720.428,721.228,721.833,721.206,721.586,722.125,722.048,723.032,725.088], 'z':[-4.255,-4.066,-2.835,-1.689,-0.632,0.534,1.869,2.673,3.478,5.167,6.038,7.003,8.150,8.067], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[57]': { 'x':[-365.713,-366.883,-367.364,-367.951,-367.590,-366.086,-365.206,-365.642], 'y':[723.216,724.451,724.954,725.173,725.573,726.170,726.953,728.929], 'z':[-29.929,-28.596,-27.811,-26.825,-25.103,-24.034,-21.788,-19.918], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[14]': { 'x':[-349.325,-348.724,-348.591,-347.995,-347.016], 'y':[719.230,719.576,719.953,720.240,720.597], 'z':[-30.168,-28.356,-27.211,-26.319,-25.730], 'diam':[0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[101]': { 'x':[-380.344,-381.313,-383.489], 'y':[724.015,724.347,724.129], 'z':[-44.355,-45.068,-44.607], 'diam':[0.613,0.613,0.613] }, prefix + 'apic[86]': { 'x':[-382.134,-383.162,-383.728], 'y':[726.717,727.850,729.654], 'z':[-40.431,-37.872,-36.522], 'diam':[0.706,0.264,0.264] }, prefix + 'apic[88]': { 'x':[-383.728,-385.207,-385.674,-387.048,-388.106,-388.561,-388.470,-389.568], 'y':[729.654,730.487,731.331,733.054,734.254,735.086,734.935,735.387], 'z':[-36.522,-36.485,-37.028,-36.814,-36.334,-37.654,-39.407,-40.369], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'dend[10]': { 'x':[-294.830,-295.640,-295.450,-294.694,-294.726,-293.419,-294.203,-295.289,-295.734,-296.180,-295.141,-293.543,-292.051,-290.781,-289.723,-289.378,-288.088,-286.941,-285.542,-284.092,-283.645,-284.772,-285.999,-287.526,-288.461,-287.967,-287.483,-286.755,-286.283,-287.194,-287.998,-287.085,-285.126,-284.878,-285.347,-285.881,-286.782,-287.650,-289.126,-290.105,-289.804,-289.077,-288.715,-287.721,-287.381,-287.442,-288.738,-289.723,-289.561,-288.807,-287.963,-287.514,-286.662,-284.561,-282.570,-281.217,-279.802,-280.861,-279.524,-278.765,-278.790,-278.763,-279.020,-279.999,-281.548,-282.640,-284.015,-284.705,-286.890,-288.634,-289.180,-288.230,-287.276,-287.563,-288.513,-289.974,-290.591,-290.583,-290.845,-292.186,-291.397,-290.192,-288.949,-290.005,-290.912,-291.519,-292.976,-292.787,-291.593,-290.416,-290.066,-290.697,-292.022,-293.006,-294.076,-294.929,-296.013,-294.622,-293.443,-291.774,-290.253,-290.273,-290.721,-290.340,-290.745,-290.617,-290.264,-290.234,-290.235,-290.868,-292.060,-293.410,-292.706,-291.754,-290.734,-291.977,-291.036,-290.427,-291.333,-290.860,-289.640,-289.288,-287.986,-289.078,-289.939,-290.730,-289.432,-288.759,-288.180,-288.007,-288.023,-288.613,-286.807,-285.979,-286.101,-286.037,-285.054,-284.233,-282.866,-281.557,-280.836,-280.910,-281.131,-281.975,-282.513,-282.688,-282.261,-281.770,-280.603,-279.859,-280.361,-282.253,-283.264,-282.732,-282.137,-281.988,-282.627,-283.196,-284.436,-285.389,-284.651,-284.775,-285.236,-286.796,-286.976,-288.348,-289.963,-291.327,-291.775,-293.295,-294.377,-293.032,-292.165,-291.113,-290.569,-291.294,-292.152,-292.846,-293.153,-294.779,-295.386,-296.052,-295.753,-295.155,-295.122,-294.939,-294.601,-293.442,-292.931,-293.528,-294.743,-295.864,-296.547,-295.360,-294.388,-295.357,-295.475,-294.593,-294.070,-293.536,-293.127,-294.477,-296.176,-297.756,-296.429,-296.297,-297.212,-298.384,-299.767,-300.285,-299.916,-299.912,-298.850,-298.943,-299.973,-300.784,-299.826,-297.522,-296.326,-295.507,-295.883,-296.436,-296.757,-296.521,-295.509,-295.312,-294.807,-294.535,-293.400,-292.763,-292.063,-291.696,-291.394,-291.458,-290.967,-290.335,-289.100,-287.852,-286.254,-287.387,-287.607,-286.741,-286.054,-286.971,-287.103,-286.690,-286.365,-285.563,-285.540,-286.532,-285.872,-284.207,-284.595,-285.816,-284.811,-283.500,-282.449,-281.391,-280.330,-279.739,-280.892,-281.820,-281.522,-280.317,-279.438,-279.451,-279.025,-278.612,-277.884,-277.873,-278.237,-279.036,-280.243,-279.809,-280.535,-282.726,-282.178,-281.502,-280.590,-279.864,-280.728,-281.723,-281.630,-279.935,-279.132,-278.168,-278.580,-279.378,-278.334,-277.403,-276.584,-275.921,-275.876,-276.302,-277.218,-277.648,-277.335,-276.456,-274.987,-273.699,-273.814,-273.212,-272.275,-271.599,-271.412,-271.380,-270.604,-270.203,-269.480,-268.753,-268.081,-267.393,-267.292,-266.883,-267.076,-265.014,-264.290,-264.039,-262.618,-261.282,-262.425,-262.780,-263.712,-264.416,-265.944,-265.798,-266.823,-268.222,-268.103,-269.320,-271.102,-271.123,-272.291,-273.089,-273.453,-273.855,-274.027,-274.532,-273.968,-273.611,-273.352,-273.484,-274.913,-275.586,-276.510,-277.437,-278.891,-279.648,-280.840,-281.086], 'y':[745.482,746.323,747.646,748.524,749.509,750.408,750.717,750.473,751.163,751.672,752.517,753.937,754.461,754.845,755.100,755.777,756.626,757.502,758.334,759.625,760.588,761.357,761.442,761.090,760.913,760.945,762.316,762.545,762.904,764.097,764.358,764.552,765.070,766.644,767.398,768.069,769.216,769.587,769.847,770.637,771.453,773.289,774.297,774.342,774.418,774.815,775.468,776.002,776.513,777.358,778.200,778.183,778.263,778.834,779.155,780.377,781.161,781.504,782.205,782.355,783.203,783.838,783.955,783.918,785.194,785.959,785.531,785.061,786.160,786.973,787.759,788.539,788.709,789.764,790.141,790.409,790.725,792.382,794.290,794.376,795.120,796.156,796.591,796.930,797.444,797.650,798.326,800.033,801.091,801.919,802.892,802.836,802.817,802.335,802.608,802.521,802.740,803.561,804.290,804.856,805.304,805.871,807.286,808.349,809.460,810.533,812.071,812.684,814.192,814.926,815.572,815.459,816.363,816.928,818.213,819.281,820.935,821.483,822.190,823.709,824.308,825.288,826.651,827.713,828.176,828.912,829.962,830.335,832.120,833.286,834.188,835.165,836.239,836.385,837.249,838.348,839.166,840.376,841.048,841.790,842.943,843.781,843.652,843.947,844.110,844.899,846.084,847.766,849.226,849.725,850.301,851.091,851.636,853.324,854.041,855.905,856.635,856.565,856.063,856.572,857.087,858.036,858.036,858.056,859.055,859.708,860.245,860.190,859.869,859.759,859.923,860.517,861.216,862.943,864.205,864.936,865.443,865.994,865.909,866.688,867.465,868.476,869.473,870.247,871.910,872.280,873.615,874.409,875.413,876.129,875.783,875.408,876.724,877.666,878.364,879.340,880.762,881.410,882.182,882.953,884.001,884.930,885.758,887.083,888.550,889.544,889.899,889.804,890.602,891.153,893.699,894.523,895.364,896.593,896.473,896.544,897.133,898.282,899.547,899.869,900.375,900.356,901.662,902.902,904.082,906.131,906.871,907.288,908.810,909.763,910.461,912.949,914.172,914.976,915.570,916.028,916.328,917.520,918.260,919.557,920.576,921.229,922.115,922.527,923.203,924.092,925.082,927.253,927.829,928.464,929.980,931.387,932.136,932.684,933.712,934.132,934.658,935.104,935.552,936.227,936.293,936.471,937.334,938.134,938.779,940.212,942.746,943.796,944.968,946.523,946.690,946.777,947.102,948.325,949.385,950.040,950.809,951.698,952.073,953.409,954.081,953.945,953.993,955.051,955.992,956.772,957.517,957.635,958.779,959.302,960.151,960.590,962.092,962.801,963.434,964.650,965.940,966.991,967.431,968.398,970.102,970.935,971.441,972.836,973.836,974.492,976.023,977.468,979.159,980.782,981.800,982.252,982.646,983.729,984.908,986.277,987.098,988.355,989.613,990.823,992.339,993.678,994.871,995.314,996.185,996.949,998.115,998.006,998.924,999.465,999.977,1002.189,1003.349,1004.127,1004.972,1006.830,1007.091,1008.878,1007.774,1008.625,1009.830,1011.138,1013.236,1013.463,1013.742,1014.491,1015.413,1016.021,1018.192,1019.920], 'z':[-106.725,-104.402,-104.064,-105.445,-106.001,-106.473,-104.117,-103.170,-102.444,-101.508,-101.794,-102.603,-103.570,-103.782,-102.764,-101.798,-100.892,-101.175,-100.829,-100.758,-101.246,-102.691,-103.914,-104.208,-103.566,-102.440,-101.815,-100.972,-100.156,-98.965,-97.658,-96.445,-96.068,-93.927,-91.931,-90.748,-90.137,-90.569,-90.075,-89.299,-88.788,-88.856,-89.000,-89.185,-87.971,-86.985,-86.747,-87.989,-89.510,-89.606,-88.312,-86.854,-85.780,-85.595,-85.738,-85.687,-85.357,-83.492,-82.024,-79.331,-77.932,-76.449,-75.302,-74.549,-74.478,-74.313,-73.870,-71.212,-70.170,-69.143,-68.174,-66.429,-65.554,-64.304,-64.075,-64.588,-65.380,-65.188,-64.173,-64.129,-64.564,-65.174,-64.485,-63.024,-62.444,-61.532,-61.997,-61.327,-60.672,-60.399,-59.243,-57.332,-55.693,-53.745,-53.310,-52.796,-53.290,-52.888,-53.648,-54.069,-53.707,-52.611,-51.893,-51.522,-50.270,-49.679,-50.393,-51.238,-50.596,-48.377,-47.794,-46.851,-45.562,-45.900,-45.350,-43.929,-43.680,-42.775,-41.480,-40.714,-40.116,-40.549,-40.557,-39.679,-39.453,-39.636,-38.637,-37.882,-37.865,-38.062,-36.700,-35.705,-36.511,-35.637,-34.191,-33.022,-33.222,-34.066,-34.252,-33.754,-33.343,-32.566,-30.887,-28.946,-27.472,-26.474,-25.632,-27.004,-27.216,-26.436,-25.253,-25.039,-23.424,-22.626,-23.425,-22.851,-20.523,-19.297,-18.398,-17.367,-15.204,-14.075,-12.833,-12.804,-13.841,-13.836,-13.393,-12.565,-10.576,-9.190,-8.195,-7.708,-7.581,-8.690,-9.316,-8.804,-7.427,-6.598,-5.595,-4.446,-4.042,-2.491,-2.252,-3.511,-3.892,-2.930,-2.765,-2.181,-1.357,-0.847,-0.820,-0.324,0.825,0.517,0.975,2.527,3.594,3.823,3.353,2.890,3.022,3.419,2.312,0.806,-0.126,-0.806,-1.147,-0.974,-1.390,-3.061,-2.988,-1.294,-0.937,0.570,0.398,1.515,2.532,2.299,2.493,3.130,4.770,6.001,7.164,7.421,6.901,7.835,9.644,10.954,10.951,11.536,12.329,12.501,13.680,14.802,13.975,13.243,13.209,12.701,12.519,11.419,10.613,9.228,9.590,9.142,8.299,7.389,7.281,7.670,6.708,6.404,6.254,5.790,4.953,4.958,5.346,5.327,5.203,5.285,5.377,4.556,3.731,2.570,1.539,1.672,1.891,3.192,4.060,4.201,4.478,5.106,6.028,7.042,7.709,8.668,9.557,9.323,10.453,10.808,11.682,11.403,12.586,13.792,15.628,16.146,16.291,16.414,17.735,18.413,19.380,19.355,19.484,20.120,21.858,23.521,23.897,25.154,24.176,24.435,24.281,24.012,23.389,21.977,21.220,21.698,22.128,23.446,22.439,23.721,22.972,22.885,22.978,23.583,25.097,24.869,24.064,25.024,24.068,23.733,24.628,23.602,23.076,22.187,21.743,20.545,19.059,18.104,17.099,16.873,15.830,14.866,13.575,13.336,13.575,12.418,11.819,11.885,10.431,10.393,10.053,9.326,8.989,8.659,8.666,10.176,11.015,11.316,11.096,10.590,9.106,9.400], 'diam':[1.584,1.405,1.405,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.056,1.056,1.056,1.056,1.141,1.141,1.141,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,0.877,0.877,0.877,0.877,0.877,0.877,0.970,1.056,1.234,1.234,1.234,1.234,1.234,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.405,1.405,1.141,1.141,1.141,1.056,1.056,1.056,1.056,1.056,1.056,1.056,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,1.056,1.056,1.056,1.056,1.056,1.056,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,1.141,1.141,1.141,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.706,0.706,0.706,0.706,0.613,0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[53]': { 'x':[-368.533,-367.013,-365.713], 'y':[725.556,724.272,723.216], 'z':[-29.616,-30.325,-29.929], 'diam':[0.349,0.349,0.349] }, prefix + 'apic[1]': { 'x':[-307.800,-309.439,-311.572,-313.045,-313.279,-315.185,-316.904,-318.742,-320.373,-321.410,-321.222,-321.668,-323.198,-324.584,-325.879,-326.960,-327.741,-328.353,-328.294,-328.457,-329.281,-330.732,-331.515,-332.332,-333.168,-334.237,-336.066,-337.787,-339.737,-340.831,-341.487,-342.366,-342.826,-343.405,-344.321,-345.188,-346.907,-348.249,-349.687,-351.307,-352.654,-354.178,-355.769,-356.813,-358.275,-359.786,-361.096,-363.107,-364.527,-365.814], 'y':[701.708,701.662,700.645,700.201,700.482,701.080,700.706,700.313,700.961,702.195,702.784,703.712,703.310,704.513,704.891,705.222,704.637,704.477,704.542,704.697,705.028,704.913,704.687,704.686,704.855,705.066,705.481,705.046,704.039,703.520,704.217,705.076,705.891,706.454,707.485,708.339,709.030,709.653,710.322,710.922,710.819,711.232,711.320,711.501,712.310,713.047,714.291,714.824,716.382,717.747], 'z':[-88.086,-90.825,-90.843,-89.633,-88.540,-88.394,-88.943,-89.127,-88.912,-87.526,-85.778,-84.205,-81.907,-81.152,-80.442,-79.474,-78.447,-77.487,-76.303,-74.644,-73.606,-74.331,-75.064,-75.881,-76.500,-77.378,-78.038,-78.291,-77.378,-76.514,-75.711,-74.685,-73.416,-70.455,-68.446,-67.427,-67.078,-67.054,-67.400,-68.040,-67.660,-67.217,-66.905,-66.742,-65.842,-64.732,-63.742,-61.937,-60.204,-58.901], 'diam':[2.111,2.290,1.933,1.762,1.762,1.762,1.762,1.762,1.762,2.111,2.111,2.111,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.847] }, prefix + 'axon': { 'x':[-295.384,-292.833,-291.698,-290.797,-290.500,-290.190,-290.049,-289.817,-289.077,-288.859], 'y':[727.861,726.253,727.784,728.697,729.609,729.827,730.979,731.298,731.819,732.157], 'z':[-103.483,-106.215,-107.317,-107.620,-108.480,-109.789,-111.454,-112.411,-114.434,-116.668], 'diam':[1.847,0.792,0.792,0.792,0.613,0.613,0.613,0.613,0.613,0.613] }, prefix + 'apic[103]': { 'x':[-385.468,-386.636,-387.519], 'y':[724.833,725.405,726.008], 'z':[-44.329,-43.700,-43.616], 'diam':[0.349,0.349,0.442] }, prefix + 'apic[36]': { 'x':[-377.821,-376.611,-375.585], 'y':[725.564,725.842,726.541], 'z':[-41.334,-38.724,-37.841], 'diam':[0.792,0.528,0.613] }, prefix + 'apic[143]': { 'x':[-392.313,-393.149,-393.620,-395.844,-396.906,-397.972], 'y':[732.909,733.729,735.242,733.712,733.360,733.506], 'z':[-53.049,-52.525,-52.809,-51.594,-50.897,-50.708], 'diam':[0.442,0.085,0.085,0.085,0.085,0.085] }, prefix + 'apic[65]': { 'x':[-399.375,-401.214,-402.006,-403.047,-404.055,-405.285,-406.241], 'y':[745.313,746.594,747.718,748.440,748.906,749.265,749.621], 'z':[-22.443,-22.214,-22.578,-22.794,-22.473,-21.685,-21.414], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[81]': { 'x':[-405.902,-406.027,-406.669], 'y':[732.221,731.166,729.976], 'z':[-32.098,-33.508,-33.897], 'diam':[0.264,0.179,0.179] }, prefix + 'apic[111]': { 'x':[-393.081,-391.578,-390.541,-390.563], 'y':[723.019,723.229,722.316,720.782], 'z':[-41.593,-41.918,-41.138,-40.745], 'diam':[0.349,0.349,0.349,0.349] }, prefix + 'apic[7]': { 'x':[-361.157,-360.532,-359.778,-359.362], 'y':[717.776,716.952,716.330,715.202], 'z':[-40.571,-39.099,-37.884,-36.885], 'diam':[0.264,0.264,0.264,0.264] }, prefix + 'apic[139]': { 'x':[-382.274,-384.558,-385.357,-386.809,-389.189,-390.467,-391.748,-392.313], 'y':[727.857,729.161,729.749,730.364,731.240,731.586,731.815,732.910], 'z':[-51.928,-52.365,-52.188,-52.683,-52.171,-51.808,-51.728,-53.049], 'diam':[0.877,0.442,0.442,0.442,0.442,0.442,0.442,0.442] }, prefix + 'apic[22]': { 'x':[-363.474,-362.344], 'y':[708.950,708.536], 'z':[-30.479,-29.530], 'diam':[0.442,0.528] }, prefix + 'apic[61]': { 'x':[-377.821,-378.506], 'y':[725.564,727.022], 'z':[-41.334,-41.156], 'diam':[0.792,0.349] }, prefix + 'dend[12]': { 'x':[-282.502,-282.951,-283.264,-282.651,-281.742,-281.836,-281.521,-281.167,-280.261,-278.950,-277.874,-277.453,-276.385,-275.693,-276.174,-275.823,-274.889,-275.709,-275.128,-274.394,-273.690,-273.799,-275.126,-274.183,-273.470,-273.059,-272.762,-272.434,-271.538,-270.287,-270.580,-269.918,-268.621,-268.176,-268.772,-268.324,-267.145,-266.008,-265.314,-264.971,-264.444,-264.715,-264.102,-263.089,-262.318,-261.276,-261.048,-260.969,-261.047,-260.995,-260.433,-259.366,-258.657,-257.841,-257.720,-256.785,-254.819,-253.896,-252.407,-251.150,-250.773,-249.012,-247.861,-247.108,-246.989,-246.580,-247.266,-247.012,-247.095,-247.104,-247.176,-245.840,-245.147,-244.552,-243.213,-242.054,-241.056,-240.447,-239.043,-238.465,-238.359,-235.924,-235.064,-233.719,-232.133,-231.126,-230.411,-230.062,-229.061,-228.056,-227.361,-225.939,-224.848,-223.318,-222.018,-221.262,-219.883,-219.418,-218.863,-217.762,-216.335,-215.267,-214.578,-213.499,-212.182,-211.160,-210.388,-210.073,-209.702,-209.145,-208.096,-207.482,-205.906,-204.867,-204.319,-203.235,-200.866,-200.512,-200.397,-200.008,-199.882,-199.628,-199.439,-199.189,-198.568,-197.782,-196.711,-195.691,-194.392,-193.562,-192.465,-191.441,-190.536,-189.684,-189.133,-188.724,-188.509,-188.375,-188.037,-187.356,-187.103,-187.114,-187.182,-186.890,-186.045,-185.187,-184.586,-183.717], 'y':[721.731,723.508,723.561,724.266,724.692,725.009,725.765,726.947,727.081,727.791,729.214,729.553,729.779,730.419,730.667,731.556,731.831,732.378,734.065,734.694,736.106,736.763,737.736,738.712,740.218,740.703,742.478,743.779,744.535,745.910,747.546,748.483,748.466,749.956,750.926,753.573,753.809,753.092,754.314,755.303,757.112,758.114,759.318,759.846,761.132,761.416,762.450,762.994,763.931,764.339,764.522,764.748,765.485,766.124,766.848,767.021,767.323,767.592,767.866,768.377,770.324,771.279,772.052,772.812,773.893,775.147,776.156,778.003,778.891,779.908,780.645,781.069,781.416,782.234,783.380,783.523,784.005,785.152,786.327,787.191,790.048,793.872,793.985,794.966,795.667,796.979,797.446,798.496,799.618,800.332,801.033,802.141,802.513,803.300,803.648,804.033,804.516,805.384,806.469,806.778,806.996,807.415,807.991,809.207,810.207,811.315,812.667,813.882,815.138,817.123,818.453,820.292,821.042,821.963,823.055,823.899,825.768,826.825,828.414,828.547,828.693,829.568,829.804,830.557,833.493,834.459,834.796,835.914,836.508,837.483,838.077,838.960,839.785,840.605,842.354,843.259,843.669,844.165,846.122,846.735,847.718,848.847,851.647,854.513,855.301,857.066,858.903,860.322], 'z':[-73.572,-71.714,-70.740,-70.083,-69.566,-68.090,-67.158,-66.572,-65.932,-64.657,-64.282,-63.052,-63.774,-63.428,-61.807,-61.097,-59.996,-57.996,-57.633,-58.102,-58.156,-57.410,-57.063,-55.885,-56.053,-54.848,-54.316,-54.799,-53.840,-53.668,-53.023,-52.715,-51.782,-50.625,-50.462,-50.540,-50.076,-49.559,-49.490,-48.790,-48.794,-48.568,-49.802,-48.691,-49.076,-49.689,-48.428,-47.404,-45.153,-43.898,-42.737,-42.300,-41.507,-41.256,-39.876,-39.346,-38.258,-37.726,-37.085,-36.387,-35.717,-35.065,-34.755,-34.767,-35.285,-34.454,-34.442,-34.274,-33.770,-33.024,-31.931,-31.790,-30.726,-31.139,-30.806,-30.214,-29.579,-29.062,-29.067,-28.310,-27.902,-27.288,-26.747,-27.252,-27.594,-27.358,-26.750,-26.558,-26.077,-25.115,-24.638,-24.803,-24.489,-24.380,-23.826,-23.016,-22.225,-21.896,-21.462,-21.240,-20.661,-19.088,-18.378,-18.703,-17.718,-16.214,-15.894,-15.373,-14.520,-13.688,-13.791,-14.670,-15.015,-14.632,-14.196,-14.143,-12.727,-12.539,-11.731,-9.870,-8.835,-7.615,-6.134,-4.674,-4.366,-3.797,-3.234,-2.879,-2.554,-2.432,-1.216,-0.727,-0.114,1.058,2.127,3.010,4.037,5.623,6.422,7.134,7.202,7.447,7.930,8.199,8.336,8.112,8.494,8.937], 'diam':[0.613,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.613,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[0]': { 'x':[-297.860,-301.678,-304.183,-306.007,-306.943,-307.800], 'y':[705.320,703.593,702.770,702.413,701.533,701.708], 'z':[-86.808,-85.198,-84.344,-84.329,-85.871,-88.086], 'diam':[3.082,2.197,2.290,2.026,2.026,2.111] }, prefix + 'apic[69]': { 'x':[-378.506,-379.512,-381.424,-381.525,-382.168,-382.693,-382.760,-382.899,-382.684], 'y':[727.022,729.156,729.306,732.428,733.429,734.979,735.904,736.649,737.085], 'z':[-41.156,-39.212,-37.874,-37.467,-36.173,-34.131,-33.186,-32.499,-31.557], 'diam':[0.349,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[63]': { 'x':[-398.247,-398.575,-399.375], 'y':[742.846,744.331,745.313], 'z':[-24.556,-23.585,-22.443], 'diam':[0.349,0.264,0.264] }, prefix + 'apic[43]': { 'x':[-365.089,-364.095,-363.786,-363.053,-361.267,-360.283,-359.567,-359.700,-359.717,-359.359,-358.745,-358.229,-357.819,-357.919,-356.174,-353.860,-352.695,-351.931,-352.066,-351.850,-352.304,-352.948,-355.406,-357.292,-358.293,-359.474], 'y':[732.271,731.448,730.651,730.469,731.074,731.081,731.639,732.750,733.367,733.577,733.590,733.950,734.561,734.489,735.624,735.539,735.280,735.259,736.319,737.215,738.411,739.295,738.353,738.555,738.629,738.284], 'z':[-3.214,-1.161,-0.621,0.093,1.827,3.405,5.921,7.997,9.324,10.252,11.257,12.974,15.144,17.122,18.674,21.851,23.084,24.246,26.174,27.649,29.726,30.552,31.291,31.413,30.925,30.508], 'diam':[0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[8]': { 'x':[-359.362,-358.113,-357.193,-355.757], 'y':[715.202,714.929,715.687,716.173], 'z':[-36.885,-35.572,-35.639,-35.725], 'diam':[0.264,0.264,0.264,0.264] }, prefix + 'apic[19]': { 'x':[-374.047,-372.254,-371.023], 'y':[713.597,714.780,715.203], 'z':[-36.870,-35.253,-34.276], 'diam':[1.056,0.877,0.877] }, prefix + 'apic[99]': { 'x':[-366.046,-365.031,-364.659,-363.949,-363.236,-362.423,-360.957,-359.890,-358.716,-358.415], 'y':[719.602,718.590,717.328,715.568,714.673,713.731,712.309,710.972,710.110,709.056], 'z':[-24.003,-24.716,-25.226,-24.867,-25.013,-25.397,-26.244,-25.981,-25.904,-25.699], 'diam':[0.613,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349] }, prefix + 'apic[55]': { 'x':[-352.948,-352.323,-351.955], 'y':[715.283,716.032,715.597], 'z':[-36.221,-38.168,-39.754], 'diam':[0.349,0.349,0.349] }, prefix + 'apic[131]': { 'x':[-394.546,-395.178,-396.816,-398.059,-397.235,-397.128,-397.378], 'y':[737.443,739.653,741.496,742.931,744.586,745.804,746.403], 'z':[-41.888,-40.861,-37.837,-35.203,-34.149,-33.312,-32.400], 'diam':[0.528,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[41]': { 'x':[-373.328,-372.916,-372.633,-371.503,-370.648,-369.763,-369.576,-368.603,-367.886,-367.894,-366.920,-366.165], 'y':[731.957,732.107,732.450,733.358,733.361,732.488,732.939,733.302,733.131,732.243,732.328,732.626], 'z':[-19.495,-18.466,-17.135,-14.191,-12.347,-12.156,-11.053,-9.863,-8.978,-8.057,-5.991,-4.049], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[50]': { 'x':[-371.908,-372.309,-372.937,-373.834,-374.959,-375.629,-376.311], 'y':[728.584,729.840,730.617,731.047,731.564,732.200,733.169], 'z':[-28.319,-29.607,-28.661,-27.823,-27.087,-25.832,-24.348], 'diam':[0.528,0.528,0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[2]': { 'x':[-365.814,-368.681,-369.788,-371.406], 'y':[717.747,716.931,718.424,719.126], 'z':[-58.901,-54.958,-53.035,-51.397], 'diam':[1.847,1.584,1.584,1.933] }, prefix + 'apic[54]': { 'x':[-365.713,-364.794,-362.683,-361.201,-359.872,-358.804,-357.848,-356.380,-355.525,-353.766,-353.747,-352.948], 'y':[723.216,722.433,722.539,721.362,720.292,719.760,719.542,718.712,717.942,717.817,714.841,715.283], 'z':[-29.929,-30.380,-30.793,-31.476,-32.613,-32.996,-33.401,-33.869,-34.407,-35.302,-35.166,-36.221], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[64]': { 'x':[-399.375,-398.949,-399.553,-399.921,-399.534,-399.055,-399.483,-399.929], 'y':[745.313,745.642,746.537,746.527,747.841,748.931,749.579,750.448], 'z':[-22.443,-20.947,-19.709,-18.472,-17.861,-17.348,-16.449,-15.017], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[142]': { 'x':[-405.528,-406.701,-406.364,-406.662,-406.591], 'y':[741.655,742.240,743.432,744.356,745.500], 'z':[-49.825,-50.398,-51.126,-51.799,-52.130], 'diam':[0.349,0.179,0.179,0.179,0.179] }, prefix + 'apic[92]': { 'x':[-366.046,-365.415,-364.489,-363.874,-363.707,-364.266,-364.450,-365.429,-365.583], 'y':[719.602,719.723,719.788,719.926,720.335,719.706,719.971,721.388,722.216], 'z':[-24.003,-22.716,-21.068,-20.212,-19.074,-17.789,-16.837,-14.735,-12.958], 'diam':[0.613,0.528,0.613,0.613,0.613,0.613,0.613,0.528,0.528] }, prefix + 'apic[18]': { 'x':[-374.024,-373.888,-374.047], 'y':[715.198,714.772,713.597], 'z':[-38.925,-37.744,-36.870], 'diam':[0.877,1.056,1.056] }, prefix + 'apic[13]': { 'x':[-349.325,-347.331,-346.054,-345.056,-342.992,-341.074,-340.066], 'y':[719.230,718.763,718.732,718.538,718.594,719.015,719.613], 'z':[-30.168,-28.903,-28.790,-28.614,-27.790,-26.946,-26.354], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[39]': { 'x':[-371.908,-371.971,-372.031,-373.102,-372.570], 'y':[728.584,729.114,730.297,730.468,730.628], 'z':[-28.319,-27.122,-25.843,-23.092,-21.545], 'diam':[0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[105]': { 'x':[-389.321,-390.872,-393.230,-394.618,-396.495,-397.479,-399.359,-399.787,-400.428,-401.421,-402.452], 'y':[727.188,728.427,728.388,728.865,729.325,729.974,731.639,732.220,732.834,733.481,733.848], 'z':[-42.050,-41.305,-40.826,-40.309,-39.867,-39.531,-38.747,-37.997,-36.897,-36.561,-36.376], 'diam':[0.349,0.264,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[20]': { 'x':[-371.023,-370.904,-369.504,-368.649,-367.762,-366.881,-366.462,-366.015,-365.121], 'y':[715.203,713.839,712.684,711.914,711.232,710.620,710.628,710.137,711.058], 'z':[-34.276,-33.412,-34.011,-34.549,-34.357,-33.825,-32.826,-31.468,-31.344], 'diam':[0.877,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[95]': { 'x':[-356.531,-356.357,-356.211,-356.847,-357.411,-358.043,-358.371,-358.373,-358.634,-359.241,-359.446,-359.670], 'y':[719.306,719.576,720.009,720.683,721.485,722.612,723.484,724.753,725.350,726.192,726.729,728.162], 'z':[-4.255,-2.374,-1.081,-0.433,0.168,1.329,2.493,4.341,5.251,6.353,7.364,8.825], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[66]': { 'x':[-398.247,-400.434,-401.322], 'y':[742.846,743.042,743.117], 'z':[-24.556,-24.298,-23.836], 'diam':[0.349,0.264,0.264] }, prefix + 'apic[70]': { 'x':[-375.082,-376.862], 'y':[723.155,723.172], 'z':[-47.527,-46.307], 'diam':[1.234,0.706] }, prefix + 'apic[78]': { 'x':[-389.242,-389.545,-388.952,-389.614,-390.274,-390.847,-391.293,-391.250,-391.190,-391.189,-391.486,-391.589,-390.671,-388.347,-386.753,-385.610,-385.313,-384.984,-384.001,-383.552], 'y':[737.183,735.720,733.874,733.561,734.323,734.985,734.122,736.084,737.218,737.671,737.249,737.279,737.752,737.795,738.020,737.726,736.788,734.907,734.454,733.489], 'z':[-16.218,-13.950,-13.821,-12.543,-11.407,-10.686,-9.825,-9.253,-8.996,-7.876,-6.916,-5.461,-4.066,-1.801,-0.859,0.388,1.668,2.830,3.889,4.727], 'diam':[0.613,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[93]': { 'x':[-365.583,-364.150,-363.331,-362.285], 'y':[722.216,721.800,721.663,721.533], 'z':[-12.958,-11.684,-10.733,-9.374], 'diam':[0.528,0.442,0.442,0.442] }, prefix + 'apic[62]': { 'x':[-378.506,-380.569,-381.467,-382.632,-384.092,-385.209,-386.393,-388.285,-389.493,-390.521,-391.530,-392.829,-393.886,-394.462,-395.274,-396.035,-397.312,-398.247], 'y':[727.022,727.879,728.886,729.984,731.203,732.263,733.444,733.643,734.731,735.347,736.427,737.673,738.514,739.576,740.314,740.502,741.987,742.846], 'z':[-41.156,-40.311,-39.264,-38.405,-37.744,-36.764,-35.594,-34.708,-33.653,-33.310,-32.279,-31.289,-30.422,-28.716,-27.909,-27.083,-25.326,-24.556], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[136]': { 'x':[-406.717,-406.842,-406.977,-407.200,-408.059,-409.312,-410.009,-411.043,-411.962,-412.473], 'y':[739.828,741.628,742.776,744.472,746.314,747.375,748.252,749.408,750.198,751.598], 'z':[-42.726,-41.140,-40.697,-39.503,-37.905,-37.289,-36.712,-35.956,-35.512,-35.486], 'diam':[0.264,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[117]': { 'x':[-365.814,-367.647,-369.685,-370.483,-371.252,-372.316,-375.201,-377.544,-378.792,-380.006,-381.261,-382.274], 'y':[717.747,719.096,719.119,720.159,720.974,721.842,724.816,724.496,725.215,726.053,727.121,727.857], 'z':[-58.901,-58.352,-57.224,-55.925,-55.151,-54.724,-53.864,-52.659,-52.857,-52.752,-52.129,-51.928], 'diam':[1.847,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.877,0.877,0.877,0.877] }, prefix + 'apic[9]': { 'x':[-359.362,-356.640,-355.265,-354.352], 'y':[715.202,714.247,713.181,712.601], 'z':[-36.885,-37.383,-37.494,-37.760], 'diam':[0.264,0.264,0.264,0.264] }, prefix + 'dend[8]': { 'x':[-295.384,-296.495,-296.116,-296.992,-298.077,-299.122,-300.559,-300.436,-299.709,-298.724,-298.273,-297.775,-297.079,-296.956,-296.054,-295.490,-294.830], 'y':[727.861,729.288,730.273,730.870,731.347,731.089,731.140,735.000,735.886,737.148,738.291,739.347,740.327,741.610,742.826,743.422,745.482], 'z':[-103.483,-104.712,-106.145,-106.773,-106.760,-106.621,-105.551,-104.625,-104.605,-104.497,-104.729,-104.954,-104.936,-105.431,-106.151,-106.776,-106.725], 'diam':[1.847,1.669,1.669,1.669,1.669,1.669,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.762,1.762,1.584] }, prefix + 'apic[102]': { 'x':[-383.489,-385.468], 'y':[724.129,724.833], 'z':[-44.607,-44.329], 'diam':[0.613,0.349] }, prefix + 'apic[128]': { 'x':[-399.616,-401.798,-402.972,-403.609,-403.999,-404.388], 'y':[745.693,745.255,745.453,747.194,748.202,749.145], 'z':[-30.891,-30.008,-30.181,-29.852,-28.906,-27.685], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[132]': { 'x':[-390.228,-391.727,-394.791,-395.800], 'y':[733.473,734.070,734.329,733.524], 'z':[-48.183,-49.096,-49.622,-49.182], 'diam':[0.792,0.706,0.528,0.528] }, prefix + 'dend[13]': { 'x':[-282.502,-281.179,-279.068,-274.478,-270.034,-267.279,-265.304,-263.436,-261.995,-260.552,-259.455,-256.293,-253.906,-250.930,-249.019,-247.267,-245.526,-243.939,-242.562,-240.274,-238.721,-236.088,-230.280,-228.669,-226.304,-222.644,-219.207,-217.921,-215.100,-208.235,-204.413,-202.147,-200.018,-198.458,-197.445,-196.573,-195.415,-191.684,-187.133,-182.885,-181.461,-180.007,-178.388,-176.229,-175.254], 'y':[721.731,722.004,723.160,724.226,724.383,725.578,725.697,725.942,726.813,726.959,727.027,727.705,729.561,729.834,730.007,730.099,730.249,731.363,731.823,733.516,734.054,733.441,733.966,734.152,735.442,735.854,736.203,736.349,737.546,738.344,740.001,739.138,739.435,739.589,739.736,739.886,739.781,740.257,740.750,740.146,740.713,740.905,741.130,741.030,740.302], 'z':[-73.572,-71.566,-70.034,-67.165,-65.426,-64.572,-64.516,-64.602,-64.593,-64.875,-65.110,-64.913,-65.462,-65.199,-64.920,-65.492,-65.483,-65.106,-64.616,-64.007,-63.245,-62.318,-61.707,-61.030,-60.615,-59.171,-57.778,-57.273,-55.282,-52.483,-50.745,-48.811,-47.342,-47.024,-46.245,-44.674,-42.222,-38.913,-35.537,-32.516,-30.047,-29.169,-28.034,-25.932,-22.899], 'diam':[0.613,0.264,0.264,0.264,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[127]': { 'x':[-399.616,-400.125,-401.188,-402.693,-403.063,-404.029,-405.162,-405.961,-406.889,-407.999,-408.825,-409.895,-411.317,-412.380,-414.016,-416.057], 'y':[745.693,746.627,747.490,747.541,748.467,748.010,747.465,748.104,749.220,749.996,750.788,751.048,750.530,749.923,749.656,750.351], 'z':[-30.891,-30.175,-29.754,-28.309,-27.250,-26.340,-25.308,-24.373,-23.269,-21.605,-19.879,-18.613,-17.488,-16.518,-16.074,-15.280], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[21]': { 'x':[-365.121,-363.474], 'y':[711.058,708.950], 'z':[-31.344,-30.479], 'diam':[0.528,0.442] }, prefix + 'apic[15]': { 'x':[-357.306,-357.953,-358.543,-358.307,-357.732,-356.809,-356.076], 'y':[721.905,722.583,723.532,723.877,725.751,726.027,726.511], 'z':[-32.611,-31.955,-30.569,-29.507,-26.441,-25.210,-24.398], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[114]': { 'x':[-376.862,-379.421,-380.552,-383.412,-385.811,-386.994,-388.388,-389.631,-392.895,-394.120,-394.255,-395.800,-396.692,-398.766,-399.803,-401.202,-402.064,-403.169,-404.794,-405.774,-406.868,-407.931], 'y':[723.172,724.228,724.759,725.283,726.433,726.483,726.359,727.152,729.428,729.721,731.952,731.709,732.381,733.725,734.770,734.440,734.624,734.576,733.158,733.727,733.887,734.348], 'z':[-46.307,-46.385,-46.866,-47.067,-46.666,-46.106,-46.158,-46.032,-45.480,-45.010,-44.703,-43.578,-42.575,-42.272,-42.288,-41.140,-40.379,-39.449,-38.574,-37.948,-37.611,-37.540], 'diam':[0.706,0.264,0.264,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[124]': { 'x':[-395.218,-396.161], 'y':[740.049,740.635], 'z':[-36.531,-35.502], 'diam':[0.613,0.528] }, prefix + 'apic[56]': { 'x':[-352.948,-351.273,-350.249,-348.228,-348.113,-348.197,-347.632,-347.377,-346.946,-346.441,-345.613,-344.655,-344.943], 'y':[715.283,714.230,713.474,713.651,712.519,711.057,709.772,708.714,707.468,706.862,705.982,704.961,703.928], 'z':[-36.221,-36.445,-36.823,-36.410,-35.304,-34.842,-34.922,-35.743,-37.199,-37.864,-38.714,-39.081,-38.677], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[82]': { 'x':[-405.902,-407.297,-408.848], 'y':[732.221,732.785,733.089], 'z':[-32.098,-33.094,-32.949], 'diam':[0.264,0.179,0.179] }, prefix + 'apic[130]': { 'x':[-396.161,-398.034,-397.334,-397.495], 'y':[740.635,740.416,740.900,740.822], 'z':[-35.501,-35.141,-37.336,-38.423], 'diam':[0.528,0.442,0.442,0.442] }, prefix + 'apic[94]': { 'x':[-362.285,-361.149,-359.575,-358.524,-357.804,-356.531], 'y':[721.533,721.113,720.106,719.504,718.726,719.306], 'z':[-9.374,-8.588,-8.560,-7.890,-6.945,-4.255], 'diam':[0.442,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[126]': { 'x':[-398.619,-399.738,-399.616], 'y':[742.819,744.346,745.693], 'z':[-31.263,-30.987,-30.891], 'diam':[0.528,0.349,0.349] }, prefix + 'apic[3]': { 'x':[-371.406,-372.417,-372.673], 'y':[719.126,716.462,717.133], 'z':[-51.397,-47.815,-46.593], 'diam':[1.933,1.320,1.320] }, prefix + 'apic[115]': { 'x':[-407.931,-408.319,-408.983,-409.267,-410.037,-410.232], 'y':[734.348,734.773,734.294,733.803,733.106,731.915], 'z':[-37.540,-38.974,-40.124,-41.483,-42.736,-43.652], 'diam':[0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[108]': { 'x':[-389.321,-389.530,-389.118,-388.421], 'y':[727.188,727.856,726.793,727.252], 'z':[-42.050,-40.572,-39.254,-38.429], 'diam':[0.349,0.264,0.264,0.264] }, prefix + 'apic[109]': { 'x':[-387.519,-387.667,-387.601,-385.286,-384.275,-384.196,-383.470], 'y':[726.008,723.804,722.659,723.001,721.928,721.093,720.237], 'z':[-43.616,-41.851,-41.171,-41.428,-41.689,-41.134,-40.508], 'diam':[0.442,0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[31]': { 'x':[-371.023,-369.996,-368.275,-366.578,-364.028,-362.378,-360.430,-359.537,-358.501,-357.324,-355.998,-354.672,-353.303,-352.256,-351.262,-349.685,-348.048,-346.503,-345.326,-344.393,-342.099,-340.425,-339.322,-338.832,-338.595,-338.475], 'y':[715.203,715.492,714.918,714.227,713.160,713.006,712.710,712.563,711.978,711.327,710.644,709.959,709.768,709.245,708.781,708.300,707.690,706.771,706.252,706.123,705.165,705.637,706.128,706.994,707.596,708.870], 'z':[-34.276,-32.378,-31.056,-30.040,-28.583,-27.587,-26.725,-25.688,-25.449,-25.181,-24.752,-24.325,-24.147,-23.752,-23.472,-23.214,-22.729,-22.822,-22.693,-21.846,-20.846,-19.484,-17.307,-16.548,-15.746,-14.759], 'diam':[0.877,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'dend[4]': { 'x':[-300.796,-303.420,-304.396,-304.639,-304.904,-305.925,-307.246,-308.656,-311.137,-312.165,-313.188,-314.124,-314.766,-315.566,-315.748,-315.600,-315.493,-315.699,-315.748,-316.649], 'y':[716.093,710.231,710.087,709.975,710.842,711.041,711.141,711.319,711.187,711.050,711.441,711.362,711.243,711.238,711.308,712.082,712.817,713.528,714.129,714.484], 'z':[-93.880,-94.683,-95.573,-96.661,-98.055,-98.288,-97.644,-97.725,-98.699,-99.365,-99.730,-100.270,-101.097,-102.895,-104.329,-105.392,-106.339,-107.942,-109.158,-111.225], 'diam':[2.639,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056] }, prefix + 'apic[77]': { 'x':[-385.814,-387.864,-388.670,-390.076,-391.455,-392.138,-394.062,-395.158,-395.490,-396.204,-395.997,-397.187,-398.152], 'y':[746.839,748.160,748.352,749.396,750.519,751.189,752.030,752.532,753.696,754.445,755.114,756.660,757.438], 'z':[9.799,9.776,8.974,9.268,9.705,9.326,9.728,10.287,10.139,10.241,8.948,8.536,7.960], 'diam':[0.528,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[42]': { 'x':[-366.165,-365.089], 'y':[732.626,732.271], 'z':[-4.049,-3.214], 'diam':[0.349,0.349] }, prefix + 'apic[104]': { 'x':[-387.519,-388.274,-389.321], 'y':[726.008,726.607,727.188], 'z':[-43.616,-43.183,-42.050], 'diam':[0.442,0.264,0.349] }, prefix + 'apic[118]': { 'x':[-382.274,-384.573,-386.892,-388.468,-390.228], 'y':[727.857,729.727,731.663,733.064,733.473], 'z':[-51.928,-50.990,-49.939,-49.003,-48.183], 'diam':[0.877,1.056,0.792,0.792,0.792] }, prefix + 'apic[16]': { 'x':[-364.098,-365.222,-365.893,-365.640,-365.187,-364.924,-364.947,-364.845,-365.211,-366.166,-366.718,-367.281], 'y':[717.234,718.621,718.444,718.480,718.203,718.504,718.257,718.524,718.969,719.106,720.415,721.020], 'z':[-39.614,-38.003,-36.096,-34.491,-33.549,-32.212,-31.174,-30.159,-29.187,-27.900,-26.029,-25.451], 'diam':[0.706,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'dend[0]': { 'x':[-307.800,-307.179,-306.302,-306.083,-305.433,-305.160,-305.222,-304.997,-304.725,-304.760,-304.916,-304.505,-304.196,-305.303,-305.149,-305.921,-306.550,-306.430,-305.491,-305.073,-304.928,-304.692,-303.934,-303.942,-303.311,-302.670,-302.124,-301.481,-303.920,-304.030,-305.719,-306.337,-306.162,-305.845,-305.569,-305.424], 'y':[701.708,699.574,698.042,695.047,693.418,691.963,690.876,689.630,688.650,686.805,684.562,683.449,682.118,681.327,680.556,679.886,679.065,677.874,676.568,675.648,674.719,673.539,672.196,670.924,669.433,668.320,666.684,665.968,663.779,662.632,662.993,662.763,661.298,660.494,658.850,657.846], 'z':[-88.086,-88.520,-88.244,-87.580,-87.601,-87.742,-88.323,-88.410,-88.532,-88.895,-89.767,-88.696,-87.877,-87.823,-86.974,-87.010,-87.310,-87.318,-86.801,-86.787,-87.166,-87.545,-87.312,-88.116,-88.144,-87.922,-88.616,-89.352,-87.629,-86.651,-86.348,-87.263,-86.915,-86.321,-86.107,-86.353], 'diam':[2.111,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706] }, prefix + 'apic[30]': { 'x':[-365.121,-366.309,-367.132,-368.091,-368.656,-369.181,-369.119,-370.042,-370.639,-371.795,-373.048,-374.080,-374.673,-375.869,-377.759,-378.720], 'y':[711.058,711.498,712.628,712.844,713.499,713.697,713.946,714.720,715.024,715.585,715.645,716.135,716.893,718.224,718.344,718.231], 'z':[-31.344,-29.195,-27.424,-26.412,-25.076,-23.402,-22.212,-20.551,-19.677,-19.827,-19.521,-18.862,-17.477,-15.663,-14.487,-14.134], 'diam':[0.528,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085] }, prefix + 'apic[24]': { 'x':[-359.839,-357.861,-356.382,-355.325,-354.069,-352.798,-350.928,-349.584,-348.536,-347.195,-346.434,-346.325,-344.670,-343.459,-341.726,-340.545,-338.510,-337.481], 'y':[708.648,707.673,707.210,706.873,707.477,707.517,706.996,706.426,705.919,705.026,703.478,702.475,702.192,701.844,701.207,700.881,700.126,699.833], 'z':[-26.957,-26.368,-24.825,-23.813,-23.258,-22.834,-22.217,-22.092,-22.306,-22.820,-22.635,-22.279,-23.122,-23.755,-23.955,-24.418,-25.199,-25.666], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[26]': { 'x':[-362.344,-361.044,-359.445,-359.718,-358.479,-357.623,-356.858], 'y':[708.536,707.290,707.408,706.088,704.423,703.564,702.880], 'z':[-29.530,-30.521,-31.256,-30.925,-29.946,-29.593,-29.899], 'diam':[0.528,0.442,0.442,0.442,0.442,0.442,0.442] }, prefix + 'apic[11]': { 'x':[-362.553,-360.713,-359.161,-358.146,-357.358,-357.306], 'y':[717.930,718.424,718.829,718.997,719.890,721.905], 'z':[-39.618,-38.090,-37.388,-35.363,-33.925,-32.611], 'diam':[0.442,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[25]': { 'x':[-359.839,-362.730,-363.058], 'y':[708.648,709.793,712.303], 'z':[-26.957,-27.056,-28.228], 'diam':[0.264,0.264,0.264] }, prefix + 'apic[76]': { 'x':[-385.814,-385.050,-384.423,-384.739,-384.753,-384.541,-384.017,-382.640,-382.233,-381.434,-381.072,-380.494,-379.211,-378.434,-377.220,-375.562,-373.409,-371.705,-370.298], 'y':[746.839,746.885,746.938,747.673,747.939,749.302,750.256,751.094,751.909,752.912,753.445,754.150,754.104,754.153,754.170,754.718,755.134,755.118,755.149], 'z':[9.799,11.124,12.899,14.198,15.296,16.674,19.393,23.645,25.377,27.728,29.310,30.742,32.057,32.775,34.152,35.366,37.665,38.784,39.721], 'diam':[0.528,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[85]': { 'x':[-399.225,-398.068,-397.897,-397.019], 'y':[733.084,734.722,735.526,736.193], 'z':[-25.820,-24.604,-23.279,-22.718], 'diam':[0.349,0.264,0.264,0.264] }, prefix + 'apic[12]': { 'x':[-357.306,-355.747,-354.298,-352.999,-351.725,-350.264,-349.325], 'y':[721.905,721.142,720.205,720.362,720.262,719.496,719.230], 'z':[-32.611,-31.972,-32.145,-32.009,-31.451,-30.993,-30.168], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[98]': { 'x':[-365.583,-367.074,-369.466,-371.117,-372.070,-372.910,-375.096,-374.840,-373.944], 'y':[722.216,723.660,724.526,725.943,727.492,728.858,730.465,731.599,732.184], 'z':[-12.958,-11.771,-10.673,-9.816,-9.388,-9.066,-9.542,-9.288,-8.601], 'diam':[0.528,0.442,0.442,0.442,0.349,0.349,0.264,0.264,0.264] }, prefix + 'apic[17]': { 'x':[-372.673,-373.356,-374.241,-373.789,-372.972,-373.175,-374.024,-374.024], 'y':[717.133,718.444,718.162,717.255,715.986,714.858,714.745,715.198], 'z':[-46.593,-44.449,-42.837,-41.843,-42.279,-40.911,-40.045,-38.925], 'diam':[1.320,0.877,0.877,0.877,0.877,0.877,0.877,0.877] }, }
92.910866
3,305
0.576177
from neuron import h class TransformTC4: def __init__(self): self.name2section = { sec.name(): sec for sec in h.allsec() } self.section_coords = { } def set_coords(self, sec_name): nrn_section = self.name2section[sec_name] new_coords = self.section_coords[sec_name] h.pt3dconst(1, sec=nrn_section) h.pt3dclear(len(new_coords["diam"]), sec=nrn_section) xvec = h.Vector(new_coords["x"]) yvec = h.Vector(new_coords["y"]) zvec = h.Vector(new_coords["z"]) dvec = h.Vector(new_coords["diam"]) h.pt3dadd(xvec, yvec, zvec, dvec, sec=nrn_section) def set_all(self): for sec_name in self.section_coords.keys(): self.set_coords(sec_name) @staticmethod def apply_on(prefix): t = TransformTC4() t.define_coords(prefix) t.set_all() @staticmethod def apply(): t = TransformTC4() t.define_coords() t.set_all() def define_coords(self, prefix = 'TC4[0]'): if prefix != '': prefix += '.' self.section_coords = { prefix + 'apic[68]': { 'x':[-401.322,-402.235,-402.958,-401.756], 'y':[743.117,744.267,743.755,747.357], 'z':[-23.836,-21.982,-21.153,-19.972], 'diam':[0.264,0.264,0.264,0.264] }, prefix + 'apic[100]': { 'x':[-368.650,-369.977,-371.475,-372.161,-372.512,-373.361,-373.937,-374.711,-375.289,-375.521,-375.522,-376.265,-375.041,-375.495,-375.517,-374.957,-374.165,-373.673,-372.672,-371.700], 'y':[721.906,722.984,723.293,723.815,724.044,724.948,725.556,726.107,726.840,727.356,728.641,728.811,731.930,731.927,732.329,732.519,732.126,732.122,732.931,732.884], 'z':[-26.366,-25.829,-24.064,-23.086,-21.692,-20.685,-20.100,-19.668,-18.622,-17.585,-16.403,-13.942,-13.605,-11.861,-10.119,-8.762,-7.375,-6.275,-5.944,-4.515], 'diam':[0.613,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[113]': { 'x':[-383.489,-383.890,-383.410,-381.081,-380.535], 'y':[724.129,724.331,723.344,724.340,723.080], 'z':[-44.607,-43.031,-41.923,-41.646,-40.779], 'diam':[0.613,0.264,0.264,0.264,0.264] }, prefix + 'apic[37]': { 'x':[-375.585,-375.040,-374.570,-372.798,-371.266], 'y':[726.541,727.069,727.549,727.462,727.211], 'z':[-37.841,-35.655,-33.710,-32.052,-30.669], 'diam':[0.613,0.706,0.706,0.792,0.792] }, prefix + 'dend[2]': { 'x':[-305.424,-306.149,-306.972,-307.633,-307.203,-306.701,-307.338,-308.001,-307.992,-308.743,-309.466,-310.076,-309.901,-309.758,-310.736,-310.876,-311.714,-311.679,-312.585,-313.265,-314.333,-315.285,-316.729,-317.738,-318.707,-319.653,-320.304,-321.717,-323.098,-323.748,-323.829,-324.387,-325.403,-325.801,-326.171,-327.007,-326.773,-326.650,-327.482,-327.738,-328.016,-328.723,-328.947,-329.713,-330.844,-331.091,-331.111,-332.015,-332.114,-332.743,-333.113,-334.087,-334.663,-335.558,-336.136,-336.693,-337.237,-337.555,-337.335,-337.787,-338.119,-339.486,-340.852,-341.635,-342.410,-343.707,-345.556,-346.546,-347.430,-347.788,-348.533,-350.674,-351.546,-352.687,-353.566,-355.548,-356.503,-358.427,-359.864,-360.664,-361.856,-363.812,-364.870,-365.902,-367.369,-368.292,-368.764,-369.440,-370.536,-369.616,-370.027,-370.562,-369.958,-371.540,-372.116,-372.849,-373.095,-373.288,-373.202,-373.851,-374.295,-374.686,-374.293,-374.813,-375.303,-375.578,-376.148,-376.218,-377.242,-377.452,-377.267,-377.331,-377.443,-377.591,-377.441,-377.731,-378.310,-378.240,-378.158,-379.308,-379.335,-379.848,-380.406,-380.797,-380.513,-380.372,-380.032,-379.849,-379.917,-379.376,-378.853,-379.067,-378.944,-379.432,-379.750,-381.569,-381.330,-381.775,-382.134,-382.884,-383.706,-384.466,-384.231,-383.911,-385.008,-385.241,-385.364,-385.829,-386.448,-386.579,-386.330,-384.136,-387.079,-387.052,-386.854,-387.056,-387.134,-386.899,-387.208,-387.344,-387.404,-388.023,-387.858,-388.750,-389.583,-389.749,-390.293,-390.904,-391.807,-392.082,-393.498,-394.299,-395.083,-396.237,-397.409,-398.536,-398.992,-399.711,-400.673,-401.799,-401.981,-402.645,-402.713,-403.474,-404.364,-404.557,-405.328,-406.310,-406.915,-406.661,-407.622,-408.540,-408.281,-408.601,-409.468,-410.498,-411.801,-412.336,-413.417,-414.658,-415.811,-417.025,-417.416,-418.083,-418.578,-418.893,-419.861,-419.442,-420.697,-420.904,-421.188,-421.585,-422.166,-421.938,-421.805,-421.925,-422.798,-423.851,-424.795], 'y':[657.846,655.817,654.383,653.371,652.356,651.413,650.015,649.378,647.780,646.618,645.949,644.136,642.224,640.841,639.570,637.857,636.189,635.102,634.031,633.678,632.205,631.336,631.200,630.695,628.655,627.457,626.996,626.050,625.432,624.547,623.001,621.427,620.541,619.190,617.529,616.051,614.099,613.047,612.730,611.830,610.882,610.074,608.913,607.579,606.409,605.188,603.234,602.723,601.681,600.729,599.748,598.653,597.857,597.572,596.367,594.512,593.448,591.688,590.399,589.428,587.989,587.069,585.854,585.221,584.161,583.198,580.883,581.289,582.894,584.788,583.671,583.680,584.025,584.415,583.736,583.322,583.894,582.830,582.608,583.592,582.619,582.818,582.532,583.399,583.482,583.227,581.977,580.616,579.303,578.936,577.589,576.747,575.455,573.755,572.849,571.127,569.857,568.450,567.149,565.861,564.832,563.384,562.328,559.544,558.447,557.437,556.355,554.987,553.428,552.117,550.812,549.716,546.844,545.215,542.425,541.523,539.703,538.178,536.442,534.657,532.485,531.476,530.006,528.892,526.795,525.742,524.451,521.642,519.838,518.634,516.972,514.884,513.827,511.941,511.025,508.376,506.818,505.672,504.514,503.805,502.764,502.042,500.095,498.508,497.199,495.989,494.709,493.780,492.397,490.989,490.029,489.595,487.717,485.106,484.052,482.960,481.577,479.617,478.870,477.803,476.740,474.906,473.845,473.536,473.042,471.747,470.879,470.946,470.850,469.999,468.585,467.704,467.859,467.609,467.765,466.920,465.363,464.453,464.173,463.719,462.390,461.857,461.112,459.863,459.303,458.068,457.058,455.924,454.394,453.021,452.240,452.244,451.172,450.056,449.408,449.081,449.179,448.412,446.642,445.859,444.628,444.020,442.960,442.026,441.460,440.411,439.813,438.771,437.936,436.800,435.005,434.026,432.869,431.080,429.895,428.409,426.955,426.013,425.250], 'z':[-86.353,-87.989,-88.761,-88.939,-88.680,-88.000,-88.761,-89.898,-89.692,-89.536,-90.332,-90.940,-91.312,-91.513,-92.119,-92.179,-92.385,-92.720,-93.485,-94.379,-96.344,-98.222,-99.345,-100.621,-101.779,-102.844,-103.498,-105.342,-106.480,-106.656,-107.169,-107.746,-108.364,-109.480,-109.473,-110.100,-110.682,-111.082,-112.447,-113.092,-113.890,-115.204,-115.781,-117.054,-117.343,-117.169,-117.852,-119.066,-119.581,-119.313,-119.441,-119.837,-120.587,-121.746,-122.672,-123.778,-124.385,-125.363,-124.846,-125.350,-126.532,-127.184,-127.755,-128.331,-129.353,-130.216,-130.395,-130.526,-130.866,-130.201,-130.487,-130.377,-130.020,-130.195,-130.095,-129.484,-129.739,-130.273,-129.503,-128.554,-128.446,-128.139,-128.708,-129.447,-129.267,-129.626,-128.220,-129.090,-128.702,-127.449,-127.936,-128.480,-128.426,-128.490,-128.582,-129.206,-128.592,-127.909,-128.036,-127.543,-128.534,-129.986,-129.992,-130.331,-130.234,-130.883,-131.173,-131.188,-131.680,-131.871,-132.231,-132.626,-133.187,-134.125,-134.815,-135.144,-136.072,-136.551,-136.788,-137.401,-138.135,-138.287,-139.150,-139.579,-140.098,-140.192,-140.236,-141.162,-141.916,-142.092,-142.369,-142.775,-143.167,-144.192,-145.113,-145.094,-145.724,-146.425,-146.455,-146.475,-147.001,-147.326,-147.918,-148.456,-148.977,-149.126,-149.373,-149.399,-149.570,-150.616,-150.866,-152.262,-150.603,-151.171,-151.544,-151.308,-152.278,-153.162,-153.967,-154.817,-155.295,-155.630,-155.975,-156.965,-156.694,-157.271,-158.206,-159.039,-160.278,-161.103,-161.318,-162.349,-163.169,-162.746,-163.119,-164.759,-164.727,-165.663,-166.734,-167.411,-167.563,-168.462,-169.395,-169.037,-169.627,-170.025,-170.360,-171.438,-171.585,-172.070,-173.092,-174.290,-174.577,-175.730,-176.070,-176.351,-177.666,-178.886,-180.318,-180.816,-182.097,-182.728,-183.377,-184.530,-185.581,-186.584,-186.938,-186.899,-187.257,-187.614,-188.210,-188.098,-187.870,-188.570,-188.928,-189.297,-189.777,-189.732,-189.137], 'diam':[0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[123]': { 'x':[-388.217,-387.909,-388.043,-388.419,-388.477,-388.170,-388.968,-389.566,-390.968,-391.192,-392.156,-392.402,-392.782,-393.483,-393.249,-393.743], 'y':[750.404,751.127,751.354,751.752,752.328,752.722,753.615,754.306,754.648,754.734,755.681,757.866,758.125,758.138,761.297,762.410], 'z':[-11.011,-8.893,-6.999,-6.000,-4.675,-3.202,-0.731,0.335,2.959,4.058,5.472,7.517,8.479,9.546,10.264,10.996], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[137]': { 'x':[-406.717,-408.041,-408.660], 'y':[739.828,738.773,737.771], 'z':[-42.726,-43.717,-44.083], 'diam':[0.264,0.264,0.264] }, prefix + 'apic[87]': { 'x':[-383.728,-383.712,-383.710,-384.757,-384.819,-384.736,-384.132,-383.222,-383.501,-383.637,-383.721], 'y':[729.654,730.154,730.665,731.362,732.288,733.530,733.810,734.566,736.049,736.656,737.408], 'z':[-36.522,-35.245,-33.983,-32.367,-30.814,-29.637,-28.144,-26.853,-24.876,-24.069,-23.133], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[107]': { 'x':[-402.452,-402.181,-402.512,-403.510,-404.990,-407.221,-407.770,-408.463,-409.672,-410.454,-411.101,-411.695,-411.789], 'y':[733.848,735.891,736.974,738.379,738.467,740.361,741.079,741.936,743.547,744.308,744.920,746.146,747.115], 'z':[-36.376,-35.862,-35.126,-34.206,-33.382,-31.205,-30.321,-29.313,-27.433,-26.810,-26.317,-25.184,-24.501], 'diam':[0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[45]': { 'x':[-366.165,-366.313,-366.835], 'y':[732.626,733.106,733.993], 'z':[-4.049,-3.108,-1.770], 'diam':[0.349,0.349,0.349] }, prefix + 'apic[35]': { 'x':[-375.082,-376.135,-376.999,-377.821], 'y':[723.155,724.325,724.617,725.564], 'z':[-47.527,-44.332,-42.503,-41.334], 'diam':[1.234,0.792,0.792,0.792] }, prefix + 'apic[38]': { 'x':[-371.266,-371.908], 'y':[727.211,728.584], 'z':[-30.669,-28.319], 'diam':[0.792,0.528] }, prefix + 'apic[33]': { 'x':[-374.024,-375.311,-377.581,-378.871,-380.203,-381.533,-382.323,-383.122,-384.607,-385.543,-385.955,-385.374,-384.843,-384.505,-384.329,-384.884,-385.583,-386.239,-387.042], 'y':[715.198,716.497,717.045,717.621,716.615,718.152,718.867,719.520,720.476,721.465,723.395,724.035,724.041,723.880,724.005,724.978,725.181,725.388,726.011], 'z':[-38.925,-37.785,-37.421,-37.312,-36.767,-35.118,-34.480,-34.154,-33.048,-31.047,-27.090,-24.605,-23.094,-21.588,-20.360,-18.534,-17.451,-14.734,-12.598], 'diam':[0.877,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[4]': { 'x':[-372.673,-370.268,-368.721,-367.836,-366.480,-365.724,-364.489,-364.000,-364.098], 'y':[717.133,716.035,716.542,716.517,716.592,716.446,716.739,717.539,717.234], 'z':[-46.593,-45.274,-45.463,-44.560,-43.284,-42.583,-42.087,-41.024,-39.614], 'diam':[1.320,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706] }, prefix + 'apic[73]': { 'x':[-382.134,-384.144,-385.221,-385.503,-386.609,-388.356,-389.217,-389.277], 'y':[726.717,727.360,728.561,729.123,729.959,730.043,731.161,731.679], 'z':[-40.431,-37.713,-36.462,-35.538,-34.327,-31.762,-30.401,-29.218], 'diam':[0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706] }, prefix + 'apic[27]': { 'x':[-356.857,-356.708,-357.203,-357.340], 'y':[702.880,703.299,703.826,703.884], 'z':[-29.899,-28.605,-27.042,-25.850], 'diam':[0.442,0.442,0.442,0.442] }, prefix + 'apic[23]': { 'x':[-362.344,-361.072,-360.172,-360.559,-359.839], 'y':[708.536,708.312,707.816,707.671,708.648], 'z':[-29.530,-28.825,-28.610,-27.247,-26.957], 'diam':[0.528,0.264,0.264,0.264,0.264] }, prefix + 'apic[120]': { 'x':[-394.546,-395.049,-395.217,-395.218], 'y':[737.443,738.429,739.655,740.049], 'z':[-41.888,-40.244,-37.510,-36.531], 'diam':[0.528,0.528,0.613,0.613] }, prefix + 'apic[80]': { 'x':[-396.249,-396.770,-398.279,-400.340,-401.841,-402.934,-404.005,-403.900,-405.902], 'y':[731.890,731.769,733.115,732.914,733.113,733.800,733.330,734.782,732.221], 'z':[-29.596,-30.740,-31.656,-31.900,-31.798,-31.216,-30.988,-32.214,-32.098], 'diam':[0.442,0.528,0.528,0.349,0.349,0.349,0.349,0.349,0.264] }, prefix + 'apic[125]': { 'x':[-396.161,-396.692,-397.460,-397.899,-398.619], 'y':[740.635,741.256,742.070,742.393,742.819], 'z':[-35.501,-33.897,-33.109,-32.098,-31.263], 'diam':[0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[140]': { 'x':[-392.313,-393.520,-394.433,-396.215,-397.872,-398.268,-400.003,-400.972,-401.942,-403.022,-403.964,-405.032,-405.625,-405.135,-405.528], 'y':[732.909,733.465,733.906,733.127,733.614,735.331,735.090,735.531,736.857,737.613,738.345,738.197,737.888,740.515,741.655], 'z':[-53.049,-53.616,-53.980,-53.947,-53.513,-53.518,-53.593,-54.213,-53.589,-53.466,-53.172,-52.276,-51.350,-51.238,-49.825], 'diam':[0.442,0.349,0.349,0.349,0.349,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[28]': { 'x':[-356.857,-356.919,-356.761], 'y':[702.880,701.549,701.058], 'z':[-29.899,-30.956,-32.674], 'diam':[0.442,0.442,0.442] }, prefix + 'apic[79]': { 'x':[-389.277,-392.355,-393.562,-395.216,-396.249], 'y':[731.679,731.891,732.249,732.656,731.890], 'z':[-29.218,-29.900,-30.475,-29.766,-29.596], 'diam':[0.706,0.442,0.442,0.442,0.442] }, prefix + 'apic[6]': { 'x':[-362.553,-361.157], 'y':[717.930,717.776], 'z':[-39.618,-40.571], 'diam':[0.442,0.264] }, prefix + 'apic[58]': { 'x':[-368.533,-367.127,-367.500,-367.990,-366.772,-364.813,-363.144,-361.999,-360.753,-360.087,-359.239,-358.460,-356.936,-355.972], 'y':[725.556,724.702,725.159,725.813,725.501,724.931,724.064,723.631,723.152,723.091,721.588,721.156,720.129,718.758], 'z':[-29.616,-28.522,-27.381,-26.560,-25.220,-23.497,-21.118,-19.723,-18.596,-17.662,-17.243,-16.599,-16.381,-16.184], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[116]': { 'x':[-407.931,-408.947,-409.732,-410.750,-412.326,-413.177], 'y':[734.348,735.025,735.733,735.467,735.552,735.258], 'z':[-37.540,-37.480,-37.005,-36.943,-36.793,-37.324], 'diam':[0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[40]': { 'x':[-372.570,-372.849,-373.328], 'y':[730.628,731.242,731.957], 'z':[-21.545,-20.472,-19.495], 'diam':[0.528,0.349,0.349] }, prefix + 'apic[74]': { 'x':[-389.277,-389.302,-389.392,-389.856,-389.686,-389.242], 'y':[731.679,732.541,733.801,735.468,736.410,737.183], 'z':[-29.218,-27.141,-24.164,-20.790,-18.228,-16.218], 'diam':[0.706,0.528,0.613,0.613,0.613,0.613] }, prefix + 'apic[112]': { 'x':[-393.081,-394.111,-395.147], 'y':[723.019,724.029,723.597], 'z':[-41.593,-40.711,-39.279], 'diam':[0.349,0.349,0.349] }, prefix + 'dend[6]': { 'x':[-316.649,-316.983,-317.001,-316.991,-318.052,-319.144,-320.229,-320.690,-320.721,-320.971,-321.537,-323.054,-323.926,-325.276,-327.635,-326.904,-327.275,-328.221,-328.880,-329.401,-329.713,-330.354,-331.563,-332.397,-332.869,-333.901,-334.766,-336.052,-337.195,-338.096,-338.652,-339.383,-339.641,-339.814,-339.943,-339.773,-340.698,-341.420,-342.074,-343.010,-343.509,-344.218,-345.016,-345.544,-345.947,-346.366,-346.623,-346.994,-348.169,-349.116,-350.655,-351.823,-352.929,-354.289,-355.540,-356.724,-358.809,-360.180,-361.545,-363.034,-364.550,-366.090,-368.226,-370.293,-371.230,-372.645,-373.711,-374.577,-376.534,-377.696,-378.902,-379.974,-380.897,-382.571,-384.229,-386.551,-386.744,-387.056,-388.525,-388.441,-388.860,-390.513,-391.655,-392.346,-393.119,-394.626,-396.507,-397.421,-398.495,-399.628,-400.393,-401.059,-400.775,-400.778,-402.156,-402.780,-403.163,-403.496,-403.410,-403.824,-403.804,-404.479,-405.193,-406.114,-405.251,-405.872,-407.220,-407.017,-407.361,-408.038,-408.831,-409.900,-409.459,-410.673,-411.358,-411.926,-412.272,-412.908,-413.529,-414.666,-415.458,-416.558,-417.888,-419.097,-419.184,-420.554,-421.509,-422.694,-423.226,-423.698,-424.487,-425.051,-426.607,-427.473,-428.605,-429.542,-431.626,-433.594,-434.985,-435.229,-435.324,-435.402,-435.347,-434.879,-434.224,-434.166,-434.772,-435.318,-435.951,-436.312,-436.963,-437.227,-437.313,-437.152,-437.569,-438.780,-440.223,-441.081,-441.657,-442.116,-443.317,-444.559,-446.245,-447.687], 'y':[714.484,714.221,715.057,716.820,716.696,716.724,716.798,717.294,717.360,717.687,718.119,718.775,718.794,718.806,719.070,719.804,719.978,720.201,720.189,720.071,720.724,721.468,721.636,721.968,722.043,722.759,722.716,723.242,723.542,723.505,723.461,724.344,724.482,724.358,724.307,724.258,724.339,724.578,724.602,724.640,725.008,725.341,725.094,724.889,724.749,725.711,726.235,727.135,727.474,727.264,728.507,729.042,729.031,728.949,728.793,728.703,728.929,728.849,728.824,729.236,729.066,728.853,730.052,729.783,729.616,729.516,729.532,729.442,729.475,729.328,729.244,729.123,728.956,728.750,728.624,730.111,729.933,731.110,731.107,731.188,731.421,731.550,731.448,731.394,731.317,731.061,730.824,731.181,731.345,731.293,731.604,731.442,731.303,731.175,733.338,733.942,734.276,734.242,734.418,734.992,735.434,735.902,736.442,736.800,736.761,737.061,737.474,737.508,738.166,739.026,739.582,739.321,739.225,739.208,739.967,739.972,740.377,740.793,740.775,740.865,741.357,741.737,741.558,741.439,741.470,742.032,742.406,742.088,738.975,738.371,738.149,737.385,737.046,736.909,736.754,736.588,735.994,735.937,735.640,735.058,734.900,735.510,736.036,735.937,735.919,735.807,735.770,735.918,736.277,736.113,735.849,735.755,735.553,735.454,735.173,734.910,734.628,734.484,734.347,734.210,733.492,733.964,734.527,734.769], 'z':[-111.225,-114.063,-116.672,-117.876,-118.327,-118.778,-119.829,-120.661,-121.710,-122.946,-123.788,-125.324,-126.776,-127.648,-128.862,-130.491,-131.624,-132.882,-134.193,-135.688,-136.718,-137.379,-139.032,-140.858,-142.578,-143.834,-144.717,-146.181,-148.760,-150.107,-151.384,-152.760,-153.873,-155.288,-156.354,-158.299,-160.121,-161.333,-162.173,-164.462,-165.634,-166.386,-169.205,-171.164,-172.511,-173.835,-175.081,-176.608,-178.738,-180.321,-181.422,-182.288,-182.632,-183.390,-184.101,-183.996,-185.383,-186.128,-186.892,-187.802,-188.348,-189.358,-189.816,-190.464,-191.580,-191.995,-192.570,-193.437,-194.785,-195.363,-195.728,-196.188,-197.307,-198.222,-198.673,-199.755,-201.642,-202.367,-202.093,-203.128,-204.036,-205.216,-205.904,-207.091,-207.836,-209.536,-210.497,-211.413,-211.993,-213.273,-214.849,-216.140,-217.461,-219.082,-220.175,-221.973,-223.114,-224.928,-225.964,-227.718,-229.134,-230.704,-232.044,-232.848,-233.580,-234.790,-236.957,-237.958,-238.881,-240.012,-241.024,-243.092,-244.631,-246.152,-246.583,-247.862,-249.239,-251.487,-253.017,-254.423,-257.443,-259.092,-260.520,-262.041,-263.933,-264.954,-266.800,-267.720,-268.800,-269.669,-270.867,-272.910,-274.841,-275.713,-276.408,-277.523,-280.140,-281.939,-284.192,-286.187,-287.933,-289.034,-290.688,-292.907,-293.812,-295.181,-296.226,-297.638,-298.721,-299.720,-301.587,-302.552,-304.882,-306.234,-309.215,-311.194,-312.640,-313.513,-314.663,-315.795,-317.907,-319.477,-320.685,-321.816], 'diam':[1.056,0.877,0.877,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.613,0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264] }, prefix + 'apic[48]': { 'x':[-369.377,-368.868,-369.001], 'y':[728.596,728.853,729.446], 'z':[-20.031,-18.610,-17.351], 'diam':[0.349,0.264,0.264] }, prefix + 'apic[90]': { 'x':[-380.344,-377.873,-376.028,-375.083,-374.022,-371.998,-371.004,-369.502,-367.979,-368.221,-367.901,-368.675,-367.791,-368.599,-368.650], 'y':[724.015,722.870,724.168,722.390,722.279,721.505,720.499,721.433,721.332,722.116,722.974,721.697,722.709,721.204,721.906], 'z':[-44.355,-43.085,-41.437,-39.030,-38.067,-36.429,-34.992,-34.486,-33.082,-31.540,-30.933,-29.551,-29.546,-28.180,-26.366], 'diam':[0.613,0.613,0.613,0.613,0.528,0.528,0.528,0.528,0.613,0.613,0.613,0.613,0.613,0.613,0.613] }, prefix + 'apic[34]': { 'x':[-371.406,-373.446,-374.045,-375.082], 'y':[719.126,720.902,722.725,723.155], 'z':[-51.397,-50.313,-48.625,-47.527], 'diam':[1.933,1.234,1.234,1.234] }, prefix + 'soma': { 'x':[-297.841,-296.129,-294.417], 'y':[712.070,707.901,703.732], 'z':[-90.454,-89.770,-89.086], 'diam':[9.117,9.117,9.117] }, prefix + 'apic[44]': { 'x':[-365.089,-365.966,-366.538,-366.585,-366.373,-365.923], 'y':[732.271,732.384,732.702,732.198,732.093,731.595], 'z':[-3.214,-0.623,1.276,2.750,4.070,5.421], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'dend[7]': { 'x':[-300.796,-300.629,-299.381,-298.107,-296.935,-295.815,-297.338,-296.883,-295.403,-294.246,-293.197,-294.411,-295.384], 'y':[716.093,716.461,718.499,719.941,720.652,722.212,722.700,723.818,725.076,725.606,726.013,727.292,727.861], 'z':[-93.880,-97.054,-98.171,-97.995,-97.600,-97.415,-98.277,-100.250,-100.297,-100.731,-101.787,-103.411,-103.483], 'diam':[2.639,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847] }, prefix + 'apic[51]': { 'x':[-371.266,-370.307,-369.473], 'y':[727.211,726.650,726.158], 'z':[-30.669,-30.517,-29.787], 'diam':[0.792,0.442,0.442] }, prefix + 'dend[1]': { 'x':[-305.424,-304.042,-302.853,-301.401,-301.475,-300.185,-299.370,-298.648,-297.367,-296.733,-296.589,-296.564,-295.410,-294.247,-293.738,-293.850,-292.744,-292.152,-291.235,-291.015,-290.358,-290.719,-290.732,-289.687,-289.078,-288.530,-288.398,-288.768,-289.694,-291.113,-291.647,-290.869,-289.664,-289.045,-289.208,-289.575,-288.697,-287.855,-287.774,-287.870,-288.258,-287.918,-288.898,-289.985,-291.039,-290.634,-289.983,-289.708,-289.081,-288.893,-288.390,-288.861,-288.311,-289.781,-289.462,-289.582,-288.727,-287.871,-286.490,-286.391,-286.640,-286.069,-285.657,-286.066,-285.516,-284.870,-284.029,-283.113,-282.856,-282.601,-283.255,-282.010,-281.988,-281.796,-281.050,-281.154,-280.658,-279.152,-276.654,-275.812,-275.296,-275.576,-275.747,-274.804,-274.308,-273.451,-273.500,-274.257,-274.079,-273.230,-271.422,-270.993,-271.541,-271.849,-271.412,-271.399,-272.308,-272.909,-272.324,-271.094,-270.359,-270.459,-270.600,-269.870,-268.826,-267.621,-266.871,-265.858,-264.683,-264.741,-264.610,-263.893,-262.818,-262.468,-262.149,-261.449,-260.954,-260.040,-259.115,-257.052,-257.087,-256.522,-256.485,-256.763,-257.396,-257.902,-257.965,-257.688,-257.164], 'y':[657.846,657.791,657.893,657.814,657.019,656.482,656.563,655.737,654.890,654.083,653.043,651.499,651.047,650.917,649.724,648.757,647.762,646.524,645.859,645.206,644.845,645.449,645.536,645.856,645.241,645.518,645.860,646.617,645.696,645.313,644.061,643.927,643.242,642.669,641.119,639.853,638.957,638.146,636.354,635.362,635.940,635.534,634.786,633.929,632.889,632.434,632.389,631.401,630.361,628.448,627.315,625.868,625.358,623.596,622.671,622.106,620.987,619.894,618.554,617.114,615.494,614.186,612.488,611.281,610.310,609.927,610.067,608.745,607.589,606.562,604.617,604.482,603.054,602.084,602.371,600.515,599.739,600.062,600.860,600.380,599.933,598.475,597.205,596.701,595.451,594.543,593.467,591.978,592.247,590.802,590.391,589.646,588.469,588.695,587.992,587.962,587.366,585.678,584.292,583.218,582.187,581.145,579.203,578.520,578.122,577.192,576.552,576.048,576.075,575.140,574.006,573.708,574.957,575.148,575.296,575.967,576.599,576.663,576.532,576.820,576.110,576.379,576.314,575.493,574.309,573.159,572.010,571.139,568.656], 'z':[-86.353,-85.529,-85.081,-85.081,-84.108,-83.038,-82.162,-82.382,-82.418,-82.809,-82.436,-82.485,-82.104,-81.102,-80.896,-81.498,-81.182,-80.628,-80.760,-78.686,-77.214,-76.173,-74.987,-73.858,-72.479,-71.627,-70.503,-69.472,-69.583,-68.837,-67.928,-67.179,-66.627,-65.977,-66.335,-66.195,-65.980,-65.711,-65.095,-64.514,-63.447,-62.578,-61.868,-62.631,-62.426,-61.430,-60.244,-59.620,-58.465,-58.266,-56.615,-56.255,-55.507,-54.016,-53.469,-52.455,-51.468,-51.645,-50.379,-50.081,-47.948,-46.420,-45.712,-45.465,-44.915,-44.095,-43.288,-43.068,-43.100,-42.232,-41.208,-40.582,-39.689,-39.174,-38.423,-36.285,-35.165,-34.167,-33.331,-32.431,-31.376,-30.655,-30.141,-29.144,-28.431,-28.655,-28.135,-27.252,-25.953,-25.375,-25.486,-24.248,-22.363,-21.133,-20.396,-19.227,-18.697,-18.745,-18.398,-18.727,-19.260,-19.073,-18.625,-18.097,-17.512,-16.403,-16.166,-15.700,-14.756,-13.758,-14.177,-12.613,-9.986,-8.810,-7.134,-6.015,-4.744,-3.132,-2.168,-1.488,-0.362,0.628,1.713,3.046,2.575,1.905,1.594,1.117,0.154], 'diam':[0.706,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[89]': { 'x':[-379.163,-380.344], 'y':[723.461,724.015], 'z':[-44.007,-44.355], 'diam':[0.877,0.613] }, prefix + 'apic[47]': { 'x':[-372.570,-371.402,-370.112,-369.377], 'y':[730.628,729.969,729.136,728.596], 'z':[-21.545,-21.283,-21.133,-20.031], 'diam':[0.528,0.349,0.349,0.349] }, prefix + 'apic[135]': { 'x':[-403.344,-404.833,-405.705,-406.717], 'y':[738.048,739.098,739.762,739.828], 'z':[-43.286,-43.078,-42.839,-42.726], 'diam':[0.442,0.264,0.264,0.264] }, prefix + 'apic[91]': { 'x':[-368.650,-367.768,-366.866,-366.207,-366.046], 'y':[721.906,721.405,720.902,720.854,719.602], 'z':[-26.366,-26.208,-25.987,-24.898,-24.003], 'diam':[0.613,0.613,0.613,0.613,0.613] }, prefix + 'apic[5]': { 'x':[-364.098,-362.553], 'y':[717.234,717.930], 'z':[-39.614,-39.618], 'diam':[0.706,0.442] }, prefix + 'apic[75]': { 'x':[-389.242,-388.895,-388.210,-388.241,-388.144,-387.602,-387.273,-387.188,-386.756,-386.127,-385.543,-385.309,-385.814], 'y':[737.183,738.243,739.209,739.894,741.103,741.980,742.475,743.913,744.573,745.087,745.377,745.847,746.839], 'z':[-16.218,-12.900,-9.258,-7.620,-5.404,-3.018,-1.408,0.555,2.090,4.370,6.626,8.162,9.799], 'diam':[0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[134]': { 'x':[-403.344,-402.905,-403.123,-403.736,-403.761,-404.028,-404.588,-405.416,-406.891,-407.591,-408.446,-409.223,-410.226,-411.601,-412.837], 'y':[738.048,738.367,738.915,738.747,739.105,739.715,740.437,741.376,741.669,742.078,741.766,742.791,742.719,742.498,741.671], 'z':[-43.286,-41.803,-40.778,-39.230,-38.238,-37.158,-36.282,-35.290,-34.281,-33.621,-32.949,-31.983,-31.129,-30.446,-29.820], 'diam':[0.442,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[59]': { 'x':[-369.473,-370.332,-370.901,-371.241,-371.721,-372.168,-372.791,-373.585,-375.066,-375.746,-377.356,-378.685,-380.662,-381.393,-382.332], 'y':[726.158,726.320,727.055,727.076,727.030,727.498,728.226,728.932,730.561,730.807,731.445,731.398,732.496,733.263,734.055], 'z':[-29.787,-28.427,-27.366,-26.320,-25.163,-24.110,-23.312,-22.837,-21.048,-19.973,-19.261,-19.341,-18.252,-17.209,-15.994], 'diam':[0.442,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[129]': { 'x':[-398.619,-398.144,-396.833,-395.620,-394.129,-393.195,-391.656], 'y':[742.819,744.039,744.242,744.354,744.977,745.242,745.878], 'z':[-31.263,-30.283,-29.397,-29.496,-29.474,-29.020,-28.572], 'diam':[0.528,0.442,0.442,0.349,0.349,0.349,0.349] }, prefix + 'apic[121]': { 'x':[-395.218,-394.442,-392.681,-392.662,-392.284,-391.833,-391.694,-391.831,-391.358,-390.996,-390.826,-390.616,-390.174,-389.856,-389.471,-389.975,-389.094,-388.217], 'y':[740.049,740.470,742.068,742.957,743.347,744.253,744.763,745.305,746.466,746.931,747.742,748.447,749.095,749.411,749.985,751.045,751.172,750.404], 'z':[-36.531,-34.248,-32.785,-30.706,-29.154,-28.049,-26.876,-25.779,-24.940,-23.069,-22.177,-20.901,-18.759,-17.774,-16.807,-15.021,-13.488,-11.011], 'diam':[0.613,0.528,0.528,0.528,0.528,0.528,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[110]': { 'x':[-385.468,-387.572,-389.788,-391.006,-392.106,-393.081], 'y':[724.833,724.673,724.627,724.242,723.925,723.019], 'z':[-44.329,-45.429,-45.203,-43.626,-42.591,-41.593], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[106]': { 'x':[-402.452,-403.941,-404.936,-406.279,-407.311,-408.710,-410.147,-411.321,-412.445,-414.348,-415.722,-416.569,-417.334,-418.375], 'y':[733.848,734.898,734.288,735.318,736.342,736.824,737.289,737.867,738.070,738.011,738.010,738.637,738.109,737.668], 'z':[-36.376,-36.168,-36.322,-35.927,-35.044,-34.549,-34.458,-34.444,-34.199,-34.411,-33.981,-33.486,-32.905,-32.090], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[84]': { 'x':[-399.225,-400.103,-401.110,-401.373,-401.164,-401.370,-402.264,-403.218,-403.813,-404.231,-404.721,-405.639,-406.121,-406.493], 'y':[733.084,733.197,733.796,734.209,734.694,735.575,736.320,736.465,737.091,736.996,737.832,737.431,737.661,737.447], 'z':[-25.820,-24.007,-23.049,-22.161,-21.072,-19.401,-18.681,-17.993,-17.246,-15.982,-14.545,-12.813,-11.146,-10.109], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[138]': { 'x':[-395.800,-395.965,-396.134,-396.609,-397.328,-398.070,-399.140], 'y':[733.524,732.992,732.306,731.152,730.447,729.318,729.053], 'z':[-49.182,-50.780,-51.807,-53.077,-54.235,-54.980,-55.770], 'diam':[0.528,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[71]': { 'x':[-376.862,-378.454,-379.163], 'y':[723.172,723.508,723.461], 'z':[-46.307,-44.748,-44.007], 'diam':[0.706,0.877,0.877] }, prefix + 'apic[46]': { 'x':[-373.328,-374.274,-375.465], 'y':[731.957,734.034,733.094], 'z':[-19.495,-19.446,-19.025], 'diam':[0.349,0.349,0.349] }, prefix + 'apic[67]': { 'x':[-401.322,-403.370,-405.274,-406.226,-407.264,-408.568,-409.344,-409.866], 'y':[743.117,744.299,744.453,744.789,745.350,745.594,745.888,746.372], 'z':[-23.836,-23.740,-23.604,-22.887,-21.930,-21.080,-20.374,-19.399], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[119]': { 'x':[-390.228,-390.976,-392.517,-393.740,-394.546], 'y':[733.473,734.446,735.745,736.353,737.443], 'z':[-48.183,-46.963,-44.675,-42.952,-41.888], 'diam':[0.792,0.613,0.613,0.613,0.528] }, prefix + 'apic[72]': { 'x':[-379.163,-380.181,-381.890,-382.134], 'y':[723.461,724.379,725.773,726.717], 'z':[-44.007,-42.596,-40.784,-40.431], 'diam':[0.877,0.613,0.706,0.706] }, prefix + 'dend[11]': { 'x':[-294.791,-293.140,-292.783,-290.713,-290.655,-290.188,-288.506,-287.280,-286.090,-284.912,-285.133,-283.721,-282.796,-282.623,-282.502], 'y':[710.004,713.461,715.652,716.458,716.473,716.604,717.441,717.570,718.762,718.895,719.742,719.885,720.735,721.054,721.731], 'z':[-86.422,-85.845,-85.220,-83.665,-82.255,-81.122,-81.177,-80.922,-80.404,-79.352,-78.063,-77.651,-76.237,-74.944,-73.572], 'diam':[1.056,0.970,0.792,0.792,0.792,0.706,0.706,0.706,0.613,0.613,0.613,0.613,0.613,0.613,0.613] }, prefix + 'apic[122]': { 'x':[-388.217,-386.515,-385.184,-383.909,-382.779], 'y':[750.404,748.284,748.026,747.797,747.609], 'z':[-11.011,-11.024,-12.036,-12.709,-13.393], 'diam':[0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[49]': { 'x':[-369.377,-368.228,-367.476,-366.543], 'y':[728.596,727.114,725.964,725.221], 'z':[-20.031,-20.326,-19.765,-18.258], 'diam':[0.349,0.264,0.264,0.264] }, prefix + 'dend[5]': { 'x':[-316.649,-318.958,-318.981,-319.333,-320.244,-321.413,-322.842,-324.481,-325.669,-326.839,-328.090,-329.139,-330.198,-331.295,-333.278,-332.747,-331.998,-332.347,-332.276,-332.415,-332.778,-333.568,-333.965,-333.579,-332.436,-332.341,-332.329,-333.431,-333.684,-334.871,-335.965,-336.832,-337.691,-337.277,-336.875,-336.846,-337.515,-337.397,-338.426,-339.039,-339.107,-339.004,-339.427,-340.204,-340.455,-341.852,-342.206,-342.441,-343.182,-344.209,-343.085,-342.254,-344.055,-344.947,-344.602,-343.618,-343.279,-342.908,-343.759,-345.362,-346.787,-347.350,-346.364,-347.149,-347.365,-347.640,-348.724,-349.710,-351.060,-350.389,-350.014,-351.023,-352.021,-351.911,-353.296,-354.248,-354.893,-356.258,-357.746,-358.774,-359.466,-359.599,-361.041,-362.928,-364.470,-365.607,-366.839,-367.907,-369.602,-371.029,-372.248,-372.467,-372.430,-374.338,-375.407,-376.527,-377.433,-378.730,-379.878,-380.990,-381.925,-383.621,-384.549,-386.062,-386.751,-387.244,-388.160,-389.073,-390.029,-390.853,-391.545,-392.577,-393.437,-393.721,-395.070,-396.529,-397.119,-397.932,-398.996,-399.741,-401.409,-402.944,-404.120,-404.359,-405.317,-406.802,-407.860,-409.152,-410.414,-411.510,-412.517,-413.068,-413.433,-413.952,-414.417,-414.571,-414.548,-414.383], 'y':[714.484,716.593,718.184,716.186,717.644,718.233,719.091,719.448,719.313,719.418,720.599,721.048,721.170,721.395,721.354,722.579,723.203,723.854,724.553,724.896,725.306,725.287,725.570,725.498,726.193,727.513,728.054,728.854,729.625,729.489,731.018,731.739,732.271,732.529,734.471,736.637,737.154,738.074,738.658,739.201,739.808,742.433,743.500,743.371,744.331,744.318,744.245,745.964,746.608,747.151,747.645,748.057,749.000,750.458,751.448,752.148,753.193,754.235,755.250,755.168,754.970,756.855,757.453,757.620,757.751,758.042,758.596,758.589,759.962,760.707,761.837,762.908,763.340,763.650,764.305,765.202,766.530,768.380,769.992,770.601,771.804,772.282,772.908,773.040,773.002,772.898,772.962,772.991,773.544,773.667,773.671,774.578,775.392,775.525,775.479,776.353,776.592,776.886,776.758,776.634,777.459,778.340,778.455,779.689,780.327,780.651,780.483,780.313,781.298,781.902,783.166,783.597,784.795,784.952,784.832,784.678,784.742,785.722,786.506,786.587,787.436,788.051,788.074,787.471,788.881,789.500,789.952,790.847,791.594,791.883,791.638,791.490,792.315,793.171,793.332,794.332,794.514,795.050], 'z':[-111.225,-112.096,-112.778,-112.952,-112.086,-112.363,-112.727,-112.864,-113.338,-113.360,-113.583,-113.837,-114.419,-114.901,-115.908,-116.220,-117.276,-118.195,-118.920,-120.715,-121.987,-122.726,-123.758,-125.640,-127.540,-128.067,-129.492,-130.248,-131.623,-132.098,-132.665,-133.357,-134.616,-135.596,-135.639,-135.664,-136.645,-135.985,-135.773,-136.517,-137.608,-138.234,-138.390,-139.128,-140.062,-140.115,-141.237,-142.085,-143.330,-144.870,-145.470,-146.247,-147.042,-148.025,-148.484,-149.022,-150.634,-151.207,-153.307,-153.989,-154.985,-155.852,-156.962,-157.833,-159.045,-160.161,-160.904,-161.222,-162.184,-162.331,-163.013,-163.759,-164.807,-166.084,-167.110,-166.909,-166.093,-166.035,-165.757,-165.335,-165.266,-164.286,-164.368,-164.008,-164.724,-164.839,-165.324,-165.097,-165.881,-166.721,-167.310,-168.314,-169.388,-170.169,-170.854,-172.060,-172.520,-173.703,-174.731,-175.178,-175.785,-176.946,-178.194,-179.466,-180.153,-181.245,-182.477,-183.588,-185.357,-185.715,-186.803,-187.278,-189.062,-191.056,-193.691,-194.063,-195.156,-197.145,-197.544,-199.456,-200.944,-202.405,-203.334,-204.265,-205.276,-206.048,-206.190,-206.854,-207.607,-208.433,-209.774,-211.073,-212.885,-214.262,-216.731,-219.673,-221.165,-222.107], 'diam':[1.056,0.792,0.792,0.792,0.792,0.792,0.792,0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[97]': { 'x':[-362.285,-362.051,-362.069,-362.465,-362.054], 'y':[721.533,722.002,722.743,722.616,725.244], 'z':[-9.374,-7.838,-6.037,-4.512,-3.277], 'diam':[0.442,0.349,0.349,0.349,0.349] }, prefix + 'dend[9]': { 'x':[-294.830,-295.019,-296.705,-298.463,-299.485,-300.396,-300.541,-300.711,-300.967,-301.287,-302.167,-303.836,-304.771,-305.265,-305.334,-304.783,-304.938,-306.477,-306.579,-306.605,-306.689,-307.224,-308.364,-309.162,-309.453,-309.910,-311.716,-313.958,-314.448,-313.862,-313.425,-314.097,-315.684,-317.108,-317.128,-317.402,-317.895,-319.382,-320.558,-320.194,-321.449,-322.181,-323.190,-323.992,-325.336,-326.664,-328.158,-329.705,-330.207,-330.231,-329.519,-328.997,-329.664,-330.116,-329.647,-328.969,-328.500,-330.009,-330.995,-331.880,-332.206,-330.894,-330.321,-330.754,-331.398,-330.727,-330.165,-329.455,-329.211,-329.932,-330.788,-331.039,-330.200,-329.123,-330.442,-331.822,-332.370,-332.965,-333.966,-335.342,-336.305,-337.337,-338.062,-337.802,-336.979,-337.241,-337.839,-337.862,-337.650,-339.262,-340.757,-340.760,-339.830,-340.562,-341.519,-342.628,-343.668,-343.146,-343.413,-345.207,-345.814,-346.727,-348.098,-349.362,-350.359,-350.885,-350.409,-350.328,-350.100,-350.166,-351.863,-352.672,-352.830,-351.990,-351.964,-352.901,-353.631,-354.191,-353.962,-353.052,-352.448,-352.575,-352.585,-352.488,-352.743,-353.489,-352.411,-351.461,-351.838,-353.632,-354.914,-356.387,-357.193,-358.372,-359.149,-360.096,-360.043,-359.621,-359.522,-359.528,-359.507,-359.366,-358.791,-357.691,-358.258,-359.288,-360.272,-362.296,-361.057,-361.591,-360.769,-359.677,-359.492,-360.772,-362.029,-363.020,-362.052,-362.053,-362.828,-364.067,-365.062,-366.401,-368.134,-369.346,-370.330,-370.535,-371.044,-371.190,-371.517,-373.030,-374.155,-376.178,-377.205,-379.135,-379.908,-379.591,-381.050,-382.671,-384.904,-385.771,-386.850,-387.624,-389.130,-390.054,-390.873,-389.911,-390.880,-392.670,-393.909,-395.051,-394.087,-393.367,-394.004,-394.952,-395.290,-394.891,-394.160,-393.017,-391.815,-391.271,-392.436,-393.456,-393.611,-392.471,-392.044,-392.390,-392.691,-393.166,-395.432,-394.087,-392.539,-391.980,-391.454,-391.349,-393.052,-394.609,-394.727,-394.135,-392.862,-391.741,-391.197,-392.902,-394.211,-394.537,-395.048,-393.304,-393.007,-393.454,-394.327,-395.345,-395.379,-394.668,-393.616,-392.766,-391.684,-391.898,-393.057,-393.293,-392.370,-393.288,-395.177,-395.728,-394.366,-394.033,-395.375,-396.420,-397.630,-399.400,-400.338,-401.494,-402.032,-402.541,-402.933,-404.294,-405.208,-406.295,-407.326,-408.671,-409.401,-411.009,-410.883,-411.841,-414.295,-415.304,-416.806,-417.313,-417.892,-419.029,-420.457,-420.779,-420.403,-421.253,-422.369,-421.540,-421.434,-421.200,-420.936,-421.233,-422.947,-424.726,-425.650,-426.884,-426.475,-426.529,-427.484,-428.742,-429.364,-429.870,-430.119,-428.618,-430.383,-431.852,-432.922,-433.970,-433.098,-432.312,-431.996,-431.601,-432.153,-431.739,-433.528,-432.767,-431.738,-432.515,-432.570,-433.421,-433.545,-432.803,-432.798,-433.210,-433.374,-432.580,-433.241,-433.819,-434.415,-434.811,-434.381,-434.951,-437.417,-438.549,-439.545,-440.883,-441.895,-443.236,-443.498,-444.618,-445.658,-447.702,-448.539,-449.584,-451.291,-452.933,-454.340,-456.504,-459.001,-460.314,-461.831,-463.193,-465.030,-466.279,-468.057,-469.173,-470.487,-471.485,-472.819,-473.561,-474.700,-475.830,-475.782,-476.661,-477.651,-478.943,-479.486,-480.410,-479.879,-480.702,-481.437,-480.497,-480.641,-480.652,-482.521,-483.324,-484.395,-485.971,-486.452], 'y':[745.482,744.352,743.219,743.800,744.449,746.007,746.859,747.858,749.656,750.480,751.048,753.750,754.930,756.068,756.744,758.140,759.155,760.524,761.354,762.503,763.005,763.440,763.998,764.570,764.898,764.869,764.346,764.319,765.107,766.001,767.422,769.417,769.880,770.429,771.439,772.813,775.088,776.363,777.119,779.079,779.481,780.412,780.724,781.609,781.305,779.904,782.475,783.082,783.100,784.517,785.215,786.928,787.447,787.683,788.110,788.990,789.803,789.930,790.079,790.062,790.946,791.931,793.595,793.963,794.357,795.361,796.090,796.402,796.803,797.787,798.493,799.800,800.938,801.769,802.525,802.648,802.886,802.852,803.499,804.297,804.842,805.280,806.123,807.350,807.879,808.693,809.383,810.764,811.272,811.338,811.427,811.822,812.431,813.547,814.073,814.577,815.709,816.688,817.727,819.067,819.690,819.794,817.293,818.399,818.671,820.298,822.874,823.842,824.717,825.499,825.296,825.238,826.200,826.766,827.593,827.854,828.093,828.450,829.209,830.051,830.441,831.215,831.978,832.821,833.120,834.227,835.383,836.194,836.766,837.168,836.616,837.484,838.267,838.488,838.633,839.115,840.373,841.928,843.574,844.835,846.355,847.361,848.759,850.050,850.851,852.153,852.547,853.898,855.096,855.972,856.997,857.214,857.943,857.957,858.348,858.326,860.524,861.790,862.292,862.392,862.175,862.586,862.080,861.735,861.481,862.462,864.487,865.461,866.392,867.722,868.078,868.574,868.716,868.865,869.618,869.901,870.340,870.872,870.916,872.019,872.045,873.016,873.280,873.350,873.508,874.412,875.846,876.039,876.271,877.669,878.962,879.867,880.266,880.881,881.525,883.278,884.233,884.794,885.859,887.392,887.771,888.566,889.325,890.103,890.860,891.566,892.443,892.672,893.165,894.595,895.287,896.465,896.900,898.008,899.305,900.586,900.818,901.506,902.470,902.988,904.741,905.246,906.312,908.023,908.740,910.493,911.581,912.613,912.874,913.624,915.199,916.316,916.536,916.706,917.052,918.717,919.789,920.528,921.368,921.923,922.993,923.102,923.804,924.601,924.933,924.925,925.005,925.497,925.938,926.734,927.705,928.522,928.871,929.140,929.739,929.885,929.840,929.580,930.295,930.619,930.764,931.272,931.176,931.755,931.502,932.505,933.405,933.900,934.629,935.894,937.165,937.775,939.299,940.168,941.640,943.283,944.239,946.413,946.528,946.015,945.659,947.900,948.609,949.588,949.989,949.789,949.972,950.591,950.699,952.564,952.515,953.117,953.166,953.969,955.103,956.117,957.570,959.134,960.239,961.239,961.663,962.324,963.749,963.905,961.947,962.811,964.146,965.825,966.270,966.956,967.559,968.192,968.472,968.900,970.231,970.887,971.103,971.058,971.829,972.074,971.811,972.336,973.337,975.128,976.087,976.664,976.993,976.606,976.604,977.364,977.966,979.931,980.712,980.760,981.149,982.842,983.566,984.157,984.343,984.565,984.960,984.705,984.286,984.373,984.471,984.652,984.938,984.708,985.375,985.914,985.511,986.685,988.974,992.202,993.280,994.033,995.336,997.476,998.370,999.680,1001.725,1002.479,1002.545,1004.289,1006.041], 'z':[-106.725,-109.001,-108.739,-108.583,-108.530,-109.027,-110.074,-110.539,-111.014,-111.748,-111.112,-109.931,-109.796,-110.057,-111.248,-111.649,-112.218,-110.520,-109.243,-108.272,-107.280,-106.377,-106.834,-105.948,-104.900,-103.802,-103.701,-104.527,-104.958,-105.431,-105.847,-105.773,-104.451,-104.119,-105.376,-105.796,-106.933,-107.209,-107.178,-107.401,-107.662,-107.640,-107.868,-107.973,-108.780,-111.078,-111.654,-112.237,-113.297,-113.470,-114.266,-114.728,-115.497,-116.532,-117.827,-118.942,-119.958,-120.840,-120.978,-121.715,-122.088,-122.474,-123.397,-125.086,-127.132,-128.463,-128.913,-129.988,-131.190,-131.565,-132.212,-133.454,-133.032,-133.007,-133.891,-134.875,-136.128,-137.427,-138.890,-139.330,-139.656,-140.119,-141.324,-141.272,-140.139,-141.090,-141.841,-143.167,-144.467,-143.976,-143.472,-144.685,-145.027,-145.724,-145.835,-145.715,-146.900,-147.905,-148.020,-146.709,-145.856,-145.334,-146.157,-146.100,-146.461,-146.981,-148.361,-149.509,-150.767,-148.395,-147.469,-146.155,-144.677,-143.876,-142.637,-142.195,-141.415,-140.370,-138.440,-136.463,-135.128,-133.322,-131.525,-129.821,-127.852,-126.957,-126.535,-126.276,-125.204,-124.914,-122.076,-120.340,-119.029,-119.870,-120.930,-122.629,-123.057,-123.305,-122.765,-121.249,-120.840,-121.504,-122.923,-123.271,-121.958,-121.172,-120.607,-119.529,-119.662,-119.014,-118.052,-117.621,-116.620,-115.651,-114.760,-114.241,-113.129,-111.731,-111.145,-110.962,-111.166,-110.723,-110.574,-110.537,-110.832,-111.761,-112.573,-114.296,-115.125,-114.001,-112.972,-113.209,-114.375,-114.555,-113.352,-112.165,-111.832,-112.856,-113.402,-112.279,-110.489,-111.888,-113.526,-114.229,-115.044,-117.066,-117.402,-118.132,-118.265,-117.808,-117.967,-118.300,-119.307,-121.780,-122.981,-123.681,-124.349,-124.124,-123.505,-123.657,-123.993,-124.409,-125.114,-125.915,-126.492,-127.790,-128.509,-129.527,-129.894,-130.940,-131.949,-132.699,-133.438,-134.220,-133.799,-135.302,-136.435,-137.355,-137.192,-136.527,-135.854,-135.750,-136.588,-136.873,-137.603,-137.112,-137.211,-138.369,-138.829,-139.236,-139.855,-139.136,-137.927,-137.191,-136.999,-137.042,-138.456,-139.750,-139.278,-138.564,-137.944,-138.976,-139.081,-140.226,-141.159,-141.426,-141.461,-141.932,-142.262,-142.554,-143.842,-146.616,-147.514,-147.864,-149.089,-149.461,-149.851,-150.039,-150.895,-151.377,-150.339,-148.826,-149.043,-148.904,-148.525,-146.954,-145.606,-144.923,-144.310,-144.874,-144.941,-145.590,-145.796,-145.791,-144.587,-144.171,-145.085,-144.277,-143.979,-143.878,-143.040,-142.802,-143.534,-142.986,-141.908,-141.910,-143.482,-144.777,-146.473,-146.765,-147.099,-147.926,-148.816,-149.406,-149.876,-150.466,-151.011,-151.435,-150.980,-149.861,-149.800,-150.081,-149.384,-148.444,-147.844,-146.951,-148.078,-149.628,-150.950,-151.670,-152.860,-153.838,-154.822,-156.033,-157.488,-159.356,-160.253,-161.386,-162.532,-162.487,-162.628,-162.317,-161.640,-161.902,-162.831,-162.415,-161.915,-161.242,-160.431,-161.141,-161.516,-160.725,-161.089,-160.943,-161.476,-160.734,-160.286,-160.674,-159.941,-160.474,-160.646,-160.657,-160.211,-159.288,-159.365,-160.144,-161.011,-161.364,-160.617,-159.636,-159.971,-159.261,-158.119,-157.558,-157.351,-156.804,-156.222,-155.675,-155.124,-155.682,-157.387,-157.305,-157.856,-157.899,-158.404], 'diam':[1.584,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.141,1.141,1.141,1.056,1.056,1.056,1.056,1.056,1.056,1.056,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,1.141,1.141,1.141,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.706,0.706,0.706,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.613,0.528,0.528,0.528,0.528] }, prefix + 'apic[133]': { 'x':[-395.800,-396.659,-398.062,-399.762,-401.076,-401.844,-402.367,-402.802,-403.344], 'y':[733.524,734.243,734.271,734.799,735.448,736.263,736.813,737.474,738.048], 'z':[-49.182,-48.793,-48.810,-47.874,-46.669,-45.895,-45.210,-44.141,-43.286], 'diam':[0.528,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442] }, prefix + 'apic[52]': { 'x':[-369.473,-368.533], 'y':[726.158,725.556], 'z':[-29.787,-29.616], 'diam':[0.442,0.349] }, prefix + 'apic[60]': { 'x':[-375.585,-374.330,-373.399], 'y':[726.541,725.473,724.744], 'z':[-37.841,-38.464,-38.753], 'diam':[0.613,0.349,0.349] }, prefix + 'apic[29]': { 'x':[-363.474,-361.593,-360.236,-356.998,-355.747,-354.171], 'y':[708.950,709.223,709.329,710.767,711.430,711.753], 'z':[-30.479,-31.285,-31.665,-31.946,-31.404,-31.184], 'diam':[0.442,0.442,0.442,0.442,0.442,0.442] }, prefix + 'apic[83]': { 'x':[-396.249,-397.668,-398.580,-399.275,-398.445,-399.225], 'y':[731.890,732.937,732.567,731.888,733.471,733.084], 'z':[-29.596,-29.295,-29.020,-28.390,-27.647,-25.820], 'diam':[0.442,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[141]': { 'x':[-405.528,-407.064,-407.997,-409.379,-410.668,-413.057,-414.735,-415.819], 'y':[741.655,740.806,741.126,741.189,741.166,742.567,742.282,742.290], 'z':[-49.825,-48.485,-47.945,-47.974,-48.236,-47.509,-46.876,-46.560], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[32]': { 'x':[-374.047,-375.377,-376.578,-376.863,-376.698,-376.712,-375.809,-375.324,-373.768,-373.132,-372.237,-370.628,-368.896,-365.873], 'y':[713.597,714.397,714.061,713.488,713.107,711.757,711.765,711.906,711.252,711.417,711.263,710.982,709.197,709.878], 'z':[-36.870,-36.237,-35.099,-34.175,-33.014,-30.618,-29.134,-28.005,-27.161,-25.704,-24.674,-24.485,-24.259,-25.370], 'diam':[1.056,0.613,0.613,0.613,0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.264,0.264,0.264] }, prefix + 'apic[10]': { 'x':[-361.157,-360.269,-359.369,-358.779,-357.548,-356.271], 'y':[717.776,716.766,715.817,715.534,714.767,714.283], 'z':[-40.571,-41.634,-42.525,-43.829,-45.002,-46.011], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'dend[3]': { 'x':[-298.473,-300.796], 'y':[711.113,716.093], 'z':[-91.333,-93.880], 'diam':[2.111,2.639] }, prefix + 'apic[96]': { 'x':[-356.531,-355.340,-355.120,-355.284,-355.345,-355.552,-355.564,-355.514,-356.372,-356.873,-357.634,-358.764,-359.947,-359.490], 'y':[719.306,718.169,718.525,719.169,719.818,720.428,721.228,721.833,721.206,721.586,722.125,722.048,723.032,725.088], 'z':[-4.255,-4.066,-2.835,-1.689,-0.632,0.534,1.869,2.673,3.478,5.167,6.038,7.003,8.150,8.067], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[57]': { 'x':[-365.713,-366.883,-367.364,-367.951,-367.590,-366.086,-365.206,-365.642], 'y':[723.216,724.451,724.954,725.173,725.573,726.170,726.953,728.929], 'z':[-29.929,-28.596,-27.811,-26.825,-25.103,-24.034,-21.788,-19.918], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[14]': { 'x':[-349.325,-348.724,-348.591,-347.995,-347.016], 'y':[719.230,719.576,719.953,720.240,720.597], 'z':[-30.168,-28.356,-27.211,-26.319,-25.730], 'diam':[0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[101]': { 'x':[-380.344,-381.313,-383.489], 'y':[724.015,724.347,724.129], 'z':[-44.355,-45.068,-44.607], 'diam':[0.613,0.613,0.613] }, prefix + 'apic[86]': { 'x':[-382.134,-383.162,-383.728], 'y':[726.717,727.850,729.654], 'z':[-40.431,-37.872,-36.522], 'diam':[0.706,0.264,0.264] }, prefix + 'apic[88]': { 'x':[-383.728,-385.207,-385.674,-387.048,-388.106,-388.561,-388.470,-389.568], 'y':[729.654,730.487,731.331,733.054,734.254,735.086,734.935,735.387], 'z':[-36.522,-36.485,-37.028,-36.814,-36.334,-37.654,-39.407,-40.369], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'dend[10]': { 'x':[-294.830,-295.640,-295.450,-294.694,-294.726,-293.419,-294.203,-295.289,-295.734,-296.180,-295.141,-293.543,-292.051,-290.781,-289.723,-289.378,-288.088,-286.941,-285.542,-284.092,-283.645,-284.772,-285.999,-287.526,-288.461,-287.967,-287.483,-286.755,-286.283,-287.194,-287.998,-287.085,-285.126,-284.878,-285.347,-285.881,-286.782,-287.650,-289.126,-290.105,-289.804,-289.077,-288.715,-287.721,-287.381,-287.442,-288.738,-289.723,-289.561,-288.807,-287.963,-287.514,-286.662,-284.561,-282.570,-281.217,-279.802,-280.861,-279.524,-278.765,-278.790,-278.763,-279.020,-279.999,-281.548,-282.640,-284.015,-284.705,-286.890,-288.634,-289.180,-288.230,-287.276,-287.563,-288.513,-289.974,-290.591,-290.583,-290.845,-292.186,-291.397,-290.192,-288.949,-290.005,-290.912,-291.519,-292.976,-292.787,-291.593,-290.416,-290.066,-290.697,-292.022,-293.006,-294.076,-294.929,-296.013,-294.622,-293.443,-291.774,-290.253,-290.273,-290.721,-290.340,-290.745,-290.617,-290.264,-290.234,-290.235,-290.868,-292.060,-293.410,-292.706,-291.754,-290.734,-291.977,-291.036,-290.427,-291.333,-290.860,-289.640,-289.288,-287.986,-289.078,-289.939,-290.730,-289.432,-288.759,-288.180,-288.007,-288.023,-288.613,-286.807,-285.979,-286.101,-286.037,-285.054,-284.233,-282.866,-281.557,-280.836,-280.910,-281.131,-281.975,-282.513,-282.688,-282.261,-281.770,-280.603,-279.859,-280.361,-282.253,-283.264,-282.732,-282.137,-281.988,-282.627,-283.196,-284.436,-285.389,-284.651,-284.775,-285.236,-286.796,-286.976,-288.348,-289.963,-291.327,-291.775,-293.295,-294.377,-293.032,-292.165,-291.113,-290.569,-291.294,-292.152,-292.846,-293.153,-294.779,-295.386,-296.052,-295.753,-295.155,-295.122,-294.939,-294.601,-293.442,-292.931,-293.528,-294.743,-295.864,-296.547,-295.360,-294.388,-295.357,-295.475,-294.593,-294.070,-293.536,-293.127,-294.477,-296.176,-297.756,-296.429,-296.297,-297.212,-298.384,-299.767,-300.285,-299.916,-299.912,-298.850,-298.943,-299.973,-300.784,-299.826,-297.522,-296.326,-295.507,-295.883,-296.436,-296.757,-296.521,-295.509,-295.312,-294.807,-294.535,-293.400,-292.763,-292.063,-291.696,-291.394,-291.458,-290.967,-290.335,-289.100,-287.852,-286.254,-287.387,-287.607,-286.741,-286.054,-286.971,-287.103,-286.690,-286.365,-285.563,-285.540,-286.532,-285.872,-284.207,-284.595,-285.816,-284.811,-283.500,-282.449,-281.391,-280.330,-279.739,-280.892,-281.820,-281.522,-280.317,-279.438,-279.451,-279.025,-278.612,-277.884,-277.873,-278.237,-279.036,-280.243,-279.809,-280.535,-282.726,-282.178,-281.502,-280.590,-279.864,-280.728,-281.723,-281.630,-279.935,-279.132,-278.168,-278.580,-279.378,-278.334,-277.403,-276.584,-275.921,-275.876,-276.302,-277.218,-277.648,-277.335,-276.456,-274.987,-273.699,-273.814,-273.212,-272.275,-271.599,-271.412,-271.380,-270.604,-270.203,-269.480,-268.753,-268.081,-267.393,-267.292,-266.883,-267.076,-265.014,-264.290,-264.039,-262.618,-261.282,-262.425,-262.780,-263.712,-264.416,-265.944,-265.798,-266.823,-268.222,-268.103,-269.320,-271.102,-271.123,-272.291,-273.089,-273.453,-273.855,-274.027,-274.532,-273.968,-273.611,-273.352,-273.484,-274.913,-275.586,-276.510,-277.437,-278.891,-279.648,-280.840,-281.086], 'y':[745.482,746.323,747.646,748.524,749.509,750.408,750.717,750.473,751.163,751.672,752.517,753.937,754.461,754.845,755.100,755.777,756.626,757.502,758.334,759.625,760.588,761.357,761.442,761.090,760.913,760.945,762.316,762.545,762.904,764.097,764.358,764.552,765.070,766.644,767.398,768.069,769.216,769.587,769.847,770.637,771.453,773.289,774.297,774.342,774.418,774.815,775.468,776.002,776.513,777.358,778.200,778.183,778.263,778.834,779.155,780.377,781.161,781.504,782.205,782.355,783.203,783.838,783.955,783.918,785.194,785.959,785.531,785.061,786.160,786.973,787.759,788.539,788.709,789.764,790.141,790.409,790.725,792.382,794.290,794.376,795.120,796.156,796.591,796.930,797.444,797.650,798.326,800.033,801.091,801.919,802.892,802.836,802.817,802.335,802.608,802.521,802.740,803.561,804.290,804.856,805.304,805.871,807.286,808.349,809.460,810.533,812.071,812.684,814.192,814.926,815.572,815.459,816.363,816.928,818.213,819.281,820.935,821.483,822.190,823.709,824.308,825.288,826.651,827.713,828.176,828.912,829.962,830.335,832.120,833.286,834.188,835.165,836.239,836.385,837.249,838.348,839.166,840.376,841.048,841.790,842.943,843.781,843.652,843.947,844.110,844.899,846.084,847.766,849.226,849.725,850.301,851.091,851.636,853.324,854.041,855.905,856.635,856.565,856.063,856.572,857.087,858.036,858.036,858.056,859.055,859.708,860.245,860.190,859.869,859.759,859.923,860.517,861.216,862.943,864.205,864.936,865.443,865.994,865.909,866.688,867.465,868.476,869.473,870.247,871.910,872.280,873.615,874.409,875.413,876.129,875.783,875.408,876.724,877.666,878.364,879.340,880.762,881.410,882.182,882.953,884.001,884.930,885.758,887.083,888.550,889.544,889.899,889.804,890.602,891.153,893.699,894.523,895.364,896.593,896.473,896.544,897.133,898.282,899.547,899.869,900.375,900.356,901.662,902.902,904.082,906.131,906.871,907.288,908.810,909.763,910.461,912.949,914.172,914.976,915.570,916.028,916.328,917.520,918.260,919.557,920.576,921.229,922.115,922.527,923.203,924.092,925.082,927.253,927.829,928.464,929.980,931.387,932.136,932.684,933.712,934.132,934.658,935.104,935.552,936.227,936.293,936.471,937.334,938.134,938.779,940.212,942.746,943.796,944.968,946.523,946.690,946.777,947.102,948.325,949.385,950.040,950.809,951.698,952.073,953.409,954.081,953.945,953.993,955.051,955.992,956.772,957.517,957.635,958.779,959.302,960.151,960.590,962.092,962.801,963.434,964.650,965.940,966.991,967.431,968.398,970.102,970.935,971.441,972.836,973.836,974.492,976.023,977.468,979.159,980.782,981.800,982.252,982.646,983.729,984.908,986.277,987.098,988.355,989.613,990.823,992.339,993.678,994.871,995.314,996.185,996.949,998.115,998.006,998.924,999.465,999.977,1002.189,1003.349,1004.127,1004.972,1006.830,1007.091,1008.878,1007.774,1008.625,1009.830,1011.138,1013.236,1013.463,1013.742,1014.491,1015.413,1016.021,1018.192,1019.920], 'z':[-106.725,-104.402,-104.064,-105.445,-106.001,-106.473,-104.117,-103.170,-102.444,-101.508,-101.794,-102.603,-103.570,-103.782,-102.764,-101.798,-100.892,-101.175,-100.829,-100.758,-101.246,-102.691,-103.914,-104.208,-103.566,-102.440,-101.815,-100.972,-100.156,-98.965,-97.658,-96.445,-96.068,-93.927,-91.931,-90.748,-90.137,-90.569,-90.075,-89.299,-88.788,-88.856,-89.000,-89.185,-87.971,-86.985,-86.747,-87.989,-89.510,-89.606,-88.312,-86.854,-85.780,-85.595,-85.738,-85.687,-85.357,-83.492,-82.024,-79.331,-77.932,-76.449,-75.302,-74.549,-74.478,-74.313,-73.870,-71.212,-70.170,-69.143,-68.174,-66.429,-65.554,-64.304,-64.075,-64.588,-65.380,-65.188,-64.173,-64.129,-64.564,-65.174,-64.485,-63.024,-62.444,-61.532,-61.997,-61.327,-60.672,-60.399,-59.243,-57.332,-55.693,-53.745,-53.310,-52.796,-53.290,-52.888,-53.648,-54.069,-53.707,-52.611,-51.893,-51.522,-50.270,-49.679,-50.393,-51.238,-50.596,-48.377,-47.794,-46.851,-45.562,-45.900,-45.350,-43.929,-43.680,-42.775,-41.480,-40.714,-40.116,-40.549,-40.557,-39.679,-39.453,-39.636,-38.637,-37.882,-37.865,-38.062,-36.700,-35.705,-36.511,-35.637,-34.191,-33.022,-33.222,-34.066,-34.252,-33.754,-33.343,-32.566,-30.887,-28.946,-27.472,-26.474,-25.632,-27.004,-27.216,-26.436,-25.253,-25.039,-23.424,-22.626,-23.425,-22.851,-20.523,-19.297,-18.398,-17.367,-15.204,-14.075,-12.833,-12.804,-13.841,-13.836,-13.393,-12.565,-10.576,-9.190,-8.195,-7.708,-7.581,-8.690,-9.316,-8.804,-7.427,-6.598,-5.595,-4.446,-4.042,-2.491,-2.252,-3.511,-3.892,-2.930,-2.765,-2.181,-1.357,-0.847,-0.820,-0.324,0.825,0.517,0.975,2.527,3.594,3.823,3.353,2.890,3.022,3.419,2.312,0.806,-0.126,-0.806,-1.147,-0.974,-1.390,-3.061,-2.988,-1.294,-0.937,0.570,0.398,1.515,2.532,2.299,2.493,3.130,4.770,6.001,7.164,7.421,6.901,7.835,9.644,10.954,10.951,11.536,12.329,12.501,13.680,14.802,13.975,13.243,13.209,12.701,12.519,11.419,10.613,9.228,9.590,9.142,8.299,7.389,7.281,7.670,6.708,6.404,6.254,5.790,4.953,4.958,5.346,5.327,5.203,5.285,5.377,4.556,3.731,2.570,1.539,1.672,1.891,3.192,4.060,4.201,4.478,5.106,6.028,7.042,7.709,8.668,9.557,9.323,10.453,10.808,11.682,11.403,12.586,13.792,15.628,16.146,16.291,16.414,17.735,18.413,19.380,19.355,19.484,20.120,21.858,23.521,23.897,25.154,24.176,24.435,24.281,24.012,23.389,21.977,21.220,21.698,22.128,23.446,22.439,23.721,22.972,22.885,22.978,23.583,25.097,24.869,24.064,25.024,24.068,23.733,24.628,23.602,23.076,22.187,21.743,20.545,19.059,18.104,17.099,16.873,15.830,14.866,13.575,13.336,13.575,12.418,11.819,11.885,10.431,10.393,10.053,9.326,8.989,8.659,8.666,10.176,11.015,11.316,11.096,10.590,9.106,9.400], 'diam':[1.584,1.405,1.405,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.056,1.056,1.056,1.056,1.141,1.141,1.141,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,1.234,0.877,0.877,0.877,0.877,0.877,0.877,0.970,1.056,1.234,1.234,1.234,1.234,1.234,1.141,1.141,1.141,1.141,1.141,1.141,1.141,1.405,1.405,1.141,1.141,1.141,1.056,1.056,1.056,1.056,1.056,1.056,1.056,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.877,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,1.056,1.056,1.056,1.056,1.056,1.056,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,0.970,1.141,1.141,1.141,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.706,0.706,0.706,0.706,0.613,0.613,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[53]': { 'x':[-368.533,-367.013,-365.713], 'y':[725.556,724.272,723.216], 'z':[-29.616,-30.325,-29.929], 'diam':[0.349,0.349,0.349] }, prefix + 'apic[1]': { 'x':[-307.800,-309.439,-311.572,-313.045,-313.279,-315.185,-316.904,-318.742,-320.373,-321.410,-321.222,-321.668,-323.198,-324.584,-325.879,-326.960,-327.741,-328.353,-328.294,-328.457,-329.281,-330.732,-331.515,-332.332,-333.168,-334.237,-336.066,-337.787,-339.737,-340.831,-341.487,-342.366,-342.826,-343.405,-344.321,-345.188,-346.907,-348.249,-349.687,-351.307,-352.654,-354.178,-355.769,-356.813,-358.275,-359.786,-361.096,-363.107,-364.527,-365.814], 'y':[701.708,701.662,700.645,700.201,700.482,701.080,700.706,700.313,700.961,702.195,702.784,703.712,703.310,704.513,704.891,705.222,704.637,704.477,704.542,704.697,705.028,704.913,704.687,704.686,704.855,705.066,705.481,705.046,704.039,703.520,704.217,705.076,705.891,706.454,707.485,708.339,709.030,709.653,710.322,710.922,710.819,711.232,711.320,711.501,712.310,713.047,714.291,714.824,716.382,717.747], 'z':[-88.086,-90.825,-90.843,-89.633,-88.540,-88.394,-88.943,-89.127,-88.912,-87.526,-85.778,-84.205,-81.907,-81.152,-80.442,-79.474,-78.447,-77.487,-76.303,-74.644,-73.606,-74.331,-75.064,-75.881,-76.500,-77.378,-78.038,-78.291,-77.378,-76.514,-75.711,-74.685,-73.416,-70.455,-68.446,-67.427,-67.078,-67.054,-67.400,-68.040,-67.660,-67.217,-66.905,-66.742,-65.842,-64.732,-63.742,-61.937,-60.204,-58.901], 'diam':[2.111,2.290,1.933,1.762,1.762,1.762,1.762,1.762,1.762,2.111,2.111,2.111,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.762,1.847] }, prefix + 'axon': { 'x':[-295.384,-292.833,-291.698,-290.797,-290.500,-290.190,-290.049,-289.817,-289.077,-288.859], 'y':[727.861,726.253,727.784,728.697,729.609,729.827,730.979,731.298,731.819,732.157], 'z':[-103.483,-106.215,-107.317,-107.620,-108.480,-109.789,-111.454,-112.411,-114.434,-116.668], 'diam':[1.847,0.792,0.792,0.792,0.613,0.613,0.613,0.613,0.613,0.613] }, prefix + 'apic[103]': { 'x':[-385.468,-386.636,-387.519], 'y':[724.833,725.405,726.008], 'z':[-44.329,-43.700,-43.616], 'diam':[0.349,0.349,0.442] }, prefix + 'apic[36]': { 'x':[-377.821,-376.611,-375.585], 'y':[725.564,725.842,726.541], 'z':[-41.334,-38.724,-37.841], 'diam':[0.792,0.528,0.613] }, prefix + 'apic[143]': { 'x':[-392.313,-393.149,-393.620,-395.844,-396.906,-397.972], 'y':[732.909,733.729,735.242,733.712,733.360,733.506], 'z':[-53.049,-52.525,-52.809,-51.594,-50.897,-50.708], 'diam':[0.442,0.085,0.085,0.085,0.085,0.085] }, prefix + 'apic[65]': { 'x':[-399.375,-401.214,-402.006,-403.047,-404.055,-405.285,-406.241], 'y':[745.313,746.594,747.718,748.440,748.906,749.265,749.621], 'z':[-22.443,-22.214,-22.578,-22.794,-22.473,-21.685,-21.414], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[81]': { 'x':[-405.902,-406.027,-406.669], 'y':[732.221,731.166,729.976], 'z':[-32.098,-33.508,-33.897], 'diam':[0.264,0.179,0.179] }, prefix + 'apic[111]': { 'x':[-393.081,-391.578,-390.541,-390.563], 'y':[723.019,723.229,722.316,720.782], 'z':[-41.593,-41.918,-41.138,-40.745], 'diam':[0.349,0.349,0.349,0.349] }, prefix + 'apic[7]': { 'x':[-361.157,-360.532,-359.778,-359.362], 'y':[717.776,716.952,716.330,715.202], 'z':[-40.571,-39.099,-37.884,-36.885], 'diam':[0.264,0.264,0.264,0.264] }, prefix + 'apic[139]': { 'x':[-382.274,-384.558,-385.357,-386.809,-389.189,-390.467,-391.748,-392.313], 'y':[727.857,729.161,729.749,730.364,731.240,731.586,731.815,732.910], 'z':[-51.928,-52.365,-52.188,-52.683,-52.171,-51.808,-51.728,-53.049], 'diam':[0.877,0.442,0.442,0.442,0.442,0.442,0.442,0.442] }, prefix + 'apic[22]': { 'x':[-363.474,-362.344], 'y':[708.950,708.536], 'z':[-30.479,-29.530], 'diam':[0.442,0.528] }, prefix + 'apic[61]': { 'x':[-377.821,-378.506], 'y':[725.564,727.022], 'z':[-41.334,-41.156], 'diam':[0.792,0.349] }, prefix + 'dend[12]': { 'x':[-282.502,-282.951,-283.264,-282.651,-281.742,-281.836,-281.521,-281.167,-280.261,-278.950,-277.874,-277.453,-276.385,-275.693,-276.174,-275.823,-274.889,-275.709,-275.128,-274.394,-273.690,-273.799,-275.126,-274.183,-273.470,-273.059,-272.762,-272.434,-271.538,-270.287,-270.580,-269.918,-268.621,-268.176,-268.772,-268.324,-267.145,-266.008,-265.314,-264.971,-264.444,-264.715,-264.102,-263.089,-262.318,-261.276,-261.048,-260.969,-261.047,-260.995,-260.433,-259.366,-258.657,-257.841,-257.720,-256.785,-254.819,-253.896,-252.407,-251.150,-250.773,-249.012,-247.861,-247.108,-246.989,-246.580,-247.266,-247.012,-247.095,-247.104,-247.176,-245.840,-245.147,-244.552,-243.213,-242.054,-241.056,-240.447,-239.043,-238.465,-238.359,-235.924,-235.064,-233.719,-232.133,-231.126,-230.411,-230.062,-229.061,-228.056,-227.361,-225.939,-224.848,-223.318,-222.018,-221.262,-219.883,-219.418,-218.863,-217.762,-216.335,-215.267,-214.578,-213.499,-212.182,-211.160,-210.388,-210.073,-209.702,-209.145,-208.096,-207.482,-205.906,-204.867,-204.319,-203.235,-200.866,-200.512,-200.397,-200.008,-199.882,-199.628,-199.439,-199.189,-198.568,-197.782,-196.711,-195.691,-194.392,-193.562,-192.465,-191.441,-190.536,-189.684,-189.133,-188.724,-188.509,-188.375,-188.037,-187.356,-187.103,-187.114,-187.182,-186.890,-186.045,-185.187,-184.586,-183.717], 'y':[721.731,723.508,723.561,724.266,724.692,725.009,725.765,726.947,727.081,727.791,729.214,729.553,729.779,730.419,730.667,731.556,731.831,732.378,734.065,734.694,736.106,736.763,737.736,738.712,740.218,740.703,742.478,743.779,744.535,745.910,747.546,748.483,748.466,749.956,750.926,753.573,753.809,753.092,754.314,755.303,757.112,758.114,759.318,759.846,761.132,761.416,762.450,762.994,763.931,764.339,764.522,764.748,765.485,766.124,766.848,767.021,767.323,767.592,767.866,768.377,770.324,771.279,772.052,772.812,773.893,775.147,776.156,778.003,778.891,779.908,780.645,781.069,781.416,782.234,783.380,783.523,784.005,785.152,786.327,787.191,790.048,793.872,793.985,794.966,795.667,796.979,797.446,798.496,799.618,800.332,801.033,802.141,802.513,803.300,803.648,804.033,804.516,805.384,806.469,806.778,806.996,807.415,807.991,809.207,810.207,811.315,812.667,813.882,815.138,817.123,818.453,820.292,821.042,821.963,823.055,823.899,825.768,826.825,828.414,828.547,828.693,829.568,829.804,830.557,833.493,834.459,834.796,835.914,836.508,837.483,838.077,838.960,839.785,840.605,842.354,843.259,843.669,844.165,846.122,846.735,847.718,848.847,851.647,854.513,855.301,857.066,858.903,860.322], 'z':[-73.572,-71.714,-70.740,-70.083,-69.566,-68.090,-67.158,-66.572,-65.932,-64.657,-64.282,-63.052,-63.774,-63.428,-61.807,-61.097,-59.996,-57.996,-57.633,-58.102,-58.156,-57.410,-57.063,-55.885,-56.053,-54.848,-54.316,-54.799,-53.840,-53.668,-53.023,-52.715,-51.782,-50.625,-50.462,-50.540,-50.076,-49.559,-49.490,-48.790,-48.794,-48.568,-49.802,-48.691,-49.076,-49.689,-48.428,-47.404,-45.153,-43.898,-42.737,-42.300,-41.507,-41.256,-39.876,-39.346,-38.258,-37.726,-37.085,-36.387,-35.717,-35.065,-34.755,-34.767,-35.285,-34.454,-34.442,-34.274,-33.770,-33.024,-31.931,-31.790,-30.726,-31.139,-30.806,-30.214,-29.579,-29.062,-29.067,-28.310,-27.902,-27.288,-26.747,-27.252,-27.594,-27.358,-26.750,-26.558,-26.077,-25.115,-24.638,-24.803,-24.489,-24.380,-23.826,-23.016,-22.225,-21.896,-21.462,-21.240,-20.661,-19.088,-18.378,-18.703,-17.718,-16.214,-15.894,-15.373,-14.520,-13.688,-13.791,-14.670,-15.015,-14.632,-14.196,-14.143,-12.727,-12.539,-11.731,-9.870,-8.835,-7.615,-6.134,-4.674,-4.366,-3.797,-3.234,-2.879,-2.554,-2.432,-1.216,-0.727,-0.114,1.058,2.127,3.010,4.037,5.623,6.422,7.134,7.202,7.447,7.930,8.199,8.336,8.112,8.494,8.937], 'diam':[0.613,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.613,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[0]': { 'x':[-297.860,-301.678,-304.183,-306.007,-306.943,-307.800], 'y':[705.320,703.593,702.770,702.413,701.533,701.708], 'z':[-86.808,-85.198,-84.344,-84.329,-85.871,-88.086], 'diam':[3.082,2.197,2.290,2.026,2.026,2.111] }, prefix + 'apic[69]': { 'x':[-378.506,-379.512,-381.424,-381.525,-382.168,-382.693,-382.760,-382.899,-382.684], 'y':[727.022,729.156,729.306,732.428,733.429,734.979,735.904,736.649,737.085], 'z':[-41.156,-39.212,-37.874,-37.467,-36.173,-34.131,-33.186,-32.499,-31.557], 'diam':[0.349,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[63]': { 'x':[-398.247,-398.575,-399.375], 'y':[742.846,744.331,745.313], 'z':[-24.556,-23.585,-22.443], 'diam':[0.349,0.264,0.264] }, prefix + 'apic[43]': { 'x':[-365.089,-364.095,-363.786,-363.053,-361.267,-360.283,-359.567,-359.700,-359.717,-359.359,-358.745,-358.229,-357.819,-357.919,-356.174,-353.860,-352.695,-351.931,-352.066,-351.850,-352.304,-352.948,-355.406,-357.292,-358.293,-359.474], 'y':[732.271,731.448,730.651,730.469,731.074,731.081,731.639,732.750,733.367,733.577,733.590,733.950,734.561,734.489,735.624,735.539,735.280,735.259,736.319,737.215,738.411,739.295,738.353,738.555,738.629,738.284], 'z':[-3.214,-1.161,-0.621,0.093,1.827,3.405,5.921,7.997,9.324,10.252,11.257,12.974,15.144,17.122,18.674,21.851,23.084,24.246,26.174,27.649,29.726,30.552,31.291,31.413,30.925,30.508], 'diam':[0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[8]': { 'x':[-359.362,-358.113,-357.193,-355.757], 'y':[715.202,714.929,715.687,716.173], 'z':[-36.885,-35.572,-35.639,-35.725], 'diam':[0.264,0.264,0.264,0.264] }, prefix + 'apic[19]': { 'x':[-374.047,-372.254,-371.023], 'y':[713.597,714.780,715.203], 'z':[-36.870,-35.253,-34.276], 'diam':[1.056,0.877,0.877] }, prefix + 'apic[99]': { 'x':[-366.046,-365.031,-364.659,-363.949,-363.236,-362.423,-360.957,-359.890,-358.716,-358.415], 'y':[719.602,718.590,717.328,715.568,714.673,713.731,712.309,710.972,710.110,709.056], 'z':[-24.003,-24.716,-25.226,-24.867,-25.013,-25.397,-26.244,-25.981,-25.904,-25.699], 'diam':[0.613,0.442,0.442,0.442,0.442,0.442,0.349,0.349,0.349,0.349] }, prefix + 'apic[55]': { 'x':[-352.948,-352.323,-351.955], 'y':[715.283,716.032,715.597], 'z':[-36.221,-38.168,-39.754], 'diam':[0.349,0.349,0.349] }, prefix + 'apic[131]': { 'x':[-394.546,-395.178,-396.816,-398.059,-397.235,-397.128,-397.378], 'y':[737.443,739.653,741.496,742.931,744.586,745.804,746.403], 'z':[-41.888,-40.861,-37.837,-35.203,-34.149,-33.312,-32.400], 'diam':[0.528,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[41]': { 'x':[-373.328,-372.916,-372.633,-371.503,-370.648,-369.763,-369.576,-368.603,-367.886,-367.894,-366.920,-366.165], 'y':[731.957,732.107,732.450,733.358,733.361,732.488,732.939,733.302,733.131,732.243,732.328,732.626], 'z':[-19.495,-18.466,-17.135,-14.191,-12.347,-12.156,-11.053,-9.863,-8.978,-8.057,-5.991,-4.049], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[50]': { 'x':[-371.908,-372.309,-372.937,-373.834,-374.959,-375.629,-376.311], 'y':[728.584,729.840,730.617,731.047,731.564,732.200,733.169], 'z':[-28.319,-29.607,-28.661,-27.823,-27.087,-25.832,-24.348], 'diam':[0.528,0.528,0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[2]': { 'x':[-365.814,-368.681,-369.788,-371.406], 'y':[717.747,716.931,718.424,719.126], 'z':[-58.901,-54.958,-53.035,-51.397], 'diam':[1.847,1.584,1.584,1.933] }, prefix + 'apic[54]': { 'x':[-365.713,-364.794,-362.683,-361.201,-359.872,-358.804,-357.848,-356.380,-355.525,-353.766,-353.747,-352.948], 'y':[723.216,722.433,722.539,721.362,720.292,719.760,719.542,718.712,717.942,717.817,714.841,715.283], 'z':[-29.929,-30.380,-30.793,-31.476,-32.613,-32.996,-33.401,-33.869,-34.407,-35.302,-35.166,-36.221], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[64]': { 'x':[-399.375,-398.949,-399.553,-399.921,-399.534,-399.055,-399.483,-399.929], 'y':[745.313,745.642,746.537,746.527,747.841,748.931,749.579,750.448], 'z':[-22.443,-20.947,-19.709,-18.472,-17.861,-17.348,-16.449,-15.017], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[142]': { 'x':[-405.528,-406.701,-406.364,-406.662,-406.591], 'y':[741.655,742.240,743.432,744.356,745.500], 'z':[-49.825,-50.398,-51.126,-51.799,-52.130], 'diam':[0.349,0.179,0.179,0.179,0.179] }, prefix + 'apic[92]': { 'x':[-366.046,-365.415,-364.489,-363.874,-363.707,-364.266,-364.450,-365.429,-365.583], 'y':[719.602,719.723,719.788,719.926,720.335,719.706,719.971,721.388,722.216], 'z':[-24.003,-22.716,-21.068,-20.212,-19.074,-17.789,-16.837,-14.735,-12.958], 'diam':[0.613,0.528,0.613,0.613,0.613,0.613,0.613,0.528,0.528] }, prefix + 'apic[18]': { 'x':[-374.024,-373.888,-374.047], 'y':[715.198,714.772,713.597], 'z':[-38.925,-37.744,-36.870], 'diam':[0.877,1.056,1.056] }, prefix + 'apic[13]': { 'x':[-349.325,-347.331,-346.054,-345.056,-342.992,-341.074,-340.066], 'y':[719.230,718.763,718.732,718.538,718.594,719.015,719.613], 'z':[-30.168,-28.903,-28.790,-28.614,-27.790,-26.946,-26.354], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[39]': { 'x':[-371.908,-371.971,-372.031,-373.102,-372.570], 'y':[728.584,729.114,730.297,730.468,730.628], 'z':[-28.319,-27.122,-25.843,-23.092,-21.545], 'diam':[0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[105]': { 'x':[-389.321,-390.872,-393.230,-394.618,-396.495,-397.479,-399.359,-399.787,-400.428,-401.421,-402.452], 'y':[727.188,728.427,728.388,728.865,729.325,729.974,731.639,732.220,732.834,733.481,733.848], 'z':[-42.050,-41.305,-40.826,-40.309,-39.867,-39.531,-38.747,-37.997,-36.897,-36.561,-36.376], 'diam':[0.349,0.264,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[20]': { 'x':[-371.023,-370.904,-369.504,-368.649,-367.762,-366.881,-366.462,-366.015,-365.121], 'y':[715.203,713.839,712.684,711.914,711.232,710.620,710.628,710.137,711.058], 'z':[-34.276,-33.412,-34.011,-34.549,-34.357,-33.825,-32.826,-31.468,-31.344], 'diam':[0.877,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528] }, prefix + 'apic[95]': { 'x':[-356.531,-356.357,-356.211,-356.847,-357.411,-358.043,-358.371,-358.373,-358.634,-359.241,-359.446,-359.670], 'y':[719.306,719.576,720.009,720.683,721.485,722.612,723.484,724.753,725.350,726.192,726.729,728.162], 'z':[-4.255,-2.374,-1.081,-0.433,0.168,1.329,2.493,4.341,5.251,6.353,7.364,8.825], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[66]': { 'x':[-398.247,-400.434,-401.322], 'y':[742.846,743.042,743.117], 'z':[-24.556,-24.298,-23.836], 'diam':[0.349,0.264,0.264] }, prefix + 'apic[70]': { 'x':[-375.082,-376.862], 'y':[723.155,723.172], 'z':[-47.527,-46.307], 'diam':[1.234,0.706] }, prefix + 'apic[78]': { 'x':[-389.242,-389.545,-388.952,-389.614,-390.274,-390.847,-391.293,-391.250,-391.190,-391.189,-391.486,-391.589,-390.671,-388.347,-386.753,-385.610,-385.313,-384.984,-384.001,-383.552], 'y':[737.183,735.720,733.874,733.561,734.323,734.985,734.122,736.084,737.218,737.671,737.249,737.279,737.752,737.795,738.020,737.726,736.788,734.907,734.454,733.489], 'z':[-16.218,-13.950,-13.821,-12.543,-11.407,-10.686,-9.825,-9.253,-8.996,-7.876,-6.916,-5.461,-4.066,-1.801,-0.859,0.388,1.668,2.830,3.889,4.727], 'diam':[0.613,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[93]': { 'x':[-365.583,-364.150,-363.331,-362.285], 'y':[722.216,721.800,721.663,721.533], 'z':[-12.958,-11.684,-10.733,-9.374], 'diam':[0.528,0.442,0.442,0.442] }, prefix + 'apic[62]': { 'x':[-378.506,-380.569,-381.467,-382.632,-384.092,-385.209,-386.393,-388.285,-389.493,-390.521,-391.530,-392.829,-393.886,-394.462,-395.274,-396.035,-397.312,-398.247], 'y':[727.022,727.879,728.886,729.984,731.203,732.263,733.444,733.643,734.731,735.347,736.427,737.673,738.514,739.576,740.314,740.502,741.987,742.846], 'z':[-41.156,-40.311,-39.264,-38.405,-37.744,-36.764,-35.594,-34.708,-33.653,-33.310,-32.279,-31.289,-30.422,-28.716,-27.909,-27.083,-25.326,-24.556], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[136]': { 'x':[-406.717,-406.842,-406.977,-407.200,-408.059,-409.312,-410.009,-411.043,-411.962,-412.473], 'y':[739.828,741.628,742.776,744.472,746.314,747.375,748.252,749.408,750.198,751.598], 'z':[-42.726,-41.140,-40.697,-39.503,-37.905,-37.289,-36.712,-35.956,-35.512,-35.486], 'diam':[0.264,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[117]': { 'x':[-365.814,-367.647,-369.685,-370.483,-371.252,-372.316,-375.201,-377.544,-378.792,-380.006,-381.261,-382.274], 'y':[717.747,719.096,719.119,720.159,720.974,721.842,724.816,724.496,725.215,726.053,727.121,727.857], 'z':[-58.901,-58.352,-57.224,-55.925,-55.151,-54.724,-53.864,-52.659,-52.857,-52.752,-52.129,-51.928], 'diam':[1.847,0.792,0.792,0.792,0.792,0.792,0.792,0.792,0.877,0.877,0.877,0.877] }, prefix + 'apic[9]': { 'x':[-359.362,-356.640,-355.265,-354.352], 'y':[715.202,714.247,713.181,712.601], 'z':[-36.885,-37.383,-37.494,-37.760], 'diam':[0.264,0.264,0.264,0.264] }, prefix + 'dend[8]': { 'x':[-295.384,-296.495,-296.116,-296.992,-298.077,-299.122,-300.559,-300.436,-299.709,-298.724,-298.273,-297.775,-297.079,-296.956,-296.054,-295.490,-294.830], 'y':[727.861,729.288,730.273,730.870,731.347,731.089,731.140,735.000,735.886,737.148,738.291,739.347,740.327,741.610,742.826,743.422,745.482], 'z':[-103.483,-104.712,-106.145,-106.773,-106.760,-106.621,-105.551,-104.625,-104.605,-104.497,-104.729,-104.954,-104.936,-105.431,-106.151,-106.776,-106.725], 'diam':[1.847,1.669,1.669,1.669,1.669,1.669,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.847,1.762,1.762,1.584] }, prefix + 'apic[102]': { 'x':[-383.489,-385.468], 'y':[724.129,724.833], 'z':[-44.607,-44.329], 'diam':[0.613,0.349] }, prefix + 'apic[128]': { 'x':[-399.616,-401.798,-402.972,-403.609,-403.999,-404.388], 'y':[745.693,745.255,745.453,747.194,748.202,749.145], 'z':[-30.891,-30.008,-30.181,-29.852,-28.906,-27.685], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[132]': { 'x':[-390.228,-391.727,-394.791,-395.800], 'y':[733.473,734.070,734.329,733.524], 'z':[-48.183,-49.096,-49.622,-49.182], 'diam':[0.792,0.706,0.528,0.528] }, prefix + 'dend[13]': { 'x':[-282.502,-281.179,-279.068,-274.478,-270.034,-267.279,-265.304,-263.436,-261.995,-260.552,-259.455,-256.293,-253.906,-250.930,-249.019,-247.267,-245.526,-243.939,-242.562,-240.274,-238.721,-236.088,-230.280,-228.669,-226.304,-222.644,-219.207,-217.921,-215.100,-208.235,-204.413,-202.147,-200.018,-198.458,-197.445,-196.573,-195.415,-191.684,-187.133,-182.885,-181.461,-180.007,-178.388,-176.229,-175.254], 'y':[721.731,722.004,723.160,724.226,724.383,725.578,725.697,725.942,726.813,726.959,727.027,727.705,729.561,729.834,730.007,730.099,730.249,731.363,731.823,733.516,734.054,733.441,733.966,734.152,735.442,735.854,736.203,736.349,737.546,738.344,740.001,739.138,739.435,739.589,739.736,739.886,739.781,740.257,740.750,740.146,740.713,740.905,741.130,741.030,740.302], 'z':[-73.572,-71.566,-70.034,-67.165,-65.426,-64.572,-64.516,-64.602,-64.593,-64.875,-65.110,-64.913,-65.462,-65.199,-64.920,-65.492,-65.483,-65.106,-64.616,-64.007,-63.245,-62.318,-61.707,-61.030,-60.615,-59.171,-57.778,-57.273,-55.282,-52.483,-50.745,-48.811,-47.342,-47.024,-46.245,-44.674,-42.222,-38.913,-35.537,-32.516,-30.047,-29.169,-28.034,-25.932,-22.899], 'diam':[0.613,0.264,0.264,0.264,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[127]': { 'x':[-399.616,-400.125,-401.188,-402.693,-403.063,-404.029,-405.162,-405.961,-406.889,-407.999,-408.825,-409.895,-411.317,-412.380,-414.016,-416.057], 'y':[745.693,746.627,747.490,747.541,748.467,748.010,747.465,748.104,749.220,749.996,750.788,751.048,750.530,749.923,749.656,750.351], 'z':[-30.891,-30.175,-29.754,-28.309,-27.250,-26.340,-25.308,-24.373,-23.269,-21.605,-19.879,-18.613,-17.488,-16.518,-16.074,-15.280], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[21]': { 'x':[-365.121,-363.474], 'y':[711.058,708.950], 'z':[-31.344,-30.479], 'diam':[0.528,0.442] }, prefix + 'apic[15]': { 'x':[-357.306,-357.953,-358.543,-358.307,-357.732,-356.809,-356.076], 'y':[721.905,722.583,723.532,723.877,725.751,726.027,726.511], 'z':[-32.611,-31.955,-30.569,-29.507,-26.441,-25.210,-24.398], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[114]': { 'x':[-376.862,-379.421,-380.552,-383.412,-385.811,-386.994,-388.388,-389.631,-392.895,-394.120,-394.255,-395.800,-396.692,-398.766,-399.803,-401.202,-402.064,-403.169,-404.794,-405.774,-406.868,-407.931], 'y':[723.172,724.228,724.759,725.283,726.433,726.483,726.359,727.152,729.428,729.721,731.952,731.709,732.381,733.725,734.770,734.440,734.624,734.576,733.158,733.727,733.887,734.348], 'z':[-46.307,-46.385,-46.866,-47.067,-46.666,-46.106,-46.158,-46.032,-45.480,-45.010,-44.703,-43.578,-42.575,-42.272,-42.288,-41.140,-40.379,-39.449,-38.574,-37.948,-37.611,-37.540], 'diam':[0.706,0.264,0.264,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[124]': { 'x':[-395.218,-396.161], 'y':[740.049,740.635], 'z':[-36.531,-35.502], 'diam':[0.613,0.528] }, prefix + 'apic[56]': { 'x':[-352.948,-351.273,-350.249,-348.228,-348.113,-348.197,-347.632,-347.377,-346.946,-346.441,-345.613,-344.655,-344.943], 'y':[715.283,714.230,713.474,713.651,712.519,711.057,709.772,708.714,707.468,706.862,705.982,704.961,703.928], 'z':[-36.221,-36.445,-36.823,-36.410,-35.304,-34.842,-34.922,-35.743,-37.199,-37.864,-38.714,-39.081,-38.677], 'diam':[0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[82]': { 'x':[-405.902,-407.297,-408.848], 'y':[732.221,732.785,733.089], 'z':[-32.098,-33.094,-32.949], 'diam':[0.264,0.179,0.179] }, prefix + 'apic[130]': { 'x':[-396.161,-398.034,-397.334,-397.495], 'y':[740.635,740.416,740.900,740.822], 'z':[-35.501,-35.141,-37.336,-38.423], 'diam':[0.528,0.442,0.442,0.442] }, prefix + 'apic[94]': { 'x':[-362.285,-361.149,-359.575,-358.524,-357.804,-356.531], 'y':[721.533,721.113,720.106,719.504,718.726,719.306], 'z':[-9.374,-8.588,-8.560,-7.890,-6.945,-4.255], 'diam':[0.442,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[126]': { 'x':[-398.619,-399.738,-399.616], 'y':[742.819,744.346,745.693], 'z':[-31.263,-30.987,-30.891], 'diam':[0.528,0.349,0.349] }, prefix + 'apic[3]': { 'x':[-371.406,-372.417,-372.673], 'y':[719.126,716.462,717.133], 'z':[-51.397,-47.815,-46.593], 'diam':[1.933,1.320,1.320] }, prefix + 'apic[115]': { 'x':[-407.931,-408.319,-408.983,-409.267,-410.037,-410.232], 'y':[734.348,734.773,734.294,733.803,733.106,731.915], 'z':[-37.540,-38.974,-40.124,-41.483,-42.736,-43.652], 'diam':[0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[108]': { 'x':[-389.321,-389.530,-389.118,-388.421], 'y':[727.188,727.856,726.793,727.252], 'z':[-42.050,-40.572,-39.254,-38.429], 'diam':[0.349,0.264,0.264,0.264] }, prefix + 'apic[109]': { 'x':[-387.519,-387.667,-387.601,-385.286,-384.275,-384.196,-383.470], 'y':[726.008,723.804,722.659,723.001,721.928,721.093,720.237], 'z':[-43.616,-41.851,-41.171,-41.428,-41.689,-41.134,-40.508], 'diam':[0.442,0.179,0.179,0.179,0.179,0.179,0.179] }, prefix + 'apic[31]': { 'x':[-371.023,-369.996,-368.275,-366.578,-364.028,-362.378,-360.430,-359.537,-358.501,-357.324,-355.998,-354.672,-353.303,-352.256,-351.262,-349.685,-348.048,-346.503,-345.326,-344.393,-342.099,-340.425,-339.322,-338.832,-338.595,-338.475], 'y':[715.203,715.492,714.918,714.227,713.160,713.006,712.710,712.563,711.978,711.327,710.644,709.959,709.768,709.245,708.781,708.300,707.690,706.771,706.252,706.123,705.165,705.637,706.128,706.994,707.596,708.870], 'z':[-34.276,-32.378,-31.056,-30.040,-28.583,-27.587,-26.725,-25.688,-25.449,-25.181,-24.752,-24.325,-24.147,-23.752,-23.472,-23.214,-22.729,-22.822,-22.693,-21.846,-20.846,-19.484,-17.307,-16.548,-15.746,-14.759], 'diam':[0.877,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'dend[4]': { 'x':[-300.796,-303.420,-304.396,-304.639,-304.904,-305.925,-307.246,-308.656,-311.137,-312.165,-313.188,-314.124,-314.766,-315.566,-315.748,-315.600,-315.493,-315.699,-315.748,-316.649], 'y':[716.093,710.231,710.087,709.975,710.842,711.041,711.141,711.319,711.187,711.050,711.441,711.362,711.243,711.238,711.308,712.082,712.817,713.528,714.129,714.484], 'z':[-93.880,-94.683,-95.573,-96.661,-98.055,-98.288,-97.644,-97.725,-98.699,-99.365,-99.730,-100.270,-101.097,-102.895,-104.329,-105.392,-106.339,-107.942,-109.158,-111.225], 'diam':[2.639,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056,1.056] }, prefix + 'apic[77]': { 'x':[-385.814,-387.864,-388.670,-390.076,-391.455,-392.138,-394.062,-395.158,-395.490,-396.204,-395.997,-397.187,-398.152], 'y':[746.839,748.160,748.352,749.396,750.519,751.189,752.030,752.532,753.696,754.445,755.114,756.660,757.438], 'z':[9.799,9.776,8.974,9.268,9.705,9.326,9.728,10.287,10.139,10.241,8.948,8.536,7.960], 'diam':[0.528,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[42]': { 'x':[-366.165,-365.089], 'y':[732.626,732.271], 'z':[-4.049,-3.214], 'diam':[0.349,0.349] }, prefix + 'apic[104]': { 'x':[-387.519,-388.274,-389.321], 'y':[726.008,726.607,727.188], 'z':[-43.616,-43.183,-42.050], 'diam':[0.442,0.264,0.349] }, prefix + 'apic[118]': { 'x':[-382.274,-384.573,-386.892,-388.468,-390.228], 'y':[727.857,729.727,731.663,733.064,733.473], 'z':[-51.928,-50.990,-49.939,-49.003,-48.183], 'diam':[0.877,1.056,0.792,0.792,0.792] }, prefix + 'apic[16]': { 'x':[-364.098,-365.222,-365.893,-365.640,-365.187,-364.924,-364.947,-364.845,-365.211,-366.166,-366.718,-367.281], 'y':[717.234,718.621,718.444,718.480,718.203,718.504,718.257,718.524,718.969,719.106,720.415,721.020], 'z':[-39.614,-38.003,-36.096,-34.491,-33.549,-32.212,-31.174,-30.159,-29.187,-27.900,-26.029,-25.451], 'diam':[0.706,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'dend[0]': { 'x':[-307.800,-307.179,-306.302,-306.083,-305.433,-305.160,-305.222,-304.997,-304.725,-304.760,-304.916,-304.505,-304.196,-305.303,-305.149,-305.921,-306.550,-306.430,-305.491,-305.073,-304.928,-304.692,-303.934,-303.942,-303.311,-302.670,-302.124,-301.481,-303.920,-304.030,-305.719,-306.337,-306.162,-305.845,-305.569,-305.424], 'y':[701.708,699.574,698.042,695.047,693.418,691.963,690.876,689.630,688.650,686.805,684.562,683.449,682.118,681.327,680.556,679.886,679.065,677.874,676.568,675.648,674.719,673.539,672.196,670.924,669.433,668.320,666.684,665.968,663.779,662.632,662.993,662.763,661.298,660.494,658.850,657.846], 'z':[-88.086,-88.520,-88.244,-87.580,-87.601,-87.742,-88.323,-88.410,-88.532,-88.895,-89.767,-88.696,-87.877,-87.823,-86.974,-87.010,-87.310,-87.318,-86.801,-86.787,-87.166,-87.545,-87.312,-88.116,-88.144,-87.922,-88.616,-89.352,-87.629,-86.651,-86.348,-87.263,-86.915,-86.321,-86.107,-86.353], 'diam':[2.111,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.528,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706,0.706] }, prefix + 'apic[30]': { 'x':[-365.121,-366.309,-367.132,-368.091,-368.656,-369.181,-369.119,-370.042,-370.639,-371.795,-373.048,-374.080,-374.673,-375.869,-377.759,-378.720], 'y':[711.058,711.498,712.628,712.844,713.499,713.697,713.946,714.720,715.024,715.585,715.645,716.135,716.893,718.224,718.344,718.231], 'z':[-31.344,-29.195,-27.424,-26.412,-25.076,-23.402,-22.212,-20.551,-19.677,-19.827,-19.521,-18.862,-17.477,-15.663,-14.487,-14.134], 'diam':[0.528,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085,0.085] }, prefix + 'apic[24]': { 'x':[-359.839,-357.861,-356.382,-355.325,-354.069,-352.798,-350.928,-349.584,-348.536,-347.195,-346.434,-346.325,-344.670,-343.459,-341.726,-340.545,-338.510,-337.481], 'y':[708.648,707.673,707.210,706.873,707.477,707.517,706.996,706.426,705.919,705.026,703.478,702.475,702.192,701.844,701.207,700.881,700.126,699.833], 'z':[-26.957,-26.368,-24.825,-23.813,-23.258,-22.834,-22.217,-22.092,-22.306,-22.820,-22.635,-22.279,-23.122,-23.755,-23.955,-24.418,-25.199,-25.666], 'diam':[0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[26]': { 'x':[-362.344,-361.044,-359.445,-359.718,-358.479,-357.623,-356.858], 'y':[708.536,707.290,707.408,706.088,704.423,703.564,702.880], 'z':[-29.530,-30.521,-31.256,-30.925,-29.946,-29.593,-29.899], 'diam':[0.528,0.442,0.442,0.442,0.442,0.442,0.442] }, prefix + 'apic[11]': { 'x':[-362.553,-360.713,-359.161,-358.146,-357.358,-357.306], 'y':[717.930,718.424,718.829,718.997,719.890,721.905], 'z':[-39.618,-38.090,-37.388,-35.363,-33.925,-32.611], 'diam':[0.442,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[25]': { 'x':[-359.839,-362.730,-363.058], 'y':[708.648,709.793,712.303], 'z':[-26.957,-27.056,-28.228], 'diam':[0.264,0.264,0.264] }, prefix + 'apic[76]': { 'x':[-385.814,-385.050,-384.423,-384.739,-384.753,-384.541,-384.017,-382.640,-382.233,-381.434,-381.072,-380.494,-379.211,-378.434,-377.220,-375.562,-373.409,-371.705,-370.298], 'y':[746.839,746.885,746.938,747.673,747.939,749.302,750.256,751.094,751.909,752.912,753.445,754.150,754.104,754.153,754.170,754.718,755.134,755.118,755.149], 'z':[9.799,11.124,12.899,14.198,15.296,16.674,19.393,23.645,25.377,27.728,29.310,30.742,32.057,32.775,34.152,35.366,37.665,38.784,39.721], 'diam':[0.528,0.442,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349,0.349] }, prefix + 'apic[85]': { 'x':[-399.225,-398.068,-397.897,-397.019], 'y':[733.084,734.722,735.526,736.193], 'z':[-25.820,-24.604,-23.279,-22.718], 'diam':[0.349,0.264,0.264,0.264] }, prefix + 'apic[12]': { 'x':[-357.306,-355.747,-354.298,-352.999,-351.725,-350.264,-349.325], 'y':[721.905,721.142,720.205,720.362,720.262,719.496,719.230], 'z':[-32.611,-31.972,-32.145,-32.009,-31.451,-30.993,-30.168], 'diam':[0.349,0.264,0.264,0.264,0.264,0.264,0.264] }, prefix + 'apic[98]': { 'x':[-365.583,-367.074,-369.466,-371.117,-372.070,-372.910,-375.096,-374.840,-373.944], 'y':[722.216,723.660,724.526,725.943,727.492,728.858,730.465,731.599,732.184], 'z':[-12.958,-11.771,-10.673,-9.816,-9.388,-9.066,-9.542,-9.288,-8.601], 'diam':[0.528,0.442,0.442,0.442,0.349,0.349,0.264,0.264,0.264] }, prefix + 'apic[17]': { 'x':[-372.673,-373.356,-374.241,-373.789,-372.972,-373.175,-374.024,-374.024], 'y':[717.133,718.444,718.162,717.255,715.986,714.858,714.745,715.198], 'z':[-46.593,-44.449,-42.837,-41.843,-42.279,-40.911,-40.045,-38.925], 'diam':[1.320,0.877,0.877,0.877,0.877,0.877,0.877,0.877] }, }
true
true
f725a28db4c34f0091289d14f2db993acdf9d82d
9,405
py
Python
core/addons/api/__init__.py
photos-network/core
dae64af83dccfa37fc0923370072a360da941c28
[ "Apache-2.0" ]
4
2020-12-30T12:48:46.000Z
2022-03-29T17:44:00.000Z
core/addons/api/__init__.py
photos-network/core
dae64af83dccfa37fc0923370072a360da941c28
[ "Apache-2.0" ]
null
null
null
core/addons/api/__init__.py
photos-network/core
dae64af83dccfa37fc0923370072a360da941c28
[ "Apache-2.0" ]
2
2021-01-24T19:13:53.000Z
2021-11-02T16:43:25.000Z
"""REST API implementation.""" import json import logging import os import pathlib from datetime import datetime from aiohttp import web from core.addons.api.dto.details import Details from core.addons.api.dto.location import Location from core.addons.api.dto.photo import PhotoDetailsResponse, PhotoEncoder, PhotoResponse from core.addons.api.dto.photo_response import PhotosResponse from core.base import Session from core.core import ApplicationCore from core.persistency.dto.photo import Photo from core.webserver.request import KEY_USER_ID, RequestView from core.webserver.status import HTTP_CREATED, HTTP_OK _LOGGER = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG) async def async_setup(core: ApplicationCore, config: dict) -> bool: """Set up addon to core application.""" if config is not None and "cors" in config: is_cors_enabled = config["cors"] else: is_cors_enabled = False _LOGGER.debug(f"enable cors: {is_cors_enabled}") core.http.register_request(APIStatusView()) core.http.register_request(PhotosView()) core.http.register_request(PhotoDetailsView()) core.http.register_request(PhotoView()) core.http.register_request(AlbumView()) return True class APIStatusView(RequestView): """View to handle Status requests.""" requires_auth = False url = "/api" name = "api:status" async def get(self, core: ApplicationCore, request: web.Request): """Retrieve if API is running.""" return self.json_message("API running.") async def head(self, core: ApplicationCore, request: web.Request): """Retrieve if API is running.""" return self.json_message("API running.") class PhotosView(RequestView): """View to handle photos requests.""" url = "/api/photos" name = "api:photo" async def get(self, core: ApplicationCore, request: web.Request) -> web.Response: """Get a list of all photo resources.""" _LOGGER.debug("GET /api/photos") await core.authentication.check_permission(request, "library:read") user_id = await core.http.get_user_id(request) if user_id is None: raise web.HTTPForbidden() limit = 50 if "limit" in request.query: limit = int(request.query["limit"]) offset = 0 if "offset" in request.query: offset = int(request.query["offset"]) _LOGGER.debug( f"read {limit} photos for user_id {user_id} beginning with {offset}" ) user_photos = await core.storage.read_photos(user_id, offset, limit) results = [] _LOGGER.debug(f"found {len(user_photos)} photos") for photo in user_photos: results.append( PhotoResponse( id=photo.uuid, name=photo.filename, image_url=f"{core.config.external_url}:{core.config.port}/api/file/{photo.uuid}", date_added=photo.date_added, date_taken=photo.date_taken, ) ) response = PhotosResponse( offset=offset, limit=limit, size=len(results), results=results ) return web.Response( text=json.dumps(response, cls=PhotoEncoder), content_type="application/json" ) class PhotoDetailsView(RequestView): """View to handle single photo requests.""" url = "/api/photo/{entity_id}" name = "api:photo" async def get( self, core: ApplicationCore, request: web.Request, entity_id: str ) -> web.Response: """Return an entity.""" _LOGGER.debug(f"GET /api/photo/{entity_id}") # TODO: add user_id to check if user has access to image photo = await core.storage.read_photo(entity_id) if photo is None: raise web.HTTPNotFound # photo owner # TODO: get first-/lastname of owner # owner = await core.authentication _LOGGER.debug(f"photo {photo.uuid}") file = os.path.join(photo.directory, photo.filename) _LOGGER.debug(f"get additional data for {file} / {os.path.exists(file)}") # photo creation time fname = pathlib.Path(file) mtime = datetime.fromtimestamp(fname.stat().st_mtime) ctime = datetime.fromtimestamp(fname.stat().st_ctime) # photo location location = None latitude = await core.storage.read("latitude") longitude = await core.storage.read("longitude") if latitude is not None and longitude is not None: altitude = await core.storage.read("altitude") if altitude is not None: location = Location( latitude=latitude, longitude=longitude, altitude=altitude ) else: location = Location( latitude=latitude, longitude=longitude, altitude="0.0" ) # photo tags tags = await core.storage.read("tags") result = PhotoDetailsResponse( id=photo.uuid, name=photo.filename, owner=photo.owner, created_at=ctime.isoformat(), modified_at=mtime.isoformat(), details=Details( camera="Nikon Z7", lens="Nikkor 200mm F1.8", focal_length="200", iso="400", shutter_speed="1/2000", aperture="4.0", ), tags=tags, location=location, image_url=f"{core.config.external_url}/api/file/{entity_id}", ) return web.Response( text=json.dumps(result, cls=PhotoEncoder), content_type="application/json" ) class PhotoView(RequestView): """View to handle photo file requests.""" requires_auth = True url = "/api/file/{entity_id}" name = "api:file" async def get( self, core: ApplicationCore, request: web.Request, entity_id: str ) -> web.Response: """Return an entity.""" _LOGGER.debug(f"GET /api/file/{entity_id}") # TODO: parse params max-with / max-height =wmax-width-hmax-height (=w2048-h1024) # -wmax-width (preserving the aspect ratio) # -hmax-height (preserving the aspect ratio) # -c crop images to max-width / max-height # -d remove exif data result = Session.query(Photo).filter(Photo.uuid == entity_id).first() if result: file = os.path.join(result.directory, result.filename) if os.path.exists(os.path.join(file)): return web.FileResponse(path=file, status=200) else: raise web.HTTPNotFound() else: raise web.HTTPNotFound() async def post(self, core: ApplicationCore, request: web.Request) -> web.Response: """Upload new photo resource.""" user = request[KEY_USER_ID] reader = await request.multipart() field = await reader.next() assert field.name == "data" original_filename = field.filename _LOGGER.warning(f"request: {original_filename}") # TODO: get storage directory for user path = os.path.join(f"./data/users/{user}/", original_filename) if os.path.exists(path): # TODO: handle filename already exists _LOGGER.warning(f"file already exists! {path}") filename = original_filename size = 0 with open(os.path.join(f"./data/users/{user}/", filename), "wb") as f: while True: chunk = await field.read_chunk() # 8192 bytes by default. if not chunk: break size += len(chunk) f.write(chunk) _LOGGER.error(f"added {filename} to data directory of {user}.") # TODO: add new filepath to database # TODO: return unique_id from database new_entity_id = 123456 new_entity_created = True status_code = HTTP_CREATED if new_entity_created else HTTP_OK resp = self.json_message( f"File successfully added with ID: {new_entity_id}", status_code ) resp.headers.add("Location", f"/api/photo/{new_entity_id}") return resp async def delete(self, core: ApplicationCore, request: web.Request, entity_id: str): """Delete an entity.""" _LOGGER.debug(f"DELETE /api/file/{entity_id}") # TODO: delete entity return self.json_message(f"return DELETE {entity_id}") class AlbumsView(RequestView): """View to handle albums requests.""" requires_auth = False url = "/api/album/" name = "api:albums" async def get(self, request: web.Request) -> web.Response: """Retrieve if API is running.""" return self.json_message("return Albums") class AlbumView(RequestView): """View to handle single album requests.""" requires_auth = False url = "/api/album/{entity_id}" name = "api:album" async def get(self, request: web.Request, entity_id) -> web.Response: """Retrieve if API is running.""" return self.json_message(f"return Album {entity_id}") async def post(self, request: web.Request) -> web.Response: """Create a new album.""" return self.json_message("create a new Album")
32.543253
101
0.612547
import json import logging import os import pathlib from datetime import datetime from aiohttp import web from core.addons.api.dto.details import Details from core.addons.api.dto.location import Location from core.addons.api.dto.photo import PhotoDetailsResponse, PhotoEncoder, PhotoResponse from core.addons.api.dto.photo_response import PhotosResponse from core.base import Session from core.core import ApplicationCore from core.persistency.dto.photo import Photo from core.webserver.request import KEY_USER_ID, RequestView from core.webserver.status import HTTP_CREATED, HTTP_OK _LOGGER = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG) async def async_setup(core: ApplicationCore, config: dict) -> bool: if config is not None and "cors" in config: is_cors_enabled = config["cors"] else: is_cors_enabled = False _LOGGER.debug(f"enable cors: {is_cors_enabled}") core.http.register_request(APIStatusView()) core.http.register_request(PhotosView()) core.http.register_request(PhotoDetailsView()) core.http.register_request(PhotoView()) core.http.register_request(AlbumView()) return True class APIStatusView(RequestView): requires_auth = False url = "/api" name = "api:status" async def get(self, core: ApplicationCore, request: web.Request): return self.json_message("API running.") async def head(self, core: ApplicationCore, request: web.Request): return self.json_message("API running.") class PhotosView(RequestView): url = "/api/photos" name = "api:photo" async def get(self, core: ApplicationCore, request: web.Request) -> web.Response: _LOGGER.debug("GET /api/photos") await core.authentication.check_permission(request, "library:read") user_id = await core.http.get_user_id(request) if user_id is None: raise web.HTTPForbidden() limit = 50 if "limit" in request.query: limit = int(request.query["limit"]) offset = 0 if "offset" in request.query: offset = int(request.query["offset"]) _LOGGER.debug( f"read {limit} photos for user_id {user_id} beginning with {offset}" ) user_photos = await core.storage.read_photos(user_id, offset, limit) results = [] _LOGGER.debug(f"found {len(user_photos)} photos") for photo in user_photos: results.append( PhotoResponse( id=photo.uuid, name=photo.filename, image_url=f"{core.config.external_url}:{core.config.port}/api/file/{photo.uuid}", date_added=photo.date_added, date_taken=photo.date_taken, ) ) response = PhotosResponse( offset=offset, limit=limit, size=len(results), results=results ) return web.Response( text=json.dumps(response, cls=PhotoEncoder), content_type="application/json" ) class PhotoDetailsView(RequestView): url = "/api/photo/{entity_id}" name = "api:photo" async def get( self, core: ApplicationCore, request: web.Request, entity_id: str ) -> web.Response: _LOGGER.debug(f"GET /api/photo/{entity_id}") photo = await core.storage.read_photo(entity_id) if photo is None: raise web.HTTPNotFound _LOGGER.debug(f"photo {photo.uuid}") file = os.path.join(photo.directory, photo.filename) _LOGGER.debug(f"get additional data for {file} / {os.path.exists(file)}") fname = pathlib.Path(file) mtime = datetime.fromtimestamp(fname.stat().st_mtime) ctime = datetime.fromtimestamp(fname.stat().st_ctime) location = None latitude = await core.storage.read("latitude") longitude = await core.storage.read("longitude") if latitude is not None and longitude is not None: altitude = await core.storage.read("altitude") if altitude is not None: location = Location( latitude=latitude, longitude=longitude, altitude=altitude ) else: location = Location( latitude=latitude, longitude=longitude, altitude="0.0" ) tags = await core.storage.read("tags") result = PhotoDetailsResponse( id=photo.uuid, name=photo.filename, owner=photo.owner, created_at=ctime.isoformat(), modified_at=mtime.isoformat(), details=Details( camera="Nikon Z7", lens="Nikkor 200mm F1.8", focal_length="200", iso="400", shutter_speed="1/2000", aperture="4.0", ), tags=tags, location=location, image_url=f"{core.config.external_url}/api/file/{entity_id}", ) return web.Response( text=json.dumps(result, cls=PhotoEncoder), content_type="application/json" ) class PhotoView(RequestView): requires_auth = True url = "/api/file/{entity_id}" name = "api:file" async def get( self, core: ApplicationCore, request: web.Request, entity_id: str ) -> web.Response: _LOGGER.debug(f"GET /api/file/{entity_id}") result = Session.query(Photo).filter(Photo.uuid == entity_id).first() if result: file = os.path.join(result.directory, result.filename) if os.path.exists(os.path.join(file)): return web.FileResponse(path=file, status=200) else: raise web.HTTPNotFound() else: raise web.HTTPNotFound() async def post(self, core: ApplicationCore, request: web.Request) -> web.Response: user = request[KEY_USER_ID] reader = await request.multipart() field = await reader.next() assert field.name == "data" original_filename = field.filename _LOGGER.warning(f"request: {original_filename}") path = os.path.join(f"./data/users/{user}/", original_filename) if os.path.exists(path): _LOGGER.warning(f"file already exists! {path}") filename = original_filename size = 0 with open(os.path.join(f"./data/users/{user}/", filename), "wb") as f: while True: chunk = await field.read_chunk() if not chunk: break size += len(chunk) f.write(chunk) _LOGGER.error(f"added {filename} to data directory of {user}.") new_entity_id = 123456 new_entity_created = True status_code = HTTP_CREATED if new_entity_created else HTTP_OK resp = self.json_message( f"File successfully added with ID: {new_entity_id}", status_code ) resp.headers.add("Location", f"/api/photo/{new_entity_id}") return resp async def delete(self, core: ApplicationCore, request: web.Request, entity_id: str): _LOGGER.debug(f"DELETE /api/file/{entity_id}") return self.json_message(f"return DELETE {entity_id}") class AlbumsView(RequestView): requires_auth = False url = "/api/album/" name = "api:albums" async def get(self, request: web.Request) -> web.Response: return self.json_message("return Albums") class AlbumView(RequestView): requires_auth = False url = "/api/album/{entity_id}" name = "api:album" async def get(self, request: web.Request, entity_id) -> web.Response: return self.json_message(f"return Album {entity_id}") async def post(self, request: web.Request) -> web.Response: return self.json_message("create a new Album")
true
true
f725a39885307cc168891a50213872ddbdd21689
1,475
py
Python
_unittests/ut_module/test_code_style.py
sdpython/papierstat
f69de884c59ada30b58224dca39f2a44d92122c1
[ "MIT" ]
7
2019-03-21T09:52:31.000Z
2021-01-17T16:56:27.000Z
_unittests/ut_module/test_code_style.py
sdpython/papierstat
f69de884c59ada30b58224dca39f2a44d92122c1
[ "MIT" ]
33
2018-02-08T23:56:57.000Z
2021-02-10T23:55:43.000Z
_unittests/ut_module/test_code_style.py
sdpython/papierstat
f69de884c59ada30b58224dca39f2a44d92122c1
[ "MIT" ]
1
2021-02-11T09:16:33.000Z
2021-02-11T09:16:33.000Z
""" @brief test log(time=150s) """ import os import unittest from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import check_pep8, ExtTestCase class TestCodeStyle(ExtTestCase): """Test style.""" def test_style_src(self): thi = os.path.abspath(os.path.dirname(__file__)) src_ = os.path.normpath(os.path.join(thi, "..", "..", "src")) check_pep8(src_, fLOG=fLOG, pylint_ignore=('C0103', 'C1801', 'R0201', 'R1705', 'W0108', 'W0613', 'C0111', 'W0223', 'W0201', 'W0212', 'C0415', 'C0209'), skip=["Parameters differ from overridden 'fit' method", "Module 'numpy.random' has no 'RandomState' member", "Instance of 'SkLearnParameters' has no '", " in module 'sklearn.cluster._k_means'", "Instance of 'Struct' has no '", ]) def test_style_test(self): thi = os.path.abspath(os.path.dirname(__file__)) test = os.path.normpath(os.path.join(thi, "..", )) check_pep8(test, fLOG=fLOG, neg_pattern="temp_.*", pylint_ignore=('C0103', 'C1801', 'R0201', 'R1705', 'W0108', 'W0613', 'C0111', 'W0612', 'E0632', 'C0415', 'C0209'), skip=["Instance of 'tuple' has no ", ]) if __name__ == "__main__": unittest.main()
38.815789
88
0.520678
import os import unittest from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import check_pep8, ExtTestCase class TestCodeStyle(ExtTestCase): def test_style_src(self): thi = os.path.abspath(os.path.dirname(__file__)) src_ = os.path.normpath(os.path.join(thi, "..", "..", "src")) check_pep8(src_, fLOG=fLOG, pylint_ignore=('C0103', 'C1801', 'R0201', 'R1705', 'W0108', 'W0613', 'C0111', 'W0223', 'W0201', 'W0212', 'C0415', 'C0209'), skip=["Parameters differ from overridden 'fit' method", "Module 'numpy.random' has no 'RandomState' member", "Instance of 'SkLearnParameters' has no '", " in module 'sklearn.cluster._k_means'", "Instance of 'Struct' has no '", ]) def test_style_test(self): thi = os.path.abspath(os.path.dirname(__file__)) test = os.path.normpath(os.path.join(thi, "..", )) check_pep8(test, fLOG=fLOG, neg_pattern="temp_.*", pylint_ignore=('C0103', 'C1801', 'R0201', 'R1705', 'W0108', 'W0613', 'C0111', 'W0612', 'E0632', 'C0415', 'C0209'), skip=["Instance of 'tuple' has no ", ]) if __name__ == "__main__": unittest.main()
true
true
f725a3fd1b003a319b8f8190e60431bedbbcf49d
1,698
py
Python
src/LossFunctions/ActionCrossEntropy.py
Marcel-Rodekamp/MLP
349ac8e10679e2ec53980908c580902996a493e7
[ "MIT" ]
1
2021-06-15T09:01:09.000Z
2021-06-15T09:01:09.000Z
src/LossFunctions/ActionCrossEntropy.py
Marcel-Rodekamp/MLP
349ac8e10679e2ec53980908c580902996a493e7
[ "MIT" ]
null
null
null
src/LossFunctions/ActionCrossEntropy.py
Marcel-Rodekamp/MLP
349ac8e10679e2ec53980908c580902996a493e7
[ "MIT" ]
null
null
null
import torch class ActionCrossEntropyFunction(torch.autograd.Function): @staticmethod def forward(self,input,target,action,force = None): self.mb_size,self.dim = input.size() # save the force for backward self.force = force # get action difference action_input = torch.tensor( [action(input[i_mb,:].numpy()) for i_mb in range(self.mb_size)], dtype = input.dtype ) action_target = torch.tensor( [action(target[i_mb,:].numpy()) for i_mb in range(self.mb_size)], dtype = input.dtype ) output = action_target * action_input.log() + (1-action_target) * (1-action_input).log() self.save_for_backward(input,action_input,action_target,output) output = torch.sqrt(output.real**2+output.imag**2) # average over batch and return output = torch.mean(output) return output @staticmethod def backward(self,grad_output): input,action_input,action_target,cross_entropy = self.saved_tensors action_grad_input = -torch.tensor( [self.force(input[i_mb,:].numpy()) for i_mb in range(self.mb_size)], dtype = input.dtype ) grad = torch.unsqueeze( cross_entropy.conj()*((action_target)/(action_input) + (1-action_target)/(1-action_input)), -1 ) * action_grad_input return grad.conj(),None,None,None ActionCrossEntropyFunc = ActionCrossEntropyFunction.apply class ActionCrossEntropy(torch.nn.Module): def __init__(self,action): super(ActionCrossEntropy, self).__init__() self.action = action.eval self.force = action.force def forward(self, input, target): return ActionCrossEntropyFunc(input,target,self.action,self.force)
36.913043
148
0.689046
import torch class ActionCrossEntropyFunction(torch.autograd.Function): @staticmethod def forward(self,input,target,action,force = None): self.mb_size,self.dim = input.size() self.force = force action_input = torch.tensor( [action(input[i_mb,:].numpy()) for i_mb in range(self.mb_size)], dtype = input.dtype ) action_target = torch.tensor( [action(target[i_mb,:].numpy()) for i_mb in range(self.mb_size)], dtype = input.dtype ) output = action_target * action_input.log() + (1-action_target) * (1-action_input).log() self.save_for_backward(input,action_input,action_target,output) output = torch.sqrt(output.real**2+output.imag**2) output = torch.mean(output) return output @staticmethod def backward(self,grad_output): input,action_input,action_target,cross_entropy = self.saved_tensors action_grad_input = -torch.tensor( [self.force(input[i_mb,:].numpy()) for i_mb in range(self.mb_size)], dtype = input.dtype ) grad = torch.unsqueeze( cross_entropy.conj()*((action_target)/(action_input) + (1-action_target)/(1-action_input)), -1 ) * action_grad_input return grad.conj(),None,None,None ActionCrossEntropyFunc = ActionCrossEntropyFunction.apply class ActionCrossEntropy(torch.nn.Module): def __init__(self,action): super(ActionCrossEntropy, self).__init__() self.action = action.eval self.force = action.force def forward(self, input, target): return ActionCrossEntropyFunc(input,target,self.action,self.force)
true
true
f725a5330ea476bf3d80b1dcb996e9b5875e2f37
918
py
Python
setup.py
NgHoangDat/lescode
f19d8f2ca47aee947d2b2d88e5008ce4a58faeb6
[ "MIT" ]
1
2020-06-17T03:33:58.000Z
2020-06-17T03:33:58.000Z
setup.py
NgHoangDat/lescode
f19d8f2ca47aee947d2b2d88e5008ce4a58faeb6
[ "MIT" ]
null
null
null
setup.py
NgHoangDat/lescode
f19d8f2ca47aee947d2b2d88e5008ce4a58faeb6
[ "MIT" ]
null
null
null
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() __VERSION__ = "0.2.10" setuptools.setup( name="lescode", packages=setuptools.find_packages(), version=__VERSION__, author="nghoangdat", author_email="18.hoang.dat.12@gmail.com", description="quiver", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/NgHoangDat/lescode.git", download_url=f"https://github.com/NgHoangDat/lescode/archive/v{__VERSION__}.tar.gz", classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.6', install_requires=[ 'dataclasses; python_version=="3.6"', 'msgpack', 'python-dateutil', 'pyyaml', 'toolz' ] )
27
88
0.641612
import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() __VERSION__ = "0.2.10" setuptools.setup( name="lescode", packages=setuptools.find_packages(), version=__VERSION__, author="nghoangdat", author_email="18.hoang.dat.12@gmail.com", description="quiver", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/NgHoangDat/lescode.git", download_url=f"https://github.com/NgHoangDat/lescode/archive/v{__VERSION__}.tar.gz", classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.6', install_requires=[ 'dataclasses; python_version=="3.6"', 'msgpack', 'python-dateutil', 'pyyaml', 'toolz' ] )
true
true
f725a7c0a43b428ee68f9ed16d64cc59f6ac188b
11,328
py
Python
haystack/utils/squad_data.py
ArzelaAscoIi/haystack
be8f50c9e3de4e264b3f345f5f4b9c9ec518ed08
[ "Apache-2.0" ]
1
2022-02-15T04:32:41.000Z
2022-02-15T04:32:41.000Z
haystack/utils/squad_data.py
ArzelaAscoIi/haystack
be8f50c9e3de4e264b3f345f5f4b9c9ec518ed08
[ "Apache-2.0" ]
null
null
null
haystack/utils/squad_data.py
ArzelaAscoIi/haystack
be8f50c9e3de4e264b3f345f5f4b9c9ec518ed08
[ "Apache-2.0" ]
null
null
null
from typing import List import logging import json import random import pandas as pd from tqdm import tqdm from haystack.schema import Document, Label from haystack.modeling.data_handler.processor import _read_squad_file logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) tqdm.pandas() COLUMN_NAMES = ["title", "context", "question", "id", "answer_text", "answer_start", "is_impossible"] class SquadData: """ This class is designed to manipulate data that is in SQuAD format """ def __init__(self, squad_data): """ :param squad_data: SQuAD format data, either as a dict with a `data` key, or just a list of SQuAD documents """ if type(squad_data) == dict: self.version = squad_data.get("version") self.data = squad_data["data"] elif type(squad_data) == list: self.version = None self.data = squad_data self.df = self.to_df(self.data) def merge_from_file(self, filename: str): """Merge the contents of a SQuAD format json file with the data stored in this object""" new_data = json.load(open(filename))["data"] self.merge(new_data) def merge(self, new_data: List): """ Merge data in SQuAD format with the data stored in this object :param new_data: A list of SQuAD document data """ df_new = self.to_df(new_data) self.df = pd.concat([df_new, self.df]) self.data = self.df_to_data(self.df) @classmethod def from_file(cls, filename: str): """ Create a SquadData object by providing the name of a SQuAD format json file """ data = json.load(open(filename)) return cls(data) def save(self, filename: str): """ Write the data stored in this object to a json file. """ with open(filename, "w") as f: squad_data = {"version": self.version, "data": self.data} json.dump(squad_data, f, indent=2) def to_dpr_dataset(self): raise NotImplementedError( "SquadData.to_dpr_dataset() not yet implemented. " "For now, have a look at the script at haystack/retriever/squad_to_dpr.py" ) def to_document_objs(self): """ Export all paragraphs stored in this object to haystack.Document objects. """ df_docs = self.df[["title", "context"]] df_docs = df_docs.drop_duplicates() record_dicts = df_docs.to_dict("records") documents = [Document(content=rd["context"], id=rd["title"]) for rd in record_dicts] return documents # TODO refactor to new Label objects def to_label_objs(self): """ Export all labels stored in this object to haystack.Label objects. """ df_labels = self.df[["id", "question", "answer_text", "answer_start"]] record_dicts = df_labels.to_dict("records") labels = [ Label( query=rd["question"], answer=rd["answer_text"], is_correct_answer=True, is_correct_document=True, id=rd["id"], origin=rd.get("origin", "SquadData tool"), document_id=rd.get("document_id", None), ) for rd in record_dicts ] return labels @staticmethod def to_df(data): """Convert a list of SQuAD document dictionaries into a pandas dataframe (each row is one annotation)""" flat = [] for document in data: title = document["title"] for paragraph in document["paragraphs"]: context = paragraph["context"] for question in paragraph["qas"]: q = question["question"] id = question["id"] is_impossible = question["is_impossible"] # For no_answer samples if len(question["answers"]) == 0: flat.append( { "title": title, "context": context, "question": q, "id": id, "answer_text": "", "answer_start": None, "is_impossible": is_impossible, } ) # For span answer samples else: for answer in question["answers"]: answer_text = answer["text"] answer_start = answer["answer_start"] flat.append( { "title": title, "context": context, "question": q, "id": id, "answer_text": answer_text, "answer_start": answer_start, "is_impossible": is_impossible, } ) df = pd.DataFrame.from_records(flat) return df def count(self, unit="questions"): """ Count the samples in the data. Choose from unit = "paragraphs", "questions", "answers", "no_answers", "span_answers" """ c = 0 for document in self.data: for paragraph in document["paragraphs"]: if unit == "paragraphs": c += 1 for question in paragraph["qas"]: if unit == "questions": c += 1 # Count no_answers if len(question["answers"]) == 0: if unit in ["answers", "no_answers"]: c += 1 # Count span answers else: for answer in question["answers"]: if unit in ["answers", "span_answers"]: c += 1 return c @classmethod def df_to_data(cls, df): """ Convert a dataframe into SQuAD format data (list of SQuAD document dictionaries). """ logger.info("Converting data frame to squad format data") # Aggregate the answers of each question logger.info("Aggregating the answers of each question") df_grouped_answers = df.groupby(["title", "context", "question", "id", "is_impossible"]) df_aggregated_answers = ( df[["title", "context", "question", "id", "is_impossible"]].drop_duplicates().reset_index() ) answers = df_grouped_answers.progress_apply(cls._aggregate_answers).rename("answers") answers = pd.DataFrame(answers).reset_index() df_aggregated_answers = pd.merge(df_aggregated_answers, answers) # Aggregate the questions of each passage logger.info("Aggregating the questions of each paragraphs of each document") df_grouped_questions = df_aggregated_answers.groupby(["title", "context"]) df_aggregated_questions = df[["title", "context"]].drop_duplicates().reset_index() questions = df_grouped_questions.progress_apply(cls._aggregate_questions).rename("qas") questions = pd.DataFrame(questions).reset_index() df_aggregated_questions = pd.merge(df_aggregated_questions, questions) logger.info("Aggregating the paragraphs of each document") df_grouped_paragraphs = df_aggregated_questions.groupby(["title"]) df_aggregated_paragraphs = df[["title"]].drop_duplicates().reset_index() paragraphs = df_grouped_paragraphs.progress_apply(cls._aggregate_passages).rename("paragraphs") paragraphs = pd.DataFrame(paragraphs).reset_index() df_aggregated_paragraphs = pd.merge(df_aggregated_paragraphs, paragraphs) df_aggregated_paragraphs = df_aggregated_paragraphs[["title", "paragraphs"]] ret = df_aggregated_paragraphs.to_dict("records") return ret @staticmethod def _aggregate_passages(x): x = x[["context", "qas"]] ret = x.to_dict("records") return ret @staticmethod def _aggregate_questions(x): x = x[["question", "id", "answers", "is_impossible"]] ret = x.to_dict("records") return ret @staticmethod def _aggregate_answers(x): x = x[["answer_text", "answer_start"]] x = x.rename(columns={"answer_text": "text"}) # Span anwser try: x["answer_start"] = x["answer_start"].astype(int) ret = x.to_dict("records") # No answer except ValueError: ret = [] return ret def set_data(self, data): self.data = data self.df = self.to_df(data) def sample_questions(self, n): """ Return a sample of n questions in SQuAD format (list of SQuAD document dictionaries) Note, that if the same question is asked on multiple different passages, this fn treats that as a single question """ all_questions = self.get_all_questions() sampled_questions = random.sample(all_questions, n) df_sampled = self.df[self.df["question"].isin(sampled_questions)] return self.df_to_data(df_sampled) def get_all_paragraphs(self): """ Return all paragraph strings. """ return self.df["context"].unique().tolist() def get_all_questions(self): """ Return all question strings. Note that if the same question appears for different paragraphs, it will be returned multiple times by this fn """ df_questions = self.df[["title", "context", "question"]] df_questions = df_questions.drop_duplicates() questions = df_questions["question"].tolist() return questions def get_all_document_titles(self): """Return all document title strings""" return self.df["title"].unique().tolist() if __name__ == "__main__": # Download the SQuAD dataset if it isn't at target directory _read_squad_file("../data/squad20/train-v2.0.json") filename1 = "../data/squad20/train-v2.0.json" filename2 = "../data/squad20/dev-v2.0.json" # Load file1 and take a sample of 10000 questions sd = SquadData.from_file(filename1) sample1 = sd.sample_questions(n=10000) # Set sd to now contain the sample of 10000 questions sd.set_data(sample1) # Merge sd with file2 and take a sample of 100 questions sd.merge_from_file(filename2) sample2 = sd.sample_questions(n=100) sd.set_data(sample2) # Save this sample of 100 sd.save("../data/squad20/sample.json") paragraphs = sd.get_all_paragraphs() questions = sd.get_all_questions() titles = sd.get_all_document_titles() documents = sd.to_document_objs() labels = sd.to_label_objs() n_qs = sd.count(unit="questions") n_as = sd.count(unit="no_answers") n_ps = sd.count(unit="paragraphs") print(n_qs) print(n_as) print(n_ps)
36.779221
124
0.566561
from typing import List import logging import json import random import pandas as pd from tqdm import tqdm from haystack.schema import Document, Label from haystack.modeling.data_handler.processor import _read_squad_file logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) tqdm.pandas() COLUMN_NAMES = ["title", "context", "question", "id", "answer_text", "answer_start", "is_impossible"] class SquadData: def __init__(self, squad_data): if type(squad_data) == dict: self.version = squad_data.get("version") self.data = squad_data["data"] elif type(squad_data) == list: self.version = None self.data = squad_data self.df = self.to_df(self.data) def merge_from_file(self, filename: str): new_data = json.load(open(filename))["data"] self.merge(new_data) def merge(self, new_data: List): df_new = self.to_df(new_data) self.df = pd.concat([df_new, self.df]) self.data = self.df_to_data(self.df) @classmethod def from_file(cls, filename: str): data = json.load(open(filename)) return cls(data) def save(self, filename: str): with open(filename, "w") as f: squad_data = {"version": self.version, "data": self.data} json.dump(squad_data, f, indent=2) def to_dpr_dataset(self): raise NotImplementedError( "SquadData.to_dpr_dataset() not yet implemented. " "For now, have a look at the script at haystack/retriever/squad_to_dpr.py" ) def to_document_objs(self): df_docs = self.df[["title", "context"]] df_docs = df_docs.drop_duplicates() record_dicts = df_docs.to_dict("records") documents = [Document(content=rd["context"], id=rd["title"]) for rd in record_dicts] return documents def to_label_objs(self): df_labels = self.df[["id", "question", "answer_text", "answer_start"]] record_dicts = df_labels.to_dict("records") labels = [ Label( query=rd["question"], answer=rd["answer_text"], is_correct_answer=True, is_correct_document=True, id=rd["id"], origin=rd.get("origin", "SquadData tool"), document_id=rd.get("document_id", None), ) for rd in record_dicts ] return labels @staticmethod def to_df(data): flat = [] for document in data: title = document["title"] for paragraph in document["paragraphs"]: context = paragraph["context"] for question in paragraph["qas"]: q = question["question"] id = question["id"] is_impossible = question["is_impossible"] if len(question["answers"]) == 0: flat.append( { "title": title, "context": context, "question": q, "id": id, "answer_text": "", "answer_start": None, "is_impossible": is_impossible, } ) else: for answer in question["answers"]: answer_text = answer["text"] answer_start = answer["answer_start"] flat.append( { "title": title, "context": context, "question": q, "id": id, "answer_text": answer_text, "answer_start": answer_start, "is_impossible": is_impossible, } ) df = pd.DataFrame.from_records(flat) return df def count(self, unit="questions"): c = 0 for document in self.data: for paragraph in document["paragraphs"]: if unit == "paragraphs": c += 1 for question in paragraph["qas"]: if unit == "questions": c += 1 if len(question["answers"]) == 0: if unit in ["answers", "no_answers"]: c += 1 else: for answer in question["answers"]: if unit in ["answers", "span_answers"]: c += 1 return c @classmethod def df_to_data(cls, df): logger.info("Converting data frame to squad format data") logger.info("Aggregating the answers of each question") df_grouped_answers = df.groupby(["title", "context", "question", "id", "is_impossible"]) df_aggregated_answers = ( df[["title", "context", "question", "id", "is_impossible"]].drop_duplicates().reset_index() ) answers = df_grouped_answers.progress_apply(cls._aggregate_answers).rename("answers") answers = pd.DataFrame(answers).reset_index() df_aggregated_answers = pd.merge(df_aggregated_answers, answers) logger.info("Aggregating the questions of each paragraphs of each document") df_grouped_questions = df_aggregated_answers.groupby(["title", "context"]) df_aggregated_questions = df[["title", "context"]].drop_duplicates().reset_index() questions = df_grouped_questions.progress_apply(cls._aggregate_questions).rename("qas") questions = pd.DataFrame(questions).reset_index() df_aggregated_questions = pd.merge(df_aggregated_questions, questions) logger.info("Aggregating the paragraphs of each document") df_grouped_paragraphs = df_aggregated_questions.groupby(["title"]) df_aggregated_paragraphs = df[["title"]].drop_duplicates().reset_index() paragraphs = df_grouped_paragraphs.progress_apply(cls._aggregate_passages).rename("paragraphs") paragraphs = pd.DataFrame(paragraphs).reset_index() df_aggregated_paragraphs = pd.merge(df_aggregated_paragraphs, paragraphs) df_aggregated_paragraphs = df_aggregated_paragraphs[["title", "paragraphs"]] ret = df_aggregated_paragraphs.to_dict("records") return ret @staticmethod def _aggregate_passages(x): x = x[["context", "qas"]] ret = x.to_dict("records") return ret @staticmethod def _aggregate_questions(x): x = x[["question", "id", "answers", "is_impossible"]] ret = x.to_dict("records") return ret @staticmethod def _aggregate_answers(x): x = x[["answer_text", "answer_start"]] x = x.rename(columns={"answer_text": "text"}) try: x["answer_start"] = x["answer_start"].astype(int) ret = x.to_dict("records") except ValueError: ret = [] return ret def set_data(self, data): self.data = data self.df = self.to_df(data) def sample_questions(self, n): all_questions = self.get_all_questions() sampled_questions = random.sample(all_questions, n) df_sampled = self.df[self.df["question"].isin(sampled_questions)] return self.df_to_data(df_sampled) def get_all_paragraphs(self): return self.df["context"].unique().tolist() def get_all_questions(self): df_questions = self.df[["title", "context", "question"]] df_questions = df_questions.drop_duplicates() questions = df_questions["question"].tolist() return questions def get_all_document_titles(self): return self.df["title"].unique().tolist() if __name__ == "__main__": _read_squad_file("../data/squad20/train-v2.0.json") filename1 = "../data/squad20/train-v2.0.json" filename2 = "../data/squad20/dev-v2.0.json" # Load file1 and take a sample of 10000 questions sd = SquadData.from_file(filename1) sample1 = sd.sample_questions(n=10000) # Set sd to now contain the sample of 10000 questions sd.set_data(sample1) # Merge sd with file2 and take a sample of 100 questions sd.merge_from_file(filename2) sample2 = sd.sample_questions(n=100) sd.set_data(sample2) # Save this sample of 100 sd.save("../data/squad20/sample.json") paragraphs = sd.get_all_paragraphs() questions = sd.get_all_questions() titles = sd.get_all_document_titles() documents = sd.to_document_objs() labels = sd.to_label_objs() n_qs = sd.count(unit="questions") n_as = sd.count(unit="no_answers") n_ps = sd.count(unit="paragraphs") print(n_qs) print(n_as) print(n_ps)
true
true
f725a83f718d805f89f9a0c04adb8de750d17bf3
7,720
py
Python
tests/test_settings.py
zbyte64/django-dockit
8d00a46cb0b6237de622fcb6816067078106a0c4
[ "BSD-3-Clause" ]
5
2015-02-25T17:01:48.000Z
2021-06-03T07:46:47.000Z
tests/test_settings.py
zbyte64/django-dockit
8d00a46cb0b6237de622fcb6816067078106a0c4
[ "BSD-3-Clause" ]
1
2015-03-11T15:19:55.000Z
2015-04-13T04:14:24.000Z
tests/test_settings.py
zbyte64/django-dockit
8d00a46cb0b6237de622fcb6816067078106a0c4
[ "BSD-3-Clause" ]
null
null
null
# Django settings for {{ project_name }} project. import os PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': ':memory:', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '/media/' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # URL prefix for admin static files -- CSS, JavaScript and images. # Make sure to use a trailing slash. # Examples: "http://foo.com/static/admin/", "/static/admin/". ADMIN_MEDIA_PREFIX = '/static/admin/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'NOTASECRET' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'tests.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'dockit', 'dockit.backends.djangodocument', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', ] DOCKIT_BACKENDS = { 'default': { 'ENGINE': 'dockit.backends.djangodocument.backend.ModelDocumentStorage', }, 'djangodocument': { 'ENGINE': 'dockit.backends.djangodocument.backend.ModelDocumentStorage', }, } DOCKIT_INDEX_BACKENDS = { 'default': { 'ENGINE': 'dockit.backends.djangodocument.backend.ModelIndexStorage', }, 'djangodocument': { 'ENGINE': 'dockit.backends.djangodocument.backend.ModelIndexStorage', }, } try: import pymongo except ImportError: pass else: from pymongo.errors import ConnectionFailure try: pymongo.MongoClient('localhost', 27017) except ConnectionFailure: pass else: INSTALLED_APPS.append('dockit.backends.mongo') DOCKIT_BACKENDS['mongo'] = { 'ENGINE':'dockit.backends.mongo.backend.MongoDocumentStorage', 'HOST':'localhost', 'DB':'testdb', 'PORT': 27017, } DOCKIT_INDEX_BACKENDS['mongo'] = { 'ENGINE':'dockit.backends.mongo.backend.MongoIndexStorage', 'HOST':'localhost', 'DB':'testdb', 'PORT': 27017, } if 'TRAVIS' in os.environ: DOCKIT_BACKENDS['mongo'] = {'ENGINE':'dockit.backends.mongo.backend.MongoDocumentStorage', 'USER':'travis', 'PASSWORD':'test', 'DB':'mydb_test', 'HOST':'127.0.0.1', 'PORT':27017,} DOCKIT_INDEX_BACKENDS['mongo'] = {'ENGINE':'dockit.backends.mongo.backend.MongoIndexStorage', 'USER':'travis', 'PASSWORD':'test', 'DB':'mydb_test', 'HOST':'127.0.0.1', 'PORT':27017,} if 'dockit.backends.mongo' not in INSTALLED_APPS: INSTALLED_APPS.append('dockit.backends.mongo') if os.environ.get('TASK_BACKEND', None) == 'celery': DOCKIT_INDEX_BACKENDS['djangodocument']['INDEX_TASKS'] = 'dockit.backends.djangodocument.tasks.CeleryIndexTasks' INSTALLED_APPS += ["djcelery"] CELERY_ALWAYS_EAGER = True import djcelery djcelery.setup_loader() if os.environ.get('TASK_BACKEND', None) == 'ztask': DOCKIT_INDEX_BACKENDS['djangodocument']['INDEX_TASKS'] = 'dockit.backends.djangodocument.tasks.ZTaskIndexTasks' INSTALLED_APPS += ["django_ztask"] ZTASKD_ALWAYS_EAGER = True # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }
34.618834
122
0.651684
import os PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } TIME_ZONE = 'America/Chicago' LANGUAGE_CODE = 'en-us' SITE_ID = 1 USE_I18N = True USE_L10N = True MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media') MEDIA_URL = '/media/' # in apps' "static/" subdirectories and in STATICFILES_DIRS. STATIC_ROOT = '' STATIC_URL = '/static/' ADMIN_MEDIA_PREFIX = '/static/admin/' STATICFILES_DIRS = ( ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'NOTASECRET' TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'tests.urls' TEMPLATE_DIRS = ( ) INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'dockit', 'dockit.backends.djangodocument', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', ] DOCKIT_BACKENDS = { 'default': { 'ENGINE': 'dockit.backends.djangodocument.backend.ModelDocumentStorage', }, 'djangodocument': { 'ENGINE': 'dockit.backends.djangodocument.backend.ModelDocumentStorage', }, } DOCKIT_INDEX_BACKENDS = { 'default': { 'ENGINE': 'dockit.backends.djangodocument.backend.ModelIndexStorage', }, 'djangodocument': { 'ENGINE': 'dockit.backends.djangodocument.backend.ModelIndexStorage', }, } try: import pymongo except ImportError: pass else: from pymongo.errors import ConnectionFailure try: pymongo.MongoClient('localhost', 27017) except ConnectionFailure: pass else: INSTALLED_APPS.append('dockit.backends.mongo') DOCKIT_BACKENDS['mongo'] = { 'ENGINE':'dockit.backends.mongo.backend.MongoDocumentStorage', 'HOST':'localhost', 'DB':'testdb', 'PORT': 27017, } DOCKIT_INDEX_BACKENDS['mongo'] = { 'ENGINE':'dockit.backends.mongo.backend.MongoIndexStorage', 'HOST':'localhost', 'DB':'testdb', 'PORT': 27017, } if 'TRAVIS' in os.environ: DOCKIT_BACKENDS['mongo'] = {'ENGINE':'dockit.backends.mongo.backend.MongoDocumentStorage', 'USER':'travis', 'PASSWORD':'test', 'DB':'mydb_test', 'HOST':'127.0.0.1', 'PORT':27017,} DOCKIT_INDEX_BACKENDS['mongo'] = {'ENGINE':'dockit.backends.mongo.backend.MongoIndexStorage', 'USER':'travis', 'PASSWORD':'test', 'DB':'mydb_test', 'HOST':'127.0.0.1', 'PORT':27017,} if 'dockit.backends.mongo' not in INSTALLED_APPS: INSTALLED_APPS.append('dockit.backends.mongo') if os.environ.get('TASK_BACKEND', None) == 'celery': DOCKIT_INDEX_BACKENDS['djangodocument']['INDEX_TASKS'] = 'dockit.backends.djangodocument.tasks.CeleryIndexTasks' INSTALLED_APPS += ["djcelery"] CELERY_ALWAYS_EAGER = True import djcelery djcelery.setup_loader() if os.environ.get('TASK_BACKEND', None) == 'ztask': DOCKIT_INDEX_BACKENDS['djangodocument']['INDEX_TASKS'] = 'dockit.backends.djangodocument.tasks.ZTaskIndexTasks' INSTALLED_APPS += ["django_ztask"] ZTASKD_ALWAYS_EAGER = True # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }
true
true
f725a8967049f2e2f616b7777ed95915bf059305
82
py
Python
src/yeelight_atmosphere/__init__.py
NikSavilov/yeelight-atmosphere
8860c2869380be50a6305b5b2aa77ed3636145d3
[ "MIT" ]
null
null
null
src/yeelight_atmosphere/__init__.py
NikSavilov/yeelight-atmosphere
8860c2869380be50a6305b5b2aa77ed3636145d3
[ "MIT" ]
7
2021-11-13T13:07:21.000Z
2021-11-19T16:30:37.000Z
src/yeelight_atmosphere/__init__.py
NikSavilov/yeelight-atmosphere
8860c2869380be50a6305b5b2aa77ed3636145d3
[ "MIT" ]
null
null
null
""" Package allows to interact with Yeelight bulbs. """ __author__ = "Savilov N."
16.4
47
0.707317
__author__ = "Savilov N."
true
true
f725a9201795c774934495e6a45ebb15b68ea359
5,930
py
Python
doc/conf.py
open-dynamic-robot-initiative/mw_dual_motor_torque_ctrl
765b2ac852952d0643caec652b2b92e9d7d18dd9
[ "BSD-3-Clause" ]
10
2020-07-06T01:06:58.000Z
2022-03-13T23:37:46.000Z
doc/conf.py
open-dynamic-robot-initiative/mw_dual_motor_torque_ctrl
765b2ac852952d0643caec652b2b92e9d7d18dd9
[ "BSD-3-Clause" ]
4
2019-08-30T06:37:14.000Z
2021-10-05T12:28:39.000Z
doc/conf.py
open-dynamic-robot-initiative/mw_dual_motor_torque_ctrl
765b2ac852952d0643caec652b2b92e9d7d18dd9
[ "BSD-3-Clause" ]
5
2021-01-01T16:03:55.000Z
2022-02-17T22:02:35.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # ODRI Motor Board Firmware for CAN Communication documentation build # configuration file, created by sphinx-quickstart on Thu Aug 12 17:06:32 2021. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.intersphinx", "sphinx.ext.todo", "sphinx.ext.mathjax", "sphinx.ext.githubpages", ] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = ".rst" # The master toctree document. master_doc = "index" # General information about the project. # project = "ODRI Motor Board Firmware for CAN Communication" project = "ODRI Firmware for CAN" copyright = "2021, Max Planck Gesellschaft" author = "Felix Widmaier" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = "1.0.0" # The full version, including alpha/beta/rc tags. release = "1.0.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars html_sidebars = { "**": [ "about.html", "navigation.html", "relations.html", # needs 'show_related': True theme option to display "searchbox.html", ] } # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = "ODRIMotorBoardFirmwareforCANCommunicationdoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ( master_doc, "ODRIMotorBoardFirmwareforCANCommunication.tex", "ODRI Motor Board Firmware for CAN Communication Documentation", "Felix Widmaier", "manual", ), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ( master_doc, "odrimotorboardfirmwareforcancommunication", "ODRI Motor Board Firmware for CAN Communication Documentation", [author], 1, ) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, "ODRIMotorBoardFirmwareforCANCommunication", "ODRI Motor Board Firmware for CAN Communication Documentation", author, "ODRIMotorBoardFirmwareforCANCommunication", "One line description of project.", "Miscellaneous", ), ] # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {"https://docs.python.org/": None}
30.885417
79
0.679764
extensions = [ "sphinx.ext.intersphinx", "sphinx.ext.todo", "sphinx.ext.mathjax", "sphinx.ext.githubpages", ] templates_path = ["_templates"] source_suffix = ".rst" master_doc = "index" project = "ODRI Firmware for CAN" copyright = "2021, Max Planck Gesellschaft" author = "Felix Widmaier" # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = "1.0.0" # The full version, including alpha/beta/rc tags. release = "1.0.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars html_sidebars = { "**": [ "about.html", "navigation.html", "relations.html", # needs 'show_related': True theme option to display "searchbox.html", ] } # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = "ODRIMotorBoardFirmwareforCANCommunicationdoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ( master_doc, "ODRIMotorBoardFirmwareforCANCommunication.tex", "ODRI Motor Board Firmware for CAN Communication Documentation", "Felix Widmaier", "manual", ), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ( master_doc, "odrimotorboardfirmwareforcancommunication", "ODRI Motor Board Firmware for CAN Communication Documentation", [author], 1, ) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, "ODRIMotorBoardFirmwareforCANCommunication", "ODRI Motor Board Firmware for CAN Communication Documentation", author, "ODRIMotorBoardFirmwareforCANCommunication", "One line description of project.", "Miscellaneous", ), ] # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {"https://docs.python.org/": None}
true
true
f725a9c6f543a4459d5a893dca60433b20e32993
4,539
py
Python
sort.py
sagittarian/personal-sort
c7875141b4e15173e4a4a2267a23ff8236e6d729
[ "MIT" ]
null
null
null
sort.py
sagittarian/personal-sort
c7875141b4e15173e4a4a2267a23ff8236e6d729
[ "MIT" ]
null
null
null
sort.py
sagittarian/personal-sort
c7875141b4e15173e4a4a2267a23ff8236e6d729
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 '''A simple implementation of a sorting algorithm, meant to allow people to manually rank a list of items using whatever subjective or objective criteria they want. This program can be called as a script and used interactively. You can provide the list of things to sort as command line arguments, or if there are no arguments provided, you can provide the list in stdin, one item per line. Example run: $ ./sort.py 'ice cream' falafel hamburgers pizza Which is greater, falafel or ice cream (<, =, or >)? < Which is greater, hamburgers or ice cream (<, =, or >)? < Which is greater, hamburgers or falafel (<, =, or >)? > Which is greater, pizza or hamburgers (<, =, or >)? > Which is greater, pizza or ice cream (<, =, or >)? < * ice cream * pizza * hamburgers * falafel Author: Adam Mesha <adam@mesha.org> License: MIT ''' from functools import cmp_to_key class memoize: '''We really want to be sure that we don't ask people to compare the same two items twice, so we cache the result. ''' def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): key = tuple(args) if key not in self.cache: self.cache[key] = self.func(*args) return self.cache[key] @memoize def cmpfunc(a, b): result = None s = 'Which is greater, {a} or {b} (<, =, or >)? '.format(a=a, b=b) while result is None or result not in '<=>': result = input(s).strip() return '<=>'.index(result) - 1 keyfunc = cmp_to_key(cmpfunc) def binary_insertion_sort(seq, keyfunc): '''Insertion sort, using binary search to insert each element. Runs in O(n**2) time, but the use case is when a human is manually deciding on the ordering, so the most important thing is to reduce the number of comparisons. ''' def mv(srcidx, dstidx): while srcidx > dstidx: seq[srcidx], seq[srcidx - 1] = seq[srcidx - 1], seq[srcidx] srcidx -= 1 i = 1 while i < len(seq): lower = 0; upper = i while lower < upper: j = (upper + lower) // 2 key1, key2 = keyfunc(seq[i]), keyfunc(seq[j]) if key1 == key2: mv(i, j+1) # XXX this is not stable i += 1 break if key1 < key2: upper = j else: # > lower = j + 1 else: mv(i, upper) i += 1 class SortableWithHeuristic: def __init__(self, val, heur): self.val = val self.heur = heur def __str__(self): return '{val}: {heur}'.format(val=self.val, heur=self.heur) def __repr__(self): return '{}(val={}, heur={})'.format(self.__class__.__name__, repr(self.val), repr(self.heur)) def get_heuristic_func(val): result = None s = 'Give an approximate numeric score to item {}: '.format(val) while result is None: try: result = float(input(s).strip()) except ValueError: pass return result def heuristic_sort(seq, get_heuristic_func, cmpfunc): def swap(a, b): seq[a], seq[b] = seq[b], seq[a] idx = 0 while idx < len(seq): val = seq[idx] heur = get_heuristic_func(val) seq[idx] = SortableWithHeuristic(val, heur) # find the current location j = idx while j > 0 and seq[j].heur < seq[j-1].heur: swap(j, j-1) j -= 1 moved = False while j < idx and cmpfunc(seq[j].val, seq[j+1].val) == 1: swap(j, j+1) j += 1 moved = True if not moved: while j > 0 and cmpfunc(seq[j].val, seq[j-1].val) == -1: swap(j, j-1) j -= 1 if 0 < j < idx: seq[j].heur = (seq[j-1].heur + seq[j+1].heur) / 2 elif idx > 0: if j == 0 and seq[j].heur > seq[j+1].heur: seq[j].heur = seq[j+1].heur - 1 elif j == idx and seq[j].heur < seq[j-1].heur: seq[j].heur = seq[j-1].heur + 1 idx += 1 def main(): import sys seq = [] if len(sys.argv) > 1: seq.extend(sys.argv[1:]) if not seq: seq.extend(x.strip() for x in sys.stdin.readlines()) heuristic_sort(seq, get_heuristic_func, cmpfunc) print('\n'.join('* {}'.format(item) for item in reversed(seq))) if __name__ == '__main__': main()
28.192547
72
0.548579
from functools import cmp_to_key class memoize: def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): key = tuple(args) if key not in self.cache: self.cache[key] = self.func(*args) return self.cache[key] @memoize def cmpfunc(a, b): result = None s = 'Which is greater, {a} or {b} (<, =, or >)? '.format(a=a, b=b) while result is None or result not in '<=>': result = input(s).strip() return '<=>'.index(result) - 1 keyfunc = cmp_to_key(cmpfunc) def binary_insertion_sort(seq, keyfunc): def mv(srcidx, dstidx): while srcidx > dstidx: seq[srcidx], seq[srcidx - 1] = seq[srcidx - 1], seq[srcidx] srcidx -= 1 i = 1 while i < len(seq): lower = 0; upper = i while lower < upper: j = (upper + lower) // 2 key1, key2 = keyfunc(seq[i]), keyfunc(seq[j]) if key1 == key2: mv(i, j+1) i += 1 break if key1 < key2: upper = j else: lower = j + 1 else: mv(i, upper) i += 1 class SortableWithHeuristic: def __init__(self, val, heur): self.val = val self.heur = heur def __str__(self): return '{val}: {heur}'.format(val=self.val, heur=self.heur) def __repr__(self): return '{}(val={}, heur={})'.format(self.__class__.__name__, repr(self.val), repr(self.heur)) def get_heuristic_func(val): result = None s = 'Give an approximate numeric score to item {}: '.format(val) while result is None: try: result = float(input(s).strip()) except ValueError: pass return result def heuristic_sort(seq, get_heuristic_func, cmpfunc): def swap(a, b): seq[a], seq[b] = seq[b], seq[a] idx = 0 while idx < len(seq): val = seq[idx] heur = get_heuristic_func(val) seq[idx] = SortableWithHeuristic(val, heur) j = idx while j > 0 and seq[j].heur < seq[j-1].heur: swap(j, j-1) j -= 1 moved = False while j < idx and cmpfunc(seq[j].val, seq[j+1].val) == 1: swap(j, j+1) j += 1 moved = True if not moved: while j > 0 and cmpfunc(seq[j].val, seq[j-1].val) == -1: swap(j, j-1) j -= 1 if 0 < j < idx: seq[j].heur = (seq[j-1].heur + seq[j+1].heur) / 2 elif idx > 0: if j == 0 and seq[j].heur > seq[j+1].heur: seq[j].heur = seq[j+1].heur - 1 elif j == idx and seq[j].heur < seq[j-1].heur: seq[j].heur = seq[j-1].heur + 1 idx += 1 def main(): import sys seq = [] if len(sys.argv) > 1: seq.extend(sys.argv[1:]) if not seq: seq.extend(x.strip() for x in sys.stdin.readlines()) heuristic_sort(seq, get_heuristic_func, cmpfunc) print('\n'.join('* {}'.format(item) for item in reversed(seq))) if __name__ == '__main__': main()
true
true
f725a9f9f6417c88c9e26be77336dc65fc531a7b
1,577
py
Python
preprocessing/homography_converter/uNetXST_homographies/2_F.py
LimJiaJing/Cam2BEV
8177e13f7a3662daee28cce62f35b85f500941c0
[ "MIT" ]
335
2020-05-11T07:24:01.000Z
2022-03-31T08:14:22.000Z
preprocessing/homography_converter/uNetXST_homographies/2_F.py
hoanganhpham1006/Cam2BEV
f788a9f58b464bc7b114e5a0dd1afcd6683f10e3
[ "MIT" ]
23
2020-07-12T23:42:31.000Z
2022-03-26T09:42:01.000Z
preprocessing/homography_converter/uNetXST_homographies/2_F.py
hoanganhpham1006/Cam2BEV
f788a9f58b464bc7b114e5a0dd1afcd6683f10e3
[ "MIT" ]
63
2020-05-11T16:27:56.000Z
2022-03-17T17:11:18.000Z
# ============================================================================== # MIT License # # Copyright 2020 Institute for Automotive Engineering of RWTH Aachen University. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # ============================================================================== import numpy as np # for dataset 2_F H = [ np.array([[0.03506686613905922, 27.971438297785962, -0.17694724954191404], [0.3821882391578238, 9.481642330993019e-17, 5.46222110929461], [25.000001047737943, 6.202207287472715e-15, 27.000001047737943]]) # front ]
50.870968
213
0.698795
import numpy as np H = [ np.array([[0.03506686613905922, 27.971438297785962, -0.17694724954191404], [0.3821882391578238, 9.481642330993019e-17, 5.46222110929461], [25.000001047737943, 6.202207287472715e-15, 27.000001047737943]]) ]
true
true
f725ab2fdd412236541d778007d38e8624e6c5f3
1,105
py
Python
gcloud/periodictask/apps.py
springborland/bk-sops
a9057672c10efb5f2414a805a30ead4092429c76
[ "Apache-2.0" ]
1
2021-05-19T04:31:34.000Z
2021-05-19T04:31:34.000Z
gcloud/periodictask/apps.py
sighttviewliu/bk-sops
6bf2f38bd93990f20f7c3a4decafc310e09e679c
[ "Apache-2.0" ]
null
null
null
gcloud/periodictask/apps.py
sighttviewliu/bk-sops
6bf2f38bd93990f20f7c3a4decafc310e09e679c
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from django.apps import AppConfig class PeriodicTaskConfig(AppConfig): name = "gcloud.periodictask" verbose_name = "GcloudPeriodicTask" def ready(self): from .signals.handlers import ( # noqa pre_periodic_task_start_handler, periodic_task_history_post_save_handler, periodic_task_start_failed_handler, )
40.925926
115
0.755656
from django.apps import AppConfig class PeriodicTaskConfig(AppConfig): name = "gcloud.periodictask" verbose_name = "GcloudPeriodicTask" def ready(self): from .signals.handlers import ( pre_periodic_task_start_handler, periodic_task_history_post_save_handler, periodic_task_start_failed_handler, )
true
true
f725abd59251190289dabcf79ac0661b33697890
1,839
py
Python
alembic/versions/4f53ec506661_add_study_template.py
jonathanzong/dmca
70157cff983310e5951024aa80e99e7a5404d758
[ "MIT" ]
2
2022-02-16T22:50:06.000Z
2022-02-21T19:38:02.000Z
alembic/versions/4f53ec506661_add_study_template.py
jonathanzong/dmca
70157cff983310e5951024aa80e99e7a5404d758
[ "MIT" ]
2
2022-02-01T05:48:07.000Z
2022-02-01T05:49:29.000Z
alembic/versions/4f53ec506661_add_study_template.py
jonathanzong/bartleby
70157cff983310e5951024aa80e99e7a5404d758
[ "MIT" ]
null
null
null
"""add study template Revision ID: 4f53ec506661 Revises: 4302608638bc Create Date: 2018-05-23 15:44:01.450488 """ # revision identifiers, used by Alembic. revision = '4f53ec506661' down_revision = '4302608638bc' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(engine_name): globals()["upgrade_%s" % engine_name]() def downgrade(engine_name): globals()["downgrade_%s" % engine_name]() def upgrade_development(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('twitter_user_recruitment_tweet_attempt', sa.Column('study_template', sa.String(length=64), nullable=True)) # ### end Alembic commands ### def downgrade_development(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('twitter_user_recruitment_tweet_attempt', 'study_template') # ### end Alembic commands ### def upgrade_test(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('twitter_user_recruitment_tweet_attempt', sa.Column('study_template', sa.String(length=64), nullable=True)) # ### end Alembic commands ### def downgrade_test(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('twitter_user_recruitment_tweet_attempt', 'study_template') # ### end Alembic commands ### def upgrade_production(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('twitter_user_recruitment_tweet_attempt', sa.Column('study_template', sa.String(length=64), nullable=True)) # ### end Alembic commands ### def downgrade_production(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('twitter_user_recruitment_tweet_attempt', 'study_template') # ### end Alembic commands ###
28.292308
125
0.712887
revision = '4f53ec506661' down_revision = '4302608638bc' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(engine_name): globals()["upgrade_%s" % engine_name]() def downgrade(engine_name): globals()["downgrade_%s" % engine_name]() def upgrade_development():
true
true
f725acb2361d7d3cd6f93696255dbd053911f91e
18,253
py
Python
iotbx/regression/tst_map_model_manager_3.py
TiankunZhou/cctbx_project
373f302f00c12d7239f8e37e3165e62bc1d852cc
[ "BSD-3-Clause-LBNL" ]
null
null
null
iotbx/regression/tst_map_model_manager_3.py
TiankunZhou/cctbx_project
373f302f00c12d7239f8e37e3165e62bc1d852cc
[ "BSD-3-Clause-LBNL" ]
null
null
null
iotbx/regression/tst_map_model_manager_3.py
TiankunZhou/cctbx_project
373f302f00c12d7239f8e37e3165e62bc1d852cc
[ "BSD-3-Clause-LBNL" ]
null
null
null
from __future__ import absolute_import, division, print_function from cctbx.array_family import flex import os, sys from libtbx.utils import Sorry from libtbx.test_utils import approx_equal from mmtbx.model import manager as model_manager from iotbx.data_manager import DataManager def exercise(file_name, out = sys.stdout): # Set up source data if not os.path.isfile(file_name): raise Sorry("Missing the file: %s" %(file_name)+"\n") print ("Reading from %s" %(file_name)) from iotbx.map_manager import map_manager m = map_manager(file_name) # make a little model sites_cart = flex.vec3_double( ((8, 10, 12), (14, 15, 16))) model = model_manager.from_sites_cart( atom_name = ' CA ', resname = 'ALA', chain_id = 'A', b_iso = 30., occ = 1., scatterer = 'C', sites_cart = sites_cart, crystal_symmetry = m.crystal_symmetry()) # make a map_model_manager with lots of maps and model and ncs from iotbx.map_model_manager import map_model_manager from mmtbx.ncs.ncs import ncs ncs_object=ncs() ncs_object.set_unit_ncs() mask_mm=m.deep_copy() mask_mm.set_is_mask(True) mam = map_model_manager( map_manager = m, ncs_object = ncs_object, map_manager_1 = m.deep_copy(), map_manager_2 = m.deep_copy(), extra_map_manager_list = [m.deep_copy(),m.deep_copy(),m.deep_copy()], extra_map_manager_id_list = ["extra_1","extra_2","map_manager_mask"], model = model.deep_copy(),) print (mam.map_manager()) print (mam.model()) print (mam.map_manager_1()) print (mam.map_manager_2()) print (mam.map_manager_mask()) print (mam.map_manager().ncs_object()) all_map_names=mam.map_id_list() for id in all_map_names: print("Map_manager %s: %s " %(id,mam.get_map_manager_by_id(id))) dm = DataManager(['model','miller_array', 'real_map', 'phil','ncs_spec']) dm.set_overwrite(True) # Create a model with ncs from iotbx.regression.ncs.tst_ncs import pdb_str_5 file_name='tst_mam.pdb' f=open(file_name,'w') print (pdb_str_5, file = f) f.close() # Generate map data from this model (it has ncs) mmm=map_model_manager() mmm.generate_map(box_cushion=0, file_name=file_name,n_residues=500) ncs_mam=mmm.deep_copy() ncs_mam_copy=mmm.deep_copy() # Make sure this model has 126 sites (42 sites times 3-fold ncs) assert ncs_mam.model().get_sites_cart().size() == 126 assert approx_equal (ncs_mam.model().get_sites_cart()[0], (23.560999999999996, 8.159, 10.660000000000002)) # Get just unique part (42 sites) unique_mam=ncs_mam.extract_all_maps_around_model(select_unique_by_ncs=True) assert unique_mam.model().get_sites_cart().size() == 42 assert approx_equal (unique_mam.model().get_sites_cart()[0], (18.740916666666664, 13.1794, 16.10544)) # Make sure that the extraction did not change the original but does change # the extracted part assert (unique_mam.model().get_sites_cart()[0] != ncs_mam.model().get_sites_cart()[0]) # it was a deep copy so original stays # Shift back the extracted part and make sure it matches the original now shifted_back_unique_model=mmm.get_model_from_other(unique_mam.deep_copy()) assert approx_equal (shifted_back_unique_model.get_sites_cart()[0], (23.560999999999996, 8.158999999999997, 10.66)) # Change the extracted model sites_cart=unique_mam.model().get_sites_cart() sites_cart[0]=(1,1,1) unique_mam.model().get_hierarchy().atoms().set_xyz(sites_cart) # Note; setting xyz in hierarchy does not set xrs by itself. do that now: unique_mam.model().set_sites_cart_from_hierarchy(multiply_ncs=False) # Make sure we really changed it assert approx_equal (unique_mam.model().get_sites_cart()[0], (1,1,1)) # Now propagate all the changes in this unique part to entire original model # using NCS ncs_mam.propagate_model_from_other(other = unique_mam, model_id = 'model', other_model_id = 'model') # ...and check that copy 1 and copy 2 both change assert approx_equal (ncs_mam.model().get_sites_cart()[0], (5.820083333333333, -4.020400000000001, -4.445440000000001)) assert approx_equal (ncs_mam.model().get_sites_cart()[42], (38.41904613024224, 17.233251085893276, 2.5547442135142524)) # Find ncs from map or model nn=ncs_mam_copy nn.write_map('ncs.ccp4') nn.write_model('ncs.pdb') ncs_object=nn.get_ncs_from_model() dm.write_ncs_spec_file(ncs_object,'ncs.ncs_spec') print ("NCS from map",ncs_object) nn.set_ncs_object(ncs_object) print ("NCS now: ",nn.ncs_object()) nn.get_ncs_from_map(ncs_object=ncs_object) print ("ncs cc:",nn.ncs_cc()) assert approx_equal(nn.ncs_cc(),0.961915979834,eps=0.01) # Make a deep_copy dc=mam.deep_copy() new_mam=mam.deep_copy() assert mam.map_manager().map_data()[0]==new_mam.map_manager().map_data()[0] # Make a customized_copy new_mam=mam.customized_copy(model_dict={'model':mam.model()}) assert new_mam.model() is mam.model() assert not new_mam.map_dict() is mam.map_dict() new_mam=mam.customized_copy(model_dict={'model':mam.model()}, map_dict=mam.map_dict()) assert new_mam.model() is mam.model() assert new_mam.map_dict() is mam.map_dict() print (mam) # Add a map mam = dc.deep_copy() print (mam.map_id_list()) assert len(mam.map_id_list()) == 6 mam.add_map_manager_by_id(mam.map_manager().deep_copy(),'new_map_manager') print (mam.map_id_list()) assert len(mam.map_id_list()) == 7 # duplicate a map mam = dc.deep_copy() print (mam.map_id_list()) assert len(mam.map_id_list()) == 6 mam.duplicate_map_manager('map_manager','new_map_manager') print (mam.map_id_list()) assert len(mam.map_id_list()) == 7 # resolution_filter a map mam = dc.deep_copy() print (mam.map_id_list()) mam.duplicate_map_manager('map_manager','new_map_manager') mam.resolution_filter(map_id='new_map_manager',d_min=3.5,d_max=6) # Add a model mam = dc.deep_copy() print (mam.model_id_list()) assert len(mam.model_id_list()) == 1 mam.add_model_by_id(mam.model().deep_copy(),'new_model') print (mam.model_id_list()) assert len(mam.model_id_list()) == 2 # Initialize a map mam1=new_mam.deep_copy() mam1.initialize_maps(map_value=6) assert mam1.map_manager().map_data()[225] == 6 # Create mask around density and apply to all maps mam1=new_mam.deep_copy() mam1.mask_all_maps_around_density(solvent_content=0.5, soft_mask=True,) s = (mam1.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1024,2048)) # Create mask around edges and apply to all maps mam1=new_mam.deep_copy() mam1.mask_all_maps_around_edges() s = (mam1.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1176,2048)) # Create a soft mask around model and apply to all maps new_mam.mask_all_maps_around_atoms(mask_atoms_atom_radius=8, soft_mask=True) s = (new_mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1944,2048)) # Create a soft mask around model and do not do anything with it new_mam.create_mask_around_atoms(mask_atoms_atom_radius=8, soft_mask=True) s = (new_mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1944,2048)) # Create a soft mask around model and do not do anything with it, wrapping =true dummy_mam=new_mam.deep_copy() dummy_mam.map_manager().set_wrapping(True) dummy_mam.create_mask_around_atoms(mask_atoms_atom_radius=8, soft_mask=True) s = (dummy_mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1944,2048)) # Create a sharp mask around model and do not do anything with it new_mam.create_mask_around_atoms(soft_mask=False, mask_atoms_atom_radius=8) s = (new_mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (138,2048)) # Mask around edges and do not do anything with it mam=dc.deep_copy() mam.create_mask_around_edges() s = (mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1176,2048)) # Mask around density and to not do anything with it mam=dc.deep_copy() mam.create_mask_around_density(soft_mask=False) s = (mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1000,2048)) # Apply the current mask to one map mam.apply_mask_to_map('map_manager') s = (mam.map_manager().map_data() > 0.) assert approx_equal( (s.count(True),s.size()), (640,2048)) s = (mam.map_manager().map_data() != 0.) assert approx_equal( (s.count(True),s.size()), (1000,2048)) assert approx_equal ((mam.map_manager().map_data()[225]),-0.0418027862906) # Apply any mask to one map mam.apply_mask_to_map('map_manager',mask_id='mask') s = (mam.map_manager().map_data() > 0.) assert approx_equal( (s.count(True),s.size()), (640,2048)) s = (mam.map_manager().map_data() != 0.) assert approx_equal( (s.count(True),s.size()), (1000,2048)) assert approx_equal ((mam.map_manager().map_data()[225]),-0.0418027862906) # Apply the mask to all maps mam.apply_mask_to_maps() s = (mam.map_manager().map_data() > 0.) assert approx_equal( (s.count(True),s.size()), (640,2048)) s = (mam.map_manager().map_data() != 0.) assert approx_equal( (s.count(True),s.size()), (1000,2048)) assert approx_equal ((mam.map_manager().map_data()[225]),-0.0418027862906) # Apply the mask to all maps, setting outside value to mean inside mam.apply_mask_to_maps(set_outside_to_mean_inside=True) s = (mam.map_manager().map_data() > 0.) assert approx_equal( (s.count(True),s.size()), (1688,2048)) s = (mam.map_manager().map_data() != 0.) assert approx_equal( (s.count(True),s.size()), (2048,2048)) assert approx_equal ((mam.map_manager().map_data()[2047]),-0.0759598612785) s = (mam.get_map_manager_by_id('mask').map_data() > 0).as_1d() inside = mam.map_manager().map_data().as_1d().select(s) outside = mam.map_manager().map_data().as_1d().select(~s) assert approx_equal ((inside.min_max_mean().max,outside.min_max_mean().max), (0.335603952408,0.0239064293122)) # Make a new map and model, get mam and box with selection mmm=map_model_manager() mmm.generate_map(box_cushion=0,wrapping=True) mam=mmm mam_dc=mam.deep_copy() new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((18, 25, 20),(18, 25, 20))) # Get local fsc or randomized map dc=mam_dc.deep_copy() dc.map_manager().set_wrapping(False) map_coeffs = dc.map_manager().map_as_fourier_coefficients(d_min=3) from cctbx.development.create_models_or_maps import generate_map new_mm_1 = generate_map(map_coeffs=map_coeffs, d_min=3, low_resolution_real_space_noise_fraction=1, high_resolution_real_space_noise_fraction=50, map_manager=dc.map_manager(), random_seed=124321) new_mm_2 = generate_map(map_coeffs=map_coeffs, d_min=3, low_resolution_real_space_noise_fraction=1, high_resolution_real_space_noise_fraction=50, map_manager=dc.map_manager(), random_seed=734119) dc.add_map_manager_by_id(new_mm_1,'map_manager_1') dc.add_map_manager_by_id(new_mm_2,'map_manager_2') cc=dc.map_map_cc() fsc_curve=dc.map_map_fsc() dc.set_log(sys.stdout) dc.local_fsc(n_boxes = 1) # Get map-map FSC dc=mam_dc.deep_copy() dc.duplicate_map_manager(map_id='map_manager',new_map_id='filtered') dc.resolution_filter(d_min=3.5, d_max=10, map_id='filtered') dc.create_mask_around_atoms() fsc_curve=dc.map_map_fsc( map_id_1='map_manager',map_id_2='filtered',mask_id='mask', resolution=3.5,fsc_cutoff = 0.97) assert approx_equal(fsc_curve.d_min, 3.93793648601,eps=0.01) assert approx_equal (fsc_curve.fsc.fsc[-1],0.707536576779) # Get map-map CC dc=mam_dc.deep_copy() dc.duplicate_map_manager(map_id='map_manager',new_map_id='filtered') dc.resolution_filter(d_min=3.5, d_max=6, map_id='filtered') cc=dc.map_map_cc('map_manager','filtered') assert approx_equal(cc , 0.676687646486) # Get map-map CC with mask dc=mam_dc.deep_copy() dc.duplicate_map_manager(map_id='map_manager',new_map_id='filtered') dc.create_mask_around_density(mask_id='filtered') cc=dc.map_map_cc('map_manager','filtered',mask_id='mask') assert approx_equal(cc , 0.422523947639) # box around model mam=mam_dc.deep_copy() mam.box_all_maps_around_model_and_shift_origin( selection_string="resseq 221:221") new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((18, 25, 20),(24, 20, 20))) # extract_around_model (get new mam) new_mam_dc=mam_dc.extract_all_maps_around_model( selection_string="resseq 221:221") new_mm_1a=new_mam_dc.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1a.map_data().all()), ((18, 25, 20),(24, 20, 20))) assert approx_equal(new_mm_1.map_data(),new_mm_1a.map_data()) # box around_density mam2=mam_dc.deep_copy() mam2.box_all_maps_around_density_and_shift_origin(box_cushion=0) new_mm_2=mam2.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_2.map_data().all()), ((18, 25, 20),(16, 23, 18))) # extract_around_density (get new mam) mam2=mam_dc.deep_copy() mam2_b=mam2.extract_all_maps_around_density(box_cushion=0) new_mm_2=mam2_b.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_2.map_data().all()), ((18, 25, 20),(16, 23, 18))) # Repeat as map_model_manager: mmm=mam_dc.as_map_model_manager().deep_copy() mmm.box_all_maps_around_model_and_shift_origin( selection_string="resseq 221:221") new_mm_1a=mmm.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1a.map_data().all()), ((24, 20, 20),(24, 20, 20))) assert approx_equal(new_mm_1.map_data(),new_mm_1a.map_data()) # box around density mam.box_all_maps_around_density_and_shift_origin(box_cushion=0) new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20 , 20),(22, 18, 18))) # extract around density (get new mam) mam1=mam_dc.deep_copy() mam1.extract_all_maps_around_density(box_cushion=0) new_mm_1=mam1.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20 , 20),(18, 25, 20))) # create mask around density, then box around mask (i.e., box around density) mam.create_mask_around_density(soft_mask=False) mam.box_all_maps_around_mask_and_shift_origin(box_cushion=3) new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20 , 20),(22, 18, 18))) # box with bounds mam.box_all_maps_with_bounds_and_shift_origin(lower_bounds=(10,10,10), upper_bounds=(15,15,15)) new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20, 20),(6, 6, 6))) # extract with bounds mam=mam_dc.deep_copy() mam_1=mam.extract_all_maps_with_bounds(lower_bounds=(10,10,10), upper_bounds=(15,15,15)) new_mm_1=mam_1.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20, 20),(6, 6, 6))) # box with unique mam=mam_dc.deep_copy() mam.box_all_maps_around_unique_and_shift_origin( molecular_mass=2500,resolution=3) new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20, 20),(18, 25, 20))) # extract with unique mam=mam_dc.deep_copy() mam_1=mam.extract_all_maps_around_unique( molecular_mass=2500,resolution=3) new_mm_1=mam_1.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20, 20),(18, 25, 20))) # extract a box and then restore model into same reference as current mam mam=mam_dc.deep_copy() mam.box_all_maps_with_bounds_and_shift_origin(lower_bounds=(2,2,2), upper_bounds=(17,17,17)) print("mam:",mam.model().get_sites_cart()[0],mam.map_manager().origin_is_zero()) # extract a box box_mam=mam.extract_all_maps_with_bounds(lower_bounds=(10,10,10), upper_bounds=(15,15,15)) box_model=box_mam.model() matched_box_model=mam.get_model_from_other(box_mam) assert approx_equal(matched_box_model.get_sites_cart()[0],mam.model().get_sites_cart()[0]) # Convert a map to fourier coefficients mam=mam_dc.deep_copy() ma=mam.map_as_fourier_coefficients(d_min=3) assert approx_equal(ma.d_min(),3.01655042414) mam.add_map_from_fourier_coefficients(ma, map_id='new_map_manager') cc=flex.linear_correlation( mam.get_map_manager_by_id('map_manager').map_data().as_1d(), mam.get_map_manager_by_id('new_map_manager').map_data().as_1d()).coefficient() assert (cc >= 0.99) # Get map-model CC dc=mam_dc.extract_all_maps_around_model( selection_string="(name ca or name cb or name c or name o) "+ "and resseq 221:221", box_cushion=0) cc=dc.map_model_cc(resolution=3) assert approx_equal (cc, 0.817089390421) # Remove model outside map dc.remove_model_outside_map(boundary=0) assert (mam_dc.model().get_sites_cart().size(), dc.model().get_sites_cart().size()) == (86, 4) # shift a model to match the map dc=mam_dc.extract_all_maps_around_model( selection_string="(name ca or name cb or name c or name o) "+ "and resseq 221:221", box_cushion=0) actual_model=dc.model().deep_copy() working_model=dc.model().deep_copy() working_model.set_shift_cart((0,0,0)) working_model.set_sites_cart(working_model.get_sites_cart()-actual_model.shift_cart()) dc.shift_any_model_to_match(working_model) assert approx_equal (actual_model.get_sites_cart()[0],working_model.get_sites_cart()[0]) if __name__ == "__main__": args = sys.argv[1:] import libtbx.load_env if not args: file_name = libtbx.env.under_dist( module_name = "iotbx", path = "ccp4_map/tst_input.map") args = [file_name] if libtbx.env.has_module("phenix"): exercise(file_name = args[0]) else: print("Skipped: Requires phenix module") print ("OK")
38.027083
92
0.718402
from __future__ import absolute_import, division, print_function from cctbx.array_family import flex import os, sys from libtbx.utils import Sorry from libtbx.test_utils import approx_equal from mmtbx.model import manager as model_manager from iotbx.data_manager import DataManager def exercise(file_name, out = sys.stdout): if not os.path.isfile(file_name): raise Sorry("Missing the file: %s" %(file_name)+"\n") print ("Reading from %s" %(file_name)) from iotbx.map_manager import map_manager m = map_manager(file_name) sites_cart = flex.vec3_double( ((8, 10, 12), (14, 15, 16))) model = model_manager.from_sites_cart( atom_name = ' CA ', resname = 'ALA', chain_id = 'A', b_iso = 30., occ = 1., scatterer = 'C', sites_cart = sites_cart, crystal_symmetry = m.crystal_symmetry()) from iotbx.map_model_manager import map_model_manager from mmtbx.ncs.ncs import ncs ncs_object=ncs() ncs_object.set_unit_ncs() mask_mm=m.deep_copy() mask_mm.set_is_mask(True) mam = map_model_manager( map_manager = m, ncs_object = ncs_object, map_manager_1 = m.deep_copy(), map_manager_2 = m.deep_copy(), extra_map_manager_list = [m.deep_copy(),m.deep_copy(),m.deep_copy()], extra_map_manager_id_list = ["extra_1","extra_2","map_manager_mask"], model = model.deep_copy(),) print (mam.map_manager()) print (mam.model()) print (mam.map_manager_1()) print (mam.map_manager_2()) print (mam.map_manager_mask()) print (mam.map_manager().ncs_object()) all_map_names=mam.map_id_list() for id in all_map_names: print("Map_manager %s: %s " %(id,mam.get_map_manager_by_id(id))) dm = DataManager(['model','miller_array', 'real_map', 'phil','ncs_spec']) dm.set_overwrite(True) from iotbx.regression.ncs.tst_ncs import pdb_str_5 file_name='tst_mam.pdb' f=open(file_name,'w') print (pdb_str_5, file = f) f.close() mmm=map_model_manager() mmm.generate_map(box_cushion=0, file_name=file_name,n_residues=500) ncs_mam=mmm.deep_copy() ncs_mam_copy=mmm.deep_copy() assert ncs_mam.model().get_sites_cart().size() == 126 assert approx_equal (ncs_mam.model().get_sites_cart()[0], (23.560999999999996, 8.159, 10.660000000000002)) unique_mam=ncs_mam.extract_all_maps_around_model(select_unique_by_ncs=True) assert unique_mam.model().get_sites_cart().size() == 42 assert approx_equal (unique_mam.model().get_sites_cart()[0], (18.740916666666664, 13.1794, 16.10544)) assert (unique_mam.model().get_sites_cart()[0] != ncs_mam.model().get_sites_cart()[0]) shifted_back_unique_model=mmm.get_model_from_other(unique_mam.deep_copy()) assert approx_equal (shifted_back_unique_model.get_sites_cart()[0], (23.560999999999996, 8.158999999999997, 10.66)) sites_cart=unique_mam.model().get_sites_cart() sites_cart[0]=(1,1,1) unique_mam.model().get_hierarchy().atoms().set_xyz(sites_cart) unique_mam.model().set_sites_cart_from_hierarchy(multiply_ncs=False) assert approx_equal (unique_mam.model().get_sites_cart()[0], (1,1,1)) ncs_mam.propagate_model_from_other(other = unique_mam, model_id = 'model', other_model_id = 'model') assert approx_equal (ncs_mam.model().get_sites_cart()[0], (5.820083333333333, -4.020400000000001, -4.445440000000001)) assert approx_equal (ncs_mam.model().get_sites_cart()[42], (38.41904613024224, 17.233251085893276, 2.5547442135142524)) nn=ncs_mam_copy nn.write_map('ncs.ccp4') nn.write_model('ncs.pdb') ncs_object=nn.get_ncs_from_model() dm.write_ncs_spec_file(ncs_object,'ncs.ncs_spec') print ("NCS from map",ncs_object) nn.set_ncs_object(ncs_object) print ("NCS now: ",nn.ncs_object()) nn.get_ncs_from_map(ncs_object=ncs_object) print ("ncs cc:",nn.ncs_cc()) assert approx_equal(nn.ncs_cc(),0.961915979834,eps=0.01) dc=mam.deep_copy() new_mam=mam.deep_copy() assert mam.map_manager().map_data()[0]==new_mam.map_manager().map_data()[0] new_mam=mam.customized_copy(model_dict={'model':mam.model()}) assert new_mam.model() is mam.model() assert not new_mam.map_dict() is mam.map_dict() new_mam=mam.customized_copy(model_dict={'model':mam.model()}, map_dict=mam.map_dict()) assert new_mam.model() is mam.model() assert new_mam.map_dict() is mam.map_dict() print (mam) mam = dc.deep_copy() print (mam.map_id_list()) assert len(mam.map_id_list()) == 6 mam.add_map_manager_by_id(mam.map_manager().deep_copy(),'new_map_manager') print (mam.map_id_list()) assert len(mam.map_id_list()) == 7 mam = dc.deep_copy() print (mam.map_id_list()) assert len(mam.map_id_list()) == 6 mam.duplicate_map_manager('map_manager','new_map_manager') print (mam.map_id_list()) assert len(mam.map_id_list()) == 7 mam = dc.deep_copy() print (mam.map_id_list()) mam.duplicate_map_manager('map_manager','new_map_manager') mam.resolution_filter(map_id='new_map_manager',d_min=3.5,d_max=6) mam = dc.deep_copy() print (mam.model_id_list()) assert len(mam.model_id_list()) == 1 mam.add_model_by_id(mam.model().deep_copy(),'new_model') print (mam.model_id_list()) assert len(mam.model_id_list()) == 2 mam1=new_mam.deep_copy() mam1.initialize_maps(map_value=6) assert mam1.map_manager().map_data()[225] == 6 mam1=new_mam.deep_copy() mam1.mask_all_maps_around_density(solvent_content=0.5, soft_mask=True,) s = (mam1.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1024,2048)) mam1=new_mam.deep_copy() mam1.mask_all_maps_around_edges() s = (mam1.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1176,2048)) new_mam.mask_all_maps_around_atoms(mask_atoms_atom_radius=8, soft_mask=True) s = (new_mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1944,2048)) new_mam.create_mask_around_atoms(mask_atoms_atom_radius=8, soft_mask=True) s = (new_mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1944,2048)) dummy_mam=new_mam.deep_copy() dummy_mam.map_manager().set_wrapping(True) dummy_mam.create_mask_around_atoms(mask_atoms_atom_radius=8, soft_mask=True) s = (dummy_mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1944,2048)) new_mam.create_mask_around_atoms(soft_mask=False, mask_atoms_atom_radius=8) s = (new_mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (138,2048)) mam=dc.deep_copy() mam.create_mask_around_edges() s = (mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1176,2048)) mam=dc.deep_copy() mam.create_mask_around_density(soft_mask=False) s = (mam.get_map_manager_by_id('mask').map_data() > 0.5) assert approx_equal( (s.count(True),s.size()), (1000,2048)) mam.apply_mask_to_map('map_manager') s = (mam.map_manager().map_data() > 0.) assert approx_equal( (s.count(True),s.size()), (640,2048)) s = (mam.map_manager().map_data() != 0.) assert approx_equal( (s.count(True),s.size()), (1000,2048)) assert approx_equal ((mam.map_manager().map_data()[225]),-0.0418027862906) mam.apply_mask_to_map('map_manager',mask_id='mask') s = (mam.map_manager().map_data() > 0.) assert approx_equal( (s.count(True),s.size()), (640,2048)) s = (mam.map_manager().map_data() != 0.) assert approx_equal( (s.count(True),s.size()), (1000,2048)) assert approx_equal ((mam.map_manager().map_data()[225]),-0.0418027862906) mam.apply_mask_to_maps() s = (mam.map_manager().map_data() > 0.) assert approx_equal( (s.count(True),s.size()), (640,2048)) s = (mam.map_manager().map_data() != 0.) assert approx_equal( (s.count(True),s.size()), (1000,2048)) assert approx_equal ((mam.map_manager().map_data()[225]),-0.0418027862906) mam.apply_mask_to_maps(set_outside_to_mean_inside=True) s = (mam.map_manager().map_data() > 0.) assert approx_equal( (s.count(True),s.size()), (1688,2048)) s = (mam.map_manager().map_data() != 0.) assert approx_equal( (s.count(True),s.size()), (2048,2048)) assert approx_equal ((mam.map_manager().map_data()[2047]),-0.0759598612785) s = (mam.get_map_manager_by_id('mask').map_data() > 0).as_1d() inside = mam.map_manager().map_data().as_1d().select(s) outside = mam.map_manager().map_data().as_1d().select(~s) assert approx_equal ((inside.min_max_mean().max,outside.min_max_mean().max), (0.335603952408,0.0239064293122)) mmm=map_model_manager() mmm.generate_map(box_cushion=0,wrapping=True) mam=mmm mam_dc=mam.deep_copy() new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((18, 25, 20),(18, 25, 20))) dc=mam_dc.deep_copy() dc.map_manager().set_wrapping(False) map_coeffs = dc.map_manager().map_as_fourier_coefficients(d_min=3) from cctbx.development.create_models_or_maps import generate_map new_mm_1 = generate_map(map_coeffs=map_coeffs, d_min=3, low_resolution_real_space_noise_fraction=1, high_resolution_real_space_noise_fraction=50, map_manager=dc.map_manager(), random_seed=124321) new_mm_2 = generate_map(map_coeffs=map_coeffs, d_min=3, low_resolution_real_space_noise_fraction=1, high_resolution_real_space_noise_fraction=50, map_manager=dc.map_manager(), random_seed=734119) dc.add_map_manager_by_id(new_mm_1,'map_manager_1') dc.add_map_manager_by_id(new_mm_2,'map_manager_2') cc=dc.map_map_cc() fsc_curve=dc.map_map_fsc() dc.set_log(sys.stdout) dc.local_fsc(n_boxes = 1) dc=mam_dc.deep_copy() dc.duplicate_map_manager(map_id='map_manager',new_map_id='filtered') dc.resolution_filter(d_min=3.5, d_max=10, map_id='filtered') dc.create_mask_around_atoms() fsc_curve=dc.map_map_fsc( map_id_1='map_manager',map_id_2='filtered',mask_id='mask', resolution=3.5,fsc_cutoff = 0.97) assert approx_equal(fsc_curve.d_min, 3.93793648601,eps=0.01) assert approx_equal (fsc_curve.fsc.fsc[-1],0.707536576779) dc=mam_dc.deep_copy() dc.duplicate_map_manager(map_id='map_manager',new_map_id='filtered') dc.resolution_filter(d_min=3.5, d_max=6, map_id='filtered') cc=dc.map_map_cc('map_manager','filtered') assert approx_equal(cc , 0.676687646486) dc=mam_dc.deep_copy() dc.duplicate_map_manager(map_id='map_manager',new_map_id='filtered') dc.create_mask_around_density(mask_id='filtered') cc=dc.map_map_cc('map_manager','filtered',mask_id='mask') assert approx_equal(cc , 0.422523947639) mam=mam_dc.deep_copy() mam.box_all_maps_around_model_and_shift_origin( selection_string="resseq 221:221") new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((18, 25, 20),(24, 20, 20))) new_mam_dc=mam_dc.extract_all_maps_around_model( selection_string="resseq 221:221") new_mm_1a=new_mam_dc.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1a.map_data().all()), ((18, 25, 20),(24, 20, 20))) assert approx_equal(new_mm_1.map_data(),new_mm_1a.map_data()) mam2=mam_dc.deep_copy() mam2.box_all_maps_around_density_and_shift_origin(box_cushion=0) new_mm_2=mam2.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_2.map_data().all()), ((18, 25, 20),(16, 23, 18))) mam2=mam_dc.deep_copy() mam2_b=mam2.extract_all_maps_around_density(box_cushion=0) new_mm_2=mam2_b.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_2.map_data().all()), ((18, 25, 20),(16, 23, 18))) mmm=mam_dc.as_map_model_manager().deep_copy() mmm.box_all_maps_around_model_and_shift_origin( selection_string="resseq 221:221") new_mm_1a=mmm.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1a.map_data().all()), ((24, 20, 20),(24, 20, 20))) assert approx_equal(new_mm_1.map_data(),new_mm_1a.map_data()) mam.box_all_maps_around_density_and_shift_origin(box_cushion=0) new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20 , 20),(22, 18, 18))) mam1=mam_dc.deep_copy() mam1.extract_all_maps_around_density(box_cushion=0) new_mm_1=mam1.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20 , 20),(18, 25, 20))) mam.create_mask_around_density(soft_mask=False) mam.box_all_maps_around_mask_and_shift_origin(box_cushion=3) new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20 , 20),(22, 18, 18))) mam.box_all_maps_with_bounds_and_shift_origin(lower_bounds=(10,10,10), upper_bounds=(15,15,15)) new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20, 20),(6, 6, 6))) mam=mam_dc.deep_copy() mam_1=mam.extract_all_maps_with_bounds(lower_bounds=(10,10,10), upper_bounds=(15,15,15)) new_mm_1=mam_1.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20, 20),(6, 6, 6))) mam=mam_dc.deep_copy() mam.box_all_maps_around_unique_and_shift_origin( molecular_mass=2500,resolution=3) new_mm_1=mam.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20, 20),(18, 25, 20))) mam=mam_dc.deep_copy() mam_1=mam.extract_all_maps_around_unique( molecular_mass=2500,resolution=3) new_mm_1=mam_1.map_manager() assert approx_equal( (mmm.map_data().all(),new_mm_1.map_data().all()), ((24, 20, 20),(18, 25, 20))) mam=mam_dc.deep_copy() mam.box_all_maps_with_bounds_and_shift_origin(lower_bounds=(2,2,2), upper_bounds=(17,17,17)) print("mam:",mam.model().get_sites_cart()[0],mam.map_manager().origin_is_zero()) box_mam=mam.extract_all_maps_with_bounds(lower_bounds=(10,10,10), upper_bounds=(15,15,15)) box_model=box_mam.model() matched_box_model=mam.get_model_from_other(box_mam) assert approx_equal(matched_box_model.get_sites_cart()[0],mam.model().get_sites_cart()[0]) mam=mam_dc.deep_copy() ma=mam.map_as_fourier_coefficients(d_min=3) assert approx_equal(ma.d_min(),3.01655042414) mam.add_map_from_fourier_coefficients(ma, map_id='new_map_manager') cc=flex.linear_correlation( mam.get_map_manager_by_id('map_manager').map_data().as_1d(), mam.get_map_manager_by_id('new_map_manager').map_data().as_1d()).coefficient() assert (cc >= 0.99) dc=mam_dc.extract_all_maps_around_model( selection_string="(name ca or name cb or name c or name o) "+ "and resseq 221:221", box_cushion=0) cc=dc.map_model_cc(resolution=3) assert approx_equal (cc, 0.817089390421) dc.remove_model_outside_map(boundary=0) assert (mam_dc.model().get_sites_cart().size(), dc.model().get_sites_cart().size()) == (86, 4) dc=mam_dc.extract_all_maps_around_model( selection_string="(name ca or name cb or name c or name o) "+ "and resseq 221:221", box_cushion=0) actual_model=dc.model().deep_copy() working_model=dc.model().deep_copy() working_model.set_shift_cart((0,0,0)) working_model.set_sites_cart(working_model.get_sites_cart()-actual_model.shift_cart()) dc.shift_any_model_to_match(working_model) assert approx_equal (actual_model.get_sites_cart()[0],working_model.get_sites_cart()[0]) if __name__ == "__main__": args = sys.argv[1:] import libtbx.load_env if not args: file_name = libtbx.env.under_dist( module_name = "iotbx", path = "ccp4_map/tst_input.map") args = [file_name] if libtbx.env.has_module("phenix"): exercise(file_name = args[0]) else: print("Skipped: Requires phenix module") print ("OK")
true
true
f725ad5a075727936af4a26120e61b5c25cd3bc9
193,257
py
Python
backend/mips_to_c/src/translate.py
Rainchus/decomp.me
607aab29a18656dcbc0443505ef2944c10afa085
[ "MIT" ]
null
null
null
backend/mips_to_c/src/translate.py
Rainchus/decomp.me
607aab29a18656dcbc0443505ef2944c10afa085
[ "MIT" ]
null
null
null
backend/mips_to_c/src/translate.py
Rainchus/decomp.me
607aab29a18656dcbc0443505ef2944c10afa085
[ "MIT" ]
null
null
null
import abc from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass, field, replace import math import struct import sys import traceback import typing from typing import ( AbstractSet, Callable, Collection, DefaultDict, Dict, Iterator, List, Mapping, Optional, Set, Tuple, Union, ) from .c_types import CType, TypeMap from .demangle_codewarrior import parse as demangle_codewarrior_parse, CxxSymbol from .error import DecompFailure, static_assert_unreachable from .flow_graph import ( ArchFlowGraph, FlowGraph, Function, Node, ReturnNode, SwitchNode, TerminalNode, locs_clobbered_until_dominator, ) from .ir_pattern import IrPattern, simplify_ir_patterns from .options import CodingStyle, Formatter, Options, Target from .parse_file import AsmData, AsmDataEntry from .parse_instruction import ( ArchAsm, Argument, AsmAddressMode, AsmGlobalSymbol, AsmLiteral, BinOp, Instruction, InstrProcessingFailure, Macro, Register, StackLocation, current_instr, ) from .types import ( AccessPath, FunctionParam, FunctionSignature, StructDeclaration, Type, TypePool, ) InstrSet = Collection[str] InstrMap = Mapping[str, Callable[["InstrArgs"], "Expression"]] StmtInstrMap = Mapping[str, Callable[["InstrArgs"], "Statement"]] CmpInstrMap = Mapping[str, Callable[["InstrArgs"], "Condition"]] StoreInstrMap = Mapping[str, Callable[["InstrArgs"], Optional["StoreStmt"]]] MaybeInstrMap = Mapping[str, Callable[["InstrArgs"], Optional["Expression"]]] PairInstrMap = Mapping[str, Callable[["InstrArgs"], Tuple["Expression", "Expression"]]] ImplicitInstrMap = Mapping[str, Tuple[Register, Callable[["InstrArgs"], "Expression"]]] PpcCmpInstrMap = Mapping[str, Callable[["InstrArgs", str], "Expression"]] class Arch(ArchFlowGraph): instrs_ignore: InstrSet = set() instrs_store: StoreInstrMap = {} instrs_store_update: StoreInstrMap = {} instrs_load_update: InstrMap = {} instrs_branches: CmpInstrMap = {} instrs_float_branches: InstrSet = set() instrs_float_comp: CmpInstrMap = {} instrs_ppc_compare: PpcCmpInstrMap = {} instrs_jumps: InstrSet = set() instrs_fn_call: InstrSet = set() instrs_no_dest: StmtInstrMap = {} instrs_hi_lo: PairInstrMap = {} instrs_source_first: InstrMap = {} instrs_destination_first: InstrMap = {} instrs_implicit_destination: ImplicitInstrMap = {} @abc.abstractmethod def function_abi( self, fn_sig: FunctionSignature, likely_regs: Dict[Register, bool], *, for_call: bool, ) -> "Abi": """ Compute stack positions/registers used by a function based on its type information. Also computes a list of registers that may contain arguments, if the function has varargs or an unknown/incomplete type. """ ... @abc.abstractmethod def function_return(self, expr: "Expression") -> Dict[Register, "Expression"]: """ Compute register location(s) & values that will hold the return value of the function call `expr`. This must have a value for each register in `all_return_regs` in order to stay consistent with `Instruction.outputs`. This is why we can't use the function's return type, even though it may be more accurate. """ ... # These are defined here to avoid a circular import in flow_graph.py ir_patterns: List[IrPattern] = [] def simplify_ir(self, flow_graph: FlowGraph) -> None: simplify_ir_patterns(self, flow_graph, self.ir_patterns) ASSOCIATIVE_OPS: Set[str] = {"+", "&&", "||", "&", "|", "^", "*"} COMPOUND_ASSIGNMENT_OPS: Set[str] = {"+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>"} PSEUDO_FUNCTION_OPS: Set[str] = {"MULT_HI", "MULTU_HI", "DMULT_HI", "DMULTU_HI", "CLZ"} def as_type(expr: "Expression", type: Type, silent: bool) -> "Expression": type = type.weaken_void_ptr() ptr_target_type = type.get_pointer_target() if expr.type.unify(type): if silent or isinstance(expr, Literal): return expr elif ptr_target_type is not None: ptr_target_type_size = ptr_target_type.get_size_bytes() field_path, field_type, _ = expr.type.get_deref_field( 0, target_size=ptr_target_type_size ) if field_path is not None and field_type.unify(ptr_target_type): expr = AddressOf( StructAccess( struct_var=expr, offset=0, target_size=ptr_target_type_size, field_path=field_path, stack_info=None, type=field_type, ), type=type, ) if silent: return expr return Cast(expr=expr, reinterpret=True, silent=False, type=type) def as_f32(expr: "Expression") -> "Expression": return as_type(expr, Type.f32(), True) def as_f64(expr: "Expression") -> "Expression": return as_type(expr, Type.f64(), True) def as_sintish(expr: "Expression", *, silent: bool = False) -> "Expression": return as_type(expr, Type.sintish(), silent) def as_uintish(expr: "Expression") -> "Expression": return as_type(expr, Type.uintish(), False) def as_u32(expr: "Expression") -> "Expression": return as_type(expr, Type.u32(), False) def as_s64(expr: "Expression", *, silent: bool = False) -> "Expression": return as_type(expr, Type.s64(), silent) def as_u64(expr: "Expression", *, silent: bool = False) -> "Expression": return as_type(expr, Type.u64(), silent) def as_intish(expr: "Expression") -> "Expression": return as_type(expr, Type.intish(), True) def as_int64(expr: "Expression") -> "Expression": return as_type(expr, Type.int64(), True) def as_intptr(expr: "Expression") -> "Expression": return as_type(expr, Type.intptr(), True) def as_ptr(expr: "Expression") -> "Expression": return as_type(expr, Type.ptr(), True) def as_function_ptr(expr: "Expression") -> "Expression": return as_type(expr, Type.ptr(Type.function()), True) @dataclass class StackInfo: function: Function global_info: "GlobalInfo" flow_graph: FlowGraph allocated_stack_size: int = 0 is_leaf: bool = True is_variadic: bool = False uses_framepointer: bool = False subroutine_arg_top: int = 0 callee_save_regs: Set[Register] = field(default_factory=set) callee_save_reg_region: Tuple[int, int] = (0, 0) unique_type_map: Dict[Tuple[str, object], "Type"] = field(default_factory=dict) local_vars: List["LocalVar"] = field(default_factory=list) temp_vars: List["EvalOnceStmt"] = field(default_factory=list) phi_vars: List["PhiExpr"] = field(default_factory=list) reg_vars: Dict[Register, "RegisterVar"] = field(default_factory=dict) used_reg_vars: Set[Register] = field(default_factory=set) arguments: List["PassedInArg"] = field(default_factory=list) temp_name_counter: Dict[str, int] = field(default_factory=dict) nonzero_accesses: Set["Expression"] = field(default_factory=set) param_names: Dict[int, str] = field(default_factory=dict) stack_pointer_type: Optional[Type] = None replace_first_arg: Optional[Tuple[str, Type]] = None weak_stack_var_types: Dict[int, Type] = field(default_factory=dict) weak_stack_var_locations: Set[int] = field(default_factory=set) def temp_var(self, prefix: str) -> str: counter = self.temp_name_counter.get(prefix, 0) + 1 self.temp_name_counter[prefix] = counter return prefix + (f"_{counter}" if counter > 1 else "") def in_subroutine_arg_region(self, location: int) -> bool: if self.global_info.arch.arch == Target.ArchEnum.PPC: return False if self.is_leaf: return False assert self.subroutine_arg_top is not None return location < self.subroutine_arg_top def in_callee_save_reg_region(self, location: int) -> bool: lower_bound, upper_bound = self.callee_save_reg_region if lower_bound <= location < upper_bound: return True # PPC saves LR in the header of the previous stack frame if ( self.global_info.arch.arch == Target.ArchEnum.PPC and location == self.allocated_stack_size + 4 ): return True return False def location_above_stack(self, location: int) -> bool: return location >= self.allocated_stack_size def add_known_param(self, offset: int, name: Optional[str], type: Type) -> None: # A common pattern in C for OOP-style polymorphism involves casting a general "base" struct # to a specific "class" struct, where the first member of the class struct is the base struct. # # For the first argument of the function, if it is a pointer to a base struct, and there # exists a class struct named after the first part of the function name, assume that # this pattern is being used. Internally, treat the argument as a pointer to the *class* # struct, even though it is only a pointer to the *base* struct in the provided context. if offset == 0 and type.is_pointer() and self.replace_first_arg is None: namespace = self.function.name.partition("_")[0] base_struct_type = type.get_pointer_target() self_struct = self.global_info.typepool.get_struct_by_tag_name( namespace, self.global_info.typemap ) if ( self_struct is not None and base_struct_type is not None and base_struct_type.is_struct() ): # Check if `self_struct_type` contains a `base_struct_type` at offset 0 self_struct_type = Type.struct(self_struct) field_path, field_type, _ = self_struct_type.get_field( offset=0, target_size=base_struct_type.get_size_bytes() ) if ( field_path is not None and field_type.unify(base_struct_type) and not self_struct_type.unify(base_struct_type) ): # Success, it looks like `self_struct_type` extends `base_struct_type`. # By default, name the local var `self`, unless the argument name is `thisx` then use `this` self.replace_first_arg = (name or "_self", type) name = "this" if name == "thisx" else "self" type = Type.ptr(Type.struct(self_struct)) if name: self.param_names[offset] = name _, arg = self.get_argument(offset) self.add_argument(arg) arg.type.unify(type) def get_param_name(self, offset: int) -> Optional[str]: return self.param_names.get(offset) def add_local_var(self, var: "LocalVar") -> None: if any(v.value == var.value for v in self.local_vars): return self.local_vars.append(var) # Make sure the local vars stay sorted in order on the stack. self.local_vars.sort(key=lambda v: v.value) def add_argument(self, arg: "PassedInArg") -> None: if any(a.value == arg.value for a in self.arguments): return self.arguments.append(arg) self.arguments.sort(key=lambda a: a.value) def get_argument(self, location: int) -> Tuple["Expression", "PassedInArg"]: real_location = location & -4 arg = PassedInArg( real_location, copied=True, stack_info=self, type=self.unique_type_for("arg", real_location, Type.any_reg()), ) if real_location == location - 3: return as_type(arg, Type.int_of_size(8), True), arg if real_location == location - 2: return as_type(arg, Type.int_of_size(16), True), arg return arg, arg def record_struct_access(self, ptr: "Expression", location: int) -> None: if location: self.nonzero_accesses.add(unwrap_deep(ptr)) def has_nonzero_access(self, ptr: "Expression") -> bool: return unwrap_deep(ptr) in self.nonzero_accesses def unique_type_for(self, category: str, key: object, default: Type) -> "Type": key = (category, key) if key not in self.unique_type_map: self.unique_type_map[key] = default return self.unique_type_map[key] def saved_reg_symbol(self, reg_name: str) -> "GlobalSymbol": sym_name = "saved_reg_" + reg_name type = self.unique_type_for("saved_reg", sym_name, Type.any_reg()) return GlobalSymbol(symbol_name=sym_name, type=type) def should_save(self, expr: "Expression", offset: Optional[int]) -> bool: expr = early_unwrap(expr) if isinstance(expr, GlobalSymbol) and ( expr.symbol_name.startswith("saved_reg_") or expr.symbol_name == "sp" ): return True if ( isinstance(expr, PassedInArg) and not expr.copied and (offset is None or offset == self.allocated_stack_size + expr.value) ): return True return False def get_stack_var(self, location: int, *, store: bool) -> "Expression": # See `get_stack_info` for explanation if self.in_callee_save_reg_region(location): # Some annoying bookkeeping instruction. To avoid # further special-casing, just return whatever - it won't matter. return LocalVar(location, type=Type.any_reg(), path=None) elif self.location_above_stack(location): ret, arg = self.get_argument(location - self.allocated_stack_size) if not store: self.add_argument(arg) return ret elif self.in_subroutine_arg_region(location): return SubroutineArg(location, type=Type.any_reg()) else: # Local variable assert self.stack_pointer_type is not None field_path, field_type, _ = self.stack_pointer_type.get_deref_field( location, target_size=None ) # Some variables on the stack are compiler-managed, and aren't declared # in the original source. These variables can have different types inside # different blocks, so we track their types but assume that they may change # on each store. # TODO: Because the types are tracked in StackInfo instead of RegInfo, it is # possible that a load could incorrectly use a weak type from a sibling node # instead of a parent node. A more correct implementation would use similar # logic to the PhiExpr system. In practice however, storing types in StackInfo # works well enough because nodes are traversed approximately depth-first. # TODO: Maybe only do this for certain configurable regions? # Get the previous type stored in `location` previous_stored_type = self.weak_stack_var_types.get(location) if previous_stored_type is not None: # Check if the `field_type` is compatible with the type of the last store if not previous_stored_type.unify(field_type): # The types weren't compatible: mark this `location` as "weak" # This marker is only used to annotate the output self.weak_stack_var_locations.add(location) if store: # If there's already been a store to `location`, then return a fresh type field_type = Type.any_field() else: # Use the type of the last store instead of the one from `get_deref_field()` field_type = previous_stored_type # Track the type last stored at `location` if store: self.weak_stack_var_types[location] = field_type return LocalVar(location, type=field_type, path=field_path) def maybe_get_register_var(self, reg: Register) -> Optional["RegisterVar"]: return self.reg_vars.get(reg) def add_register_var(self, reg: Register, name: str) -> None: type = Type.floatish() if reg.is_float() else Type.intptr() self.reg_vars[reg] = RegisterVar(reg=reg, type=type, name=name) def use_register_var(self, var: "RegisterVar") -> None: self.used_reg_vars.add(var.reg) def is_stack_reg(self, reg: Register) -> bool: if reg == self.global_info.arch.stack_pointer_reg: return True if reg == self.global_info.arch.frame_pointer_reg: return self.uses_framepointer return False def get_struct_type_map(self) -> Dict["Expression", Dict[int, Type]]: """Reorganize struct information in unique_type_map by var & offset""" struct_type_map: Dict[Expression, Dict[int, Type]] = {} for (category, key), type in self.unique_type_map.items(): if category != "struct": continue var, offset = typing.cast(Tuple[Expression, int], key) if var not in struct_type_map: struct_type_map[var] = {} struct_type_map[var][offset] = type return struct_type_map def __str__(self) -> str: return "\n".join( [ f"Stack info for function {self.function.name}:", f"Allocated stack size: {self.allocated_stack_size}", f"Leaf? {self.is_leaf}", f"Bounds of callee-saved vars region: {self.callee_save_reg_region}", f"Callee save registers: {self.callee_save_regs}", ] ) def get_stack_info( function: Function, global_info: "GlobalInfo", flow_graph: FlowGraph, ) -> StackInfo: arch = global_info.arch info = StackInfo(function, global_info, flow_graph) # The goal here is to pick out special instructions that provide information # about this function's stack setup. # # IDO puts local variables *above* the saved registers on the stack, but # GCC puts local variables *below* the saved registers. # To support both, we explicitly determine both the upper & lower bounds of the # saved registers. Then, we estimate the boundary of the subroutine arguments # by finding the lowest stack offset that is loaded from or computed. (This # assumes that the compiler will never reuse a section of stack for *both* # a local variable *and* a subroutine argument.) Anything within the stack frame, # but outside of these two regions, is considered a local variable. callee_saved_offsets: List[int] = [] # Track simple literal values stored into registers: MIPS compilers need a temp # reg to move the stack pointer more than 0x7FFF bytes. temp_reg_values: Dict[Register, int] = {} for inst in flow_graph.entry_node().block.instructions: arch_mnemonic = inst.arch_mnemonic(arch) if inst.mnemonic in arch.instrs_fn_call: break elif arch_mnemonic == "mips:addiu" and inst.args[0] == arch.stack_pointer_reg: # Moving the stack pointer on MIPS assert isinstance(inst.args[2], AsmLiteral) info.allocated_stack_size = abs(inst.args[2].signed_value()) elif ( arch_mnemonic == "mips:subu" and inst.args[0] == arch.stack_pointer_reg and inst.args[1] == arch.stack_pointer_reg and inst.args[2] in temp_reg_values ): # Moving the stack pointer more than 0x7FFF on MIPS # TODO: This instruction needs to be ignored later in translation, in the # same way that `addiu $sp, $sp, N` is ignored in handle_addi_real assert isinstance(inst.args[2], Register) info.allocated_stack_size = temp_reg_values[inst.args[2]] elif arch_mnemonic == "ppc:stwu" and inst.args[0] == arch.stack_pointer_reg: # Moving the stack pointer on PPC assert isinstance(inst.args[1], AsmAddressMode) assert isinstance(inst.args[1].lhs, AsmLiteral) info.allocated_stack_size = abs(inst.args[1].lhs.signed_value()) elif ( arch_mnemonic == "mips:move" and inst.args[0] == arch.frame_pointer_reg and inst.args[1] == arch.stack_pointer_reg ): # "move fp, sp" very likely means the code is compiled with frame # pointers enabled; thus fp should be treated the same as sp. info.uses_framepointer = True elif ( arch_mnemonic in [ "mips:sw", "mips:swc1", "mips:sdc1", "ppc:stw", "ppc:stmw", "ppc:stfd", "ppc:psq_st", ] and isinstance(inst.args[0], Register) and inst.args[0] in arch.saved_regs and isinstance(inst.args[1], AsmAddressMode) and inst.args[1].rhs == arch.stack_pointer_reg and ( inst.args[0] not in info.callee_save_regs or arch_mnemonic == "ppc:psq_st" ) ): # Initial saving of callee-save register onto the stack. if inst.args[0] in (arch.return_address_reg, Register("r0")): # Saving the return address on the stack. info.is_leaf = False # The registers & their stack accesses must be matched up in ArchAsm.parse for reg, mem in zip(inst.inputs, inst.outputs): if isinstance(reg, Register) and isinstance(mem, StackLocation): assert mem.symbolic_offset is None stack_offset = mem.offset if arch_mnemonic != "ppc:psq_st": # psq_st instructions store the same register as stfd, just # as packed singles instead. Prioritize the stfd. info.callee_save_regs.add(reg) callee_saved_offsets.append(stack_offset) elif arch_mnemonic == "ppc:mflr" and inst.args[0] == Register("r0"): info.is_leaf = False elif arch_mnemonic == "mips:li" and inst.args[0] in arch.temp_regs: assert isinstance(inst.args[0], Register) assert isinstance(inst.args[1], AsmLiteral) temp_reg_values[inst.args[0]] = inst.args[1].value elif ( arch_mnemonic == "mips:ori" and inst.args[0] == inst.args[1] and inst.args[0] in temp_reg_values ): assert isinstance(inst.args[0], Register) assert isinstance(inst.args[2], AsmLiteral) temp_reg_values[inst.args[0]] |= inst.args[2].value if not info.is_leaf: # Iterate over the whole function, not just the first basic block, # to estimate the boundary for the subroutine argument region info.subroutine_arg_top = info.allocated_stack_size for node in flow_graph.nodes: for inst in node.block.instructions: arch_mnemonic = inst.arch_mnemonic(arch) if ( arch_mnemonic in ["mips:lw", "mips:lwc1", "mips:ldc1", "ppc:lwz"] and isinstance(inst.args[1], AsmAddressMode) and inst.args[1].rhs == arch.stack_pointer_reg and inst.args[1].lhs_as_literal() >= 16 ): info.subroutine_arg_top = min( info.subroutine_arg_top, inst.args[1].lhs_as_literal() ) elif ( arch_mnemonic == "mips:addiu" and inst.args[0] != arch.stack_pointer_reg and inst.args[1] == arch.stack_pointer_reg and isinstance(inst.args[2], AsmLiteral) and inst.args[2].value < info.allocated_stack_size ): info.subroutine_arg_top = min( info.subroutine_arg_top, inst.args[2].value ) # Compute the bounds of the callee-saved register region, including padding if callee_saved_offsets: callee_saved_offsets.sort() bottom = callee_saved_offsets[0] # Both IDO & GCC save registers in two subregions: # (a) One for double-sized registers # (b) One for word-sized registers, padded to a multiple of 8 bytes # IDO has (a) lower than (b); GCC has (b) lower than (a) # Check that there are no gaps in this region, other than a single # 4-byte word between subregions. top = bottom internal_padding_added = False for offset in callee_saved_offsets: if offset != top: if not internal_padding_added and offset == top + 4: internal_padding_added = True else: raise DecompFailure( f"Gap in callee-saved word stack region. " f"Saved: {callee_saved_offsets}, " f"gap at: {offset} != {top}." ) top = offset + 4 info.callee_save_reg_region = (bottom, top) # Subroutine arguments must be at the very bottom of the stack, so they # must come after the callee-saved region info.subroutine_arg_top = min(info.subroutine_arg_top, bottom) # Use a struct to represent the stack layout. If the struct is provided in the context, # its fields will be used for variable types & names. stack_struct_name = f"_mips2c_stack_{function.name}" stack_struct = global_info.typepool.get_struct_by_tag_name( stack_struct_name, global_info.typemap ) if stack_struct is not None: if stack_struct.size != info.allocated_stack_size: raise DecompFailure( f"Function {function.name} has a provided stack type {stack_struct_name} " f"with size {stack_struct.size}, but the detected stack size was " f"{info.allocated_stack_size}." ) else: stack_struct = StructDeclaration.unknown( global_info.typepool, size=info.allocated_stack_size, tag_name=stack_struct_name, ) # Mark the struct as a stack struct so we never try to use a reference to the struct itself stack_struct.is_stack = True stack_struct.new_field_prefix = "sp" # This acts as the type of the $sp register info.stack_pointer_type = Type.ptr(Type.struct(stack_struct)) return info def format_hex(val: int) -> str: return format(val, "x").upper() def escape_byte(b: int) -> bytes: table = { b"\0": b"\\0", b"\b": b"\\b", b"\f": b"\\f", b"\n": b"\\n", b"\r": b"\\r", b"\t": b"\\t", b"\v": b"\\v", b"\\": b"\\\\", b'"': b'\\"', } bs = bytes([b]) if bs in table: return table[bs] if b < 0x20 or b in (0xFF, 0x7F): return f"\\x{b:02x}".encode("ascii") return bs @dataclass(eq=False) class Var: stack_info: StackInfo = field(repr=False) prefix: str num_usages: int = 0 name: Optional[str] = None def format(self, fmt: Formatter) -> str: if self.name is None: self.name = self.stack_info.temp_var(self.prefix) return self.name def __str__(self) -> str: return "<temp>" class Expression(abc.ABC): type: Type @abc.abstractmethod def dependencies(self) -> List["Expression"]: ... def use(self) -> None: """Mark an expression as "will occur in the output". Various subclasses override this to provide special behavior; for instance, EvalOnceExpr checks if it occurs more than once in the output and if so emits a temp. It is important to get the number of use() calls correct: * if use() is called but the expression is not emitted, it may cause function calls to be silently dropped. * if use() is not called but the expression is emitted, it may cause phi variables to be printed as unnamed-phi($reg), without any assignment to that phi. * if use() is called once but the expression is emitted twice, it may cause function calls to be duplicated.""" for expr in self.dependencies(): expr.use() @abc.abstractmethod def format(self, fmt: Formatter) -> str: ... def __str__(self) -> str: """Stringify an expression for debug purposes. The output can change depending on when this is called, e.g. because of EvalOnceExpr state. To avoid using it by accident, output is quoted.""" fmt = Formatter(debug=True) return '"' + self.format(fmt) + '"' class Condition(Expression): @abc.abstractmethod def negated(self) -> "Condition": ... class Statement(abc.ABC): @abc.abstractmethod def should_write(self) -> bool: ... @abc.abstractmethod def format(self, fmt: Formatter) -> str: ... def __str__(self) -> str: """Stringify a statement for debug purposes. The output can change depending on when this is called, e.g. because of EvalOnceExpr state. To avoid using it by accident, output is quoted.""" fmt = Formatter(debug=True) return '"' + self.format(fmt) + '"' @dataclass(frozen=True, eq=False) class ErrorExpr(Condition): desc: Optional[str] = None type: Type = field(default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [] def negated(self) -> "Condition": return self def format(self, fmt: Formatter) -> str: if self.desc is not None: return f"MIPS2C_ERROR({self.desc})" return "MIPS2C_ERROR()" @dataclass(frozen=True) class CommentExpr(Expression): expr: Expression type: Type = field(compare=False) prefix: Optional[str] = None suffix: Optional[str] = None def dependencies(self) -> List[Expression]: return [self.expr] def format(self, fmt: Formatter) -> str: expr_str = self.expr.format(fmt) if fmt.coding_style.comment_style == CodingStyle.CommentStyle.NONE: return expr_str prefix_str = f"/* {self.prefix} */ " if self.prefix is not None else "" suffix_str = f" /* {self.suffix} */" if self.suffix is not None else "" return f"{prefix_str}{expr_str}{suffix_str}" @staticmethod def wrap( expr: Expression, prefix: Optional[str] = None, suffix: Optional[str] = None ) -> Expression: if prefix is None and suffix is None: return expr return CommentExpr(expr=expr, type=expr.type, prefix=prefix, suffix=suffix) @dataclass(frozen=True, eq=False) class SecondF64Half(Expression): type: Type = field(default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: return "(second half of f64)" @dataclass(frozen=True, eq=False) class CarryBit(Expression): type: Type = field(default_factory=Type.intish) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: return "MIPS2C_CARRY" @staticmethod def add_to(expr: Expression) -> "BinaryOp": return fold_divmod(BinaryOp.intptr(expr, "+", CarryBit())) @staticmethod def sub_from(expr: Expression) -> "BinaryOp": return BinaryOp.intptr(expr, "-", UnaryOp("!", CarryBit(), type=Type.intish())) @dataclass(frozen=True, eq=False) class BinaryOp(Condition): left: Expression op: str right: Expression type: Type @staticmethod def int(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_intish(left), op=op, right=as_intish(right), type=Type.intish() ) @staticmethod def int64(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_int64(left), op=op, right=as_int64(right), type=Type.int64() ) @staticmethod def intptr(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_intptr(left), op=op, right=as_intptr(right), type=Type.intptr() ) @staticmethod def icmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_intptr(left), op=op, right=as_intptr(right), type=Type.bool() ) @staticmethod def scmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_sintish(left, silent=True), op=op, right=as_sintish(right, silent=True), type=Type.bool(), ) @staticmethod def sintptr_cmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_type(left, Type.sintptr(), False), op=op, right=as_type(right, Type.sintptr(), False), type=Type.bool(), ) @staticmethod def ucmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_uintish(left), op=op, right=as_uintish(right), type=Type.bool() ) @staticmethod def uintptr_cmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_type(left, Type.uintptr(), False), op=op, right=as_type(right, Type.uintptr(), False), type=Type.bool(), ) @staticmethod def fcmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_f32(left), op=op, right=as_f32(right), type=Type.bool(), ) @staticmethod def dcmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_f64(left), op=op, right=as_f64(right), type=Type.bool(), ) @staticmethod def sint( left: Expression, op: str, right: Expression, *, silent: bool = False ) -> "BinaryOp": return BinaryOp( left=as_sintish(left, silent=silent), op=op, right=as_sintish(right, silent=silent), type=Type.s32(), ) @staticmethod def uint(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_uintish(left), op=op, right=as_uintish(right), type=Type.u32() ) @staticmethod def s64(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp(left=as_s64(left), op=op, right=as_s64(right), type=Type.s64()) @staticmethod def u64(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp(left=as_u64(left), op=op, right=as_u64(right), type=Type.u64()) @staticmethod def f32(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_f32(left), op=op, right=as_f32(right), type=Type.f32(), ) @staticmethod def f64(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_f64(left), op=op, right=as_f64(right), type=Type.f64(), ) def is_comparison(self) -> bool: return self.op in ["==", "!=", ">", "<", ">=", "<="] def is_floating(self) -> bool: return self.left.type.is_float() and self.right.type.is_float() def negated(self) -> "Condition": if ( self.op in ["&&", "||"] and isinstance(self.left, Condition) and isinstance(self.right, Condition) ): # DeMorgan's Laws return BinaryOp( left=self.left.negated(), op={"&&": "||", "||": "&&"}[self.op], right=self.right.negated(), type=Type.bool(), ) if not self.is_comparison() or ( self.is_floating() and self.op in ["<", ">", "<=", ">="] ): # Floating-point comparisons cannot be negated in any nice way, # due to nans. return UnaryOp("!", self, type=Type.bool()) return BinaryOp( left=self.left, op={"==": "!=", "!=": "==", ">": "<=", "<": ">=", ">=": "<", "<=": ">"}[ self.op ], right=self.right, type=Type.bool(), ) def dependencies(self) -> List[Expression]: return [self.left, self.right] def format(self, fmt: Formatter) -> str: left_expr = late_unwrap(self.left) right_expr = late_unwrap(self.right) if ( self.is_comparison() and isinstance(left_expr, Literal) and not isinstance(right_expr, Literal) ): return BinaryOp( left=right_expr, op=self.op.translate(str.maketrans("<>", "><")), right=left_expr, type=self.type, ).format(fmt) if ( not self.is_floating() and isinstance(right_expr, Literal) and right_expr.value < 0 ): if self.op == "+": neg = Literal(value=-right_expr.value, type=right_expr.type) sub = BinaryOp(op="-", left=left_expr, right=neg, type=self.type) return sub.format(fmt) if self.op in ("&", "|"): neg = Literal(value=~right_expr.value, type=right_expr.type) right = UnaryOp("~", neg, type=Type.any_reg()) expr = BinaryOp(op=self.op, left=left_expr, right=right, type=self.type) return expr.format(fmt) # For commutative, left-associative operations, strip unnecessary parentheses. lhs = left_expr.format(fmt) if ( isinstance(left_expr, BinaryOp) and left_expr.op == self.op and self.op in ASSOCIATIVE_OPS ): lhs = lhs[1:-1] # For certain operators, use base-10 (decimal) for the RHS if self.op in ("/", "%") and isinstance(right_expr, Literal): rhs = right_expr.format(fmt, force_dec=True) else: rhs = right_expr.format(fmt) # These aren't real operators (or functions); format them as a fn call if self.op in PSEUDO_FUNCTION_OPS: return f"{self.op}({lhs}, {rhs})" return f"({lhs} {self.op} {rhs})" @dataclass(frozen=True, eq=False) class TernaryOp(Expression): cond: Condition left: Expression right: Expression type: Type def dependencies(self) -> List[Expression]: return [self.cond, self.left, self.right] def format(self, fmt: Formatter) -> str: cond_str = simplify_condition(self.cond).format(fmt) left_str = self.left.format(fmt) right_str = self.right.format(fmt) return f"({cond_str} ? {left_str} : {right_str})" @dataclass(frozen=True, eq=False) class UnaryOp(Condition): op: str expr: Expression type: Type def dependencies(self) -> List[Expression]: return [self.expr] @staticmethod def sint(op: str, expr: Expression) -> "UnaryOp": expr = as_sintish(expr, silent=True) return UnaryOp( op=op, expr=expr, type=expr.type, ) def negated(self) -> "Condition": if self.op == "!" and isinstance(self.expr, (UnaryOp, BinaryOp)): return self.expr return UnaryOp("!", self, type=Type.bool()) def format(self, fmt: Formatter) -> str: # These aren't real operators (or functions); format them as a fn call if self.op in PSEUDO_FUNCTION_OPS: return f"{self.op}({self.expr.format(fmt)})" return f"{self.op}{self.expr.format(fmt)}" @dataclass(frozen=True, eq=False) class ExprCondition(Condition): expr: Expression type: Type is_negated: bool = False def dependencies(self) -> List[Expression]: return [self.expr] def negated(self) -> "Condition": return ExprCondition(self.expr, self.type, not self.is_negated) def format(self, fmt: Formatter) -> str: neg = "!" if self.is_negated else "" return f"{neg}{self.expr.format(fmt)}" @dataclass(frozen=True, eq=False) class CommaConditionExpr(Condition): statements: List["Statement"] condition: "Condition" type: Type = Type.bool() def dependencies(self) -> List[Expression]: assert False, "CommaConditionExpr should not be used within translate.py" return [] def negated(self) -> "Condition": return CommaConditionExpr(self.statements, self.condition.negated()) def format(self, fmt: Formatter) -> str: comma_joined = ", ".join( stmt.format(fmt).rstrip(";") for stmt in self.statements ) return f"({comma_joined}, {self.condition.format(fmt)})" @dataclass(frozen=True, eq=False) class Cast(Expression): expr: Expression type: Type reinterpret: bool = False silent: bool = True def dependencies(self) -> List[Expression]: return [self.expr] def use(self) -> None: # Try to unify, to make stringification output better. self.expr.type.unify(self.type) super().use() def needed_for_store(self) -> bool: if not self.reinterpret: # int <-> float casts should be emitted even for stores. return True if not self.expr.type.unify(self.type): # Emit casts when types fail to unify. return True return False def is_trivial(self) -> bool: return ( self.reinterpret and self.expr.type.is_float() == self.type.is_float() and is_trivial_expression(self.expr) ) def format(self, fmt: Formatter) -> str: if self.reinterpret and self.expr.type.is_float() != self.type.is_float(): # This shouldn't happen, but mark it in the output if it does. if fmt.valid_syntax: return ( f"MIPS2C_BITWISE({self.type.format(fmt)}, {self.expr.format(fmt)})" ) return f"(bitwise {self.type.format(fmt)}) {self.expr.format(fmt)}" if self.reinterpret and ( self.silent or (is_type_obvious(self.expr) and self.expr.type.unify(self.type)) ): return self.expr.format(fmt) if fmt.skip_casts: return self.expr.format(fmt) # Function casts require special logic because function calls have # higher precedence than casts fn_sig = self.type.get_function_pointer_signature() if fn_sig: prototype_sig = self.expr.type.get_function_pointer_signature() if not prototype_sig or not prototype_sig.unify_with_args(fn_sig): # A function pointer cast is required if the inner expr is not # a function pointer, or has incompatible argument types return f"(({self.type.format(fmt)}) {self.expr.format(fmt)})" if not prototype_sig.return_type.unify(fn_sig.return_type): # Only cast the return value of the call return f"({fn_sig.return_type.format(fmt)}) {self.expr.format(fmt)}" # No cast needed return self.expr.format(fmt) return f"({self.type.format(fmt)}) {self.expr.format(fmt)}" @dataclass(frozen=True, eq=False) class FuncCall(Expression): function: Expression args: List[Expression] type: Type def dependencies(self) -> List[Expression]: return self.args + [self.function] def format(self, fmt: Formatter) -> str: # TODO: The function type may have a different number of params than it had # when the FuncCall was created. Should we warn that there may be the wrong # number of arguments at this callsite? args = ", ".join(format_expr(arg, fmt) for arg in self.args) return f"{self.function.format(fmt)}({args})" @dataclass(frozen=True, eq=True) class LocalVar(Expression): value: int type: Type = field(compare=False) path: Optional[AccessPath] = field(compare=False) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: fallback_name = f"unksp{format_hex(self.value)}" if self.path is None: return fallback_name name = StructAccess.access_path_to_field_name(self.path, fmt) if name.startswith("->"): return name[2:] return fallback_name def toplevel_decl(self, fmt: Formatter) -> Optional[str]: """Return a declaration for this LocalVar, if required.""" # If len(self.path) > 2, then this local is an inner field of another # local, so it doesn't need to be declared. if ( self.path is None or len(self.path) != 2 or not isinstance(self.path[1], str) ): return None return self.type.to_decl(self.path[1], fmt) @dataclass(frozen=True, eq=False) class RegisterVar(Expression): reg: Register name: str type: Type def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: return self.name @dataclass(frozen=True, eq=True) class PassedInArg(Expression): value: int copied: bool = field(compare=False) stack_info: StackInfo = field(compare=False, repr=False) type: Type = field(compare=False) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: assert self.value % 4 == 0 name = self.stack_info.get_param_name(self.value) return name or f"arg{format_hex(self.value // 4)}" @dataclass(frozen=True, eq=True) class SubroutineArg(Expression): value: int type: Type = field(compare=False) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: return f"subroutine_arg{format_hex(self.value // 4)}" @dataclass(eq=True, unsafe_hash=True) class StructAccess(Expression): # Represents struct_var->offset. # This has eq=True since it represents a live expression and not an access # at a certain point in time -- this sometimes helps get rid of phi nodes. # prevent_later_uses makes sure it's not used after writes/function calls # that may invalidate it. struct_var: Expression offset: int target_size: Optional[int] field_path: Optional[AccessPath] = field(compare=False) stack_info: Optional[StackInfo] = field(compare=False, repr=False) type: Type = field(compare=False) checked_late_field_path: bool = field(default=False, compare=False) def __post_init__(self) -> None: # stack_info is used to resolve field_path late assert ( self.stack_info is not None or self.field_path is not None ), "Must provide at least one of (stack_info, field_path)" self.assert_valid_field_path(self.field_path) @staticmethod def assert_valid_field_path(path: Optional[AccessPath]) -> None: assert path is None or ( path and isinstance(path[0], int) ), "The first element of the field path, if present, must be an int" @classmethod def access_path_to_field_name(cls, path: AccessPath, fmt: Formatter) -> str: """ Convert an access path into a dereferencing field name, like the following examples: - `[0, "foo", 3, "bar"]` into `"->foo[3].bar"` - `[0, 3, "bar"]` into `"[0][3].bar"` - `[0, 1, 2]` into `"[0][1][2]" - `[0]` into `"[0]"` The path must have at least one element, and the first element must be an int. """ cls.assert_valid_field_path(path) output = "" # Replace an initial "[0]." with "->" if len(path) >= 2 and path[0] == 0 and isinstance(path[1], str): output += f"->{path[1]}" path = path[2:] for p in path: if isinstance(p, str): output += f".{p}" elif isinstance(p, int): output += f"[{fmt.format_int(p)}]" else: static_assert_unreachable(p) return output def dependencies(self) -> List[Expression]: return [self.struct_var] def make_reference(self) -> Optional["StructAccess"]: field_path = self.late_field_path() if field_path and len(field_path) >= 2 and field_path[-1] == 0: return replace(self, field_path=field_path[:-1]) return None def late_field_path(self) -> Optional[AccessPath]: # If we didn't have a type at the time when the struct access was # constructed, but now we do, compute field name. if self.field_path is None and not self.checked_late_field_path: var = late_unwrap(self.struct_var) # Format var to recursively resolve any late_field_path it has to # potentially improve var.type before we look up our field name var.format(Formatter()) field_path, field_type, _ = var.type.get_deref_field( self.offset, target_size=self.target_size ) if field_path is not None: self.assert_valid_field_path(field_path) self.field_path = field_path self.type.unify(field_type) self.checked_late_field_path = True return self.field_path def late_has_known_type(self) -> bool: if self.late_field_path() is not None: return True assert ( self.stack_info is not None ), "StructAccess must have stack_info if field_path isn't set" if self.offset == 0: var = late_unwrap(self.struct_var) if ( not self.stack_info.has_nonzero_access(var) and isinstance(var, AddressOf) and isinstance(var.expr, GlobalSymbol) and var.expr.type_provided ): return True return False def format(self, fmt: Formatter) -> str: var = late_unwrap(self.struct_var) has_nonzero_access = False if self.stack_info is not None: has_nonzero_access = self.stack_info.has_nonzero_access(var) field_path = self.late_field_path() if field_path is not None and field_path != [0]: has_nonzero_access = True elif fmt.valid_syntax and (self.offset != 0 or has_nonzero_access): offset_str = fmt.format_int(self.offset) return f"MIPS2C_FIELD({var.format(fmt)}, {Type.ptr(self.type).format(fmt)}, {offset_str})" else: prefix = "unk" + ("_" if fmt.coding_style.unknown_underscore else "") field_path = [0, prefix + format_hex(self.offset)] field_name = self.access_path_to_field_name(field_path, fmt) # Rewrite `(&x)->y` to `x.y` by stripping `AddressOf` & setting deref=False deref = True if ( isinstance(var, AddressOf) and not var.expr.type.is_array() and field_name.startswith("->") ): var = var.expr field_name = field_name.replace("->", ".", 1) deref = False # Rewrite `x->unk0` to `*x` and `x.unk0` to `x`, unless has_nonzero_access if self.offset == 0 and not has_nonzero_access: return f"{'*' if deref else ''}{var.format(fmt)}" return f"{parenthesize_for_struct_access(var, fmt)}{field_name}" @dataclass(frozen=True, eq=True) class ArrayAccess(Expression): # Represents ptr[index]. eq=True for symmetry with StructAccess. ptr: Expression index: Expression type: Type = field(compare=False) def dependencies(self) -> List[Expression]: return [self.ptr, self.index] def format(self, fmt: Formatter) -> str: base = parenthesize_for_struct_access(self.ptr, fmt) index = format_expr(self.index, fmt) return f"{base}[{index}]" @dataclass(eq=False) class GlobalSymbol(Expression): symbol_name: str type: Type asm_data_entry: Optional[AsmDataEntry] = None symbol_in_context: bool = False type_provided: bool = False initializer_in_typemap: bool = False demangled_str: Optional[str] = None def dependencies(self) -> List[Expression]: return [] def is_string_constant(self) -> bool: ent = self.asm_data_entry if not ent or not ent.is_string: return False return len(ent.data) == 1 and isinstance(ent.data[0], bytes) def format_string_constant(self, fmt: Formatter) -> str: assert self.is_string_constant(), "checked by caller" assert self.asm_data_entry and isinstance(self.asm_data_entry.data[0], bytes) has_trailing_null = False data = self.asm_data_entry.data[0] while data and data[-1] == 0: data = data[:-1] has_trailing_null = True data = b"".join(map(escape_byte, data)) strdata = data.decode("utf-8", "backslashreplace") ret = f'"{strdata}"' if not has_trailing_null: ret += " /* not null-terminated */" return ret def format(self, fmt: Formatter) -> str: return self.symbol_name def potential_array_dim(self, element_size: int) -> Tuple[int, int]: """ Using the size of the symbol's `asm_data_entry` and a potential array element size, return the corresponding array dimension and number of "extra" bytes left at the end of the symbol's data. If the extra bytes are nonzero, then it's likely that `element_size` is incorrect. """ # If we don't have the .data/.rodata entry for this symbol, we can't guess # its array dimension. Jump tables are ignored and not treated as arrays. if self.asm_data_entry is None or self.asm_data_entry.is_jtbl: return 0, element_size min_data_size, max_data_size = self.asm_data_entry.size_range_bytes() if element_size > max_data_size: # The type is too big for the data (not an array) return 0, max_data_size # Check if it's possible that this symbol is not an array, and is just 1 element if min_data_size <= element_size <= max_data_size and not self.type.is_array(): return 1, 0 array_dim, extra_bytes = divmod(min_data_size, element_size) if extra_bytes != 0: # If it's not possible to make an exact multiple of element_size by incorporating # bytes from the padding, then indicate that in the return value. padding_bytes = element_size - extra_bytes if min_data_size + padding_bytes > max_data_size: return array_dim, extra_bytes # Include potential padding in the array. Although this is unlikely to match the original C, # it's much easier to manually remove all or some of these elements than to add them back in. return max_data_size // element_size, 0 @dataclass(frozen=True, eq=True) class Literal(Expression): value: int type: Type = field(compare=False, default_factory=Type.any) elide_cast: bool = field(compare=False, default=False) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter, force_dec: bool = False) -> str: enum_name = self.type.get_enum_name(self.value) if enum_name is not None: return enum_name if self.type.is_likely_float(): if self.type.get_size_bits() == 64: return format_f64_imm(self.value) else: return format_f32_imm(self.value) + "f" if self.type.is_pointer() and self.value == 0: return "NULL" prefix = "" suffix = "" if not fmt.skip_casts and not self.elide_cast: if self.type.is_pointer(): prefix = f"({self.type.format(fmt)})" if self.type.is_unsigned(): suffix = "U" if force_dec: value = str(self.value) else: size_bits = self.type.get_size_bits() v = self.value # The top 2 bits are tested rather than just the sign bit # to help prevent N64 VRAM pointers (0x80000000+) turning negative if ( self.type.is_signed() and size_bits and v & (1 << (size_bits - 1)) and v > (3 << (size_bits - 2)) and v < 2 ** size_bits ): v -= 1 << size_bits value = fmt.format_int(v, size_bits=size_bits) return prefix + value + suffix def likely_partial_offset(self) -> bool: return self.value % 2 ** 15 in (0, 2 ** 15 - 1) and self.value < 0x1000000 @dataclass(frozen=True, eq=True) class AddressOf(Expression): expr: Expression type: Type = field(compare=False, default_factory=Type.ptr) def dependencies(self) -> List[Expression]: return [self.expr] def format(self, fmt: Formatter) -> str: if isinstance(self.expr, GlobalSymbol): if self.expr.is_string_constant(): return self.expr.format_string_constant(fmt) if self.expr.type.is_array(): return f"{self.expr.format(fmt)}" if self.expr.type.is_function(): # Functions are automatically converted to function pointers # without an explicit `&` by the compiler return f"{self.expr.format(fmt)}" if isinstance(self.expr, StructAccess): # Simplify `&x[0]` into `x` ref = self.expr.make_reference() if ref: return f"{ref.format(fmt)}" return f"&{self.expr.format(fmt)}" @dataclass(frozen=True) class Lwl(Expression): load_expr: Expression key: Tuple[int, object] type: Type = field(compare=False, default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [self.load_expr] def format(self, fmt: Formatter) -> str: return f"MIPS2C_LWL({self.load_expr.format(fmt)})" @dataclass(frozen=True) class Load3Bytes(Expression): load_expr: Expression type: Type = field(compare=False, default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [self.load_expr] def format(self, fmt: Formatter) -> str: if fmt.valid_syntax: return f"MIPS2C_FIRST3BYTES({self.load_expr.format(fmt)})" return f"(first 3 bytes) {self.load_expr.format(fmt)}" @dataclass(frozen=True) class UnalignedLoad(Expression): load_expr: Expression type: Type = field(compare=False, default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [self.load_expr] def format(self, fmt: Formatter) -> str: if fmt.valid_syntax: return f"MIPS2C_UNALIGNED32({self.load_expr.format(fmt)})" return f"(unaligned s32) {self.load_expr.format(fmt)}" @dataclass(frozen=False, eq=False) class EvalOnceExpr(Expression): wrapped_expr: Expression var: Var type: Type # True for function calls/errors emit_exactly_once: bool # Mutable state: # True if this EvalOnceExpr should be totally transparent and not emit a variable, # It may dynamically change from true to false due to forced emissions. # Initially, it is based on is_trivial_expression. trivial: bool # True if this EvalOnceExpr must emit a variable (see RegMeta.force) forced_emit: bool = False # The number of expressions that depend on this EvalOnceExpr; we emit a variable # if this is > 1. num_usages: int = 0 def dependencies(self) -> List[Expression]: # (this is a bit iffy since state can change over time, but improves uses_expr) if self.need_decl(): return [] return [self.wrapped_expr] def use(self) -> None: self.num_usages += 1 if self.trivial or (self.num_usages == 1 and not self.emit_exactly_once): self.wrapped_expr.use() def force(self) -> None: # Transition to non-trivial, and mark as used multiple times to force a var. # TODO: If it was originally trivial, we may previously have marked its # wrappee used multiple times, even though we now know that it should # have been marked just once... We could fix that by moving marking of # trivial EvalOnceExpr's to the very end. At least the consequences of # getting this wrong are pretty mild -- it just causes extraneous var # emission in rare cases. self.trivial = False self.forced_emit = True self.use() self.use() def need_decl(self) -> bool: return self.num_usages > 1 and not self.trivial def format(self, fmt: Formatter) -> str: if not self.need_decl(): return self.wrapped_expr.format(fmt) else: return self.var.format(fmt) @dataclass(frozen=False, eq=False) class PhiExpr(Expression): reg: Register node: Node type: Type used_phis: List["PhiExpr"] name: Optional[str] = None num_usages: int = 0 replacement_expr: Optional[Expression] = None used_by: Optional["PhiExpr"] = None def dependencies(self) -> List[Expression]: return [] def get_var_name(self) -> str: return self.name or f"unnamed-phi({self.reg.register_name})" def use(self, from_phi: Optional["PhiExpr"] = None) -> None: if self.num_usages == 0: self.used_phis.append(self) self.used_by = from_phi self.num_usages += 1 if self.used_by != from_phi: self.used_by = None if self.replacement_expr is not None: self.replacement_expr.use() def propagates_to(self) -> "PhiExpr": """Compute the phi that stores to this phi should propagate to. This is usually the phi itself, but if the phi is only once for the purpose of computing another phi, we forward the store there directly. This is admittedly a bit sketchy, in case the phi is in scope here and used later on... but we have that problem with regular phi assignments as well.""" if self.used_by is None or self.replacement_expr is not None: return self return self.used_by.propagates_to() def format(self, fmt: Formatter) -> str: if self.replacement_expr: return self.replacement_expr.format(fmt) return self.get_var_name() @dataclass class SwitchControl: control_expr: Expression jump_table: Optional[GlobalSymbol] = None offset: int = 0 is_irregular: bool = False def matches_guard_condition(self, cond: Condition) -> bool: """ Return True if `cond` is one of: - `((control_expr + (-offset)) >= len(jump_table))`, if `offset != 0` - `(control_expr >= len(jump_table))`, if `offset == 0` These are the appropriate bounds checks before using `jump_table`. """ cmp_expr = simplify_condition(cond) if not isinstance(cmp_expr, BinaryOp) or cmp_expr.op not in (">=", ">"): return False cmp_exclusive = cmp_expr.op == ">" # The LHS may have been wrapped in a u32 cast left_expr = late_unwrap(cmp_expr.left) if isinstance(left_expr, Cast): left_expr = late_unwrap(left_expr.expr) if self.offset != 0: if ( not isinstance(left_expr, BinaryOp) or late_unwrap(left_expr.left) != late_unwrap(self.control_expr) or left_expr.op != "+" or late_unwrap(left_expr.right) != Literal(-self.offset) ): return False elif left_expr != late_unwrap(self.control_expr): return False right_expr = late_unwrap(cmp_expr.right) if ( self.jump_table is None or self.jump_table.asm_data_entry is None or not self.jump_table.asm_data_entry.is_jtbl or not isinstance(right_expr, Literal) ): return False # Count the number of labels (exclude padding bytes) jump_table_len = sum( isinstance(e, str) for e in self.jump_table.asm_data_entry.data ) return right_expr.value + int(cmp_exclusive) == jump_table_len @staticmethod def irregular_from_expr(control_expr: Expression) -> "SwitchControl": """ Return a SwitchControl representing a "irregular" switch statement. The switch does not have a single jump table; instead it is a series of if statements & other switches. """ return SwitchControl( control_expr=control_expr, jump_table=None, offset=0, is_irregular=True, ) @staticmethod def from_expr(expr: Expression) -> "SwitchControl": """ Try to convert `expr` into a SwitchControl from one of the following forms: - `*(&jump_table + (control_expr * 4))` - `*(&jump_table + ((control_expr + (-offset)) * 4))` If `offset` is not present, it defaults to 0. If `expr` does not match, return a thin wrapper around the input expression, with `jump_table` set to `None`. """ # The "error" expression we use if we aren't able to parse `expr` error_expr = SwitchControl(expr) # Match `*(&jump_table + (control_expr * 4))` struct_expr = early_unwrap(expr) if not isinstance(struct_expr, StructAccess) or struct_expr.offset != 0: return error_expr add_expr = early_unwrap(struct_expr.struct_var) if not isinstance(add_expr, BinaryOp) or add_expr.op != "+": return error_expr # Check for either `*(&jump_table + (control_expr * 4))` and `*((control_expr * 4) + &jump_table)` left_expr, right_expr = early_unwrap(add_expr.left), early_unwrap( add_expr.right ) if isinstance(left_expr, AddressOf) and isinstance( left_expr.expr, GlobalSymbol ): jtbl_addr_expr, mul_expr = left_expr, right_expr elif isinstance(right_expr, AddressOf) and isinstance( right_expr.expr, GlobalSymbol ): mul_expr, jtbl_addr_expr = left_expr, right_expr else: return error_expr jump_table = jtbl_addr_expr.expr assert isinstance(jump_table, GlobalSymbol) if ( not isinstance(mul_expr, BinaryOp) or mul_expr.op != "*" or early_unwrap(mul_expr.right) != Literal(4) ): return error_expr control_expr = mul_expr.left # Optionally match `control_expr + (-offset)` offset = 0 uw_control_expr = early_unwrap(control_expr) if isinstance(uw_control_expr, BinaryOp) and uw_control_expr.op == "+": offset_lit = early_unwrap(uw_control_expr.right) if isinstance(offset_lit, Literal): control_expr = uw_control_expr.left offset = -offset_lit.value # Check that it is really a jump table if jump_table.asm_data_entry is None or not jump_table.asm_data_entry.is_jtbl: return error_expr return SwitchControl(control_expr, jump_table, offset) @dataclass class EvalOnceStmt(Statement): expr: EvalOnceExpr def need_decl(self) -> bool: return self.expr.need_decl() def should_write(self) -> bool: if self.expr.emit_exactly_once: return self.expr.num_usages != 1 else: return self.need_decl() def format(self, fmt: Formatter) -> str: val_str = format_expr(elide_casts_for_store(self.expr.wrapped_expr), fmt) if self.expr.emit_exactly_once and self.expr.num_usages == 0: return f"{val_str};" return f"{self.expr.var.format(fmt)} = {val_str};" @dataclass class SetPhiStmt(Statement): phi: PhiExpr expr: Expression def should_write(self) -> bool: expr = self.expr if isinstance(expr, PhiExpr) and expr.propagates_to() != expr: # When we have phi1 = phi2, and phi2 is only used in this place, # the SetPhiStmt for phi2 will store directly to phi1 and we can # skip this store. assert expr.propagates_to() == self.phi.propagates_to() return False if late_unwrap(expr) == self.phi.propagates_to(): # Elide "phi = phi". return False return True def format(self, fmt: Formatter) -> str: return format_assignment(self.phi.propagates_to(), self.expr, fmt) @dataclass class ExprStmt(Statement): expr: Expression def should_write(self) -> bool: return True def format(self, fmt: Formatter) -> str: return f"{format_expr(self.expr, fmt)};" @dataclass class StoreStmt(Statement): source: Expression dest: Expression def should_write(self) -> bool: return True def format(self, fmt: Formatter) -> str: dest = self.dest source = self.source if ( isinstance(dest, StructAccess) and dest.late_has_known_type() ) or isinstance(dest, (ArrayAccess, LocalVar, RegisterVar, SubroutineArg)): # Known destination; fine to elide some casts. source = elide_casts_for_store(source) return format_assignment(dest, source, fmt) @dataclass class CommentStmt(Statement): contents: str def should_write(self) -> bool: return True def format(self, fmt: Formatter) -> str: return f"// {self.contents}" def error_stmt(msg: str) -> ExprStmt: return ExprStmt(ErrorExpr(msg)) @dataclass(frozen=True) class AddressMode: offset: int rhs: Register def __str__(self) -> str: if self.offset: return f"{self.offset}({self.rhs})" else: return f"({self.rhs})" @dataclass(frozen=True) class RawSymbolRef: offset: int sym: AsmGlobalSymbol def __str__(self) -> str: if self.offset: return f"{self.sym.symbol_name} + {self.offset}" else: return self.sym.symbol_name @dataclass class RegMeta: # True if this regdata is unchanged from the start of the block inherited: bool = False # True if this regdata is read by some later node is_read: bool = False # True if the value derives solely from function call return values function_return: bool = False # True if the value derives solely from regdata's with is_read = True, # function_return = True, or is a passed in argument uninteresting: bool = False # True if the regdata must be replaced by variable if it is ever read force: bool = False # True if the regdata was assigned by an Instruction marked as in_pattern; # it was part of a matched IR pattern but couldn't be elided at the time in_pattern: bool = False @dataclass class RegData: value: Expression meta: RegMeta @dataclass class RegInfo: stack_info: StackInfo = field(repr=False) contents: Dict[Register, RegData] = field(default_factory=dict) read_inherited: Set[Register] = field(default_factory=set) _active_instr: Optional[Instruction] = None def __getitem__(self, key: Register) -> Expression: if self._active_instr is not None and key not in self._active_instr.inputs: lineno = self._active_instr.meta.lineno return ErrorExpr(f"Read from unset register {key} on line {lineno}") if key == Register("zero"): return Literal(0) data = self.contents.get(key) if data is None: return ErrorExpr(f"Read from unset register {key}") ret = data.value data.meta.is_read = True if data.meta.inherited: self.read_inherited.add(key) if isinstance(ret, PassedInArg) and not ret.copied: # Create a new argument object to better distinguish arguments we # are called with from arguments passed to subroutines. Also, unify # the argument's type with what we can guess from the register used. val, arg = self.stack_info.get_argument(ret.value) self.stack_info.add_argument(arg) val.type.unify(ret.type) return val if data.meta.force: assert isinstance(ret, EvalOnceExpr) ret.force() return ret def __contains__(self, key: Register) -> bool: return key in self.contents def __setitem__(self, key: Register, value: Expression) -> None: self.set_with_meta(key, value, RegMeta()) def set_with_meta(self, key: Register, value: Expression, meta: RegMeta) -> None: if self._active_instr is not None and key not in self._active_instr.outputs: raise DecompFailure(f"Undeclared write to {key} in {self._active_instr}") self.unchecked_set_with_meta(key, value, meta) def unchecked_set_with_meta( self, key: Register, value: Expression, meta: RegMeta ) -> None: assert key != Register("zero") self.contents[key] = RegData(value, meta) def __delitem__(self, key: Register) -> None: assert key != Register("zero") del self.contents[key] def get_raw(self, key: Register) -> Optional[Expression]: data = self.contents.get(key) return data.value if data is not None else None def get_meta(self, key: Register) -> Optional[RegMeta]: data = self.contents.get(key) return data.meta if data is not None else None @contextmanager def current_instr(self, instr: Instruction) -> Iterator[None]: self._active_instr = instr try: with current_instr(instr): yield finally: self._active_instr = None def __str__(self) -> str: return ", ".join( f"{k}: {v.value}" for k, v in sorted(self.contents.items(), key=lambda x: x[0].register_name) if not self.stack_info.should_save(v.value, None) ) @dataclass class BlockInfo: """ Contains translated assembly code (to_write), the block's branch condition, and block's final register states. """ to_write: List[Statement] return_value: Optional[Expression] switch_control: Optional[SwitchControl] branch_condition: Optional[Condition] final_register_states: RegInfo has_function_call: bool def __str__(self) -> str: newline = "\n\t" return "\n".join( [ f"Statements: {newline.join(str(w) for w in self.statements_to_write())}", f"Branch condition: {self.branch_condition}", f"Final register states: {self.final_register_states}", ] ) def statements_to_write(self) -> List[Statement]: return [st for st in self.to_write if st.should_write()] def get_block_info(node: Node) -> BlockInfo: ret = node.block.block_info assert isinstance(ret, BlockInfo) return ret @dataclass class InstrArgs: raw_args: List[Argument] regs: RegInfo = field(repr=False) stack_info: StackInfo = field(repr=False) def raw_arg(self, index: int) -> Argument: assert index >= 0 if index >= len(self.raw_args): raise DecompFailure( f"Too few arguments for instruction, expected at least {index + 1}" ) return self.raw_args[index] def reg_ref(self, index: int) -> Register: ret = self.raw_arg(index) if not isinstance(ret, Register): raise DecompFailure( f"Expected instruction argument to be a register, but found {ret}" ) return ret def imm_value(self, index: int) -> int: arg = self.full_imm(index) assert isinstance(arg, Literal) return arg.value def reg(self, index: int) -> Expression: return self.regs[self.reg_ref(index)] def dreg(self, index: int) -> Expression: """Extract a double from a register. This may involve reading both the mentioned register and the next.""" reg = self.reg_ref(index) if not reg.is_float(): raise DecompFailure( f"Expected instruction argument {reg} to be a float register" ) ret = self.regs[reg] # PPC: FPR's hold doubles (64 bits), so we don't need to do anything special if self.stack_info.global_info.arch.arch == Target.ArchEnum.PPC: return ret # MIPS: Look at the paired FPR to get the full 64-bit value if not isinstance(ret, Literal) or ret.type.get_size_bits() == 64: return ret reg_num = int(reg.register_name[1:]) if reg_num % 2 != 0: raise DecompFailure( "Tried to use a double-precision instruction with odd-numbered float " f"register {reg}" ) other = self.regs[Register(f"f{reg_num+1}")] if not isinstance(other, Literal) or other.type.get_size_bits() == 64: raise DecompFailure( f"Unable to determine a value for double-precision register {reg} " "whose second half is non-static. This is a mips_to_c restriction " "which may be lifted in the future." ) value = ret.value | (other.value << 32) return Literal(value, type=Type.f64()) def cmp_reg(self, key: str) -> Condition: cond = self.regs[Register(key)] if not isinstance(cond, Condition): cond = BinaryOp.icmp(cond, "!=", Literal(0)) return cond def full_imm(self, index: int) -> Expression: arg = strip_macros(self.raw_arg(index)) ret = literal_expr(arg, self.stack_info) return ret def imm(self, index: int) -> Expression: ret = self.full_imm(index) if isinstance(ret, Literal): return Literal(((ret.value + 0x8000) & 0xFFFF) - 0x8000) return ret def unsigned_imm(self, index: int) -> Expression: ret = self.full_imm(index) if isinstance(ret, Literal): return Literal(ret.value & 0xFFFF) return ret def hi_imm(self, index: int) -> Argument: arg = self.raw_arg(index) if not isinstance(arg, Macro) or arg.macro_name not in ("hi", "ha", "h"): raise DecompFailure( f"Got lui/lis instruction with macro other than %hi/@ha/@h: {arg}" ) return arg.argument def shifted_imm(self, index: int) -> Expression: # TODO: Should this be part of hi_imm? Do we need to handle @ha? raw_imm = self.unsigned_imm(index) assert isinstance(raw_imm, Literal) return Literal(raw_imm.value << 16) def memory_ref(self, index: int) -> Union[AddressMode, RawSymbolRef]: ret = strip_macros(self.raw_arg(index)) # In MIPS, we want to allow "lw $v0, symbol + 4", which is outputted by # some disassemblers (like IDA) even though it isn't valid assembly. # For PPC, we want to allow "lwz $r1, symbol@sda21($r13)" where $r13 is # assumed to point to the start of a small data area (SDA). if isinstance(ret, AsmGlobalSymbol): return RawSymbolRef(offset=0, sym=ret) if ( isinstance(ret, BinOp) and ret.op in "+-" and isinstance(ret.lhs, AsmGlobalSymbol) and isinstance(ret.rhs, AsmLiteral) ): sign = 1 if ret.op == "+" else -1 return RawSymbolRef(offset=(ret.rhs.value * sign), sym=ret.lhs) if not isinstance(ret, AsmAddressMode): raise DecompFailure( "Expected instruction argument to be of the form offset($register), " f"but found {ret}" ) if not isinstance(ret.lhs, AsmLiteral): raise DecompFailure( f"Unable to parse offset for instruction argument {ret}. " "Expected a constant or a %lo macro." ) return AddressMode(offset=ret.lhs.signed_value(), rhs=ret.rhs) def count(self) -> int: return len(self.raw_args) def deref( arg: Union[AddressMode, RawSymbolRef, Expression], regs: RegInfo, stack_info: StackInfo, *, size: int, store: bool = False, ) -> Expression: if isinstance(arg, Expression): offset = 0 var = arg elif isinstance(arg, AddressMode): offset = arg.offset if stack_info.is_stack_reg(arg.rhs): return stack_info.get_stack_var(offset, store=store) var = regs[arg.rhs] else: offset = arg.offset var = stack_info.global_info.address_of_gsym(arg.sym.symbol_name) # Struct member is being dereferenced. # Cope slightly better with raw pointers. if isinstance(var, Literal) and var.value % (2 ** 16) == 0: var = Literal(var.value + offset, type=var.type) offset = 0 # Handle large struct offsets. uw_var = early_unwrap(var) if isinstance(uw_var, BinaryOp) and uw_var.op == "+": for base, addend in [(uw_var.left, uw_var.right), (uw_var.right, uw_var.left)]: if isinstance(addend, Literal) and addend.likely_partial_offset(): offset += addend.value var = base uw_var = early_unwrap(var) break var.type.unify(Type.ptr()) stack_info.record_struct_access(var, offset) field_name: Optional[str] = None type: Type = stack_info.unique_type_for("struct", (uw_var, offset), Type.any()) # Struct access with type information. array_expr = array_access_from_add( var, offset, stack_info, target_size=size, ptr=False ) if array_expr is not None: return array_expr field_path, field_type, _ = var.type.get_deref_field(offset, target_size=size) if field_path is not None: field_type.unify(type) type = field_type else: field_path = None return StructAccess( struct_var=var, offset=offset, target_size=size, field_path=field_path, stack_info=stack_info, type=type, ) def is_trivial_expression(expr: Expression) -> bool: # Determine whether an expression should be evaluated only once or not. if isinstance( expr, ( EvalOnceExpr, Literal, GlobalSymbol, LocalVar, PassedInArg, PhiExpr, RegisterVar, SubroutineArg, ), ): return True if isinstance(expr, AddressOf): return all(is_trivial_expression(e) for e in expr.dependencies()) if isinstance(expr, Cast): return expr.is_trivial() return False def is_type_obvious(expr: Expression) -> bool: """ Determine whether an expression's type is "obvious", e.g. because the expression refers to a variable which has a declaration. With perfect type information this this function would not be needed. This function may produce wrong results while code is being generated, since at that point we don't know the final status of EvalOnceExpr's. """ if isinstance( expr, ( Cast, Literal, AddressOf, LocalVar, PhiExpr, PassedInArg, RegisterVar, FuncCall, ), ): return True if isinstance(expr, EvalOnceExpr): if expr.need_decl(): return True return is_type_obvious(expr.wrapped_expr) return False def simplify_condition(expr: Expression) -> Expression: """ Simplify a boolean expression. This function may produce wrong results while code is being generated, since at that point we don't know the final status of EvalOnceExpr's. """ if isinstance(expr, EvalOnceExpr) and not expr.need_decl(): return simplify_condition(expr.wrapped_expr) if isinstance(expr, UnaryOp): inner = simplify_condition(expr.expr) if expr.op == "!" and isinstance(inner, Condition): return inner.negated() return UnaryOp(expr=inner, op=expr.op, type=expr.type) if isinstance(expr, BinaryOp): left = simplify_condition(expr.left) right = simplify_condition(expr.right) if isinstance(left, BinaryOp) and left.is_comparison() and right == Literal(0): if expr.op == "==": return simplify_condition(left.negated()) if expr.op == "!=": return left if ( expr.is_comparison() and isinstance(left, Literal) and not isinstance(right, Literal) ): return BinaryOp( left=right, op=expr.op.translate(str.maketrans("<>", "><")), right=left, type=expr.type, ) return BinaryOp(left=left, op=expr.op, right=right, type=expr.type) return expr def balanced_parentheses(string: str) -> bool: """ Check if parentheses in a string are balanced, ignoring any non-parenthesis characters. E.g. true for "(x())yz", false for ")(" or "(". """ bal = 0 for c in string: if c == "(": bal += 1 elif c == ")": if bal == 0: return False bal -= 1 return bal == 0 def format_expr(expr: Expression, fmt: Formatter) -> str: """Stringify an expression, stripping unnecessary parentheses around it.""" ret = expr.format(fmt) if ret.startswith("(") and balanced_parentheses(ret[1:-1]): return ret[1:-1] return ret def format_assignment(dest: Expression, source: Expression, fmt: Formatter) -> str: """Stringify `dest = source;`.""" dest = late_unwrap(dest) source = late_unwrap(source) if isinstance(source, BinaryOp) and source.op in COMPOUND_ASSIGNMENT_OPS: rhs = None if late_unwrap(source.left) == dest: rhs = source.right elif late_unwrap(source.right) == dest and source.op in ASSOCIATIVE_OPS: rhs = source.left if rhs is not None: return f"{dest.format(fmt)} {source.op}= {format_expr(rhs, fmt)};" return f"{dest.format(fmt)} = {format_expr(source, fmt)};" def parenthesize_for_struct_access(expr: Expression, fmt: Formatter) -> str: # Nested dereferences may need to be parenthesized. All other # expressions will already have adequate parentheses added to them. s = expr.format(fmt) if ( s.startswith("*") or s.startswith("&") or (isinstance(expr, Cast) and expr.needed_for_store()) ): return f"({s})" return s def elide_casts_for_store(expr: Expression) -> Expression: uw_expr = late_unwrap(expr) if isinstance(uw_expr, Cast) and not uw_expr.needed_for_store(): return elide_casts_for_store(uw_expr.expr) if isinstance(uw_expr, Literal) and uw_expr.type.is_int(): # Avoid suffixes for unsigned ints return replace(uw_expr, elide_cast=True) return uw_expr def uses_expr(expr: Expression, expr_filter: Callable[[Expression], bool]) -> bool: if expr_filter(expr): return True for e in expr.dependencies(): if uses_expr(e, expr_filter): return True return False def late_unwrap(expr: Expression) -> Expression: """ Unwrap EvalOnceExpr's, stopping at variable boundaries. This function may produce wrong results while code is being generated, since at that point we don't know the final status of EvalOnceExpr's. """ if isinstance(expr, EvalOnceExpr) and not expr.need_decl(): return late_unwrap(expr.wrapped_expr) if isinstance(expr, PhiExpr) and expr.replacement_expr is not None: return late_unwrap(expr.replacement_expr) return expr def early_unwrap(expr: Expression) -> Expression: """ Unwrap EvalOnceExpr's, even past variable boundaries. This is fine to use even while code is being generated, but disrespects decisions to use a temp for a value, so use with care. """ if ( isinstance(expr, EvalOnceExpr) and not expr.forced_emit and not expr.emit_exactly_once ): return early_unwrap(expr.wrapped_expr) return expr def early_unwrap_ints(expr: Expression) -> Expression: """ Unwrap EvalOnceExpr's, even past variable boundaries or through int Cast's This is a bit sketchier than early_unwrap(), but can be used for pattern matching. """ uw_expr = early_unwrap(expr) if isinstance(uw_expr, Cast) and uw_expr.reinterpret and uw_expr.type.is_int(): return early_unwrap_ints(uw_expr.expr) return uw_expr def unwrap_deep(expr: Expression) -> Expression: """ Unwrap EvalOnceExpr's, even past variable boundaries. This is generally a sketchy thing to do, try to avoid it. In particular: - the returned expression is not usable for emission, because it may contain accesses at an earlier point in time or an expression that should not be repeated. - just because unwrap_deep(a) == unwrap_deep(b) doesn't mean a and b are interchangable, because they may be computed in different places. """ if isinstance(expr, EvalOnceExpr): return unwrap_deep(expr.wrapped_expr) return expr def literal_expr(arg: Argument, stack_info: StackInfo) -> Expression: if isinstance(arg, AsmGlobalSymbol): return stack_info.global_info.address_of_gsym(arg.symbol_name) if isinstance(arg, AsmLiteral): return Literal(arg.value) if isinstance(arg, BinOp): lhs = literal_expr(arg.lhs, stack_info) rhs = literal_expr(arg.rhs, stack_info) return BinaryOp.int(left=lhs, op=arg.op, right=rhs) raise DecompFailure(f"Instruction argument {arg} must be a literal") def imm_add_32(expr: Expression) -> Expression: if isinstance(expr, Literal): return as_intish(Literal(expr.value + 32)) else: return BinaryOp.int(expr, "+", Literal(32)) def fn_op(fn_name: str, args: List[Expression], type: Type) -> FuncCall: fn_sig = FunctionSignature( return_type=type, params=[FunctionParam(type=arg.type) for arg in args], params_known=True, is_variadic=False, ) return FuncCall( function=GlobalSymbol(symbol_name=fn_name, type=Type.function(fn_sig)), args=args, type=type, ) def void_fn_op(fn_name: str, args: List[Expression]) -> ExprStmt: fn_call = fn_op(fn_name, args, Type.any_reg()) fn_call.use() return ExprStmt(fn_call) def load_upper(args: InstrArgs) -> Expression: arg = args.raw_arg(1) if not isinstance(arg, Macro): assert not isinstance( arg, Literal ), "normalize_instruction should convert lui/lis <literal> to li" raise DecompFailure( f"lui/lis argument must be a literal or %hi/@ha macro, found {arg}" ) hi_arg = args.hi_imm(1) if ( isinstance(hi_arg, BinOp) and hi_arg.op in "+-" and isinstance(hi_arg.lhs, AsmGlobalSymbol) and isinstance(hi_arg.rhs, AsmLiteral) ): sym = hi_arg.lhs offset = hi_arg.rhs.value * (-1 if hi_arg.op == "-" else 1) elif isinstance(hi_arg, AsmGlobalSymbol): sym = hi_arg offset = 0 else: raise DecompFailure(f"Invalid %hi/@ha argument {hi_arg}") stack_info = args.stack_info source = stack_info.global_info.address_of_gsym(sym.symbol_name) imm = Literal(offset) return handle_addi_real(args.reg_ref(0), None, source, imm, stack_info) def handle_convert(expr: Expression, dest_type: Type, source_type: Type) -> Cast: # int <-> float casts should be explicit silent = dest_type.data().kind != source_type.data().kind expr.type.unify(source_type) return Cast(expr=expr, type=dest_type, silent=silent, reinterpret=False) def handle_la(args: InstrArgs) -> Expression: target = args.memory_ref(1) stack_info = args.stack_info if isinstance(target, AddressMode): return handle_addi( InstrArgs( raw_args=[args.reg_ref(0), target.rhs, AsmLiteral(target.offset)], regs=args.regs, stack_info=args.stack_info, ) ) var = stack_info.global_info.address_of_gsym(target.sym.symbol_name) return add_imm(var, Literal(target.offset), stack_info) def handle_or(left: Expression, right: Expression) -> Expression: if left == right: # `or $rD, $rS, $rS` can be used to move $rS into $rD return left if isinstance(left, Literal) and isinstance(right, Literal): if (((left.value & 0xFFFF) == 0 and (right.value & 0xFFFF0000) == 0)) or ( (right.value & 0xFFFF) == 0 and (left.value & 0xFFFF0000) == 0 ): return Literal(value=(left.value | right.value)) # Regular bitwise OR. return BinaryOp.int(left=left, op="|", right=right) def handle_sltu(args: InstrArgs) -> Expression: right = args.reg(2) if args.reg_ref(1) == Register("zero"): # (0U < x) is equivalent to (x != 0) uw_right = early_unwrap(right) if isinstance(uw_right, BinaryOp) and uw_right.op == "^": # ((a ^ b) != 0) is equivalent to (a != b) return BinaryOp.icmp(uw_right.left, "!=", uw_right.right) return BinaryOp.icmp(right, "!=", Literal(0)) else: left = args.reg(1) return BinaryOp.ucmp(left, "<", right) def handle_sltiu(args: InstrArgs) -> Expression: left = args.reg(1) right = args.imm(2) if isinstance(right, Literal): value = right.value & 0xFFFFFFFF if value == 1: # (x < 1U) is equivalent to (x == 0) uw_left = early_unwrap(left) if isinstance(uw_left, BinaryOp) and uw_left.op == "^": # ((a ^ b) == 0) is equivalent to (a == b) return BinaryOp.icmp(uw_left.left, "==", uw_left.right) return BinaryOp.icmp(left, "==", Literal(0)) else: right = Literal(value) return BinaryOp.ucmp(left, "<", right) def handle_addi(args: InstrArgs) -> Expression: stack_info = args.stack_info source_reg = args.reg_ref(1) source = args.reg(1) imm = args.imm(2) # `(x + 0xEDCC)` is emitted as `((x + 0x10000) - 0x1234)`, # i.e. as an `addis` followed by an `addi` uw_source = early_unwrap(source) if ( isinstance(uw_source, BinaryOp) and uw_source.op == "+" and isinstance(uw_source.right, Literal) and uw_source.right.value % 0x10000 == 0 and isinstance(imm, Literal) ): return add_imm( uw_source.left, Literal(imm.value + uw_source.right.value), stack_info ) return handle_addi_real(args.reg_ref(0), source_reg, source, imm, stack_info) def handle_addis(args: InstrArgs) -> Expression: stack_info = args.stack_info source_reg = args.reg_ref(1) source = args.reg(1) imm = args.shifted_imm(2) return handle_addi_real(args.reg_ref(0), source_reg, source, imm, stack_info) def handle_addi_real( output_reg: Register, source_reg: Optional[Register], source: Expression, imm: Expression, stack_info: StackInfo, ) -> Expression: if source_reg is not None and stack_info.is_stack_reg(source_reg): # Adding to sp, i.e. passing an address. assert isinstance(imm, Literal) if stack_info.is_stack_reg(output_reg): # Changing sp. Just ignore that. return source # Keep track of all local variables that we take addresses of. var = stack_info.get_stack_var(imm.value, store=False) if isinstance(var, LocalVar): stack_info.add_local_var(var) return AddressOf(var, type=var.type.reference()) else: return add_imm(source, imm, stack_info) def add_imm(source: Expression, imm: Expression, stack_info: StackInfo) -> Expression: if imm == Literal(0): # addiu $reg1, $reg2, 0 is a move # (this happens when replacing %lo(...) by 0) return source elif source.type.is_pointer_or_array(): # Pointer addition (this may miss some pointers that get detected later; # unfortunately that's hard to do anything about with mips_to_c's single-pass # architecture). if isinstance(imm, Literal) and not imm.likely_partial_offset(): array_access = array_access_from_add( source, imm.value, stack_info, target_size=None, ptr=True ) if array_access is not None: return array_access field_path, field_type, _ = source.type.get_deref_field( imm.value, target_size=None ) if field_path is not None: return AddressOf( StructAccess( struct_var=source, offset=imm.value, target_size=None, field_path=field_path, stack_info=stack_info, type=field_type, ), type=field_type.reference(), ) if isinstance(imm, Literal): target = source.type.get_pointer_target() if target: target_size = target.get_size_bytes() if target_size and imm.value % target_size == 0: # Pointer addition. return BinaryOp( left=source, op="+", right=as_intish(imm), type=source.type ) return BinaryOp(left=source, op="+", right=as_intish(imm), type=Type.ptr()) elif isinstance(source, Literal) and isinstance(imm, Literal): return Literal(source.value + imm.value) else: # Regular binary addition. return BinaryOp.intptr(left=source, op="+", right=imm) def handle_load(args: InstrArgs, type: Type) -> Expression: # For now, make the cast silent so that output doesn't become cluttered. # Though really, it would be great to expose the load types somehow... size = type.get_size_bytes() assert size is not None expr = deref(args.memory_ref(1), args.regs, args.stack_info, size=size) # Detect rodata constants if isinstance(expr, StructAccess) and expr.offset == 0: target = early_unwrap(expr.struct_var) if ( isinstance(target, AddressOf) and isinstance(target.expr, GlobalSymbol) and type.is_likely_float() ): sym_name = target.expr.symbol_name ent = args.stack_info.global_info.asm_data_value(sym_name) if ( ent and ent.data and isinstance(ent.data[0], bytes) and len(ent.data[0]) >= size and ent.is_readonly and type.unify(target.expr.type) ): data = ent.data[0][:size] val: int if size == 4: (val,) = struct.unpack(">I", data) else: (val,) = struct.unpack(">Q", data) return Literal(value=val, type=type) return as_type(expr, type, silent=True) def deref_unaligned( arg: Union[AddressMode, RawSymbolRef], regs: RegInfo, stack_info: StackInfo, *, store: bool = False, ) -> Expression: # We don't know the correct size pass to deref. Passing None would signal that we # are taking an address, cause us to prefer entire substructs as referenced fields, # which would be confusing. Instead, we lie and pass 1. Hopefully nothing bad will # happen... return deref(arg, regs, stack_info, size=1, store=store) def handle_lwl(args: InstrArgs) -> Expression: # Unaligned load for the left part of a register (lwl can technically merge with # a pre-existing lwr, but doesn't in practice, so we treat this as a standard # destination-first operation) ref = args.memory_ref(1) expr = deref_unaligned(ref, args.regs, args.stack_info) key: Tuple[int, object] if isinstance(ref, AddressMode): key = (ref.offset, args.regs[ref.rhs]) else: key = (ref.offset, ref.sym) return Lwl(expr, key) def handle_lwr(args: InstrArgs) -> Expression: # Unaligned load for the right part of a register. This lwr may merge with an # existing lwl, if it loads from the same target but with an offset that's +3. uw_old_value = early_unwrap(args.reg(0)) ref = args.memory_ref(1) lwl_key: Tuple[int, object] if isinstance(ref, AddressMode): lwl_key = (ref.offset - 3, args.regs[ref.rhs]) else: lwl_key = (ref.offset - 3, ref.sym) if isinstance(uw_old_value, Lwl) and uw_old_value.key[0] == lwl_key[0]: return UnalignedLoad(uw_old_value.load_expr) if ref.offset % 4 == 2: left_mem_ref = replace(ref, offset=ref.offset - 2) load_expr = deref_unaligned(left_mem_ref, args.regs, args.stack_info) return Load3Bytes(load_expr) return ErrorExpr("Unable to handle lwr; missing a corresponding lwl") def make_store(args: InstrArgs, type: Type) -> Optional[StoreStmt]: size = type.get_size_bytes() assert size is not None stack_info = args.stack_info source_reg = args.reg_ref(0) source_raw = args.regs.get_raw(source_reg) if type.is_likely_float() and size == 8: source_val = args.dreg(0) else: source_val = args.reg(0) target = args.memory_ref(1) is_stack = isinstance(target, AddressMode) and stack_info.is_stack_reg(target.rhs) if ( is_stack and source_raw is not None and stack_info.should_save(source_raw, target.offset) ): # Elide register preserval. return None dest = deref(target, args.regs, stack_info, size=size, store=True) dest.type.unify(type) return StoreStmt(source=as_type(source_val, type, silent=is_stack), dest=dest) def make_storex(args: InstrArgs, type: Type) -> Optional[StoreStmt]: # "indexed stores" like `stwx rS, rA, rB` write `rS` into `(rA + rB)` size = type.get_size_bytes() assert size is not None source = args.reg(0) ptr = BinaryOp.intptr(left=args.reg(1), op="+", right=args.reg(2)) # TODO: Can we assume storex's are never used to save registers to the stack? dest = deref(ptr, args.regs, args.stack_info, size=size, store=True) dest.type.unify(type) return StoreStmt(source=as_type(source, type, silent=False), dest=dest) def handle_swl(args: InstrArgs) -> Optional[StoreStmt]: # swl in practice only occurs together with swr, so we can treat it as a regular # store, with the expression wrapped in UnalignedLoad if needed. source = args.reg(0) target = args.memory_ref(1) if not isinstance(early_unwrap(source), UnalignedLoad): source = UnalignedLoad(source) dest = deref_unaligned(target, args.regs, args.stack_info, store=True) return StoreStmt(source=source, dest=dest) def handle_swr(args: InstrArgs) -> Optional[StoreStmt]: expr = early_unwrap(args.reg(0)) target = args.memory_ref(1) if not isinstance(expr, Load3Bytes): # Elide swr's that don't come from 3-byte-loading lwr's; they probably # come with a corresponding swl which has already been emitted. return None real_target = replace(target, offset=target.offset - 2) dest = deref_unaligned(real_target, args.regs, args.stack_info, store=True) return StoreStmt(source=expr, dest=dest) def handle_sra(args: InstrArgs) -> Expression: lhs = args.reg(1) shift = args.imm(2) if isinstance(shift, Literal) and shift.value in [16, 24]: expr = early_unwrap(lhs) pow2 = 1 << shift.value if isinstance(expr, BinaryOp) and isinstance(expr.right, Literal): tp = Type.s16() if shift.value == 16 else Type.s8() rhs = expr.right.value if expr.op == "<<" and rhs == shift.value: return as_type(expr.left, tp, silent=False) elif expr.op == "<<" and rhs > shift.value: new_shift = fold_mul_chains( BinaryOp.int(expr.left, "<<", Literal(rhs - shift.value)) ) return as_type(new_shift, tp, silent=False) elif expr.op == "*" and rhs % pow2 == 0 and rhs != pow2: mul = BinaryOp.int(expr.left, "*", Literal(value=rhs // pow2)) return as_type(mul, tp, silent=False) return fold_divmod( BinaryOp(as_sintish(lhs), ">>", as_intish(shift), type=Type.s32()) ) def handle_conditional_move(args: InstrArgs, nonzero: bool) -> Expression: op = "!=" if nonzero else "==" type = Type.any_reg() return TernaryOp( BinaryOp.scmp(args.reg(2), op, Literal(0)), as_type(args.reg(1), type, silent=True), as_type(args.reg(0), type, silent=True), type, ) def format_f32_imm(num: int) -> str: packed = struct.pack(">I", num & (2 ** 32 - 1)) value = struct.unpack(">f", packed)[0] if not value or value == 4294967296.0: # Zero, negative zero, nan, or INT_MAX. return str(value) # Write values smaller than 1e-7 / greater than 1e7 using scientific notation, # and values in between using fixed point. if abs(math.log10(abs(value))) > 6.9: fmt_char = "e" elif abs(value) < 1: fmt_char = "f" else: fmt_char = "g" def fmt(prec: int) -> str: """Format 'value' with 'prec' significant digits/decimals, in either scientific or regular notation depending on 'fmt_char'.""" ret = ("{:." + str(prec) + fmt_char + "}").format(value) if fmt_char == "e": return ret.replace("e+", "e").replace("e0", "e").replace("e-0", "e-") if "e" in ret: # The "g" format character can sometimes introduce scientific notation if # formatting with too few decimals. If this happens, return an incorrect # value to prevent the result from being used. # # Since the value we are formatting is within (1e-7, 1e7) in absolute # value, it will at least be possible to format with 7 decimals, which is # less than float precision. Thus, this annoying Python limitation won't # lead to us outputting numbers with more precision than we really have. return "0" return ret # 20 decimals is more than enough for a float. Start there, then try to shrink it. prec = 20 while prec > 0: prec -= 1 value2 = float(fmt(prec)) if struct.pack(">f", value2) != packed: prec += 1 break if prec == 20: # Uh oh, even the original value didn't format correctly. Fall back to str(), # which ought to work. return str(value) ret = fmt(prec) if "." not in ret: ret += ".0" return ret def format_f64_imm(num: int) -> str: (value,) = struct.unpack(">d", struct.pack(">Q", num & (2 ** 64 - 1))) return str(value) def fold_divmod(original_expr: BinaryOp) -> BinaryOp: """ Return a new BinaryOp instance if this one can be simplified to a single / or % op. This involves simplifying expressions using MULT_HI, MULTU_HI, +, -, <<, >>, and /. In GCC 2.7.2, the code that generates these instructions is in expmed.c. See also https://ridiculousfish.com/blog/posts/labor-of-division-episode-i.html for a modern writeup of a similar algorithm. This optimization is also used by MWCC and modern compilers (but not IDO). """ mult_high_ops = ("MULT_HI", "MULTU_HI") possible_match_ops = mult_high_ops + ("-", "+", ">>") # Only operate on integer expressions of certain operations if original_expr.is_floating() or original_expr.op not in possible_match_ops: return original_expr # Use `early_unwrap_ints` instead of `early_unwrap` to ignore Casts to integer types # Although this discards some extra type information, this function largely ignores # sign/size information to stay simpler. The result will be made with BinaryOp.int() # regardless of input types. expr = original_expr left_expr = early_unwrap_ints(expr.left) right_expr = early_unwrap_ints(expr.right) divisor_shift = 0 # Detect signed power-of-two division: (x >> N) + MIPS2C_CARRY --> x / (1 << N) if ( isinstance(left_expr, BinaryOp) and left_expr.op == ">>" and isinstance(left_expr.right, Literal) and expr.op == "+" and isinstance(right_expr, CarryBit) ): new_denom = 1 << left_expr.right.value return BinaryOp.sint( left=left_expr.left, op="/", right=Literal(new_denom), silent=True, ) # Fold `/` with `>>`: ((x / N) >> M) --> x / (N << M) # NB: If x is signed, this is only correct if there is a sign-correcting subtraction term if ( isinstance(left_expr, BinaryOp) and left_expr.op == "/" and isinstance(left_expr.right, Literal) and expr.op == ">>" and isinstance(right_expr, Literal) ): new_denom = left_expr.right.value << right_expr.value if new_denom < (1 << 32): return BinaryOp.int( left=left_expr.left, op="/", right=Literal(new_denom), ) # Detect `%`: (x - ((x / y) * y)) --> x % y if expr.op == "-" and isinstance(right_expr, BinaryOp) and right_expr.op == "*": div_expr = early_unwrap_ints(right_expr.left) mod_base = early_unwrap_ints(right_expr.right) if ( isinstance(div_expr, BinaryOp) and early_unwrap_ints(div_expr.left) == left_expr ): # Accept either `(x / y) * y` or `(x >> N) * M` (where `1 << N == M`) divisor = early_unwrap_ints(div_expr.right) if (div_expr.op == "/" and divisor == mod_base) or ( div_expr.op == ">>" and isinstance(divisor, Literal) and isinstance(mod_base, Literal) and (1 << divisor.value) == mod_base.value ): return BinaryOp.int(left=left_expr, op="%", right=right_expr.right) # Detect dividing by a negative: ((x >> 31) - (x / N)) --> x / -N if ( expr.op == "-" and isinstance(left_expr, BinaryOp) and left_expr.op == ">>" and early_unwrap_ints(left_expr.right) == Literal(31) and isinstance(right_expr, BinaryOp) and right_expr.op == "/" and isinstance(right_expr.right, Literal) ): # Swap left_expr & right_expr, but replace the N in right_expr with -N left_expr, right_expr = ( replace(right_expr, right=Literal(-right_expr.right.value)), left_expr, ) # Remove outer error term: ((x / N) + ((x / N) >> 31)) --> x / N # As N gets close to (1 << 30), this is no longer a negligible error term if ( expr.op == "+" and isinstance(left_expr, BinaryOp) and left_expr.op == "/" and isinstance(left_expr.right, Literal) and left_expr.right.value <= (1 << 29) and isinstance(right_expr, BinaryOp) and early_unwrap_ints(right_expr.left) == left_expr and right_expr.op == ">>" and early_unwrap_ints(right_expr.right) == Literal(31) ): return left_expr # Remove outer error term: ((x / N) - (x >> 31)) --> x / N if ( expr.op == "-" and isinstance(left_expr, BinaryOp) and left_expr.op == "/" and isinstance(left_expr.right, Literal) and isinstance(right_expr, BinaryOp) and right_expr.op == ">>" and early_unwrap_ints(right_expr.right) == Literal(31) ): div_expr = left_expr shift_var_expr = early_unwrap_ints(right_expr.left) div_var_expr = early_unwrap_ints(div_expr.left) # Check if the LHS of the shift is the same var that we're dividing by if div_var_expr == shift_var_expr: if isinstance(div_expr.right, Literal) and div_expr.right.value >= ( 1 << 30 ): return BinaryOp.int( left=div_expr.left, op=div_expr.op, right=div_expr.right, ) return div_expr # If the var is under 32 bits, the error term may look like `(x << K) >> 31` instead if ( isinstance(shift_var_expr, BinaryOp) and early_unwrap_ints(div_expr.left) == early_unwrap_ints(shift_var_expr.left) and shift_var_expr.op == "<<" and isinstance(shift_var_expr.right, Literal) ): return div_expr # Shift on the result of the mul: MULT_HI(x, N) >> M, shift the divisor by M if ( isinstance(left_expr, BinaryOp) and expr.op == ">>" and isinstance(right_expr, Literal) ): divisor_shift += right_expr.value expr = left_expr left_expr = early_unwrap_ints(expr.left) right_expr = early_unwrap_ints(expr.right) # Normalize MULT_HI(N, x) to MULT_HI(x, N) if isinstance(left_expr, Literal) and not isinstance(right_expr, Literal): left_expr, right_expr = right_expr, left_expr # Remove inner addition: (MULT_HI(x, N) + x) >> M --> MULT_HI(x, N) >> M # MULT_HI performs signed multiplication, so the `+ x` acts as setting the 32nd bit # while having a result with the same sign as x. # We can ignore it because `round_div` can work with arbitrarily large constants if ( isinstance(left_expr, BinaryOp) and left_expr.op == "MULT_HI" and expr.op == "+" and early_unwrap_ints(left_expr.left) == right_expr ): expr = left_expr left_expr = early_unwrap_ints(expr.left) right_expr = early_unwrap_ints(expr.right) # Shift on the LHS of the mul: MULT_HI(x >> M, N) --> MULT_HI(x, N) >> M if ( expr.op in mult_high_ops and isinstance(left_expr, BinaryOp) and left_expr.op == ">>" and isinstance(left_expr.right, Literal) ): divisor_shift += left_expr.right.value left_expr = early_unwrap_ints(left_expr.left) # Instead of checking for the error term precisely, just check that # the quotient is "close enough" to the integer value def round_div(x: int, y: int) -> Optional[int]: if y <= 1: return None result = round(x / y) if x / (y + 1) <= result <= x / (y - 1): return result return None if expr.op in mult_high_ops and isinstance(right_expr, Literal): denom = round_div(1 << (32 + divisor_shift), right_expr.value) if denom is not None: return BinaryOp.int( left=left_expr, op="/", right=Literal(denom), ) return original_expr def replace_clz_shift(expr: BinaryOp) -> BinaryOp: """ Simplify an expression matching `CLZ(x) >> 5` into `x == 0`, and further simplify `(a - b) == 0` into `a == b`. """ # Check that the outer expression is `>>` if expr.is_floating() or expr.op != ">>": return expr # Match `CLZ(x) >> 5`, or return the original expr left_expr = early_unwrap_ints(expr.left) right_expr = early_unwrap_ints(expr.right) if not ( isinstance(left_expr, UnaryOp) and left_expr.op == "CLZ" and isinstance(right_expr, Literal) and right_expr.value == 5 ): return expr # If the inner `x` is `(a - b)`, return `a == b` sub_expr = early_unwrap(left_expr.expr) if ( isinstance(sub_expr, BinaryOp) and not sub_expr.is_floating() and sub_expr.op == "-" ): return BinaryOp.icmp(sub_expr.left, "==", sub_expr.right) return BinaryOp.icmp(left_expr.expr, "==", Literal(0, type=left_expr.expr.type)) def replace_bitand(expr: BinaryOp) -> Expression: """Detect expressions using `&` for truncating integer casts""" if not expr.is_floating() and expr.op == "&": if expr.right == Literal(0xFF): return as_type(expr.left, Type.int_of_size(8), silent=False) if expr.right == Literal(0xFFFF): return as_type(expr.left, Type.int_of_size(16), silent=False) return expr def fold_mul_chains(expr: Expression) -> Expression: """Simplify an expression involving +, -, * and << to a single multiplication, e.g. 4*x - x -> 3*x, or x<<2 -> x*4. This includes some logic for preventing folds of consecutive sll, and keeping multiplications by large powers of two as bitshifts at the top layer.""" def fold( expr: Expression, toplevel: bool, allow_sll: bool ) -> Tuple[Expression, int]: if isinstance(expr, BinaryOp): lbase, lnum = fold(expr.left, False, (expr.op != "<<")) rbase, rnum = fold(expr.right, False, (expr.op != "<<")) if expr.op == "<<" and isinstance(expr.right, Literal) and allow_sll: # Left-shifts by small numbers are easier to understand if # written as multiplications (they compile to the same thing). if toplevel and lnum == 1 and not (1 <= expr.right.value <= 4): return (expr, 1) return (lbase, lnum << expr.right.value) if ( expr.op == "*" and isinstance(expr.right, Literal) and (allow_sll or expr.right.value % 2 != 0) ): return (lbase, lnum * expr.right.value) if early_unwrap(lbase) == early_unwrap(rbase): if expr.op == "+": return (lbase, lnum + rnum) if expr.op == "-": return (lbase, lnum - rnum) if isinstance(expr, UnaryOp) and expr.op == "-" and not toplevel: base, num = fold(expr.expr, False, True) return (base, -num) if ( isinstance(expr, EvalOnceExpr) and not expr.emit_exactly_once and not expr.forced_emit ): base, num = fold(early_unwrap(expr), False, allow_sll) if num != 1 and is_trivial_expression(base): return (base, num) return (expr, 1) base, num = fold(expr, True, True) if num == 1: return expr return BinaryOp.int(left=base, op="*", right=Literal(num)) def array_access_from_add( expr: Expression, offset: int, stack_info: StackInfo, *, target_size: Optional[int], ptr: bool, ) -> Optional[Expression]: expr = early_unwrap(expr) if not isinstance(expr, BinaryOp) or expr.op != "+": return None base = expr.left addend = expr.right if addend.type.is_pointer_or_array() and not base.type.is_pointer_or_array(): base, addend = addend, base index: Expression scale: int uw_addend = early_unwrap(addend) if ( isinstance(uw_addend, BinaryOp) and uw_addend.op == "*" and isinstance(uw_addend.right, Literal) ): index = uw_addend.left scale = uw_addend.right.value elif ( isinstance(uw_addend, BinaryOp) and uw_addend.op == "<<" and isinstance(uw_addend.right, Literal) ): index = uw_addend.left scale = 1 << uw_addend.right.value else: index = addend scale = 1 if scale < 0: scale = -scale index = UnaryOp.sint("-", index) target_type = base.type.get_pointer_target() if target_type is None: return None uw_base = early_unwrap(base) typepool = stack_info.global_info.typepool # In `&x + index * scale`, if the type of `x` is not known, try to mark it as an array. # Skip the `scale = 1` case because this often indicates a complex `index` expression, # and is not actually a 1-byte array lookup. if ( scale > 1 and offset == 0 and isinstance(uw_base, AddressOf) and target_type.get_size_bytes() is None ): inner_type: Optional[Type] = None if ( isinstance(uw_base.expr, GlobalSymbol) and uw_base.expr.potential_array_dim(scale)[1] != 0 ): # For GlobalSymbols, use the size of the asm data to check the feasibility of being # an array with `scale`. This helps be more conservative around fake symbols. pass elif scale == 2: # This *could* be a struct, but is much more likely to be an int inner_type = Type.int_of_size(16) elif scale == 4: inner_type = Type.reg32(likely_float=False) elif typepool.unk_inference and isinstance(uw_base.expr, GlobalSymbol): # Make up a struct with a tag name based on the symbol & struct size. # Although `scale = 8` could indicate an array of longs/doubles, it seems more # common to be an array of structs. struct_name = f"_struct_{uw_base.expr.symbol_name}_0x{scale:X}" struct = typepool.get_struct_by_tag_name( struct_name, stack_info.global_info.typemap ) if struct is None: struct = StructDeclaration.unknown( typepool, size=scale, tag_name=struct_name ) elif struct.size != scale: # This should only happen if there was already a struct with this name in the context raise DecompFailure(f"sizeof(struct {struct_name}) != {scale:#x}") inner_type = Type.struct(struct) if inner_type is not None: # This might fail, if `uw_base.expr.type` can't be changed to an array uw_base.expr.type.unify(Type.array(inner_type, dim=None)) # This acts as a backup, and will usually succeed target_type.unify(inner_type) if target_type.get_size_bytes() == scale: # base[index] pass else: # base->subarray[index] sub_path, sub_type, remaining_offset = base.type.get_deref_field( offset, target_size=scale, exact=False ) # Check if the last item in the path is `0`, which indicates the start of an array # If it is, remove it: it will be replaced by `[index]` if sub_path is None or len(sub_path) < 2 or sub_path[-1] != 0: return None sub_path.pop() base = StructAccess( struct_var=base, offset=offset - remaining_offset, target_size=None, field_path=sub_path, stack_info=stack_info, type=sub_type, ) offset = remaining_offset target_type = sub_type ret: Expression = ArrayAccess(base, index, type=target_type) # Add .field if necessary by wrapping ret in StructAccess(AddressOf(...)) ret_ref = AddressOf(ret, type=ret.type.reference()) field_path, field_type, _ = ret_ref.type.get_deref_field( offset, target_size=target_size ) if offset != 0 or (target_size is not None and target_size != scale): ret = StructAccess( struct_var=ret_ref, offset=offset, target_size=target_size, field_path=field_path, stack_info=stack_info, type=field_type, ) if ptr: ret = AddressOf(ret, type=ret.type.reference()) return ret def handle_add(args: InstrArgs) -> Expression: lhs = args.reg(1) rhs = args.reg(2) stack_info = args.stack_info type = Type.intptr() # Because lhs & rhs are in registers, it shouldn't be possible for them to be arrays. # If they are, treat them the same as pointers anyways. if lhs.type.is_pointer_or_array(): type = Type.ptr() elif rhs.type.is_pointer_or_array(): type = Type.ptr() # addiu instructions can sometimes be emitted as addu instead, when the # offset is too large. if isinstance(rhs, Literal): return handle_addi_real(args.reg_ref(0), args.reg_ref(1), lhs, rhs, stack_info) if isinstance(lhs, Literal): return handle_addi_real(args.reg_ref(0), args.reg_ref(2), rhs, lhs, stack_info) expr = BinaryOp(left=as_intptr(lhs), op="+", right=as_intptr(rhs), type=type) folded_expr = fold_mul_chains(expr) if isinstance(folded_expr, BinaryOp): folded_expr = fold_divmod(folded_expr) if folded_expr is not expr: return folded_expr array_expr = array_access_from_add(expr, 0, stack_info, target_size=None, ptr=True) if array_expr is not None: return array_expr return expr def handle_add_float(args: InstrArgs) -> Expression: if args.reg_ref(1) == args.reg_ref(2): two = Literal(1 << 30, type=Type.f32()) return BinaryOp.f32(two, "*", args.reg(1)) return BinaryOp.f32(args.reg(1), "+", args.reg(2)) def handle_add_double(args: InstrArgs) -> Expression: if args.reg_ref(1) == args.reg_ref(2): two = Literal(1 << 62, type=Type.f64()) return BinaryOp.f64(two, "*", args.dreg(1)) return BinaryOp.f64(args.dreg(1), "+", args.dreg(2)) def handle_bgez(args: InstrArgs) -> Condition: expr = args.reg(0) uw_expr = early_unwrap(expr) if ( isinstance(uw_expr, BinaryOp) and uw_expr.op == "<<" and isinstance(uw_expr.right, Literal) ): shift = uw_expr.right.value bitand = BinaryOp.int(uw_expr.left, "&", Literal(1 << (31 - shift))) return UnaryOp("!", bitand, type=Type.bool()) return BinaryOp.scmp(expr, ">=", Literal(0)) def rlwi_mask(mask_begin: int, mask_end: int) -> int: # Compute the mask constant used by the rlwi* family of PPC instructions, # referred to as the `MASK(MB, ME)` function in the processor manual. # Bit 0 is the MSB, Bit 31 is the LSB bits_upto: Callable[[int], int] = lambda m: (1 << (32 - m)) - 1 all_ones = 0xFFFFFFFF if mask_begin <= mask_end: # Set bits inside the range, fully inclusive mask = bits_upto(mask_begin) - bits_upto(mask_end + 1) else: # Set bits from [31, mask_end] and [mask_begin, 0] mask = (bits_upto(mask_end + 1) - bits_upto(mask_begin)) ^ all_ones return mask def handle_rlwinm( source: Expression, shift: int, mask_begin: int, mask_end: int, simplify: bool = True, ) -> Expression: # TODO: Detect shift + truncate, like `(x << 2) & 0xFFF3` or `(x >> 2) & 0x3FFF` # The output of the rlwinm instruction is `ROTL(source, shift) & mask`. We write this as # ((source << shift) & mask) | ((source >> (32 - shift)) & mask) # and compute both OR operands (upper_bits and lower_bits respectively). all_ones = 0xFFFFFFFF mask = rlwi_mask(mask_begin, mask_end) left_shift = shift right_shift = 32 - shift left_mask = (all_ones << left_shift) & mask right_mask = (all_ones >> right_shift) & mask # We only simplify if the `simplify` argument is True, and there will be no `|` in the # resulting expression. If there is an `|`, the expression is best left as bitwise math simplify = simplify and not (left_mask and right_mask) if isinstance(source, Literal): upper_value = (source.value << left_shift) & mask lower_value = (source.value >> right_shift) & mask return Literal(upper_value | lower_value) upper_bits: Optional[Expression] if left_mask == 0: upper_bits = None else: upper_bits = source if left_shift != 0: upper_bits = BinaryOp.int( left=upper_bits, op="<<", right=Literal(left_shift) ) if simplify: upper_bits = fold_mul_chains(upper_bits) if left_mask != (all_ones << left_shift) & all_ones: upper_bits = BinaryOp.int(left=upper_bits, op="&", right=Literal(left_mask)) if simplify: upper_bits = replace_bitand(upper_bits) lower_bits: Optional[Expression] if right_mask == 0: lower_bits = None else: lower_bits = BinaryOp.uint(left=source, op=">>", right=Literal(right_shift)) if simplify: lower_bits = replace_clz_shift(fold_divmod(lower_bits)) if right_mask != (all_ones >> right_shift) & all_ones: lower_bits = BinaryOp.int( left=lower_bits, op="&", right=Literal(right_mask) ) if simplify: lower_bits = replace_bitand(lower_bits) if upper_bits is None and lower_bits is None: return Literal(0) elif upper_bits is None: assert lower_bits is not None return lower_bits elif lower_bits is None: return upper_bits else: return BinaryOp.int(left=upper_bits, op="|", right=lower_bits) def handle_rlwimi( base: Expression, source: Expression, shift: int, mask_begin: int, mask_end: int ) -> Expression: # This instruction reads from `base`, replaces some bits with values from `source`, then # writes the result back into the first register. This can be used to copy any contiguous # bitfield from `source` into `base`, and is commonly used when manipulating flags, such # as in `x |= 0x10` or `x &= ~0x10`. # It's generally more readable to write the mask with `~` (instead of computing the inverse here) mask_literal = Literal(rlwi_mask(mask_begin, mask_end)) mask = UnaryOp("~", mask_literal, type=Type.u32()) masked_base = BinaryOp.int(left=base, op="&", right=mask) if source == Literal(0): # If the source is 0, there are no bits inserted. (This may look like `x &= ~0x10`) return masked_base # Set `simplify=False` to keep the `inserted` expression as bitwise math instead of `*` or `/` inserted = handle_rlwinm(source, shift, mask_begin, mask_end, simplify=False) if inserted == mask_literal: # If this instruction will set all the bits in the mask, we can OR the values # together without masking the base. (`x |= 0xF0` instead of `x = (x & ~0xF0) | 0xF0`) return BinaryOp.int(left=base, op="|", right=inserted) return BinaryOp.int(left=masked_base, op="|", right=inserted) def handle_loadx(args: InstrArgs, type: Type) -> Expression: # "indexed loads" like `lwzx rD, rA, rB` read `(rA + rB)` into `rD` size = type.get_size_bytes() assert size is not None ptr = BinaryOp.intptr(left=args.reg(1), op="+", right=args.reg(2)) expr = deref(ptr, args.regs, args.stack_info, size=size) return as_type(expr, type, silent=True) def strip_macros(arg: Argument) -> Argument: """Replace %lo(...) by 0, and assert that there are no %hi(...). We assume that %hi's only ever occur in lui, where we expand them to an entire value, and not just the upper part. This preserves semantics in most cases (though not when %hi's are reused for different %lo's...)""" if isinstance(arg, Macro): if arg.macro_name in ["sda2", "sda21"]: return arg.argument if arg.macro_name == "hi": raise DecompFailure("%hi macro outside of lui") if arg.macro_name not in ["lo", "l"]: raise DecompFailure(f"Unrecognized linker macro %{arg.macro_name}") # This is sort of weird; for `symbol@l` we return 0 here and assume # that this @l is always perfectly paired with one other @ha. # However, with `literal@l`, we return the literal value, and assume it is # paired with another `literal@ha`. This lets us reuse `literal@ha` values, # but assumes that we never mix literals & symbols if isinstance(arg.argument, AsmLiteral): return AsmLiteral(arg.argument.value) return AsmLiteral(0) elif isinstance(arg, AsmAddressMode) and isinstance(arg.lhs, Macro): if arg.lhs.macro_name in ["sda2", "sda21"]: return arg.lhs.argument if arg.lhs.macro_name not in ["lo", "l"]: raise DecompFailure( f"Bad linker macro in instruction argument {arg}, expected %lo" ) return AsmAddressMode(lhs=AsmLiteral(0), rhs=arg.rhs) else: return arg @dataclass class AbiArgSlot: offset: int reg: Optional[Register] type: Type name: Optional[str] = None comment: Optional[str] = None @dataclass class Abi: arg_slots: List[AbiArgSlot] possible_slots: List[AbiArgSlot] def reg_always_set(node: Node, reg: Register, *, dom_set: bool) -> bool: if node.immediate_dominator is None: return False seen = {node.immediate_dominator} stack = node.parents[:] while stack: n = stack.pop() if n == node.immediate_dominator and not dom_set: return False if n in seen: continue seen.add(n) clobbered: Optional[bool] = None for instr in n.block.instructions: with current_instr(instr): if reg in instr.outputs: clobbered = False elif reg in instr.clobbers: clobbered = True if clobbered == True: return False if clobbered is None: stack.extend(n.parents) return True def pick_phi_assignment_nodes( reg: Register, nodes: List[Node], expr: Expression ) -> List[Node]: """ As part of `assign_phis()`, we need to pick a set of nodes where we can emit a `SetPhiStmt` that assigns the phi for `reg` to `expr`. The final register state for `reg` for each node in `nodes` is `expr`, so the best case would be finding a single dominating node for the assignment. """ # Find the set of nodes which dominate *all* of `nodes`, sorted by number # of dominators. (This puts "earlier" nodes at the beginning of the list.) dominators = sorted( set.intersection(*(node.dominators for node in nodes)), key=lambda n: len(n.dominators), ) # Check the dominators for a node with the correct final state for `reg` for node in dominators: regs = get_block_info(node).final_register_states raw = regs.get_raw(reg) meta = regs.get_meta(reg) if raw is None or meta is None or meta.force: continue if raw == expr: return [node] # We couldn't find anything, so fall back to the naive solution # TODO: In some cases there may be a better solution (e.g. one that requires 2 nodes) return nodes def assign_phis(used_phis: List[PhiExpr], stack_info: StackInfo) -> None: i = 0 # Iterate over used phis until there are no more remaining. New ones may # appear during iteration, hence the while loop. while i < len(used_phis): phi = used_phis[i] assert phi.num_usages > 0 assert len(phi.node.parents) >= 2 # Group parent nodes by the value of their phi register equivalent_nodes: DefaultDict[Expression, List[Node]] = defaultdict(list) for node in phi.node.parents: expr = get_block_info(node).final_register_states[phi.reg] expr.type.unify(phi.type) equivalent_nodes[expr].append(node) exprs = list(equivalent_nodes.keys()) first_uw = early_unwrap(exprs[0]) if all(early_unwrap(e) == first_uw for e in exprs[1:]): # All the phis have the same value (e.g. because we recomputed an # expression after a store, or restored a register after a function # call). Just use that value instead of introducing a phi node. # TODO: the unwrapping here is necessary, but also kinda sketchy: # we may set as replacement_expr an expression that really shouldn't # be repeated, e.g. a StructAccess. It would make sense to use less # eager unwrapping, and/or to emit an EvalOnceExpr at this point # (though it's too late for it to be able to participate in the # prevent_later_uses machinery). phi.replacement_expr = as_type(first_uw, phi.type, silent=True) for _ in range(phi.num_usages): first_uw.use() else: for expr, nodes in equivalent_nodes.items(): for node in pick_phi_assignment_nodes(phi.reg, nodes, expr): block_info = get_block_info(node) expr = block_info.final_register_states[phi.reg] if isinstance(expr, PhiExpr): # Explicitly mark how the expression is used if it's a phi, # so we can propagate phi sets (to get rid of temporaries). expr.use(from_phi=phi) else: expr.use() typed_expr = as_type(expr, phi.type, silent=True) block_info.to_write.append(SetPhiStmt(phi, typed_expr)) i += 1 name_counter: Dict[Register, int] = {} for phi in used_phis: if not phi.replacement_expr and phi.propagates_to() == phi: counter = name_counter.get(phi.reg, 0) + 1 name_counter[phi.reg] = counter output_reg_name = stack_info.function.reg_formatter.format(phi.reg) prefix = f"phi_{output_reg_name}" phi.name = f"{prefix}_{counter}" if counter > 1 else prefix stack_info.phi_vars.append(phi) def propagate_register_meta(nodes: List[Node], reg: Register) -> None: """Propagate RegMeta bits forwards/backwards.""" non_terminal: List[Node] = [n for n in nodes if not isinstance(n, TerminalNode)] # Set `is_read` based on `read_inherited`. for n in non_terminal: if reg in get_block_info(n).final_register_states.read_inherited: for p in n.parents: par_meta = get_block_info(p).final_register_states.get_meta(reg) if par_meta: par_meta.is_read = True # Propagate `is_read` backwards. todo = non_terminal[:] while todo: n = todo.pop() meta = get_block_info(n).final_register_states.get_meta(reg) for p in n.parents: par_meta = get_block_info(p).final_register_states.get_meta(reg) if (par_meta and not par_meta.is_read) and ( meta and meta.inherited and meta.is_read ): par_meta.is_read = True todo.append(p) # Set `uninteresting` and propagate it, `function_return`, and `in_pattern` forwards. # Start by assuming inherited values are all set; they will get unset iteratively, # but for cyclic dependency purposes we want to assume them set. for n in non_terminal: meta = get_block_info(n).final_register_states.get_meta(reg) if meta: if meta.inherited: meta.uninteresting = True meta.function_return = True meta.in_pattern = True else: meta.uninteresting |= ( meta.is_read or meta.function_return or meta.in_pattern ) todo = non_terminal[:] while todo: n = todo.pop() if isinstance(n, TerminalNode): continue meta = get_block_info(n).final_register_states.get_meta(reg) if not meta or not meta.inherited: continue all_uninteresting = True all_function_return = True all_in_pattern = True for p in n.parents: par_meta = get_block_info(p).final_register_states.get_meta(reg) if par_meta: all_uninteresting &= par_meta.uninteresting all_function_return &= par_meta.function_return all_in_pattern &= par_meta.in_pattern if meta.uninteresting and not all_uninteresting and not meta.is_read: meta.uninteresting = False todo.extend(n.children()) if meta.function_return and not all_function_return: meta.function_return = False todo.extend(n.children()) if meta.in_pattern and not all_in_pattern: meta.in_pattern = False todo.extend(n.children()) def determine_return_register( return_blocks: List[BlockInfo], fn_decl_provided: bool, arch: Arch ) -> Optional[Register]: """Determine which of the arch's base_return_regs (i.e. v0, f0) is the most likely to contain the return value, or if the function is likely void.""" def priority(block_info: BlockInfo, reg: Register) -> int: meta = block_info.final_register_states.get_meta(reg) if not meta: return 4 if meta.uninteresting: return 2 if meta.in_pattern: return 1 if meta.function_return: return 0 return 3 if not return_blocks: return None best_reg: Optional[Register] = None best_prio = -1 for reg in arch.base_return_regs: prios = [priority(b, reg) for b in return_blocks] max_prio = max(prios) if max_prio == 4: # Register is not always set, skip it continue if max_prio <= 2 and not fn_decl_provided: # Register is always read after being written, or comes from a # function call; seems unlikely to be an intentional return. # Skip it, unless we have a known non-void return type. continue if max_prio > best_prio: best_prio = max_prio best_reg = reg return best_reg def translate_node_body(node: Node, regs: RegInfo, stack_info: StackInfo) -> BlockInfo: """ Given a node and current register contents, return a BlockInfo containing the translated AST for that node. """ to_write: List[Union[Statement]] = [] local_var_writes: Dict[LocalVar, Tuple[Register, Expression]] = {} subroutine_args: Dict[int, Expression] = {} branch_condition: Optional[Condition] = None switch_expr: Optional[Expression] = None has_custom_return: bool = False has_function_call: bool = False in_pattern: bool = False arch = stack_info.global_info.arch def eval_once( expr: Expression, *, emit_exactly_once: bool, trivial: bool, prefix: str = "", reuse_var: Optional[Var] = None, ) -> EvalOnceExpr: if emit_exactly_once: # (otherwise this will be marked used once num_usages reaches 1) expr.use() elif "_fictive_" in prefix and isinstance(expr, EvalOnceExpr): # Avoid creating additional EvalOnceExprs for fictive Registers # so they're less likely to appear in the output return expr assert reuse_var or prefix if prefix == "condition_bit": prefix = "cond" var = reuse_var or Var(stack_info, "temp_" + prefix) expr = EvalOnceExpr( wrapped_expr=expr, var=var, type=expr.type, emit_exactly_once=emit_exactly_once, trivial=trivial, ) var.num_usages += 1 stmt = EvalOnceStmt(expr) to_write.append(stmt) stack_info.temp_vars.append(stmt) return expr def prevent_later_uses(expr_filter: Callable[[Expression], bool]) -> None: """Prevent later uses of registers whose contents match a callback filter.""" for r in regs.contents.keys(): data = regs.contents.get(r) assert data is not None expr = data.value if not data.meta.force and expr_filter(expr): # Mark the register as "if used, emit the expression's once # var". We usually always have a once var at this point, # but if we don't, create one. if not isinstance(expr, EvalOnceExpr): expr = eval_once( expr, emit_exactly_once=False, trivial=False, prefix=stack_info.function.reg_formatter.format(r), ) # This write isn't changing the value of the register; it didn't need # to be declared as part of the current instruction's inputs/outputs. regs.unchecked_set_with_meta(r, expr, replace(data.meta, force=True)) def prevent_later_value_uses(sub_expr: Expression) -> None: """Prevent later uses of registers that recursively contain a given subexpression.""" # Unused PassedInArg are fine; they can pass the uses_expr test simply based # on having the same variable name. If we didn't filter them out here it could # cause them to be incorrectly passed as function arguments -- the function # call logic sees an opaque wrapper and doesn't realize that they are unused # arguments that should not be passed on. prevent_later_uses( lambda e: uses_expr(e, lambda e2: e2 == sub_expr) and not (isinstance(e, PassedInArg) and not e.copied) ) def prevent_later_function_calls() -> None: """Prevent later uses of registers that recursively contain a function call.""" prevent_later_uses(lambda e: uses_expr(e, lambda e2: isinstance(e2, FuncCall))) def prevent_later_reads() -> None: """Prevent later uses of registers that recursively contain a read.""" contains_read = lambda e: isinstance(e, (StructAccess, ArrayAccess)) prevent_later_uses(lambda e: uses_expr(e, contains_read)) def set_reg_maybe_return(reg: Register, expr: Expression) -> None: regs.set_with_meta(reg, expr, RegMeta(in_pattern=in_pattern)) def set_reg(reg: Register, expr: Optional[Expression]) -> Optional[Expression]: if expr is None: if reg in regs: del regs[reg] return None if isinstance(expr, LocalVar): if ( isinstance(node, ReturnNode) and stack_info.maybe_get_register_var(reg) and stack_info.in_callee_save_reg_region(expr.value) and reg in stack_info.callee_save_regs ): # Elide saved register restores with --reg-vars (it doesn't # matter in other cases). return None if expr in local_var_writes: # Elide register restores (only for the same register for now, # to be conversative). orig_reg, orig_expr = local_var_writes[expr] if orig_reg == reg: expr = orig_expr uw_expr = expr if not isinstance(expr, Literal): expr = eval_once( expr, emit_exactly_once=False, trivial=is_trivial_expression(expr), prefix=stack_info.function.reg_formatter.format(reg), ) if reg == Register("zero"): # Emit the expression as is. It's probably a volatile load. expr.use() to_write.append(ExprStmt(expr)) else: dest = stack_info.maybe_get_register_var(reg) if dest is not None: stack_info.use_register_var(dest) # Avoid emitting x = x, but still refresh EvalOnceExpr's etc. if not (isinstance(uw_expr, RegisterVar) and uw_expr.reg == reg): source = as_type(expr, dest.type, True) source.use() to_write.append(StoreStmt(source=source, dest=dest)) expr = dest set_reg_maybe_return(reg, expr) return expr def clear_caller_save_regs() -> None: for reg in arch.temp_regs: if reg in regs: del regs[reg] def maybe_clear_local_var_writes(func_args: List[Expression]) -> None: # Clear the `local_var_writes` dict if any of the `func_args` contain # a reference to a stack var. (The called function may modify the stack, # replacing the value we have in `local_var_writes`.) for arg in func_args: if uses_expr( arg, lambda expr: isinstance(expr, AddressOf) and isinstance(expr.expr, LocalVar), ): local_var_writes.clear() return def process_instr(instr: Instruction) -> None: nonlocal branch_condition, switch_expr, has_function_call, in_pattern in_pattern = instr.in_pattern mnemonic = instr.mnemonic arch_mnemonic = instr.arch_mnemonic(arch) args = InstrArgs(instr.args, regs, stack_info) expr: Expression # Figure out what code to generate! if mnemonic in arch.instrs_ignore: pass elif mnemonic in arch.instrs_store or mnemonic in arch.instrs_store_update: # Store a value in a permanent place. if mnemonic in arch.instrs_store: to_store = arch.instrs_store[mnemonic](args) else: # PPC specific store-and-update instructions # `stwu r3, 8(r4)` is equivalent to `$r3 = *($r4 + 8); $r4 += 8;` to_store = arch.instrs_store_update[mnemonic](args) # Update the register in the second argument update = args.memory_ref(1) if not isinstance(update, AddressMode): raise DecompFailure( f"Unhandled store-and-update arg in {instr}: {update!r}" ) set_reg( update.rhs, add_imm(args.regs[update.rhs], Literal(update.offset), stack_info), ) if to_store is None: # Elided register preserval. pass elif isinstance(to_store.dest, SubroutineArg): # About to call a subroutine with this argument. Skip arguments for the # first four stack slots; they are also passed in registers. if to_store.dest.value >= 0x10: subroutine_args[to_store.dest.value] = to_store.source else: if isinstance(to_store.dest, LocalVar): stack_info.add_local_var(to_store.dest) raw_value = to_store.source if isinstance(raw_value, Cast) and raw_value.reinterpret: # When preserving values on the stack across function calls, # ignore the type of the stack variable. The same stack slot # might be used to preserve values of different types. raw_value = raw_value.expr local_var_writes[to_store.dest] = (args.reg_ref(0), raw_value) # Emit a write. This includes four steps: # - mark the expression as used (since writes are always emitted) # - mark the dest used (if it's a struct access it needs to be # evaluated, though ideally we would not mark the top-level expression # used; it may cause early emissions that shouldn't happen) # - mark other usages of the dest as "emit before this point if used". # - emit the actual write. # # Note that the prevent_later_value_uses step happens after use(), since # the stored expression is allowed to reference its destination var, # but before the write is written, since prevent_later_value_uses might # emit writes of its own that should go before this write. In practice # that probably never occurs -- all relevant register contents should be # EvalOnceExpr's that can be emitted at their point of creation, but # I'm not 100% certain that that's always the case and will remain so. to_store.source.use() to_store.dest.use() prevent_later_value_uses(to_store.dest) prevent_later_function_calls() to_write.append(to_store) elif mnemonic in arch.instrs_source_first: # Just 'mtc1'. It's reversed, so we have to specially handle it. set_reg(args.reg_ref(1), arch.instrs_source_first[mnemonic](args)) elif mnemonic in arch.instrs_branches: assert branch_condition is None branch_condition = arch.instrs_branches[mnemonic](args) elif mnemonic in arch.instrs_float_branches: assert branch_condition is None cond_bit = regs[Register("condition_bit")] if not isinstance(cond_bit, BinaryOp): cond_bit = ExprCondition(cond_bit, type=cond_bit.type) if arch_mnemonic == "mips:bc1t": branch_condition = cond_bit elif arch_mnemonic == "mips:bc1f": branch_condition = cond_bit.negated() elif mnemonic in arch.instrs_jumps: if arch_mnemonic == "ppc:bctr": # Switch jump assert isinstance(node, SwitchNode) switch_expr = args.regs[Register("ctr")] elif arch_mnemonic == "mips:jr": # MIPS: if args.reg_ref(0) == arch.return_address_reg: # Return from the function. assert isinstance(node, ReturnNode) else: # Switch jump. assert isinstance(node, SwitchNode) switch_expr = args.reg(0) elif arch_mnemonic == "ppc:blr": assert isinstance(node, ReturnNode) else: assert False, f"Unhandled jump mnemonic {arch_mnemonic}" elif mnemonic in arch.instrs_fn_call: if arch_mnemonic in ["mips:jal", "ppc:bl"]: fn_target = args.imm(0) if not ( ( isinstance(fn_target, AddressOf) and isinstance(fn_target.expr, GlobalSymbol) ) or isinstance(fn_target, Literal) ): raise DecompFailure( f"Target of function call must be a symbol, not {fn_target}" ) elif arch_mnemonic == "ppc:blrl": fn_target = args.regs[Register("lr")] elif arch_mnemonic == "ppc:bctrl": fn_target = args.regs[Register("ctr")] elif arch_mnemonic == "mips:jalr": fn_target = args.reg(1) else: assert False, f"Unhandled fn call mnemonic {arch_mnemonic}" fn_target = as_function_ptr(fn_target) fn_sig = fn_target.type.get_function_pointer_signature() assert fn_sig is not None, "known function pointers must have a signature" likely_regs: Dict[Register, bool] = {} for reg, data in regs.contents.items(): # We use a much stricter filter for PPC than MIPS, because the same # registers can be used arguments & return values. # The ABI can also mix & match the rN & fN registers, which makes the # "require" heuristic less powerful. # # - `meta.inherited` will only be False for registers set in *this* basic block # - `meta.function_return` will only be accurate for registers set within this # basic block because we have not called `propagate_register_meta` yet. # Within this block, it will be True for registers that were return values. if arch.arch == Target.ArchEnum.PPC and ( data.meta.inherited or data.meta.function_return ): likely_regs[reg] = False elif data.meta.in_pattern: # Like `meta.function_return` mentioned above, `meta.in_pattern` will only be # accurate for registers set within this basic block. likely_regs[reg] = False elif isinstance(data.value, PassedInArg) and not data.value.copied: likely_regs[reg] = False else: likely_regs[reg] = True abi = arch.function_abi(fn_sig, likely_regs, for_call=True) func_args: List[Expression] = [] for slot in abi.arg_slots: if slot.reg: expr = regs[slot.reg] elif slot.offset in subroutine_args: expr = subroutine_args.pop(slot.offset) else: expr = ErrorExpr( f"Unable to find stack arg {slot.offset:#x} in block" ) func_args.append( CommentExpr.wrap( as_type(expr, slot.type, True), prefix=slot.comment ) ) for slot in abi.possible_slots: assert slot.reg is not None func_args.append(regs[slot.reg]) # Add the arguments after a3. # TODO: limit this based on abi.arg_slots. If the function type is known # and not variadic, this list should be empty. for _, arg in sorted(subroutine_args.items()): if fn_sig.params_known and not fn_sig.is_variadic: func_args.append(CommentExpr.wrap(arg, prefix="extra?")) else: func_args.append(arg) if not fn_sig.params_known: while len(func_args) > len(fn_sig.params): fn_sig.params.append(FunctionParam()) # When the function signature isn't provided, the we only assume that each # parameter is "simple" (<=4 bytes, no return struct, etc.). This may not # match the actual function signature, but it's the best we can do. # Without that assumption, the logic from `function_abi` would be needed here. for i, (arg_expr, param) in enumerate(zip(func_args, fn_sig.params)): func_args[i] = as_type(arg_expr, param.type.decay(), True) # Reset subroutine_args, for the next potential function call. subroutine_args.clear() call: Expression = FuncCall( fn_target, func_args, fn_sig.return_type.weaken_void_ptr() ) call = eval_once(call, emit_exactly_once=True, trivial=False, prefix="ret") # Clear out caller-save registers, for clarity and to ensure that # argument regs don't get passed into the next function. clear_caller_save_regs() # Clear out local var write tracking if any argument contains a stack # reference. That dict is used to track register saves/restores, which # are unreliable if we call a function with a stack reference. maybe_clear_local_var_writes(func_args) # Prevent reads and function calls from moving across this call. # This isn't really right, because this call might be moved later, # and then this prevention should also be... but it's the best we # can do with the current code architecture. prevent_later_function_calls() prevent_later_reads() return_reg_vals = arch.function_return(call) for out in instr.outputs: if not isinstance(out, Register): continue val = return_reg_vals[out] if not isinstance(val, SecondF64Half): val = eval_once( val, emit_exactly_once=False, trivial=False, prefix=stack_info.function.reg_formatter.format(out), ) regs.set_with_meta(out, val, RegMeta(function_return=True)) has_function_call = True elif mnemonic in arch.instrs_float_comp: expr = arch.instrs_float_comp[mnemonic](args) regs[Register("condition_bit")] = expr elif mnemonic in arch.instrs_hi_lo: hi, lo = arch.instrs_hi_lo[mnemonic](args) set_reg(Register("hi"), hi) set_reg(Register("lo"), lo) elif mnemonic in arch.instrs_implicit_destination: reg, expr_fn = arch.instrs_implicit_destination[mnemonic] set_reg(reg, expr_fn(args)) elif mnemonic in arch.instrs_ppc_compare: if instr.args[0] != Register("cr0"): raise DecompFailure( f"Instruction {instr} not supported (first arg is not $cr0)" ) set_reg(Register("cr0_eq"), arch.instrs_ppc_compare[mnemonic](args, "==")) set_reg(Register("cr0_gt"), arch.instrs_ppc_compare[mnemonic](args, ">")) set_reg(Register("cr0_lt"), arch.instrs_ppc_compare[mnemonic](args, "<")) set_reg(Register("cr0_so"), Literal(0)) elif mnemonic in arch.instrs_no_dest: stmt = arch.instrs_no_dest[mnemonic](args) to_write.append(stmt) elif mnemonic.rstrip(".") in arch.instrs_destination_first: target = args.reg_ref(0) val = arch.instrs_destination_first[mnemonic.rstrip(".")](args) # TODO: IDO tends to keep variables within single registers. Thus, # if source = target, maybe we could overwrite that variable instead # of creating a new one? target_val = set_reg(target, val) mn_parts = arch_mnemonic.split(".") if arch_mnemonic.startswith("ppc:") and arch_mnemonic.endswith("."): # PPC instructions suffixed with . set condition bits (CR0) based on the result value if target_val is None: target_val = val set_reg( Register("cr0_eq"), BinaryOp.icmp(target_val, "==", Literal(0, type=target_val.type)), ) # Use manual casts for cr0_gt/cr0_lt so that the type of target_val is not modified # until the resulting bit is .use()'d. target_s32 = Cast( target_val, reinterpret=True, silent=True, type=Type.s32() ) set_reg( Register("cr0_gt"), BinaryOp(target_s32, ">", Literal(0), type=Type.s32()), ) set_reg( Register("cr0_lt"), BinaryOp(target_s32, "<", Literal(0), type=Type.s32()), ) set_reg( Register("cr0_so"), fn_op("MIPS2C_OVERFLOW", [target_val], type=Type.s32()), ) elif ( len(mn_parts) >= 2 and mn_parts[0].startswith("mips:") and mn_parts[1] == "d" ) or arch_mnemonic == "mips:ldc1": set_reg(target.other_f64_reg(), SecondF64Half()) elif mnemonic in arch.instrs_load_update: target = args.reg_ref(0) val = arch.instrs_load_update[mnemonic](args) set_reg(target, val) if arch_mnemonic in ["ppc:lwzux", "ppc:lhzux", "ppc:lbzux"]: # In `rD, rA, rB`, update `rA = rA + rB` update_reg = args.reg_ref(1) offset = args.reg(2) else: # In `rD, rA(N)`, update `rA = rA + N` update = args.memory_ref(1) if not isinstance(update, AddressMode): raise DecompFailure( f"Unhandled store-and-update arg in {instr}: {update!r}" ) update_reg = update.rhs offset = Literal(update.offset) if update_reg == target: raise DecompFailure( f"Invalid instruction, rA and rD must be different in {instr}" ) set_reg(update_reg, add_imm(args.regs[update_reg], offset, stack_info)) else: expr = ErrorExpr(f"unknown instruction: {instr}") if arch_mnemonic.startswith("ppc:") and arch_mnemonic.endswith("."): # Unimplemented PPC instructions that modify CR0 set_reg(Register("cr0_eq"), expr) set_reg(Register("cr0_gt"), expr) set_reg(Register("cr0_lt"), expr) set_reg(Register("cr0_so"), expr) if args.count() >= 1 and isinstance(args.raw_arg(0), Register): reg = args.reg_ref(0) expr = eval_once( expr, emit_exactly_once=True, trivial=False, prefix=stack_info.function.reg_formatter.format(reg), ) if reg != Register("zero"): set_reg_maybe_return(reg, expr) else: to_write.append(ExprStmt(expr)) for instr in node.block.instructions: with regs.current_instr(instr): process_instr(instr) if branch_condition is not None: branch_condition.use() switch_control: Optional[SwitchControl] = None if switch_expr is not None: switch_control = SwitchControl.from_expr(switch_expr) switch_control.control_expr.use() return BlockInfo( to_write=to_write, return_value=None, switch_control=switch_control, branch_condition=branch_condition, final_register_states=regs, has_function_call=has_function_call, ) def translate_graph_from_block( node: Node, regs: RegInfo, stack_info: StackInfo, used_phis: List[PhiExpr], return_blocks: List[BlockInfo], options: Options, ) -> None: """ Given a FlowGraph node and a dictionary of register contents, give that node its appropriate BlockInfo (which contains the AST of its code). """ if options.debug: print(f"\nNode in question: {node}") # Translate the given node and discover final register states. try: block_info = translate_node_body(node, regs, stack_info) if options.debug: print(block_info) except Exception as e: # TODO: handle issues better if options.stop_on_error: raise instr: Optional[Instruction] = None if isinstance(e, InstrProcessingFailure) and isinstance(e.__cause__, Exception): instr = e.instr e = e.__cause__ if isinstance(e, DecompFailure): emsg = str(e) print(emsg) else: tb = e.__traceback__ traceback.print_exception(None, e, tb) emsg = str(e) or traceback.format_tb(tb)[-1] emsg = emsg.strip().split("\n")[-1].strip() error_stmts: List[Statement] = [CommentStmt(f"Error: {emsg}")] if instr is not None: print( f"Error occurred while processing instruction: {instr}", file=sys.stderr ) error_stmts.append(CommentStmt(f"At instruction: {instr}")) print(file=sys.stderr) block_info = BlockInfo( to_write=error_stmts, return_value=None, switch_control=None, branch_condition=ErrorExpr(), final_register_states=regs, has_function_call=False, ) node.block.add_block_info(block_info) if isinstance(node, ReturnNode): return_blocks.append(block_info) # Translate everything dominated by this node, now that we know our own # final register state. This will eventually reach every node. for child in node.immediately_dominates: if isinstance(child, TerminalNode): continue new_regs = RegInfo(stack_info=stack_info) for reg, data in regs.contents.items(): new_regs.set_with_meta( reg, data.value, RegMeta(inherited=True, force=data.meta.force) ) phi_regs = ( r for r in locs_clobbered_until_dominator(child) if isinstance(r, Register) ) for reg in phi_regs: if reg_always_set(child, reg, dom_set=(reg in regs)): expr: Optional[Expression] = stack_info.maybe_get_register_var(reg) if expr is None: expr = PhiExpr( reg=reg, node=child, used_phis=used_phis, type=Type.any_reg() ) new_regs.set_with_meta(reg, expr, RegMeta(inherited=True)) elif reg in new_regs: del new_regs[reg] translate_graph_from_block( child, new_regs, stack_info, used_phis, return_blocks, options ) def resolve_types_late(stack_info: StackInfo) -> None: """ After translating a function, perform a final type-resolution pass. """ # Final check over stack var types. Because of delayed type unification, some # locations should now be marked as "weak". for location in stack_info.weak_stack_var_types.keys(): stack_info.get_stack_var(location, store=False) # Use dereferences to determine pointer types struct_type_map = stack_info.get_struct_type_map() for var, offset_type_map in struct_type_map.items(): if len(offset_type_map) == 1 and 0 in offset_type_map: # var was probably a plain pointer, not a struct # Try to unify it with the appropriate pointer type, # to fill in the type if it does not already have one type = offset_type_map[0] var.type.unify(Type.ptr(type)) @dataclass class FunctionInfo: stack_info: StackInfo flow_graph: FlowGraph return_type: Type symbol: GlobalSymbol @dataclass class GlobalInfo: asm_data: AsmData arch: Arch target: Target local_functions: Set[str] typemap: TypeMap typepool: TypePool global_symbol_map: Dict[str, GlobalSymbol] = field(default_factory=dict) def asm_data_value(self, sym_name: str) -> Optional[AsmDataEntry]: return self.asm_data.values.get(sym_name) def address_of_gsym(self, sym_name: str) -> AddressOf: if sym_name in self.global_symbol_map: sym = self.global_symbol_map[sym_name] else: demangled_symbol: Optional[CxxSymbol] = None demangled_str: Optional[str] = None if self.target.language == Target.LanguageEnum.CXX: try: demangled_symbol = demangle_codewarrior_parse(sym_name) except ValueError: pass else: demangled_str = str(demangled_symbol) sym = self.global_symbol_map[sym_name] = GlobalSymbol( symbol_name=sym_name, type=Type.any(), asm_data_entry=self.asm_data_value(sym_name), demangled_str=demangled_str, ) # If the symbol is a C++ vtable, try to build a custom type for it by parsing it if ( self.target.language == Target.LanguageEnum.CXX and sym_name.startswith("__vt__") and sym.asm_data_entry is not None ): sym.type.unify(self.vtable_type(sym_name, sym.asm_data_entry)) fn = self.typemap.functions.get(sym_name) ctype: Optional[CType] if fn is not None: ctype = fn.type else: ctype = self.typemap.var_types.get(sym_name) if ctype is not None: sym.symbol_in_context = True sym.initializer_in_typemap = ( sym_name in self.typemap.vars_with_initializers ) sym.type.unify(Type.ctype(ctype, self.typemap, self.typepool)) if sym_name not in self.typepool.unknown_decls: sym.type_provided = True elif sym_name in self.local_functions: sym.type.unify(Type.function()) # Do this after unifying the type in the typemap, so that it has lower precedence if demangled_symbol is not None: sym.type.unify( Type.demangled_symbol(self.typemap, self.typepool, demangled_symbol) ) return AddressOf(sym, type=sym.type.reference()) def vtable_type(self, sym_name: str, asm_data_entry: AsmDataEntry) -> Type: """ Parse MWCC vtable data to create a custom struct to represent it. This format is not well documented, but is briefly explored in this series of posts: https://web.archive.org/web/20220413174849/http://hacksoflife.blogspot.com/2007/02/c-objects-part-2-single-inheritance.html """ size = asm_data_entry.size_range_bytes()[1] struct = StructDeclaration.unknown( self.typepool, size=size, align=4, tag_name=sym_name ) offset = 0 for entry in asm_data_entry.data: if isinstance(entry, bytes): # MWCC vtables start with a pointer to a typeid struct (or NULL) and an offset if len(entry) % 4 != 0: raise DecompFailure( f"Unable to parse misaligned vtable data in {sym_name}" ) for i in range(len(entry) // 4): field_name = f"{struct.new_field_prefix}{offset:X}" struct.try_add_field( Type.reg32(likely_float=False), offset, field_name, size=4 ) offset += 4 else: entry_name = entry try: demangled_field_sym = demangle_codewarrior_parse(entry) if demangled_field_sym.name.qualified_name is not None: entry_name = str(demangled_field_sym.name.qualified_name[-1]) except ValueError: pass field = struct.try_add_field( self.address_of_gsym(entry).type, offset, name=entry_name, size=4, ) assert field is not None field.known = True offset += 4 return Type.struct(struct) def is_function_known_void(self, sym_name: str) -> bool: """Return True if the function exists in the context, and has no return value""" fn = self.typemap.functions.get(sym_name) if fn is None: return False return fn.ret_type is None def initializer_for_symbol( self, sym: GlobalSymbol, fmt: Formatter ) -> Optional[str]: assert sym.asm_data_entry is not None data = sym.asm_data_entry.data[:] def read_uint(n: int) -> Optional[int]: """Read the next `n` bytes from `data` as an (long) integer""" assert 0 < n <= 8 if not data or not isinstance(data[0], bytes): return None if len(data[0]) < n: return None bs = data[0][:n] data[0] = data[0][n:] if not data[0]: del data[0] value = 0 for b in bs: value = (value << 8) | b return value def read_pointer() -> Optional[Expression]: """Read the next label from `data`""" if not data or not isinstance(data[0], str): return None label = data[0] data.pop(0) return self.address_of_gsym(label) def for_type(type: Type) -> Optional[str]: """Return the initializer for a single element of type `type`""" if type.is_struct() or type.is_array(): struct_fields = type.get_initializer_fields() if not struct_fields: return None members = [] for field in struct_fields: if isinstance(field, int): # Check that all padding bytes are 0 for i in range(field): padding = read_uint(1) if padding != 0: return None else: m = for_type(field) if m is None: return None members.append(m) return fmt.format_array(members) if type.is_reg(): size = type.get_size_bytes() if not size: return None if size == 4: ptr = read_pointer() if ptr is not None: return as_type(ptr, type, silent=True).format(fmt) value = read_uint(size) if value is not None: enum_name = type.get_enum_name(value) if enum_name is not None: return enum_name expr = as_type(Literal(value), type, True) return elide_casts_for_store(expr).format(fmt) # Type kinds K_FN and K_VOID do not have initializers return None return for_type(sym.type) def find_forward_declares_needed(self, functions: List[FunctionInfo]) -> Set[str]: funcs_seen = set() forward_declares_needed = self.asm_data.mentioned_labels for func in functions: funcs_seen.add(func.stack_info.function.name) for instr in func.stack_info.function.body: if not isinstance(instr, Instruction): continue for arg in instr.args: if isinstance(arg, AsmGlobalSymbol): func_name = arg.symbol_name elif isinstance(arg, Macro) and isinstance( arg.argument, AsmGlobalSymbol ): func_name = arg.argument.symbol_name else: continue if func_name in self.local_functions: if func_name not in funcs_seen: forward_declares_needed.add(func_name) return forward_declares_needed def global_decls( self, fmt: Formatter, decls: Options.GlobalDeclsEnum, functions: List[FunctionInfo], ) -> str: # Format labels from symbol_type_map into global declarations. # As the initializers are formatted, this may cause more symbols # to be added to the global_symbol_map. forward_declares_needed = self.find_forward_declares_needed(functions) lines = [] processed_names: Set[str] = set() while True: names: AbstractSet[str] = self.global_symbol_map.keys() if decls == Options.GlobalDeclsEnum.ALL: names |= self.asm_data.values.keys() names -= processed_names if not names: break for name in sorted(names): processed_names.add(name) sym = self.address_of_gsym(name).expr assert isinstance(sym, GlobalSymbol) data_entry = sym.asm_data_entry # Is the label defined in this unit (in the active AsmData file(s)) is_in_file = data_entry is not None or name in self.local_functions # Is the label externally visible (mentioned in the context file) is_global = sym.symbol_in_context # Is the label a symbol in .rodata? is_const = data_entry is not None and data_entry.is_readonly if data_entry and data_entry.is_jtbl: # Skip jump tables continue if is_in_file and is_global and sym.type.is_function(): # Skip externally-declared functions that are defined here continue if self.local_functions == {name}: # Skip the function being decompiled if just a single one continue if not is_in_file and sym.type_provided: # Skip externally-declared symbols that are defined in other files continue # TODO: Use original MIPSFile ordering for variables sort_order = ( not sym.type.is_function(), is_global, is_in_file, is_const, name, ) qualifier = "" value: Optional[str] = None comments = [] # Determine type qualifier: static, extern, or neither if is_in_file and is_global: qualifier = "" elif is_in_file: qualifier = "static" else: qualifier = "extern" if sym.type.is_function(): comments.append(qualifier) qualifier = "" # Try to guess if the symbol is an array (and if it is, its dimension) if # we have a data entry for it, and the symbol is either not in the typemap # or was a variable-length array there ("VLA", e.g. `int []`) # (Otherwise, if the dim is provided by the typemap, we trust it.) element_type, array_dim = sym.type.get_array() is_vla = element_type is not None and ( array_dim is None or array_dim <= 0 ) if data_entry and (not sym.type_provided or is_vla): # The size of the data entry is uncertain, because of padding # between sections. Generally `(max_data_size - data_size) < 16`. min_data_size, max_data_size = data_entry.size_range_bytes() # The size of the element type (not the size of the array type) if element_type is None: element_type = sym.type # If we don't know the type, we can't guess the array_dim type_size = element_type.get_size_bytes() if type_size: potential_dim, extra_bytes = sym.potential_array_dim(type_size) if potential_dim == 0 and extra_bytes > 0: # The type is too big for our data. (not an array) comments.append( f"type too large by {fmt.format_int(type_size - extra_bytes)}" ) elif potential_dim > 1 or is_vla: # NB: In general, replacing the types of Expressions can be sketchy. # However, the GlobalSymbol here came from address_of_gsym(), which # always returns a reference to the element_type. array_dim = potential_dim sym.type = Type.array(element_type, array_dim) if potential_dim != 0 and extra_bytes > 0: comments.append( f"extra bytes: {fmt.format_int(extra_bytes)}" ) # Try to convert the data from .data/.rodata into an initializer if data_entry and not data_entry.is_bss: value = self.initializer_for_symbol(sym, fmt) if value is None: # This warning helps distinguish .bss symbols from .data/.rodata, # IDO only puts symbols in .bss if they don't have any initializer comments.append("unable to generate initializer") if is_const: comments.append("const") # Float & string constants are almost always inlined and can be omitted if sym.is_string_constant(): continue if array_dim is None and sym.type.is_likely_float(): continue # In "none" mode, do not emit any decls if decls == Options.GlobalDeclsEnum.NONE: continue # In modes except "all", skip the decl if the context file already had an initializer if decls != Options.GlobalDeclsEnum.ALL and sym.initializer_in_typemap: continue # In modes except "all", skip vtable decls when compiling C++ if ( decls != Options.GlobalDeclsEnum.ALL and self.target.language == Target.LanguageEnum.CXX and name.startswith("__vt__") ): continue if ( sym.type.is_function() and decls != Options.GlobalDeclsEnum.ALL and name in self.local_functions and name not in forward_declares_needed ): continue qualifier = f"{qualifier} " if qualifier else "" value = f" = {value}" if value else "" lines.append( ( sort_order, fmt.with_comments( f"{qualifier}{sym.type.to_decl(name, fmt)}{value};", comments, ) + "\n", ) ) lines.sort() return "".join(line for _, line in lines) def narrow_func_call_outputs( function: Function, global_info: GlobalInfo, ) -> None: """ Modify the `outputs` list of function call Instructions using the context file. For now, this only handles known-void functions, but in the future it could be extended to select a specific register subset based on type. """ for instr in function.body: if ( isinstance(instr, Instruction) and isinstance(instr.function_target, AsmGlobalSymbol) and global_info.is_function_known_void(instr.function_target.symbol_name) ): instr.outputs.clear() def translate_to_ast( function: Function, flow_graph: FlowGraph, options: Options, global_info: GlobalInfo, ) -> FunctionInfo: """ Given a function, produce a FlowGraph that both contains control-flow information and has AST transformations for each block of code and branch condition. """ # Initialize info about the function. stack_info = get_stack_info(function, global_info, flow_graph) start_regs: RegInfo = RegInfo(stack_info=stack_info) arch = global_info.arch start_regs[arch.stack_pointer_reg] = GlobalSymbol("sp", type=Type.ptr()) for reg in arch.saved_regs: start_regs[reg] = stack_info.saved_reg_symbol(reg.register_name) fn_sym = global_info.address_of_gsym(function.name).expr assert isinstance(fn_sym, GlobalSymbol) fn_type = fn_sym.type fn_type.unify(Type.function()) fn_sig = Type.ptr(fn_type).get_function_pointer_signature() assert fn_sig is not None, "fn_type is known to be a function" return_type = fn_sig.return_type stack_info.is_variadic = fn_sig.is_variadic def make_arg(offset: int, type: Type) -> PassedInArg: assert offset % 4 == 0 return PassedInArg(offset, copied=False, stack_info=stack_info, type=type) abi = arch.function_abi( fn_sig, likely_regs={reg: True for reg in arch.argument_regs}, for_call=False, ) for slot in abi.arg_slots: stack_info.add_known_param(slot.offset, slot.name, slot.type) if slot.reg is not None: start_regs.set_with_meta( slot.reg, make_arg(slot.offset, slot.type), RegMeta(uninteresting=True) ) for slot in abi.possible_slots: if slot.reg is not None: start_regs.set_with_meta( slot.reg, make_arg(slot.offset, slot.type), RegMeta(uninteresting=True) ) if options.reg_vars == ["saved"]: reg_vars = arch.saved_regs elif options.reg_vars == ["most"]: reg_vars = arch.saved_regs + arch.simple_temp_regs elif options.reg_vars == ["all"]: reg_vars = arch.saved_regs + arch.simple_temp_regs + arch.argument_regs else: reg_vars = [ stack_info.function.reg_formatter.parse(x, arch) for x in options.reg_vars ] for reg in reg_vars: reg_name = stack_info.function.reg_formatter.format(reg) stack_info.add_register_var(reg, reg_name) if options.debug: print(stack_info) print("\nNow, we attempt to translate:") used_phis: List[PhiExpr] = [] return_blocks: List[BlockInfo] = [] translate_graph_from_block( flow_graph.entry_node(), start_regs, stack_info, used_phis, return_blocks, options, ) for reg in arch.base_return_regs: propagate_register_meta(flow_graph.nodes, reg) return_reg: Optional[Register] = None if not options.void and not return_type.is_void(): return_reg = determine_return_register( return_blocks, fn_sym.type_provided, arch ) if return_reg is not None: for b in return_blocks: if return_reg in b.final_register_states: ret_val = b.final_register_states[return_reg] ret_val = as_type(ret_val, return_type, True) ret_val.use() b.return_value = ret_val else: return_type.unify(Type.void()) if not fn_sig.params_known: while len(fn_sig.params) < len(stack_info.arguments): fn_sig.params.append(FunctionParam()) for param, arg in zip(fn_sig.params, stack_info.arguments): param.type.unify(arg.type) if not param.name: param.name = arg.format(Formatter()) assign_phis(used_phis, stack_info) resolve_types_late(stack_info) if options.pdb_translate: import pdb v: Dict[str, object] = {} fmt = Formatter() for local in stack_info.local_vars: var_name = local.format(fmt) v[var_name] = local for temp in stack_info.temp_vars: if temp.need_decl(): var_name = temp.expr.var.format(fmt) v[var_name] = temp.expr for phi in stack_info.phi_vars: assert phi.name is not None v[phi.name] = phi pdb.set_trace() return FunctionInfo(stack_info, flow_graph, return_type, fn_sym)
38.14032
131
0.598064
import abc from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass, field, replace import math import struct import sys import traceback import typing from typing import ( AbstractSet, Callable, Collection, DefaultDict, Dict, Iterator, List, Mapping, Optional, Set, Tuple, Union, ) from .c_types import CType, TypeMap from .demangle_codewarrior import parse as demangle_codewarrior_parse, CxxSymbol from .error import DecompFailure, static_assert_unreachable from .flow_graph import ( ArchFlowGraph, FlowGraph, Function, Node, ReturnNode, SwitchNode, TerminalNode, locs_clobbered_until_dominator, ) from .ir_pattern import IrPattern, simplify_ir_patterns from .options import CodingStyle, Formatter, Options, Target from .parse_file import AsmData, AsmDataEntry from .parse_instruction import ( ArchAsm, Argument, AsmAddressMode, AsmGlobalSymbol, AsmLiteral, BinOp, Instruction, InstrProcessingFailure, Macro, Register, StackLocation, current_instr, ) from .types import ( AccessPath, FunctionParam, FunctionSignature, StructDeclaration, Type, TypePool, ) InstrSet = Collection[str] InstrMap = Mapping[str, Callable[["InstrArgs"], "Expression"]] StmtInstrMap = Mapping[str, Callable[["InstrArgs"], "Statement"]] CmpInstrMap = Mapping[str, Callable[["InstrArgs"], "Condition"]] StoreInstrMap = Mapping[str, Callable[["InstrArgs"], Optional["StoreStmt"]]] MaybeInstrMap = Mapping[str, Callable[["InstrArgs"], Optional["Expression"]]] PairInstrMap = Mapping[str, Callable[["InstrArgs"], Tuple["Expression", "Expression"]]] ImplicitInstrMap = Mapping[str, Tuple[Register, Callable[["InstrArgs"], "Expression"]]] PpcCmpInstrMap = Mapping[str, Callable[["InstrArgs", str], "Expression"]] class Arch(ArchFlowGraph): instrs_ignore: InstrSet = set() instrs_store: StoreInstrMap = {} instrs_store_update: StoreInstrMap = {} instrs_load_update: InstrMap = {} instrs_branches: CmpInstrMap = {} instrs_float_branches: InstrSet = set() instrs_float_comp: CmpInstrMap = {} instrs_ppc_compare: PpcCmpInstrMap = {} instrs_jumps: InstrSet = set() instrs_fn_call: InstrSet = set() instrs_no_dest: StmtInstrMap = {} instrs_hi_lo: PairInstrMap = {} instrs_source_first: InstrMap = {} instrs_destination_first: InstrMap = {} instrs_implicit_destination: ImplicitInstrMap = {} @abc.abstractmethod def function_abi( self, fn_sig: FunctionSignature, likely_regs: Dict[Register, bool], *, for_call: bool, ) -> "Abi": ... @abc.abstractmethod def function_return(self, expr: "Expression") -> Dict[Register, "Expression"]: ... ir_patterns: List[IrPattern] = [] def simplify_ir(self, flow_graph: FlowGraph) -> None: simplify_ir_patterns(self, flow_graph, self.ir_patterns) ASSOCIATIVE_OPS: Set[str] = {"+", "&&", "||", "&", "|", "^", "*"} COMPOUND_ASSIGNMENT_OPS: Set[str] = {"+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>"} PSEUDO_FUNCTION_OPS: Set[str] = {"MULT_HI", "MULTU_HI", "DMULT_HI", "DMULTU_HI", "CLZ"} def as_type(expr: "Expression", type: Type, silent: bool) -> "Expression": type = type.weaken_void_ptr() ptr_target_type = type.get_pointer_target() if expr.type.unify(type): if silent or isinstance(expr, Literal): return expr elif ptr_target_type is not None: ptr_target_type_size = ptr_target_type.get_size_bytes() field_path, field_type, _ = expr.type.get_deref_field( 0, target_size=ptr_target_type_size ) if field_path is not None and field_type.unify(ptr_target_type): expr = AddressOf( StructAccess( struct_var=expr, offset=0, target_size=ptr_target_type_size, field_path=field_path, stack_info=None, type=field_type, ), type=type, ) if silent: return expr return Cast(expr=expr, reinterpret=True, silent=False, type=type) def as_f32(expr: "Expression") -> "Expression": return as_type(expr, Type.f32(), True) def as_f64(expr: "Expression") -> "Expression": return as_type(expr, Type.f64(), True) def as_sintish(expr: "Expression", *, silent: bool = False) -> "Expression": return as_type(expr, Type.sintish(), silent) def as_uintish(expr: "Expression") -> "Expression": return as_type(expr, Type.uintish(), False) def as_u32(expr: "Expression") -> "Expression": return as_type(expr, Type.u32(), False) def as_s64(expr: "Expression", *, silent: bool = False) -> "Expression": return as_type(expr, Type.s64(), silent) def as_u64(expr: "Expression", *, silent: bool = False) -> "Expression": return as_type(expr, Type.u64(), silent) def as_intish(expr: "Expression") -> "Expression": return as_type(expr, Type.intish(), True) def as_int64(expr: "Expression") -> "Expression": return as_type(expr, Type.int64(), True) def as_intptr(expr: "Expression") -> "Expression": return as_type(expr, Type.intptr(), True) def as_ptr(expr: "Expression") -> "Expression": return as_type(expr, Type.ptr(), True) def as_function_ptr(expr: "Expression") -> "Expression": return as_type(expr, Type.ptr(Type.function()), True) @dataclass class StackInfo: function: Function global_info: "GlobalInfo" flow_graph: FlowGraph allocated_stack_size: int = 0 is_leaf: bool = True is_variadic: bool = False uses_framepointer: bool = False subroutine_arg_top: int = 0 callee_save_regs: Set[Register] = field(default_factory=set) callee_save_reg_region: Tuple[int, int] = (0, 0) unique_type_map: Dict[Tuple[str, object], "Type"] = field(default_factory=dict) local_vars: List["LocalVar"] = field(default_factory=list) temp_vars: List["EvalOnceStmt"] = field(default_factory=list) phi_vars: List["PhiExpr"] = field(default_factory=list) reg_vars: Dict[Register, "RegisterVar"] = field(default_factory=dict) used_reg_vars: Set[Register] = field(default_factory=set) arguments: List["PassedInArg"] = field(default_factory=list) temp_name_counter: Dict[str, int] = field(default_factory=dict) nonzero_accesses: Set["Expression"] = field(default_factory=set) param_names: Dict[int, str] = field(default_factory=dict) stack_pointer_type: Optional[Type] = None replace_first_arg: Optional[Tuple[str, Type]] = None weak_stack_var_types: Dict[int, Type] = field(default_factory=dict) weak_stack_var_locations: Set[int] = field(default_factory=set) def temp_var(self, prefix: str) -> str: counter = self.temp_name_counter.get(prefix, 0) + 1 self.temp_name_counter[prefix] = counter return prefix + (f"_{counter}" if counter > 1 else "") def in_subroutine_arg_region(self, location: int) -> bool: if self.global_info.arch.arch == Target.ArchEnum.PPC: return False if self.is_leaf: return False assert self.subroutine_arg_top is not None return location < self.subroutine_arg_top def in_callee_save_reg_region(self, location: int) -> bool: lower_bound, upper_bound = self.callee_save_reg_region if lower_bound <= location < upper_bound: return True if ( self.global_info.arch.arch == Target.ArchEnum.PPC and location == self.allocated_stack_size + 4 ): return True return False def location_above_stack(self, location: int) -> bool: return location >= self.allocated_stack_size def add_known_param(self, offset: int, name: Optional[str], type: Type) -> None: if offset == 0 and type.is_pointer() and self.replace_first_arg is None: namespace = self.function.name.partition("_")[0] base_struct_type = type.get_pointer_target() self_struct = self.global_info.typepool.get_struct_by_tag_name( namespace, self.global_info.typemap ) if ( self_struct is not None and base_struct_type is not None and base_struct_type.is_struct() ): self_struct_type = Type.struct(self_struct) field_path, field_type, _ = self_struct_type.get_field( offset=0, target_size=base_struct_type.get_size_bytes() ) if ( field_path is not None and field_type.unify(base_struct_type) and not self_struct_type.unify(base_struct_type) ): self.replace_first_arg = (name or "_self", type) name = "this" if name == "thisx" else "self" type = Type.ptr(Type.struct(self_struct)) if name: self.param_names[offset] = name _, arg = self.get_argument(offset) self.add_argument(arg) arg.type.unify(type) def get_param_name(self, offset: int) -> Optional[str]: return self.param_names.get(offset) def add_local_var(self, var: "LocalVar") -> None: if any(v.value == var.value for v in self.local_vars): return self.local_vars.append(var) self.local_vars.sort(key=lambda v: v.value) def add_argument(self, arg: "PassedInArg") -> None: if any(a.value == arg.value for a in self.arguments): return self.arguments.append(arg) self.arguments.sort(key=lambda a: a.value) def get_argument(self, location: int) -> Tuple["Expression", "PassedInArg"]: real_location = location & -4 arg = PassedInArg( real_location, copied=True, stack_info=self, type=self.unique_type_for("arg", real_location, Type.any_reg()), ) if real_location == location - 3: return as_type(arg, Type.int_of_size(8), True), arg if real_location == location - 2: return as_type(arg, Type.int_of_size(16), True), arg return arg, arg def record_struct_access(self, ptr: "Expression", location: int) -> None: if location: self.nonzero_accesses.add(unwrap_deep(ptr)) def has_nonzero_access(self, ptr: "Expression") -> bool: return unwrap_deep(ptr) in self.nonzero_accesses def unique_type_for(self, category: str, key: object, default: Type) -> "Type": key = (category, key) if key not in self.unique_type_map: self.unique_type_map[key] = default return self.unique_type_map[key] def saved_reg_symbol(self, reg_name: str) -> "GlobalSymbol": sym_name = "saved_reg_" + reg_name type = self.unique_type_for("saved_reg", sym_name, Type.any_reg()) return GlobalSymbol(symbol_name=sym_name, type=type) def should_save(self, expr: "Expression", offset: Optional[int]) -> bool: expr = early_unwrap(expr) if isinstance(expr, GlobalSymbol) and ( expr.symbol_name.startswith("saved_reg_") or expr.symbol_name == "sp" ): return True if ( isinstance(expr, PassedInArg) and not expr.copied and (offset is None or offset == self.allocated_stack_size + expr.value) ): return True return False def get_stack_var(self, location: int, *, store: bool) -> "Expression": if self.in_callee_save_reg_region(location): return LocalVar(location, type=Type.any_reg(), path=None) elif self.location_above_stack(location): ret, arg = self.get_argument(location - self.allocated_stack_size) if not store: self.add_argument(arg) return ret elif self.in_subroutine_arg_region(location): return SubroutineArg(location, type=Type.any_reg()) else: # Local variable assert self.stack_pointer_type is not None field_path, field_type, _ = self.stack_pointer_type.get_deref_field( location, target_size=None ) # Some variables on the stack are compiler-managed, and aren't declared previous_stored_type = self.weak_stack_var_types.get(location) if previous_stored_type is not None: if not previous_stored_type.unify(field_type): # This marker is only used to annotate the output self.weak_stack_var_locations.add(location) if store: # If there's already been a store to `location`, then return a fresh type field_type = Type.any_field() else: field_type = previous_stored_type if store: self.weak_stack_var_types[location] = field_type return LocalVar(location, type=field_type, path=field_path) def maybe_get_register_var(self, reg: Register) -> Optional["RegisterVar"]: return self.reg_vars.get(reg) def add_register_var(self, reg: Register, name: str) -> None: type = Type.floatish() if reg.is_float() else Type.intptr() self.reg_vars[reg] = RegisterVar(reg=reg, type=type, name=name) def use_register_var(self, var: "RegisterVar") -> None: self.used_reg_vars.add(var.reg) def is_stack_reg(self, reg: Register) -> bool: if reg == self.global_info.arch.stack_pointer_reg: return True if reg == self.global_info.arch.frame_pointer_reg: return self.uses_framepointer return False def get_struct_type_map(self) -> Dict["Expression", Dict[int, Type]]: struct_type_map: Dict[Expression, Dict[int, Type]] = {} for (category, key), type in self.unique_type_map.items(): if category != "struct": continue var, offset = typing.cast(Tuple[Expression, int], key) if var not in struct_type_map: struct_type_map[var] = {} struct_type_map[var][offset] = type return struct_type_map def __str__(self) -> str: return "\n".join( [ f"Stack info for function {self.function.name}:", f"Allocated stack size: {self.allocated_stack_size}", f"Leaf? {self.is_leaf}", f"Bounds of callee-saved vars region: {self.callee_save_reg_region}", f"Callee save registers: {self.callee_save_regs}", ] ) def get_stack_info( function: Function, global_info: "GlobalInfo", flow_graph: FlowGraph, ) -> StackInfo: arch = global_info.arch info = StackInfo(function, global_info, flow_graph) # # IDO puts local variables *above* the saved registers on the stack, but # GCC puts local variables *below* the saved registers. # To support both, we explicitly determine both the upper & lower bounds of the # saved registers. Then, we estimate the boundary of the subroutine arguments # by finding the lowest stack offset that is loaded from or computed. (This # assumes that the compiler will never reuse a section of stack for *both* # a local variable *and* a subroutine argument.) Anything within the stack frame, # but outside of these two regions, is considered a local variable. callee_saved_offsets: List[int] = [] # Track simple literal values stored into registers: MIPS compilers need a temp # reg to move the stack pointer more than 0x7FFF bytes. temp_reg_values: Dict[Register, int] = {} for inst in flow_graph.entry_node().block.instructions: arch_mnemonic = inst.arch_mnemonic(arch) if inst.mnemonic in arch.instrs_fn_call: break elif arch_mnemonic == "mips:addiu" and inst.args[0] == arch.stack_pointer_reg: # Moving the stack pointer on MIPS assert isinstance(inst.args[2], AsmLiteral) info.allocated_stack_size = abs(inst.args[2].signed_value()) elif ( arch_mnemonic == "mips:subu" and inst.args[0] == arch.stack_pointer_reg and inst.args[1] == arch.stack_pointer_reg and inst.args[2] in temp_reg_values ): # Moving the stack pointer more than 0x7FFF on MIPS # TODO: This instruction needs to be ignored later in translation, in the # same way that `addiu $sp, $sp, N` is ignored in handle_addi_real assert isinstance(inst.args[2], Register) info.allocated_stack_size = temp_reg_values[inst.args[2]] elif arch_mnemonic == "ppc:stwu" and inst.args[0] == arch.stack_pointer_reg: # Moving the stack pointer on PPC assert isinstance(inst.args[1], AsmAddressMode) assert isinstance(inst.args[1].lhs, AsmLiteral) info.allocated_stack_size = abs(inst.args[1].lhs.signed_value()) elif ( arch_mnemonic == "mips:move" and inst.args[0] == arch.frame_pointer_reg and inst.args[1] == arch.stack_pointer_reg ): # "move fp, sp" very likely means the code is compiled with frame # pointers enabled; thus fp should be treated the same as sp. info.uses_framepointer = True elif ( arch_mnemonic in [ "mips:sw", "mips:swc1", "mips:sdc1", "ppc:stw", "ppc:stmw", "ppc:stfd", "ppc:psq_st", ] and isinstance(inst.args[0], Register) and inst.args[0] in arch.saved_regs and isinstance(inst.args[1], AsmAddressMode) and inst.args[1].rhs == arch.stack_pointer_reg and ( inst.args[0] not in info.callee_save_regs or arch_mnemonic == "ppc:psq_st" ) ): # Initial saving of callee-save register onto the stack. if inst.args[0] in (arch.return_address_reg, Register("r0")): # Saving the return address on the stack. info.is_leaf = False # The registers & their stack accesses must be matched up in ArchAsm.parse for reg, mem in zip(inst.inputs, inst.outputs): if isinstance(reg, Register) and isinstance(mem, StackLocation): assert mem.symbolic_offset is None stack_offset = mem.offset if arch_mnemonic != "ppc:psq_st": # psq_st instructions store the same register as stfd, just # as packed singles instead. Prioritize the stfd. info.callee_save_regs.add(reg) callee_saved_offsets.append(stack_offset) elif arch_mnemonic == "ppc:mflr" and inst.args[0] == Register("r0"): info.is_leaf = False elif arch_mnemonic == "mips:li" and inst.args[0] in arch.temp_regs: assert isinstance(inst.args[0], Register) assert isinstance(inst.args[1], AsmLiteral) temp_reg_values[inst.args[0]] = inst.args[1].value elif ( arch_mnemonic == "mips:ori" and inst.args[0] == inst.args[1] and inst.args[0] in temp_reg_values ): assert isinstance(inst.args[0], Register) assert isinstance(inst.args[2], AsmLiteral) temp_reg_values[inst.args[0]] |= inst.args[2].value if not info.is_leaf: # Iterate over the whole function, not just the first basic block, # to estimate the boundary for the subroutine argument region info.subroutine_arg_top = info.allocated_stack_size for node in flow_graph.nodes: for inst in node.block.instructions: arch_mnemonic = inst.arch_mnemonic(arch) if ( arch_mnemonic in ["mips:lw", "mips:lwc1", "mips:ldc1", "ppc:lwz"] and isinstance(inst.args[1], AsmAddressMode) and inst.args[1].rhs == arch.stack_pointer_reg and inst.args[1].lhs_as_literal() >= 16 ): info.subroutine_arg_top = min( info.subroutine_arg_top, inst.args[1].lhs_as_literal() ) elif ( arch_mnemonic == "mips:addiu" and inst.args[0] != arch.stack_pointer_reg and inst.args[1] == arch.stack_pointer_reg and isinstance(inst.args[2], AsmLiteral) and inst.args[2].value < info.allocated_stack_size ): info.subroutine_arg_top = min( info.subroutine_arg_top, inst.args[2].value ) # Compute the bounds of the callee-saved register region, including padding if callee_saved_offsets: callee_saved_offsets.sort() bottom = callee_saved_offsets[0] # Both IDO & GCC save registers in two subregions: # (a) One for double-sized registers # (b) One for word-sized registers, padded to a multiple of 8 bytes # IDO has (a) lower than (b); GCC has (b) lower than (a) # Check that there are no gaps in this region, other than a single # 4-byte word between subregions. top = bottom internal_padding_added = False for offset in callee_saved_offsets: if offset != top: if not internal_padding_added and offset == top + 4: internal_padding_added = True else: raise DecompFailure( f"Gap in callee-saved word stack region. " f"Saved: {callee_saved_offsets}, " f"gap at: {offset} != {top}." ) top = offset + 4 info.callee_save_reg_region = (bottom, top) # Subroutine arguments must be at the very bottom of the stack, so they # must come after the callee-saved region info.subroutine_arg_top = min(info.subroutine_arg_top, bottom) # Use a struct to represent the stack layout. If the struct is provided in the context, # its fields will be used for variable types & names. stack_struct_name = f"_mips2c_stack_{function.name}" stack_struct = global_info.typepool.get_struct_by_tag_name( stack_struct_name, global_info.typemap ) if stack_struct is not None: if stack_struct.size != info.allocated_stack_size: raise DecompFailure( f"Function {function.name} has a provided stack type {stack_struct_name} " f"with size {stack_struct.size}, but the detected stack size was " f"{info.allocated_stack_size}." ) else: stack_struct = StructDeclaration.unknown( global_info.typepool, size=info.allocated_stack_size, tag_name=stack_struct_name, ) # Mark the struct as a stack struct so we never try to use a reference to the struct itself stack_struct.is_stack = True stack_struct.new_field_prefix = "sp" # This acts as the type of the $sp register info.stack_pointer_type = Type.ptr(Type.struct(stack_struct)) return info def format_hex(val: int) -> str: return format(val, "x").upper() def escape_byte(b: int) -> bytes: table = { b"\0": b"\\0", b"\b": b"\\b", b"\f": b"\\f", b"\n": b"\\n", b"\r": b"\\r", b"\t": b"\\t", b"\v": b"\\v", b"\\": b"\\\\", b'"': b'\\"', } bs = bytes([b]) if bs in table: return table[bs] if b < 0x20 or b in (0xFF, 0x7F): return f"\\x{b:02x}".encode("ascii") return bs @dataclass(eq=False) class Var: stack_info: StackInfo = field(repr=False) prefix: str num_usages: int = 0 name: Optional[str] = None def format(self, fmt: Formatter) -> str: if self.name is None: self.name = self.stack_info.temp_var(self.prefix) return self.name def __str__(self) -> str: return "<temp>" class Expression(abc.ABC): type: Type @abc.abstractmethod def dependencies(self) -> List["Expression"]: ... def use(self) -> None: for expr in self.dependencies(): expr.use() @abc.abstractmethod def format(self, fmt: Formatter) -> str: ... def __str__(self) -> str: fmt = Formatter(debug=True) return '"' + self.format(fmt) + '"' class Condition(Expression): @abc.abstractmethod def negated(self) -> "Condition": ... class Statement(abc.ABC): @abc.abstractmethod def should_write(self) -> bool: ... @abc.abstractmethod def format(self, fmt: Formatter) -> str: ... def __str__(self) -> str: fmt = Formatter(debug=True) return '"' + self.format(fmt) + '"' @dataclass(frozen=True, eq=False) class ErrorExpr(Condition): desc: Optional[str] = None type: Type = field(default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [] def negated(self) -> "Condition": return self def format(self, fmt: Formatter) -> str: if self.desc is not None: return f"MIPS2C_ERROR({self.desc})" return "MIPS2C_ERROR()" @dataclass(frozen=True) class CommentExpr(Expression): expr: Expression type: Type = field(compare=False) prefix: Optional[str] = None suffix: Optional[str] = None def dependencies(self) -> List[Expression]: return [self.expr] def format(self, fmt: Formatter) -> str: expr_str = self.expr.format(fmt) if fmt.coding_style.comment_style == CodingStyle.CommentStyle.NONE: return expr_str prefix_str = f"/* {self.prefix} */ " if self.prefix is not None else "" suffix_str = f" /* {self.suffix} */" if self.suffix is not None else "" return f"{prefix_str}{expr_str}{suffix_str}" @staticmethod def wrap( expr: Expression, prefix: Optional[str] = None, suffix: Optional[str] = None ) -> Expression: if prefix is None and suffix is None: return expr return CommentExpr(expr=expr, type=expr.type, prefix=prefix, suffix=suffix) @dataclass(frozen=True, eq=False) class SecondF64Half(Expression): type: Type = field(default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: return "(second half of f64)" @dataclass(frozen=True, eq=False) class CarryBit(Expression): type: Type = field(default_factory=Type.intish) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: return "MIPS2C_CARRY" @staticmethod def add_to(expr: Expression) -> "BinaryOp": return fold_divmod(BinaryOp.intptr(expr, "+", CarryBit())) @staticmethod def sub_from(expr: Expression) -> "BinaryOp": return BinaryOp.intptr(expr, "-", UnaryOp("!", CarryBit(), type=Type.intish())) @dataclass(frozen=True, eq=False) class BinaryOp(Condition): left: Expression op: str right: Expression type: Type @staticmethod def int(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_intish(left), op=op, right=as_intish(right), type=Type.intish() ) @staticmethod def int64(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_int64(left), op=op, right=as_int64(right), type=Type.int64() ) @staticmethod def intptr(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_intptr(left), op=op, right=as_intptr(right), type=Type.intptr() ) @staticmethod def icmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_intptr(left), op=op, right=as_intptr(right), type=Type.bool() ) @staticmethod def scmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_sintish(left, silent=True), op=op, right=as_sintish(right, silent=True), type=Type.bool(), ) @staticmethod def sintptr_cmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_type(left, Type.sintptr(), False), op=op, right=as_type(right, Type.sintptr(), False), type=Type.bool(), ) @staticmethod def ucmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_uintish(left), op=op, right=as_uintish(right), type=Type.bool() ) @staticmethod def uintptr_cmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_type(left, Type.uintptr(), False), op=op, right=as_type(right, Type.uintptr(), False), type=Type.bool(), ) @staticmethod def fcmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_f32(left), op=op, right=as_f32(right), type=Type.bool(), ) @staticmethod def dcmp(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_f64(left), op=op, right=as_f64(right), type=Type.bool(), ) @staticmethod def sint( left: Expression, op: str, right: Expression, *, silent: bool = False ) -> "BinaryOp": return BinaryOp( left=as_sintish(left, silent=silent), op=op, right=as_sintish(right, silent=silent), type=Type.s32(), ) @staticmethod def uint(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_uintish(left), op=op, right=as_uintish(right), type=Type.u32() ) @staticmethod def s64(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp(left=as_s64(left), op=op, right=as_s64(right), type=Type.s64()) @staticmethod def u64(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp(left=as_u64(left), op=op, right=as_u64(right), type=Type.u64()) @staticmethod def f32(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_f32(left), op=op, right=as_f32(right), type=Type.f32(), ) @staticmethod def f64(left: Expression, op: str, right: Expression) -> "BinaryOp": return BinaryOp( left=as_f64(left), op=op, right=as_f64(right), type=Type.f64(), ) def is_comparison(self) -> bool: return self.op in ["==", "!=", ">", "<", ">=", "<="] def is_floating(self) -> bool: return self.left.type.is_float() and self.right.type.is_float() def negated(self) -> "Condition": if ( self.op in ["&&", "||"] and isinstance(self.left, Condition) and isinstance(self.right, Condition) ): # DeMorgan's Laws return BinaryOp( left=self.left.negated(), op={"&&": "||", "||": "&&"}[self.op], right=self.right.negated(), type=Type.bool(), ) if not self.is_comparison() or ( self.is_floating() and self.op in ["<", ">", "<=", ">="] ): return UnaryOp("!", self, type=Type.bool()) return BinaryOp( left=self.left, op={"==": "!=", "!=": "==", ">": "<=", "<": ">=", ">=": "<", "<=": ">"}[ self.op ], right=self.right, type=Type.bool(), ) def dependencies(self) -> List[Expression]: return [self.left, self.right] def format(self, fmt: Formatter) -> str: left_expr = late_unwrap(self.left) right_expr = late_unwrap(self.right) if ( self.is_comparison() and isinstance(left_expr, Literal) and not isinstance(right_expr, Literal) ): return BinaryOp( left=right_expr, op=self.op.translate(str.maketrans("<>", "><")), right=left_expr, type=self.type, ).format(fmt) if ( not self.is_floating() and isinstance(right_expr, Literal) and right_expr.value < 0 ): if self.op == "+": neg = Literal(value=-right_expr.value, type=right_expr.type) sub = BinaryOp(op="-", left=left_expr, right=neg, type=self.type) return sub.format(fmt) if self.op in ("&", "|"): neg = Literal(value=~right_expr.value, type=right_expr.type) right = UnaryOp("~", neg, type=Type.any_reg()) expr = BinaryOp(op=self.op, left=left_expr, right=right, type=self.type) return expr.format(fmt) lhs = left_expr.format(fmt) if ( isinstance(left_expr, BinaryOp) and left_expr.op == self.op and self.op in ASSOCIATIVE_OPS ): lhs = lhs[1:-1] if self.op in ("/", "%") and isinstance(right_expr, Literal): rhs = right_expr.format(fmt, force_dec=True) else: rhs = right_expr.format(fmt) if self.op in PSEUDO_FUNCTION_OPS: return f"{self.op}({lhs}, {rhs})" return f"({lhs} {self.op} {rhs})" @dataclass(frozen=True, eq=False) class TernaryOp(Expression): cond: Condition left: Expression right: Expression type: Type def dependencies(self) -> List[Expression]: return [self.cond, self.left, self.right] def format(self, fmt: Formatter) -> str: cond_str = simplify_condition(self.cond).format(fmt) left_str = self.left.format(fmt) right_str = self.right.format(fmt) return f"({cond_str} ? {left_str} : {right_str})" @dataclass(frozen=True, eq=False) class UnaryOp(Condition): op: str expr: Expression type: Type def dependencies(self) -> List[Expression]: return [self.expr] @staticmethod def sint(op: str, expr: Expression) -> "UnaryOp": expr = as_sintish(expr, silent=True) return UnaryOp( op=op, expr=expr, type=expr.type, ) def negated(self) -> "Condition": if self.op == "!" and isinstance(self.expr, (UnaryOp, BinaryOp)): return self.expr return UnaryOp("!", self, type=Type.bool()) def format(self, fmt: Formatter) -> str: # These aren't real operators (or functions); format them as a fn call if self.op in PSEUDO_FUNCTION_OPS: return f"{self.op}({self.expr.format(fmt)})" return f"{self.op}{self.expr.format(fmt)}" @dataclass(frozen=True, eq=False) class ExprCondition(Condition): expr: Expression type: Type is_negated: bool = False def dependencies(self) -> List[Expression]: return [self.expr] def negated(self) -> "Condition": return ExprCondition(self.expr, self.type, not self.is_negated) def format(self, fmt: Formatter) -> str: neg = "!" if self.is_negated else "" return f"{neg}{self.expr.format(fmt)}" @dataclass(frozen=True, eq=False) class CommaConditionExpr(Condition): statements: List["Statement"] condition: "Condition" type: Type = Type.bool() def dependencies(self) -> List[Expression]: assert False, "CommaConditionExpr should not be used within translate.py" return [] def negated(self) -> "Condition": return CommaConditionExpr(self.statements, self.condition.negated()) def format(self, fmt: Formatter) -> str: comma_joined = ", ".join( stmt.format(fmt).rstrip(";") for stmt in self.statements ) return f"({comma_joined}, {self.condition.format(fmt)})" @dataclass(frozen=True, eq=False) class Cast(Expression): expr: Expression type: Type reinterpret: bool = False silent: bool = True def dependencies(self) -> List[Expression]: return [self.expr] def use(self) -> None: self.expr.type.unify(self.type) super().use() def needed_for_store(self) -> bool: if not self.reinterpret: return True if not self.expr.type.unify(self.type): return True return False def is_trivial(self) -> bool: return ( self.reinterpret and self.expr.type.is_float() == self.type.is_float() and is_trivial_expression(self.expr) ) def format(self, fmt: Formatter) -> str: if self.reinterpret and self.expr.type.is_float() != self.type.is_float(): if fmt.valid_syntax: return ( f"MIPS2C_BITWISE({self.type.format(fmt)}, {self.expr.format(fmt)})" ) return f"(bitwise {self.type.format(fmt)}) {self.expr.format(fmt)}" if self.reinterpret and ( self.silent or (is_type_obvious(self.expr) and self.expr.type.unify(self.type)) ): return self.expr.format(fmt) if fmt.skip_casts: return self.expr.format(fmt) # Function casts require special logic because function calls have # higher precedence than casts fn_sig = self.type.get_function_pointer_signature() if fn_sig: prototype_sig = self.expr.type.get_function_pointer_signature() if not prototype_sig or not prototype_sig.unify_with_args(fn_sig): # A function pointer cast is required if the inner expr is not # a function pointer, or has incompatible argument types return f"(({self.type.format(fmt)}) {self.expr.format(fmt)})" if not prototype_sig.return_type.unify(fn_sig.return_type): # Only cast the return value of the call return f"({fn_sig.return_type.format(fmt)}) {self.expr.format(fmt)}" # No cast needed return self.expr.format(fmt) return f"({self.type.format(fmt)}) {self.expr.format(fmt)}" @dataclass(frozen=True, eq=False) class FuncCall(Expression): function: Expression args: List[Expression] type: Type def dependencies(self) -> List[Expression]: return self.args + [self.function] def format(self, fmt: Formatter) -> str: # TODO: The function type may have a different number of params than it had # when the FuncCall was created. Should we warn that there may be the wrong # number of arguments at this callsite? args = ", ".join(format_expr(arg, fmt) for arg in self.args) return f"{self.function.format(fmt)}({args})" @dataclass(frozen=True, eq=True) class LocalVar(Expression): value: int type: Type = field(compare=False) path: Optional[AccessPath] = field(compare=False) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: fallback_name = f"unksp{format_hex(self.value)}" if self.path is None: return fallback_name name = StructAccess.access_path_to_field_name(self.path, fmt) if name.startswith("->"): return name[2:] return fallback_name def toplevel_decl(self, fmt: Formatter) -> Optional[str]: # If len(self.path) > 2, then this local is an inner field of another # local, so it doesn't need to be declared. if ( self.path is None or len(self.path) != 2 or not isinstance(self.path[1], str) ): return None return self.type.to_decl(self.path[1], fmt) @dataclass(frozen=True, eq=False) class RegisterVar(Expression): reg: Register name: str type: Type def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: return self.name @dataclass(frozen=True, eq=True) class PassedInArg(Expression): value: int copied: bool = field(compare=False) stack_info: StackInfo = field(compare=False, repr=False) type: Type = field(compare=False) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: assert self.value % 4 == 0 name = self.stack_info.get_param_name(self.value) return name or f"arg{format_hex(self.value // 4)}" @dataclass(frozen=True, eq=True) class SubroutineArg(Expression): value: int type: Type = field(compare=False) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter) -> str: return f"subroutine_arg{format_hex(self.value // 4)}" @dataclass(eq=True, unsafe_hash=True) class StructAccess(Expression): # that may invalidate it. struct_var: Expression offset: int target_size: Optional[int] field_path: Optional[AccessPath] = field(compare=False) stack_info: Optional[StackInfo] = field(compare=False, repr=False) type: Type = field(compare=False) checked_late_field_path: bool = field(default=False, compare=False) def __post_init__(self) -> None: # stack_info is used to resolve field_path late assert ( self.stack_info is not None or self.field_path is not None ), "Must provide at least one of (stack_info, field_path)" self.assert_valid_field_path(self.field_path) @staticmethod def assert_valid_field_path(path: Optional[AccessPath]) -> None: assert path is None or ( path and isinstance(path[0], int) ), "The first element of the field path, if present, must be an int" @classmethod def access_path_to_field_name(cls, path: AccessPath, fmt: Formatter) -> str: cls.assert_valid_field_path(path) output = "" # Replace an initial "[0]." with "->" if len(path) >= 2 and path[0] == 0 and isinstance(path[1], str): output += f"->{path[1]}" path = path[2:] for p in path: if isinstance(p, str): output += f".{p}" elif isinstance(p, int): output += f"[{fmt.format_int(p)}]" else: static_assert_unreachable(p) return output def dependencies(self) -> List[Expression]: return [self.struct_var] def make_reference(self) -> Optional["StructAccess"]: field_path = self.late_field_path() if field_path and len(field_path) >= 2 and field_path[-1] == 0: return replace(self, field_path=field_path[:-1]) return None def late_field_path(self) -> Optional[AccessPath]: # If we didn't have a type at the time when the struct access was if self.field_path is None and not self.checked_late_field_path: var = late_unwrap(self.struct_var) var.format(Formatter()) field_path, field_type, _ = var.type.get_deref_field( self.offset, target_size=self.target_size ) if field_path is not None: self.assert_valid_field_path(field_path) self.field_path = field_path self.type.unify(field_type) self.checked_late_field_path = True return self.field_path def late_has_known_type(self) -> bool: if self.late_field_path() is not None: return True assert ( self.stack_info is not None ), "StructAccess must have stack_info if field_path isn't set" if self.offset == 0: var = late_unwrap(self.struct_var) if ( not self.stack_info.has_nonzero_access(var) and isinstance(var, AddressOf) and isinstance(var.expr, GlobalSymbol) and var.expr.type_provided ): return True return False def format(self, fmt: Formatter) -> str: var = late_unwrap(self.struct_var) has_nonzero_access = False if self.stack_info is not None: has_nonzero_access = self.stack_info.has_nonzero_access(var) field_path = self.late_field_path() if field_path is not None and field_path != [0]: has_nonzero_access = True elif fmt.valid_syntax and (self.offset != 0 or has_nonzero_access): offset_str = fmt.format_int(self.offset) return f"MIPS2C_FIELD({var.format(fmt)}, {Type.ptr(self.type).format(fmt)}, {offset_str})" else: prefix = "unk" + ("_" if fmt.coding_style.unknown_underscore else "") field_path = [0, prefix + format_hex(self.offset)] field_name = self.access_path_to_field_name(field_path, fmt) # Rewrite `(&x)->y` to `x.y` by stripping `AddressOf` & setting deref=False deref = True if ( isinstance(var, AddressOf) and not var.expr.type.is_array() and field_name.startswith("->") ): var = var.expr field_name = field_name.replace("->", ".", 1) deref = False # Rewrite `x->unk0` to `*x` and `x.unk0` to `x`, unless has_nonzero_access if self.offset == 0 and not has_nonzero_access: return f"{'*' if deref else ''}{var.format(fmt)}" return f"{parenthesize_for_struct_access(var, fmt)}{field_name}" @dataclass(frozen=True, eq=True) class ArrayAccess(Expression): # Represents ptr[index]. eq=True for symmetry with StructAccess. ptr: Expression index: Expression type: Type = field(compare=False) def dependencies(self) -> List[Expression]: return [self.ptr, self.index] def format(self, fmt: Formatter) -> str: base = parenthesize_for_struct_access(self.ptr, fmt) index = format_expr(self.index, fmt) return f"{base}[{index}]" @dataclass(eq=False) class GlobalSymbol(Expression): symbol_name: str type: Type asm_data_entry: Optional[AsmDataEntry] = None symbol_in_context: bool = False type_provided: bool = False initializer_in_typemap: bool = False demangled_str: Optional[str] = None def dependencies(self) -> List[Expression]: return [] def is_string_constant(self) -> bool: ent = self.asm_data_entry if not ent or not ent.is_string: return False return len(ent.data) == 1 and isinstance(ent.data[0], bytes) def format_string_constant(self, fmt: Formatter) -> str: assert self.is_string_constant(), "checked by caller" assert self.asm_data_entry and isinstance(self.asm_data_entry.data[0], bytes) has_trailing_null = False data = self.asm_data_entry.data[0] while data and data[-1] == 0: data = data[:-1] has_trailing_null = True data = b"".join(map(escape_byte, data)) strdata = data.decode("utf-8", "backslashreplace") ret = f'"{strdata}"' if not has_trailing_null: ret += " /* not null-terminated */" return ret def format(self, fmt: Formatter) -> str: return self.symbol_name def potential_array_dim(self, element_size: int) -> Tuple[int, int]: # If we don't have the .data/.rodata entry for this symbol, we can't guess # its array dimension. Jump tables are ignored and not treated as arrays. if self.asm_data_entry is None or self.asm_data_entry.is_jtbl: return 0, element_size min_data_size, max_data_size = self.asm_data_entry.size_range_bytes() if element_size > max_data_size: # The type is too big for the data (not an array) return 0, max_data_size # Check if it's possible that this symbol is not an array, and is just 1 element if min_data_size <= element_size <= max_data_size and not self.type.is_array(): return 1, 0 array_dim, extra_bytes = divmod(min_data_size, element_size) if extra_bytes != 0: # bytes from the padding, then indicate that in the return value. padding_bytes = element_size - extra_bytes if min_data_size + padding_bytes > max_data_size: return array_dim, extra_bytes # Include potential padding in the array. Although this is unlikely to match the original C, # it's much easier to manually remove all or some of these elements than to add them back in. return max_data_size // element_size, 0 @dataclass(frozen=True, eq=True) class Literal(Expression): value: int type: Type = field(compare=False, default_factory=Type.any) elide_cast: bool = field(compare=False, default=False) def dependencies(self) -> List[Expression]: return [] def format(self, fmt: Formatter, force_dec: bool = False) -> str: enum_name = self.type.get_enum_name(self.value) if enum_name is not None: return enum_name if self.type.is_likely_float(): if self.type.get_size_bits() == 64: return format_f64_imm(self.value) else: return format_f32_imm(self.value) + "f" if self.type.is_pointer() and self.value == 0: return "NULL" prefix = "" suffix = "" if not fmt.skip_casts and not self.elide_cast: if self.type.is_pointer(): prefix = f"({self.type.format(fmt)})" if self.type.is_unsigned(): suffix = "U" if force_dec: value = str(self.value) else: size_bits = self.type.get_size_bits() v = self.value if ( self.type.is_signed() and size_bits and v & (1 << (size_bits - 1)) and v > (3 << (size_bits - 2)) and v < 2 ** size_bits ): v -= 1 << size_bits value = fmt.format_int(v, size_bits=size_bits) return prefix + value + suffix def likely_partial_offset(self) -> bool: return self.value % 2 ** 15 in (0, 2 ** 15 - 1) and self.value < 0x1000000 @dataclass(frozen=True, eq=True) class AddressOf(Expression): expr: Expression type: Type = field(compare=False, default_factory=Type.ptr) def dependencies(self) -> List[Expression]: return [self.expr] def format(self, fmt: Formatter) -> str: if isinstance(self.expr, GlobalSymbol): if self.expr.is_string_constant(): return self.expr.format_string_constant(fmt) if self.expr.type.is_array(): return f"{self.expr.format(fmt)}" if self.expr.type.is_function(): return f"{self.expr.format(fmt)}" if isinstance(self.expr, StructAccess): ref = self.expr.make_reference() if ref: return f"{ref.format(fmt)}" return f"&{self.expr.format(fmt)}" @dataclass(frozen=True) class Lwl(Expression): load_expr: Expression key: Tuple[int, object] type: Type = field(compare=False, default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [self.load_expr] def format(self, fmt: Formatter) -> str: return f"MIPS2C_LWL({self.load_expr.format(fmt)})" @dataclass(frozen=True) class Load3Bytes(Expression): load_expr: Expression type: Type = field(compare=False, default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [self.load_expr] def format(self, fmt: Formatter) -> str: if fmt.valid_syntax: return f"MIPS2C_FIRST3BYTES({self.load_expr.format(fmt)})" return f"(first 3 bytes) {self.load_expr.format(fmt)}" @dataclass(frozen=True) class UnalignedLoad(Expression): load_expr: Expression type: Type = field(compare=False, default_factory=Type.any_reg) def dependencies(self) -> List[Expression]: return [self.load_expr] def format(self, fmt: Formatter) -> str: if fmt.valid_syntax: return f"MIPS2C_UNALIGNED32({self.load_expr.format(fmt)})" return f"(unaligned s32) {self.load_expr.format(fmt)}" @dataclass(frozen=False, eq=False) class EvalOnceExpr(Expression): wrapped_expr: Expression var: Var type: Type emit_exactly_once: bool trivial: bool forced_emit: bool = False num_usages: int = 0 def dependencies(self) -> List[Expression]: if self.need_decl(): return [] return [self.wrapped_expr] def use(self) -> None: self.num_usages += 1 if self.trivial or (self.num_usages == 1 and not self.emit_exactly_once): self.wrapped_expr.use() def force(self) -> None: # getting this wrong are pretty mild -- it just causes extraneous var # emission in rare cases. self.trivial = False self.forced_emit = True self.use() self.use() def need_decl(self) -> bool: return self.num_usages > 1 and not self.trivial def format(self, fmt: Formatter) -> str: if not self.need_decl(): return self.wrapped_expr.format(fmt) else: return self.var.format(fmt) @dataclass(frozen=False, eq=False) class PhiExpr(Expression): reg: Register node: Node type: Type used_phis: List["PhiExpr"] name: Optional[str] = None num_usages: int = 0 replacement_expr: Optional[Expression] = None used_by: Optional["PhiExpr"] = None def dependencies(self) -> List[Expression]: return [] def get_var_name(self) -> str: return self.name or f"unnamed-phi({self.reg.register_name})" def use(self, from_phi: Optional["PhiExpr"] = None) -> None: if self.num_usages == 0: self.used_phis.append(self) self.used_by = from_phi self.num_usages += 1 if self.used_by != from_phi: self.used_by = None if self.replacement_expr is not None: self.replacement_expr.use() def propagates_to(self) -> "PhiExpr": if self.used_by is None or self.replacement_expr is not None: return self return self.used_by.propagates_to() def format(self, fmt: Formatter) -> str: if self.replacement_expr: return self.replacement_expr.format(fmt) return self.get_var_name() @dataclass class SwitchControl: control_expr: Expression jump_table: Optional[GlobalSymbol] = None offset: int = 0 is_irregular: bool = False def matches_guard_condition(self, cond: Condition) -> bool: cmp_expr = simplify_condition(cond) if not isinstance(cmp_expr, BinaryOp) or cmp_expr.op not in (">=", ">"): return False cmp_exclusive = cmp_expr.op == ">" # The LHS may have been wrapped in a u32 cast left_expr = late_unwrap(cmp_expr.left) if isinstance(left_expr, Cast): left_expr = late_unwrap(left_expr.expr) if self.offset != 0: if ( not isinstance(left_expr, BinaryOp) or late_unwrap(left_expr.left) != late_unwrap(self.control_expr) or left_expr.op != "+" or late_unwrap(left_expr.right) != Literal(-self.offset) ): return False elif left_expr != late_unwrap(self.control_expr): return False right_expr = late_unwrap(cmp_expr.right) if ( self.jump_table is None or self.jump_table.asm_data_entry is None or not self.jump_table.asm_data_entry.is_jtbl or not isinstance(right_expr, Literal) ): return False # Count the number of labels (exclude padding bytes) jump_table_len = sum( isinstance(e, str) for e in self.jump_table.asm_data_entry.data ) return right_expr.value + int(cmp_exclusive) == jump_table_len @staticmethod def irregular_from_expr(control_expr: Expression) -> "SwitchControl": return SwitchControl( control_expr=control_expr, jump_table=None, offset=0, is_irregular=True, ) @staticmethod def from_expr(expr: Expression) -> "SwitchControl": # The "error" expression we use if we aren't able to parse `expr` error_expr = SwitchControl(expr) struct_expr = early_unwrap(expr) if not isinstance(struct_expr, StructAccess) or struct_expr.offset != 0: return error_expr add_expr = early_unwrap(struct_expr.struct_var) if not isinstance(add_expr, BinaryOp) or add_expr.op != "+": return error_expr left_expr, right_expr = early_unwrap(add_expr.left), early_unwrap( add_expr.right ) if isinstance(left_expr, AddressOf) and isinstance( left_expr.expr, GlobalSymbol ): jtbl_addr_expr, mul_expr = left_expr, right_expr elif isinstance(right_expr, AddressOf) and isinstance( right_expr.expr, GlobalSymbol ): mul_expr, jtbl_addr_expr = left_expr, right_expr else: return error_expr jump_table = jtbl_addr_expr.expr assert isinstance(jump_table, GlobalSymbol) if ( not isinstance(mul_expr, BinaryOp) or mul_expr.op != "*" or early_unwrap(mul_expr.right) != Literal(4) ): return error_expr control_expr = mul_expr.left offset = 0 uw_control_expr = early_unwrap(control_expr) if isinstance(uw_control_expr, BinaryOp) and uw_control_expr.op == "+": offset_lit = early_unwrap(uw_control_expr.right) if isinstance(offset_lit, Literal): control_expr = uw_control_expr.left offset = -offset_lit.value if jump_table.asm_data_entry is None or not jump_table.asm_data_entry.is_jtbl: return error_expr return SwitchControl(control_expr, jump_table, offset) @dataclass class EvalOnceStmt(Statement): expr: EvalOnceExpr def need_decl(self) -> bool: return self.expr.need_decl() def should_write(self) -> bool: if self.expr.emit_exactly_once: return self.expr.num_usages != 1 else: return self.need_decl() def format(self, fmt: Formatter) -> str: val_str = format_expr(elide_casts_for_store(self.expr.wrapped_expr), fmt) if self.expr.emit_exactly_once and self.expr.num_usages == 0: return f"{val_str};" return f"{self.expr.var.format(fmt)} = {val_str};" @dataclass class SetPhiStmt(Statement): phi: PhiExpr expr: Expression def should_write(self) -> bool: expr = self.expr if isinstance(expr, PhiExpr) and expr.propagates_to() != expr: assert expr.propagates_to() == self.phi.propagates_to() return False if late_unwrap(expr) == self.phi.propagates_to(): return False return True def format(self, fmt: Formatter) -> str: return format_assignment(self.phi.propagates_to(), self.expr, fmt) @dataclass class ExprStmt(Statement): expr: Expression def should_write(self) -> bool: return True def format(self, fmt: Formatter) -> str: return f"{format_expr(self.expr, fmt)};" @dataclass class StoreStmt(Statement): source: Expression dest: Expression def should_write(self) -> bool: return True def format(self, fmt: Formatter) -> str: dest = self.dest source = self.source if ( isinstance(dest, StructAccess) and dest.late_has_known_type() ) or isinstance(dest, (ArrayAccess, LocalVar, RegisterVar, SubroutineArg)): source = elide_casts_for_store(source) return format_assignment(dest, source, fmt) @dataclass class CommentStmt(Statement): contents: str def should_write(self) -> bool: return True def format(self, fmt: Formatter) -> str: return f"// {self.contents}" def error_stmt(msg: str) -> ExprStmt: return ExprStmt(ErrorExpr(msg)) @dataclass(frozen=True) class AddressMode: offset: int rhs: Register def __str__(self) -> str: if self.offset: return f"{self.offset}({self.rhs})" else: return f"({self.rhs})" @dataclass(frozen=True) class RawSymbolRef: offset: int sym: AsmGlobalSymbol def __str__(self) -> str: if self.offset: return f"{self.sym.symbol_name} + {self.offset}" else: return self.sym.symbol_name @dataclass class RegMeta: inherited: bool = False is_read: bool = False function_return: bool = False # function_return = True, or is a passed in argument uninteresting: bool = False # True if the regdata must be replaced by variable if it is ever read force: bool = False # True if the regdata was assigned by an Instruction marked as in_pattern; # it was part of a matched IR pattern but couldn't be elided at the time in_pattern: bool = False @dataclass class RegData: value: Expression meta: RegMeta @dataclass class RegInfo: stack_info: StackInfo = field(repr=False) contents: Dict[Register, RegData] = field(default_factory=dict) read_inherited: Set[Register] = field(default_factory=set) _active_instr: Optional[Instruction] = None def __getitem__(self, key: Register) -> Expression: if self._active_instr is not None and key not in self._active_instr.inputs: lineno = self._active_instr.meta.lineno return ErrorExpr(f"Read from unset register {key} on line {lineno}") if key == Register("zero"): return Literal(0) data = self.contents.get(key) if data is None: return ErrorExpr(f"Read from unset register {key}") ret = data.value data.meta.is_read = True if data.meta.inherited: self.read_inherited.add(key) if isinstance(ret, PassedInArg) and not ret.copied: val, arg = self.stack_info.get_argument(ret.value) self.stack_info.add_argument(arg) val.type.unify(ret.type) return val if data.meta.force: assert isinstance(ret, EvalOnceExpr) ret.force() return ret def __contains__(self, key: Register) -> bool: return key in self.contents def __setitem__(self, key: Register, value: Expression) -> None: self.set_with_meta(key, value, RegMeta()) def set_with_meta(self, key: Register, value: Expression, meta: RegMeta) -> None: if self._active_instr is not None and key not in self._active_instr.outputs: raise DecompFailure(f"Undeclared write to {key} in {self._active_instr}") self.unchecked_set_with_meta(key, value, meta) def unchecked_set_with_meta( self, key: Register, value: Expression, meta: RegMeta ) -> None: assert key != Register("zero") self.contents[key] = RegData(value, meta) def __delitem__(self, key: Register) -> None: assert key != Register("zero") del self.contents[key] def get_raw(self, key: Register) -> Optional[Expression]: data = self.contents.get(key) return data.value if data is not None else None def get_meta(self, key: Register) -> Optional[RegMeta]: data = self.contents.get(key) return data.meta if data is not None else None @contextmanager def current_instr(self, instr: Instruction) -> Iterator[None]: self._active_instr = instr try: with current_instr(instr): yield finally: self._active_instr = None def __str__(self) -> str: return ", ".join( f"{k}: {v.value}" for k, v in sorted(self.contents.items(), key=lambda x: x[0].register_name) if not self.stack_info.should_save(v.value, None) ) @dataclass class BlockInfo: to_write: List[Statement] return_value: Optional[Expression] switch_control: Optional[SwitchControl] branch_condition: Optional[Condition] final_register_states: RegInfo has_function_call: bool def __str__(self) -> str: newline = "\n\t" return "\n".join( [ f"Statements: {newline.join(str(w) for w in self.statements_to_write())}", f"Branch condition: {self.branch_condition}", f"Final register states: {self.final_register_states}", ] ) def statements_to_write(self) -> List[Statement]: return [st for st in self.to_write if st.should_write()] def get_block_info(node: Node) -> BlockInfo: ret = node.block.block_info assert isinstance(ret, BlockInfo) return ret @dataclass class InstrArgs: raw_args: List[Argument] regs: RegInfo = field(repr=False) stack_info: StackInfo = field(repr=False) def raw_arg(self, index: int) -> Argument: assert index >= 0 if index >= len(self.raw_args): raise DecompFailure( f"Too few arguments for instruction, expected at least {index + 1}" ) return self.raw_args[index] def reg_ref(self, index: int) -> Register: ret = self.raw_arg(index) if not isinstance(ret, Register): raise DecompFailure( f"Expected instruction argument to be a register, but found {ret}" ) return ret def imm_value(self, index: int) -> int: arg = self.full_imm(index) assert isinstance(arg, Literal) return arg.value def reg(self, index: int) -> Expression: return self.regs[self.reg_ref(index)] def dreg(self, index: int) -> Expression: reg = self.reg_ref(index) if not reg.is_float(): raise DecompFailure( f"Expected instruction argument {reg} to be a float register" ) ret = self.regs[reg] # PPC: FPR's hold doubles (64 bits), so we don't need to do anything special if self.stack_info.global_info.arch.arch == Target.ArchEnum.PPC: return ret # MIPS: Look at the paired FPR to get the full 64-bit value if not isinstance(ret, Literal) or ret.type.get_size_bits() == 64: return ret reg_num = int(reg.register_name[1:]) if reg_num % 2 != 0: raise DecompFailure( "Tried to use a double-precision instruction with odd-numbered float " f"register {reg}" ) other = self.regs[Register(f"f{reg_num+1}")] if not isinstance(other, Literal) or other.type.get_size_bits() == 64: raise DecompFailure( f"Unable to determine a value for double-precision register {reg} " "whose second half is non-static. This is a mips_to_c restriction " "which may be lifted in the future." ) value = ret.value | (other.value << 32) return Literal(value, type=Type.f64()) def cmp_reg(self, key: str) -> Condition: cond = self.regs[Register(key)] if not isinstance(cond, Condition): cond = BinaryOp.icmp(cond, "!=", Literal(0)) return cond def full_imm(self, index: int) -> Expression: arg = strip_macros(self.raw_arg(index)) ret = literal_expr(arg, self.stack_info) return ret def imm(self, index: int) -> Expression: ret = self.full_imm(index) if isinstance(ret, Literal): return Literal(((ret.value + 0x8000) & 0xFFFF) - 0x8000) return ret def unsigned_imm(self, index: int) -> Expression: ret = self.full_imm(index) if isinstance(ret, Literal): return Literal(ret.value & 0xFFFF) return ret def hi_imm(self, index: int) -> Argument: arg = self.raw_arg(index) if not isinstance(arg, Macro) or arg.macro_name not in ("hi", "ha", "h"): raise DecompFailure( f"Got lui/lis instruction with macro other than %hi/@ha/@h: {arg}" ) return arg.argument def shifted_imm(self, index: int) -> Expression: # TODO: Should this be part of hi_imm? Do we need to handle @ha? raw_imm = self.unsigned_imm(index) assert isinstance(raw_imm, Literal) return Literal(raw_imm.value << 16) def memory_ref(self, index: int) -> Union[AddressMode, RawSymbolRef]: ret = strip_macros(self.raw_arg(index)) # In MIPS, we want to allow "lw $v0, symbol + 4", which is outputted by # some disassemblers (like IDA) even though it isn't valid assembly. if isinstance(ret, AsmGlobalSymbol): return RawSymbolRef(offset=0, sym=ret) if ( isinstance(ret, BinOp) and ret.op in "+-" and isinstance(ret.lhs, AsmGlobalSymbol) and isinstance(ret.rhs, AsmLiteral) ): sign = 1 if ret.op == "+" else -1 return RawSymbolRef(offset=(ret.rhs.value * sign), sym=ret.lhs) if not isinstance(ret, AsmAddressMode): raise DecompFailure( "Expected instruction argument to be of the form offset($register), " f"but found {ret}" ) if not isinstance(ret.lhs, AsmLiteral): raise DecompFailure( f"Unable to parse offset for instruction argument {ret}. " "Expected a constant or a %lo macro." ) return AddressMode(offset=ret.lhs.signed_value(), rhs=ret.rhs) def count(self) -> int: return len(self.raw_args) def deref( arg: Union[AddressMode, RawSymbolRef, Expression], regs: RegInfo, stack_info: StackInfo, *, size: int, store: bool = False, ) -> Expression: if isinstance(arg, Expression): offset = 0 var = arg elif isinstance(arg, AddressMode): offset = arg.offset if stack_info.is_stack_reg(arg.rhs): return stack_info.get_stack_var(offset, store=store) var = regs[arg.rhs] else: offset = arg.offset var = stack_info.global_info.address_of_gsym(arg.sym.symbol_name) if isinstance(var, Literal) and var.value % (2 ** 16) == 0: var = Literal(var.value + offset, type=var.type) offset = 0 uw_var = early_unwrap(var) if isinstance(uw_var, BinaryOp) and uw_var.op == "+": for base, addend in [(uw_var.left, uw_var.right), (uw_var.right, uw_var.left)]: if isinstance(addend, Literal) and addend.likely_partial_offset(): offset += addend.value var = base uw_var = early_unwrap(var) break var.type.unify(Type.ptr()) stack_info.record_struct_access(var, offset) field_name: Optional[str] = None type: Type = stack_info.unique_type_for("struct", (uw_var, offset), Type.any()) array_expr = array_access_from_add( var, offset, stack_info, target_size=size, ptr=False ) if array_expr is not None: return array_expr field_path, field_type, _ = var.type.get_deref_field(offset, target_size=size) if field_path is not None: field_type.unify(type) type = field_type else: field_path = None return StructAccess( struct_var=var, offset=offset, target_size=size, field_path=field_path, stack_info=stack_info, type=type, ) def is_trivial_expression(expr: Expression) -> bool: if isinstance( expr, ( EvalOnceExpr, Literal, GlobalSymbol, LocalVar, PassedInArg, PhiExpr, RegisterVar, SubroutineArg, ), ): return True if isinstance(expr, AddressOf): return all(is_trivial_expression(e) for e in expr.dependencies()) if isinstance(expr, Cast): return expr.is_trivial() return False def is_type_obvious(expr: Expression) -> bool: if isinstance( expr, ( Cast, Literal, AddressOf, LocalVar, PhiExpr, PassedInArg, RegisterVar, FuncCall, ), ): return True if isinstance(expr, EvalOnceExpr): if expr.need_decl(): return True return is_type_obvious(expr.wrapped_expr) return False def simplify_condition(expr: Expression) -> Expression: if isinstance(expr, EvalOnceExpr) and not expr.need_decl(): return simplify_condition(expr.wrapped_expr) if isinstance(expr, UnaryOp): inner = simplify_condition(expr.expr) if expr.op == "!" and isinstance(inner, Condition): return inner.negated() return UnaryOp(expr=inner, op=expr.op, type=expr.type) if isinstance(expr, BinaryOp): left = simplify_condition(expr.left) right = simplify_condition(expr.right) if isinstance(left, BinaryOp) and left.is_comparison() and right == Literal(0): if expr.op == "==": return simplify_condition(left.negated()) if expr.op == "!=": return left if ( expr.is_comparison() and isinstance(left, Literal) and not isinstance(right, Literal) ): return BinaryOp( left=right, op=expr.op.translate(str.maketrans("<>", "><")), right=left, type=expr.type, ) return BinaryOp(left=left, op=expr.op, right=right, type=expr.type) return expr def balanced_parentheses(string: str) -> bool: bal = 0 for c in string: if c == "(": bal += 1 elif c == ")": if bal == 0: return False bal -= 1 return bal == 0 def format_expr(expr: Expression, fmt: Formatter) -> str: ret = expr.format(fmt) if ret.startswith("(") and balanced_parentheses(ret[1:-1]): return ret[1:-1] return ret def format_assignment(dest: Expression, source: Expression, fmt: Formatter) -> str: dest = late_unwrap(dest) source = late_unwrap(source) if isinstance(source, BinaryOp) and source.op in COMPOUND_ASSIGNMENT_OPS: rhs = None if late_unwrap(source.left) == dest: rhs = source.right elif late_unwrap(source.right) == dest and source.op in ASSOCIATIVE_OPS: rhs = source.left if rhs is not None: return f"{dest.format(fmt)} {source.op}= {format_expr(rhs, fmt)};" return f"{dest.format(fmt)} = {format_expr(source, fmt)};" def parenthesize_for_struct_access(expr: Expression, fmt: Formatter) -> str: s = expr.format(fmt) if ( s.startswith("*") or s.startswith("&") or (isinstance(expr, Cast) and expr.needed_for_store()) ): return f"({s})" return s def elide_casts_for_store(expr: Expression) -> Expression: uw_expr = late_unwrap(expr) if isinstance(uw_expr, Cast) and not uw_expr.needed_for_store(): return elide_casts_for_store(uw_expr.expr) if isinstance(uw_expr, Literal) and uw_expr.type.is_int(): return replace(uw_expr, elide_cast=True) return uw_expr def uses_expr(expr: Expression, expr_filter: Callable[[Expression], bool]) -> bool: if expr_filter(expr): return True for e in expr.dependencies(): if uses_expr(e, expr_filter): return True return False def late_unwrap(expr: Expression) -> Expression: if isinstance(expr, EvalOnceExpr) and not expr.need_decl(): return late_unwrap(expr.wrapped_expr) if isinstance(expr, PhiExpr) and expr.replacement_expr is not None: return late_unwrap(expr.replacement_expr) return expr def early_unwrap(expr: Expression) -> Expression: if ( isinstance(expr, EvalOnceExpr) and not expr.forced_emit and not expr.emit_exactly_once ): return early_unwrap(expr.wrapped_expr) return expr def early_unwrap_ints(expr: Expression) -> Expression: uw_expr = early_unwrap(expr) if isinstance(uw_expr, Cast) and uw_expr.reinterpret and uw_expr.type.is_int(): return early_unwrap_ints(uw_expr.expr) return uw_expr def unwrap_deep(expr: Expression) -> Expression: if isinstance(expr, EvalOnceExpr): return unwrap_deep(expr.wrapped_expr) return expr def literal_expr(arg: Argument, stack_info: StackInfo) -> Expression: if isinstance(arg, AsmGlobalSymbol): return stack_info.global_info.address_of_gsym(arg.symbol_name) if isinstance(arg, AsmLiteral): return Literal(arg.value) if isinstance(arg, BinOp): lhs = literal_expr(arg.lhs, stack_info) rhs = literal_expr(arg.rhs, stack_info) return BinaryOp.int(left=lhs, op=arg.op, right=rhs) raise DecompFailure(f"Instruction argument {arg} must be a literal") def imm_add_32(expr: Expression) -> Expression: if isinstance(expr, Literal): return as_intish(Literal(expr.value + 32)) else: return BinaryOp.int(expr, "+", Literal(32)) def fn_op(fn_name: str, args: List[Expression], type: Type) -> FuncCall: fn_sig = FunctionSignature( return_type=type, params=[FunctionParam(type=arg.type) for arg in args], params_known=True, is_variadic=False, ) return FuncCall( function=GlobalSymbol(symbol_name=fn_name, type=Type.function(fn_sig)), args=args, type=type, ) def void_fn_op(fn_name: str, args: List[Expression]) -> ExprStmt: fn_call = fn_op(fn_name, args, Type.any_reg()) fn_call.use() return ExprStmt(fn_call) def load_upper(args: InstrArgs) -> Expression: arg = args.raw_arg(1) if not isinstance(arg, Macro): assert not isinstance( arg, Literal ), "normalize_instruction should convert lui/lis <literal> to li" raise DecompFailure( f"lui/lis argument must be a literal or %hi/@ha macro, found {arg}" ) hi_arg = args.hi_imm(1) if ( isinstance(hi_arg, BinOp) and hi_arg.op in "+-" and isinstance(hi_arg.lhs, AsmGlobalSymbol) and isinstance(hi_arg.rhs, AsmLiteral) ): sym = hi_arg.lhs offset = hi_arg.rhs.value * (-1 if hi_arg.op == "-" else 1) elif isinstance(hi_arg, AsmGlobalSymbol): sym = hi_arg offset = 0 else: raise DecompFailure(f"Invalid %hi/@ha argument {hi_arg}") stack_info = args.stack_info source = stack_info.global_info.address_of_gsym(sym.symbol_name) imm = Literal(offset) return handle_addi_real(args.reg_ref(0), None, source, imm, stack_info) def handle_convert(expr: Expression, dest_type: Type, source_type: Type) -> Cast: silent = dest_type.data().kind != source_type.data().kind expr.type.unify(source_type) return Cast(expr=expr, type=dest_type, silent=silent, reinterpret=False) def handle_la(args: InstrArgs) -> Expression: target = args.memory_ref(1) stack_info = args.stack_info if isinstance(target, AddressMode): return handle_addi( InstrArgs( raw_args=[args.reg_ref(0), target.rhs, AsmLiteral(target.offset)], regs=args.regs, stack_info=args.stack_info, ) ) var = stack_info.global_info.address_of_gsym(target.sym.symbol_name) return add_imm(var, Literal(target.offset), stack_info) def handle_or(left: Expression, right: Expression) -> Expression: if left == right: return left if isinstance(left, Literal) and isinstance(right, Literal): if (((left.value & 0xFFFF) == 0 and (right.value & 0xFFFF0000) == 0)) or ( (right.value & 0xFFFF) == 0 and (left.value & 0xFFFF0000) == 0 ): return Literal(value=(left.value | right.value)) return BinaryOp.int(left=left, op="|", right=right) def handle_sltu(args: InstrArgs) -> Expression: right = args.reg(2) if args.reg_ref(1) == Register("zero"): uw_right = early_unwrap(right) if isinstance(uw_right, BinaryOp) and uw_right.op == "^": return BinaryOp.icmp(uw_right.left, "!=", uw_right.right) return BinaryOp.icmp(right, "!=", Literal(0)) else: left = args.reg(1) return BinaryOp.ucmp(left, "<", right) def handle_sltiu(args: InstrArgs) -> Expression: left = args.reg(1) right = args.imm(2) if isinstance(right, Literal): value = right.value & 0xFFFFFFFF if value == 1: uw_left = early_unwrap(left) if isinstance(uw_left, BinaryOp) and uw_left.op == "^": return BinaryOp.icmp(uw_left.left, "==", uw_left.right) return BinaryOp.icmp(left, "==", Literal(0)) else: right = Literal(value) return BinaryOp.ucmp(left, "<", right) def handle_addi(args: InstrArgs) -> Expression: stack_info = args.stack_info source_reg = args.reg_ref(1) source = args.reg(1) imm = args.imm(2) uw_source = early_unwrap(source) if ( isinstance(uw_source, BinaryOp) and uw_source.op == "+" and isinstance(uw_source.right, Literal) and uw_source.right.value % 0x10000 == 0 and isinstance(imm, Literal) ): return add_imm( uw_source.left, Literal(imm.value + uw_source.right.value), stack_info ) return handle_addi_real(args.reg_ref(0), source_reg, source, imm, stack_info) def handle_addis(args: InstrArgs) -> Expression: stack_info = args.stack_info source_reg = args.reg_ref(1) source = args.reg(1) imm = args.shifted_imm(2) return handle_addi_real(args.reg_ref(0), source_reg, source, imm, stack_info) def handle_addi_real( output_reg: Register, source_reg: Optional[Register], source: Expression, imm: Expression, stack_info: StackInfo, ) -> Expression: if source_reg is not None and stack_info.is_stack_reg(source_reg): assert isinstance(imm, Literal) if stack_info.is_stack_reg(output_reg): return source var = stack_info.get_stack_var(imm.value, store=False) if isinstance(var, LocalVar): stack_info.add_local_var(var) return AddressOf(var, type=var.type.reference()) else: return add_imm(source, imm, stack_info) def add_imm(source: Expression, imm: Expression, stack_info: StackInfo) -> Expression: if imm == Literal(0): return source elif source.type.is_pointer_or_array(): if isinstance(imm, Literal) and not imm.likely_partial_offset(): array_access = array_access_from_add( source, imm.value, stack_info, target_size=None, ptr=True ) if array_access is not None: return array_access field_path, field_type, _ = source.type.get_deref_field( imm.value, target_size=None ) if field_path is not None: return AddressOf( StructAccess( struct_var=source, offset=imm.value, target_size=None, field_path=field_path, stack_info=stack_info, type=field_type, ), type=field_type.reference(), ) if isinstance(imm, Literal): target = source.type.get_pointer_target() if target: target_size = target.get_size_bytes() if target_size and imm.value % target_size == 0: return BinaryOp( left=source, op="+", right=as_intish(imm), type=source.type ) return BinaryOp(left=source, op="+", right=as_intish(imm), type=Type.ptr()) elif isinstance(source, Literal) and isinstance(imm, Literal): return Literal(source.value + imm.value) else: return BinaryOp.intptr(left=source, op="+", right=imm) def handle_load(args: InstrArgs, type: Type) -> Expression: # Though really, it would be great to expose the load types somehow... size = type.get_size_bytes() assert size is not None expr = deref(args.memory_ref(1), args.regs, args.stack_info, size=size) # Detect rodata constants if isinstance(expr, StructAccess) and expr.offset == 0: target = early_unwrap(expr.struct_var) if ( isinstance(target, AddressOf) and isinstance(target.expr, GlobalSymbol) and type.is_likely_float() ): sym_name = target.expr.symbol_name ent = args.stack_info.global_info.asm_data_value(sym_name) if ( ent and ent.data and isinstance(ent.data[0], bytes) and len(ent.data[0]) >= size and ent.is_readonly and type.unify(target.expr.type) ): data = ent.data[0][:size] val: int if size == 4: (val,) = struct.unpack(">I", data) else: (val,) = struct.unpack(">Q", data) return Literal(value=val, type=type) return as_type(expr, type, silent=True) def deref_unaligned( arg: Union[AddressMode, RawSymbolRef], regs: RegInfo, stack_info: StackInfo, *, store: bool = False, ) -> Expression: # We don't know the correct size pass to deref. Passing None would signal that we return deref(arg, regs, stack_info, size=1, store=store) def handle_lwl(args: InstrArgs) -> Expression: # destination-first operation) ref = args.memory_ref(1) expr = deref_unaligned(ref, args.regs, args.stack_info) key: Tuple[int, object] if isinstance(ref, AddressMode): key = (ref.offset, args.regs[ref.rhs]) else: key = (ref.offset, ref.sym) return Lwl(expr, key) def handle_lwr(args: InstrArgs) -> Expression: # Unaligned load for the right part of a register. This lwr may merge with an # existing lwl, if it loads from the same target but with an offset that's +3. uw_old_value = early_unwrap(args.reg(0)) ref = args.memory_ref(1) lwl_key: Tuple[int, object] if isinstance(ref, AddressMode): lwl_key = (ref.offset - 3, args.regs[ref.rhs]) else: lwl_key = (ref.offset - 3, ref.sym) if isinstance(uw_old_value, Lwl) and uw_old_value.key[0] == lwl_key[0]: return UnalignedLoad(uw_old_value.load_expr) if ref.offset % 4 == 2: left_mem_ref = replace(ref, offset=ref.offset - 2) load_expr = deref_unaligned(left_mem_ref, args.regs, args.stack_info) return Load3Bytes(load_expr) return ErrorExpr("Unable to handle lwr; missing a corresponding lwl") def make_store(args: InstrArgs, type: Type) -> Optional[StoreStmt]: size = type.get_size_bytes() assert size is not None stack_info = args.stack_info source_reg = args.reg_ref(0) source_raw = args.regs.get_raw(source_reg) if type.is_likely_float() and size == 8: source_val = args.dreg(0) else: source_val = args.reg(0) target = args.memory_ref(1) is_stack = isinstance(target, AddressMode) and stack_info.is_stack_reg(target.rhs) if ( is_stack and source_raw is not None and stack_info.should_save(source_raw, target.offset) ): return None dest = deref(target, args.regs, stack_info, size=size, store=True) dest.type.unify(type) return StoreStmt(source=as_type(source_val, type, silent=is_stack), dest=dest) def make_storex(args: InstrArgs, type: Type) -> Optional[StoreStmt]: size = type.get_size_bytes() assert size is not None source = args.reg(0) ptr = BinaryOp.intptr(left=args.reg(1), op="+", right=args.reg(2)) dest = deref(ptr, args.regs, args.stack_info, size=size, store=True) dest.type.unify(type) return StoreStmt(source=as_type(source, type, silent=False), dest=dest) def handle_swl(args: InstrArgs) -> Optional[StoreStmt]: # swl in practice only occurs together with swr, so we can treat it as a regular # store, with the expression wrapped in UnalignedLoad if needed. source = args.reg(0) target = args.memory_ref(1) if not isinstance(early_unwrap(source), UnalignedLoad): source = UnalignedLoad(source) dest = deref_unaligned(target, args.regs, args.stack_info, store=True) return StoreStmt(source=source, dest=dest) def handle_swr(args: InstrArgs) -> Optional[StoreStmt]: expr = early_unwrap(args.reg(0)) target = args.memory_ref(1) if not isinstance(expr, Load3Bytes): # Elide swr's that don't come from 3-byte-loading lwr's; they probably return None real_target = replace(target, offset=target.offset - 2) dest = deref_unaligned(real_target, args.regs, args.stack_info, store=True) return StoreStmt(source=expr, dest=dest) def handle_sra(args: InstrArgs) -> Expression: lhs = args.reg(1) shift = args.imm(2) if isinstance(shift, Literal) and shift.value in [16, 24]: expr = early_unwrap(lhs) pow2 = 1 << shift.value if isinstance(expr, BinaryOp) and isinstance(expr.right, Literal): tp = Type.s16() if shift.value == 16 else Type.s8() rhs = expr.right.value if expr.op == "<<" and rhs == shift.value: return as_type(expr.left, tp, silent=False) elif expr.op == "<<" and rhs > shift.value: new_shift = fold_mul_chains( BinaryOp.int(expr.left, "<<", Literal(rhs - shift.value)) ) return as_type(new_shift, tp, silent=False) elif expr.op == "*" and rhs % pow2 == 0 and rhs != pow2: mul = BinaryOp.int(expr.left, "*", Literal(value=rhs // pow2)) return as_type(mul, tp, silent=False) return fold_divmod( BinaryOp(as_sintish(lhs), ">>", as_intish(shift), type=Type.s32()) ) def handle_conditional_move(args: InstrArgs, nonzero: bool) -> Expression: op = "!=" if nonzero else "==" type = Type.any_reg() return TernaryOp( BinaryOp.scmp(args.reg(2), op, Literal(0)), as_type(args.reg(1), type, silent=True), as_type(args.reg(0), type, silent=True), type, ) def format_f32_imm(num: int) -> str: packed = struct.pack(">I", num & (2 ** 32 - 1)) value = struct.unpack(">f", packed)[0] if not value or value == 4294967296.0: return str(value) if abs(math.log10(abs(value))) > 6.9: fmt_char = "e" elif abs(value) < 1: fmt_char = "f" else: fmt_char = "g" def fmt(prec: int) -> str: ret = ("{:." + str(prec) + fmt_char + "}").format(value) if fmt_char == "e": return ret.replace("e+", "e").replace("e0", "e").replace("e-0", "e-") if "e" in ret: # lead to us outputting numbers with more precision than we really have. return "0" return ret # 20 decimals is more than enough for a float. Start there, then try to shrink it. prec = 20 while prec > 0: prec -= 1 value2 = float(fmt(prec)) if struct.pack(">f", value2) != packed: prec += 1 break if prec == 20: # Uh oh, even the original value didn't format correctly. Fall back to str(), return str(value) ret = fmt(prec) if "." not in ret: ret += ".0" return ret def format_f64_imm(num: int) -> str: (value,) = struct.unpack(">d", struct.pack(">Q", num & (2 ** 64 - 1))) return str(value) def fold_divmod(original_expr: BinaryOp) -> BinaryOp: mult_high_ops = ("MULT_HI", "MULTU_HI") possible_match_ops = mult_high_ops + ("-", "+", ">>") if original_expr.is_floating() or original_expr.op not in possible_match_ops: return original_expr expr = original_expr left_expr = early_unwrap_ints(expr.left) right_expr = early_unwrap_ints(expr.right) divisor_shift = 0 if ( isinstance(left_expr, BinaryOp) and left_expr.op == ">>" and isinstance(left_expr.right, Literal) and expr.op == "+" and isinstance(right_expr, CarryBit) ): new_denom = 1 << left_expr.right.value return BinaryOp.sint( left=left_expr.left, op="/", right=Literal(new_denom), silent=True, ) if ( isinstance(left_expr, BinaryOp) and left_expr.op == "/" and isinstance(left_expr.right, Literal) and expr.op == ">>" and isinstance(right_expr, Literal) ): new_denom = left_expr.right.value << right_expr.value if new_denom < (1 << 32): return BinaryOp.int( left=left_expr.left, op="/", right=Literal(new_denom), ) if expr.op == "-" and isinstance(right_expr, BinaryOp) and right_expr.op == "*": div_expr = early_unwrap_ints(right_expr.left) mod_base = early_unwrap_ints(right_expr.right) if ( isinstance(div_expr, BinaryOp) and early_unwrap_ints(div_expr.left) == left_expr ): divisor = early_unwrap_ints(div_expr.right) if (div_expr.op == "/" and divisor == mod_base) or ( div_expr.op == ">>" and isinstance(divisor, Literal) and isinstance(mod_base, Literal) and (1 << divisor.value) == mod_base.value ): return BinaryOp.int(left=left_expr, op="%", right=right_expr.right) if ( expr.op == "-" and isinstance(left_expr, BinaryOp) and left_expr.op == ">>" and early_unwrap_ints(left_expr.right) == Literal(31) and isinstance(right_expr, BinaryOp) and right_expr.op == "/" and isinstance(right_expr.right, Literal) ): left_expr, right_expr = ( replace(right_expr, right=Literal(-right_expr.right.value)), left_expr, ) if ( expr.op == "+" and isinstance(left_expr, BinaryOp) and left_expr.op == "/" and isinstance(left_expr.right, Literal) and left_expr.right.value <= (1 << 29) and isinstance(right_expr, BinaryOp) and early_unwrap_ints(right_expr.left) == left_expr and right_expr.op == ">>" and early_unwrap_ints(right_expr.right) == Literal(31) ): return left_expr if ( expr.op == "-" and isinstance(left_expr, BinaryOp) and left_expr.op == "/" and isinstance(left_expr.right, Literal) and isinstance(right_expr, BinaryOp) and right_expr.op == ">>" and early_unwrap_ints(right_expr.right) == Literal(31) ): div_expr = left_expr shift_var_expr = early_unwrap_ints(right_expr.left) div_var_expr = early_unwrap_ints(div_expr.left) if div_var_expr == shift_var_expr: if isinstance(div_expr.right, Literal) and div_expr.right.value >= ( 1 << 30 ): return BinaryOp.int( left=div_expr.left, op=div_expr.op, right=div_expr.right, ) return div_expr # If the var is under 32 bits, the error term may look like `(x << K) >> 31` instead if ( isinstance(shift_var_expr, BinaryOp) and early_unwrap_ints(div_expr.left) == early_unwrap_ints(shift_var_expr.left) and shift_var_expr.op == "<<" and isinstance(shift_var_expr.right, Literal) ): return div_expr # Shift on the result of the mul: MULT_HI(x, N) >> M, shift the divisor by M if ( isinstance(left_expr, BinaryOp) and expr.op == ">>" and isinstance(right_expr, Literal) ): divisor_shift += right_expr.value expr = left_expr left_expr = early_unwrap_ints(expr.left) right_expr = early_unwrap_ints(expr.right) # Normalize MULT_HI(N, x) to MULT_HI(x, N) if isinstance(left_expr, Literal) and not isinstance(right_expr, Literal): left_expr, right_expr = right_expr, left_expr # Remove inner addition: (MULT_HI(x, N) + x) >> M --> MULT_HI(x, N) >> M # MULT_HI performs signed multiplication, so the `+ x` acts as setting the 32nd bit # while having a result with the same sign as x. # We can ignore it because `round_div` can work with arbitrarily large constants if ( isinstance(left_expr, BinaryOp) and left_expr.op == "MULT_HI" and expr.op == "+" and early_unwrap_ints(left_expr.left) == right_expr ): expr = left_expr left_expr = early_unwrap_ints(expr.left) right_expr = early_unwrap_ints(expr.right) # Shift on the LHS of the mul: MULT_HI(x >> M, N) --> MULT_HI(x, N) >> M if ( expr.op in mult_high_ops and isinstance(left_expr, BinaryOp) and left_expr.op == ">>" and isinstance(left_expr.right, Literal) ): divisor_shift += left_expr.right.value left_expr = early_unwrap_ints(left_expr.left) # Instead of checking for the error term precisely, just check that # the quotient is "close enough" to the integer value def round_div(x: int, y: int) -> Optional[int]: if y <= 1: return None result = round(x / y) if x / (y + 1) <= result <= x / (y - 1): return result return None if expr.op in mult_high_ops and isinstance(right_expr, Literal): denom = round_div(1 << (32 + divisor_shift), right_expr.value) if denom is not None: return BinaryOp.int( left=left_expr, op="/", right=Literal(denom), ) return original_expr def replace_clz_shift(expr: BinaryOp) -> BinaryOp: # Check that the outer expression is `>>` if expr.is_floating() or expr.op != ">>": return expr # Match `CLZ(x) >> 5`, or return the original expr left_expr = early_unwrap_ints(expr.left) right_expr = early_unwrap_ints(expr.right) if not ( isinstance(left_expr, UnaryOp) and left_expr.op == "CLZ" and isinstance(right_expr, Literal) and right_expr.value == 5 ): return expr # If the inner `x` is `(a - b)`, return `a == b` sub_expr = early_unwrap(left_expr.expr) if ( isinstance(sub_expr, BinaryOp) and not sub_expr.is_floating() and sub_expr.op == "-" ): return BinaryOp.icmp(sub_expr.left, "==", sub_expr.right) return BinaryOp.icmp(left_expr.expr, "==", Literal(0, type=left_expr.expr.type)) def replace_bitand(expr: BinaryOp) -> Expression: if not expr.is_floating() and expr.op == "&": if expr.right == Literal(0xFF): return as_type(expr.left, Type.int_of_size(8), silent=False) if expr.right == Literal(0xFFFF): return as_type(expr.left, Type.int_of_size(16), silent=False) return expr def fold_mul_chains(expr: Expression) -> Expression: def fold( expr: Expression, toplevel: bool, allow_sll: bool ) -> Tuple[Expression, int]: if isinstance(expr, BinaryOp): lbase, lnum = fold(expr.left, False, (expr.op != "<<")) rbase, rnum = fold(expr.right, False, (expr.op != "<<")) if expr.op == "<<" and isinstance(expr.right, Literal) and allow_sll: # Left-shifts by small numbers are easier to understand if # written as multiplications (they compile to the same thing). if toplevel and lnum == 1 and not (1 <= expr.right.value <= 4): return (expr, 1) return (lbase, lnum << expr.right.value) if ( expr.op == "*" and isinstance(expr.right, Literal) and (allow_sll or expr.right.value % 2 != 0) ): return (lbase, lnum * expr.right.value) if early_unwrap(lbase) == early_unwrap(rbase): if expr.op == "+": return (lbase, lnum + rnum) if expr.op == "-": return (lbase, lnum - rnum) if isinstance(expr, UnaryOp) and expr.op == "-" and not toplevel: base, num = fold(expr.expr, False, True) return (base, -num) if ( isinstance(expr, EvalOnceExpr) and not expr.emit_exactly_once and not expr.forced_emit ): base, num = fold(early_unwrap(expr), False, allow_sll) if num != 1 and is_trivial_expression(base): return (base, num) return (expr, 1) base, num = fold(expr, True, True) if num == 1: return expr return BinaryOp.int(left=base, op="*", right=Literal(num)) def array_access_from_add( expr: Expression, offset: int, stack_info: StackInfo, *, target_size: Optional[int], ptr: bool, ) -> Optional[Expression]: expr = early_unwrap(expr) if not isinstance(expr, BinaryOp) or expr.op != "+": return None base = expr.left addend = expr.right if addend.type.is_pointer_or_array() and not base.type.is_pointer_or_array(): base, addend = addend, base index: Expression scale: int uw_addend = early_unwrap(addend) if ( isinstance(uw_addend, BinaryOp) and uw_addend.op == "*" and isinstance(uw_addend.right, Literal) ): index = uw_addend.left scale = uw_addend.right.value elif ( isinstance(uw_addend, BinaryOp) and uw_addend.op == "<<" and isinstance(uw_addend.right, Literal) ): index = uw_addend.left scale = 1 << uw_addend.right.value else: index = addend scale = 1 if scale < 0: scale = -scale index = UnaryOp.sint("-", index) target_type = base.type.get_pointer_target() if target_type is None: return None uw_base = early_unwrap(base) typepool = stack_info.global_info.typepool # In `&x + index * scale`, if the type of `x` is not known, try to mark it as an array. # Skip the `scale = 1` case because this often indicates a complex `index` expression, # and is not actually a 1-byte array lookup. if ( scale > 1 and offset == 0 and isinstance(uw_base, AddressOf) and target_type.get_size_bytes() is None ): inner_type: Optional[Type] = None if ( isinstance(uw_base.expr, GlobalSymbol) and uw_base.expr.potential_array_dim(scale)[1] != 0 ): # For GlobalSymbols, use the size of the asm data to check the feasibility of being # an array with `scale`. This helps be more conservative around fake symbols. pass elif scale == 2: # This *could* be a struct, but is much more likely to be an int inner_type = Type.int_of_size(16) elif scale == 4: inner_type = Type.reg32(likely_float=False) elif typepool.unk_inference and isinstance(uw_base.expr, GlobalSymbol): # Make up a struct with a tag name based on the symbol & struct size. # Although `scale = 8` could indicate an array of longs/doubles, it seems more # common to be an array of structs. struct_name = f"_struct_{uw_base.expr.symbol_name}_0x{scale:X}" struct = typepool.get_struct_by_tag_name( struct_name, stack_info.global_info.typemap ) if struct is None: struct = StructDeclaration.unknown( typepool, size=scale, tag_name=struct_name ) elif struct.size != scale: # This should only happen if there was already a struct with this name in the context raise DecompFailure(f"sizeof(struct {struct_name}) != {scale:#x}") inner_type = Type.struct(struct) if inner_type is not None: # This might fail, if `uw_base.expr.type` can't be changed to an array uw_base.expr.type.unify(Type.array(inner_type, dim=None)) target_type.unify(inner_type) if target_type.get_size_bytes() == scale: pass else: sub_path, sub_type, remaining_offset = base.type.get_deref_field( offset, target_size=scale, exact=False ) if sub_path is None or len(sub_path) < 2 or sub_path[-1] != 0: return None sub_path.pop() base = StructAccess( struct_var=base, offset=offset - remaining_offset, target_size=None, field_path=sub_path, stack_info=stack_info, type=sub_type, ) offset = remaining_offset target_type = sub_type ret: Expression = ArrayAccess(base, index, type=target_type) ret_ref = AddressOf(ret, type=ret.type.reference()) field_path, field_type, _ = ret_ref.type.get_deref_field( offset, target_size=target_size ) if offset != 0 or (target_size is not None and target_size != scale): ret = StructAccess( struct_var=ret_ref, offset=offset, target_size=target_size, field_path=field_path, stack_info=stack_info, type=field_type, ) if ptr: ret = AddressOf(ret, type=ret.type.reference()) return ret def handle_add(args: InstrArgs) -> Expression: lhs = args.reg(1) rhs = args.reg(2) stack_info = args.stack_info type = Type.intptr() # If they are, treat them the same as pointers anyways. if lhs.type.is_pointer_or_array(): type = Type.ptr() elif rhs.type.is_pointer_or_array(): type = Type.ptr() # addiu instructions can sometimes be emitted as addu instead, when the # offset is too large. if isinstance(rhs, Literal): return handle_addi_real(args.reg_ref(0), args.reg_ref(1), lhs, rhs, stack_info) if isinstance(lhs, Literal): return handle_addi_real(args.reg_ref(0), args.reg_ref(2), rhs, lhs, stack_info) expr = BinaryOp(left=as_intptr(lhs), op="+", right=as_intptr(rhs), type=type) folded_expr = fold_mul_chains(expr) if isinstance(folded_expr, BinaryOp): folded_expr = fold_divmod(folded_expr) if folded_expr is not expr: return folded_expr array_expr = array_access_from_add(expr, 0, stack_info, target_size=None, ptr=True) if array_expr is not None: return array_expr return expr def handle_add_float(args: InstrArgs) -> Expression: if args.reg_ref(1) == args.reg_ref(2): two = Literal(1 << 30, type=Type.f32()) return BinaryOp.f32(two, "*", args.reg(1)) return BinaryOp.f32(args.reg(1), "+", args.reg(2)) def handle_add_double(args: InstrArgs) -> Expression: if args.reg_ref(1) == args.reg_ref(2): two = Literal(1 << 62, type=Type.f64()) return BinaryOp.f64(two, "*", args.dreg(1)) return BinaryOp.f64(args.dreg(1), "+", args.dreg(2)) def handle_bgez(args: InstrArgs) -> Condition: expr = args.reg(0) uw_expr = early_unwrap(expr) if ( isinstance(uw_expr, BinaryOp) and uw_expr.op == "<<" and isinstance(uw_expr.right, Literal) ): shift = uw_expr.right.value bitand = BinaryOp.int(uw_expr.left, "&", Literal(1 << (31 - shift))) return UnaryOp("!", bitand, type=Type.bool()) return BinaryOp.scmp(expr, ">=", Literal(0)) def rlwi_mask(mask_begin: int, mask_end: int) -> int: # Compute the mask constant used by the rlwi* family of PPC instructions, # referred to as the `MASK(MB, ME)` function in the processor manual. # Bit 0 is the MSB, Bit 31 is the LSB bits_upto: Callable[[int], int] = lambda m: (1 << (32 - m)) - 1 all_ones = 0xFFFFFFFF if mask_begin <= mask_end: # Set bits inside the range, fully inclusive mask = bits_upto(mask_begin) - bits_upto(mask_end + 1) else: # Set bits from [31, mask_end] and [mask_begin, 0] mask = (bits_upto(mask_end + 1) - bits_upto(mask_begin)) ^ all_ones return mask def handle_rlwinm( source: Expression, shift: int, mask_begin: int, mask_end: int, simplify: bool = True, ) -> Expression: # TODO: Detect shift + truncate, like `(x << 2) & 0xFFF3` or `(x >> 2) & 0x3FFF` # The output of the rlwinm instruction is `ROTL(source, shift) & mask`. We write this as # ((source << shift) & mask) | ((source >> (32 - shift)) & mask) # and compute both OR operands (upper_bits and lower_bits respectively). all_ones = 0xFFFFFFFF mask = rlwi_mask(mask_begin, mask_end) left_shift = shift right_shift = 32 - shift left_mask = (all_ones << left_shift) & mask right_mask = (all_ones >> right_shift) & mask # We only simplify if the `simplify` argument is True, and there will be no `|` in the # resulting expression. If there is an `|`, the expression is best left as bitwise math simplify = simplify and not (left_mask and right_mask) if isinstance(source, Literal): upper_value = (source.value << left_shift) & mask lower_value = (source.value >> right_shift) & mask return Literal(upper_value | lower_value) upper_bits: Optional[Expression] if left_mask == 0: upper_bits = None else: upper_bits = source if left_shift != 0: upper_bits = BinaryOp.int( left=upper_bits, op="<<", right=Literal(left_shift) ) if simplify: upper_bits = fold_mul_chains(upper_bits) if left_mask != (all_ones << left_shift) & all_ones: upper_bits = BinaryOp.int(left=upper_bits, op="&", right=Literal(left_mask)) if simplify: upper_bits = replace_bitand(upper_bits) lower_bits: Optional[Expression] if right_mask == 0: lower_bits = None else: lower_bits = BinaryOp.uint(left=source, op=">>", right=Literal(right_shift)) if simplify: lower_bits = replace_clz_shift(fold_divmod(lower_bits)) if right_mask != (all_ones >> right_shift) & all_ones: lower_bits = BinaryOp.int( left=lower_bits, op="&", right=Literal(right_mask) ) if simplify: lower_bits = replace_bitand(lower_bits) if upper_bits is None and lower_bits is None: return Literal(0) elif upper_bits is None: assert lower_bits is not None return lower_bits elif lower_bits is None: return upper_bits else: return BinaryOp.int(left=upper_bits, op="|", right=lower_bits) def handle_rlwimi( base: Expression, source: Expression, shift: int, mask_begin: int, mask_end: int ) -> Expression: # This instruction reads from `base`, replaces some bits with values from `source`, then # writes the result back into the first register. This can be used to copy any contiguous # bitfield from `source` into `base`, and is commonly used when manipulating flags, such # as in `x |= 0x10` or `x &= ~0x10`. # It's generally more readable to write the mask with `~` (instead of computing the inverse here) mask_literal = Literal(rlwi_mask(mask_begin, mask_end)) mask = UnaryOp("~", mask_literal, type=Type.u32()) masked_base = BinaryOp.int(left=base, op="&", right=mask) if source == Literal(0): return masked_base inserted = handle_rlwinm(source, shift, mask_begin, mask_end, simplify=False) if inserted == mask_literal: return BinaryOp.int(left=base, op="|", right=inserted) return BinaryOp.int(left=masked_base, op="|", right=inserted) def handle_loadx(args: InstrArgs, type: Type) -> Expression: size = type.get_size_bytes() assert size is not None ptr = BinaryOp.intptr(left=args.reg(1), op="+", right=args.reg(2)) expr = deref(ptr, args.regs, args.stack_info, size=size) return as_type(expr, type, silent=True) def strip_macros(arg: Argument) -> Argument: if isinstance(arg, Macro): if arg.macro_name in ["sda2", "sda21"]: return arg.argument if arg.macro_name == "hi": raise DecompFailure("%hi macro outside of lui") if arg.macro_name not in ["lo", "l"]: raise DecompFailure(f"Unrecognized linker macro %{arg.macro_name}") if isinstance(arg.argument, AsmLiteral): return AsmLiteral(arg.argument.value) return AsmLiteral(0) elif isinstance(arg, AsmAddressMode) and isinstance(arg.lhs, Macro): if arg.lhs.macro_name in ["sda2", "sda21"]: return arg.lhs.argument if arg.lhs.macro_name not in ["lo", "l"]: raise DecompFailure( f"Bad linker macro in instruction argument {arg}, expected %lo" ) return AsmAddressMode(lhs=AsmLiteral(0), rhs=arg.rhs) else: return arg @dataclass class AbiArgSlot: offset: int reg: Optional[Register] type: Type name: Optional[str] = None comment: Optional[str] = None @dataclass class Abi: arg_slots: List[AbiArgSlot] possible_slots: List[AbiArgSlot] def reg_always_set(node: Node, reg: Register, *, dom_set: bool) -> bool: if node.immediate_dominator is None: return False seen = {node.immediate_dominator} stack = node.parents[:] while stack: n = stack.pop() if n == node.immediate_dominator and not dom_set: return False if n in seen: continue seen.add(n) clobbered: Optional[bool] = None for instr in n.block.instructions: with current_instr(instr): if reg in instr.outputs: clobbered = False elif reg in instr.clobbers: clobbered = True if clobbered == True: return False if clobbered is None: stack.extend(n.parents) return True def pick_phi_assignment_nodes( reg: Register, nodes: List[Node], expr: Expression ) -> List[Node]: dominators = sorted( set.intersection(*(node.dominators for node in nodes)), key=lambda n: len(n.dominators), ) for node in dominators: regs = get_block_info(node).final_register_states raw = regs.get_raw(reg) meta = regs.get_meta(reg) if raw is None or meta is None or meta.force: continue if raw == expr: return [node] # TODO: In some cases there may be a better solution (e.g. one that requires 2 nodes) return nodes def assign_phis(used_phis: List[PhiExpr], stack_info: StackInfo) -> None: i = 0 # Iterate over used phis until there are no more remaining. New ones may # appear during iteration, hence the while loop. while i < len(used_phis): phi = used_phis[i] assert phi.num_usages > 0 assert len(phi.node.parents) >= 2 # Group parent nodes by the value of their phi register equivalent_nodes: DefaultDict[Expression, List[Node]] = defaultdict(list) for node in phi.node.parents: expr = get_block_info(node).final_register_states[phi.reg] expr.type.unify(phi.type) equivalent_nodes[expr].append(node) exprs = list(equivalent_nodes.keys()) first_uw = early_unwrap(exprs[0]) if all(early_unwrap(e) == first_uw for e in exprs[1:]): # All the phis have the same value (e.g. because we recomputed an # expression after a store, or restored a register after a function # call). Just use that value instead of introducing a phi node. # TODO: the unwrapping here is necessary, but also kinda sketchy: # we may set as replacement_expr an expression that really shouldn't # prevent_later_uses machinery). phi.replacement_expr = as_type(first_uw, phi.type, silent=True) for _ in range(phi.num_usages): first_uw.use() else: for expr, nodes in equivalent_nodes.items(): for node in pick_phi_assignment_nodes(phi.reg, nodes, expr): block_info = get_block_info(node) expr = block_info.final_register_states[phi.reg] if isinstance(expr, PhiExpr): # Explicitly mark how the expression is used if it's a phi, expr.use(from_phi=phi) else: expr.use() typed_expr = as_type(expr, phi.type, silent=True) block_info.to_write.append(SetPhiStmt(phi, typed_expr)) i += 1 name_counter: Dict[Register, int] = {} for phi in used_phis: if not phi.replacement_expr and phi.propagates_to() == phi: counter = name_counter.get(phi.reg, 0) + 1 name_counter[phi.reg] = counter output_reg_name = stack_info.function.reg_formatter.format(phi.reg) prefix = f"phi_{output_reg_name}" phi.name = f"{prefix}_{counter}" if counter > 1 else prefix stack_info.phi_vars.append(phi) def propagate_register_meta(nodes: List[Node], reg: Register) -> None: non_terminal: List[Node] = [n for n in nodes if not isinstance(n, TerminalNode)] for n in non_terminal: if reg in get_block_info(n).final_register_states.read_inherited: for p in n.parents: par_meta = get_block_info(p).final_register_states.get_meta(reg) if par_meta: par_meta.is_read = True todo = non_terminal[:] while todo: n = todo.pop() meta = get_block_info(n).final_register_states.get_meta(reg) for p in n.parents: par_meta = get_block_info(p).final_register_states.get_meta(reg) if (par_meta and not par_meta.is_read) and ( meta and meta.inherited and meta.is_read ): par_meta.is_read = True todo.append(p) for n in non_terminal: meta = get_block_info(n).final_register_states.get_meta(reg) if meta: if meta.inherited: meta.uninteresting = True meta.function_return = True meta.in_pattern = True else: meta.uninteresting |= ( meta.is_read or meta.function_return or meta.in_pattern ) todo = non_terminal[:] while todo: n = todo.pop() if isinstance(n, TerminalNode): continue meta = get_block_info(n).final_register_states.get_meta(reg) if not meta or not meta.inherited: continue all_uninteresting = True all_function_return = True all_in_pattern = True for p in n.parents: par_meta = get_block_info(p).final_register_states.get_meta(reg) if par_meta: all_uninteresting &= par_meta.uninteresting all_function_return &= par_meta.function_return all_in_pattern &= par_meta.in_pattern if meta.uninteresting and not all_uninteresting and not meta.is_read: meta.uninteresting = False todo.extend(n.children()) if meta.function_return and not all_function_return: meta.function_return = False todo.extend(n.children()) if meta.in_pattern and not all_in_pattern: meta.in_pattern = False todo.extend(n.children()) def determine_return_register( return_blocks: List[BlockInfo], fn_decl_provided: bool, arch: Arch ) -> Optional[Register]: def priority(block_info: BlockInfo, reg: Register) -> int: meta = block_info.final_register_states.get_meta(reg) if not meta: return 4 if meta.uninteresting: return 2 if meta.in_pattern: return 1 if meta.function_return: return 0 return 3 if not return_blocks: return None best_reg: Optional[Register] = None best_prio = -1 for reg in arch.base_return_regs: prios = [priority(b, reg) for b in return_blocks] max_prio = max(prios) if max_prio == 4: continue if max_prio <= 2 and not fn_decl_provided: continue if max_prio > best_prio: best_prio = max_prio best_reg = reg return best_reg def translate_node_body(node: Node, regs: RegInfo, stack_info: StackInfo) -> BlockInfo: to_write: List[Union[Statement]] = [] local_var_writes: Dict[LocalVar, Tuple[Register, Expression]] = {} subroutine_args: Dict[int, Expression] = {} branch_condition: Optional[Condition] = None switch_expr: Optional[Expression] = None has_custom_return: bool = False has_function_call: bool = False in_pattern: bool = False arch = stack_info.global_info.arch def eval_once( expr: Expression, *, emit_exactly_once: bool, trivial: bool, prefix: str = "", reuse_var: Optional[Var] = None, ) -> EvalOnceExpr: if emit_exactly_once: expr.use() elif "_fictive_" in prefix and isinstance(expr, EvalOnceExpr): return expr assert reuse_var or prefix if prefix == "condition_bit": prefix = "cond" var = reuse_var or Var(stack_info, "temp_" + prefix) expr = EvalOnceExpr( wrapped_expr=expr, var=var, type=expr.type, emit_exactly_once=emit_exactly_once, trivial=trivial, ) var.num_usages += 1 stmt = EvalOnceStmt(expr) to_write.append(stmt) stack_info.temp_vars.append(stmt) return expr def prevent_later_uses(expr_filter: Callable[[Expression], bool]) -> None: for r in regs.contents.keys(): data = regs.contents.get(r) assert data is not None expr = data.value if not data.meta.force and expr_filter(expr): # Mark the register as "if used, emit the expression's once # var". We usually always have a once var at this point, if not isinstance(expr, EvalOnceExpr): expr = eval_once( expr, emit_exactly_once=False, trivial=False, prefix=stack_info.function.reg_formatter.format(r), ) # This write isn't changing the value of the register; it didn't need # to be declared as part of the current instruction's inputs/outputs. regs.unchecked_set_with_meta(r, expr, replace(data.meta, force=True)) def prevent_later_value_uses(sub_expr: Expression) -> None: # cause them to be incorrectly passed as function arguments -- the function # call logic sees an opaque wrapper and doesn't realize that they are unused prevent_later_uses( lambda e: uses_expr(e, lambda e2: e2 == sub_expr) and not (isinstance(e, PassedInArg) and not e.copied) ) def prevent_later_function_calls() -> None: prevent_later_uses(lambda e: uses_expr(e, lambda e2: isinstance(e2, FuncCall))) def prevent_later_reads() -> None: contains_read = lambda e: isinstance(e, (StructAccess, ArrayAccess)) prevent_later_uses(lambda e: uses_expr(e, contains_read)) def set_reg_maybe_return(reg: Register, expr: Expression) -> None: regs.set_with_meta(reg, expr, RegMeta(in_pattern=in_pattern)) def set_reg(reg: Register, expr: Optional[Expression]) -> Optional[Expression]: if expr is None: if reg in regs: del regs[reg] return None if isinstance(expr, LocalVar): if ( isinstance(node, ReturnNode) and stack_info.maybe_get_register_var(reg) and stack_info.in_callee_save_reg_region(expr.value) and reg in stack_info.callee_save_regs ): # matter in other cases). return None if expr in local_var_writes: # Elide register restores (only for the same register for now, # to be conversative). orig_reg, orig_expr = local_var_writes[expr] if orig_reg == reg: expr = orig_expr uw_expr = expr if not isinstance(expr, Literal): expr = eval_once( expr, emit_exactly_once=False, trivial=is_trivial_expression(expr), prefix=stack_info.function.reg_formatter.format(reg), ) if reg == Register("zero"): # Emit the expression as is. It's probably a volatile load. expr.use() to_write.append(ExprStmt(expr)) else: dest = stack_info.maybe_get_register_var(reg) if dest is not None: stack_info.use_register_var(dest) if not (isinstance(uw_expr, RegisterVar) and uw_expr.reg == reg): source = as_type(expr, dest.type, True) source.use() to_write.append(StoreStmt(source=source, dest=dest)) expr = dest set_reg_maybe_return(reg, expr) return expr def clear_caller_save_regs() -> None: for reg in arch.temp_regs: if reg in regs: del regs[reg] def maybe_clear_local_var_writes(func_args: List[Expression]) -> None: # Clear the `local_var_writes` dict if any of the `func_args` contain # a reference to a stack var. (The called function may modify the stack, # replacing the value we have in `local_var_writes`.) for arg in func_args: if uses_expr( arg, lambda expr: isinstance(expr, AddressOf) and isinstance(expr.expr, LocalVar), ): local_var_writes.clear() return def process_instr(instr: Instruction) -> None: nonlocal branch_condition, switch_expr, has_function_call, in_pattern in_pattern = instr.in_pattern mnemonic = instr.mnemonic arch_mnemonic = instr.arch_mnemonic(arch) args = InstrArgs(instr.args, regs, stack_info) expr: Expression # Figure out what code to generate! if mnemonic in arch.instrs_ignore: pass elif mnemonic in arch.instrs_store or mnemonic in arch.instrs_store_update: # Store a value in a permanent place. if mnemonic in arch.instrs_store: to_store = arch.instrs_store[mnemonic](args) else: # PPC specific store-and-update instructions # `stwu r3, 8(r4)` is equivalent to `$r3 = *($r4 + 8); $r4 += 8;` to_store = arch.instrs_store_update[mnemonic](args) # Update the register in the second argument update = args.memory_ref(1) if not isinstance(update, AddressMode): raise DecompFailure( f"Unhandled store-and-update arg in {instr}: {update!r}" ) set_reg( update.rhs, add_imm(args.regs[update.rhs], Literal(update.offset), stack_info), ) if to_store is None: # Elided register preserval. pass elif isinstance(to_store.dest, SubroutineArg): # About to call a subroutine with this argument. Skip arguments for the # first four stack slots; they are also passed in registers. if to_store.dest.value >= 0x10: subroutine_args[to_store.dest.value] = to_store.source else: if isinstance(to_store.dest, LocalVar): stack_info.add_local_var(to_store.dest) raw_value = to_store.source if isinstance(raw_value, Cast) and raw_value.reinterpret: # When preserving values on the stack across function calls, # ignore the type of the stack variable. The same stack slot # might be used to preserve values of different types. raw_value = raw_value.expr local_var_writes[to_store.dest] = (args.reg_ref(0), raw_value) # Emit a write. This includes four steps: # - mark the expression as used (since writes are always emitted) # - mark the dest used (if it's a struct access it needs to be # - mark other usages of the dest as "emit before this point if used". # - emit the actual write. # # Note that the prevent_later_value_uses step happens after use(), since # the stored expression is allowed to reference its destination var, # but before the write is written, since prevent_later_value_uses might # emit writes of its own that should go before this write. In practice # that probably never occurs -- all relevant register contents should be # EvalOnceExpr's that can be emitted at their point of creation, but to_store.source.use() to_store.dest.use() prevent_later_value_uses(to_store.dest) prevent_later_function_calls() to_write.append(to_store) elif mnemonic in arch.instrs_source_first: set_reg(args.reg_ref(1), arch.instrs_source_first[mnemonic](args)) elif mnemonic in arch.instrs_branches: assert branch_condition is None branch_condition = arch.instrs_branches[mnemonic](args) elif mnemonic in arch.instrs_float_branches: assert branch_condition is None cond_bit = regs[Register("condition_bit")] if not isinstance(cond_bit, BinaryOp): cond_bit = ExprCondition(cond_bit, type=cond_bit.type) if arch_mnemonic == "mips:bc1t": branch_condition = cond_bit elif arch_mnemonic == "mips:bc1f": branch_condition = cond_bit.negated() elif mnemonic in arch.instrs_jumps: if arch_mnemonic == "ppc:bctr": # Switch jump assert isinstance(node, SwitchNode) switch_expr = args.regs[Register("ctr")] elif arch_mnemonic == "mips:jr": # MIPS: if args.reg_ref(0) == arch.return_address_reg: # Return from the function. assert isinstance(node, ReturnNode) else: # Switch jump. assert isinstance(node, SwitchNode) switch_expr = args.reg(0) elif arch_mnemonic == "ppc:blr": assert isinstance(node, ReturnNode) else: assert False, f"Unhandled jump mnemonic {arch_mnemonic}" elif mnemonic in arch.instrs_fn_call: if arch_mnemonic in ["mips:jal", "ppc:bl"]: fn_target = args.imm(0) if not ( ( isinstance(fn_target, AddressOf) and isinstance(fn_target.expr, GlobalSymbol) ) or isinstance(fn_target, Literal) ): raise DecompFailure( f"Target of function call must be a symbol, not {fn_target}" ) elif arch_mnemonic == "ppc:blrl": fn_target = args.regs[Register("lr")] elif arch_mnemonic == "ppc:bctrl": fn_target = args.regs[Register("ctr")] elif arch_mnemonic == "mips:jalr": fn_target = args.reg(1) else: assert False, f"Unhandled fn call mnemonic {arch_mnemonic}" fn_target = as_function_ptr(fn_target) fn_sig = fn_target.type.get_function_pointer_signature() assert fn_sig is not None, "known function pointers must have a signature" likely_regs: Dict[Register, bool] = {} for reg, data in regs.contents.items(): # We use a much stricter filter for PPC than MIPS, because the same # registers can be used arguments & return values. # The ABI can also mix & match the rN & fN registers, which makes the # "require" heuristic less powerful. # # - `meta.inherited` will only be False for registers set in *this* basic block # - `meta.function_return` will only be accurate for registers set within this # basic block because we have not called `propagate_register_meta` yet. # Within this block, it will be True for registers that were return values. if arch.arch == Target.ArchEnum.PPC and ( data.meta.inherited or data.meta.function_return ): likely_regs[reg] = False elif data.meta.in_pattern: # Like `meta.function_return` mentioned above, `meta.in_pattern` will only be # accurate for registers set within this basic block. likely_regs[reg] = False elif isinstance(data.value, PassedInArg) and not data.value.copied: likely_regs[reg] = False else: likely_regs[reg] = True abi = arch.function_abi(fn_sig, likely_regs, for_call=True) func_args: List[Expression] = [] for slot in abi.arg_slots: if slot.reg: expr = regs[slot.reg] elif slot.offset in subroutine_args: expr = subroutine_args.pop(slot.offset) else: expr = ErrorExpr( f"Unable to find stack arg {slot.offset:#x} in block" ) func_args.append( CommentExpr.wrap( as_type(expr, slot.type, True), prefix=slot.comment ) ) for slot in abi.possible_slots: assert slot.reg is not None func_args.append(regs[slot.reg]) # Add the arguments after a3. # TODO: limit this based on abi.arg_slots. If the function type is known # and not variadic, this list should be empty. for _, arg in sorted(subroutine_args.items()): if fn_sig.params_known and not fn_sig.is_variadic: func_args.append(CommentExpr.wrap(arg, prefix="extra?")) else: func_args.append(arg) if not fn_sig.params_known: while len(func_args) > len(fn_sig.params): fn_sig.params.append(FunctionParam()) # When the function signature isn't provided, the we only assume that each # Without that assumption, the logic from `function_abi` would be needed here. for i, (arg_expr, param) in enumerate(zip(func_args, fn_sig.params)): func_args[i] = as_type(arg_expr, param.type.decay(), True) # Reset subroutine_args, for the next potential function call. subroutine_args.clear() call: Expression = FuncCall( fn_target, func_args, fn_sig.return_type.weaken_void_ptr() ) call = eval_once(call, emit_exactly_once=True, trivial=False, prefix="ret") # Clear out caller-save registers, for clarity and to ensure that # argument regs don't get passed into the next function. clear_caller_save_regs() maybe_clear_local_var_writes(func_args) # and then this prevention should also be... but it's the best we prevent_later_function_calls() prevent_later_reads() return_reg_vals = arch.function_return(call) for out in instr.outputs: if not isinstance(out, Register): continue val = return_reg_vals[out] if not isinstance(val, SecondF64Half): val = eval_once( val, emit_exactly_once=False, trivial=False, prefix=stack_info.function.reg_formatter.format(out), ) regs.set_with_meta(out, val, RegMeta(function_return=True)) has_function_call = True elif mnemonic in arch.instrs_float_comp: expr = arch.instrs_float_comp[mnemonic](args) regs[Register("condition_bit")] = expr elif mnemonic in arch.instrs_hi_lo: hi, lo = arch.instrs_hi_lo[mnemonic](args) set_reg(Register("hi"), hi) set_reg(Register("lo"), lo) elif mnemonic in arch.instrs_implicit_destination: reg, expr_fn = arch.instrs_implicit_destination[mnemonic] set_reg(reg, expr_fn(args)) elif mnemonic in arch.instrs_ppc_compare: if instr.args[0] != Register("cr0"): raise DecompFailure( f"Instruction {instr} not supported (first arg is not $cr0)" ) set_reg(Register("cr0_eq"), arch.instrs_ppc_compare[mnemonic](args, "==")) set_reg(Register("cr0_gt"), arch.instrs_ppc_compare[mnemonic](args, ">")) set_reg(Register("cr0_lt"), arch.instrs_ppc_compare[mnemonic](args, "<")) set_reg(Register("cr0_so"), Literal(0)) elif mnemonic in arch.instrs_no_dest: stmt = arch.instrs_no_dest[mnemonic](args) to_write.append(stmt) elif mnemonic.rstrip(".") in arch.instrs_destination_first: target = args.reg_ref(0) val = arch.instrs_destination_first[mnemonic.rstrip(".")](args) target_val = set_reg(target, val) mn_parts = arch_mnemonic.split(".") if arch_mnemonic.startswith("ppc:") and arch_mnemonic.endswith("."): if target_val is None: target_val = val set_reg( Register("cr0_eq"), BinaryOp.icmp(target_val, "==", Literal(0, type=target_val.type)), ) target_s32 = Cast( target_val, reinterpret=True, silent=True, type=Type.s32() ) set_reg( Register("cr0_gt"), BinaryOp(target_s32, ">", Literal(0), type=Type.s32()), ) set_reg( Register("cr0_lt"), BinaryOp(target_s32, "<", Literal(0), type=Type.s32()), ) set_reg( Register("cr0_so"), fn_op("MIPS2C_OVERFLOW", [target_val], type=Type.s32()), ) elif ( len(mn_parts) >= 2 and mn_parts[0].startswith("mips:") and mn_parts[1] == "d" ) or arch_mnemonic == "mips:ldc1": set_reg(target.other_f64_reg(), SecondF64Half()) elif mnemonic in arch.instrs_load_update: target = args.reg_ref(0) val = arch.instrs_load_update[mnemonic](args) set_reg(target, val) if arch_mnemonic in ["ppc:lwzux", "ppc:lhzux", "ppc:lbzux"]: # In `rD, rA, rB`, update `rA = rA + rB` update_reg = args.reg_ref(1) offset = args.reg(2) else: # In `rD, rA(N)`, update `rA = rA + N` update = args.memory_ref(1) if not isinstance(update, AddressMode): raise DecompFailure( f"Unhandled store-and-update arg in {instr}: {update!r}" ) update_reg = update.rhs offset = Literal(update.offset) if update_reg == target: raise DecompFailure( f"Invalid instruction, rA and rD must be different in {instr}" ) set_reg(update_reg, add_imm(args.regs[update_reg], offset, stack_info)) else: expr = ErrorExpr(f"unknown instruction: {instr}") if arch_mnemonic.startswith("ppc:") and arch_mnemonic.endswith("."): # Unimplemented PPC instructions that modify CR0 set_reg(Register("cr0_eq"), expr) set_reg(Register("cr0_gt"), expr) set_reg(Register("cr0_lt"), expr) set_reg(Register("cr0_so"), expr) if args.count() >= 1 and isinstance(args.raw_arg(0), Register): reg = args.reg_ref(0) expr = eval_once( expr, emit_exactly_once=True, trivial=False, prefix=stack_info.function.reg_formatter.format(reg), ) if reg != Register("zero"): set_reg_maybe_return(reg, expr) else: to_write.append(ExprStmt(expr)) for instr in node.block.instructions: with regs.current_instr(instr): process_instr(instr) if branch_condition is not None: branch_condition.use() switch_control: Optional[SwitchControl] = None if switch_expr is not None: switch_control = SwitchControl.from_expr(switch_expr) switch_control.control_expr.use() return BlockInfo( to_write=to_write, return_value=None, switch_control=switch_control, branch_condition=branch_condition, final_register_states=regs, has_function_call=has_function_call, ) def translate_graph_from_block( node: Node, regs: RegInfo, stack_info: StackInfo, used_phis: List[PhiExpr], return_blocks: List[BlockInfo], options: Options, ) -> None: if options.debug: print(f"\nNode in question: {node}") # Translate the given node and discover final register states. try: block_info = translate_node_body(node, regs, stack_info) if options.debug: print(block_info) except Exception as e: # TODO: handle issues better if options.stop_on_error: raise instr: Optional[Instruction] = None if isinstance(e, InstrProcessingFailure) and isinstance(e.__cause__, Exception): instr = e.instr e = e.__cause__ if isinstance(e, DecompFailure): emsg = str(e) print(emsg) else: tb = e.__traceback__ traceback.print_exception(None, e, tb) emsg = str(e) or traceback.format_tb(tb)[-1] emsg = emsg.strip().split("\n")[-1].strip() error_stmts: List[Statement] = [CommentStmt(f"Error: {emsg}")] if instr is not None: print( f"Error occurred while processing instruction: {instr}", file=sys.stderr ) error_stmts.append(CommentStmt(f"At instruction: {instr}")) print(file=sys.stderr) block_info = BlockInfo( to_write=error_stmts, return_value=None, switch_control=None, branch_condition=ErrorExpr(), final_register_states=regs, has_function_call=False, ) node.block.add_block_info(block_info) if isinstance(node, ReturnNode): return_blocks.append(block_info) # Translate everything dominated by this node, now that we know our own # final register state. This will eventually reach every node. for child in node.immediately_dominates: if isinstance(child, TerminalNode): continue new_regs = RegInfo(stack_info=stack_info) for reg, data in regs.contents.items(): new_regs.set_with_meta( reg, data.value, RegMeta(inherited=True, force=data.meta.force) ) phi_regs = ( r for r in locs_clobbered_until_dominator(child) if isinstance(r, Register) ) for reg in phi_regs: if reg_always_set(child, reg, dom_set=(reg in regs)): expr: Optional[Expression] = stack_info.maybe_get_register_var(reg) if expr is None: expr = PhiExpr( reg=reg, node=child, used_phis=used_phis, type=Type.any_reg() ) new_regs.set_with_meta(reg, expr, RegMeta(inherited=True)) elif reg in new_regs: del new_regs[reg] translate_graph_from_block( child, new_regs, stack_info, used_phis, return_blocks, options ) def resolve_types_late(stack_info: StackInfo) -> None: # Final check over stack var types. Because of delayed type unification, some # locations should now be marked as "weak". for location in stack_info.weak_stack_var_types.keys(): stack_info.get_stack_var(location, store=False) # Use dereferences to determine pointer types struct_type_map = stack_info.get_struct_type_map() for var, offset_type_map in struct_type_map.items(): if len(offset_type_map) == 1 and 0 in offset_type_map: # var was probably a plain pointer, not a struct # Try to unify it with the appropriate pointer type, # to fill in the type if it does not already have one type = offset_type_map[0] var.type.unify(Type.ptr(type)) @dataclass class FunctionInfo: stack_info: StackInfo flow_graph: FlowGraph return_type: Type symbol: GlobalSymbol @dataclass class GlobalInfo: asm_data: AsmData arch: Arch target: Target local_functions: Set[str] typemap: TypeMap typepool: TypePool global_symbol_map: Dict[str, GlobalSymbol] = field(default_factory=dict) def asm_data_value(self, sym_name: str) -> Optional[AsmDataEntry]: return self.asm_data.values.get(sym_name) def address_of_gsym(self, sym_name: str) -> AddressOf: if sym_name in self.global_symbol_map: sym = self.global_symbol_map[sym_name] else: demangled_symbol: Optional[CxxSymbol] = None demangled_str: Optional[str] = None if self.target.language == Target.LanguageEnum.CXX: try: demangled_symbol = demangle_codewarrior_parse(sym_name) except ValueError: pass else: demangled_str = str(demangled_symbol) sym = self.global_symbol_map[sym_name] = GlobalSymbol( symbol_name=sym_name, type=Type.any(), asm_data_entry=self.asm_data_value(sym_name), demangled_str=demangled_str, ) # If the symbol is a C++ vtable, try to build a custom type for it by parsing it if ( self.target.language == Target.LanguageEnum.CXX and sym_name.startswith("__vt__") and sym.asm_data_entry is not None ): sym.type.unify(self.vtable_type(sym_name, sym.asm_data_entry)) fn = self.typemap.functions.get(sym_name) ctype: Optional[CType] if fn is not None: ctype = fn.type else: ctype = self.typemap.var_types.get(sym_name) if ctype is not None: sym.symbol_in_context = True sym.initializer_in_typemap = ( sym_name in self.typemap.vars_with_initializers ) sym.type.unify(Type.ctype(ctype, self.typemap, self.typepool)) if sym_name not in self.typepool.unknown_decls: sym.type_provided = True elif sym_name in self.local_functions: sym.type.unify(Type.function()) # Do this after unifying the type in the typemap, so that it has lower precedence if demangled_symbol is not None: sym.type.unify( Type.demangled_symbol(self.typemap, self.typepool, demangled_symbol) ) return AddressOf(sym, type=sym.type.reference()) def vtable_type(self, sym_name: str, asm_data_entry: AsmDataEntry) -> Type: size = asm_data_entry.size_range_bytes()[1] struct = StructDeclaration.unknown( self.typepool, size=size, align=4, tag_name=sym_name ) offset = 0 for entry in asm_data_entry.data: if isinstance(entry, bytes): # MWCC vtables start with a pointer to a typeid struct (or NULL) and an offset if len(entry) % 4 != 0: raise DecompFailure( f"Unable to parse misaligned vtable data in {sym_name}" ) for i in range(len(entry) // 4): field_name = f"{struct.new_field_prefix}{offset:X}" struct.try_add_field( Type.reg32(likely_float=False), offset, field_name, size=4 ) offset += 4 else: entry_name = entry try: demangled_field_sym = demangle_codewarrior_parse(entry) if demangled_field_sym.name.qualified_name is not None: entry_name = str(demangled_field_sym.name.qualified_name[-1]) except ValueError: pass field = struct.try_add_field( self.address_of_gsym(entry).type, offset, name=entry_name, size=4, ) assert field is not None field.known = True offset += 4 return Type.struct(struct) def is_function_known_void(self, sym_name: str) -> bool: fn = self.typemap.functions.get(sym_name) if fn is None: return False return fn.ret_type is None def initializer_for_symbol( self, sym: GlobalSymbol, fmt: Formatter ) -> Optional[str]: assert sym.asm_data_entry is not None data = sym.asm_data_entry.data[:] def read_uint(n: int) -> Optional[int]: assert 0 < n <= 8 if not data or not isinstance(data[0], bytes): return None if len(data[0]) < n: return None bs = data[0][:n] data[0] = data[0][n:] if not data[0]: del data[0] value = 0 for b in bs: value = (value << 8) | b return value def read_pointer() -> Optional[Expression]: if not data or not isinstance(data[0], str): return None label = data[0] data.pop(0) return self.address_of_gsym(label) def for_type(type: Type) -> Optional[str]: if type.is_struct() or type.is_array(): struct_fields = type.get_initializer_fields() if not struct_fields: return None members = [] for field in struct_fields: if isinstance(field, int): # Check that all padding bytes are 0 for i in range(field): padding = read_uint(1) if padding != 0: return None else: m = for_type(field) if m is None: return None members.append(m) return fmt.format_array(members) if type.is_reg(): size = type.get_size_bytes() if not size: return None if size == 4: ptr = read_pointer() if ptr is not None: return as_type(ptr, type, silent=True).format(fmt) value = read_uint(size) if value is not None: enum_name = type.get_enum_name(value) if enum_name is not None: return enum_name expr = as_type(Literal(value), type, True) return elide_casts_for_store(expr).format(fmt) # Type kinds K_FN and K_VOID do not have initializers return None return for_type(sym.type) def find_forward_declares_needed(self, functions: List[FunctionInfo]) -> Set[str]: funcs_seen = set() forward_declares_needed = self.asm_data.mentioned_labels for func in functions: funcs_seen.add(func.stack_info.function.name) for instr in func.stack_info.function.body: if not isinstance(instr, Instruction): continue for arg in instr.args: if isinstance(arg, AsmGlobalSymbol): func_name = arg.symbol_name elif isinstance(arg, Macro) and isinstance( arg.argument, AsmGlobalSymbol ): func_name = arg.argument.symbol_name else: continue if func_name in self.local_functions: if func_name not in funcs_seen: forward_declares_needed.add(func_name) return forward_declares_needed def global_decls( self, fmt: Formatter, decls: Options.GlobalDeclsEnum, functions: List[FunctionInfo], ) -> str: # Format labels from symbol_type_map into global declarations. # As the initializers are formatted, this may cause more symbols # to be added to the global_symbol_map. forward_declares_needed = self.find_forward_declares_needed(functions) lines = [] processed_names: Set[str] = set() while True: names: AbstractSet[str] = self.global_symbol_map.keys() if decls == Options.GlobalDeclsEnum.ALL: names |= self.asm_data.values.keys() names -= processed_names if not names: break for name in sorted(names): processed_names.add(name) sym = self.address_of_gsym(name).expr assert isinstance(sym, GlobalSymbol) data_entry = sym.asm_data_entry # Is the label defined in this unit (in the active AsmData file(s)) is_in_file = data_entry is not None or name in self.local_functions # Is the label externally visible (mentioned in the context file) is_global = sym.symbol_in_context # Is the label a symbol in .rodata? is_const = data_entry is not None and data_entry.is_readonly if data_entry and data_entry.is_jtbl: # Skip jump tables continue if is_in_file and is_global and sym.type.is_function(): # Skip externally-declared functions that are defined here continue if self.local_functions == {name}: # Skip the function being decompiled if just a single one continue if not is_in_file and sym.type_provided: # Skip externally-declared symbols that are defined in other files continue # TODO: Use original MIPSFile ordering for variables sort_order = ( not sym.type.is_function(), is_global, is_in_file, is_const, name, ) qualifier = "" value: Optional[str] = None comments = [] # Determine type qualifier: static, extern, or neither if is_in_file and is_global: qualifier = "" elif is_in_file: qualifier = "static" else: qualifier = "extern" if sym.type.is_function(): comments.append(qualifier) qualifier = "" # Try to guess if the symbol is an array (and if it is, its dimension) if # we have a data entry for it, and the symbol is either not in the typemap # or was a variable-length array there ("VLA", e.g. `int []`) # (Otherwise, if the dim is provided by the typemap, we trust it.) element_type, array_dim = sym.type.get_array() is_vla = element_type is not None and ( array_dim is None or array_dim <= 0 ) if data_entry and (not sym.type_provided or is_vla): # The size of the data entry is uncertain, because of padding # between sections. Generally `(max_data_size - data_size) < 16`. min_data_size, max_data_size = data_entry.size_range_bytes() # The size of the element type (not the size of the array type) if element_type is None: element_type = sym.type # If we don't know the type, we can't guess the array_dim type_size = element_type.get_size_bytes() if type_size: potential_dim, extra_bytes = sym.potential_array_dim(type_size) if potential_dim == 0 and extra_bytes > 0: # The type is too big for our data. (not an array) comments.append( f"type too large by {fmt.format_int(type_size - extra_bytes)}" ) elif potential_dim > 1 or is_vla: # NB: In general, replacing the types of Expressions can be sketchy. # However, the GlobalSymbol here came from address_of_gsym(), which # always returns a reference to the element_type. array_dim = potential_dim sym.type = Type.array(element_type, array_dim) if potential_dim != 0 and extra_bytes > 0: comments.append( f"extra bytes: {fmt.format_int(extra_bytes)}" ) # Try to convert the data from .data/.rodata into an initializer if data_entry and not data_entry.is_bss: value = self.initializer_for_symbol(sym, fmt) if value is None: # This warning helps distinguish .bss symbols from .data/.rodata, # IDO only puts symbols in .bss if they don't have any initializer comments.append("unable to generate initializer") if is_const: comments.append("const") if sym.is_string_constant(): continue if array_dim is None and sym.type.is_likely_float(): continue if decls == Options.GlobalDeclsEnum.NONE: continue if decls != Options.GlobalDeclsEnum.ALL and sym.initializer_in_typemap: continue if ( decls != Options.GlobalDeclsEnum.ALL and self.target.language == Target.LanguageEnum.CXX and name.startswith("__vt__") ): continue if ( sym.type.is_function() and decls != Options.GlobalDeclsEnum.ALL and name in self.local_functions and name not in forward_declares_needed ): continue qualifier = f"{qualifier} " if qualifier else "" value = f" = {value}" if value else "" lines.append( ( sort_order, fmt.with_comments( f"{qualifier}{sym.type.to_decl(name, fmt)}{value};", comments, ) + "\n", ) ) lines.sort() return "".join(line for _, line in lines) def narrow_func_call_outputs( function: Function, global_info: GlobalInfo, ) -> None: for instr in function.body: if ( isinstance(instr, Instruction) and isinstance(instr.function_target, AsmGlobalSymbol) and global_info.is_function_known_void(instr.function_target.symbol_name) ): instr.outputs.clear() def translate_to_ast( function: Function, flow_graph: FlowGraph, options: Options, global_info: GlobalInfo, ) -> FunctionInfo: stack_info = get_stack_info(function, global_info, flow_graph) start_regs: RegInfo = RegInfo(stack_info=stack_info) arch = global_info.arch start_regs[arch.stack_pointer_reg] = GlobalSymbol("sp", type=Type.ptr()) for reg in arch.saved_regs: start_regs[reg] = stack_info.saved_reg_symbol(reg.register_name) fn_sym = global_info.address_of_gsym(function.name).expr assert isinstance(fn_sym, GlobalSymbol) fn_type = fn_sym.type fn_type.unify(Type.function()) fn_sig = Type.ptr(fn_type).get_function_pointer_signature() assert fn_sig is not None, "fn_type is known to be a function" return_type = fn_sig.return_type stack_info.is_variadic = fn_sig.is_variadic def make_arg(offset: int, type: Type) -> PassedInArg: assert offset % 4 == 0 return PassedInArg(offset, copied=False, stack_info=stack_info, type=type) abi = arch.function_abi( fn_sig, likely_regs={reg: True for reg in arch.argument_regs}, for_call=False, ) for slot in abi.arg_slots: stack_info.add_known_param(slot.offset, slot.name, slot.type) if slot.reg is not None: start_regs.set_with_meta( slot.reg, make_arg(slot.offset, slot.type), RegMeta(uninteresting=True) ) for slot in abi.possible_slots: if slot.reg is not None: start_regs.set_with_meta( slot.reg, make_arg(slot.offset, slot.type), RegMeta(uninteresting=True) ) if options.reg_vars == ["saved"]: reg_vars = arch.saved_regs elif options.reg_vars == ["most"]: reg_vars = arch.saved_regs + arch.simple_temp_regs elif options.reg_vars == ["all"]: reg_vars = arch.saved_regs + arch.simple_temp_regs + arch.argument_regs else: reg_vars = [ stack_info.function.reg_formatter.parse(x, arch) for x in options.reg_vars ] for reg in reg_vars: reg_name = stack_info.function.reg_formatter.format(reg) stack_info.add_register_var(reg, reg_name) if options.debug: print(stack_info) print("\nNow, we attempt to translate:") used_phis: List[PhiExpr] = [] return_blocks: List[BlockInfo] = [] translate_graph_from_block( flow_graph.entry_node(), start_regs, stack_info, used_phis, return_blocks, options, ) for reg in arch.base_return_regs: propagate_register_meta(flow_graph.nodes, reg) return_reg: Optional[Register] = None if not options.void and not return_type.is_void(): return_reg = determine_return_register( return_blocks, fn_sym.type_provided, arch ) if return_reg is not None: for b in return_blocks: if return_reg in b.final_register_states: ret_val = b.final_register_states[return_reg] ret_val = as_type(ret_val, return_type, True) ret_val.use() b.return_value = ret_val else: return_type.unify(Type.void()) if not fn_sig.params_known: while len(fn_sig.params) < len(stack_info.arguments): fn_sig.params.append(FunctionParam()) for param, arg in zip(fn_sig.params, stack_info.arguments): param.type.unify(arg.type) if not param.name: param.name = arg.format(Formatter()) assign_phis(used_phis, stack_info) resolve_types_late(stack_info) if options.pdb_translate: import pdb v: Dict[str, object] = {} fmt = Formatter() for local in stack_info.local_vars: var_name = local.format(fmt) v[var_name] = local for temp in stack_info.temp_vars: if temp.need_decl(): var_name = temp.expr.var.format(fmt) v[var_name] = temp.expr for phi in stack_info.phi_vars: assert phi.name is not None v[phi.name] = phi pdb.set_trace() return FunctionInfo(stack_info, flow_graph, return_type, fn_sym)
true
true
f725ad7f8cee325b6f43a8b62288b6b7f43cee75
2,727
py
Python
ibis/backends/clickhouse/tests/test_types.py
GrapeBaBa/ibis
507bb14efdcfd719a0487ee23fe1c85c177517f6
[ "Apache-2.0" ]
1
2015-11-05T15:40:12.000Z
2015-11-05T15:40:12.000Z
ibis/backends/clickhouse/tests/test_types.py
GrapeBaBa/ibis
507bb14efdcfd719a0487ee23fe1c85c177517f6
[ "Apache-2.0" ]
7
2021-09-02T21:18:10.000Z
2022-01-31T12:03:40.000Z
ibis/backends/clickhouse/tests/test_types.py
GrapeBaBa/ibis
507bb14efdcfd719a0487ee23fe1c85c177517f6
[ "Apache-2.0" ]
null
null
null
import pytest from pkg_resources import parse_version import ibis.expr.datatypes as dt from ibis.backends.clickhouse.client import ClickhouseDataType def test_column_types(alltypes): df = alltypes.execute() assert df.tinyint_col.dtype.name == 'int8' assert df.smallint_col.dtype.name == 'int16' assert df.int_col.dtype.name == 'int32' assert df.bigint_col.dtype.name == 'int64' assert df.float_col.dtype.name == 'float32' assert df.double_col.dtype.name == 'float64' assert df.timestamp_col.dtype.name == 'datetime64[ns]' def test_columns_types_with_additional_argument(con): sql_types = ["toFixedString('foo', 8) AS fixedstring_col"] if parse_version(con.version).base_version >= '1.1.54337': sql_types.append( "toDateTime('2018-07-02 00:00:00', 'UTC') AS datetime_col" ) sql = 'SELECT {}'.format(', '.join(sql_types)) df = con.sql(sql).execute() assert df.fixedstring_col.dtype.name == 'object' if parse_version(con.version).base_version >= '1.1.54337': assert df.datetime_col.dtype.name == 'datetime64[ns]' @pytest.mark.parametrize( ('ch_type', 'ibis_type'), [ ('Array(Int8)', dt.Array(dt.Int8(nullable=False))), ('Array(Int16)', dt.Array(dt.Int16(nullable=False))), ('Array(Int32)', dt.Array(dt.Int32(nullable=False))), ('Array(Int64)', dt.Array(dt.Int64(nullable=False))), ('Array(UInt8)', dt.Array(dt.UInt8(nullable=False))), ('Array(UInt16)', dt.Array(dt.UInt16(nullable=False))), ('Array(UInt32)', dt.Array(dt.UInt32(nullable=False))), ('Array(UInt64)', dt.Array(dt.UInt64(nullable=False))), ('Array(Float32)', dt.Array(dt.Float32(nullable=False))), ('Array(Float64)', dt.Array(dt.Float64(nullable=False))), ('Array(String)', dt.Array(dt.String(nullable=False))), ('Array(FixedString(32))', dt.Array(dt.String(nullable=False))), ('Array(Date)', dt.Array(dt.Date(nullable=False))), ('Array(DateTime)', dt.Array(dt.Timestamp(nullable=False))), ('Array(DateTime64)', dt.Array(dt.Timestamp(nullable=False))), ('Array(Nothing)', dt.Array(dt.Null(nullable=False))), ('Array(Null)', dt.Array(dt.Null(nullable=False))), ('Array(Array(Int8))', dt.Array(dt.Array(dt.Int8(nullable=False)))), ( 'Array(Array(Array(Int8)))', dt.Array(dt.Array(dt.Array(dt.Int8(nullable=False)))), ), ( 'Array(Array(Array(Array(Int8))))', dt.Array(dt.Array(dt.Array(dt.Array(dt.Int8(nullable=False))))), ), ], ) def test_array_type(ch_type, ibis_type): assert ClickhouseDataType(ch_type).to_ibis() == ibis_type
41.953846
76
0.635497
import pytest from pkg_resources import parse_version import ibis.expr.datatypes as dt from ibis.backends.clickhouse.client import ClickhouseDataType def test_column_types(alltypes): df = alltypes.execute() assert df.tinyint_col.dtype.name == 'int8' assert df.smallint_col.dtype.name == 'int16' assert df.int_col.dtype.name == 'int32' assert df.bigint_col.dtype.name == 'int64' assert df.float_col.dtype.name == 'float32' assert df.double_col.dtype.name == 'float64' assert df.timestamp_col.dtype.name == 'datetime64[ns]' def test_columns_types_with_additional_argument(con): sql_types = ["toFixedString('foo', 8) AS fixedstring_col"] if parse_version(con.version).base_version >= '1.1.54337': sql_types.append( "toDateTime('2018-07-02 00:00:00', 'UTC') AS datetime_col" ) sql = 'SELECT {}'.format(', '.join(sql_types)) df = con.sql(sql).execute() assert df.fixedstring_col.dtype.name == 'object' if parse_version(con.version).base_version >= '1.1.54337': assert df.datetime_col.dtype.name == 'datetime64[ns]' @pytest.mark.parametrize( ('ch_type', 'ibis_type'), [ ('Array(Int8)', dt.Array(dt.Int8(nullable=False))), ('Array(Int16)', dt.Array(dt.Int16(nullable=False))), ('Array(Int32)', dt.Array(dt.Int32(nullable=False))), ('Array(Int64)', dt.Array(dt.Int64(nullable=False))), ('Array(UInt8)', dt.Array(dt.UInt8(nullable=False))), ('Array(UInt16)', dt.Array(dt.UInt16(nullable=False))), ('Array(UInt32)', dt.Array(dt.UInt32(nullable=False))), ('Array(UInt64)', dt.Array(dt.UInt64(nullable=False))), ('Array(Float32)', dt.Array(dt.Float32(nullable=False))), ('Array(Float64)', dt.Array(dt.Float64(nullable=False))), ('Array(String)', dt.Array(dt.String(nullable=False))), ('Array(FixedString(32))', dt.Array(dt.String(nullable=False))), ('Array(Date)', dt.Array(dt.Date(nullable=False))), ('Array(DateTime)', dt.Array(dt.Timestamp(nullable=False))), ('Array(DateTime64)', dt.Array(dt.Timestamp(nullable=False))), ('Array(Nothing)', dt.Array(dt.Null(nullable=False))), ('Array(Null)', dt.Array(dt.Null(nullable=False))), ('Array(Array(Int8))', dt.Array(dt.Array(dt.Int8(nullable=False)))), ( 'Array(Array(Array(Int8)))', dt.Array(dt.Array(dt.Array(dt.Int8(nullable=False)))), ), ( 'Array(Array(Array(Array(Int8))))', dt.Array(dt.Array(dt.Array(dt.Array(dt.Int8(nullable=False))))), ), ], ) def test_array_type(ch_type, ibis_type): assert ClickhouseDataType(ch_type).to_ibis() == ibis_type
true
true
f725adf48debebf7012aabc4bd719b3c1bf15fb2
13,130
py
Python
torchreid/data_manager/cuhk03.py
phoenix1712/deep-person-reid
8537a9d94b31cbf85e475bd115bb2714086f9be0
[ "MIT" ]
11
2019-01-10T08:03:31.000Z
2020-10-23T03:14:23.000Z
torchreid/data_manager/cuhk03.py
xinshengwang/deep-person-reid
70365320f5319e180d7fce4993003382b06906b0
[ "MIT" ]
1
2020-11-13T08:20:53.000Z
2021-01-12T23:06:55.000Z
torchreid/data_manager/cuhk03.py
xinshengwang/deep-person-reid
70365320f5319e180d7fce4993003382b06906b0
[ "MIT" ]
8
2019-03-05T09:12:54.000Z
2022-02-05T06:21:21.000Z
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import glob import re import sys import urllib import tarfile import zipfile import os.path as osp from scipy.io import loadmat import numpy as np import h5py from scipy.misc import imsave from torchreid.utils.iotools import mkdir_if_missing, write_json, read_json class CUHK03(object): """ CUHK03 Reference: Li et al. DeepReID: Deep Filter Pairing Neural Network for Person Re-identification. CVPR 2014. URL: http://www.ee.cuhk.edu.hk/~xgwang/CUHK_identification.html#! Dataset statistics: # identities: 1360 # images: 13164 # cameras: 6 # splits: 20 (classic) Args: split_id (int): split index (default: 0) cuhk03_labeled (bool): whether to load labeled images; if false, detected images are loaded (default: False) """ dataset_dir = 'cuhk03' def __init__(self, root='data', split_id=0, cuhk03_labeled=False, cuhk03_classic_split=False, verbose=True, **kwargs): super(CUHK03, self).__init__() self.dataset_dir = osp.join(root, self.dataset_dir) self.data_dir = osp.join(self.dataset_dir, 'cuhk03_release') self.raw_mat_path = osp.join(self.data_dir, 'cuhk-03.mat') self.imgs_detected_dir = osp.join(self.dataset_dir, 'images_detected') self.imgs_labeled_dir = osp.join(self.dataset_dir, 'images_labeled') self.split_classic_det_json_path = osp.join(self.dataset_dir, 'splits_classic_detected.json') self.split_classic_lab_json_path = osp.join(self.dataset_dir, 'splits_classic_labeled.json') self.split_new_det_json_path = osp.join(self.dataset_dir, 'splits_new_detected.json') self.split_new_lab_json_path = osp.join(self.dataset_dir, 'splits_new_labeled.json') self.split_new_det_mat_path = osp.join(self.dataset_dir, 'cuhk03_new_protocol_config_detected.mat') self.split_new_lab_mat_path = osp.join(self.dataset_dir, 'cuhk03_new_protocol_config_labeled.mat') self._check_before_run() self._preprocess() if cuhk03_labeled: image_type = 'labeled' split_path = self.split_classic_lab_json_path if cuhk03_classic_split else self.split_new_lab_json_path else: image_type = 'detected' split_path = self.split_classic_det_json_path if cuhk03_classic_split else self.split_new_det_json_path splits = read_json(split_path) assert split_id < len(splits), "Condition split_id ({}) < len(splits) ({}) is false".format(split_id, len(splits)) split = splits[split_id] print("Split index = {}".format(split_id)) train = split['train'] query = split['query'] gallery = split['gallery'] num_train_pids = split['num_train_pids'] num_query_pids = split['num_query_pids'] num_gallery_pids = split['num_gallery_pids'] num_total_pids = num_train_pids + num_query_pids num_train_imgs = split['num_train_imgs'] num_query_imgs = split['num_query_imgs'] num_gallery_imgs = split['num_gallery_imgs'] num_total_imgs = num_train_imgs + num_query_imgs if verbose: print("=> CUHK03 ({}) loaded".format(image_type)) print("Dataset statistics:") print(" ------------------------------") print(" subset | # ids | # images") print(" ------------------------------") print(" train | {:5d} | {:8d}".format(num_train_pids, num_train_imgs)) print(" query | {:5d} | {:8d}".format(num_query_pids, num_query_imgs)) print(" gallery | {:5d} | {:8d}".format(num_gallery_pids, num_gallery_imgs)) print(" ------------------------------") print(" total | {:5d} | {:8d}".format(num_total_pids, num_total_imgs)) print(" ------------------------------") self.train = train self.query = query self.gallery = gallery self.num_train_pids = num_train_pids self.num_query_pids = num_query_pids self.num_gallery_pids = num_gallery_pids def _check_before_run(self): """Check if all files are available before going deeper""" if not osp.exists(self.dataset_dir): raise RuntimeError("'{}' is not available".format(self.dataset_dir)) if not osp.exists(self.data_dir): raise RuntimeError("'{}' is not available".format(self.data_dir)) if not osp.exists(self.raw_mat_path): raise RuntimeError("'{}' is not available".format(self.raw_mat_path)) if not osp.exists(self.split_new_det_mat_path): raise RuntimeError("'{}' is not available".format(self.split_new_det_mat_path)) if not osp.exists(self.split_new_lab_mat_path): raise RuntimeError("'{}' is not available".format(self.split_new_lab_mat_path)) def _preprocess(self): """ This function is a bit complex and ugly, what it does is 1. Extract data from cuhk-03.mat and save as png images. 2. Create 20 classic splits. (Li et al. CVPR'14) 3. Create new split. (Zhong et al. CVPR'17) """ print("Note: if root path is changed, the previously generated json files need to be re-generated (delete them first)") if osp.exists(self.imgs_labeled_dir) and \ osp.exists(self.imgs_detected_dir) and \ osp.exists(self.split_classic_det_json_path) and \ osp.exists(self.split_classic_lab_json_path) and \ osp.exists(self.split_new_det_json_path) and \ osp.exists(self.split_new_lab_json_path): return mkdir_if_missing(self.imgs_detected_dir) mkdir_if_missing(self.imgs_labeled_dir) print("Extract image data from {} and save as png".format(self.raw_mat_path)) mat = h5py.File(self.raw_mat_path, 'r') def _deref(ref): return mat[ref][:].T def _process_images(img_refs, campid, pid, save_dir): img_paths = [] # Note: some persons only have images for one view for imgid, img_ref in enumerate(img_refs): img = _deref(img_ref) # skip empty cell if img.size == 0 or img.ndim < 3: continue # images are saved with the following format, index-1 (ensure uniqueness) # campid: index of camera pair (1-5) # pid: index of person in 'campid'-th camera pair # viewid: index of view, {1, 2} # imgid: index of image, (1-10) viewid = 1 if imgid < 5 else 2 img_name = '{:01d}_{:03d}_{:01d}_{:02d}.png'.format(campid+1, pid+1, viewid, imgid+1) img_path = osp.join(save_dir, img_name) imsave(img_path, img) img_paths.append(img_path) return img_paths def _extract_img(name): print("Processing {} images (extract and save) ...".format(name)) meta_data = [] imgs_dir = self.imgs_detected_dir if name == 'detected' else self.imgs_labeled_dir for campid, camp_ref in enumerate(mat[name][0]): camp = _deref(camp_ref) num_pids = camp.shape[0] for pid in range(num_pids): img_paths = _process_images(camp[pid,:], campid, pid, imgs_dir) assert len(img_paths) > 0, "campid{}-pid{} has no images".format(campid, pid) meta_data.append((campid+1, pid+1, img_paths)) print("done camera pair {} with {} identities".format(campid+1, num_pids)) return meta_data meta_detected = _extract_img('detected') meta_labeled = _extract_img('labeled') def _extract_classic_split(meta_data, test_split): train, test = [], [] num_train_pids, num_test_pids = 0, 0 num_train_imgs, num_test_imgs = 0, 0 for i, (campid, pid, img_paths) in enumerate(meta_data): if [campid, pid] in test_split: for img_path in img_paths: camid = int(osp.basename(img_path).split('_')[2]) test.append((img_path, num_test_pids, camid)) num_test_pids += 1 num_test_imgs += len(img_paths) else: for img_path in img_paths: camid = int(osp.basename(img_path).split('_')[2]) train.append((img_path, num_train_pids, camid)) num_train_pids += 1 num_train_imgs += len(img_paths) return train, num_train_pids, num_train_imgs, test, num_test_pids, num_test_imgs print("Creating classic splits (# = 20) ...") splits_classic_det, splits_classic_lab = [], [] for split_ref in mat['testsets'][0]: test_split = _deref(split_ref).tolist() # create split for detected images train, num_train_pids, num_train_imgs, test, num_test_pids, num_test_imgs = \ _extract_classic_split(meta_detected, test_split) splits_classic_det.append({ 'train': train, 'query': test, 'gallery': test, 'num_train_pids': num_train_pids, 'num_train_imgs': num_train_imgs, 'num_query_pids': num_test_pids, 'num_query_imgs': num_test_imgs, 'num_gallery_pids': num_test_pids, 'num_gallery_imgs': num_test_imgs, }) # create split for labeled images train, num_train_pids, num_train_imgs, test, num_test_pids, num_test_imgs = \ _extract_classic_split(meta_labeled, test_split) splits_classic_lab.append({ 'train': train, 'query': test, 'gallery': test, 'num_train_pids': num_train_pids, 'num_train_imgs': num_train_imgs, 'num_query_pids': num_test_pids, 'num_query_imgs': num_test_imgs, 'num_gallery_pids': num_test_pids, 'num_gallery_imgs': num_test_imgs, }) write_json(splits_classic_det, self.split_classic_det_json_path) write_json(splits_classic_lab, self.split_classic_lab_json_path) def _extract_set(filelist, pids, pid2label, idxs, img_dir, relabel): tmp_set = [] unique_pids = set() for idx in idxs: img_name = filelist[idx][0] camid = int(img_name.split('_')[2]) pid = pids[idx] if relabel: pid = pid2label[pid] img_path = osp.join(img_dir, img_name) tmp_set.append((img_path, int(pid), camid)) unique_pids.add(pid) return tmp_set, len(unique_pids), len(idxs) def _extract_new_split(split_dict, img_dir): train_idxs = split_dict['train_idx'].flatten() - 1 # index-0 pids = split_dict['labels'].flatten() train_pids = set(pids[train_idxs]) pid2label = {pid: label for label, pid in enumerate(train_pids)} query_idxs = split_dict['query_idx'].flatten() - 1 gallery_idxs = split_dict['gallery_idx'].flatten() - 1 filelist = split_dict['filelist'].flatten() train_info = _extract_set(filelist, pids, pid2label, train_idxs, img_dir, relabel=True) query_info = _extract_set(filelist, pids, pid2label, query_idxs, img_dir, relabel=False) gallery_info = _extract_set(filelist, pids, pid2label, gallery_idxs, img_dir, relabel=False) return train_info, query_info, gallery_info print("Creating new splits for detected images (767/700) ...") train_info, query_info, gallery_info = _extract_new_split( loadmat(self.split_new_det_mat_path), self.imgs_detected_dir, ) splits = [{ 'train': train_info[0], 'query': query_info[0], 'gallery': gallery_info[0], 'num_train_pids': train_info[1], 'num_train_imgs': train_info[2], 'num_query_pids': query_info[1], 'num_query_imgs': query_info[2], 'num_gallery_pids': gallery_info[1], 'num_gallery_imgs': gallery_info[2], }] write_json(splits, self.split_new_det_json_path) print("Creating new splits for labeled images (767/700) ...") train_info, query_info, gallery_info = _extract_new_split( loadmat(self.split_new_lab_mat_path), self.imgs_labeled_dir, ) splits = [{ 'train': train_info[0], 'query': query_info[0], 'gallery': gallery_info[0], 'num_train_pids': train_info[1], 'num_train_imgs': train_info[2], 'num_query_pids': query_info[1], 'num_query_imgs': query_info[2], 'num_gallery_pids': gallery_info[1], 'num_gallery_imgs': gallery_info[2], }] write_json(splits, self.split_new_lab_json_path)
46.560284
127
0.6131
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import glob import re import sys import urllib import tarfile import zipfile import os.path as osp from scipy.io import loadmat import numpy as np import h5py from scipy.misc import imsave from torchreid.utils.iotools import mkdir_if_missing, write_json, read_json class CUHK03(object): dataset_dir = 'cuhk03' def __init__(self, root='data', split_id=0, cuhk03_labeled=False, cuhk03_classic_split=False, verbose=True, **kwargs): super(CUHK03, self).__init__() self.dataset_dir = osp.join(root, self.dataset_dir) self.data_dir = osp.join(self.dataset_dir, 'cuhk03_release') self.raw_mat_path = osp.join(self.data_dir, 'cuhk-03.mat') self.imgs_detected_dir = osp.join(self.dataset_dir, 'images_detected') self.imgs_labeled_dir = osp.join(self.dataset_dir, 'images_labeled') self.split_classic_det_json_path = osp.join(self.dataset_dir, 'splits_classic_detected.json') self.split_classic_lab_json_path = osp.join(self.dataset_dir, 'splits_classic_labeled.json') self.split_new_det_json_path = osp.join(self.dataset_dir, 'splits_new_detected.json') self.split_new_lab_json_path = osp.join(self.dataset_dir, 'splits_new_labeled.json') self.split_new_det_mat_path = osp.join(self.dataset_dir, 'cuhk03_new_protocol_config_detected.mat') self.split_new_lab_mat_path = osp.join(self.dataset_dir, 'cuhk03_new_protocol_config_labeled.mat') self._check_before_run() self._preprocess() if cuhk03_labeled: image_type = 'labeled' split_path = self.split_classic_lab_json_path if cuhk03_classic_split else self.split_new_lab_json_path else: image_type = 'detected' split_path = self.split_classic_det_json_path if cuhk03_classic_split else self.split_new_det_json_path splits = read_json(split_path) assert split_id < len(splits), "Condition split_id ({}) < len(splits) ({}) is false".format(split_id, len(splits)) split = splits[split_id] print("Split index = {}".format(split_id)) train = split['train'] query = split['query'] gallery = split['gallery'] num_train_pids = split['num_train_pids'] num_query_pids = split['num_query_pids'] num_gallery_pids = split['num_gallery_pids'] num_total_pids = num_train_pids + num_query_pids num_train_imgs = split['num_train_imgs'] num_query_imgs = split['num_query_imgs'] num_gallery_imgs = split['num_gallery_imgs'] num_total_imgs = num_train_imgs + num_query_imgs if verbose: print("=> CUHK03 ({}) loaded".format(image_type)) print("Dataset statistics:") print(" ------------------------------") print(" subset | # ids | # images") print(" ------------------------------") print(" train | {:5d} | {:8d}".format(num_train_pids, num_train_imgs)) print(" query | {:5d} | {:8d}".format(num_query_pids, num_query_imgs)) print(" gallery | {:5d} | {:8d}".format(num_gallery_pids, num_gallery_imgs)) print(" ------------------------------") print(" total | {:5d} | {:8d}".format(num_total_pids, num_total_imgs)) print(" ------------------------------") self.train = train self.query = query self.gallery = gallery self.num_train_pids = num_train_pids self.num_query_pids = num_query_pids self.num_gallery_pids = num_gallery_pids def _check_before_run(self): if not osp.exists(self.dataset_dir): raise RuntimeError("'{}' is not available".format(self.dataset_dir)) if not osp.exists(self.data_dir): raise RuntimeError("'{}' is not available".format(self.data_dir)) if not osp.exists(self.raw_mat_path): raise RuntimeError("'{}' is not available".format(self.raw_mat_path)) if not osp.exists(self.split_new_det_mat_path): raise RuntimeError("'{}' is not available".format(self.split_new_det_mat_path)) if not osp.exists(self.split_new_lab_mat_path): raise RuntimeError("'{}' is not available".format(self.split_new_lab_mat_path)) def _preprocess(self): print("Note: if root path is changed, the previously generated json files need to be re-generated (delete them first)") if osp.exists(self.imgs_labeled_dir) and \ osp.exists(self.imgs_detected_dir) and \ osp.exists(self.split_classic_det_json_path) and \ osp.exists(self.split_classic_lab_json_path) and \ osp.exists(self.split_new_det_json_path) and \ osp.exists(self.split_new_lab_json_path): return mkdir_if_missing(self.imgs_detected_dir) mkdir_if_missing(self.imgs_labeled_dir) print("Extract image data from {} and save as png".format(self.raw_mat_path)) mat = h5py.File(self.raw_mat_path, 'r') def _deref(ref): return mat[ref][:].T def _process_images(img_refs, campid, pid, save_dir): img_paths = [] for imgid, img_ref in enumerate(img_refs): img = _deref(img_ref) if img.size == 0 or img.ndim < 3: continue viewid = 1 if imgid < 5 else 2 img_name = '{:01d}_{:03d}_{:01d}_{:02d}.png'.format(campid+1, pid+1, viewid, imgid+1) img_path = osp.join(save_dir, img_name) imsave(img_path, img) img_paths.append(img_path) return img_paths def _extract_img(name): print("Processing {} images (extract and save) ...".format(name)) meta_data = [] imgs_dir = self.imgs_detected_dir if name == 'detected' else self.imgs_labeled_dir for campid, camp_ref in enumerate(mat[name][0]): camp = _deref(camp_ref) num_pids = camp.shape[0] for pid in range(num_pids): img_paths = _process_images(camp[pid,:], campid, pid, imgs_dir) assert len(img_paths) > 0, "campid{}-pid{} has no images".format(campid, pid) meta_data.append((campid+1, pid+1, img_paths)) print("done camera pair {} with {} identities".format(campid+1, num_pids)) return meta_data meta_detected = _extract_img('detected') meta_labeled = _extract_img('labeled') def _extract_classic_split(meta_data, test_split): train, test = [], [] num_train_pids, num_test_pids = 0, 0 num_train_imgs, num_test_imgs = 0, 0 for i, (campid, pid, img_paths) in enumerate(meta_data): if [campid, pid] in test_split: for img_path in img_paths: camid = int(osp.basename(img_path).split('_')[2]) test.append((img_path, num_test_pids, camid)) num_test_pids += 1 num_test_imgs += len(img_paths) else: for img_path in img_paths: camid = int(osp.basename(img_path).split('_')[2]) train.append((img_path, num_train_pids, camid)) num_train_pids += 1 num_train_imgs += len(img_paths) return train, num_train_pids, num_train_imgs, test, num_test_pids, num_test_imgs print("Creating classic splits (# = 20) ...") splits_classic_det, splits_classic_lab = [], [] for split_ref in mat['testsets'][0]: test_split = _deref(split_ref).tolist() train, num_train_pids, num_train_imgs, test, num_test_pids, num_test_imgs = \ _extract_classic_split(meta_detected, test_split) splits_classic_det.append({ 'train': train, 'query': test, 'gallery': test, 'num_train_pids': num_train_pids, 'num_train_imgs': num_train_imgs, 'num_query_pids': num_test_pids, 'num_query_imgs': num_test_imgs, 'num_gallery_pids': num_test_pids, 'num_gallery_imgs': num_test_imgs, }) train, num_train_pids, num_train_imgs, test, num_test_pids, num_test_imgs = \ _extract_classic_split(meta_labeled, test_split) splits_classic_lab.append({ 'train': train, 'query': test, 'gallery': test, 'num_train_pids': num_train_pids, 'num_train_imgs': num_train_imgs, 'num_query_pids': num_test_pids, 'num_query_imgs': num_test_imgs, 'num_gallery_pids': num_test_pids, 'num_gallery_imgs': num_test_imgs, }) write_json(splits_classic_det, self.split_classic_det_json_path) write_json(splits_classic_lab, self.split_classic_lab_json_path) def _extract_set(filelist, pids, pid2label, idxs, img_dir, relabel): tmp_set = [] unique_pids = set() for idx in idxs: img_name = filelist[idx][0] camid = int(img_name.split('_')[2]) pid = pids[idx] if relabel: pid = pid2label[pid] img_path = osp.join(img_dir, img_name) tmp_set.append((img_path, int(pid), camid)) unique_pids.add(pid) return tmp_set, len(unique_pids), len(idxs) def _extract_new_split(split_dict, img_dir): train_idxs = split_dict['train_idx'].flatten() - 1 pids = split_dict['labels'].flatten() train_pids = set(pids[train_idxs]) pid2label = {pid: label for label, pid in enumerate(train_pids)} query_idxs = split_dict['query_idx'].flatten() - 1 gallery_idxs = split_dict['gallery_idx'].flatten() - 1 filelist = split_dict['filelist'].flatten() train_info = _extract_set(filelist, pids, pid2label, train_idxs, img_dir, relabel=True) query_info = _extract_set(filelist, pids, pid2label, query_idxs, img_dir, relabel=False) gallery_info = _extract_set(filelist, pids, pid2label, gallery_idxs, img_dir, relabel=False) return train_info, query_info, gallery_info print("Creating new splits for detected images (767/700) ...") train_info, query_info, gallery_info = _extract_new_split( loadmat(self.split_new_det_mat_path), self.imgs_detected_dir, ) splits = [{ 'train': train_info[0], 'query': query_info[0], 'gallery': gallery_info[0], 'num_train_pids': train_info[1], 'num_train_imgs': train_info[2], 'num_query_pids': query_info[1], 'num_query_imgs': query_info[2], 'num_gallery_pids': gallery_info[1], 'num_gallery_imgs': gallery_info[2], }] write_json(splits, self.split_new_det_json_path) print("Creating new splits for labeled images (767/700) ...") train_info, query_info, gallery_info = _extract_new_split( loadmat(self.split_new_lab_mat_path), self.imgs_labeled_dir, ) splits = [{ 'train': train_info[0], 'query': query_info[0], 'gallery': gallery_info[0], 'num_train_pids': train_info[1], 'num_train_imgs': train_info[2], 'num_query_pids': query_info[1], 'num_query_imgs': query_info[2], 'num_gallery_pids': gallery_info[1], 'num_gallery_imgs': gallery_info[2], }] write_json(splits, self.split_new_lab_json_path)
true
true
f725ae061cedbfc0818ee7c7320e4bbe82b540ad
62,902
py
Python
pandas/core/groupby/generic.py
selasley/pandas
5b5574520dba1e79ac95e5079724a41151c20b9a
[ "BSD-3-Clause" ]
null
null
null
pandas/core/groupby/generic.py
selasley/pandas
5b5574520dba1e79ac95e5079724a41151c20b9a
[ "BSD-3-Clause" ]
null
null
null
pandas/core/groupby/generic.py
selasley/pandas
5b5574520dba1e79ac95e5079724a41151c20b9a
[ "BSD-3-Clause" ]
null
null
null
""" Define the SeriesGroupBy and DataFrameGroupBy classes that hold the groupby interfaces (and some implementations). These are user facing as the result of the ``df.groupby(...)`` operations, which here returns a DataFrameGroupBy object. """ from __future__ import annotations from collections import abc from functools import partial from textwrap import dedent from typing import ( Any, Callable, Hashable, Iterable, Mapping, NamedTuple, Sequence, TypeVar, Union, cast, ) import warnings import numpy as np from pandas._libs import ( Interval, reduction as libreduction, ) from pandas._typing import ( ArrayLike, Manager, Manager2D, SingleManager, ) from pandas.util._decorators import ( Appender, Substitution, doc, ) from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( ensure_int64, is_bool, is_categorical_dtype, is_dict_like, is_integer_dtype, is_interval_dtype, is_scalar, ) from pandas.core.dtypes.missing import ( isna, notna, ) from pandas.core import ( algorithms, nanops, ) from pandas.core.apply import ( GroupByApply, maybe_mangle_lambdas, reconstruct_func, validate_func_kwargs, ) from pandas.core.base import SpecificationError import pandas.core.common as com from pandas.core.construction import create_series_with_explicit_dtype from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame from pandas.core.groupby import base from pandas.core.groupby.groupby import ( GroupBy, _agg_template, _apply_docs, _transform_template, warn_dropping_nuisance_columns_deprecated, ) from pandas.core.groupby.grouper import get_grouper from pandas.core.indexes.api import ( Index, MultiIndex, all_indexes_same, ) from pandas.core.series import Series from pandas.core.shared_docs import _shared_docs from pandas.core.util.numba_ import maybe_use_numba from pandas.plotting import boxplot_frame_groupby # TODO(typing) the return value on this callable should be any *scalar*. AggScalar = Union[str, Callable[..., Any]] # TODO: validate types on ScalarResult and move to _typing # Blocked from using by https://github.com/python/mypy/issues/1484 # See note at _mangle_lambda_list ScalarResult = TypeVar("ScalarResult") class NamedAgg(NamedTuple): column: Hashable aggfunc: AggScalar def generate_property(name: str, klass: type[DataFrame | Series]): """ Create a property for a GroupBy subclass to dispatch to DataFrame/Series. Parameters ---------- name : str klass : {DataFrame, Series} Returns ------- property """ def prop(self): return self._make_wrapper(name) parent_method = getattr(klass, name) prop.__doc__ = parent_method.__doc__ or "" prop.__name__ = name return property(prop) def pin_allowlisted_properties( klass: type[DataFrame | Series], allowlist: frozenset[str] ): """ Create GroupBy member defs for DataFrame/Series names in a allowlist. Parameters ---------- klass : DataFrame or Series class class where members are defined. allowlist : frozenset[str] Set of names of klass methods to be constructed Returns ------- class decorator Notes ----- Since we don't want to override methods explicitly defined in the base class, any such name is skipped. """ def pinner(cls): for name in allowlist: if hasattr(cls, name): # don't override anything that was explicitly defined # in the base class continue prop = generate_property(name, klass) setattr(cls, name, prop) return cls return pinner @pin_allowlisted_properties(Series, base.series_apply_allowlist) class SeriesGroupBy(GroupBy[Series]): _apply_allowlist = base.series_apply_allowlist def _wrap_agged_manager(self, mgr: Manager) -> Series: if mgr.ndim == 1: mgr = cast(SingleManager, mgr) single = mgr else: mgr = cast(Manager2D, mgr) single = mgr.iget(0) ser = self.obj._constructor(single, name=self.obj.name) # NB: caller is responsible for setting ser.index return ser def _get_data_to_aggregate(self) -> SingleManager: ser = self._obj_with_exclusions single = ser._mgr return single def _iterate_slices(self) -> Iterable[Series]: yield self._selected_obj _agg_examples_doc = dedent( """ Examples -------- >>> s = pd.Series([1, 2, 3, 4]) >>> s 0 1 1 2 2 3 3 4 dtype: int64 >>> s.groupby([1, 1, 2, 2]).min() 1 1 2 3 dtype: int64 >>> s.groupby([1, 1, 2, 2]).agg('min') 1 1 2 3 dtype: int64 >>> s.groupby([1, 1, 2, 2]).agg(['min', 'max']) min max 1 1 2 2 3 4 The output column names can be controlled by passing the desired column names and aggregations as keyword arguments. >>> s.groupby([1, 1, 2, 2]).agg( ... minimum='min', ... maximum='max', ... ) minimum maximum 1 1 2 2 3 4 .. versionchanged:: 1.3.0 The resulting dtype will reflect the return value of the aggregating function. >>> s.groupby([1, 1, 2, 2]).agg(lambda x: x.astype(float).min()) 1 1.0 2 3.0 dtype: float64 """ ) @Appender( _apply_docs["template"].format( input="series", examples=_apply_docs["series_examples"] ) ) def apply(self, func, *args, **kwargs) -> Series: return super().apply(func, *args, **kwargs) @doc(_agg_template, examples=_agg_examples_doc, klass="Series") def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs): if maybe_use_numba(engine): with self._group_selection_context(): data = self._selected_obj result = self._aggregate_with_numba( data.to_frame(), func, *args, engine_kwargs=engine_kwargs, **kwargs ) index = self.grouper.result_index return self.obj._constructor(result.ravel(), index=index, name=data.name) relabeling = func is None columns = None if relabeling: columns, func = validate_func_kwargs(kwargs) kwargs = {} if isinstance(func, str): return getattr(self, func)(*args, **kwargs) elif isinstance(func, abc.Iterable): # Catch instances of lists / tuples # but not the class list / tuple itself. func = maybe_mangle_lambdas(func) ret = self._aggregate_multiple_funcs(func) if relabeling: # error: Incompatible types in assignment (expression has type # "Optional[List[str]]", variable has type "Index") ret.columns = columns # type: ignore[assignment] return ret else: cyfunc = com.get_cython_func(func) if cyfunc and not args and not kwargs: return getattr(self, cyfunc)() if self.grouper.nkeys > 1: return self._python_agg_general(func, *args, **kwargs) try: return self._python_agg_general(func, *args, **kwargs) except KeyError: # TODO: KeyError is raised in _python_agg_general, # see test_groupby.test_basic result = self._aggregate_named(func, *args, **kwargs) # result is a dict whose keys are the elements of result_index index = self.grouper.result_index return create_series_with_explicit_dtype( result, index=index, dtype_if_empty=object ) agg = aggregate def _aggregate_multiple_funcs(self, arg) -> DataFrame: if isinstance(arg, dict): # show the deprecation, but only if we # have not shown a higher level one # GH 15931 raise SpecificationError("nested renamer is not supported") elif any(isinstance(x, (tuple, list)) for x in arg): arg = [(x, x) if not isinstance(x, (tuple, list)) else x for x in arg] # indicated column order columns = next(zip(*arg)) else: # list of functions / function names columns = [] for f in arg: columns.append(com.get_callable_name(f) or f) arg = zip(columns, arg) results: dict[base.OutputKey, DataFrame | Series] = {} for idx, (name, func) in enumerate(arg): key = base.OutputKey(label=name, position=idx) results[key] = self.aggregate(func) if any(isinstance(x, DataFrame) for x in results.values()): from pandas import concat res_df = concat( results.values(), axis=1, keys=[key.label for key in results.keys()] ) return res_df indexed_output = {key.position: val for key, val in results.items()} output = self.obj._constructor_expanddim(indexed_output, index=None) output.columns = Index(key.label for key in results) output = self._reindex_output(output) return output def _indexed_output_to_ndframe( self, output: Mapping[base.OutputKey, ArrayLike] ) -> Series: """ Wrap the dict result of a GroupBy aggregation into a Series. """ assert len(output) == 1 values = next(iter(output.values())) result = self.obj._constructor(values) result.name = self.obj.name return result def _wrap_applied_output( self, data: Series, values: list[Any], not_indexed_same: bool = False, override_group_keys: bool = False, ) -> DataFrame | Series: """ Wrap the output of SeriesGroupBy.apply into the expected result. Parameters ---------- data : Series Input data for groupby operation. values : List[Any] Applied output for each group. not_indexed_same : bool, default False Whether the applied outputs are not indexed the same as the group axes. Returns ------- DataFrame or Series """ if len(values) == 0: # GH #6265 return self.obj._constructor( [], name=self.obj.name, index=self.grouper.result_index, dtype=data.dtype, ) assert values is not None if isinstance(values[0], dict): # GH #823 #24880 index = self.grouper.result_index res_df = self.obj._constructor_expanddim(values, index=index) res_df = self._reindex_output(res_df) # if self.observed is False, # keep all-NaN rows created while re-indexing res_ser = res_df.stack(dropna=self.observed) res_ser.name = self.obj.name return res_ser elif isinstance(values[0], (Series, DataFrame)): result = self._concat_objects( values, not_indexed_same=not_indexed_same, override_group_keys=override_group_keys, ) result.name = self.obj.name return result else: # GH #6265 #24880 result = self.obj._constructor( data=values, index=self.grouper.result_index, name=self.obj.name ) return self._reindex_output(result) def _aggregate_named(self, func, *args, **kwargs): # Note: this is very similar to _aggregate_series_pure_python, # but that does not pin group.name result = {} initialized = False for name, group in self: object.__setattr__(group, "name", name) output = func(group, *args, **kwargs) output = libreduction.extract_result(output) if not initialized: # We only do this validation on the first iteration libreduction.check_result_array(output, group.dtype) initialized = True result[name] = output return result @Substitution(klass="Series") @Appender(_transform_template) def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): return self._transform( func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs ) def _cython_transform( self, how: str, numeric_only: bool = True, axis: int = 0, **kwargs ): assert axis == 0 # handled by caller obj = self._selected_obj try: result = self.grouper._cython_operation( "transform", obj._values, how, axis, **kwargs ) except NotImplementedError as err: raise TypeError(f"{how} is not supported for {obj.dtype} dtype") from err return obj._constructor(result, index=self.obj.index, name=obj.name) def _transform_general(self, func: Callable, *args, **kwargs) -> Series: """ Transform with a callable func`. """ assert callable(func) klass = type(self.obj) results = [] for name, group in self: # this setattr is needed for test_transform_lambda_with_datetimetz object.__setattr__(group, "name", name) res = func(group, *args, **kwargs) results.append(klass(res, index=group.index)) # check for empty "results" to avoid concat ValueError if results: from pandas.core.reshape.concat import concat concatenated = concat(results) result = self._set_result_index_ordered(concatenated) else: result = self.obj._constructor(dtype=np.float64) result.name = self.obj.name return result def filter(self, func, dropna: bool = True, *args, **kwargs): """ Return a copy of a Series excluding elements from groups that do not satisfy the boolean criterion specified by func. Parameters ---------- func : function To apply to each group. Should return True or False. dropna : Drop groups that do not pass the filter. True by default; if False, groups that evaluate False are filled with NaNs. Notes ----- Functions that mutate the passed object can produce unexpected behavior or errors and are not supported. See :ref:`gotchas.udf-mutation` for more details. Examples -------- >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', ... 'foo', 'bar'], ... 'B' : [1, 2, 3, 4, 5, 6], ... 'C' : [2.0, 5., 8., 1., 2., 9.]}) >>> grouped = df.groupby('A') >>> df.groupby('A').B.filter(lambda x: x.mean() > 3.) 1 2 3 4 5 6 Name: B, dtype: int64 Returns ------- filtered : Series """ if isinstance(func, str): wrapper = lambda x: getattr(x, func)(*args, **kwargs) else: wrapper = lambda x: func(x, *args, **kwargs) # Interpret np.nan as False. def true_and_notna(x) -> bool: b = wrapper(x) return b and notna(b) try: indices = [ self._get_index(name) for name, group in self if true_and_notna(group) ] except (ValueError, TypeError) as err: raise TypeError("the filter must return a boolean result") from err filtered = self._apply_filter(indices, dropna) return filtered def nunique(self, dropna: bool = True) -> Series: """ Return number of unique elements in the group. Returns ------- Series Number of unique values within each group. """ ids, _, _ = self.grouper.group_info val = self.obj._values codes, _ = algorithms.factorize(val, sort=False) sorter = np.lexsort((codes, ids)) codes = codes[sorter] ids = ids[sorter] # group boundaries are where group ids change # unique observations are where sorted values change idx = np.r_[0, 1 + np.nonzero(ids[1:] != ids[:-1])[0]] inc = np.r_[1, codes[1:] != codes[:-1]] # 1st item of each group is a new unique observation mask = codes == -1 if dropna: inc[idx] = 1 inc[mask] = 0 else: inc[mask & np.r_[False, mask[:-1]]] = 0 inc[idx] = 1 out = np.add.reduceat(inc, idx).astype("int64", copy=False) if len(ids): # NaN/NaT group exists if the head of ids is -1, # so remove it from res and exclude its index from idx if ids[0] == -1: res = out[1:] idx = idx[np.flatnonzero(idx)] else: res = out else: res = out[1:] ri = self.grouper.result_index # we might have duplications among the bins if len(res) != len(ri): res, out = np.zeros(len(ri), dtype=out.dtype), res res[ids[idx]] = out result = self.obj._constructor(res, index=ri, name=self.obj.name) return self._reindex_output(result, fill_value=0) @doc(Series.describe) def describe(self, **kwargs): return super().describe(**kwargs) def value_counts( self, normalize: bool = False, sort: bool = True, ascending: bool = False, bins=None, dropna: bool = True, ): from pandas.core.reshape.merge import get_join_indexers from pandas.core.reshape.tile import cut ids, _, _ = self.grouper.group_info val = self.obj._values names = self.grouper.names + [self.obj.name] if is_categorical_dtype(val.dtype) or ( bins is not None and not np.iterable(bins) ): # scalar bins cannot be done at top level # in a backward compatible way # GH38672 relates to categorical dtype ser = self.apply( Series.value_counts, normalize=normalize, sort=sort, ascending=ascending, bins=bins, ) ser.index.names = names return ser # groupby removes null keys from groupings mask = ids != -1 ids, val = ids[mask], val[mask] if bins is None: lab, lev = algorithms.factorize(val, sort=True) llab = lambda lab, inc: lab[inc] else: # lab is a Categorical with categories an IntervalIndex lab = cut(Series(val), bins, include_lowest=True) # error: "ndarray" has no attribute "cat" lev = lab.cat.categories # type: ignore[attr-defined] # error: No overload variant of "take" of "_ArrayOrScalarCommon" matches # argument types "Any", "bool", "Union[Any, float]" lab = lev.take( # type: ignore[call-overload] # error: "ndarray" has no attribute "cat" lab.cat.codes, # type: ignore[attr-defined] allow_fill=True, # error: Item "ndarray" of "Union[ndarray, Index]" has no attribute # "_na_value" fill_value=lev._na_value, # type: ignore[union-attr] ) llab = lambda lab, inc: lab[inc]._multiindex.codes[-1] if is_interval_dtype(lab.dtype): # TODO: should we do this inside II? lab_interval = cast(Interval, lab) sorter = np.lexsort((lab_interval.left, lab_interval.right, ids)) else: sorter = np.lexsort((lab, ids)) ids, lab = ids[sorter], lab[sorter] # group boundaries are where group ids change idchanges = 1 + np.nonzero(ids[1:] != ids[:-1])[0] idx = np.r_[0, idchanges] if not len(ids): idx = idchanges # new values are where sorted labels change lchanges = llab(lab, slice(1, None)) != llab(lab, slice(None, -1)) inc = np.r_[True, lchanges] if not len(val): inc = lchanges inc[idx] = True # group boundaries are also new values out = np.diff(np.nonzero(np.r_[inc, True])[0]) # value counts # num. of times each group should be repeated rep = partial(np.repeat, repeats=np.add.reduceat(inc, idx)) # multi-index components codes = self.grouper.reconstructed_codes codes = [rep(level_codes) for level_codes in codes] + [llab(lab, inc)] # error: List item 0 has incompatible type "Union[ndarray[Any, Any], Index]"; # expected "Index" levels = [ping.group_index for ping in self.grouper.groupings] + [ lev # type: ignore[list-item] ] if dropna: mask = codes[-1] != -1 if mask.all(): dropna = False else: out, codes = out[mask], [level_codes[mask] for level_codes in codes] if normalize: out = out.astype("float") d = np.diff(np.r_[idx, len(ids)]) if dropna: m = ids[lab == -1] np.add.at(d, m, -1) acc = rep(d)[mask] else: acc = rep(d) out /= acc if sort and bins is None: cat = ids[inc][mask] if dropna else ids[inc] sorter = np.lexsort((out if ascending else -out, cat)) out, codes[-1] = out[sorter], codes[-1][sorter] if bins is not None: # for compat. with libgroupby.value_counts need to ensure every # bin is present at every index level, null filled with zeros diff = np.zeros(len(out), dtype="bool") for level_codes in codes[:-1]: diff |= np.r_[True, level_codes[1:] != level_codes[:-1]] ncat, nbin = diff.sum(), len(levels[-1]) left = [np.repeat(np.arange(ncat), nbin), np.tile(np.arange(nbin), ncat)] right = [diff.cumsum() - 1, codes[-1]] _, idx = get_join_indexers(left, right, sort=False, how="left") out = np.where(idx != -1, out[idx], 0) if sort: sorter = np.lexsort((out if ascending else -out, left[0])) out, left[-1] = out[sorter], left[-1][sorter] # build the multi-index w/ full levels def build_codes(lev_codes: np.ndarray) -> np.ndarray: return np.repeat(lev_codes[diff], nbin) codes = [build_codes(lev_codes) for lev_codes in codes[:-1]] codes.append(left[-1]) mi = MultiIndex(levels=levels, codes=codes, names=names, verify_integrity=False) if is_integer_dtype(out.dtype): out = ensure_int64(out) return self.obj._constructor(out, index=mi, name=self.obj.name) @doc(Series.nlargest) def nlargest(self, n: int = 5, keep: str = "first"): f = partial(Series.nlargest, n=n, keep=keep) data = self._obj_with_exclusions # Don't change behavior if result index happens to be the same, i.e. # already ordered and n >= all group sizes. result = self._python_apply_general(f, data, not_indexed_same=True) return result @doc(Series.nsmallest) def nsmallest(self, n: int = 5, keep: str = "first"): f = partial(Series.nsmallest, n=n, keep=keep) data = self._obj_with_exclusions # Don't change behavior if result index happens to be the same, i.e. # already ordered and n >= all group sizes. result = self._python_apply_general(f, data, not_indexed_same=True) return result @pin_allowlisted_properties(DataFrame, base.dataframe_apply_allowlist) class DataFrameGroupBy(GroupBy[DataFrame]): _apply_allowlist = base.dataframe_apply_allowlist _agg_examples_doc = dedent( """ Examples -------- >>> df = pd.DataFrame( ... { ... "A": [1, 1, 2, 2], ... "B": [1, 2, 3, 4], ... "C": [0.362838, 0.227877, 1.267767, -0.562860], ... } ... ) >>> df A B C 0 1 1 0.362838 1 1 2 0.227877 2 2 3 1.267767 3 2 4 -0.562860 The aggregation is for each column. >>> df.groupby('A').agg('min') B C A 1 1 0.227877 2 3 -0.562860 Multiple aggregations >>> df.groupby('A').agg(['min', 'max']) B C min max min max A 1 1 2 0.227877 0.362838 2 3 4 -0.562860 1.267767 Select a column for aggregation >>> df.groupby('A').B.agg(['min', 'max']) min max A 1 1 2 2 3 4 Different aggregations per column >>> df.groupby('A').agg({'B': ['min', 'max'], 'C': 'sum'}) B C min max sum A 1 1 2 0.590715 2 3 4 0.704907 To control the output names with different aggregations per column, pandas supports "named aggregation" >>> df.groupby("A").agg( ... b_min=pd.NamedAgg(column="B", aggfunc="min"), ... c_sum=pd.NamedAgg(column="C", aggfunc="sum")) b_min c_sum A 1 1 0.590715 2 3 0.704907 - The keywords are the *output* column names - The values are tuples whose first element is the column to select and the second element is the aggregation to apply to that column. Pandas provides the ``pandas.NamedAgg`` namedtuple with the fields ``['column', 'aggfunc']`` to make it clearer what the arguments are. As usual, the aggregation can be a callable or a string alias. See :ref:`groupby.aggregate.named` for more. .. versionchanged:: 1.3.0 The resulting dtype will reflect the return value of the aggregating function. >>> df.groupby("A")[["B"]].agg(lambda x: x.astype(float).min()) B A 1 1.0 2 3.0 """ ) @doc(_agg_template, examples=_agg_examples_doc, klass="DataFrame") def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs): if maybe_use_numba(engine): with self._group_selection_context(): data = self._selected_obj result = self._aggregate_with_numba( data, func, *args, engine_kwargs=engine_kwargs, **kwargs ) index = self.grouper.result_index return self.obj._constructor(result, index=index, columns=data.columns) relabeling, func, columns, order = reconstruct_func(func, **kwargs) func = maybe_mangle_lambdas(func) op = GroupByApply(self, func, args, kwargs) result = op.agg() if not is_dict_like(func) and result is not None: return result elif relabeling and result is not None: # this should be the only (non-raising) case with relabeling # used reordered index of columns result = result.iloc[:, order] result.columns = columns if result is None: # grouper specific aggregations if self.grouper.nkeys > 1: # test_groupby_as_index_series_scalar gets here with 'not self.as_index' return self._python_agg_general(func, *args, **kwargs) elif args or kwargs: # test_pass_args_kwargs gets here (with and without as_index) # can't return early result = self._aggregate_frame(func, *args, **kwargs) elif self.axis == 1: # _aggregate_multiple_funcs does not allow self.axis == 1 # Note: axis == 1 precludes 'not self.as_index', see __init__ result = self._aggregate_frame(func) return result else: # try to treat as if we are passing a list gba = GroupByApply(self, [func], args=(), kwargs={}) try: result = gba.agg() except ValueError as err: if "no results" not in str(err): # raised directly by _aggregate_multiple_funcs raise result = self._aggregate_frame(func) else: sobj = self._selected_obj if isinstance(sobj, Series): # GH#35246 test_groupby_as_index_select_column_sum_empty_df result.columns = self._obj_with_exclusions.columns.copy() else: # Retain our column names result.columns._set_names( sobj.columns.names, level=list(range(sobj.columns.nlevels)) ) # select everything except for the last level, which is the one # containing the name of the function(s), see GH#32040 result.columns = result.columns.droplevel(-1) if not self.as_index: self._insert_inaxis_grouper_inplace(result) result.index = Index(range(len(result))) return result agg = aggregate def _iterate_slices(self) -> Iterable[Series]: obj = self._selected_obj if self.axis == 1: obj = obj.T if isinstance(obj, Series) and obj.name not in self.exclusions: # Occurs when doing DataFrameGroupBy(...)["X"] yield obj else: for label, values in obj.items(): if label in self.exclusions: continue yield values def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame: if self.grouper.nkeys != 1: raise AssertionError("Number of keys must be 1") obj = self._obj_with_exclusions result: dict[Hashable, NDFrame | np.ndarray] = {} if self.axis == 0: # test_pass_args_kwargs_duplicate_columns gets here with non-unique columns for name, data in self: fres = func(data, *args, **kwargs) result[name] = fres else: # we get here in a number of test_multilevel tests for name in self.indices: grp_df = self.get_group(name, obj=obj) fres = func(grp_df, *args, **kwargs) result[name] = fres result_index = self.grouper.result_index other_ax = obj.axes[1 - self.axis] out = self.obj._constructor(result, index=other_ax, columns=result_index) if self.axis == 0: out = out.T return out def _aggregate_item_by_item(self, func, *args, **kwargs) -> DataFrame: # only for axis==0 # tests that get here with non-unique cols: # test_resample_with_timedelta_yields_no_empty_groups, # test_resample_apply_product obj = self._obj_with_exclusions result: dict[int, NDFrame] = {} for i, (item, sgb) in enumerate(self._iterate_column_groupbys(obj)): result[i] = sgb.aggregate(func, *args, **kwargs) res_df = self.obj._constructor(result) res_df.columns = obj.columns return res_df def _wrap_applied_output( self, data: DataFrame, values: list, not_indexed_same: bool = False, override_group_keys: bool = False, ): if len(values) == 0: result = self.obj._constructor( index=self.grouper.result_index, columns=data.columns ) result = result.astype(data.dtypes, copy=False) return result # GH12824 first_not_none = next(com.not_none(*values), None) if first_not_none is None: # GH9684 - All values are None, return an empty frame. return self.obj._constructor() elif isinstance(first_not_none, DataFrame): return self._concat_objects( values, not_indexed_same=not_indexed_same, override_group_keys=override_group_keys, ) key_index = self.grouper.result_index if self.as_index else None if isinstance(first_not_none, (np.ndarray, Index)): # GH#1738: values is list of arrays of unequal lengths # fall through to the outer else clause # TODO: sure this is right? we used to do this # after raising AttributeError above return self.obj._constructor_sliced( values, index=key_index, name=self._selection ) elif not isinstance(first_not_none, Series): # values are not series or array-like but scalars # self._selection not passed through to Series as the # result should not take the name of original selection # of columns if self.as_index: return self.obj._constructor_sliced(values, index=key_index) else: result = self.obj._constructor(values, columns=[self._selection]) self._insert_inaxis_grouper_inplace(result) return result else: # values are Series return self._wrap_applied_output_series( values, not_indexed_same, first_not_none, key_index, override_group_keys, ) def _wrap_applied_output_series( self, values: list[Series], not_indexed_same: bool, first_not_none, key_index, override_group_keys: bool, ) -> DataFrame | Series: # this is to silence a DeprecationWarning # TODO(2.0): Remove when default dtype of empty Series is object kwargs = first_not_none._construct_axes_dict() backup = create_series_with_explicit_dtype(dtype_if_empty=object, **kwargs) values = [x if (x is not None) else backup for x in values] all_indexed_same = all_indexes_same(x.index for x in values) # GH3596 # provide a reduction (Frame -> Series) if groups are # unique if self.squeeze: applied_index = self._selected_obj._get_axis(self.axis) singular_series = len(values) == 1 and applied_index.nlevels == 1 if singular_series: # GH2893 # we have series in the values array, we want to # produce a series: # if any of the sub-series are not indexed the same # OR we don't have a multi-index and we have only a # single values return self._concat_objects( values, not_indexed_same=not_indexed_same, override_group_keys=override_group_keys, ) # still a series # path added as of GH 5545 elif all_indexed_same: from pandas.core.reshape.concat import concat return concat(values) if not all_indexed_same: # GH 8467 return self._concat_objects( values, not_indexed_same=True, override_group_keys=override_group_keys, ) # Combine values # vstack+constructor is faster than concat and handles MI-columns stacked_values = np.vstack([np.asarray(v) for v in values]) if self.axis == 0: index = key_index columns = first_not_none.index.copy() if columns.name is None: # GH6124 - propagate name of Series when it's consistent names = {v.name for v in values} if len(names) == 1: columns.name = list(names)[0] else: index = first_not_none.index columns = key_index stacked_values = stacked_values.T if stacked_values.dtype == object: # We'll have the DataFrame constructor do inference stacked_values = stacked_values.tolist() result = self.obj._constructor(stacked_values, index=index, columns=columns) if not self.as_index: self._insert_inaxis_grouper_inplace(result) return self._reindex_output(result) def _cython_transform( self, how: str, numeric_only: bool = True, axis: int = 0, **kwargs ) -> DataFrame: assert axis == 0 # handled by caller # TODO: no tests with self.ndim == 1 for DataFrameGroupBy # With self.axis == 0, we have multi-block tests # e.g. test_rank_min_int, test_cython_transform_frame # test_transform_numeric_ret # With self.axis == 1, _get_data_to_aggregate does a transpose # so we always have a single block. mgr: Manager2D = self._get_data_to_aggregate() if numeric_only: mgr = mgr.get_numeric_data(copy=False) def arr_func(bvalues: ArrayLike) -> ArrayLike: return self.grouper._cython_operation( "transform", bvalues, how, 1, **kwargs ) # We could use `mgr.apply` here and not have to set_axis, but # we would have to do shape gymnastics for ArrayManager compat res_mgr = mgr.grouped_reduce(arr_func, ignore_failures=True) res_mgr.set_axis(1, mgr.axes[1]) if len(res_mgr) < len(mgr): warn_dropping_nuisance_columns_deprecated(type(self), how) res_df = self.obj._constructor(res_mgr) if self.axis == 1: res_df = res_df.T return res_df def _transform_general(self, func, *args, **kwargs): from pandas.core.reshape.concat import concat applied = [] obj = self._obj_with_exclusions gen = self.grouper.get_iterator(obj, axis=self.axis) fast_path, slow_path = self._define_paths(func, *args, **kwargs) # Determine whether to use slow or fast path by evaluating on the first group. # Need to handle the case of an empty generator and process the result so that # it does not need to be computed again. try: name, group = next(gen) except StopIteration: pass else: object.__setattr__(group, "name", name) try: path, res = self._choose_path(fast_path, slow_path, group) except TypeError: return self._transform_item_by_item(obj, fast_path) except ValueError as err: msg = "transform must return a scalar value for each group" raise ValueError(msg) from err if group.size > 0: res = _wrap_transform_general_frame(self.obj, group, res) applied.append(res) # Compute and process with the remaining groups for name, group in gen: if group.size == 0: continue object.__setattr__(group, "name", name) res = path(group) res = _wrap_transform_general_frame(self.obj, group, res) applied.append(res) concat_index = obj.columns if self.axis == 0 else obj.index other_axis = 1 if self.axis == 0 else 0 # switches between 0 & 1 concatenated = concat(applied, axis=self.axis, verify_integrity=False) concatenated = concatenated.reindex(concat_index, axis=other_axis, copy=False) return self._set_result_index_ordered(concatenated) @Substitution(klass="DataFrame") @Appender(_transform_template) def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): return self._transform( func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs ) def _define_paths(self, func, *args, **kwargs): if isinstance(func, str): fast_path = lambda group: getattr(group, func)(*args, **kwargs) slow_path = lambda group: group.apply( lambda x: getattr(x, func)(*args, **kwargs), axis=self.axis ) else: fast_path = lambda group: func(group, *args, **kwargs) slow_path = lambda group: group.apply( lambda x: func(x, *args, **kwargs), axis=self.axis ) return fast_path, slow_path def _choose_path(self, fast_path: Callable, slow_path: Callable, group: DataFrame): path = slow_path res = slow_path(group) if self.ngroups == 1: # no need to evaluate multiple paths when only # a single group exists return path, res # if we make it here, test if we can use the fast path try: res_fast = fast_path(group) except AssertionError: raise # pragma: no cover except Exception: # GH#29631 For user-defined function, we can't predict what may be # raised; see test_transform.test_transform_fastpath_raises return path, res # verify fast path returns either: # a DataFrame with columns equal to group.columns # OR a Series with index equal to group.columns if isinstance(res_fast, DataFrame): if not res_fast.columns.equals(group.columns): return path, res elif isinstance(res_fast, Series): if not res_fast.index.equals(group.columns): return path, res else: return path, res if res_fast.equals(res): path = fast_path return path, res def _transform_item_by_item(self, obj: DataFrame, wrapper) -> DataFrame: # iterate through columns, see test_transform_exclude_nuisance # gets here with non-unique columns output = {} inds = [] for i, (colname, sgb) in enumerate(self._iterate_column_groupbys(obj)): try: output[i] = sgb.transform(wrapper) except TypeError: # e.g. trying to call nanmean with string values warn_dropping_nuisance_columns_deprecated(type(self), "transform") else: inds.append(i) if not output: raise TypeError("Transform function invalid for data types") columns = obj.columns.take(inds) result = self.obj._constructor(output, index=obj.index) result.columns = columns return result def filter(self, func, dropna=True, *args, **kwargs): """ Return a copy of a DataFrame excluding filtered elements. Elements from groups are filtered if they do not satisfy the boolean criterion specified by func. Parameters ---------- func : function Function to apply to each subframe. Should return True or False. dropna : Drop groups that do not pass the filter. True by default; If False, groups that evaluate False are filled with NaNs. Returns ------- filtered : DataFrame Notes ----- Each subframe is endowed the attribute 'name' in case you need to know which group you are working on. Functions that mutate the passed object can produce unexpected behavior or errors and are not supported. See :ref:`gotchas.udf-mutation` for more details. Examples -------- >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', ... 'foo', 'bar'], ... 'B' : [1, 2, 3, 4, 5, 6], ... 'C' : [2.0, 5., 8., 1., 2., 9.]}) >>> grouped = df.groupby('A') >>> grouped.filter(lambda x: x['B'].mean() > 3.) A B C 1 bar 2 5.0 3 bar 4 1.0 5 bar 6 9.0 """ indices = [] obj = self._selected_obj gen = self.grouper.get_iterator(obj, axis=self.axis) for name, group in gen: object.__setattr__(group, "name", name) res = func(group, *args, **kwargs) try: res = res.squeeze() except AttributeError: # allow e.g., scalars and frames to pass pass # interpret the result of the filter if is_bool(res) or (is_scalar(res) and isna(res)): if res and notna(res): indices.append(self._get_index(name)) else: # non scalars aren't allowed raise TypeError( f"filter function returned a {type(res).__name__}, " "but expected a scalar bool" ) return self._apply_filter(indices, dropna) def __getitem__(self, key) -> DataFrameGroupBy | SeriesGroupBy: if self.axis == 1: # GH 37725 raise ValueError("Cannot subset columns when using axis=1") # per GH 23566 if isinstance(key, tuple) and len(key) > 1: # if len == 1, then it becomes a SeriesGroupBy and this is actually # valid syntax, so don't raise warning warnings.warn( "Indexing with multiple keys (implicitly converted to a tuple " "of keys) will be deprecated, use a list instead.", FutureWarning, stacklevel=find_stack_level(), ) return super().__getitem__(key) def _gotitem(self, key, ndim: int, subset=None): """ sub-classes to define return a sliced object Parameters ---------- key : string / list of selections ndim : {1, 2} requested ndim of result subset : object, default None subset to act on """ if ndim == 2: if subset is None: subset = self.obj return DataFrameGroupBy( subset, self.grouper, axis=self.axis, level=self.level, grouper=self.grouper, exclusions=self.exclusions, selection=key, as_index=self.as_index, sort=self.sort, group_keys=self.group_keys, squeeze=self.squeeze, observed=self.observed, mutated=self.mutated, dropna=self.dropna, ) elif ndim == 1: if subset is None: subset = self.obj[key] return SeriesGroupBy( subset, level=self.level, grouper=self.grouper, selection=key, sort=self.sort, group_keys=self.group_keys, squeeze=self.squeeze, observed=self.observed, dropna=self.dropna, ) raise AssertionError("invalid ndim for _gotitem") def _get_data_to_aggregate(self) -> Manager2D: obj = self._obj_with_exclusions if self.axis == 1: return obj.T._mgr else: return obj._mgr def _insert_inaxis_grouper_inplace(self, result: DataFrame) -> None: # zip in reverse so we can always insert at loc 0 columns = result.columns for name, lev, in_axis in zip( reversed(self.grouper.names), reversed(self.grouper.get_group_levels()), reversed([grp.in_axis for grp in self.grouper.groupings]), ): # GH #28549 # When using .apply(-), name will be in columns already if in_axis and name not in columns: result.insert(0, name, lev) def _indexed_output_to_ndframe( self, output: Mapping[base.OutputKey, ArrayLike] ) -> DataFrame: """ Wrap the dict result of a GroupBy aggregation into a DataFrame. """ indexed_output = {key.position: val for key, val in output.items()} columns = Index([key.label for key in output]) columns._set_names(self._obj_with_exclusions._get_axis(1 - self.axis).names) result = self.obj._constructor(indexed_output) result.columns = columns return result def _wrap_agged_manager(self, mgr: Manager2D) -> DataFrame: if not self.as_index: # GH 41998 - empty mgr always gets index of length 0 rows = mgr.shape[1] if mgr.shape[0] > 0 else 0 index = Index(range(rows)) mgr.set_axis(1, index) result = self.obj._constructor(mgr) self._insert_inaxis_grouper_inplace(result) result = result._consolidate() else: index = self.grouper.result_index mgr.set_axis(1, index) result = self.obj._constructor(mgr) if self.axis == 1: result = result.T # Note: we only need to pass datetime=True in order to get numeric # values converted return self._reindex_output(result)._convert(datetime=True) def _iterate_column_groupbys(self, obj: DataFrame | Series): for i, colname in enumerate(obj.columns): yield colname, SeriesGroupBy( obj.iloc[:, i], selection=colname, grouper=self.grouper, exclusions=self.exclusions, observed=self.observed, ) def _apply_to_column_groupbys(self, func, obj: DataFrame | Series) -> DataFrame: from pandas.core.reshape.concat import concat columns = obj.columns results = [ func(col_groupby) for _, col_groupby in self._iterate_column_groupbys(obj) ] if not len(results): # concat would raise return DataFrame([], columns=columns, index=self.grouper.result_index) else: return concat(results, keys=columns, axis=1) def nunique(self, dropna: bool = True) -> DataFrame: """ Return DataFrame with counts of unique elements in each position. Parameters ---------- dropna : bool, default True Don't include NaN in the counts. Returns ------- nunique: DataFrame Examples -------- >>> df = pd.DataFrame({'id': ['spam', 'egg', 'egg', 'spam', ... 'ham', 'ham'], ... 'value1': [1, 5, 5, 2, 5, 5], ... 'value2': list('abbaxy')}) >>> df id value1 value2 0 spam 1 a 1 egg 5 b 2 egg 5 b 3 spam 2 a 4 ham 5 x 5 ham 5 y >>> df.groupby('id').nunique() value1 value2 id egg 1 1 ham 1 2 spam 2 1 Check for rows with the same id but conflicting values: >>> df.groupby('id').filter(lambda g: (g.nunique() > 1).any()) id value1 value2 0 spam 1 a 3 spam 2 a 4 ham 5 x 5 ham 5 y """ if self.axis != 0: # see test_groupby_crash_on_nunique return self._python_agg_general(lambda sgb: sgb.nunique(dropna)) obj = self._obj_with_exclusions results = self._apply_to_column_groupbys( lambda sgb: sgb.nunique(dropna), obj=obj ) if not self.as_index: results.index = Index(range(len(results))) self._insert_inaxis_grouper_inplace(results) return results @doc( _shared_docs["idxmax"], numeric_only_default="True for axis=0, False for axis=1", ) def idxmax(self, axis=0, skipna: bool = True, numeric_only: bool | None = None): axis = DataFrame._get_axis_number(axis) if numeric_only is None: numeric_only = None if axis == 0 else False def func(df): # NB: here we use numeric_only=None, in DataFrame it is False GH#38217 res = df._reduce( nanops.nanargmax, "argmax", axis=axis, skipna=skipna, numeric_only=numeric_only, ) indices = res._values index = df._get_axis(axis) result = [index[i] if i >= 0 else np.nan for i in indices] return df._constructor_sliced(result, index=res.index) func.__name__ = "idxmax" return self._python_apply_general(func, self._obj_with_exclusions) @doc( _shared_docs["idxmin"], numeric_only_default="True for axis=0, False for axis=1", ) def idxmin(self, axis=0, skipna: bool = True, numeric_only: bool | None = None): axis = DataFrame._get_axis_number(axis) if numeric_only is None: numeric_only = None if axis == 0 else False def func(df): # NB: here we use numeric_only=None, in DataFrame it is False GH#46560 res = df._reduce( nanops.nanargmin, "argmin", axis=axis, skipna=skipna, numeric_only=numeric_only, ) indices = res._values index = df._get_axis(axis) result = [index[i] if i >= 0 else np.nan for i in indices] return df._constructor_sliced(result, index=res.index) func.__name__ = "idxmin" return self._python_apply_general(func, self._obj_with_exclusions) boxplot = boxplot_frame_groupby def value_counts( self, subset: Sequence[Hashable] | None = None, normalize: bool = False, sort: bool = True, ascending: bool = False, dropna: bool = True, ) -> DataFrame | Series: """ Return a Series or DataFrame containing counts of unique rows. .. versionadded:: 1.4.0 Parameters ---------- subset : list-like, optional Columns to use when counting unique combinations. normalize : bool, default False Return proportions rather than frequencies. sort : bool, default True Sort by frequencies. ascending : bool, default False Sort in ascending order. dropna : bool, default True Don’t include counts of rows that contain NA values. Returns ------- Series or DataFrame Series if the groupby as_index is True, otherwise DataFrame. See Also -------- Series.value_counts: Equivalent method on Series. DataFrame.value_counts: Equivalent method on DataFrame. SeriesGroupBy.value_counts: Equivalent method on SeriesGroupBy. Notes ----- - If the groupby as_index is True then the returned Series will have a MultiIndex with one level per input column. - If the groupby as_index is False then the returned DataFrame will have an additional column with the value_counts. The column is labelled 'count' or 'proportion', depending on the ``normalize`` parameter. By default, rows that contain any NA values are omitted from the result. By default, the result will be in descending order so that the first element of each group is the most frequently-occurring row. Examples -------- >>> df = pd.DataFrame({ ... 'gender': ['male', 'male', 'female', 'male', 'female', 'male'], ... 'education': ['low', 'medium', 'high', 'low', 'high', 'low'], ... 'country': ['US', 'FR', 'US', 'FR', 'FR', 'FR'] ... }) >>> df gender education country 0 male low US 1 male medium FR 2 female high US 3 male low FR 4 female high FR 5 male low FR >>> df.groupby('gender').value_counts() gender education country female high FR 1 US 1 male low FR 2 US 1 medium FR 1 dtype: int64 >>> df.groupby('gender').value_counts(ascending=True) gender education country female high FR 1 US 1 male low US 1 medium FR 1 low FR 2 dtype: int64 >>> df.groupby('gender').value_counts(normalize=True) gender education country female high FR 0.50 US 0.50 male low FR 0.50 US 0.25 medium FR 0.25 dtype: float64 >>> df.groupby('gender', as_index=False).value_counts() gender education country count 0 female high FR 1 1 female high US 1 2 male low FR 2 3 male low US 1 4 male medium FR 1 >>> df.groupby('gender', as_index=False).value_counts(normalize=True) gender education country proportion 0 female high FR 0.50 1 female high US 0.50 2 male low FR 0.50 3 male low US 0.25 4 male medium FR 0.25 """ if self.axis == 1: raise NotImplementedError( "DataFrameGroupBy.value_counts only handles axis=0" ) with self._group_selection_context(): df = self.obj in_axis_names = { grouping.name for grouping in self.grouper.groupings if grouping.in_axis } if isinstance(self._selected_obj, Series): name = self._selected_obj.name keys = [] if name in in_axis_names else [self._selected_obj] else: keys = [ # Can't use .values because the column label needs to be preserved self._selected_obj.iloc[:, idx] for idx, name in enumerate(self._selected_obj.columns) if name not in in_axis_names ] if subset is not None: clashing = set(subset) & set(in_axis_names) if clashing: raise ValueError( f"Keys {clashing} in subset cannot be in " "the groupby column keys" ) groupings = list(self.grouper.groupings) for key in keys: grouper, _, _ = get_grouper( df, key=key, axis=self.axis, sort=self.sort, dropna=dropna, ) groupings += list(grouper.groupings) # Take the size of the overall columns gb = df.groupby( groupings, sort=self.sort, observed=self.observed, dropna=self.dropna, ) result_series = cast(Series, gb.size()) if normalize: # Normalize the results by dividing by the original group sizes. # We are guaranteed to have the first N levels be the # user-requested grouping. levels = list( range(len(self.grouper.groupings), result_series.index.nlevels) ) indexed_group_size = result_series.groupby( result_series.index.droplevel(levels), sort=self.sort, observed=self.observed, dropna=self.dropna, ).transform("sum") result_series /= indexed_group_size if sort: # Sort the values and then resort by the main grouping index_level = range(len(self.grouper.groupings)) result_series = result_series.sort_values( ascending=ascending ).sort_index(level=index_level, sort_remaining=False) result: Series | DataFrame if self.as_index: result = result_series else: # Convert to frame name = "proportion" if normalize else "count" index = result_series.index columns = com.fill_missing_names(index.names) if name in columns: raise ValueError( f"Column label '{name}' is duplicate of result column" ) result_series.name = name result_series.index = index.set_names(range(len(columns))) result_frame = result_series.reset_index() result_frame.columns = columns + [name] result = result_frame return result.__finalize__(self.obj, method="value_counts") def _wrap_transform_general_frame( obj: DataFrame, group: DataFrame, res: DataFrame | Series ) -> DataFrame: from pandas import concat if isinstance(res, Series): # we need to broadcast across the # other dimension; this will preserve dtypes # GH14457 if res.index.is_(obj.index): res_frame = concat([res] * len(group.columns), axis=1) res_frame.columns = group.columns res_frame.index = group.index else: res_frame = obj._constructor( np.tile(res.values, (len(group.index), 1)), columns=group.columns, index=group.index, ) assert isinstance(res_frame, DataFrame) return res_frame else: return res
34.204459
88
0.555833
from __future__ import annotations from collections import abc from functools import partial from textwrap import dedent from typing import ( Any, Callable, Hashable, Iterable, Mapping, NamedTuple, Sequence, TypeVar, Union, cast, ) import warnings import numpy as np from pandas._libs import ( Interval, reduction as libreduction, ) from pandas._typing import ( ArrayLike, Manager, Manager2D, SingleManager, ) from pandas.util._decorators import ( Appender, Substitution, doc, ) from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( ensure_int64, is_bool, is_categorical_dtype, is_dict_like, is_integer_dtype, is_interval_dtype, is_scalar, ) from pandas.core.dtypes.missing import ( isna, notna, ) from pandas.core import ( algorithms, nanops, ) from pandas.core.apply import ( GroupByApply, maybe_mangle_lambdas, reconstruct_func, validate_func_kwargs, ) from pandas.core.base import SpecificationError import pandas.core.common as com from pandas.core.construction import create_series_with_explicit_dtype from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame from pandas.core.groupby import base from pandas.core.groupby.groupby import ( GroupBy, _agg_template, _apply_docs, _transform_template, warn_dropping_nuisance_columns_deprecated, ) from pandas.core.groupby.grouper import get_grouper from pandas.core.indexes.api import ( Index, MultiIndex, all_indexes_same, ) from pandas.core.series import Series from pandas.core.shared_docs import _shared_docs from pandas.core.util.numba_ import maybe_use_numba from pandas.plotting import boxplot_frame_groupby AggScalar = Union[str, Callable[..., Any]] ScalarResult = TypeVar("ScalarResult") class NamedAgg(NamedTuple): column: Hashable aggfunc: AggScalar def generate_property(name: str, klass: type[DataFrame | Series]): def prop(self): return self._make_wrapper(name) parent_method = getattr(klass, name) prop.__doc__ = parent_method.__doc__ or "" prop.__name__ = name return property(prop) def pin_allowlisted_properties( klass: type[DataFrame | Series], allowlist: frozenset[str] ): def pinner(cls): for name in allowlist: if hasattr(cls, name): # in the base class continue prop = generate_property(name, klass) setattr(cls, name, prop) return cls return pinner @pin_allowlisted_properties(Series, base.series_apply_allowlist) class SeriesGroupBy(GroupBy[Series]): _apply_allowlist = base.series_apply_allowlist def _wrap_agged_manager(self, mgr: Manager) -> Series: if mgr.ndim == 1: mgr = cast(SingleManager, mgr) single = mgr else: mgr = cast(Manager2D, mgr) single = mgr.iget(0) ser = self.obj._constructor(single, name=self.obj.name) # NB: caller is responsible for setting ser.index return ser def _get_data_to_aggregate(self) -> SingleManager: ser = self._obj_with_exclusions single = ser._mgr return single def _iterate_slices(self) -> Iterable[Series]: yield self._selected_obj _agg_examples_doc = dedent( """ Examples -------- >>> s = pd.Series([1, 2, 3, 4]) >>> s 0 1 1 2 2 3 3 4 dtype: int64 >>> s.groupby([1, 1, 2, 2]).min() 1 1 2 3 dtype: int64 >>> s.groupby([1, 1, 2, 2]).agg('min') 1 1 2 3 dtype: int64 >>> s.groupby([1, 1, 2, 2]).agg(['min', 'max']) min max 1 1 2 2 3 4 The output column names can be controlled by passing the desired column names and aggregations as keyword arguments. >>> s.groupby([1, 1, 2, 2]).agg( ... minimum='min', ... maximum='max', ... ) minimum maximum 1 1 2 2 3 4 .. versionchanged:: 1.3.0 The resulting dtype will reflect the return value of the aggregating function. >>> s.groupby([1, 1, 2, 2]).agg(lambda x: x.astype(float).min()) 1 1.0 2 3.0 dtype: float64 """ ) @Appender( _apply_docs["template"].format( input="series", examples=_apply_docs["series_examples"] ) ) def apply(self, func, *args, **kwargs) -> Series: return super().apply(func, *args, **kwargs) @doc(_agg_template, examples=_agg_examples_doc, klass="Series") def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs): if maybe_use_numba(engine): with self._group_selection_context(): data = self._selected_obj result = self._aggregate_with_numba( data.to_frame(), func, *args, engine_kwargs=engine_kwargs, **kwargs ) index = self.grouper.result_index return self.obj._constructor(result.ravel(), index=index, name=data.name) relabeling = func is None columns = None if relabeling: columns, func = validate_func_kwargs(kwargs) kwargs = {} if isinstance(func, str): return getattr(self, func)(*args, **kwargs) elif isinstance(func, abc.Iterable): # Catch instances of lists / tuples # but not the class list / tuple itself. func = maybe_mangle_lambdas(func) ret = self._aggregate_multiple_funcs(func) if relabeling: # error: Incompatible types in assignment (expression has type # "Optional[List[str]]", variable has type "Index") ret.columns = columns # type: ignore[assignment] return ret else: cyfunc = com.get_cython_func(func) if cyfunc and not args and not kwargs: return getattr(self, cyfunc)() if self.grouper.nkeys > 1: return self._python_agg_general(func, *args, **kwargs) try: return self._python_agg_general(func, *args, **kwargs) except KeyError: # TODO: KeyError is raised in _python_agg_general, # see test_groupby.test_basic result = self._aggregate_named(func, *args, **kwargs) # result is a dict whose keys are the elements of result_index index = self.grouper.result_index return create_series_with_explicit_dtype( result, index=index, dtype_if_empty=object ) agg = aggregate def _aggregate_multiple_funcs(self, arg) -> DataFrame: if isinstance(arg, dict): # show the deprecation, but only if we # have not shown a higher level one # GH 15931 raise SpecificationError("nested renamer is not supported") elif any(isinstance(x, (tuple, list)) for x in arg): arg = [(x, x) if not isinstance(x, (tuple, list)) else x for x in arg] # indicated column order columns = next(zip(*arg)) else: # list of functions / function names columns = [] for f in arg: columns.append(com.get_callable_name(f) or f) arg = zip(columns, arg) results: dict[base.OutputKey, DataFrame | Series] = {} for idx, (name, func) in enumerate(arg): key = base.OutputKey(label=name, position=idx) results[key] = self.aggregate(func) if any(isinstance(x, DataFrame) for x in results.values()): from pandas import concat res_df = concat( results.values(), axis=1, keys=[key.label for key in results.keys()] ) return res_df indexed_output = {key.position: val for key, val in results.items()} output = self.obj._constructor_expanddim(indexed_output, index=None) output.columns = Index(key.label for key in results) output = self._reindex_output(output) return output def _indexed_output_to_ndframe( self, output: Mapping[base.OutputKey, ArrayLike] ) -> Series: assert len(output) == 1 values = next(iter(output.values())) result = self.obj._constructor(values) result.name = self.obj.name return result def _wrap_applied_output( self, data: Series, values: list[Any], not_indexed_same: bool = False, override_group_keys: bool = False, ) -> DataFrame | Series: if len(values) == 0: # GH #6265 return self.obj._constructor( [], name=self.obj.name, index=self.grouper.result_index, dtype=data.dtype, ) assert values is not None if isinstance(values[0], dict): # GH #823 #24880 index = self.grouper.result_index res_df = self.obj._constructor_expanddim(values, index=index) res_df = self._reindex_output(res_df) # if self.observed is False, # keep all-NaN rows created while re-indexing res_ser = res_df.stack(dropna=self.observed) res_ser.name = self.obj.name return res_ser elif isinstance(values[0], (Series, DataFrame)): result = self._concat_objects( values, not_indexed_same=not_indexed_same, override_group_keys=override_group_keys, ) result.name = self.obj.name return result else: # GH #6265 #24880 result = self.obj._constructor( data=values, index=self.grouper.result_index, name=self.obj.name ) return self._reindex_output(result) def _aggregate_named(self, func, *args, **kwargs): # Note: this is very similar to _aggregate_series_pure_python, # but that does not pin group.name result = {} initialized = False for name, group in self: object.__setattr__(group, "name", name) output = func(group, *args, **kwargs) output = libreduction.extract_result(output) if not initialized: # We only do this validation on the first iteration libreduction.check_result_array(output, group.dtype) initialized = True result[name] = output return result @Substitution(klass="Series") @Appender(_transform_template) def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): return self._transform( func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs ) def _cython_transform( self, how: str, numeric_only: bool = True, axis: int = 0, **kwargs ): assert axis == 0 # handled by caller obj = self._selected_obj try: result = self.grouper._cython_operation( "transform", obj._values, how, axis, **kwargs ) except NotImplementedError as err: raise TypeError(f"{how} is not supported for {obj.dtype} dtype") from err return obj._constructor(result, index=self.obj.index, name=obj.name) def _transform_general(self, func: Callable, *args, **kwargs) -> Series: assert callable(func) klass = type(self.obj) results = [] for name, group in self: # this setattr is needed for test_transform_lambda_with_datetimetz object.__setattr__(group, "name", name) res = func(group, *args, **kwargs) results.append(klass(res, index=group.index)) # check for empty "results" to avoid concat ValueError if results: from pandas.core.reshape.concat import concat concatenated = concat(results) result = self._set_result_index_ordered(concatenated) else: result = self.obj._constructor(dtype=np.float64) result.name = self.obj.name return result def filter(self, func, dropna: bool = True, *args, **kwargs): if isinstance(func, str): wrapper = lambda x: getattr(x, func)(*args, **kwargs) else: wrapper = lambda x: func(x, *args, **kwargs) # Interpret np.nan as False. def true_and_notna(x) -> bool: b = wrapper(x) return b and notna(b) try: indices = [ self._get_index(name) for name, group in self if true_and_notna(group) ] except (ValueError, TypeError) as err: raise TypeError("the filter must return a boolean result") from err filtered = self._apply_filter(indices, dropna) return filtered def nunique(self, dropna: bool = True) -> Series: ids, _, _ = self.grouper.group_info val = self.obj._values codes, _ = algorithms.factorize(val, sort=False) sorter = np.lexsort((codes, ids)) codes = codes[sorter] ids = ids[sorter] # group boundaries are where group ids change # unique observations are where sorted values change idx = np.r_[0, 1 + np.nonzero(ids[1:] != ids[:-1])[0]] inc = np.r_[1, codes[1:] != codes[:-1]] # 1st item of each group is a new unique observation mask = codes == -1 if dropna: inc[idx] = 1 inc[mask] = 0 else: inc[mask & np.r_[False, mask[:-1]]] = 0 inc[idx] = 1 out = np.add.reduceat(inc, idx).astype("int64", copy=False) if len(ids): # NaN/NaT group exists if the head of ids is -1, # so remove it from res and exclude its index from idx if ids[0] == -1: res = out[1:] idx = idx[np.flatnonzero(idx)] else: res = out else: res = out[1:] ri = self.grouper.result_index # we might have duplications among the bins if len(res) != len(ri): res, out = np.zeros(len(ri), dtype=out.dtype), res res[ids[idx]] = out result = self.obj._constructor(res, index=ri, name=self.obj.name) return self._reindex_output(result, fill_value=0) @doc(Series.describe) def describe(self, **kwargs): return super().describe(**kwargs) def value_counts( self, normalize: bool = False, sort: bool = True, ascending: bool = False, bins=None, dropna: bool = True, ): from pandas.core.reshape.merge import get_join_indexers from pandas.core.reshape.tile import cut ids, _, _ = self.grouper.group_info val = self.obj._values names = self.grouper.names + [self.obj.name] if is_categorical_dtype(val.dtype) or ( bins is not None and not np.iterable(bins) ): # scalar bins cannot be done at top level # in a backward compatible way # GH38672 relates to categorical dtype ser = self.apply( Series.value_counts, normalize=normalize, sort=sort, ascending=ascending, bins=bins, ) ser.index.names = names return ser # groupby removes null keys from groupings mask = ids != -1 ids, val = ids[mask], val[mask] if bins is None: lab, lev = algorithms.factorize(val, sort=True) llab = lambda lab, inc: lab[inc] else: # lab is a Categorical with categories an IntervalIndex lab = cut(Series(val), bins, include_lowest=True) # error: "ndarray" has no attribute "cat" lev = lab.cat.categories # type: ignore[attr-defined] # error: No overload variant of "take" of "_ArrayOrScalarCommon" matches # argument types "Any", "bool", "Union[Any, float]" lab = lev.take( # type: ignore[call-overload] # error: "ndarray" has no attribute "cat" lab.cat.codes, # type: ignore[attr-defined] allow_fill=True, # error: Item "ndarray" of "Union[ndarray, Index]" has no attribute # "_na_value" fill_value=lev._na_value, # type: ignore[union-attr] ) llab = lambda lab, inc: lab[inc]._multiindex.codes[-1] if is_interval_dtype(lab.dtype): # TODO: should we do this inside II? lab_interval = cast(Interval, lab) sorter = np.lexsort((lab_interval.left, lab_interval.right, ids)) else: sorter = np.lexsort((lab, ids)) ids, lab = ids[sorter], lab[sorter] # group boundaries are where group ids change idchanges = 1 + np.nonzero(ids[1:] != ids[:-1])[0] idx = np.r_[0, idchanges] if not len(ids): idx = idchanges # new values are where sorted labels change lchanges = llab(lab, slice(1, None)) != llab(lab, slice(None, -1)) inc = np.r_[True, lchanges] if not len(val): inc = lchanges inc[idx] = True # group boundaries are also new values out = np.diff(np.nonzero(np.r_[inc, True])[0]) # value counts # num. of times each group should be repeated rep = partial(np.repeat, repeats=np.add.reduceat(inc, idx)) # multi-index components codes = self.grouper.reconstructed_codes codes = [rep(level_codes) for level_codes in codes] + [llab(lab, inc)] # error: List item 0 has incompatible type "Union[ndarray[Any, Any], Index]"; # expected "Index" levels = [ping.group_index for ping in self.grouper.groupings] + [ lev # type: ignore[list-item] ] if dropna: mask = codes[-1] != -1 if mask.all(): dropna = False else: out, codes = out[mask], [level_codes[mask] for level_codes in codes] if normalize: out = out.astype("float") d = np.diff(np.r_[idx, len(ids)]) if dropna: m = ids[lab == -1] np.add.at(d, m, -1) acc = rep(d)[mask] else: acc = rep(d) out /= acc if sort and bins is None: cat = ids[inc][mask] if dropna else ids[inc] sorter = np.lexsort((out if ascending else -out, cat)) out, codes[-1] = out[sorter], codes[-1][sorter] if bins is not None: # for compat. with libgroupby.value_counts need to ensure every # bin is present at every index level, null filled with zeros diff = np.zeros(len(out), dtype="bool") for level_codes in codes[:-1]: diff |= np.r_[True, level_codes[1:] != level_codes[:-1]] ncat, nbin = diff.sum(), len(levels[-1]) left = [np.repeat(np.arange(ncat), nbin), np.tile(np.arange(nbin), ncat)] right = [diff.cumsum() - 1, codes[-1]] _, idx = get_join_indexers(left, right, sort=False, how="left") out = np.where(idx != -1, out[idx], 0) if sort: sorter = np.lexsort((out if ascending else -out, left[0])) out, left[-1] = out[sorter], left[-1][sorter] # build the multi-index w/ full levels def build_codes(lev_codes: np.ndarray) -> np.ndarray: return np.repeat(lev_codes[diff], nbin) codes = [build_codes(lev_codes) for lev_codes in codes[:-1]] codes.append(left[-1]) mi = MultiIndex(levels=levels, codes=codes, names=names, verify_integrity=False) if is_integer_dtype(out.dtype): out = ensure_int64(out) return self.obj._constructor(out, index=mi, name=self.obj.name) @doc(Series.nlargest) def nlargest(self, n: int = 5, keep: str = "first"): f = partial(Series.nlargest, n=n, keep=keep) data = self._obj_with_exclusions # Don't change behavior if result index happens to be the same, i.e. result = self._python_apply_general(f, data, not_indexed_same=True) return result @doc(Series.nsmallest) def nsmallest(self, n: int = 5, keep: str = "first"): f = partial(Series.nsmallest, n=n, keep=keep) data = self._obj_with_exclusions # already ordered and n >= all group sizes. result = self._python_apply_general(f, data, not_indexed_same=True) return result @pin_allowlisted_properties(DataFrame, base.dataframe_apply_allowlist) class DataFrameGroupBy(GroupBy[DataFrame]): _apply_allowlist = base.dataframe_apply_allowlist _agg_examples_doc = dedent( """ Examples -------- >>> df = pd.DataFrame( ... { ... "A": [1, 1, 2, 2], ... "B": [1, 2, 3, 4], ... "C": [0.362838, 0.227877, 1.267767, -0.562860], ... } ... ) >>> df A B C 0 1 1 0.362838 1 1 2 0.227877 2 2 3 1.267767 3 2 4 -0.562860 The aggregation is for each column. >>> df.groupby('A').agg('min') B C A 1 1 0.227877 2 3 -0.562860 Multiple aggregations >>> df.groupby('A').agg(['min', 'max']) B C min max min max A 1 1 2 0.227877 0.362838 2 3 4 -0.562860 1.267767 Select a column for aggregation >>> df.groupby('A').B.agg(['min', 'max']) min max A 1 1 2 2 3 4 Different aggregations per column >>> df.groupby('A').agg({'B': ['min', 'max'], 'C': 'sum'}) B C min max sum A 1 1 2 0.590715 2 3 4 0.704907 To control the output names with different aggregations per column, pandas supports "named aggregation" >>> df.groupby("A").agg( ... b_min=pd.NamedAgg(column="B", aggfunc="min"), ... c_sum=pd.NamedAgg(column="C", aggfunc="sum")) b_min c_sum A 1 1 0.590715 2 3 0.704907 - The keywords are the *output* column names - The values are tuples whose first element is the column to select and the second element is the aggregation to apply to that column. Pandas provides the ``pandas.NamedAgg`` namedtuple with the fields ``['column', 'aggfunc']`` to make it clearer what the arguments are. As usual, the aggregation can be a callable or a string alias. See :ref:`groupby.aggregate.named` for more. .. versionchanged:: 1.3.0 The resulting dtype will reflect the return value of the aggregating function. >>> df.groupby("A")[["B"]].agg(lambda x: x.astype(float).min()) B A 1 1.0 2 3.0 """ ) @doc(_agg_template, examples=_agg_examples_doc, klass="DataFrame") def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs): if maybe_use_numba(engine): with self._group_selection_context(): data = self._selected_obj result = self._aggregate_with_numba( data, func, *args, engine_kwargs=engine_kwargs, **kwargs ) index = self.grouper.result_index return self.obj._constructor(result, index=index, columns=data.columns) relabeling, func, columns, order = reconstruct_func(func, **kwargs) func = maybe_mangle_lambdas(func) op = GroupByApply(self, func, args, kwargs) result = op.agg() if not is_dict_like(func) and result is not None: return result elif relabeling and result is not None: # this should be the only (non-raising) case with relabeling # used reordered index of columns result = result.iloc[:, order] result.columns = columns if result is None: # grouper specific aggregations if self.grouper.nkeys > 1: # test_groupby_as_index_series_scalar gets here with 'not self.as_index' return self._python_agg_general(func, *args, **kwargs) elif args or kwargs: # test_pass_args_kwargs gets here (with and without as_index) # can't return early result = self._aggregate_frame(func, *args, **kwargs) elif self.axis == 1: result = self._aggregate_frame(func) return result else: gba = GroupByApply(self, [func], args=(), kwargs={}) try: result = gba.agg() except ValueError as err: if "no results" not in str(err): raise result = self._aggregate_frame(func) else: sobj = self._selected_obj if isinstance(sobj, Series): h_exclusions.columns.copy() else: result.columns._set_names( sobj.columns.names, level=list(range(sobj.columns.nlevels)) ) result.columns = result.columns.droplevel(-1) if not self.as_index: self._insert_inaxis_grouper_inplace(result) result.index = Index(range(len(result))) return result agg = aggregate def _iterate_slices(self) -> Iterable[Series]: obj = self._selected_obj if self.axis == 1: obj = obj.T if isinstance(obj, Series) and obj.name not in self.exclusions: yield obj else: for label, values in obj.items(): if label in self.exclusions: continue yield values def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame: if self.grouper.nkeys != 1: raise AssertionError("Number of keys must be 1") obj = self._obj_with_exclusions result: dict[Hashable, NDFrame | np.ndarray] = {} if self.axis == 0: for name, data in self: fres = func(data, *args, **kwargs) result[name] = fres else: for name in self.indices: grp_df = self.get_group(name, obj=obj) fres = func(grp_df, *args, **kwargs) result[name] = fres result_index = self.grouper.result_index other_ax = obj.axes[1 - self.axis] out = self.obj._constructor(result, index=other_ax, columns=result_index) if self.axis == 0: out = out.T return out def _aggregate_item_by_item(self, func, *args, **kwargs) -> DataFrame: obj = self._obj_with_exclusions result: dict[int, NDFrame] = {} for i, (item, sgb) in enumerate(self._iterate_column_groupbys(obj)): result[i] = sgb.aggregate(func, *args, **kwargs) res_df = self.obj._constructor(result) res_df.columns = obj.columns return res_df def _wrap_applied_output( self, data: DataFrame, values: list, not_indexed_same: bool = False, override_group_keys: bool = False, ): if len(values) == 0: result = self.obj._constructor( index=self.grouper.result_index, columns=data.columns ) result = result.astype(data.dtypes, copy=False) return result first_not_none = next(com.not_none(*values), None) if first_not_none is None: return self.obj._constructor() elif isinstance(first_not_none, DataFrame): return self._concat_objects( values, not_indexed_same=not_indexed_same, override_group_keys=override_group_keys, ) key_index = self.grouper.result_index if self.as_index else None if isinstance(first_not_none, (np.ndarray, Index)): return self.obj._constructor_sliced( values, index=key_index, name=self._selection ) elif not isinstance(first_not_none, Series): if self.as_index: return self.obj._constructor_sliced(values, index=key_index) else: result = self.obj._constructor(values, columns=[self._selection]) self._insert_inaxis_grouper_inplace(result) return result else: return self._wrap_applied_output_series( values, not_indexed_same, first_not_none, key_index, override_group_keys, ) def _wrap_applied_output_series( self, values: list[Series], not_indexed_same: bool, first_not_none, key_index, override_group_keys: bool, ) -> DataFrame | Series: kwargs = first_not_none._construct_axes_dict() backup = create_series_with_explicit_dtype(dtype_if_empty=object, **kwargs) values = [x if (x is not None) else backup for x in values] all_indexed_same = all_indexes_same(x.index for x in values) if self.squeeze: applied_index = self._selected_obj._get_axis(self.axis) singular_series = len(values) == 1 and applied_index.nlevels == 1 if singular_series: # single values return self._concat_objects( values, not_indexed_same=not_indexed_same, override_group_keys=override_group_keys, ) # still a series # path added as of GH 5545 elif all_indexed_same: from pandas.core.reshape.concat import concat return concat(values) if not all_indexed_same: # GH 8467 return self._concat_objects( values, not_indexed_same=True, override_group_keys=override_group_keys, ) # Combine values # vstack+constructor is faster than concat and handles MI-columns stacked_values = np.vstack([np.asarray(v) for v in values]) if self.axis == 0: index = key_index columns = first_not_none.index.copy() if columns.name is None: # GH6124 - propagate name of Series when it's consistent names = {v.name for v in values} if len(names) == 1: columns.name = list(names)[0] else: index = first_not_none.index columns = key_index stacked_values = stacked_values.T if stacked_values.dtype == object: stacked_values = stacked_values.tolist() result = self.obj._constructor(stacked_values, index=index, columns=columns) if not self.as_index: self._insert_inaxis_grouper_inplace(result) return self._reindex_output(result) def _cython_transform( self, how: str, numeric_only: bool = True, axis: int = 0, **kwargs ) -> DataFrame: assert axis == 0 # handled by caller # TODO: no tests with self.ndim == 1 for DataFrameGroupBy # With self.axis == 0, we have multi-block tests # e.g. test_rank_min_int, test_cython_transform_frame # test_transform_numeric_ret # With self.axis == 1, _get_data_to_aggregate does a transpose # so we always have a single block. mgr: Manager2D = self._get_data_to_aggregate() if numeric_only: mgr = mgr.get_numeric_data(copy=False) def arr_func(bvalues: ArrayLike) -> ArrayLike: return self.grouper._cython_operation( "transform", bvalues, how, 1, **kwargs ) # We could use `mgr.apply` here and not have to set_axis, but # we would have to do shape gymnastics for ArrayManager compat res_mgr = mgr.grouped_reduce(arr_func, ignore_failures=True) res_mgr.set_axis(1, mgr.axes[1]) if len(res_mgr) < len(mgr): warn_dropping_nuisance_columns_deprecated(type(self), how) res_df = self.obj._constructor(res_mgr) if self.axis == 1: res_df = res_df.T return res_df def _transform_general(self, func, *args, **kwargs): from pandas.core.reshape.concat import concat applied = [] obj = self._obj_with_exclusions gen = self.grouper.get_iterator(obj, axis=self.axis) fast_path, slow_path = self._define_paths(func, *args, **kwargs) # Determine whether to use slow or fast path by evaluating on the first group. # Need to handle the case of an empty generator and process the result so that # it does not need to be computed again. try: name, group = next(gen) except StopIteration: pass else: object.__setattr__(group, "name", name) try: path, res = self._choose_path(fast_path, slow_path, group) except TypeError: return self._transform_item_by_item(obj, fast_path) except ValueError as err: msg = "transform must return a scalar value for each group" raise ValueError(msg) from err if group.size > 0: res = _wrap_transform_general_frame(self.obj, group, res) applied.append(res) # Compute and process with the remaining groups for name, group in gen: if group.size == 0: continue object.__setattr__(group, "name", name) res = path(group) res = _wrap_transform_general_frame(self.obj, group, res) applied.append(res) concat_index = obj.columns if self.axis == 0 else obj.index other_axis = 1 if self.axis == 0 else 0 # switches between 0 & 1 concatenated = concat(applied, axis=self.axis, verify_integrity=False) concatenated = concatenated.reindex(concat_index, axis=other_axis, copy=False) return self._set_result_index_ordered(concatenated) @Substitution(klass="DataFrame") @Appender(_transform_template) def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): return self._transform( func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs ) def _define_paths(self, func, *args, **kwargs): if isinstance(func, str): fast_path = lambda group: getattr(group, func)(*args, **kwargs) slow_path = lambda group: group.apply( lambda x: getattr(x, func)(*args, **kwargs), axis=self.axis ) else: fast_path = lambda group: func(group, *args, **kwargs) slow_path = lambda group: group.apply( lambda x: func(x, *args, **kwargs), axis=self.axis ) return fast_path, slow_path def _choose_path(self, fast_path: Callable, slow_path: Callable, group: DataFrame): path = slow_path res = slow_path(group) if self.ngroups == 1: # no need to evaluate multiple paths when only # a single group exists return path, res # if we make it here, test if we can use the fast path try: res_fast = fast_path(group) except AssertionError: raise # pragma: no cover except Exception: # GH#29631 For user-defined function, we can't predict what may be return path, res if isinstance(res_fast, DataFrame): if not res_fast.columns.equals(group.columns): return path, res elif isinstance(res_fast, Series): if not res_fast.index.equals(group.columns): return path, res else: return path, res if res_fast.equals(res): path = fast_path return path, res def _transform_item_by_item(self, obj: DataFrame, wrapper) -> DataFrame: output = {} inds = [] for i, (colname, sgb) in enumerate(self._iterate_column_groupbys(obj)): try: output[i] = sgb.transform(wrapper) except TypeError: warn_dropping_nuisance_columns_deprecated(type(self), "transform") else: inds.append(i) if not output: raise TypeError("Transform function invalid for data types") columns = obj.columns.take(inds) result = self.obj._constructor(output, index=obj.index) result.columns = columns return result def filter(self, func, dropna=True, *args, **kwargs): indices = [] obj = self._selected_obj gen = self.grouper.get_iterator(obj, axis=self.axis) for name, group in gen: object.__setattr__(group, "name", name) res = func(group, *args, **kwargs) try: res = res.squeeze() except AttributeError: pass if is_bool(res) or (is_scalar(res) and isna(res)): if res and notna(res): indices.append(self._get_index(name)) else: raise TypeError( f"filter function returned a {type(res).__name__}, " "but expected a scalar bool" ) return self._apply_filter(indices, dropna) def __getitem__(self, key) -> DataFrameGroupBy | SeriesGroupBy: if self.axis == 1: # GH 37725 raise ValueError("Cannot subset columns when using axis=1") # per GH 23566 if isinstance(key, tuple) and len(key) > 1: # if len == 1, then it becomes a SeriesGroupBy and this is actually # valid syntax, so don't raise warning warnings.warn( "Indexing with multiple keys (implicitly converted to a tuple " "of keys) will be deprecated, use a list instead.", FutureWarning, stacklevel=find_stack_level(), ) return super().__getitem__(key) def _gotitem(self, key, ndim: int, subset=None): if ndim == 2: if subset is None: subset = self.obj return DataFrameGroupBy( subset, self.grouper, axis=self.axis, level=self.level, grouper=self.grouper, exclusions=self.exclusions, selection=key, as_index=self.as_index, sort=self.sort, group_keys=self.group_keys, squeeze=self.squeeze, observed=self.observed, mutated=self.mutated, dropna=self.dropna, ) elif ndim == 1: if subset is None: subset = self.obj[key] return SeriesGroupBy( subset, level=self.level, grouper=self.grouper, selection=key, sort=self.sort, group_keys=self.group_keys, squeeze=self.squeeze, observed=self.observed, dropna=self.dropna, ) raise AssertionError("invalid ndim for _gotitem") def _get_data_to_aggregate(self) -> Manager2D: obj = self._obj_with_exclusions if self.axis == 1: return obj.T._mgr else: return obj._mgr def _insert_inaxis_grouper_inplace(self, result: DataFrame) -> None: columns = result.columns for name, lev, in_axis in zip( reversed(self.grouper.names), reversed(self.grouper.get_group_levels()), reversed([grp.in_axis for grp in self.grouper.groupings]), ): if in_axis and name not in columns: result.insert(0, name, lev) def _indexed_output_to_ndframe( self, output: Mapping[base.OutputKey, ArrayLike] ) -> DataFrame: indexed_output = {key.position: val for key, val in output.items()} columns = Index([key.label for key in output]) columns._set_names(self._obj_with_exclusions._get_axis(1 - self.axis).names) result = self.obj._constructor(indexed_output) result.columns = columns return result def _wrap_agged_manager(self, mgr: Manager2D) -> DataFrame: if not self.as_index: rows = mgr.shape[1] if mgr.shape[0] > 0 else 0 index = Index(range(rows)) mgr.set_axis(1, index) result = self.obj._constructor(mgr) self._insert_inaxis_grouper_inplace(result) result = result._consolidate() else: index = self.grouper.result_index mgr.set_axis(1, index) result = self.obj._constructor(mgr) if self.axis == 1: result = result.T return self._reindex_output(result)._convert(datetime=True) def _iterate_column_groupbys(self, obj: DataFrame | Series): for i, colname in enumerate(obj.columns): yield colname, SeriesGroupBy( obj.iloc[:, i], selection=colname, grouper=self.grouper, exclusions=self.exclusions, observed=self.observed, ) def _apply_to_column_groupbys(self, func, obj: DataFrame | Series) -> DataFrame: from pandas.core.reshape.concat import concat columns = obj.columns results = [ func(col_groupby) for _, col_groupby in self._iterate_column_groupbys(obj) ] if not len(results): return DataFrame([], columns=columns, index=self.grouper.result_index) else: return concat(results, keys=columns, axis=1) def nunique(self, dropna: bool = True) -> DataFrame: if self.axis != 0: return self._python_agg_general(lambda sgb: sgb.nunique(dropna)) obj = self._obj_with_exclusions results = self._apply_to_column_groupbys( lambda sgb: sgb.nunique(dropna), obj=obj ) if not self.as_index: results.index = Index(range(len(results))) self._insert_inaxis_grouper_inplace(results) return results @doc( _shared_docs["idxmax"], numeric_only_default="True for axis=0, False for axis=1", ) def idxmax(self, axis=0, skipna: bool = True, numeric_only: bool | None = None): axis = DataFrame._get_axis_number(axis) if numeric_only is None: numeric_only = None if axis == 0 else False def func(df): res = df._reduce( nanops.nanargmax, "argmax", axis=axis, skipna=skipna, numeric_only=numeric_only, ) indices = res._values index = df._get_axis(axis) result = [index[i] if i >= 0 else np.nan for i in indices] return df._constructor_sliced(result, index=res.index) func.__name__ = "idxmax" return self._python_apply_general(func, self._obj_with_exclusions) @doc( _shared_docs["idxmin"], numeric_only_default="True for axis=0, False for axis=1", ) def idxmin(self, axis=0, skipna: bool = True, numeric_only: bool | None = None): axis = DataFrame._get_axis_number(axis) if numeric_only is None: numeric_only = None if axis == 0 else False def func(df): res = df._reduce( nanops.nanargmin, "argmin", axis=axis, skipna=skipna, numeric_only=numeric_only, ) indices = res._values index = df._get_axis(axis) result = [index[i] if i >= 0 else np.nan for i in indices] return df._constructor_sliced(result, index=res.index) func.__name__ = "idxmin" return self._python_apply_general(func, self._obj_with_exclusions) boxplot = boxplot_frame_groupby def value_counts( self, subset: Sequence[Hashable] | None = None, normalize: bool = False, sort: bool = True, ascending: bool = False, dropna: bool = True, ) -> DataFrame | Series: if self.axis == 1: raise NotImplementedError( "DataFrameGroupBy.value_counts only handles axis=0" ) with self._group_selection_context(): df = self.obj in_axis_names = { grouping.name for grouping in self.grouper.groupings if grouping.in_axis } if isinstance(self._selected_obj, Series): name = self._selected_obj.name keys = [] if name in in_axis_names else [self._selected_obj] else: keys = [ self._selected_obj.iloc[:, idx] for idx, name in enumerate(self._selected_obj.columns) if name not in in_axis_names ] if subset is not None: clashing = set(subset) & set(in_axis_names) if clashing: raise ValueError( f"Keys {clashing} in subset cannot be in " "the groupby column keys" ) groupings = list(self.grouper.groupings) for key in keys: grouper, _, _ = get_grouper( df, key=key, axis=self.axis, sort=self.sort, dropna=dropna, ) groupings += list(grouper.groupings) # Take the size of the overall columns gb = df.groupby( groupings, sort=self.sort, observed=self.observed, dropna=self.dropna, ) result_series = cast(Series, gb.size()) if normalize: # Normalize the results by dividing by the original group sizes. # We are guaranteed to have the first N levels be the # user-requested grouping. levels = list( range(len(self.grouper.groupings), result_series.index.nlevels) ) indexed_group_size = result_series.groupby( result_series.index.droplevel(levels), sort=self.sort, observed=self.observed, dropna=self.dropna, ).transform("sum") result_series /= indexed_group_size if sort: # Sort the values and then resort by the main grouping index_level = range(len(self.grouper.groupings)) result_series = result_series.sort_values( ascending=ascending ).sort_index(level=index_level, sort_remaining=False) result: Series | DataFrame if self.as_index: result = result_series else: # Convert to frame name = "proportion" if normalize else "count" index = result_series.index columns = com.fill_missing_names(index.names) if name in columns: raise ValueError( f"Column label '{name}' is duplicate of result column" ) result_series.name = name result_series.index = index.set_names(range(len(columns))) result_frame = result_series.reset_index() result_frame.columns = columns + [name] result = result_frame return result.__finalize__(self.obj, method="value_counts") def _wrap_transform_general_frame( obj: DataFrame, group: DataFrame, res: DataFrame | Series ) -> DataFrame: from pandas import concat if isinstance(res, Series): # we need to broadcast across the # other dimension; this will preserve dtypes # GH14457 if res.index.is_(obj.index): res_frame = concat([res] * len(group.columns), axis=1) res_frame.columns = group.columns res_frame.index = group.index else: res_frame = obj._constructor( np.tile(res.values, (len(group.index), 1)), columns=group.columns, index=group.index, ) assert isinstance(res_frame, DataFrame) return res_frame else: return res
true
true
f725aeade897e373631ced4d97f1f6a440b377d9
1,600
py
Python
utils/runner/optimizer/builder.py
UESTC-Liuxin/CVMI_Sementic_Segmentation
dc5bf6e940cf6961ef65abb6e7ec372f29d55249
[ "Apache-2.0" ]
null
null
null
utils/runner/optimizer/builder.py
UESTC-Liuxin/CVMI_Sementic_Segmentation
dc5bf6e940cf6961ef65abb6e7ec372f29d55249
[ "Apache-2.0" ]
null
null
null
utils/runner/optimizer/builder.py
UESTC-Liuxin/CVMI_Sementic_Segmentation
dc5bf6e940cf6961ef65abb6e7ec372f29d55249
[ "Apache-2.0" ]
null
null
null
''' Author: Liu Xin Date: 2021-11-21 18:10:58 LastEditors: Liu Xin LastEditTime: 2021-11-21 21:38:30 Description: file content FilePath: /CVMI_Sementic_Segmentation/utils/runner/optimizer/builder.py ''' import copy import inspect import torch from utils.registry import Registry, build OPTIMIZERS = Registry('optimizer') OPTIMIZER_BUILDERS = Registry('optimizer builder') def register_torch_optimizers(): """ @description : 通过扫描torvh.optim文件,获取torch实现的优化器对象 @param : @Returns : """ torch_optimizers = [] for module_name in dir(torch.optim): if module_name.startswith('__'): continue _optim = getattr(torch.optim, module_name) if inspect.isclass(_optim) and issubclass(_optim, torch.optim.Optimizer): OPTIMIZERS.register_module(_optim.__name__)(_optim) torch_optimizers.append(module_name) return torch_optimizers TORCH_OPTIMIZERS = register_torch_optimizers() def build_optimizer_constructor(cfg): return build(cfg, OPTIMIZER_BUILDERS) def build_optimizer(model, cfg): optimizer_cfg = copy.deepcopy(cfg) constructor_type = optimizer_cfg.pop('constructor', 'DefaultOptimizerConstructor') paramwise_cfg = optimizer_cfg.pop('paramwise_cfg', None) optim_constructor = build_optimizer_constructor( dict( name=constructor_type, optimizer_cfg=optimizer_cfg, paramwise_cfg=paramwise_cfg)) optimizer = optim_constructor(model) return optimizer
30.188679
73
0.683125
import copy import inspect import torch from utils.registry import Registry, build OPTIMIZERS = Registry('optimizer') OPTIMIZER_BUILDERS = Registry('optimizer builder') def register_torch_optimizers(): torch_optimizers = [] for module_name in dir(torch.optim): if module_name.startswith('__'): continue _optim = getattr(torch.optim, module_name) if inspect.isclass(_optim) and issubclass(_optim, torch.optim.Optimizer): OPTIMIZERS.register_module(_optim.__name__)(_optim) torch_optimizers.append(module_name) return torch_optimizers TORCH_OPTIMIZERS = register_torch_optimizers() def build_optimizer_constructor(cfg): return build(cfg, OPTIMIZER_BUILDERS) def build_optimizer(model, cfg): optimizer_cfg = copy.deepcopy(cfg) constructor_type = optimizer_cfg.pop('constructor', 'DefaultOptimizerConstructor') paramwise_cfg = optimizer_cfg.pop('paramwise_cfg', None) optim_constructor = build_optimizer_constructor( dict( name=constructor_type, optimizer_cfg=optimizer_cfg, paramwise_cfg=paramwise_cfg)) optimizer = optim_constructor(model) return optimizer
true
true
f725afde370dd3d08133a4a847cf11682d4bc65e
30
py
Python
py_yahoo/__init__.py
satheshrgs/py_yahoo
c18d680a9c75bb28364b95ada8b4dead0302d6ed
[ "MIT" ]
null
null
null
py_yahoo/__init__.py
satheshrgs/py_yahoo
c18d680a9c75bb28364b95ada8b4dead0302d6ed
[ "MIT" ]
null
null
null
py_yahoo/__init__.py
satheshrgs/py_yahoo
c18d680a9c75bb28364b95ada8b4dead0302d6ed
[ "MIT" ]
null
null
null
from .py_yahoo import YWeather
30
30
0.866667
from .py_yahoo import YWeather
true
true
f725b02ef1848fb30f10583d1d0ba4ed093eebfa
878
py
Python
examples/demo1/main.py
Layto888/laylib-1.0.1
c7317c29659a476adf6e90eb729b09ce4c49e219
[ "MIT" ]
1
2018-08-04T14:44:42.000Z
2018-08-04T14:44:42.000Z
examples/demo1/main.py
Layto888/laylib-1.0
c7317c29659a476adf6e90eb729b09ce4c49e219
[ "MIT" ]
null
null
null
examples/demo1/main.py
Layto888/laylib-1.0
c7317c29659a476adf6e90eb729b09ce4c49e219
[ "MIT" ]
null
null
null
""" Demo 01 Made with python and pygame to test and improve the laylib-pygame framework for fast game prototyping. ---- Author: Amardjia Amine Date: 20/10/18 Github: --- - This demo shows how the Resources manager loads and separates the different data and their associated variables. All resources are showed in the terminal after running your program. """ from laylib import Environment from engine import Engine import sys def main(): # init global environment demo = Environment( 800, # width 600, # height False, # full screen '2D Demo' # window title ) # load resources, set the game demo.load_complete(Engine(), '../data') # play demo.gInstance.main_loop() # quit the game demo.destroy() if __name__ == "__main__": sys.exit(main())
22.512821
75
0.632118
from laylib import Environment from engine import Engine import sys def main(): demo = Environment( 800, 600, False, '2D Demo' ) demo.load_complete(Engine(), '../data') demo.gInstance.main_loop() demo.destroy() if __name__ == "__main__": sys.exit(main())
true
true
f725b0a65f050af516439f7b25d526190cc56ff4
15,585
py
Python
mpunet/callbacks/callbacks.py
sandeepsinghsengar/MPUNet2Plus
fd97800cd349ee47d2c9cce1851a332dcbcb047c
[ "MIT" ]
156
2018-12-19T19:21:30.000Z
2022-03-10T13:14:52.000Z
mpunet/callbacks/callbacks.py
sandeepsinghsengar/MPUNet2Plus
fd97800cd349ee47d2c9cce1851a332dcbcb047c
[ "MIT" ]
25
2019-07-30T07:45:26.000Z
2022-02-10T00:38:31.000Z
mpunet/callbacks/callbacks.py
sandeepsinghsengar/MPUNet2Plus
fd97800cd349ee47d2c9cce1851a332dcbcb047c
[ "MIT" ]
33
2019-01-26T16:34:50.000Z
2022-02-20T13:48:44.000Z
import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import tensorflow as tf import psutil import numpy as np import os from tensorflow.keras.callbacks import Callback from datetime import datetime from mpunet.logging import ScreenLogger from mpunet.utils.plotting import (imshow_with_label_overlay, imshow, plot_all_training_curves) class DividerLine(Callback): """ Simply prints a line to screen after each epoch """ def __init__(self, logger=None): """ Args: logger: An instance of a MultiPlanar Logger that prints to screen and/or file """ super().__init__() self.logger = logger or ScreenLogger() def on_epoch_end(self, epoch, logs=None): self.logger("-"*45 + "\n") class LearningCurve(Callback): """ On epoch end this callback looks for all csv files matching the 'csv_regex' regex within the dir 'out_dir' and attempts to create a learning curve for each file that will be saved to 'out_dir'. Note: Failure to plot a learning curve based on a given csv file will is handled in the plot_all_training_curves function and will not cause the LearningCurve callback to raise an exception. """ def __init__(self, log_dir="logs", out_dir="logs", fname="curve.png", csv_regex="*training.csv", logger=None, **plot_kwargs): """ Args: log_dir: Relative path from the out_dir: fname: csv_regex: logger: """ super().__init__() out_dir = os.path.abspath(out_dir) if not os.path.exists(out_dir): os.makedirs(out_dir) self.csv_regex = os.path.join(os.path.abspath(log_dir), csv_regex) self.save_path = os.path.join(out_dir, fname) self.logger = logger or ScreenLogger() self.plot_kwargs = plot_kwargs def on_epoch_end(self, epoch, logs={}): plot_all_training_curves(self.csv_regex, self.save_path, logy=True, raise_error=False, logger=self.logger, **self.plot_kwargs) class MemoryConsumption(Callback): def __init__(self, max_gib=None, round_=2, logger=None): self.max_gib = max_gib self.logger = logger self.round_ = round_ def on_epoch_end(self, epoch, logs={}): process = psutil.Process(os.getpid()) mem_bytes = process.memory_info().rss mem_gib = round(mem_bytes / (1024**3), self.round_) logs['memory_usage_gib'] = mem_gib if self.max_gib and mem_gib >= self.max_gib: self.warn("Stopping training from callback 'MemoryConsumption'! " "Total memory consumption of {} GiB exceeds limitation" " (self.max_gib = {}) ".format(mem_gib, self.max_gib)) self.model.stop_training = True class DelayedCallback(object): """ Callback wrapper that delays the functionality of another callback by N number of epochs. """ def __init__(self, callback, start_from=0, logger=None): """ Args: callback: A tf.keras callback start_from: Delay the activity of 'callback' until this epoch 'start_from' logger: An instance of a MultiPlanar Logger that prints to screen and/or file """ self.logger = logger or ScreenLogger() self.callback = callback self.start_from = start_from def __getattr__(self, item): return getattr(self.callback, item) def on_epoch_end(self, epoch, logs=None): if epoch >= self.start_from-1: self.callback.on_epoch_end(epoch, logs=logs) else: self.logger("[%s] Not active at epoch %i - will be at %i" % (self.callback.__class__.__name__, epoch+1, self.start_from)) class TrainTimer(Callback): """ Appends train timing information to the log. If called prior to tf.keras.callbacks.CSVLogger this information will be written to disk. """ def __init__(self, logger=None, max_minutes=None, verbose=1): super().__init__() self.logger = logger or ScreenLogger() self.max_minutes = int(max_minutes) if max_minutes else None self.verbose = bool(verbose) # Timing attributes self.train_begin_time = None self.prev_epoch_time = None def on_train_begin(self, logs=None): self.train_begin_time = datetime.now() def on_epoch_begin(self, epoch, logs=None): self.prev_epoch_time = datetime.now() def on_epoch_end(self, epoch, logs=None): # Compute epoch execution time end_time = datetime.now() epoch_time = end_time - self.prev_epoch_time train_time = end_time - self.train_begin_time # Update attributes self.prev_epoch_time = end_time # Add to logs train_hours = round(train_time.total_seconds() / 3600, 4) epoch_minutes = round(epoch_time.total_seconds() / 60, 4) logs["epoch_minutes"] = epoch_minutes logs["train_hours"] = train_hours if self.verbose: self.logger("[TrainTimer] Epoch time: %.2f minutes " "- Total train time: %.2f hours" % (epoch_minutes, train_hours)) if self.max_minutes and train_hours*60 > self.max_minutes: self.logger("Stopping training. Training ran for {} minutes, " "max_minutes of {} was specified on the TrainTimer " "callback.".format(train_hours*60, self.max_minutes)) self.model.stop_training = True class FGBatchBalancer(Callback): """ mpunet callback. Sets the forced FG fraction in a batch at each epoch to 1-recall over the validation data at the previous epoch """ def __init__(self, train_data, val_data=None, logger=None): """ Args: train_data: A mpunet.sequence object representing the training data val_data: A mpunet.sequence object representing the validation data logger: An instance of a MultiPlanar Logger that prints to screen and/or file """ super().__init__() self.data = (("train", train_data), ("val", val_data)) self.logger = logger or ScreenLogger() self.active = True def on_epoch_end(self, epoch, logs=None): if not self.active: return None recall = logs.get("val_recall") if recall is None: self.logger("[FGBatchBalancer] No val_recall in logs. " "Disabling callback. " "Did you put this callback before the validation " "callback?") self.active = False else: # Always at least 1 image slice fraction = max(0.01, 1 - recall) for name, data in self.data: if data is not None: data.fg_batch_fraction = fraction self.logger("[FGBatchBalancer] Setting FG fraction for %s " "to: %.4f - Now %s/%s" % (name, fraction, data.n_fg_slices, data.batch_size)) class MeanReduceLogArrays(Callback): """ On epoch end, goes through the log and replaces any array entries with their mean value. """ def __init__(self): super().__init__() def on_epoch_end(self, epoch, logs={}): for key, value in logs.items(): if isinstance(value, (np.ndarray, list)): logs[key] = np.mean(value) class PrintLayerWeights(Callback): """ Print the weights of a specified layer every some epoch or batch. """ def __init__(self, layer, every=10, first=10, per_epoch=False, logger=None): """ Args: layer: A tf.keras layer every: Print the weights every 'every' batch or epoch if per_epoch=True first: Print the first 'first' elements of each weight matrix per_epoch: Print after 'every' epoch instead of batch logger: An instance of a MultiPlanar Logger that prints to screen and/or file """ super().__init__() if isinstance(layer, int): self.layer = self.model.layers[layer] else: self.layer = layer self.first = first self.every = every self.logger = logger or ScreenLogger() self.per_epoch = per_epoch if per_epoch: # Apply on every epoch instead of per batches self.on_epoch_begin = self.on_batch_begin self.on_batch_begin = lambda *args, **kwargs: None self.log() def log(self): self.logger("PrintLayerWeights Callback") self.logger("Layer: ", self.layer) self.logger("Every: ", self.every) self.logger("First: ", self.first) self.logger("Per epoch: ", self.per_epoch) def on_batch_begin(self, batch, logs=None): if batch % self.every: return weights = self.layer.get_weights() self.logger("Weights for layer '%s'" % self.layer) self.logger("Weights:\n%s" % weights[0].ravel()[:self.first]) try: self.logger("Baises:\n%s" % weights[1].ravel()[:self.first]) except IndexError: pass class SaveOutputAs2DImage(Callback): """ Save random 2D slices from the output of a given layer during training. """ def __init__(self, layer, sequence, model, out_dir, every=10, logger=None): """ Args: layer: A tf.keras layer sequence: A MultiPlanar.sequence object from which batches are sampled and pushed through the graph to output of layer model: A tf.keras model object out_dir: Path to directory (existing or non-existing) in which images will be stored every: Perform this operation every 'every' batches """ super().__init__() self.every = every self.seq = sequence self.layer = layer self.epoch = None self.model = model self.logger = logger or ScreenLogger() self.out_dir = out_dir if not os.path.exists(out_dir): os.makedirs(self.out_dir) self.log() def log(self): self.logger("Save Output as 2D Image Callback") self.logger("Layer: ", self.layer) self.logger("Every: ", self.every) def on_epoch_begin(self, epoch, logs=None): self.epoch = epoch def on_batch_end(self, batch, logs=None): if batch % self.every: return # Get output of layer self.model.predict_on_batch() sess = tf.keras.backend.get_session() X, _, _ = self.seq[0] outs = sess.run([self.layer.output], feed_dict={self.model.input: X})[0] if isinstance(outs, list): outs = outs[0] for i, (model_in, layer_out) in enumerate(zip(X, outs)): fig = plt.figure(figsize=(12, 6)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) # Plot model input and layer outputs on each ax chl1, axis, slice = imshow(ax1, model_in) chl2, _, _ = imshow(ax2, layer_out, axis=axis, slice=slice) # Set labels and save figure ax1.set_title("Model input - Channel %i - Axis %i - Slice %i" % (chl1, axis,slice), size=22) ax2.set_title("Layer output - Channel %i - Axis %i - Slice %i" % (chl2, axis, slice), size=22) fig.tight_layout() fig.savefig(os.path.join(self.out_dir, "epoch_%i_batch_%i_im_%i" % (self.epoch, batch, i))) plt.close(fig) class SavePredictionImages(Callback): """ Save images after each epoch of training of the model on a batch of training and a batch of validation data sampled from sequence objects. Saves the input image with ground truth overlay as well as the predicted label masks. """ def __init__(self, train_data, val_data, outdir='images'): """ Args: train_data: A mpunet.sequence object from which training data can be sampled via the __getitem__ method. val_data: A mpunet.sequence object from which validation data can be sampled via the __getitem__ method. outdir: Path to directory (existing or non-existing) in which images will be stored. """ super().__init__() self.train_data = train_data self.val_data = val_data self.save_path = os.path.abspath(os.path.join(outdir, "pred_images_at_epoch")) if not os.path.exists(self.save_path): os.makedirs(self.save_path) def pred_and_save(self, data, subdir): # Get a random batch X, y, _ = data[np.random.randint(len(data), dtype=np.int64)] # Predict on the batch pred = self.model.predict(X) subdir = os.path.join(self.save_path, subdir) if not os.path.exists(subdir): os.mkdir(subdir) # Plot each sample in the batch for i, (im, lab, p) in enumerate(zip(X, y, pred)): fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(12, 6)) lab = lab.reshape(im.shape[:-1] + (lab.shape[-1],)) p = p.reshape(im.shape[:-1] + (p.shape[-1],)) # Imshow ground truth on ax2 # This function will determine which channel, axis and slice to # show and return so that we can use them for the other 2 axes chnl, axis, slice = imshow_with_label_overlay(ax2, im, lab, lab_alpha=1.0) # Imshow pred on ax3 imshow_with_label_overlay(ax3, im, p, lab_alpha=1.0, channel=chnl, axis=axis, slice=slice) # Imshow raw image on ax1 # Chose the same slice, channel and axis as above im = im[..., chnl] im = np.moveaxis(im, axis, 0) if slice is not None: # Only for 3D imges im = im[slice] ax1.imshow(im, cmap="gray") # Set labels ax1.set_title("Image", size=18) ax2.set_title("True labels", size=18) ax3.set_title("Prediction", size=18) fig.tight_layout() with np.testing.suppress_warnings() as sup: sup.filter(UserWarning) fig.savefig(os.path.join(subdir, str(i) + ".png")) plt.close(fig.number) def on_epoch_end(self, epoch, logs={}): self.pred_and_save(self.train_data, "train_%s" % epoch) if self.val_data is not None: self.pred_and_save(self.val_data, "val_%s" % epoch)
37.019002
86
0.569714
import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import tensorflow as tf import psutil import numpy as np import os from tensorflow.keras.callbacks import Callback from datetime import datetime from mpunet.logging import ScreenLogger from mpunet.utils.plotting import (imshow_with_label_overlay, imshow, plot_all_training_curves) class DividerLine(Callback): def __init__(self, logger=None): super().__init__() self.logger = logger or ScreenLogger() def on_epoch_end(self, epoch, logs=None): self.logger("-"*45 + "\n") class LearningCurve(Callback): def __init__(self, log_dir="logs", out_dir="logs", fname="curve.png", csv_regex="*training.csv", logger=None, **plot_kwargs): super().__init__() out_dir = os.path.abspath(out_dir) if not os.path.exists(out_dir): os.makedirs(out_dir) self.csv_regex = os.path.join(os.path.abspath(log_dir), csv_regex) self.save_path = os.path.join(out_dir, fname) self.logger = logger or ScreenLogger() self.plot_kwargs = plot_kwargs def on_epoch_end(self, epoch, logs={}): plot_all_training_curves(self.csv_regex, self.save_path, logy=True, raise_error=False, logger=self.logger, **self.plot_kwargs) class MemoryConsumption(Callback): def __init__(self, max_gib=None, round_=2, logger=None): self.max_gib = max_gib self.logger = logger self.round_ = round_ def on_epoch_end(self, epoch, logs={}): process = psutil.Process(os.getpid()) mem_bytes = process.memory_info().rss mem_gib = round(mem_bytes / (1024**3), self.round_) logs['memory_usage_gib'] = mem_gib if self.max_gib and mem_gib >= self.max_gib: self.warn("Stopping training from callback 'MemoryConsumption'! " "Total memory consumption of {} GiB exceeds limitation" " (self.max_gib = {}) ".format(mem_gib, self.max_gib)) self.model.stop_training = True class DelayedCallback(object): def __init__(self, callback, start_from=0, logger=None): self.logger = logger or ScreenLogger() self.callback = callback self.start_from = start_from def __getattr__(self, item): return getattr(self.callback, item) def on_epoch_end(self, epoch, logs=None): if epoch >= self.start_from-1: self.callback.on_epoch_end(epoch, logs=logs) else: self.logger("[%s] Not active at epoch %i - will be at %i" % (self.callback.__class__.__name__, epoch+1, self.start_from)) class TrainTimer(Callback): def __init__(self, logger=None, max_minutes=None, verbose=1): super().__init__() self.logger = logger or ScreenLogger() self.max_minutes = int(max_minutes) if max_minutes else None self.verbose = bool(verbose) self.train_begin_time = None self.prev_epoch_time = None def on_train_begin(self, logs=None): self.train_begin_time = datetime.now() def on_epoch_begin(self, epoch, logs=None): self.prev_epoch_time = datetime.now() def on_epoch_end(self, epoch, logs=None): end_time = datetime.now() epoch_time = end_time - self.prev_epoch_time train_time = end_time - self.train_begin_time self.prev_epoch_time = end_time train_hours = round(train_time.total_seconds() / 3600, 4) epoch_minutes = round(epoch_time.total_seconds() / 60, 4) logs["epoch_minutes"] = epoch_minutes logs["train_hours"] = train_hours if self.verbose: self.logger("[TrainTimer] Epoch time: %.2f minutes " "- Total train time: %.2f hours" % (epoch_minutes, train_hours)) if self.max_minutes and train_hours*60 > self.max_minutes: self.logger("Stopping training. Training ran for {} minutes, " "max_minutes of {} was specified on the TrainTimer " "callback.".format(train_hours*60, self.max_minutes)) self.model.stop_training = True class FGBatchBalancer(Callback): def __init__(self, train_data, val_data=None, logger=None): super().__init__() self.data = (("train", train_data), ("val", val_data)) self.logger = logger or ScreenLogger() self.active = True def on_epoch_end(self, epoch, logs=None): if not self.active: return None recall = logs.get("val_recall") if recall is None: self.logger("[FGBatchBalancer] No val_recall in logs. " "Disabling callback. " "Did you put this callback before the validation " "callback?") self.active = False else: fraction = max(0.01, 1 - recall) for name, data in self.data: if data is not None: data.fg_batch_fraction = fraction self.logger("[FGBatchBalancer] Setting FG fraction for %s " "to: %.4f - Now %s/%s" % (name, fraction, data.n_fg_slices, data.batch_size)) class MeanReduceLogArrays(Callback): def __init__(self): super().__init__() def on_epoch_end(self, epoch, logs={}): for key, value in logs.items(): if isinstance(value, (np.ndarray, list)): logs[key] = np.mean(value) class PrintLayerWeights(Callback): def __init__(self, layer, every=10, first=10, per_epoch=False, logger=None): super().__init__() if isinstance(layer, int): self.layer = self.model.layers[layer] else: self.layer = layer self.first = first self.every = every self.logger = logger or ScreenLogger() self.per_epoch = per_epoch if per_epoch: self.on_epoch_begin = self.on_batch_begin self.on_batch_begin = lambda *args, **kwargs: None self.log() def log(self): self.logger("PrintLayerWeights Callback") self.logger("Layer: ", self.layer) self.logger("Every: ", self.every) self.logger("First: ", self.first) self.logger("Per epoch: ", self.per_epoch) def on_batch_begin(self, batch, logs=None): if batch % self.every: return weights = self.layer.get_weights() self.logger("Weights for layer '%s'" % self.layer) self.logger("Weights:\n%s" % weights[0].ravel()[:self.first]) try: self.logger("Baises:\n%s" % weights[1].ravel()[:self.first]) except IndexError: pass class SaveOutputAs2DImage(Callback): def __init__(self, layer, sequence, model, out_dir, every=10, logger=None): super().__init__() self.every = every self.seq = sequence self.layer = layer self.epoch = None self.model = model self.logger = logger or ScreenLogger() self.out_dir = out_dir if not os.path.exists(out_dir): os.makedirs(self.out_dir) self.log() def log(self): self.logger("Save Output as 2D Image Callback") self.logger("Layer: ", self.layer) self.logger("Every: ", self.every) def on_epoch_begin(self, epoch, logs=None): self.epoch = epoch def on_batch_end(self, batch, logs=None): if batch % self.every: return self.model.predict_on_batch() sess = tf.keras.backend.get_session() X, _, _ = self.seq[0] outs = sess.run([self.layer.output], feed_dict={self.model.input: X})[0] if isinstance(outs, list): outs = outs[0] for i, (model_in, layer_out) in enumerate(zip(X, outs)): fig = plt.figure(figsize=(12, 6)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) chl1, axis, slice = imshow(ax1, model_in) chl2, _, _ = imshow(ax2, layer_out, axis=axis, slice=slice) ax1.set_title("Model input - Channel %i - Axis %i - Slice %i" % (chl1, axis,slice), size=22) ax2.set_title("Layer output - Channel %i - Axis %i - Slice %i" % (chl2, axis, slice), size=22) fig.tight_layout() fig.savefig(os.path.join(self.out_dir, "epoch_%i_batch_%i_im_%i" % (self.epoch, batch, i))) plt.close(fig) class SavePredictionImages(Callback): def __init__(self, train_data, val_data, outdir='images'): super().__init__() self.train_data = train_data self.val_data = val_data self.save_path = os.path.abspath(os.path.join(outdir, "pred_images_at_epoch")) if not os.path.exists(self.save_path): os.makedirs(self.save_path) def pred_and_save(self, data, subdir): X, y, _ = data[np.random.randint(len(data), dtype=np.int64)] pred = self.model.predict(X) subdir = os.path.join(self.save_path, subdir) if not os.path.exists(subdir): os.mkdir(subdir) for i, (im, lab, p) in enumerate(zip(X, y, pred)): fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(12, 6)) lab = lab.reshape(im.shape[:-1] + (lab.shape[-1],)) p = p.reshape(im.shape[:-1] + (p.shape[-1],)) chnl, axis, slice = imshow_with_label_overlay(ax2, im, lab, lab_alpha=1.0) imshow_with_label_overlay(ax3, im, p, lab_alpha=1.0, channel=chnl, axis=axis, slice=slice) im = im[..., chnl] im = np.moveaxis(im, axis, 0) if slice is not None: im = im[slice] ax1.imshow(im, cmap="gray") ax1.set_title("Image", size=18) ax2.set_title("True labels", size=18) ax3.set_title("Prediction", size=18) fig.tight_layout() with np.testing.suppress_warnings() as sup: sup.filter(UserWarning) fig.savefig(os.path.join(subdir, str(i) + ".png")) plt.close(fig.number) def on_epoch_end(self, epoch, logs={}): self.pred_and_save(self.train_data, "train_%s" % epoch) if self.val_data is not None: self.pred_and_save(self.val_data, "val_%s" % epoch)
true
true
f725b10ac41ecee5ca5b5e982437b8bbd0484e3c
273
py
Python
src/password_generator.py
thiamsantos/python-labs
91262d64b3772526d91db96976f2df77011a2343
[ "MIT" ]
null
null
null
src/password_generator.py
thiamsantos/python-labs
91262d64b3772526d91db96976f2df77011a2343
[ "MIT" ]
null
null
null
src/password_generator.py
thiamsantos/python-labs
91262d64b3772526d91db96976f2df77011a2343
[ "MIT" ]
null
null
null
import string import random def generate_password(): chars = string.ascii_letters + string.digits + string.punctuation return ''.join([random.choice(chars) for i in range(0, 15)]) def main(): print(generate_password()) if __name__ == '__main__': main()
19.5
69
0.692308
import string import random def generate_password(): chars = string.ascii_letters + string.digits + string.punctuation return ''.join([random.choice(chars) for i in range(0, 15)]) def main(): print(generate_password()) if __name__ == '__main__': main()
true
true
f725b1ae42f7b8692600bca55736971aa629fa7d
4,921
py
Python
lib/jnpr/healthbot/swagger/models/rule_schema_formula_min.py
Juniper/healthbot-py-client
49f0884b5d01ac8430aa7ed4c9acb4e7a2b717a6
[ "Apache-2.0" ]
10
2019-10-23T12:54:37.000Z
2022-02-07T19:24:30.000Z
lib/jnpr/healthbot/swagger/models/rule_schema_formula_min.py
Juniper/healthbot-py-client
49f0884b5d01ac8430aa7ed4c9acb4e7a2b717a6
[ "Apache-2.0" ]
5
2019-09-30T04:29:25.000Z
2022-02-16T12:21:06.000Z
lib/jnpr/healthbot/swagger/models/rule_schema_formula_min.py
Juniper/healthbot-py-client
49f0884b5d01ac8430aa7ed4c9acb4e7a2b717a6
[ "Apache-2.0" ]
4
2019-09-30T01:17:48.000Z
2020-08-25T07:27:54.000Z
# coding: utf-8 """ Paragon Insights APIs API interface for PI application # noqa: E501 OpenAPI spec version: 4.0.0 Contact: healthbot-feedback@juniper.net Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class RuleSchemaFormulaMin(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'field_name': 'str', 'time_range': 'str' } attribute_map = { 'field_name': 'field-name', 'time_range': 'time-range' } def __init__(self, field_name=None, time_range=None): # noqa: E501 """RuleSchemaFormulaMin - a model defined in Swagger""" # noqa: E501 self._field_name = None self._time_range = None self.discriminator = None self.field_name = field_name self.time_range = time_range @property def field_name(self): """Gets the field_name of this RuleSchemaFormulaMin. # noqa: E501 Field name on which min operation needs to be performed # noqa: E501 :return: The field_name of this RuleSchemaFormulaMin. # noqa: E501 :rtype: str """ return self._field_name @field_name.setter def field_name(self, field_name): """Sets the field_name of this RuleSchemaFormulaMin. Field name on which min operation needs to be performed # noqa: E501 :param field_name: The field_name of this RuleSchemaFormulaMin. # noqa: E501 :type: str """ if field_name is None: raise ValueError("Invalid value for `field_name`, must not be `None`") # noqa: E501 self._field_name = field_name @property def time_range(self): """Gets the time_range of this RuleSchemaFormulaMin. # noqa: E501 How much back in time should we look for data. Specify positive integer followed by s/m/h/d/w/y/o representing seconds/minutes/hours/days/weeks/years/offset. Eg: 2s # noqa: E501 :return: The time_range of this RuleSchemaFormulaMin. # noqa: E501 :rtype: str """ return self._time_range @time_range.setter def time_range(self, time_range): """Sets the time_range of this RuleSchemaFormulaMin. How much back in time should we look for data. Specify positive integer followed by s/m/h/d/w/y/o representing seconds/minutes/hours/days/weeks/years/offset. Eg: 2s # noqa: E501 :param time_range: The time_range of this RuleSchemaFormulaMin. # noqa: E501 :type: str """ if time_range is None: raise ValueError("Invalid value for `time_range`, must not be `None`") # noqa: E501 if time_range is not None and not re.search(r'^[1-9][0-9]*(\\.[0-9]+)?(o|s|m|h|d|w|y|offset)$', time_range): # noqa: E501 raise ValueError(r"Invalid value for `time_range`, must be a follow pattern or equal to `/^[1-9][0-9]*(\\.[0-9]+)?(o|s|m|h|d|w|y|offset)$/`") # noqa: E501 self._time_range = time_range def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(RuleSchemaFormulaMin, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, RuleSchemaFormulaMin): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
32.806667
186
0.59622
import pprint import re import six class RuleSchemaFormulaMin(object): swagger_types = { 'field_name': 'str', 'time_range': 'str' } attribute_map = { 'field_name': 'field-name', 'time_range': 'time-range' } def __init__(self, field_name=None, time_range=None): self._field_name = None self._time_range = None self.discriminator = None self.field_name = field_name self.time_range = time_range @property def field_name(self): return self._field_name @field_name.setter def field_name(self, field_name): if field_name is None: raise ValueError("Invalid value for `field_name`, must not be `None`") self._field_name = field_name @property def time_range(self): return self._time_range @time_range.setter def time_range(self, time_range): if time_range is None: raise ValueError("Invalid value for `time_range`, must not be `None`") if time_range is not None and not re.search(r'^[1-9][0-9]*(\\.[0-9]+)?(o|s|m|h|d|w|y|offset)$', time_range): raise ValueError(r"Invalid value for `time_range`, must be a follow pattern or equal to `/^[1-9][0-9]*(\\.[0-9]+)?(o|s|m|h|d|w|y|offset)$/`") self._time_range = time_range def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(RuleSchemaFormulaMin, dict): for key, value in self.items(): result[key] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, RuleSchemaFormulaMin): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
f725b253adc761c90bb78171d6e459fcd4106d11
5,638
py
Python
tests/integration/climsoft/controller/test_regkey_controller.py
opencdms/opencdms-api
f1ed6e1d883025a8658746fe457e0c975718c7be
[ "MIT" ]
3
2020-12-01T09:25:18.000Z
2022-02-14T23:57:34.000Z
tests/integration/climsoft/controller/test_regkey_controller.py
opencdms/opencdms-api
f1ed6e1d883025a8658746fe457e0c975718c7be
[ "MIT" ]
11
2021-12-05T10:09:00.000Z
2022-02-17T08:11:22.000Z
tests/integration/climsoft/controller/test_regkey_controller.py
opencdms/opencdms-api
f1ed6e1d883025a8658746fe457e0c975718c7be
[ "MIT" ]
2
2021-03-10T19:03:05.000Z
2021-12-11T08:36:04.000Z
import json import pytest from sqlalchemy.sql import text as sa_text from sqlalchemy.orm.session import sessionmaker from opencdms.models.climsoft import v4_1_1_core as climsoft_models from apps.climsoft.db.engine import db_engine from apps.climsoft.schemas import regkey_schema from datagen.climsoft import regkey as climsoft_regkey from faker import Faker from fastapi.testclient import TestClient from apps.auth.db.engine import db_engine as auth_db_engine from apps.auth.db.models import user_model from passlib.hash import django_pbkdf2_sha256 as handler fake = Faker() def setup_module(module): with auth_db_engine.connect().execution_options(autocommit=True) as connection: with connection.begin(): auth_db_engine.execute(sa_text(f''' TRUNCATE TABLE {user_model.AuthUser.__tablename__} RESTART IDENTITY CASCADE ''').execution_options(autocommit=True)) with db_engine.connect().execution_options(autocommit=True) as connection: with connection.begin(): db_engine.execute(sa_text(f""" SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE {climsoft_models.Regkey.__tablename__}; SET FOREIGN_KEY_CHECKS = 1; """)) Session = sessionmaker(bind=db_engine) db_session = Session() for i in range(1, 11): db_session.add(climsoft_models.Regkey( **climsoft_regkey.get_valid_reg_key_input().dict() )) db_session.commit() db_session.close() AuthSession = sessionmaker(bind=auth_db_engine) auth_session = AuthSession() user = user_model.AuthUser( username="testuser", password=handler.hash("password"), first_name=fake.first_name(), last_name=fake.last_name(), email=fake.email() ) auth_session.add(user) auth_session.commit() auth_session.close() def teardown_module(module): with auth_db_engine.connect().execution_options(autocommit=True) as connection: with connection.begin(): auth_db_engine.execute(sa_text(f''' TRUNCATE TABLE {user_model.AuthUser.__tablename__} RESTART IDENTITY CASCADE ''').execution_options(autocommit=True)) with db_engine.connect().execution_options(autocommit=True) as connection: with connection.begin(): db_engine.execute(sa_text(f""" SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE {climsoft_models.Regkey.__tablename__}; SET FOREIGN_KEY_CHECKS = 1; """)) @pytest.fixture def get_access_token(user_access_token: str) -> str: return user_access_token @pytest.fixture def get_reg_key(): Session = sessionmaker(bind=db_engine) session = Session() reg_key = climsoft_models.Regkey(**climsoft_regkey.get_valid_reg_key_input().dict()) session.add(reg_key) session.commit() yield reg_key session.close() def test_should_return_first_five_reg_keys(client: TestClient, get_access_token: str): response = client.get("/climsoft/v1/reg-keys", params={"limit": 5}, headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 200 response_data = response.json() assert len(response_data["result"]) == 5 def test_should_return_single_reg_key(client: TestClient, get_reg_key: climsoft_models.Regkey, get_access_token: str): response = client.get(f"/climsoft/v1/reg-keys/{get_reg_key.keyName}", headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 200 response_data = response.json() assert len(response_data["result"]) == 1 def test_should_create_a_reg_key(client: TestClient, get_access_token: str): reg_key_data = climsoft_regkey.get_valid_reg_key_input().dict(by_alias=True) response = client.post("/climsoft/v1/reg-keys", data=json.dumps(reg_key_data, default=str), headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 200 response_data = response.json() assert len(response_data["result"]) == 1 def test_should_raise_validation_error(client: TestClient, get_access_token: str): reg_key_data = {"aaa": "bbbbbbb"} response = client.post("/climsoft/v1/reg-keys", data=json.dumps(reg_key_data, default=str), headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 422 def test_should_update_reg_key(client: TestClient, get_reg_key, get_access_token: str): reg_key_data = regkey_schema.RegKey.from_orm(get_reg_key).dict(by_alias=True) key_name = reg_key_data.pop("key_name") updates = {**reg_key_data, "key_description": "updated name"} response = client.put(f"/climsoft/v1/reg-keys/{key_name}", data=json.dumps(updates, default=str), headers={ "Authorization": f"Bearer {get_access_token}" }) response_data = response.json() assert response.status_code == 200 assert response_data["result"][0]["key_description"] == updates["key_description"] def test_should_delete_reg_key(client: TestClient, get_reg_key, get_access_token: str): reg_key_data = regkey_schema.RegKey.from_orm(get_reg_key).dict(by_alias=True) key_name = reg_key_data.pop("key_name") response = client.delete(f"/climsoft/v1/reg-keys/{key_name}", headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 200 response = client.get(f"/climsoft/v1/reg-keys/{key_name}", headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 404
37.586667
118
0.707166
import json import pytest from sqlalchemy.sql import text as sa_text from sqlalchemy.orm.session import sessionmaker from opencdms.models.climsoft import v4_1_1_core as climsoft_models from apps.climsoft.db.engine import db_engine from apps.climsoft.schemas import regkey_schema from datagen.climsoft import regkey as climsoft_regkey from faker import Faker from fastapi.testclient import TestClient from apps.auth.db.engine import db_engine as auth_db_engine from apps.auth.db.models import user_model from passlib.hash import django_pbkdf2_sha256 as handler fake = Faker() def setup_module(module): with auth_db_engine.connect().execution_options(autocommit=True) as connection: with connection.begin(): auth_db_engine.execute(sa_text(f''' TRUNCATE TABLE {user_model.AuthUser.__tablename__} RESTART IDENTITY CASCADE ''').execution_options(autocommit=True)) with db_engine.connect().execution_options(autocommit=True) as connection: with connection.begin(): db_engine.execute(sa_text(f""" SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE {climsoft_models.Regkey.__tablename__}; SET FOREIGN_KEY_CHECKS = 1; """)) Session = sessionmaker(bind=db_engine) db_session = Session() for i in range(1, 11): db_session.add(climsoft_models.Regkey( **climsoft_regkey.get_valid_reg_key_input().dict() )) db_session.commit() db_session.close() AuthSession = sessionmaker(bind=auth_db_engine) auth_session = AuthSession() user = user_model.AuthUser( username="testuser", password=handler.hash("password"), first_name=fake.first_name(), last_name=fake.last_name(), email=fake.email() ) auth_session.add(user) auth_session.commit() auth_session.close() def teardown_module(module): with auth_db_engine.connect().execution_options(autocommit=True) as connection: with connection.begin(): auth_db_engine.execute(sa_text(f''' TRUNCATE TABLE {user_model.AuthUser.__tablename__} RESTART IDENTITY CASCADE ''').execution_options(autocommit=True)) with db_engine.connect().execution_options(autocommit=True) as connection: with connection.begin(): db_engine.execute(sa_text(f""" SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE {climsoft_models.Regkey.__tablename__}; SET FOREIGN_KEY_CHECKS = 1; """)) @pytest.fixture def get_access_token(user_access_token: str) -> str: return user_access_token @pytest.fixture def get_reg_key(): Session = sessionmaker(bind=db_engine) session = Session() reg_key = climsoft_models.Regkey(**climsoft_regkey.get_valid_reg_key_input().dict()) session.add(reg_key) session.commit() yield reg_key session.close() def test_should_return_first_five_reg_keys(client: TestClient, get_access_token: str): response = client.get("/climsoft/v1/reg-keys", params={"limit": 5}, headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 200 response_data = response.json() assert len(response_data["result"]) == 5 def test_should_return_single_reg_key(client: TestClient, get_reg_key: climsoft_models.Regkey, get_access_token: str): response = client.get(f"/climsoft/v1/reg-keys/{get_reg_key.keyName}", headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 200 response_data = response.json() assert len(response_data["result"]) == 1 def test_should_create_a_reg_key(client: TestClient, get_access_token: str): reg_key_data = climsoft_regkey.get_valid_reg_key_input().dict(by_alias=True) response = client.post("/climsoft/v1/reg-keys", data=json.dumps(reg_key_data, default=str), headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 200 response_data = response.json() assert len(response_data["result"]) == 1 def test_should_raise_validation_error(client: TestClient, get_access_token: str): reg_key_data = {"aaa": "bbbbbbb"} response = client.post("/climsoft/v1/reg-keys", data=json.dumps(reg_key_data, default=str), headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 422 def test_should_update_reg_key(client: TestClient, get_reg_key, get_access_token: str): reg_key_data = regkey_schema.RegKey.from_orm(get_reg_key).dict(by_alias=True) key_name = reg_key_data.pop("key_name") updates = {**reg_key_data, "key_description": "updated name"} response = client.put(f"/climsoft/v1/reg-keys/{key_name}", data=json.dumps(updates, default=str), headers={ "Authorization": f"Bearer {get_access_token}" }) response_data = response.json() assert response.status_code == 200 assert response_data["result"][0]["key_description"] == updates["key_description"] def test_should_delete_reg_key(client: TestClient, get_reg_key, get_access_token: str): reg_key_data = regkey_schema.RegKey.from_orm(get_reg_key).dict(by_alias=True) key_name = reg_key_data.pop("key_name") response = client.delete(f"/climsoft/v1/reg-keys/{key_name}", headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 200 response = client.get(f"/climsoft/v1/reg-keys/{key_name}", headers={ "Authorization": f"Bearer {get_access_token}" }) assert response.status_code == 404
true
true
f725b3453489b66fbfc7b49799e450b8abfbfc00
11,264
py
Python
deployer/src/config_creator.py
yugabyte/docsearch-scraper
8b58d364c7721cbce892843e946834a3ccc5fcd7
[ "MIT" ]
null
null
null
deployer/src/config_creator.py
yugabyte/docsearch-scraper
8b58d364c7721cbce892843e946834a3ccc5fcd7
[ "MIT" ]
null
null
null
deployer/src/config_creator.py
yugabyte/docsearch-scraper
8b58d364c7721cbce892843e946834a3ccc5fcd7
[ "MIT" ]
1
2020-04-01T22:01:17.000Z
2020-04-01T22:01:17.000Z
from collections import OrderedDict import tldextract import re from . import helpers from . import helpdesk_helper from urllib.parse import urlparse def extract_root_from_input(input_string): # We cant parse the url since user might have not enter a proper link # We assume that the string is already the proper root if input_string.endswith('/'): return input_string # extracting substring before the first isolated / (not //) domain = re.match(".+?([^/]/(?!/))", input_string) try: url_parsed = urlparse(input_string) # Removing unused parameters url_parsed._replace(params='', query='', fragment='') path_splited = url_parsed.path.split('/') # Path is redirecting to a page if ('html' in path_splited[-1]): url_parsed = url_parsed._replace(path='/'.join(path_splited[: -1])) # We are fine else: pass return url_parsed.geturl() + '/' except ValueError: return domain.group() if domain else input_string def to_docusaurus_config(config, urls=None): if urls: config["sitemap_urls"] = [ extract_root_from_input(urls[0]) + "sitemap.xml"] config["sitemap_alternate_links"] = True config["custom_settings"] = {"attributesForFaceting": ["language", "version"] } config["selectors"]["lvl0"] = OrderedDict(( ("selector", "//*[contains(@class,'navGroups')]//*[contains(@class,'navListItemActive')]/preceding::h3[1]"), ("type", "xpath"), ("global", True), ("default_value", "Documentation") )) config["selectors"]["lvl1"] = ".post h1" config["selectors"]["lvl2"] = ".post h2" config["selectors"]["lvl3"] = ".post h3" config["selectors"]["lvl4"] = ".post h4" config["selectors"]["lvl5"] = ".post h5" config["selectors"]["text"] = ".post article p, .post article li" config["selectors_exclude"] = [".hash-link"] return config def to_gitbook_config(config): config["selectors"]["lvl0"] = ".markdown-section h1" config["selectors"]["lvl1"] = ".markdown-section h2" config["selectors"]["lvl2"] = ".markdown-section h3" config["selectors"]["lvl3"] = ".markdown-section h4" config["selectors"]["lvl4"] = ".markdown-section h4" config["selectors"]["lvl5"] = ".markdown-section h5" config["selectors"]["text"] = ".markdown-section p, .markdown-section li" return config def to_pkgdown_config(config, urls=None): if urls: root = extract_root_from_input(urls[0]) config["start_urls"] = [{ "url": root + "index.html", "selectors_key": "homepage", "tags": [ "homepage" ] }, { "url": root + "reference", "selectors_key": "reference", "tags": [ "reference" ] }, { "url": root + "articles", "selectors_key": "articles", "tags": [ "articles" ] }] config["sitemap_urls"] = [ root + "sitemap.xml"] config["selectors"] = OrderedDict(( ("homepage", OrderedDict(( ("lvl0", OrderedDict(( ("selector", ".contents h1"), ("default_value", "pkgdown Home page") ))), ("lvl1", ".contents h2"), ("lvl2", OrderedDict(( ("selector", ".contents h3"), ("default_value", "Context") ))), ("lvl3", ".ref-arguments td, .ref-description"), ("text", ".contents p, .contents li, .contents .pre") ))), ("reference", OrderedDict(( ("lvl0", ".contents h1"), ("lvl1", OrderedDict(( ("selector", ".contents .name"), ("default_value", "Argument") ))), ("lvl2", OrderedDict(( ("selector", ".ref-arguments th"), ("default_value", "Description") ))), ("lvl3", ".ref-arguments td, .ref-description"), ("text", ".contents p, .contents li") ))), ("articles", OrderedDict(( ("lvl0", ".contents h1"), ("lvl1", ".contents .name"), ("lvl2", OrderedDict(( ("selector", ".contents h2, .contents h3"), ("default_value", "Context") ))), ("text", ".contents p, .contents li") ))), ("default", OrderedDict(( ("lvl1", ".contents h2"), ("lvl2", ".contents h3, .contents th"), ("lvl3", ".contents h4"), ("lvl4", ".contents h5"), ("text", ".contents p, .contents li, .usage, .template-article .contents .pre") ))) )) config["selectors_exclude"] = [".dont-index"] config["stop_urls"] = ["/reference/$", "/reference/index.html", "/articles/$", "/articles/index.html"] config["custom_settings"] = { "separatorsToIndex": "_", "attributesToRetrieve": ["hierarchy", "content", "anchor", "url", "url_without_anchor"] } config["min_indexed_level"] = 2 return config def to_vuepress_config(config): config["selectors"]["lvl0"] = OrderedDict(( ("selector", "p.sidebar-heading.open"), ("global", True), ("default_value", "Documentation") )) config["custom_settings"] = {"attributesForFaceting": ["lang"] } config["selectors"]["lvl1"] = ".content h1" config["selectors"]["lvl2"] = ".content h2" config["selectors"]["lvl3"] = ".content h3" config["selectors"]["lvl4"] = ".content h4" config["selectors"]["lvl5"] = ".content h5" config["selectors"]["text"] = ".content p, .content li" config["selectors"]["lang"] = OrderedDict(( ("selector", "/html/@lang"), ("type", "xpath"), ("global", True), ("default_value", "en-US") )) config["scrap_start_urls"] = False config["strip_chars"] = " .,;:#" return config def to_larecipe_config(config, urls=None): if urls: config["sitemap_urls"] = [ extract_root_from_input(urls[0]) + "sitemap.xml"] config["selectors"]["lvl0"] = OrderedDict(( ("selector", "//div[contains(@class, 'sidebar')]//li/a[text()=//div[contains(@class, 'article')]//h1[1]/text()]"), ("global", True), ("type", "xpath"), ("default_value", "Documentation") )) config["selectors"]["lvl1"] = "div.article h1" config["selectors"]["lvl2"] = "div.article h2" config["selectors"]["lvl3"] = "div.article h3" config["selectors"]["lvl4"] = "div.article h4" config["selectors"]["lvl5"] = "div.article h5" config["selectors"]["text"] = "div.article p, div.article li" return config def to_publii_config(config, urls=None): if urls: config["sitemap_urls"] = [ extract_root_from_input(urls[0]) + "sitemap.xml"] config["selectors"]["lvl0"] = OrderedDict(( ("selector", ".active-parent > span"), ("global", True), ("default_value", "Documentation") )) config["selectors"]["lvl1"] = ".content h1" config["selectors"]["lvl2"] = ".content h2" config["selectors"]["lvl3"] = ".content h3" config["selectors"]["lvl4"] = ".content h4" config["selectors"]["lvl5"] = ".content h5" config["selectors"]["text"] = ".content p, .content li" config["only_content_level"] = True return config def to_jsdoc_config(config, urls=None): config["stop_urls"] = ["\\.js\\.html", "/index\\.html$"] config["selectors"]["lvl0"] = OrderedDict(( ("selector", "#main .page-title"), ("global", True), ("default_value", "Documentation") )) config["selectors"]["lvl1"] = "#main h3" config["selectors"]["lvl2"] = "#main h4" config["selectors"]["lvl3"] = "#main h5" config["selectors"]["lvl4"] = "#main h6, #main td.name" del config["selectors"]["lvl5"] config["selectors"]["text"] = "#main p, #main li" config["selectors_exclude"] = [".signature", ".type-signature", ".details"] return config def create_config(u=None): config = OrderedDict(( ("index_name", ""), ("start_urls", []), ("stop_urls", []), ("selectors", OrderedDict(( ("lvl0", "FIXME h1"), ("lvl1", "FIXME h2"), ("lvl2", "FIXME h3"), ("lvl3", "FIXME h4"), ("lvl4", "FIXME h5"), ("lvl5", "FIXME h6"), ("text", "FIXME p, FIXME li") ))) )) if u is None: u = helpers.get_user_value("start url: ") urls = [u] if helpdesk_helper.is_helpdesk_url(u): cuid = helpdesk_helper.get_conversation_ID_from_url(u) conversation = helpdesk_helper.get_conversation(cuid) url_from_conversation = helpdesk_helper.get_start_url_from_conversation( conversation) urls = [url_from_conversation] u = url_from_conversation if helpdesk_helper.is_docusaurus_conversation(conversation): config = to_docusaurus_config(config, urls) elif helpdesk_helper.is_gitbook_conversation(conversation): config = to_gitbook_config(config) elif helpdesk_helper.is_pkgdown_conversation(conversation): config = to_pkgdown_config(config, urls) elif helpdesk_helper.is_vuepress_conversation(conversation): config = to_vuepress_config(config) elif helpdesk_helper.is_larecipe_conversation(conversation): config = to_larecipe_config(config, urls) elif helpdesk_helper.is_publii_conversation(conversation): config = to_publii_config(config, urls) elif helpdesk_helper.is_jsdoc_conversation(conversation): config = to_jsdoc_config(config, urls) config["conversation_id"] = [cuid] if '.html' in u: urls.append(u.rsplit('/', 1)[0]) # Use subdomain for github website https://<subdomain>.github.io/ config['index_name'] = tldextract.extract( u).subdomain if tldextract.extract( u).domain == 'github' else tldextract.extract(u).domain if len(config['start_urls']) == 0: config['start_urls'] = urls user_index_name = helpers.get_user_value( 'index_name is \033[1;33m{}\033[0m [enter to confirm]: '.format(config[ "index_name"])) if user_index_name != "": config['index_name'] = user_index_name print('index_name is now \033[1;33m{}\033[0m'.format(config[ "index_name"])) return config
34.552147
110
0.532404
from collections import OrderedDict import tldextract import re from . import helpers from . import helpdesk_helper from urllib.parse import urlparse def extract_root_from_input(input_string): if input_string.endswith('/'): return input_string domain = re.match(".+?([^/]/(?!/))", input_string) try: url_parsed = urlparse(input_string) url_parsed._replace(params='', query='', fragment='') path_splited = url_parsed.path.split('/') if ('html' in path_splited[-1]): url_parsed = url_parsed._replace(path='/'.join(path_splited[: -1])) else: pass return url_parsed.geturl() + '/' except ValueError: return domain.group() if domain else input_string def to_docusaurus_config(config, urls=None): if urls: config["sitemap_urls"] = [ extract_root_from_input(urls[0]) + "sitemap.xml"] config["sitemap_alternate_links"] = True config["custom_settings"] = {"attributesForFaceting": ["language", "version"] } config["selectors"]["lvl0"] = OrderedDict(( ("selector", "//*[contains(@class,'navGroups')]//*[contains(@class,'navListItemActive')]/preceding::h3[1]"), ("type", "xpath"), ("global", True), ("default_value", "Documentation") )) config["selectors"]["lvl1"] = ".post h1" config["selectors"]["lvl2"] = ".post h2" config["selectors"]["lvl3"] = ".post h3" config["selectors"]["lvl4"] = ".post h4" config["selectors"]["lvl5"] = ".post h5" config["selectors"]["text"] = ".post article p, .post article li" config["selectors_exclude"] = [".hash-link"] return config def to_gitbook_config(config): config["selectors"]["lvl0"] = ".markdown-section h1" config["selectors"]["lvl1"] = ".markdown-section h2" config["selectors"]["lvl2"] = ".markdown-section h3" config["selectors"]["lvl3"] = ".markdown-section h4" config["selectors"]["lvl4"] = ".markdown-section h4" config["selectors"]["lvl5"] = ".markdown-section h5" config["selectors"]["text"] = ".markdown-section p, .markdown-section li" return config def to_pkgdown_config(config, urls=None): if urls: root = extract_root_from_input(urls[0]) config["start_urls"] = [{ "url": root + "index.html", "selectors_key": "homepage", "tags": [ "homepage" ] }, { "url": root + "reference", "selectors_key": "reference", "tags": [ "reference" ] }, { "url": root + "articles", "selectors_key": "articles", "tags": [ "articles" ] }] config["sitemap_urls"] = [ root + "sitemap.xml"] config["selectors"] = OrderedDict(( ("homepage", OrderedDict(( ("lvl0", OrderedDict(( ("selector", ".contents h1"), ("default_value", "pkgdown Home page") ))), ("lvl1", ".contents h2"), ("lvl2", OrderedDict(( ("selector", ".contents h3"), ("default_value", "Context") ))), ("lvl3", ".ref-arguments td, .ref-description"), ("text", ".contents p, .contents li, .contents .pre") ))), ("reference", OrderedDict(( ("lvl0", ".contents h1"), ("lvl1", OrderedDict(( ("selector", ".contents .name"), ("default_value", "Argument") ))), ("lvl2", OrderedDict(( ("selector", ".ref-arguments th"), ("default_value", "Description") ))), ("lvl3", ".ref-arguments td, .ref-description"), ("text", ".contents p, .contents li") ))), ("articles", OrderedDict(( ("lvl0", ".contents h1"), ("lvl1", ".contents .name"), ("lvl2", OrderedDict(( ("selector", ".contents h2, .contents h3"), ("default_value", "Context") ))), ("text", ".contents p, .contents li") ))), ("default", OrderedDict(( ("lvl1", ".contents h2"), ("lvl2", ".contents h3, .contents th"), ("lvl3", ".contents h4"), ("lvl4", ".contents h5"), ("text", ".contents p, .contents li, .usage, .template-article .contents .pre") ))) )) config["selectors_exclude"] = [".dont-index"] config["stop_urls"] = ["/reference/$", "/reference/index.html", "/articles/$", "/articles/index.html"] config["custom_settings"] = { "separatorsToIndex": "_", "attributesToRetrieve": ["hierarchy", "content", "anchor", "url", "url_without_anchor"] } config["min_indexed_level"] = 2 return config def to_vuepress_config(config): config["selectors"]["lvl0"] = OrderedDict(( ("selector", "p.sidebar-heading.open"), ("global", True), ("default_value", "Documentation") )) config["custom_settings"] = {"attributesForFaceting": ["lang"] } config["selectors"]["lvl1"] = ".content h1" config["selectors"]["lvl2"] = ".content h2" config["selectors"]["lvl3"] = ".content h3" config["selectors"]["lvl4"] = ".content h4" config["selectors"]["lvl5"] = ".content h5" config["selectors"]["text"] = ".content p, .content li" config["selectors"]["lang"] = OrderedDict(( ("selector", "/html/@lang"), ("type", "xpath"), ("global", True), ("default_value", "en-US") )) config["scrap_start_urls"] = False config["strip_chars"] = " .,;:#" return config def to_larecipe_config(config, urls=None): if urls: config["sitemap_urls"] = [ extract_root_from_input(urls[0]) + "sitemap.xml"] config["selectors"]["lvl0"] = OrderedDict(( ("selector", "//div[contains(@class, 'sidebar')]//li/a[text()=//div[contains(@class, 'article')]//h1[1]/text()]"), ("global", True), ("type", "xpath"), ("default_value", "Documentation") )) config["selectors"]["lvl1"] = "div.article h1" config["selectors"]["lvl2"] = "div.article h2" config["selectors"]["lvl3"] = "div.article h3" config["selectors"]["lvl4"] = "div.article h4" config["selectors"]["lvl5"] = "div.article h5" config["selectors"]["text"] = "div.article p, div.article li" return config def to_publii_config(config, urls=None): if urls: config["sitemap_urls"] = [ extract_root_from_input(urls[0]) + "sitemap.xml"] config["selectors"]["lvl0"] = OrderedDict(( ("selector", ".active-parent > span"), ("global", True), ("default_value", "Documentation") )) config["selectors"]["lvl1"] = ".content h1" config["selectors"]["lvl2"] = ".content h2" config["selectors"]["lvl3"] = ".content h3" config["selectors"]["lvl4"] = ".content h4" config["selectors"]["lvl5"] = ".content h5" config["selectors"]["text"] = ".content p, .content li" config["only_content_level"] = True return config def to_jsdoc_config(config, urls=None): config["stop_urls"] = ["\\.js\\.html", "/index\\.html$"] config["selectors"]["lvl0"] = OrderedDict(( ("selector", "#main .page-title"), ("global", True), ("default_value", "Documentation") )) config["selectors"]["lvl1"] = "#main h3" config["selectors"]["lvl2"] = "#main h4" config["selectors"]["lvl3"] = "#main h5" config["selectors"]["lvl4"] = "#main h6, #main td.name" del config["selectors"]["lvl5"] config["selectors"]["text"] = "#main p, #main li" config["selectors_exclude"] = [".signature", ".type-signature", ".details"] return config def create_config(u=None): config = OrderedDict(( ("index_name", ""), ("start_urls", []), ("stop_urls", []), ("selectors", OrderedDict(( ("lvl0", "FIXME h1"), ("lvl1", "FIXME h2"), ("lvl2", "FIXME h3"), ("lvl3", "FIXME h4"), ("lvl4", "FIXME h5"), ("lvl5", "FIXME h6"), ("text", "FIXME p, FIXME li") ))) )) if u is None: u = helpers.get_user_value("start url: ") urls = [u] if helpdesk_helper.is_helpdesk_url(u): cuid = helpdesk_helper.get_conversation_ID_from_url(u) conversation = helpdesk_helper.get_conversation(cuid) url_from_conversation = helpdesk_helper.get_start_url_from_conversation( conversation) urls = [url_from_conversation] u = url_from_conversation if helpdesk_helper.is_docusaurus_conversation(conversation): config = to_docusaurus_config(config, urls) elif helpdesk_helper.is_gitbook_conversation(conversation): config = to_gitbook_config(config) elif helpdesk_helper.is_pkgdown_conversation(conversation): config = to_pkgdown_config(config, urls) elif helpdesk_helper.is_vuepress_conversation(conversation): config = to_vuepress_config(config) elif helpdesk_helper.is_larecipe_conversation(conversation): config = to_larecipe_config(config, urls) elif helpdesk_helper.is_publii_conversation(conversation): config = to_publii_config(config, urls) elif helpdesk_helper.is_jsdoc_conversation(conversation): config = to_jsdoc_config(config, urls) config["conversation_id"] = [cuid] if '.html' in u: urls.append(u.rsplit('/', 1)[0]) config['index_name'] = tldextract.extract( u).subdomain if tldextract.extract( u).domain == 'github' else tldextract.extract(u).domain if len(config['start_urls']) == 0: config['start_urls'] = urls user_index_name = helpers.get_user_value( 'index_name is \033[1;33m{}\033[0m [enter to confirm]: '.format(config[ "index_name"])) if user_index_name != "": config['index_name'] = user_index_name print('index_name is now \033[1;33m{}\033[0m'.format(config[ "index_name"])) return config
true
true
f725b3e77a5288c1d9314ff987b54ca1c859daff
46,076
py
Python
tests/plugins/test_reactor_config.py
MartinBasti/atomic-reactor
4431225c5a474c7f88c63ec1f25216d4b84a0f1d
[ "BSD-3-Clause" ]
null
null
null
tests/plugins/test_reactor_config.py
MartinBasti/atomic-reactor
4431225c5a474c7f88c63ec1f25216d4b84a0f1d
[ "BSD-3-Clause" ]
null
null
null
tests/plugins/test_reactor_config.py
MartinBasti/atomic-reactor
4431225c5a474c7f88c63ec1f25216d4b84a0f1d
[ "BSD-3-Clause" ]
null
null
null
""" Copyright (c) 2017 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import unicode_literals from jsonschema import ValidationError import io import logging import os import pkg_resources import pytest from textwrap import dedent import re import yaml import smtplib from copy import deepcopy import atomic_reactor import koji from atomic_reactor.core import DockerTasker from atomic_reactor.inner import DockerBuildWorkflow from atomic_reactor.util import read_yaml import atomic_reactor.koji_util import atomic_reactor.pulp_util import atomic_reactor.odcs_util import osbs.conf import osbs.api from osbs.utils import RegistryURI from atomic_reactor.plugins.pre_reactor_config import (ReactorConfig, ReactorConfigPlugin, get_config, WORKSPACE_CONF_KEY, get_koji_session, get_koji_path_info, get_pulp_session, get_odcs_session, get_smtp_session, get_openshift_session, get_clusters_client_config_path, get_docker_registry, get_platform_to_goarch_mapping, get_goarch_to_platform_mapping, get_default_image_build_method, get_flatpak_base_image, CONTAINER_DEFAULT_BUILD_METHOD, get_build_image_override, NO_FALLBACK) from tests.constants import TEST_IMAGE, REACTOR_CONFIG_MAP from tests.docker_mock import mock_docker from tests.fixtures import reactor_config_map # noqa from flexmock import flexmock class TestReactorConfigPlugin(object): def prepare(self): mock_docker() tasker = DockerTasker() workflow = DockerBuildWorkflow({'provider': 'git', 'uri': 'asd'}, TEST_IMAGE) return tasker, workflow @pytest.mark.parametrize(('fallback'), [ False, True ]) @pytest.mark.parametrize(('config', 'valid'), [ ("""\ version: 1 registries: - url: https://container-registry.example.com/v2 auth: cfg_path: /var/run/secrets/atomic-reactor/v2-registry-dockercfg """, True), ("""\ version: 1 registries: - url: https://old-container-registry.example.com/v1 auth: cfg_path: /var/run/secrets/atomic-reactor/v1-registry-dockercfg - url: https://container-registry.example.com/v2 auth: cfg_path: /var/run/secrets/atomic-reactor/v2-registry-dockercfg """, True), ("""\ version: 1 registries: - url: https://old-container-registry.example.com/v1 auth: cfg_path: /var/run/secrets/atomic-reactor/v1-registry-dockercfg """, False), ]) def test_get_docker_registry(self, config, fallback, valid): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} config_json = read_yaml(config, 'schemas/config.json') docker_reg = { 'version': 'v2', 'insecure': False, 'secret': '/var/run/secrets/atomic-reactor/v2-registry-dockercfg', 'url': 'https://container-registry.example.com/v2', } if fallback: if valid: docker_fallback = docker_reg expected = docker_reg else: docker_fallback = NO_FALLBACK else: docker_fallback = {} expected = { 'url': 'https://container-registry.example.com', 'insecure': False, 'secret': '/var/run/secrets/atomic-reactor/v2-registry-dockercfg' } workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) if valid: docker_registry = get_docker_registry(workflow, docker_fallback) assert docker_registry == expected else: if fallback: with pytest.raises(KeyError): get_docker_registry(workflow, docker_fallback) else: with pytest.raises(RuntimeError): get_docker_registry(workflow, docker_fallback) def test_no_config(self): tasker, workflow = self.prepare() conf = get_config(workflow) assert isinstance(conf, ReactorConfig) same_conf = get_config(workflow) assert conf is same_conf @pytest.mark.parametrize('basename', ['reactor-config.yaml', None]) def test_filename(self, tmpdir, basename): filename = os.path.join(str(tmpdir), basename or 'config.yaml') with open(filename, 'w'): pass tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir), basename=filename) assert plugin.run() is None def test_filename_not_found(self): tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path='/not-found') with pytest.raises(Exception): plugin.run() def test_no_schema_resource(self, tmpdir, caplog): class FakeProvider(object): def get_resource_stream(self, pkg, rsc): raise IOError # pkg_resources.resource_stream() cannot be mocked directly # Instead mock the module-level function it calls. (flexmock(pkg_resources) .should_receive('get_provider') .and_return(FakeProvider())) filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w'): pass tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) with caplog.atLevel(logging.ERROR), pytest.raises(Exception): plugin.run() captured_errs = [x.message for x in caplog.records()] assert "unable to extract JSON schema, cannot validate" in captured_errs @pytest.mark.parametrize('schema', [ # Invalid JSON '{', # Invalid schema '{"properties": {"any": null}}', ]) def test_invalid_schema_resource(self, tmpdir, caplog, schema): class FakeProvider(object): def get_resource_stream(self, pkg, rsc): return io.BufferedReader(io.BytesIO(schema)) # pkg_resources.resource_stream() cannot be mocked directly # Instead mock the module-level function it calls. (flexmock(pkg_resources) .should_receive('get_provider') .and_return(FakeProvider())) filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w'): pass tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) with caplog.atLevel(logging.ERROR), pytest.raises(Exception): plugin.run() captured_errs = [x.message for x in caplog.records()] assert any("cannot validate" in x for x in captured_errs) @pytest.mark.parametrize(('config', 'errors'), [ # noqa:F811 ("""\ clusters: foo: - name: bar max_concurrent_builds: 1 """, [ "validation error (at top level): " "%r is a required property" % u'version', ]), ("""\ version: 1 clusters: foo: bar: 1 plat/form: - name: foo max_concurrent_builds: 1 """, [ "validation error (clusters.foo): None is not of type %r" % u'array', "validation error (clusters.bar): 1 is not of type %r" % u'array', re.compile(r"validation error \(clusters\): .*'plat/form'"), ]), ("""\ version: 1 clusters: foo: - name: 1 max_concurrent_builds: 1 - name: blah max_concurrent_builds: one - name: "2" # quoting prevents error max_concurrent_builds: 2 - name: negative max_concurrent_builds: -1 """, [ "validation error (clusters.foo[0].name): " "1 is not of type %r" % u'string', "validation error (clusters.foo[1].max_concurrent_builds): " "'one' is not of type %r" % u'integer', re.compile(r"validation error \(clusters\.foo\[3\]\.max_concurrent_builds\): -1(\.0)?" r" is less than the minimum of 0"), ]), ("""\ version: 1 clusters: foo: - name: blah max_concurrent_builds: 1 enabled: never """, [ "validation error (clusters.foo[0].enabled): " "'never' is not of type %r" % u'boolean', ]), ("""\ version: 1 clusters: foo: # missing name - nam: bar max_concurrent_builds: 1 # missing max_concurrent_builds - name: baz max_concurrrent_builds: 2 - name: bar max_concurrent_builds: 4 extra: false """, [ "validation error (clusters.foo[0]): " "%r is a required property" % u'name', "validation error (clusters.foo[1]): " "%r is a required property" % u'max_concurrent_builds', "validation error (clusters.foo[2]): " "Additional properties are not allowed ('extra' was unexpected)", ]) ]) def test_bad_cluster_config(self, tmpdir, caplog, reactor_config_map, config, errors): if reactor_config_map: os.environ['REACTOR_CONFIG'] = dedent(config) else: filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w') as fp: fp.write(dedent(config)) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) with caplog.atLevel(logging.ERROR), pytest.raises(ValidationError): plugin.run() os.environ.pop('REACTOR_CONFIG', None) captured_errs = [x.message for x in caplog.records()] for error in errors: try: # Match regexp assert any(filter(error.match, captured_errs)) except AttributeError: # String comparison assert error in captured_errs def test_bad_version(self, tmpdir): filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w') as fp: fp.write("version: 2") tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) with pytest.raises(ValueError): plugin.run() @pytest.mark.parametrize(('config', 'clusters'), [ # noqa:F811 # Empty config ("", []), # Built-in default config (yaml.dump(ReactorConfig.DEFAULT_CONFIG), []), # Unknown key ("""\ version: 1 special: foo """, []), ("""\ version: 1 clusters: ignored: - name: foo max_concurrent_builds: 2 platform: - name: one max_concurrent_builds: 4 - name: two max_concurrent_builds: 8 enabled: true - name: three max_concurrent_builds: 16 enabled: false """, [ ('one', 4), ('two', 8), ]), ]) def test_good_cluster_config(self, tmpdir, reactor_config_map, config, clusters): if reactor_config_map and config: os.environ['REACTOR_CONFIG'] = dedent(config) else: filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w') as fp: fp.write(dedent(config)) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) assert plugin.run() is None os.environ.pop('REACTOR_CONFIG', None) conf = get_config(workflow) enabled = conf.get_enabled_clusters_for_platform('platform') assert set([(x.name, x.max_concurrent_builds) for x in enabled]) == set(clusters) @pytest.mark.parametrize(('extra_config', 'fallback', 'error'), [ # noqa:F811 ('clusters_client_config_dir: /the/path', None, None), ('clusters_client_config_dir: /the/path', '/unused/path', None), (None, '/the/path', None), (None, NO_FALLBACK, KeyError), ]) def test_cluster_client_config_path(self, tmpdir, reactor_config_map, extra_config, fallback, error): config = 'version: 1' if extra_config: config += '\n' + extra_config if reactor_config_map and config: os.environ['REACTOR_CONFIG'] = config else: filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w') as fp: fp.write(config) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) assert plugin.run() is None os.environ.pop('REACTOR_CONFIG', None) if error: with pytest.raises(error): get_clusters_client_config_path(workflow, fallback) else: path = get_clusters_client_config_path(workflow, fallback) assert path == '/the/path/osbs.conf' @pytest.mark.parametrize('default', ( 'release', 'beta', 'unsigned', )) def test_odcs_config(self, tmpdir, default): filename = str(tmpdir.join('config.yaml')) with open(filename, 'w') as fp: fp.write(dedent("""\ version: 1 odcs: signing_intents: - name: release keys: [R123, R234] - name: beta keys: [R123, B456, B457] - name: unsigned keys: [] default_signing_intent: {default} api_url: http://odcs.example.com auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """.format(default=default))) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) assert plugin.run() is None odcs_config = get_config(workflow).get_odcs_config() assert odcs_config.default_signing_intent == default unsigned_intent = {'name': 'unsigned', 'keys': [], 'restrictiveness': 0} beta_intent = {'name': 'beta', 'keys': ['R123', 'B456', 'B457'], 'restrictiveness': 1} release_intent = {'name': 'release', 'keys': ['R123', 'R234'], 'restrictiveness': 2} assert odcs_config.signing_intents == [ unsigned_intent, beta_intent, release_intent ] assert odcs_config.get_signing_intent_by_name('release') == release_intent assert odcs_config.get_signing_intent_by_name('beta') == beta_intent assert odcs_config.get_signing_intent_by_name('unsigned') == unsigned_intent with pytest.raises(ValueError): odcs_config.get_signing_intent_by_name('missing') assert odcs_config.get_signing_intent_by_keys(['R123', 'R234'])['name'] == 'release' assert odcs_config.get_signing_intent_by_keys('R123 R234')['name'] == 'release' assert odcs_config.get_signing_intent_by_keys(['R123'])['name'] == 'release' assert odcs_config.get_signing_intent_by_keys('R123')['name'] == 'release' assert odcs_config.get_signing_intent_by_keys(['R123', 'B456'])['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys(['B456', 'R123'])['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys('B456 R123')['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys('R123 B456 ')['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys(['B456'])['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys('B456')['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys([])['name'] == 'unsigned' assert odcs_config.get_signing_intent_by_keys('')['name'] == 'unsigned' with pytest.raises(ValueError): assert odcs_config.get_signing_intent_by_keys(['missing']) with pytest.raises(ValueError): assert odcs_config.get_signing_intent_by_keys(['R123', 'R234', 'B457']) def test_odcs_config_invalid_default_signing_intent(self, tmpdir): filename = str(tmpdir.join('config.yaml')) with open(filename, 'w') as fp: fp.write(dedent("""\ version: 1 odcs: signing_intents: - name: release keys: [R123] - name: beta keys: [R123, B456] - name: unsigned keys: [] default_signing_intent: spam api_url: http://odcs.example.com auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """)) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) assert plugin.run() is None with pytest.raises(ValueError) as exc_info: get_config(workflow).get_odcs_config() message = str(exc_info.value) assert message == dedent("""\ unknown signing intent name "spam", valid names: unsigned, beta, release """.rstrip()) @pytest.mark.parametrize('fallback', (True, False, None)) @pytest.mark.parametrize('method', [ 'koji', 'pulp', 'odcs', 'smtp', 'arrangement_version', 'artifacts_allowed_domains', 'image_labels', 'image_label_info_url_format', 'image_equal_labels', 'openshift', 'group_manifests', 'platform_descriptors', 'prefer_schema1_digest', 'content_versions', 'registries', 'yum_proxy', 'source_registry', 'sources_command', 'required_secrets', 'worker_token_secrets', 'clusters', ]) def test_get_methods(self, fallback, method): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if fallback is False: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] = \ ReactorConfig(yaml.safe_load(REACTOR_CONFIG_MAP)) else: if fallback: fall_source = ReactorConfig(yaml.safe_load(REACTOR_CONFIG_MAP)) else: fall_source = ReactorConfig(yaml.safe_load("version: 1")) method_name = 'get_' + method real_method = getattr(atomic_reactor.plugins.pre_reactor_config, method_name) if fallback is True: output = real_method(workflow, fall_source.conf[method]) else: if fallback is False: output = real_method(workflow) else: with pytest.raises(KeyError): real_method(workflow) return expected = yaml.safe_load(REACTOR_CONFIG_MAP)[method] if method == 'registries': registries_cm = {} for registry in expected: reguri = RegistryURI(registry.get('url')) regdict = {} regdict['version'] = reguri.version if registry.get('auth'): regdict['secret'] = registry['auth']['cfg_path'] regdict['insecure'] = registry.get('insecure', False) regdict['expected_media_types'] = registry.get('expected_media_types', []) registries_cm[reguri.docker_uri] = regdict if fallback: output = real_method(workflow, registries_cm) assert output == registries_cm return if method == 'source_registry': expect = { 'uri': RegistryURI(expected['url']), 'insecure': expected.get('insecure', False) } if fallback: output = real_method(workflow, expect) assert output['insecure'] == expect['insecure'] assert output['uri'].uri == expect['uri'].uri return assert output == expected @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'expect'), [ ("""\ version: 1 platform_descriptors: - platform: x86_64 architecture: amd64 """, {'x86_64': 'amd64', 'ppc64le': 'ppc64le'}), ]) def test_get_platform_to_goarch_mapping(self, fallback, config, expect): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} config_json = read_yaml(config, 'schemas/config.json') workspace = workflow.plugin_workspace[ReactorConfigPlugin.key] workspace[WORKSPACE_CONF_KEY] = ReactorConfig(config_json) kwargs = {} if fallback: kwargs['descriptors_fallback'] = {'x86_64': 'amd64'} platform_to_goarch = get_platform_to_goarch_mapping(workflow, **kwargs) goarch_to_platform = get_goarch_to_platform_mapping(workflow, **kwargs) for plat, goarch in expect.items(): assert platform_to_goarch[plat] == goarch assert goarch_to_platform[goarch] == plat @pytest.mark.parametrize(('config', 'expect'), [ ("""\ version: 1 default_image_build_method: imagebuilder """, "imagebuilder"), ("""\ version: 1 """, CONTAINER_DEFAULT_BUILD_METHOD), ]) def test_get_default_image_build_method(self, config, expect): config_json = read_yaml(config, 'schemas/config.json') _, workflow = self.prepare() workspace = workflow.plugin_workspace.setdefault(ReactorConfigPlugin.key, {}) workspace[WORKSPACE_CONF_KEY] = ReactorConfig(config_json) method = get_default_image_build_method(workflow) assert method == expect @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'expect'), [ ("""\ version: 1 build_image_override: ppc64le: registry.example.com/buildroot-ppc64le:latest arm: registry.example.com/buildroot-arm:latest """, {'ppc64le': 'registry.example.com/buildroot-ppc64le:latest', 'arm': 'registry.example.com/buildroot-arm:latest'}), ]) def test_get_build_image_override(self, fallback, config, expect): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} config_json = read_yaml(config, 'schemas/config.json') workspace = workflow.plugin_workspace[ReactorConfigPlugin.key] workspace[WORKSPACE_CONF_KEY] = ReactorConfig(config_json) kwargs = {} if fallback: kwargs['fallback'] = expect build_image_override = get_build_image_override(workflow, **kwargs) assert build_image_override == expect @pytest.mark.parametrize(('config', 'fallback', 'expect'), [ ("""\ version: 1 flatpak: base_image: fedora:latest """, "x", "fedora:latest"), ("""\ version: 1 flatpak: {} """, "x", "x"), ("""\ version: 1 """, "x", "x"), ("""\ version: 1 """, None, None), ("""\ version: 1 flatpak: {} """, None, None), ]) def test_get_flatpak_base_image(self, config, fallback, expect): config_json = read_yaml(config, 'schemas/config.json') _, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = { WORKSPACE_CONF_KEY: ReactorConfig(config_json) } kwargs = {} if fallback: kwargs['fallback'] = fallback if expect: base_image = get_flatpak_base_image(workflow, **kwargs) assert base_image == expect else: with pytest.raises(KeyError): get_flatpak_base_image(workflow, **kwargs) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_principal: krb_principal krb_keytab_path: /tmp/krb_keytab """, False), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser ssl_certs_dir: /var/certs """, False), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser """, False), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_principal: krb_principal krb_keytab_path: /tmp/krb_keytab ssl_certs_dir: /var/certs """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_keytab_path: /tmp/krb_keytab """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_principal: krb_principal """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_principal: krb_principal ssl_certs_dir: /var/certs """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_keytab_path: /tmp/krb_keytab ssl_certs_dir: /var/certs """, True), ]) def test_get_koji_session(self, fallback, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') auth_info = { "proxyuser": config_json['koji']['auth'].get('proxyuser'), "ssl_certs_dir": config_json['koji']['auth'].get('ssl_certs_dir'), "krb_principal": config_json['koji']['auth'].get('krb_principal'), "krb_keytab": config_json['koji']['auth'].get('krb_keytab_path') } fallback_map = {} if fallback: fallback_map = {'auth': deepcopy(auth_info), 'hub_url': config_json['koji']['hub_url']} fallback_map['auth']['krb_keytab_path'] = fallback_map['auth'].pop('krb_keytab') else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] = \ ReactorConfig(config_json) (flexmock(atomic_reactor.koji_util) .should_receive('create_koji_session') .with_args(config_json['koji']['hub_url'], auth_info) .once() .and_return(True)) get_koji_session(workflow, fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize('root_url', ( 'https://koji.example.com/root', 'https://koji.example.com/root/', None )) def test_get_koji_path_info(self, fallback, root_url): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} config = { 'version': 1, 'koji': { 'hub_url': 'https://koji.example.com/hub', 'auth': { 'ssl_certs_dir': '/var/certs' } } } expected_root_url = 'https://koji.example.com/root' if root_url: config['koji']['root_url'] = root_url config_yaml = yaml.safe_dump(config) expect_error = not root_url if expect_error: with pytest.raises(Exception): read_yaml(config_yaml, 'schemas/config.json') return parsed_config = read_yaml(config_yaml, 'schemas/config.json') fallback_map = {} if fallback: fallback_map = deepcopy(config['koji']) else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] = \ ReactorConfig(parsed_config) (flexmock(koji.PathInfo) .should_receive('__init__') .with_args(topdir=expected_root_url) .once()) get_koji_path_info(workflow, fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 pulp: name: my-pulp auth: password: testpasswd username: testuser """, False), ("""\ version: 1 pulp: name: my-pulp auth: ssl_certs_dir: /var/certs """, False), ("""\ version: 1 pulp: name: my-pulp auth: ssl_certs_dir: /var/certs password: testpasswd username: testuser """, True), ("""\ version: 1 pulp: name: my-pulp auth: ssl_certs_dir: /var/certs password: testpasswd """, True), ("""\ version: 1 pulp: name: my-pulp auth: ssl_certs_dir: /var/certs username: testuser """, True), ("""\ version: 1 pulp: name: my-pulp auth: username: testuser """, True), ("""\ version: 1 pulp: name: my-pulp auth: password: testpasswd """, True), ]) def test_get_pulp_session(self, fallback, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') auth_info = { "pulp_secret_path": config_json['pulp']['auth'].get('ssl_certs_dir'), "username": config_json['pulp']['auth'].get('username'), "password": config_json['pulp']['auth'].get('password'), "dockpulp_loglevel": None } fallback_map = {} if fallback: fallback_map = {'auth': deepcopy(auth_info), 'name': config_json['pulp']['name']} fallback_map['auth']['ssl_certs_dir'] = fallback_map['auth'].pop('pulp_secret_path') else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) (flexmock(atomic_reactor.pulp_util.PulpHandler) .should_receive('__init__') .with_args(workflow, config_json['pulp']['name'], 'logger', **auth_info) .once() .and_return(None)) get_pulp_session(workflow, 'logger', fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret signing_intents: - name: release keys: [R123] default_signing_intent: default """, False), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: ssl_certs_dir: nonexistent signing_intents: - name: release keys: [R123] default_signing_intent: default """, False), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: openidc_dir: /var/run/open_idc signing_intents: - name: release keys: [R123] default_signing_intent: default """, False), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: openidc_dir: /var/run/open_idc ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret signing_intents: - name: release keys: [R123] default_signing_intent: default """, True), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: openidc_dir: /var/run/open_idc signing_intents: - name: release keys: [R123] """, True), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: openidc_dir: /var/run/open_idc default_signing_intent: default """, True), ("""\ version: 1 odcs: auth: openidc_dir: /var/run/open_idc signing_intents: - name: release keys: [R123] default_signing_intent: default """, True), ]) def test_get_odcs_session(self, tmpdir, fallback, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') auth_info = {'insecure': config_json['odcs'].get('insecure', False)} if 'openidc_dir' in config_json['odcs']['auth']: config_json['odcs']['auth']['openidc_dir'] = str(tmpdir) filename = str(tmpdir.join('token')) with open(filename, 'w') as fp: fp.write("my_token") auth_info['token'] = "my_token" ssl_dir_raise = False if 'ssl_certs_dir' in config_json['odcs']['auth']: if config_json['odcs']['auth']['ssl_certs_dir'] != "nonexistent": config_json['odcs']['auth']['ssl_certs_dir'] = str(tmpdir) filename = str(tmpdir.join('cert')) with open(filename, 'w') as fp: fp.write("my_cert") auth_info['cert'] = filename else: ssl_dir_raise = True fallback_map = {} if fallback: fallback_map = {'auth': deepcopy(auth_info), 'api_url': config_json['odcs']['api_url']} fallback_map['auth']['ssl_certs_dir'] = config_json['odcs']['auth'].get('ssl_certs_dir') fallback_map['auth']['openidc_dir'] = config_json['odcs']['auth'].get('openidc_dir') else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) if not ssl_dir_raise: (flexmock(atomic_reactor.odcs_util.ODCSClient) .should_receive('__init__') .with_args(config_json['odcs']['api_url'], **auth_info) .once() .and_return(None)) get_odcs_session(workflow, fallback_map) else: with pytest.raises(KeyError): get_odcs_session(workflow, fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 smtp: host: smtp.example.com from_address: osbs@example.com """, False), ("""\ version: 1 smtp: from_address: osbs@example.com """, True), ("""\ version: 1 smtp: host: smtp.example.com """, True), ("""\ version: 1 smtp: """, True), ]) def test_get_smtp_session(self, fallback, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') fallback_map = {} if fallback: fallback_map['host'] = config_json['smtp']['host'] else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) (flexmock(smtplib.SMTP) .should_receive('__init__') .with_args(config_json['smtp']['host']) .once() .and_return(None)) get_smtp_session(workflow, fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize('build_json_dir', [ None, "/tmp/build_json_dir", ]) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 openshift: url: https://openshift.example.com auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """, False), ("""\ version: 1 openshift: url: https://openshift.example.com """, False), ("""\ version: 1 openshift: url: https://openshift.example.com auth: krb_principal: principal krb_keytab_path: /var/keytab """, False), ("""\ version: 1 openshift: url: https://openshift.example.com auth: krb_principal: principal krb_keytab_path: /var/keytab krb_cache_path: /var/krb/cache """, False), ("""\ version: 1 openshift: url: https://openshift.example.com auth: enable: True """, False), ("""\ version: 1 openshift: url: https://openshift.example.com auth: krb_keytab_path: /var/keytab """, True), ("""\ version: 1 openshift: url: https://openshift.example.com auth: krb_principal: principal """, True), ("""\ version: 1 openshift: auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """, True), ("""\ version: 1 openshift: auth: krb_principal: principal krb_keytab_path: /var/keytab """, True), ("""\ version: 1 openshift: url: https://openshift.example.com auth: """, True), ("""\ version: 1 openshift: auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """, True), ]) def test_get_openshift_session(self, fallback, build_json_dir, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if build_json_dir: config += " build_json_dir: " + build_json_dir if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') auth_info = { 'openshift_url': config_json['openshift']['url'], 'verify_ssl': not config_json['openshift'].get('insecure', False), 'use_auth': False, 'conf_file': None, 'namespace': 'namespace', 'build_json_dir': build_json_dir } if config_json['openshift'].get('auth'): if config_json['openshift']['auth'].get('krb_keytab_path'): auth_info['kerberos_keytab'] =\ config_json['openshift']['auth'].get('krb_keytab_path') if config_json['openshift']['auth'].get('krb_principal'): auth_info['kerberos_principal'] =\ config_json['openshift']['auth'].get('krb_principal') if config_json['openshift']['auth'].get('krb_cache_path'): auth_info['kerberos_ccache'] =\ config_json['openshift']['auth'].get('krb_cache_path') if config_json['openshift']['auth'].get('ssl_certs_dir'): auth_info['client_cert'] =\ os.path.join(config_json['openshift']['auth'].get('ssl_certs_dir'), 'cert') auth_info['client_key'] =\ os.path.join(config_json['openshift']['auth'].get('ssl_certs_dir'), 'key') auth_info['use_auth'] = config_json['openshift']['auth'].get('enable', False) fallback_map = {} if fallback: fallback_map = {'url': config_json['openshift']['url'], 'insecure': config_json['openshift'].get('insecure', False), 'build_json_dir': build_json_dir} if config_json['openshift'].get('auth'): fallback_map['auth'] = {} fallback_map['auth']['krb_keytab_path'] =\ config_json['openshift']['auth'].get('krb_keytab_path') fallback_map['auth']['krb_principal'] =\ config_json['openshift']['auth'].get('krb_principal') fallback_map['auth']['enable'] =\ config_json['openshift']['auth'].get('enable', False) fallback_map['auth']['krb_cache_path'] =\ config_json['openshift']['auth'].get('krb_cache_path') fallback_map['auth']['ssl_certs_dir'] =\ config_json['openshift']['auth'].get('ssl_certs_dir') else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) (flexmock(osbs.conf.Configuration) .should_call('__init__') .with_args(**auth_info) .once()) (flexmock(osbs.api.OSBS) .should_call('__init__') .once()) flexmock(os, environ={'BUILD': '{"metadata": {"namespace": "namespace"}}'}) get_openshift_session(workflow, fallback_map)
35.092155
100
0.532924
from __future__ import unicode_literals from jsonschema import ValidationError import io import logging import os import pkg_resources import pytest from textwrap import dedent import re import yaml import smtplib from copy import deepcopy import atomic_reactor import koji from atomic_reactor.core import DockerTasker from atomic_reactor.inner import DockerBuildWorkflow from atomic_reactor.util import read_yaml import atomic_reactor.koji_util import atomic_reactor.pulp_util import atomic_reactor.odcs_util import osbs.conf import osbs.api from osbs.utils import RegistryURI from atomic_reactor.plugins.pre_reactor_config import (ReactorConfig, ReactorConfigPlugin, get_config, WORKSPACE_CONF_KEY, get_koji_session, get_koji_path_info, get_pulp_session, get_odcs_session, get_smtp_session, get_openshift_session, get_clusters_client_config_path, get_docker_registry, get_platform_to_goarch_mapping, get_goarch_to_platform_mapping, get_default_image_build_method, get_flatpak_base_image, CONTAINER_DEFAULT_BUILD_METHOD, get_build_image_override, NO_FALLBACK) from tests.constants import TEST_IMAGE, REACTOR_CONFIG_MAP from tests.docker_mock import mock_docker from tests.fixtures import reactor_config_map from flexmock import flexmock class TestReactorConfigPlugin(object): def prepare(self): mock_docker() tasker = DockerTasker() workflow = DockerBuildWorkflow({'provider': 'git', 'uri': 'asd'}, TEST_IMAGE) return tasker, workflow @pytest.mark.parametrize(('fallback'), [ False, True ]) @pytest.mark.parametrize(('config', 'valid'), [ ("""\ version: 1 registries: - url: https://container-registry.example.com/v2 auth: cfg_path: /var/run/secrets/atomic-reactor/v2-registry-dockercfg """, True), ("""\ version: 1 registries: - url: https://old-container-registry.example.com/v1 auth: cfg_path: /var/run/secrets/atomic-reactor/v1-registry-dockercfg - url: https://container-registry.example.com/v2 auth: cfg_path: /var/run/secrets/atomic-reactor/v2-registry-dockercfg """, True), ("""\ version: 1 registries: - url: https://old-container-registry.example.com/v1 auth: cfg_path: /var/run/secrets/atomic-reactor/v1-registry-dockercfg """, False), ]) def test_get_docker_registry(self, config, fallback, valid): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} config_json = read_yaml(config, 'schemas/config.json') docker_reg = { 'version': 'v2', 'insecure': False, 'secret': '/var/run/secrets/atomic-reactor/v2-registry-dockercfg', 'url': 'https://container-registry.example.com/v2', } if fallback: if valid: docker_fallback = docker_reg expected = docker_reg else: docker_fallback = NO_FALLBACK else: docker_fallback = {} expected = { 'url': 'https://container-registry.example.com', 'insecure': False, 'secret': '/var/run/secrets/atomic-reactor/v2-registry-dockercfg' } workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) if valid: docker_registry = get_docker_registry(workflow, docker_fallback) assert docker_registry == expected else: if fallback: with pytest.raises(KeyError): get_docker_registry(workflow, docker_fallback) else: with pytest.raises(RuntimeError): get_docker_registry(workflow, docker_fallback) def test_no_config(self): tasker, workflow = self.prepare() conf = get_config(workflow) assert isinstance(conf, ReactorConfig) same_conf = get_config(workflow) assert conf is same_conf @pytest.mark.parametrize('basename', ['reactor-config.yaml', None]) def test_filename(self, tmpdir, basename): filename = os.path.join(str(tmpdir), basename or 'config.yaml') with open(filename, 'w'): pass tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir), basename=filename) assert plugin.run() is None def test_filename_not_found(self): tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path='/not-found') with pytest.raises(Exception): plugin.run() def test_no_schema_resource(self, tmpdir, caplog): class FakeProvider(object): def get_resource_stream(self, pkg, rsc): raise IOError (flexmock(pkg_resources) .should_receive('get_provider') .and_return(FakeProvider())) filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w'): pass tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) with caplog.atLevel(logging.ERROR), pytest.raises(Exception): plugin.run() captured_errs = [x.message for x in caplog.records()] assert "unable to extract JSON schema, cannot validate" in captured_errs @pytest.mark.parametrize('schema', [ '{', '{"properties": {"any": null}}', ]) def test_invalid_schema_resource(self, tmpdir, caplog, schema): class FakeProvider(object): def get_resource_stream(self, pkg, rsc): return io.BufferedReader(io.BytesIO(schema)) (flexmock(pkg_resources) .should_receive('get_provider') .and_return(FakeProvider())) filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w'): pass tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) with caplog.atLevel(logging.ERROR), pytest.raises(Exception): plugin.run() captured_errs = [x.message for x in caplog.records()] assert any("cannot validate" in x for x in captured_errs) @pytest.mark.parametrize(('config', 'errors'), [ ("""\ clusters: foo: - name: bar max_concurrent_builds: 1 """, [ "validation error (at top level): " "%r is a required property" % u'version', ]), ("""\ version: 1 clusters: foo: bar: 1 plat/form: - name: foo max_concurrent_builds: 1 """, [ "validation error (clusters.foo): None is not of type %r" % u'array', "validation error (clusters.bar): 1 is not of type %r" % u'array', re.compile(r"validation error \(clusters\): .*'plat/form'"), ]), ("""\ version: 1 clusters: foo: - name: 1 max_concurrent_builds: 1 - name: blah max_concurrent_builds: one - name: "2" # quoting prevents error max_concurrent_builds: 2 - name: negative max_concurrent_builds: -1 """, [ "validation error (clusters.foo[0].name): " "1 is not of type %r" % u'string', "validation error (clusters.foo[1].max_concurrent_builds): " "'one' is not of type %r" % u'integer', re.compile(r"validation error \(clusters\.foo\[3\]\.max_concurrent_builds\): -1(\.0)?" r" is less than the minimum of 0"), ]), ("""\ version: 1 clusters: foo: - name: blah max_concurrent_builds: 1 enabled: never """, [ "validation error (clusters.foo[0].enabled): " "'never' is not of type %r" % u'boolean', ]), ("""\ version: 1 clusters: foo: # missing name - nam: bar max_concurrent_builds: 1 # missing max_concurrent_builds - name: baz max_concurrrent_builds: 2 - name: bar max_concurrent_builds: 4 extra: false """, [ "validation error (clusters.foo[0]): " "%r is a required property" % u'name', "validation error (clusters.foo[1]): " "%r is a required property" % u'max_concurrent_builds', "validation error (clusters.foo[2]): " "Additional properties are not allowed ('extra' was unexpected)", ]) ]) def test_bad_cluster_config(self, tmpdir, caplog, reactor_config_map, config, errors): if reactor_config_map: os.environ['REACTOR_CONFIG'] = dedent(config) else: filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w') as fp: fp.write(dedent(config)) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) with caplog.atLevel(logging.ERROR), pytest.raises(ValidationError): plugin.run() os.environ.pop('REACTOR_CONFIG', None) captured_errs = [x.message for x in caplog.records()] for error in errors: try: assert any(filter(error.match, captured_errs)) except AttributeError: assert error in captured_errs def test_bad_version(self, tmpdir): filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w') as fp: fp.write("version: 2") tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) with pytest.raises(ValueError): plugin.run() @pytest.mark.parametrize(('config', 'clusters'), [ ("", []), (yaml.dump(ReactorConfig.DEFAULT_CONFIG), []), ("""\ version: 1 special: foo """, []), ("""\ version: 1 clusters: ignored: - name: foo max_concurrent_builds: 2 platform: - name: one max_concurrent_builds: 4 - name: two max_concurrent_builds: 8 enabled: true - name: three max_concurrent_builds: 16 enabled: false """, [ ('one', 4), ('two', 8), ]), ]) def test_good_cluster_config(self, tmpdir, reactor_config_map, config, clusters): if reactor_config_map and config: os.environ['REACTOR_CONFIG'] = dedent(config) else: filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w') as fp: fp.write(dedent(config)) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) assert plugin.run() is None os.environ.pop('REACTOR_CONFIG', None) conf = get_config(workflow) enabled = conf.get_enabled_clusters_for_platform('platform') assert set([(x.name, x.max_concurrent_builds) for x in enabled]) == set(clusters) @pytest.mark.parametrize(('extra_config', 'fallback', 'error'), [ ('clusters_client_config_dir: /the/path', None, None), ('clusters_client_config_dir: /the/path', '/unused/path', None), (None, '/the/path', None), (None, NO_FALLBACK, KeyError), ]) def test_cluster_client_config_path(self, tmpdir, reactor_config_map, extra_config, fallback, error): config = 'version: 1' if extra_config: config += '\n' + extra_config if reactor_config_map and config: os.environ['REACTOR_CONFIG'] = config else: filename = os.path.join(str(tmpdir), 'config.yaml') with open(filename, 'w') as fp: fp.write(config) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) assert plugin.run() is None os.environ.pop('REACTOR_CONFIG', None) if error: with pytest.raises(error): get_clusters_client_config_path(workflow, fallback) else: path = get_clusters_client_config_path(workflow, fallback) assert path == '/the/path/osbs.conf' @pytest.mark.parametrize('default', ( 'release', 'beta', 'unsigned', )) def test_odcs_config(self, tmpdir, default): filename = str(tmpdir.join('config.yaml')) with open(filename, 'w') as fp: fp.write(dedent("""\ version: 1 odcs: signing_intents: - name: release keys: [R123, R234] - name: beta keys: [R123, B456, B457] - name: unsigned keys: [] default_signing_intent: {default} api_url: http://odcs.example.com auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """.format(default=default))) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) assert plugin.run() is None odcs_config = get_config(workflow).get_odcs_config() assert odcs_config.default_signing_intent == default unsigned_intent = {'name': 'unsigned', 'keys': [], 'restrictiveness': 0} beta_intent = {'name': 'beta', 'keys': ['R123', 'B456', 'B457'], 'restrictiveness': 1} release_intent = {'name': 'release', 'keys': ['R123', 'R234'], 'restrictiveness': 2} assert odcs_config.signing_intents == [ unsigned_intent, beta_intent, release_intent ] assert odcs_config.get_signing_intent_by_name('release') == release_intent assert odcs_config.get_signing_intent_by_name('beta') == beta_intent assert odcs_config.get_signing_intent_by_name('unsigned') == unsigned_intent with pytest.raises(ValueError): odcs_config.get_signing_intent_by_name('missing') assert odcs_config.get_signing_intent_by_keys(['R123', 'R234'])['name'] == 'release' assert odcs_config.get_signing_intent_by_keys('R123 R234')['name'] == 'release' assert odcs_config.get_signing_intent_by_keys(['R123'])['name'] == 'release' assert odcs_config.get_signing_intent_by_keys('R123')['name'] == 'release' assert odcs_config.get_signing_intent_by_keys(['R123', 'B456'])['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys(['B456', 'R123'])['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys('B456 R123')['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys('R123 B456 ')['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys(['B456'])['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys('B456')['name'] == 'beta' assert odcs_config.get_signing_intent_by_keys([])['name'] == 'unsigned' assert odcs_config.get_signing_intent_by_keys('')['name'] == 'unsigned' with pytest.raises(ValueError): assert odcs_config.get_signing_intent_by_keys(['missing']) with pytest.raises(ValueError): assert odcs_config.get_signing_intent_by_keys(['R123', 'R234', 'B457']) def test_odcs_config_invalid_default_signing_intent(self, tmpdir): filename = str(tmpdir.join('config.yaml')) with open(filename, 'w') as fp: fp.write(dedent("""\ version: 1 odcs: signing_intents: - name: release keys: [R123] - name: beta keys: [R123, B456] - name: unsigned keys: [] default_signing_intent: spam api_url: http://odcs.example.com auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """)) tasker, workflow = self.prepare() plugin = ReactorConfigPlugin(tasker, workflow, config_path=str(tmpdir)) assert plugin.run() is None with pytest.raises(ValueError) as exc_info: get_config(workflow).get_odcs_config() message = str(exc_info.value) assert message == dedent("""\ unknown signing intent name "spam", valid names: unsigned, beta, release """.rstrip()) @pytest.mark.parametrize('fallback', (True, False, None)) @pytest.mark.parametrize('method', [ 'koji', 'pulp', 'odcs', 'smtp', 'arrangement_version', 'artifacts_allowed_domains', 'image_labels', 'image_label_info_url_format', 'image_equal_labels', 'openshift', 'group_manifests', 'platform_descriptors', 'prefer_schema1_digest', 'content_versions', 'registries', 'yum_proxy', 'source_registry', 'sources_command', 'required_secrets', 'worker_token_secrets', 'clusters', ]) def test_get_methods(self, fallback, method): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if fallback is False: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] = \ ReactorConfig(yaml.safe_load(REACTOR_CONFIG_MAP)) else: if fallback: fall_source = ReactorConfig(yaml.safe_load(REACTOR_CONFIG_MAP)) else: fall_source = ReactorConfig(yaml.safe_load("version: 1")) method_name = 'get_' + method real_method = getattr(atomic_reactor.plugins.pre_reactor_config, method_name) if fallback is True: output = real_method(workflow, fall_source.conf[method]) else: if fallback is False: output = real_method(workflow) else: with pytest.raises(KeyError): real_method(workflow) return expected = yaml.safe_load(REACTOR_CONFIG_MAP)[method] if method == 'registries': registries_cm = {} for registry in expected: reguri = RegistryURI(registry.get('url')) regdict = {} regdict['version'] = reguri.version if registry.get('auth'): regdict['secret'] = registry['auth']['cfg_path'] regdict['insecure'] = registry.get('insecure', False) regdict['expected_media_types'] = registry.get('expected_media_types', []) registries_cm[reguri.docker_uri] = regdict if fallback: output = real_method(workflow, registries_cm) assert output == registries_cm return if method == 'source_registry': expect = { 'uri': RegistryURI(expected['url']), 'insecure': expected.get('insecure', False) } if fallback: output = real_method(workflow, expect) assert output['insecure'] == expect['insecure'] assert output['uri'].uri == expect['uri'].uri return assert output == expected @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'expect'), [ ("""\ version: 1 platform_descriptors: - platform: x86_64 architecture: amd64 """, {'x86_64': 'amd64', 'ppc64le': 'ppc64le'}), ]) def test_get_platform_to_goarch_mapping(self, fallback, config, expect): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} config_json = read_yaml(config, 'schemas/config.json') workspace = workflow.plugin_workspace[ReactorConfigPlugin.key] workspace[WORKSPACE_CONF_KEY] = ReactorConfig(config_json) kwargs = {} if fallback: kwargs['descriptors_fallback'] = {'x86_64': 'amd64'} platform_to_goarch = get_platform_to_goarch_mapping(workflow, **kwargs) goarch_to_platform = get_goarch_to_platform_mapping(workflow, **kwargs) for plat, goarch in expect.items(): assert platform_to_goarch[plat] == goarch assert goarch_to_platform[goarch] == plat @pytest.mark.parametrize(('config', 'expect'), [ ("""\ version: 1 default_image_build_method: imagebuilder """, "imagebuilder"), ("""\ version: 1 """, CONTAINER_DEFAULT_BUILD_METHOD), ]) def test_get_default_image_build_method(self, config, expect): config_json = read_yaml(config, 'schemas/config.json') _, workflow = self.prepare() workspace = workflow.plugin_workspace.setdefault(ReactorConfigPlugin.key, {}) workspace[WORKSPACE_CONF_KEY] = ReactorConfig(config_json) method = get_default_image_build_method(workflow) assert method == expect @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'expect'), [ ("""\ version: 1 build_image_override: ppc64le: registry.example.com/buildroot-ppc64le:latest arm: registry.example.com/buildroot-arm:latest """, {'ppc64le': 'registry.example.com/buildroot-ppc64le:latest', 'arm': 'registry.example.com/buildroot-arm:latest'}), ]) def test_get_build_image_override(self, fallback, config, expect): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} config_json = read_yaml(config, 'schemas/config.json') workspace = workflow.plugin_workspace[ReactorConfigPlugin.key] workspace[WORKSPACE_CONF_KEY] = ReactorConfig(config_json) kwargs = {} if fallback: kwargs['fallback'] = expect build_image_override = get_build_image_override(workflow, **kwargs) assert build_image_override == expect @pytest.mark.parametrize(('config', 'fallback', 'expect'), [ ("""\ version: 1 flatpak: base_image: fedora:latest """, "x", "fedora:latest"), ("""\ version: 1 flatpak: {} """, "x", "x"), ("""\ version: 1 """, "x", "x"), ("""\ version: 1 """, None, None), ("""\ version: 1 flatpak: {} """, None, None), ]) def test_get_flatpak_base_image(self, config, fallback, expect): config_json = read_yaml(config, 'schemas/config.json') _, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = { WORKSPACE_CONF_KEY: ReactorConfig(config_json) } kwargs = {} if fallback: kwargs['fallback'] = fallback if expect: base_image = get_flatpak_base_image(workflow, **kwargs) assert base_image == expect else: with pytest.raises(KeyError): get_flatpak_base_image(workflow, **kwargs) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_principal: krb_principal krb_keytab_path: /tmp/krb_keytab """, False), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser ssl_certs_dir: /var/certs """, False), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser """, False), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_principal: krb_principal krb_keytab_path: /tmp/krb_keytab ssl_certs_dir: /var/certs """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_keytab_path: /tmp/krb_keytab """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_principal: krb_principal """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_principal: krb_principal ssl_certs_dir: /var/certs """, True), ("""\ version: 1 koji: hub_url: https://koji.example.com/hub root_url: https://koji.example.com/root auth: proxyuser: proxyuser krb_keytab_path: /tmp/krb_keytab ssl_certs_dir: /var/certs """, True), ]) def test_get_koji_session(self, fallback, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') auth_info = { "proxyuser": config_json['koji']['auth'].get('proxyuser'), "ssl_certs_dir": config_json['koji']['auth'].get('ssl_certs_dir'), "krb_principal": config_json['koji']['auth'].get('krb_principal'), "krb_keytab": config_json['koji']['auth'].get('krb_keytab_path') } fallback_map = {} if fallback: fallback_map = {'auth': deepcopy(auth_info), 'hub_url': config_json['koji']['hub_url']} fallback_map['auth']['krb_keytab_path'] = fallback_map['auth'].pop('krb_keytab') else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] = \ ReactorConfig(config_json) (flexmock(atomic_reactor.koji_util) .should_receive('create_koji_session') .with_args(config_json['koji']['hub_url'], auth_info) .once() .and_return(True)) get_koji_session(workflow, fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize('root_url', ( 'https://koji.example.com/root', 'https://koji.example.com/root/', None )) def test_get_koji_path_info(self, fallback, root_url): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} config = { 'version': 1, 'koji': { 'hub_url': 'https://koji.example.com/hub', 'auth': { 'ssl_certs_dir': '/var/certs' } } } expected_root_url = 'https://koji.example.com/root' if root_url: config['koji']['root_url'] = root_url config_yaml = yaml.safe_dump(config) expect_error = not root_url if expect_error: with pytest.raises(Exception): read_yaml(config_yaml, 'schemas/config.json') return parsed_config = read_yaml(config_yaml, 'schemas/config.json') fallback_map = {} if fallback: fallback_map = deepcopy(config['koji']) else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] = \ ReactorConfig(parsed_config) (flexmock(koji.PathInfo) .should_receive('__init__') .with_args(topdir=expected_root_url) .once()) get_koji_path_info(workflow, fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 pulp: name: my-pulp auth: password: testpasswd username: testuser """, False), ("""\ version: 1 pulp: name: my-pulp auth: ssl_certs_dir: /var/certs """, False), ("""\ version: 1 pulp: name: my-pulp auth: ssl_certs_dir: /var/certs password: testpasswd username: testuser """, True), ("""\ version: 1 pulp: name: my-pulp auth: ssl_certs_dir: /var/certs password: testpasswd """, True), ("""\ version: 1 pulp: name: my-pulp auth: ssl_certs_dir: /var/certs username: testuser """, True), ("""\ version: 1 pulp: name: my-pulp auth: username: testuser """, True), ("""\ version: 1 pulp: name: my-pulp auth: password: testpasswd """, True), ]) def test_get_pulp_session(self, fallback, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') auth_info = { "pulp_secret_path": config_json['pulp']['auth'].get('ssl_certs_dir'), "username": config_json['pulp']['auth'].get('username'), "password": config_json['pulp']['auth'].get('password'), "dockpulp_loglevel": None } fallback_map = {} if fallback: fallback_map = {'auth': deepcopy(auth_info), 'name': config_json['pulp']['name']} fallback_map['auth']['ssl_certs_dir'] = fallback_map['auth'].pop('pulp_secret_path') else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) (flexmock(atomic_reactor.pulp_util.PulpHandler) .should_receive('__init__') .with_args(workflow, config_json['pulp']['name'], 'logger', **auth_info) .once() .and_return(None)) get_pulp_session(workflow, 'logger', fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret signing_intents: - name: release keys: [R123] default_signing_intent: default """, False), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: ssl_certs_dir: nonexistent signing_intents: - name: release keys: [R123] default_signing_intent: default """, False), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: openidc_dir: /var/run/open_idc signing_intents: - name: release keys: [R123] default_signing_intent: default """, False), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: openidc_dir: /var/run/open_idc ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret signing_intents: - name: release keys: [R123] default_signing_intent: default """, True), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: openidc_dir: /var/run/open_idc signing_intents: - name: release keys: [R123] """, True), ("""\ version: 1 odcs: api_url: https://odcs.example.com/api/1 auth: openidc_dir: /var/run/open_idc default_signing_intent: default """, True), ("""\ version: 1 odcs: auth: openidc_dir: /var/run/open_idc signing_intents: - name: release keys: [R123] default_signing_intent: default """, True), ]) def test_get_odcs_session(self, tmpdir, fallback, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') auth_info = {'insecure': config_json['odcs'].get('insecure', False)} if 'openidc_dir' in config_json['odcs']['auth']: config_json['odcs']['auth']['openidc_dir'] = str(tmpdir) filename = str(tmpdir.join('token')) with open(filename, 'w') as fp: fp.write("my_token") auth_info['token'] = "my_token" ssl_dir_raise = False if 'ssl_certs_dir' in config_json['odcs']['auth']: if config_json['odcs']['auth']['ssl_certs_dir'] != "nonexistent": config_json['odcs']['auth']['ssl_certs_dir'] = str(tmpdir) filename = str(tmpdir.join('cert')) with open(filename, 'w') as fp: fp.write("my_cert") auth_info['cert'] = filename else: ssl_dir_raise = True fallback_map = {} if fallback: fallback_map = {'auth': deepcopy(auth_info), 'api_url': config_json['odcs']['api_url']} fallback_map['auth']['ssl_certs_dir'] = config_json['odcs']['auth'].get('ssl_certs_dir') fallback_map['auth']['openidc_dir'] = config_json['odcs']['auth'].get('openidc_dir') else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) if not ssl_dir_raise: (flexmock(atomic_reactor.odcs_util.ODCSClient) .should_receive('__init__') .with_args(config_json['odcs']['api_url'], **auth_info) .once() .and_return(None)) get_odcs_session(workflow, fallback_map) else: with pytest.raises(KeyError): get_odcs_session(workflow, fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 smtp: host: smtp.example.com from_address: osbs@example.com """, False), ("""\ version: 1 smtp: from_address: osbs@example.com """, True), ("""\ version: 1 smtp: host: smtp.example.com """, True), ("""\ version: 1 smtp: """, True), ]) def test_get_smtp_session(self, fallback, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') fallback_map = {} if fallback: fallback_map['host'] = config_json['smtp']['host'] else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) (flexmock(smtplib.SMTP) .should_receive('__init__') .with_args(config_json['smtp']['host']) .once() .and_return(None)) get_smtp_session(workflow, fallback_map) @pytest.mark.parametrize('fallback', (True, False)) @pytest.mark.parametrize('build_json_dir', [ None, "/tmp/build_json_dir", ]) @pytest.mark.parametrize(('config', 'raise_error'), [ ("""\ version: 1 openshift: url: https://openshift.example.com auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """, False), ("""\ version: 1 openshift: url: https://openshift.example.com """, False), ("""\ version: 1 openshift: url: https://openshift.example.com auth: krb_principal: principal krb_keytab_path: /var/keytab """, False), ("""\ version: 1 openshift: url: https://openshift.example.com auth: krb_principal: principal krb_keytab_path: /var/keytab krb_cache_path: /var/krb/cache """, False), ("""\ version: 1 openshift: url: https://openshift.example.com auth: enable: True """, False), ("""\ version: 1 openshift: url: https://openshift.example.com auth: krb_keytab_path: /var/keytab """, True), ("""\ version: 1 openshift: url: https://openshift.example.com auth: krb_principal: principal """, True), ("""\ version: 1 openshift: auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """, True), ("""\ version: 1 openshift: auth: krb_principal: principal krb_keytab_path: /var/keytab """, True), ("""\ version: 1 openshift: url: https://openshift.example.com auth: """, True), ("""\ version: 1 openshift: auth: ssl_certs_dir: /var/run/secrets/atomic-reactor/odcssecret """, True), ]) def test_get_openshift_session(self, fallback, build_json_dir, config, raise_error): tasker, workflow = self.prepare() workflow.plugin_workspace[ReactorConfigPlugin.key] = {} if build_json_dir: config += " build_json_dir: " + build_json_dir if raise_error: with pytest.raises(Exception): read_yaml(config, 'schemas/config.json') return config_json = read_yaml(config, 'schemas/config.json') auth_info = { 'openshift_url': config_json['openshift']['url'], 'verify_ssl': not config_json['openshift'].get('insecure', False), 'use_auth': False, 'conf_file': None, 'namespace': 'namespace', 'build_json_dir': build_json_dir } if config_json['openshift'].get('auth'): if config_json['openshift']['auth'].get('krb_keytab_path'): auth_info['kerberos_keytab'] =\ config_json['openshift']['auth'].get('krb_keytab_path') if config_json['openshift']['auth'].get('krb_principal'): auth_info['kerberos_principal'] =\ config_json['openshift']['auth'].get('krb_principal') if config_json['openshift']['auth'].get('krb_cache_path'): auth_info['kerberos_ccache'] =\ config_json['openshift']['auth'].get('krb_cache_path') if config_json['openshift']['auth'].get('ssl_certs_dir'): auth_info['client_cert'] =\ os.path.join(config_json['openshift']['auth'].get('ssl_certs_dir'), 'cert') auth_info['client_key'] =\ os.path.join(config_json['openshift']['auth'].get('ssl_certs_dir'), 'key') auth_info['use_auth'] = config_json['openshift']['auth'].get('enable', False) fallback_map = {} if fallback: fallback_map = {'url': config_json['openshift']['url'], 'insecure': config_json['openshift'].get('insecure', False), 'build_json_dir': build_json_dir} if config_json['openshift'].get('auth'): fallback_map['auth'] = {} fallback_map['auth']['krb_keytab_path'] =\ config_json['openshift']['auth'].get('krb_keytab_path') fallback_map['auth']['krb_principal'] =\ config_json['openshift']['auth'].get('krb_principal') fallback_map['auth']['enable'] =\ config_json['openshift']['auth'].get('enable', False) fallback_map['auth']['krb_cache_path'] =\ config_json['openshift']['auth'].get('krb_cache_path') fallback_map['auth']['ssl_certs_dir'] =\ config_json['openshift']['auth'].get('ssl_certs_dir') else: workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\ ReactorConfig(config_json) (flexmock(osbs.conf.Configuration) .should_call('__init__') .with_args(**auth_info) .once()) (flexmock(osbs.api.OSBS) .should_call('__init__') .once()) flexmock(os, environ={'BUILD': '{"metadata": {"namespace": "namespace"}}'}) get_openshift_session(workflow, fallback_map)
true
true